Imported Upstream version 8.6.11 upstream/8.6.11
authorJinWang An <jinwang.an@samsung.com>
Tue, 10 Jan 2023 04:51:43 +0000 (13:51 +0900)
committerJinWang An <jinwang.an@samsung.com>
Tue, 10 Jan 2023 04:51:43 +0000 (13:51 +0900)
925 files changed:
.github/workflows/linux-build.yml [new file with mode: 0644]
.github/workflows/mac-build.yml [new file with mode: 0644]
.github/workflows/win-build.yml [new file with mode: 0644]
.travis.yml [new file with mode: 0644]
ChangeLog
ChangeLog.2000
ChangeLog.2001
ChangeLog.2002
ChangeLog.2004
ChangeLog.2005
README.md
changes
compat/fake-rfc2553.c
compat/gettod.c
compat/mkstemp.c
compat/opendir.c
compat/strstr.c
compat/strtol.c
compat/strtoul.c
compat/waitpid.c
compat/zlib/contrib/minizip/crypt.h
compat/zlib/contrib/minizip/tinydir.h [new file with mode: 0755]
compat/zlib/contrib/vstudio/vc10/zlibvc.sln
compat/zlib/contrib/vstudio/vc11/zlibvc.sln
compat/zlib/contrib/vstudio/vc12/zlibvc.sln
compat/zlib/contrib/vstudio/vc14/zlibvc.sln
compat/zlib/contrib/vstudio/vc9/zlibvc.sln
compat/zlib/win32/zdll.lib [changed mode: 0755->0644]
doc/CallDel.3
doc/CmdCmplt.3
doc/Concat.3
doc/CrtAlias.3 [moved from doc/CrtSlave.3 with 69% similarity]
doc/CrtChannel.3
doc/CrtFileHdlr.3
doc/CrtInterp.3
doc/CrtTimerHdlr.3
doc/CrtTrace.3
doc/DetachPids.3
doc/DictObj.3
doc/DoWhenIdle.3
doc/DumpActiveMemory.3
doc/Environment.3
doc/ExprLongObj.3
doc/FileSystem.3
doc/FindExec.3
doc/GetCwd.3
doc/GetHostName.3
doc/GetIndex.3
doc/GetOpnFl.3
doc/GetStdChan.3
doc/GetTime.3
doc/Init.3
doc/InitStubs.3
doc/Limit.3
doc/ListObj.3
doc/Load.3
doc/NRE.3
doc/Namespace.3
doc/ObjectType.3
doc/OpenTcp.3
doc/Panic.3
doc/ParseCmd.3
doc/Preserve.3
doc/PrintDbl.3
doc/RecEvalObj.3
doc/RecordEval.3
doc/SaveResult.3
doc/SetErrno.3
doc/SetRecLmt.3
doc/SetResult.3
doc/Signal.3
doc/Sleep.3
doc/SourceRCFile.3
doc/SplitList.3
doc/SplitPath.3
doc/StaticPkg.3
doc/StdChannels.3
doc/StrMatch.3
doc/StringObj.3
doc/SubstObj.3
doc/TCL_MEM_DEBUG.3
doc/TclZlib.3
doc/Tcl_Main.3
doc/ToUpper.3
doc/Utf.3
doc/binary.n
doc/break.n
doc/case.n
doc/cd.n
doc/chan.n
doc/clock.n
doc/close.n
doc/concat.n
doc/continue.n
doc/copy.n
doc/coroutine.n
doc/dict.n
doc/encoding.n
doc/eof.n
doc/eval.n
doc/exec.n
doc/exit.n
doc/expr.n
doc/fblocked.n
doc/fconfigure.n
doc/flush.n
doc/foreach.n
doc/gets.n
doc/history.n
doc/http.n
doc/if.n
doc/incr.n
doc/info.n
doc/interp.n
doc/join.n
doc/lappend.n
doc/lassign.n
doc/library.n
doc/lindex.n
doc/list.n
doc/load.n
doc/lrepeat.n
doc/lreverse.n
doc/lsearch.n
doc/lset.n
doc/mathfunc.n
doc/memory.n
doc/namespace.n
doc/next.n
doc/packagens.n
doc/pid.n
doc/pkgMkIndex.n
doc/platform.n
doc/platform_shell.n
doc/prefix.n
doc/puts.n
doc/pwd.n
doc/re_syntax.n
doc/refchan.n
doc/registry.n
doc/rename.n
doc/safe.n
doc/seek.n
doc/socket.n
doc/source.n
doc/split.n
doc/switch.n
doc/tailcall.n
doc/tclsh.1
doc/tcltest.n
doc/tell.n
doc/throw.n
doc/time.n
doc/tm.n
doc/zlib.n
generic/regc_lex.c
generic/regc_locale.c
generic/regcomp.c
generic/regcustom.h
generic/regexec.c
generic/regguts.h
generic/tcl.decls
generic/tcl.h
generic/tclAlloc.c
generic/tclAssembly.c
generic/tclBasic.c
generic/tclBinary.c
generic/tclCkalloc.c
generic/tclClock.c
generic/tclCmdAH.c
generic/tclCmdIL.c
generic/tclCmdMZ.c
generic/tclCompCmds.c
generic/tclCompCmdsGR.c
generic/tclCompCmdsSZ.c
generic/tclCompExpr.c
generic/tclCompile.c
generic/tclCompile.h
generic/tclDate.c
generic/tclDecls.h
generic/tclDictObj.c
generic/tclDisassemble.c
generic/tclEncoding.c
generic/tclEnsemble.c
generic/tclEnv.c
generic/tclEvent.c
generic/tclExecute.c
generic/tclFCmd.c
generic/tclFileName.c
generic/tclGetDate.y
generic/tclHash.c
generic/tclHistory.c
generic/tclIO.c
generic/tclIO.h
generic/tclIOCmd.c
generic/tclIOGT.c
generic/tclIORChan.c
generic/tclIORTrans.c
generic/tclIOSock.c
generic/tclIOUtil.c
generic/tclIndexObj.c
generic/tclInt.decls
generic/tclInt.h
generic/tclIntDecls.h
generic/tclIntPlatDecls.h
generic/tclInterp.c
generic/tclListObj.c
generic/tclLiteral.c
generic/tclLoad.c
generic/tclMain.c
generic/tclNamesp.c
generic/tclOO.c
generic/tclOOBasic.c
generic/tclOOCall.c
generic/tclOODefineCmds.c
generic/tclOOInfo.c
generic/tclOOInt.h
generic/tclOOMethod.c
generic/tclObj.c
generic/tclOptimize.c
generic/tclParse.c
generic/tclPathObj.c
generic/tclPipe.c
generic/tclPkg.c
generic/tclPkgConfig.c
generic/tclPlatDecls.h
generic/tclProc.c
generic/tclRegexp.c
generic/tclResult.c
generic/tclScan.c
generic/tclStrToD.c
generic/tclStringObj.c
generic/tclStringRep.h
generic/tclStringTrim.h
generic/tclStubInit.c
generic/tclTest.c
generic/tclTestObj.c
generic/tclThread.c
generic/tclThreadAlloc.c
generic/tclThreadStorage.c
generic/tclThreadTest.c
generic/tclTimer.c
generic/tclTomMath.decls
generic/tclTomMathDecls.h
generic/tclTomMathInterface.c
generic/tclTrace.c
generic/tclUniData.c
generic/tclUtf.c
generic/tclUtil.c
generic/tclVar.c
generic/tclZlib.c
library/auto.tcl
library/clock.tcl
library/dde/pkgIndex.tcl
library/encoding/tis-620.enc
library/http/http.tcl
library/http/pkgIndex.tcl
library/init.tcl
library/msgcat/msgcat.tcl
library/opt/optparse.tcl
library/opt/pkgIndex.tcl
library/package.tcl
library/platform/pkgIndex.tcl
library/platform/platform.tcl
library/reg/pkgIndex.tcl [changed mode: 0755->0644]
library/safe.tcl
library/tcltest/pkgIndex.tcl
library/tcltest/tcltest.tcl
library/tm.tcl
library/tzdata/Africa/Accra
library/tzdata/Africa/Algiers
library/tzdata/Africa/Casablanca
library/tzdata/Africa/El_Aaiun
library/tzdata/Africa/Lagos
library/tzdata/Africa/Nairobi
library/tzdata/America/Belize
library/tzdata/America/Dawson
library/tzdata/America/Godthab
library/tzdata/America/Grand_Turk
library/tzdata/America/Nassau
library/tzdata/America/Nuuk [new file with mode: 0644]
library/tzdata/America/Whitehorse
library/tzdata/Antarctica/Casey
library/tzdata/Antarctica/Macquarie
library/tzdata/Asia/Gaza
library/tzdata/Asia/Hebron
library/tzdata/Asia/Jerusalem
library/tzdata/Asia/Shanghai
library/tzdata/Atlantic/Bermuda
library/tzdata/Australia/Adelaide
library/tzdata/Australia/Brisbane
library/tzdata/Australia/Broken_Hill
library/tzdata/Australia/Currie
library/tzdata/Australia/Darwin
library/tzdata/Australia/Eucla
library/tzdata/Australia/Hobart
library/tzdata/Australia/Lindeman
library/tzdata/Australia/Melbourne
library/tzdata/Australia/Perth
library/tzdata/Australia/Sydney
library/tzdata/Europe/Budapest
library/tzdata/Europe/Monaco
library/tzdata/Europe/Paris
library/tzdata/Europe/Volgograd
library/tzdata/Indian/Mahe
library/tzdata/Pacific/Efate
library/tzdata/Pacific/Fiji
library/word.tcl
macosx/GNUmakefile
macosx/README
macosx/Tcl.xcode/project.pbxproj
macosx/Tcl.xcodeproj/project.pbxproj
macosx/configure
macosx/tclMacOSXBundle.c
macosx/tclMacOSXFCmd.c
macosx/tclMacOSXNotify.c
manifest.uuid [new file with mode: 0644]
pkgs/README
pkgs/itcl4.2.0/win/rules-ext.vc [deleted file]
pkgs/itcl4.2.1/.project [moved from pkgs/itcl4.2.0/.project with 100% similarity]
pkgs/itcl4.2.1/ChangeLog [moved from pkgs/itcl4.2.0/ChangeLog with 100% similarity]
pkgs/itcl4.2.1/Makefile.in [moved from pkgs/itcl4.2.0/Makefile.in with 94% similarity]
pkgs/itcl4.2.1/README [moved from pkgs/itcl4.2.0/README with 96% similarity]
pkgs/itcl4.2.1/TODO [moved from pkgs/itcl4.2.0/TODO with 100% similarity]
pkgs/itcl4.2.1/aclocal.m4 [moved from pkgs/sqlite3.30.1.2/aclocal.m4 with 100% similarity]
pkgs/itcl4.2.1/configure [moved from pkgs/itcl4.2.0/configure with 98% similarity]
pkgs/itcl4.2.1/configure.ac [moved from pkgs/itcl4.2.0/configure.ac with 99% similarity]
pkgs/itcl4.2.1/doc/Class.3 [moved from pkgs/itcl4.2.0/doc/Class.3 with 100% similarity]
pkgs/itcl4.2.1/doc/List.3 [moved from pkgs/itcl4.2.0/doc/List.3 with 100% similarity]
pkgs/itcl4.2.1/doc/Object.3 [moved from pkgs/itcl4.2.0/doc/Object.3 with 100% similarity]
pkgs/itcl4.2.1/doc/Preserve.3 [moved from pkgs/itcl4.2.0/doc/Preserve.3 with 97% similarity]
pkgs/itcl4.2.1/doc/RegisterC.3 [moved from pkgs/itcl4.2.0/doc/RegisterC.3 with 100% similarity]
pkgs/itcl4.2.1/doc/Stack.3 [moved from pkgs/itcl4.2.0/doc/Stack.3 with 100% similarity]
pkgs/itcl4.2.1/doc/body.n [moved from pkgs/itcl4.2.0/doc/body.n with 100% similarity]
pkgs/itcl4.2.1/doc/class.n [moved from pkgs/itcl4.2.0/doc/class.n with 99% similarity]
pkgs/itcl4.2.1/doc/code.n [moved from pkgs/itcl4.2.0/doc/code.n with 100% similarity]
pkgs/itcl4.2.1/doc/configbody.n [moved from pkgs/itcl4.2.0/doc/configbody.n with 100% similarity]
pkgs/itcl4.2.1/doc/delete.n [moved from pkgs/itcl4.2.0/doc/delete.n with 100% similarity]
pkgs/itcl4.2.1/doc/ensemble.n [moved from pkgs/itcl4.2.0/doc/ensemble.n with 100% similarity]
pkgs/itcl4.2.1/doc/find.n [moved from pkgs/itcl4.2.0/doc/find.n with 100% similarity]
pkgs/itcl4.2.1/doc/is.n [moved from pkgs/itcl4.2.0/doc/is.n with 100% similarity]
pkgs/itcl4.2.1/doc/itcl.n [moved from pkgs/itcl4.2.0/doc/itcl.n with 100% similarity]
pkgs/itcl4.2.1/doc/itclcomponent.n [moved from pkgs/itcl4.2.0/doc/itclcomponent.n with 100% similarity]
pkgs/itcl4.2.1/doc/itcldelegate.n [moved from pkgs/itcl4.2.0/doc/itcldelegate.n with 100% similarity]
pkgs/itcl4.2.1/doc/itclextendedclass.n [moved from pkgs/itcl4.2.0/doc/itclextendedclass.n with 100% similarity]
pkgs/itcl4.2.1/doc/itcloption.n [moved from pkgs/itcl4.2.0/doc/itcloption.n with 100% similarity]
pkgs/itcl4.2.1/doc/itclvars.n [moved from pkgs/itcl4.2.0/doc/itclvars.n with 100% similarity]
pkgs/itcl4.2.1/doc/itclwidget.n [moved from pkgs/itcl4.2.0/doc/itclwidget.n with 100% similarity]
pkgs/itcl4.2.1/doc/license.terms [moved from pkgs/itcl4.2.0/doc/license.terms with 100% similarity]
pkgs/itcl4.2.1/doc/local.n [moved from pkgs/itcl4.2.0/doc/local.n with 100% similarity]
pkgs/itcl4.2.1/doc/man.macros [moved from pkgs/itcl4.2.0/doc/man.macros with 100% similarity]
pkgs/itcl4.2.1/doc/scope.n [moved from pkgs/itcl4.2.0/doc/scope.n with 100% similarity]
pkgs/itcl4.2.1/generic/clientData [new file with mode: 0644]
pkgs/itcl4.2.1/generic/itcl.decls [moved from pkgs/itcl4.2.0/generic/itcl.decls with 100% similarity]
pkgs/itcl4.2.1/generic/itcl.h [moved from pkgs/itcl4.2.0/generic/itcl.h with 99% similarity]
pkgs/itcl4.2.1/generic/itcl2TclOO.c [moved from pkgs/itcl4.2.0/generic/itcl2TclOO.c with 96% similarity]
pkgs/itcl4.2.1/generic/itcl2TclOO.h [moved from pkgs/itcl4.2.0/generic/itcl2TclOO.h with 100% similarity]
pkgs/itcl4.2.1/generic/itclBase.c [moved from pkgs/itcl4.2.0/generic/itclBase.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclBuiltin.c [moved from pkgs/itcl4.2.0/generic/itclBuiltin.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclClass.c [moved from pkgs/itcl4.2.0/generic/itclClass.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclCmd.c [moved from pkgs/itcl4.2.0/generic/itclCmd.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclDecls.h [moved from pkgs/itcl4.2.0/generic/itclDecls.h with 100% similarity]
pkgs/itcl4.2.1/generic/itclEnsemble.c [moved from pkgs/itcl4.2.0/generic/itclEnsemble.c with 98% similarity]
pkgs/itcl4.2.1/generic/itclHelpers.c [moved from pkgs/itcl4.2.0/generic/itclHelpers.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclInfo.c [moved from pkgs/itcl4.2.0/generic/itclInfo.c with 98% similarity]
pkgs/itcl4.2.1/generic/itclInt.h [moved from pkgs/itcl4.2.0/generic/itclInt.h with 99% similarity]
pkgs/itcl4.2.1/generic/itclIntDecls.h [moved from pkgs/itcl4.2.0/generic/itclIntDecls.h with 100% similarity]
pkgs/itcl4.2.1/generic/itclLinkage.c [moved from pkgs/itcl4.2.0/generic/itclLinkage.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclMethod.c [moved from pkgs/itcl4.2.0/generic/itclMethod.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclMigrate2TclCore.c [moved from pkgs/itcl4.2.0/generic/itclMigrate2TclCore.c with 96% similarity]
pkgs/itcl4.2.1/generic/itclMigrate2TclCore.h [moved from pkgs/itcl4.2.0/generic/itclMigrate2TclCore.h with 100% similarity]
pkgs/itcl4.2.1/generic/itclObject.c [moved from pkgs/itcl4.2.0/generic/itclObject.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclParse.c [moved from pkgs/itcl4.2.0/generic/itclParse.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclResolve.c [moved from pkgs/itcl4.2.0/generic/itclResolve.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclStubInit.c [moved from pkgs/itcl4.2.0/generic/itclStubInit.c with 100% similarity]
pkgs/itcl4.2.1/generic/itclStubLib.c [moved from pkgs/itcl4.2.0/generic/itclStubLib.c with 100% similarity]
pkgs/itcl4.2.1/generic/itclStubs.c [moved from pkgs/itcl4.2.0/generic/itclStubs.c with 98% similarity]
pkgs/itcl4.2.1/generic/itclTclIntStubsFcn.c [moved from pkgs/itcl4.2.0/generic/itclTclIntStubsFcn.c with 99% similarity]
pkgs/itcl4.2.1/generic/itclTclIntStubsFcn.h [moved from pkgs/itcl4.2.0/generic/itclTclIntStubsFcn.h with 100% similarity]
pkgs/itcl4.2.1/generic/itclTestRegisterC.c [moved from pkgs/itcl4.2.0/generic/itclTestRegisterC.c with 100% similarity]
pkgs/itcl4.2.1/generic/itclUtil.c [moved from pkgs/itcl4.2.0/generic/itclUtil.c with 99% similarity]
pkgs/itcl4.2.1/itclConfig.sh.in [moved from pkgs/itcl4.2.0/itclConfig.sh.in with 100% similarity]
pkgs/itcl4.2.1/library/itcl.tcl [moved from pkgs/itcl4.2.0/library/itcl.tcl with 100% similarity]
pkgs/itcl4.2.1/library/itclHullCmds.tcl [moved from pkgs/itcl4.2.0/library/itclHullCmds.tcl with 100% similarity]
pkgs/itcl4.2.1/library/itclWidget.tcl [moved from pkgs/itcl4.2.0/library/itclWidget.tcl with 100% similarity]
pkgs/itcl4.2.1/library/test_Itcl_CreateObject.tcl [moved from pkgs/itcl4.2.0/library/test_Itcl_CreateObject.tcl with 100% similarity]
pkgs/itcl4.2.1/license.terms [moved from pkgs/itcl4.2.0/license.terms with 100% similarity]
pkgs/itcl4.2.1/pkgIndex.tcl.in [moved from pkgs/itcl4.2.0/pkgIndex.tcl.in with 93% similarity]
pkgs/itcl4.2.1/releasenotes.txt [moved from pkgs/itcl4.2.0/releasenotes.txt with 100% similarity]
pkgs/itcl4.2.1/tclconfig/README.txt [moved from pkgs/tdbcmysql1.1.1/tclconfig/README.txt with 81% similarity]
pkgs/itcl4.2.1/tclconfig/install-sh [moved from pkgs/tdbc1.1.1/tclconfig/install-sh with 55% similarity]
pkgs/itcl4.2.1/tclconfig/tcl.m4 [moved from pkgs/tdbc1.1.1/tclconfig/tcl.m4 with 95% similarity]
pkgs/itcl4.2.1/tests/all.tcl [moved from pkgs/itcl4.2.0/tests/all.tcl with 100% similarity]
pkgs/itcl4.2.1/tests/basic.test [moved from pkgs/itcl4.2.0/tests/basic.test with 99% similarity]
pkgs/itcl4.2.1/tests/body.test [moved from pkgs/itcl4.2.0/tests/body.test with 100% similarity]
pkgs/itcl4.2.1/tests/chain.test [moved from pkgs/itcl4.2.0/tests/chain.test with 100% similarity]
pkgs/itcl4.2.1/tests/delete.test [moved from pkgs/itcl4.2.0/tests/delete.test with 100% similarity]
pkgs/itcl4.2.1/tests/eclasscomponent.test [moved from pkgs/itcl4.2.0/tests/eclasscomponent.test with 100% similarity]
pkgs/itcl4.2.1/tests/ensemble.test [moved from pkgs/itcl4.2.0/tests/ensemble.test with 100% similarity]
pkgs/itcl4.2.1/tests/general1.test [moved from pkgs/itcl4.2.0/tests/general1.test with 100% similarity]
pkgs/itcl4.2.1/tests/helpers.tcl [moved from pkgs/itcl4.2.0/tests/helpers.tcl with 100% similarity]
pkgs/itcl4.2.1/tests/import.test [moved from pkgs/itcl4.2.0/tests/import.test with 97% similarity]
pkgs/itcl4.2.1/tests/info.test [moved from pkgs/itcl4.2.0/tests/info.test with 100% similarity]
pkgs/itcl4.2.1/tests/inherit.test [moved from pkgs/itcl4.2.0/tests/inherit.test with 100% similarity]
pkgs/itcl4.2.1/tests/interp.test [moved from pkgs/itcl4.2.0/tests/interp.test with 68% similarity]
pkgs/itcl4.2.1/tests/local.test [moved from pkgs/itcl4.2.0/tests/local.test with 100% similarity]
pkgs/itcl4.2.1/tests/methods.test [moved from pkgs/itcl4.2.0/tests/methods.test with 83% similarity]
pkgs/itcl4.2.1/tests/mkindex.itcl [moved from pkgs/itcl4.2.0/tests/mkindex.itcl with 100% similarity]
pkgs/itcl4.2.1/tests/mkindex.test [moved from pkgs/itcl4.2.0/tests/mkindex.test with 100% similarity]
pkgs/itcl4.2.1/tests/namespace.test [moved from pkgs/itcl4.2.0/tests/namespace.test with 100% similarity]
pkgs/itcl4.2.1/tests/protection.test [moved from pkgs/itcl4.2.0/tests/protection.test with 100% similarity]
pkgs/itcl4.2.1/tests/scope.test [moved from pkgs/itcl4.2.0/tests/scope.test with 100% similarity]
pkgs/itcl4.2.1/tests/sfbugs.test [moved from pkgs/itcl4.2.0/tests/sfbugs.test with 99% similarity]
pkgs/itcl4.2.1/tests/tclIndex [moved from pkgs/itcl4.2.0/tests/tclIndex with 100% similarity]
pkgs/itcl4.2.1/tests/typeclass.test [moved from pkgs/itcl4.2.0/tests/typeclass.test with 100% similarity]
pkgs/itcl4.2.1/tests/typedelegation.test [moved from pkgs/itcl4.2.0/tests/typedelegation.test with 100% similarity]
pkgs/itcl4.2.1/tests/typefunction.test [moved from pkgs/itcl4.2.0/tests/typefunction.test with 100% similarity]
pkgs/itcl4.2.1/tests/typeinfo.test [moved from pkgs/itcl4.2.0/tests/typeinfo.test with 100% similarity]
pkgs/itcl4.2.1/tests/typeoption.test [moved from pkgs/itcl4.2.0/tests/typeoption.test with 100% similarity]
pkgs/itcl4.2.1/tests/typevariable.test [moved from pkgs/itcl4.2.0/tests/typevariable.test with 100% similarity]
pkgs/itcl4.2.1/tests/widgetadaptor.test [moved from pkgs/itcl4.2.0/tests/widgetadaptor.test with 100% similarity]
pkgs/itcl4.2.1/tests/widgetclass.test [moved from pkgs/itcl4.2.0/tests/widgetclass.test with 100% similarity]
pkgs/itcl4.2.1/tools/genStubs.tcl [moved from pkgs/itcl4.2.0/tools/genStubs.tcl with 100% similarity]
pkgs/itcl4.2.1/win/dllEntryPoint.c [moved from pkgs/itcl4.2.0/win/dllEntryPoint.c with 100% similarity]
pkgs/itcl4.2.1/win/itcl.rc [moved from pkgs/itcl4.2.0/win/itcl.rc with 100% similarity]
pkgs/itcl4.2.1/win/makefile.vc [moved from pkgs/itcl4.2.0/win/makefile.vc with 100% similarity]
pkgs/itcl4.2.1/win/nmakehlp.c [moved from pkgs/itcl4.2.0/win/nmakehlp.c with 100% similarity]
pkgs/itcl4.2.1/win/rules-ext.vc [moved from pkgs/tdbc1.1.1/win/rules-ext.vc with 94% similarity]
pkgs/itcl4.2.1/win/rules.vc [moved from pkgs/tdbc1.1.1/win/rules.vc with 89% similarity]
pkgs/itcl4.2.1/win/targets.vc [moved from pkgs/sqlite3.30.1.2/win/targets.vc with 93% similarity]
pkgs/itcl4.2.1/win/toaster.bmp [moved from pkgs/itcl4.2.0/win/toaster.bmp with 100% similarity]
pkgs/sqlite3.30.1.2/win/sqlite.rc [deleted file]
pkgs/sqlite3.34.0/Makefile.in [moved from pkgs/sqlite3.30.1.2/Makefile.in with 93% similarity]
pkgs/sqlite3.34.0/README [moved from pkgs/sqlite3.30.1.2/README with 100% similarity]
pkgs/sqlite3.34.0/aclocal.m4 [moved from pkgs/itcl4.2.0/aclocal.m4 with 100% similarity]
pkgs/sqlite3.34.0/compat/sqlite3/shell.c [moved from pkgs/sqlite3.30.1.2/compat/sqlite3/shell.c with 87% similarity]
pkgs/sqlite3.34.0/compat/sqlite3/spaceanal.tcl [moved from pkgs/sqlite3.30.1.2/compat/sqlite3/spaceanal.tcl with 97% similarity]
pkgs/sqlite3.34.0/compat/sqlite3/sqlite3.c [moved from pkgs/sqlite3.30.1.2/compat/sqlite3/sqlite3.c with 91% similarity]
pkgs/sqlite3.34.0/compat/sqlite3/sqlite3.h [moved from pkgs/sqlite3.30.1.2/compat/sqlite3/sqlite3.h with 92% similarity]
pkgs/sqlite3.34.0/compat/sqlite3/sqlite3ext.h [moved from pkgs/sqlite3.30.1.2/compat/sqlite3/sqlite3ext.h with 96% similarity]
pkgs/sqlite3.34.0/configure [moved from pkgs/sqlite3.30.1.2/configure with 98% similarity]
pkgs/sqlite3.34.0/configure.ac [moved from pkgs/sqlite3.30.1.2/configure.ac with 99% similarity]
pkgs/sqlite3.34.0/doc/sqlite3.n [moved from pkgs/sqlite3.30.1.2/doc/sqlite3.n with 100% similarity]
pkgs/sqlite3.34.0/generic/tclsqlite3.c [moved from pkgs/sqlite3.30.1.2/generic/tclsqlite3.c with 97% similarity]
pkgs/sqlite3.34.0/license.terms [moved from pkgs/sqlite3.30.1.2/license.terms with 100% similarity]
pkgs/sqlite3.34.0/pkgIndex.tcl.in [moved from pkgs/sqlite3.30.1.2/pkgIndex.tcl.in with 100% similarity]
pkgs/sqlite3.34.0/tclconfig/install-sh [moved from pkgs/sqlite3.30.1.2/tclconfig/install-sh with 55% similarity]
pkgs/sqlite3.34.0/tclconfig/tcl.m4 [moved from pkgs/sqlite3.30.1.2/tclconfig/tcl.m4 with 95% similarity]
pkgs/sqlite3.34.0/tests/all.tcl [moved from pkgs/sqlite3.30.1.2/tests/all.tcl with 100% similarity]
pkgs/sqlite3.34.0/tests/leapsecond.test [moved from pkgs/sqlite3.30.1.2/tests/leapsecond.test with 100% similarity]
pkgs/sqlite3.34.0/win/makefile.vc [moved from pkgs/sqlite3.30.1.2/win/makefile.vc with 100% similarity]
pkgs/sqlite3.34.0/win/nmakehlp.c [moved from pkgs/sqlite3.30.1.2/win/nmakehlp.c with 100% similarity]
pkgs/sqlite3.34.0/win/rules-ext.vc [moved from pkgs/thread2.8.5/win/rules-ext.vc with 100% similarity]
pkgs/sqlite3.34.0/win/rules.vc [moved from pkgs/thread2.8.5/win/rules.vc with 95% similarity]
pkgs/sqlite3.34.0/win/targets.vc [moved from pkgs/thread2.8.5/win/targets.vc with 100% similarity]
pkgs/tdbc1.1.2/ChangeLog [moved from pkgs/tdbc1.1.1/ChangeLog with 100% similarity]
pkgs/tdbc1.1.2/Makefile.in [moved from pkgs/tdbc1.1.1/Makefile.in with 98% similarity]
pkgs/tdbc1.1.2/README [moved from pkgs/tdbc1.1.1/README with 98% similarity]
pkgs/tdbc1.1.2/aclocal.m4 [moved from pkgs/tdbcsqlite3-1.1.1/aclocal.m4 with 100% similarity]
pkgs/tdbc1.1.2/configure [moved from pkgs/tdbc1.1.1/configure with 98% similarity]
pkgs/tdbc1.1.2/configure.ac [moved from pkgs/tdbc1.1.1/configure.ac with 99% similarity]
pkgs/tdbc1.1.2/doc/Tdbc_Init.3 [moved from pkgs/tdbc1.1.1/doc/Tdbc_Init.3 with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc.n [moved from pkgs/tdbc1.1.1/doc/tdbc.n with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc_connection.n [moved from pkgs/tdbc1.1.1/doc/tdbc_connection.n with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc_mapSqlState.n [moved from pkgs/tdbc1.1.1/doc/tdbc_mapSqlState.n with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc_resultset.n [moved from pkgs/tdbc1.1.1/doc/tdbc_resultset.n with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc_statement.n [moved from pkgs/tdbc1.1.1/doc/tdbc_statement.n with 100% similarity]
pkgs/tdbc1.1.2/doc/tdbc_tokenize.n [moved from pkgs/tdbc1.1.1/doc/tdbc_tokenize.n with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbc.c [moved from pkgs/tdbc1.1.1/generic/tdbc.c with 99% similarity]
pkgs/tdbc1.1.2/generic/tdbc.decls [moved from pkgs/tdbc1.1.1/generic/tdbc.decls with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbc.h [moved from pkgs/tdbc1.1.1/generic/tdbc.h with 96% similarity]
pkgs/tdbc1.1.2/generic/tdbcDecls.h [moved from pkgs/tdbc1.1.1/generic/tdbcDecls.h with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbcInt.h [moved from pkgs/tdbc1.1.1/generic/tdbcInt.h with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbcStubInit.c [moved from pkgs/tdbc1.1.1/generic/tdbcStubInit.c with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbcStubLib.c [moved from pkgs/tdbc1.1.1/generic/tdbcStubLib.c with 100% similarity]
pkgs/tdbc1.1.2/generic/tdbcTokenize.c [moved from pkgs/tdbc1.1.1/generic/tdbcTokenize.c with 99% similarity]
pkgs/tdbc1.1.2/library/tdbc.tcl [moved from pkgs/tdbc1.1.1/library/tdbc.tcl with 100% similarity]
pkgs/tdbc1.1.2/license.terms [moved from pkgs/tdbcodbc1.1.1/license.terms with 100% similarity]
pkgs/tdbc1.1.2/pkgIndex.tcl.in [moved from pkgs/tdbc1.1.1/pkgIndex.tcl.in with 100% similarity]
pkgs/tdbc1.1.2/tclconfig/README.txt [moved from pkgs/itcl4.2.0/tclconfig/README.txt with 81% similarity]
pkgs/tdbc1.1.2/tclconfig/install-sh [moved from pkgs/itcl4.2.0/tclconfig/install-sh with 55% similarity]
pkgs/tdbc1.1.2/tclconfig/tcl.m4 [moved from pkgs/itcl4.2.0/tclconfig/tcl.m4 with 95% similarity]
pkgs/tdbc1.1.2/tdbcConfig.sh.in [moved from pkgs/tdbc1.1.1/tdbcConfig.sh.in with 100% similarity]
pkgs/tdbc1.1.2/tests/all.tcl [moved from pkgs/tdbc1.1.1/tests/all.tcl with 100% similarity]
pkgs/tdbc1.1.2/tests/tdbc.test [moved from pkgs/tdbc1.1.1/tests/tdbc.test with 100% similarity]
pkgs/tdbc1.1.2/tests/tokenize.test [moved from pkgs/tdbc1.1.1/tests/tokenize.test with 100% similarity]
pkgs/tdbc1.1.2/tools/genExtStubs.tcl [moved from pkgs/tdbc1.1.1/tools/genExtStubs.tcl with 100% similarity]
pkgs/tdbc1.1.2/tools/genStubs.tcl [moved from pkgs/tdbc1.1.1/tools/genStubs.tcl with 100% similarity]
pkgs/tdbc1.1.2/tools/tdbc-man2html.tcl [moved from pkgs/tdbc1.1.1/tools/tdbc-man2html.tcl with 100% similarity]
pkgs/tdbc1.1.2/win/makefile.vc [moved from pkgs/tdbc1.1.1/win/makefile.vc with 94% similarity]
pkgs/tdbc1.1.2/win/nmakehlp.c [moved from pkgs/tdbcsqlite3-1.1.1/win/nmakehlp.c with 100% similarity]
pkgs/tdbc1.1.2/win/rules-ext.vc [moved from pkgs/sqlite3.30.1.2/win/rules-ext.vc with 94% similarity]
pkgs/tdbc1.1.2/win/rules.vc [moved from pkgs/sqlite3.30.1.2/win/rules.vc with 89% similarity]
pkgs/tdbc1.1.2/win/targets.vc [moved from pkgs/tdbcmysql1.1.1/win/targets.vc with 93% similarity]
pkgs/tdbc1.1.2/win/tdbc.rc [moved from pkgs/tdbc1.1.1/win/tdbc.rc with 100% similarity]
pkgs/tdbcmysql1.1.1/win/rules.vc [deleted file]
pkgs/tdbcmysql1.1.2/ChangeLog [moved from pkgs/tdbcmysql1.1.1/ChangeLog with 100% similarity]
pkgs/tdbcmysql1.1.2/Makefile.in [moved from pkgs/tdbcmysql1.1.1/Makefile.in with 98% similarity]
pkgs/tdbcmysql1.1.2/README [moved from pkgs/tdbcmysql1.1.1/README with 97% similarity]
pkgs/tdbcmysql1.1.2/aclocal.m4 [moved from pkgs/tdbcpostgres1.1.1/aclocal.m4 with 100% similarity]
pkgs/tdbcmysql1.1.2/configure [moved from pkgs/tdbcmysql1.1.1/configure with 98% similarity]
pkgs/tdbcmysql1.1.2/configure.ac [moved from pkgs/tdbcmysql1.1.1/configure.ac with 99% similarity]
pkgs/tdbcmysql1.1.2/doc/tdbc_mysql.n [moved from pkgs/tdbcmysql1.1.1/doc/tdbc_mysql.n with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/fakemysql.h [moved from pkgs/tdbcmysql1.1.1/generic/fakemysql.h with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/int2ptr_ptr2int.h [moved from pkgs/tdbcpostgres1.1.1/generic/int2ptr_ptr2int.h with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/mysqlStubDefs.txt [moved from pkgs/tdbcmysql1.1.1/generic/mysqlStubDefs.txt with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/mysqlStubInit.c [moved from pkgs/tdbcmysql1.1.1/generic/mysqlStubInit.c with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/mysqlStubs.h [moved from pkgs/tdbcmysql1.1.1/generic/mysqlStubs.h with 100% similarity]
pkgs/tdbcmysql1.1.2/generic/tdbcmysql.c [moved from pkgs/tdbcmysql1.1.1/generic/tdbcmysql.c with 99% similarity]
pkgs/tdbcmysql1.1.2/library/tdbcmysql.tcl [moved from pkgs/tdbcmysql1.1.1/library/tdbcmysql.tcl with 100% similarity]
pkgs/tdbcmysql1.1.2/license.terms [moved from pkgs/tdbcmysql1.1.1/license.terms with 100% similarity]
pkgs/tdbcmysql1.1.2/pkgIndex.tcl.in [moved from pkgs/tdbcmysql1.1.1/pkgIndex.tcl.in with 100% similarity]
pkgs/tdbcmysql1.1.2/tclconfig/README.txt [moved from pkgs/tdbc1.1.1/tclconfig/README.txt with 81% similarity]
pkgs/tdbcmysql1.1.2/tclconfig/install-sh [moved from pkgs/tdbcmysql1.1.1/tclconfig/install-sh with 55% similarity]
pkgs/tdbcmysql1.1.2/tclconfig/tcl.m4 [moved from pkgs/tdbcmysql1.1.1/tclconfig/tcl.m4 with 95% similarity]
pkgs/tdbcmysql1.1.2/tests/all.tcl [moved from pkgs/tdbcodbc1.1.1/tests/all.tcl with 100% similarity]
pkgs/tdbcmysql1.1.2/tests/tdbcmysql.test [moved from pkgs/tdbcmysql1.1.1/tests/tdbcmysql.test with 100% similarity]
pkgs/tdbcmysql1.1.2/win/makefile.vc [moved from pkgs/tdbcmysql1.1.1/win/makefile.vc with 95% similarity]
pkgs/tdbcmysql1.1.2/win/nmakehlp.c [moved from pkgs/tdbc1.1.1/win/nmakehlp.c with 99% similarity]
pkgs/tdbcmysql1.1.2/win/rules-ext.vc [moved from pkgs/tdbcodbc1.1.1/win/rules-ext.vc with 94% similarity]
pkgs/tdbcmysql1.1.2/win/rules.vc [new file with mode: 0644]
pkgs/tdbcmysql1.1.2/win/targets.vc [moved from pkgs/tdbc1.1.1/win/targets.vc with 93% similarity]
pkgs/tdbcodbc1.1.1/tclconfig/install-sh [deleted file]
pkgs/tdbcodbc1.1.1/tclconfig/tcl.m4 [deleted file]
pkgs/tdbcodbc1.1.1/win/rules.vc [deleted file]
pkgs/tdbcodbc1.1.1/win/targets.vc [deleted file]
pkgs/tdbcodbc1.1.2/ChangeLog [moved from pkgs/tdbcodbc1.1.1/ChangeLog with 100% similarity]
pkgs/tdbcodbc1.1.2/Makefile.in [moved from pkgs/tdbcodbc1.1.1/Makefile.in with 100% similarity]
pkgs/tdbcodbc1.1.2/README [moved from pkgs/tdbcodbc1.1.1/README with 95% similarity]
pkgs/tdbcodbc1.1.2/aclocal.m4 [moved from pkgs/tdbcodbc1.1.1/aclocal.m4 with 100% similarity]
pkgs/tdbcodbc1.1.2/configure [moved from pkgs/tdbcodbc1.1.1/configure with 98% similarity]
pkgs/tdbcodbc1.1.2/configure.ac [moved from pkgs/tdbcodbc1.1.1/configure.ac with 99% similarity]
pkgs/tdbcodbc1.1.2/doc/tdbc_odbc.n [moved from pkgs/tdbcodbc1.1.1/doc/tdbc_odbc.n with 100% similarity]
pkgs/tdbcodbc1.1.2/generic/fakesql.h [moved from pkgs/tdbcodbc1.1.1/generic/fakesql.h with 99% similarity]
pkgs/tdbcodbc1.1.2/generic/int2ptr_ptr2int.h [moved from pkgs/tdbcodbc1.1.1/generic/int2ptr_ptr2int.h with 100% similarity]
pkgs/tdbcodbc1.1.2/generic/odbcStubDefs.txt [moved from pkgs/tdbcodbc1.1.1/generic/odbcStubDefs.txt with 100% similarity]
pkgs/tdbcodbc1.1.2/generic/odbcStubInit.c [moved from pkgs/tdbcodbc1.1.1/generic/odbcStubInit.c with 100% similarity]
pkgs/tdbcodbc1.1.2/generic/odbcStubs.h [moved from pkgs/tdbcodbc1.1.1/generic/odbcStubs.h with 100% similarity]
pkgs/tdbcodbc1.1.2/generic/tdbcodbc.c [moved from pkgs/tdbcodbc1.1.1/generic/tdbcodbc.c with 97% similarity]
pkgs/tdbcodbc1.1.2/library/tdbcodbc.tcl [moved from pkgs/tdbcodbc1.1.1/library/tdbcodbc.tcl with 100% similarity]
pkgs/tdbcodbc1.1.2/license.terms [moved from pkgs/tdbc1.1.1/license.terms with 100% similarity]
pkgs/tdbcodbc1.1.2/pkgIndex.tcl.in [moved from pkgs/tdbcodbc1.1.1/pkgIndex.tcl.in with 100% similarity]
pkgs/tdbcodbc1.1.2/tclconfig/README.txt [moved from pkgs/tdbcodbc1.1.1/tclconfig/README.txt with 81% similarity]
pkgs/tdbcodbc1.1.2/tclconfig/install-sh [new file with mode: 0644]
pkgs/tdbcodbc1.1.2/tclconfig/tcl.m4 [new file with mode: 0644]
pkgs/tdbcodbc1.1.2/tests/all.tcl [moved from pkgs/tdbcmysql1.1.1/tests/all.tcl with 100% similarity]
pkgs/tdbcodbc1.1.2/tests/tdbcodbc.test [moved from pkgs/tdbcodbc1.1.1/tests/tdbcodbc.test with 100% similarity]
pkgs/tdbcodbc1.1.2/tests/test.mdb [moved from pkgs/tdbcodbc1.1.1/tests/test.mdb with 100% similarity]
pkgs/tdbcodbc1.1.2/win/makefile.vc [moved from pkgs/tdbcodbc1.1.1/win/makefile.vc with 96% similarity]
pkgs/tdbcodbc1.1.2/win/nmakehlp.c [moved from pkgs/tdbcmysql1.1.1/win/nmakehlp.c with 99% similarity]
pkgs/tdbcodbc1.1.2/win/rules-ext.vc [moved from pkgs/tdbcmysql1.1.1/win/rules-ext.vc with 94% similarity]
pkgs/tdbcodbc1.1.2/win/rules.vc [new file with mode: 0644]
pkgs/tdbcodbc1.1.2/win/targets.vc [moved from pkgs/itcl4.2.0/win/targets.vc with 93% similarity]
pkgs/tdbcpostgres1.1.1/tclconfig/README.txt [deleted file]
pkgs/tdbcpostgres1.1.1/tclconfig/install-sh [deleted file]
pkgs/tdbcpostgres1.1.1/tclconfig/tcl.m4 [deleted file]
pkgs/tdbcpostgres1.1.1/win/nmakehlp.c [deleted file]
pkgs/tdbcpostgres1.1.1/win/rules-ext.vc [deleted file]
pkgs/tdbcpostgres1.1.1/win/rules.vc [deleted file]
pkgs/tdbcpostgres1.1.1/win/targets.vc [deleted file]
pkgs/tdbcpostgres1.1.2/ChangeLog [moved from pkgs/tdbcpostgres1.1.1/ChangeLog with 99% similarity]
pkgs/tdbcpostgres1.1.2/Makefile.in [moved from pkgs/tdbcpostgres1.1.1/Makefile.in with 98% similarity]
pkgs/tdbcpostgres1.1.2/README [moved from pkgs/tdbcpostgres1.1.1/README with 96% similarity]
pkgs/tdbcpostgres1.1.2/TODO [moved from pkgs/tdbcpostgres1.1.1/TODO with 100% similarity]
pkgs/tdbcpostgres1.1.2/aclocal.m4 [moved from pkgs/tdbcmysql1.1.1/aclocal.m4 with 100% similarity]
pkgs/tdbcpostgres1.1.2/configure [moved from pkgs/tdbcpostgres1.1.1/configure with 98% similarity]
pkgs/tdbcpostgres1.1.2/configure.ac [moved from pkgs/tdbcpostgres1.1.1/configure.ac with 99% similarity]
pkgs/tdbcpostgres1.1.2/doc/tdbc_postgres.n [moved from pkgs/tdbcpostgres1.1.1/doc/tdbc_postgres.n with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/fakepq.h [moved from pkgs/tdbcpostgres1.1.1/generic/fakepq.h with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/int2ptr_ptr2int.h [moved from pkgs/tdbcmysql1.1.1/generic/int2ptr_ptr2int.h with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/pqStubDefs.txt [moved from pkgs/tdbcpostgres1.1.1/generic/pqStubDefs.txt with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/pqStubInit.c [moved from pkgs/tdbcpostgres1.1.1/generic/pqStubInit.c with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/pqStubs.h [moved from pkgs/tdbcpostgres1.1.1/generic/pqStubs.h with 100% similarity]
pkgs/tdbcpostgres1.1.2/generic/tdbcpostgres.c [moved from pkgs/tdbcpostgres1.1.1/generic/tdbcpostgres.c with 99% similarity]
pkgs/tdbcpostgres1.1.2/library/tdbcpostgres.tcl [moved from pkgs/tdbcpostgres1.1.1/library/tdbcpostgres.tcl with 100% similarity]
pkgs/tdbcpostgres1.1.2/license.terms [moved from pkgs/tdbcpostgres1.1.1/license.terms with 100% similarity]
pkgs/tdbcpostgres1.1.2/pkgIndex.tcl.in [moved from pkgs/tdbcpostgres1.1.1/pkgIndex.tcl.in with 100% similarity]
pkgs/tdbcpostgres1.1.2/tclconfig/README.txt [new file with mode: 0644]
pkgs/tdbcpostgres1.1.2/tclconfig/install-sh [new file with mode: 0644]
pkgs/tdbcpostgres1.1.2/tclconfig/tcl.m4 [new file with mode: 0644]
pkgs/tdbcpostgres1.1.2/tests/all.tcl [moved from pkgs/tdbcpostgres1.1.1/tests/all.tcl with 100% similarity]
pkgs/tdbcpostgres1.1.2/tests/future/tdbcpostgre.test.tcl [moved from pkgs/tdbcpostgres1.1.1/tests/future/tdbcpostgre.test.tcl with 100% similarity]
pkgs/tdbcpostgres1.1.2/tests/tdbcpostgres.test [moved from pkgs/tdbcpostgres1.1.1/tests/tdbcpostgres.test with 100% similarity]
pkgs/tdbcpostgres1.1.2/win/makefile.vc [moved from pkgs/tdbcpostgres1.1.1/win/makefile.vc with 95% similarity]
pkgs/tdbcpostgres1.1.2/win/nmakehlp.c [moved from pkgs/tdbcodbc1.1.1/win/nmakehlp.c with 99% similarity]
pkgs/tdbcpostgres1.1.2/win/rules-ext.vc [new file with mode: 0644]
pkgs/tdbcpostgres1.1.2/win/rules.vc [new file with mode: 0644]
pkgs/tdbcpostgres1.1.2/win/targets.vc [new file with mode: 0644]
pkgs/tdbcsqlite3-1.1.1/tclconfig/README.txt [deleted file]
pkgs/tdbcsqlite3-1.1.1/tclconfig/install-sh [deleted file]
pkgs/tdbcsqlite3-1.1.1/tclconfig/tcl.m4 [deleted file]
pkgs/tdbcsqlite3-1.1.1/win/rules.vc [deleted file]
pkgs/tdbcsqlite3-1.1.1/win/targets.vc [deleted file]
pkgs/tdbcsqlite3-1.1.2/ChangeLog [moved from pkgs/tdbcsqlite3-1.1.1/ChangeLog with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/Makefile.in [moved from pkgs/tdbcsqlite3-1.1.1/Makefile.in with 99% similarity]
pkgs/tdbcsqlite3-1.1.2/README [moved from pkgs/tdbcsqlite3-1.1.1/README with 96% similarity]
pkgs/tdbcsqlite3-1.1.2/aclocal.m4 [moved from pkgs/tdbc1.1.1/aclocal.m4 with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/configure [moved from pkgs/tdbcsqlite3-1.1.1/configure with 98% similarity]
pkgs/tdbcsqlite3-1.1.2/configure.ac [moved from pkgs/tdbcsqlite3-1.1.1/configure.ac with 99% similarity]
pkgs/tdbcsqlite3-1.1.2/doc/tdbc_sqlite3.n [moved from pkgs/tdbcsqlite3-1.1.1/doc/tdbc_sqlite3.n with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/library/tdbcsqlite3.tcl [moved from pkgs/tdbcsqlite3-1.1.1/library/tdbcsqlite3.tcl with 99% similarity]
pkgs/tdbcsqlite3-1.1.2/license.terms [moved from pkgs/tdbcsqlite3-1.1.1/license.terms with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/pkgIndex.tcl.in [moved from pkgs/tdbcsqlite3-1.1.1/pkgIndex.tcl.in with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/tclconfig/README.txt [new file with mode: 0644]
pkgs/tdbcsqlite3-1.1.2/tclconfig/install-sh [new file with mode: 0644]
pkgs/tdbcsqlite3-1.1.2/tclconfig/tcl.m4 [new file with mode: 0644]
pkgs/tdbcsqlite3-1.1.2/tests/all.tcl [moved from pkgs/tdbcsqlite3-1.1.1/tests/all.tcl with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/tests/tdbcsqlite3.test [moved from pkgs/tdbcsqlite3-1.1.1/tests/tdbcsqlite3.test with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/win/makefile.vc [moved from pkgs/tdbcsqlite3-1.1.1/win/makefile.vc with 91% similarity]
pkgs/tdbcsqlite3-1.1.2/win/nmakehlp.c [new file with mode: 0644]
pkgs/tdbcsqlite3-1.1.2/win/rules-ext.vc [moved from pkgs/tdbcsqlite3-1.1.1/win/rules-ext.vc with 100% similarity]
pkgs/tdbcsqlite3-1.1.2/win/rules.vc [moved from pkgs/itcl4.2.0/win/rules.vc with 93% similarity]
pkgs/tdbcsqlite3-1.1.2/win/targets.vc [new file with mode: 0644]
pkgs/thread2.8.5/tclconfig/README.txt [deleted file]
pkgs/thread2.8.5/tclconfig/install-sh [deleted file]
pkgs/thread2.8.5/tclconfig/tcl.m4 [deleted file]
pkgs/thread2.8.6/ChangeLog [moved from pkgs/thread2.8.5/ChangeLog with 100% similarity]
pkgs/thread2.8.6/Makefile.in [moved from pkgs/thread2.8.5/Makefile.in with 87% similarity]
pkgs/thread2.8.6/README [moved from pkgs/thread2.8.5/README with 91% similarity]
pkgs/thread2.8.6/aclocal.m4 [moved from pkgs/thread2.8.5/aclocal.m4 with 95% similarity]
pkgs/thread2.8.6/configure [moved from pkgs/thread2.8.5/configure with 65% similarity]
pkgs/thread2.8.6/configure.ac [moved from pkgs/thread2.8.5/configure.ac with 99% similarity]
pkgs/thread2.8.6/doc/format.tcl [moved from pkgs/thread2.8.5/doc/format.tcl with 100% similarity]
pkgs/thread2.8.6/doc/html/thread.html [moved from pkgs/thread2.8.5/doc/html/thread.html with 100% similarity]
pkgs/thread2.8.6/doc/html/tpool.html [moved from pkgs/thread2.8.5/doc/html/tpool.html with 100% similarity]
pkgs/thread2.8.6/doc/html/tsv.html [moved from pkgs/thread2.8.5/doc/html/tsv.html with 100% similarity]
pkgs/thread2.8.6/doc/html/ttrace.html [moved from pkgs/thread2.8.5/doc/html/ttrace.html with 100% similarity]
pkgs/thread2.8.6/doc/man.macros [moved from pkgs/thread2.8.5/doc/man.macros with 100% similarity]
pkgs/thread2.8.6/doc/man/thread.n [moved from pkgs/thread2.8.5/doc/man/thread.n with 100% similarity]
pkgs/thread2.8.6/doc/man/tpool.n [moved from pkgs/thread2.8.5/doc/man/tpool.n with 100% similarity]
pkgs/thread2.8.6/doc/man/tsv.n [moved from pkgs/thread2.8.5/doc/man/tsv.n with 100% similarity]
pkgs/thread2.8.6/doc/man/ttrace.n [moved from pkgs/thread2.8.5/doc/man/ttrace.n with 100% similarity]
pkgs/thread2.8.6/doc/thread.man [moved from pkgs/thread2.8.5/doc/thread.man with 100% similarity]
pkgs/thread2.8.6/doc/tpool.man [moved from pkgs/thread2.8.5/doc/tpool.man with 100% similarity]
pkgs/thread2.8.6/doc/tsv.man [moved from pkgs/thread2.8.5/doc/tsv.man with 100% similarity]
pkgs/thread2.8.6/doc/ttrace.man [moved from pkgs/thread2.8.5/doc/ttrace.man with 100% similarity]
pkgs/thread2.8.6/generic/psGdbm.c [moved from pkgs/thread2.8.5/generic/psGdbm.c with 93% similarity]
pkgs/thread2.8.6/generic/psGdbm.h [moved from pkgs/thread2.8.5/generic/psGdbm.h with 100% similarity]
pkgs/thread2.8.6/generic/psLmdb.c [moved from pkgs/thread2.8.5/generic/psLmdb.c with 97% similarity]
pkgs/thread2.8.6/generic/psLmdb.h [moved from pkgs/thread2.8.5/generic/psLmdb.h with 100% similarity]
pkgs/thread2.8.6/generic/tclThread.h [moved from pkgs/thread2.8.5/generic/tclThread.h with 100% similarity]
pkgs/thread2.8.6/generic/tclThreadInt.h [moved from pkgs/thread2.8.5/generic/tclThreadInt.h with 81% similarity]
pkgs/thread2.8.6/generic/tclXkeylist.c [moved from pkgs/thread2.8.5/generic/tclXkeylist.c with 99% similarity]
pkgs/thread2.8.6/generic/tclXkeylist.h [moved from pkgs/thread2.8.5/generic/tclXkeylist.h with 100% similarity]
pkgs/thread2.8.6/generic/threadCmd.c [moved from pkgs/thread2.8.5/generic/threadCmd.c with 98% similarity]
pkgs/thread2.8.6/generic/threadNs.c [moved from pkgs/thread2.8.5/generic/threadNs.c with 100% similarity]
pkgs/thread2.8.6/generic/threadPoolCmd.c [moved from pkgs/thread2.8.5/generic/threadPoolCmd.c with 99% similarity]
pkgs/thread2.8.6/generic/threadSpCmd.c [moved from pkgs/thread2.8.5/generic/threadSpCmd.c with 99% similarity]
pkgs/thread2.8.6/generic/threadSpCmd.h [moved from pkgs/thread2.8.5/generic/threadSpCmd.h with 100% similarity]
pkgs/thread2.8.6/generic/threadSvCmd.c [moved from pkgs/thread2.8.5/generic/threadSvCmd.c with 99% similarity]
pkgs/thread2.8.6/generic/threadSvCmd.h [moved from pkgs/thread2.8.5/generic/threadSvCmd.h with 100% similarity]
pkgs/thread2.8.6/generic/threadSvKeylistCmd.c [moved from pkgs/thread2.8.5/generic/threadSvKeylistCmd.c with 100% similarity]
pkgs/thread2.8.6/generic/threadSvKeylistCmd.h [moved from pkgs/thread2.8.5/generic/threadSvKeylistCmd.h with 100% similarity]
pkgs/thread2.8.6/generic/threadSvListCmd.c [moved from pkgs/thread2.8.5/generic/threadSvListCmd.c with 99% similarity]
pkgs/thread2.8.6/generic/threadSvListCmd.h [moved from pkgs/thread2.8.5/generic/threadSvListCmd.h with 100% similarity]
pkgs/thread2.8.6/lib/ttrace.tcl [moved from pkgs/thread2.8.5/lib/ttrace.tcl with 99% similarity]
pkgs/thread2.8.6/license.terms [moved from pkgs/thread2.8.5/license.terms with 100% similarity]
pkgs/thread2.8.6/manifest.uuid [new file with mode: 0644]
pkgs/thread2.8.6/naviserver.m4 [moved from pkgs/thread2.8.5/naviserver.m4 with 100% similarity]
pkgs/thread2.8.6/pkgIndex.tcl.in [moved from pkgs/thread2.8.5/pkgIndex.tcl.in with 97% similarity]
pkgs/thread2.8.6/tcl/README [moved from pkgs/thread2.8.5/tcl/README with 100% similarity]
pkgs/thread2.8.6/tcl/cmdsrv/cmdsrv.tcl [moved from pkgs/thread2.8.5/tcl/cmdsrv/cmdsrv.tcl with 100% similarity]
pkgs/thread2.8.6/tcl/phttpd/index.htm [moved from pkgs/thread2.8.5/tcl/phttpd/index.htm with 100% similarity]
pkgs/thread2.8.6/tcl/phttpd/phttpd.tcl [moved from pkgs/thread2.8.5/tcl/phttpd/phttpd.tcl with 100% similarity]
pkgs/thread2.8.6/tcl/phttpd/uhttpd.tcl [moved from pkgs/thread2.8.5/tcl/phttpd/uhttpd.tcl with 100% similarity]
pkgs/thread2.8.6/tcl/tpool/tpool.tcl [moved from pkgs/thread2.8.5/tcl/tpool/tpool.tcl with 100% similarity]
pkgs/thread2.8.6/tclconfig/README.txt [new file with mode: 0644]
pkgs/thread2.8.6/tclconfig/install-sh [new file with mode: 0644]
pkgs/thread2.8.6/tclconfig/tcl.m4 [new file with mode: 0644]
pkgs/thread2.8.6/tests/French.txt [moved from pkgs/thread2.8.5/tests/French.txt with 100% similarity]
pkgs/thread2.8.6/tests/all.tcl [moved from pkgs/thread2.8.5/tests/all.tcl with 100% similarity]
pkgs/thread2.8.6/tests/store-load.tcl [moved from pkgs/thread2.8.5/tests/store-load.tcl with 100% similarity]
pkgs/thread2.8.6/tests/thread.test [moved from pkgs/thread2.8.5/tests/thread.test with 100% similarity]
pkgs/thread2.8.6/tests/tkt-84be1b5a73.test [moved from pkgs/thread2.8.5/tests/tkt-84be1b5a73.test with 100% similarity]
pkgs/thread2.8.6/tests/tpool.test [moved from pkgs/thread2.8.5/tests/tpool.test with 100% similarity]
pkgs/thread2.8.6/tests/tsv.test [moved from pkgs/thread2.8.5/tests/tsv.test with 100% similarity]
pkgs/thread2.8.6/tests/ttrace.test [moved from pkgs/thread2.8.5/tests/ttrace.test with 100% similarity]
pkgs/thread2.8.6/unix/CONFIG [moved from pkgs/thread2.8.5/unix/CONFIG with 100% similarity]
pkgs/thread2.8.6/unix/README [moved from pkgs/thread2.8.5/unix/README with 100% similarity]
pkgs/thread2.8.6/unix/threadUnix.c [moved from pkgs/thread2.8.5/unix/threadUnix.c with 100% similarity]
pkgs/thread2.8.6/win/CONFIG [moved from pkgs/thread2.8.5/win/CONFIG with 100% similarity]
pkgs/thread2.8.6/win/README.txt [moved from pkgs/thread2.8.5/win/README.txt with 100% similarity]
pkgs/thread2.8.6/win/makefile.vc [moved from pkgs/thread2.8.5/win/makefile.vc with 89% similarity]
pkgs/thread2.8.6/win/nmakehlp.c [moved from pkgs/thread2.8.5/win/nmakehlp.c with 100% similarity]
pkgs/thread2.8.6/win/pkg.vc [moved from pkgs/thread2.8.5/win/pkg.vc with 78% similarity]
pkgs/thread2.8.6/win/rules-ext.vc [new file with mode: 0644]
pkgs/thread2.8.6/win/rules.vc [new file with mode: 0644]
pkgs/thread2.8.6/win/targets.vc [new file with mode: 0644]
pkgs/thread2.8.6/win/thread.rc [moved from pkgs/thread2.8.5/win/thread.rc with 100% similarity]
pkgs/thread2.8.6/win/thread_win.dsp [moved from pkgs/thread2.8.5/win/thread_win.dsp with 100% similarity]
pkgs/thread2.8.6/win/thread_win.dsw [moved from pkgs/thread2.8.5/win/thread_win.dsw with 100% similarity]
tests/README
tests/aaa_exit.test
tests/all.tcl
tests/append.test
tests/appendComp.test
tests/apply.test
tests/assemble.test
tests/assocd.test
tests/async.test
tests/auto0/auto1/file1.tcl [new file with mode: 0644]
tests/auto0/auto1/package1.tcl [new file with mode: 0644]
tests/auto0/auto1/pkgIndex.tcl [new file with mode: 0644]
tests/auto0/auto1/tclIndex [new file with mode: 0644]
tests/auto0/auto2/file2.tcl [new file with mode: 0644]
tests/auto0/auto2/package2.tcl [new file with mode: 0644]
tests/auto0/auto2/pkgIndex.tcl [new file with mode: 0644]
tests/auto0/auto2/tclIndex [new file with mode: 0644]
tests/auto0/modules/mod1/test1-1.0.tm [new file with mode: 0644]
tests/auto0/modules/mod2/test2-2.0.tm [new file with mode: 0644]
tests/auto0/modules/test0-0.5.tm [new file with mode: 0644]
tests/autoMkindex.test
tests/basic.test
tests/binary.test
tests/case.test
tests/chan.test
tests/chanio.test
tests/clock.test
tests/cmdAH.test
tests/cmdIL.test
tests/cmdInfo.test
tests/cmdMZ.test
tests/compExpr-old.test
tests/compExpr.test
tests/compile.test
tests/concat.test
tests/config.test
tests/coroutine.test
tests/dcall.test
tests/dict.test
tests/dstring.test
tests/encoding.test
tests/env.test
tests/error.test
tests/eval.test
tests/event.test
tests/exec.test
tests/execute.test
tests/expr-old.test
tests/expr.test
tests/fCmd.test
tests/fileName.test
tests/fileSystem.test
tests/fileSystemEncoding.test
tests/for-old.test
tests/for.test
tests/foreach.test
tests/format.test
tests/get.test
tests/history.test
tests/http.test
tests/http11.test
tests/httpPipeline.test
tests/httpTest.tcl
tests/httpd
tests/httpd11.tcl
tests/httpold.test
tests/if-old.test
tests/if.test
tests/incr-old.test
tests/incr.test
tests/indexObj.test
tests/info.test
tests/init.test
tests/internals.tcl [new file with mode: 0644]
tests/interp.test
tests/io.test
tests/ioCmd.test
tests/ioTrans.test
tests/join.test
tests/lindex.test
tests/link.test
tests/linsert.test
tests/list.test
tests/listObj.test
tests/llength.test
tests/lmap.test
tests/load.test
tests/lrange.test
tests/lrepeat.test
tests/lreplace.test
tests/lsearch.test
tests/lset.test
tests/lsetComp.test
tests/macOSXFCmd.test
tests/macOSXLoad.test
tests/main.test
tests/mathop.test
tests/misc.test
tests/msgcat.test
tests/namespace-old.test
tests/namespace.test
tests/notify.test
tests/nre.test
tests/obj.test
tests/oo.test
tests/ooNext2.test
tests/opt.test
tests/package.test
tests/parse.test
tests/parseExpr.test
tests/parseOld.test
tests/pid.test
tests/pkgMkIndex.test
tests/platform.test
tests/proc-old.test
tests/proc.test
tests/pwd.test
tests/reg.test
tests/regexp.test
tests/regexpComp.test
tests/registry.test
tests/remote.tcl
tests/rename.test
tests/resolver.test
tests/result.test
tests/safe-stock.test [new file with mode: 0644]
tests/safe.test
tests/scan.test
tests/security.test
tests/set-old.test
tests/set.test
tests/socket.test
tests/split.test
tests/stack.test
tests/string.test
tests/stringComp.test
tests/stringObj.test
tests/subst.test
tests/switch.test
tests/tailcall.test
tests/tcltest.test
tests/tcltests.tcl
tests/thread.test
tests/timer.test
tests/tm.test
tests/trace.test
tests/unixFCmd.test
tests/unixFile.test
tests/unixForkEvent.test
tests/unixInit.test
tests/unixNotfy.test
tests/unknown.test
tests/unload.test
tests/uplevel.test
tests/upvar.test
tests/utf.test
tests/util.test
tests/var.test
tests/while-old.test
tests/while.test
tests/winConsole.test
tests/winDde.test
tests/winFCmd.test
tests/winFile.test
tests/winNotify.test
tests/winPipe.test
tests/winTime.test
tests/zlib.test
tools/checkLibraryDoc.tcl [changed mode: 0755->0644]
tools/fix_tommath_h.tcl
tools/genStubs.tcl
tools/index.tcl
tools/installData.tcl
tools/loadICU.tcl
tools/makeTestCases.tcl
tools/man2help.tcl
tools/man2help2.tcl
tools/man2html.tcl
tools/man2html1.tcl
tools/man2html2.tcl
tools/mkdepend.tcl
tools/regexpTestLib.tcl
tools/tclZIC.tcl
tools/tcltk-man2html-utils.tcl
tools/tcltk-man2html.tcl
tools/uniClass.tcl
tools/uniParse.tcl
unix/Makefile.in
unix/configure
unix/configure.in [changed mode: 0755->0644]
unix/install-sh
unix/installManPage
unix/tcl.m4
unix/tcl.spec
unix/tclLoadAix.c
unix/tclLoadDyld.c
unix/tclUnixChan.c
unix/tclUnixCompat.c
unix/tclUnixFCmd.c
unix/tclUnixFile.c
unix/tclUnixInit.c
unix/tclUnixNotfy.c
unix/tclUnixPipe.c
unix/tclUnixPort.h
unix/tclUnixSock.c
unix/tclUnixThrd.c
win/Makefile.in
win/configure
win/configure.in
win/makefile.vc
win/nmakehlp.c
win/rules-ext.vc
win/rules.vc
win/targets.vc
win/tcl.dsp
win/tcl.m4
win/tclAppInit.c
win/tclWin32Dll.c
win/tclWinChan.c
win/tclWinConsole.c
win/tclWinDde.c
win/tclWinFCmd.c
win/tclWinFile.c
win/tclWinInit.c
win/tclWinInt.h
win/tclWinLoad.c
win/tclWinPipe.c
win/tclWinPort.h
win/tclWinReg.c
win/tclWinSerial.c
win/tclWinSock.c
win/tclWinTest.c
win/tclWinThrd.c
win/tclWinTime.c

diff --git a/.github/workflows/linux-build.yml b/.github/workflows/linux-build.yml
new file mode 100644 (file)
index 0000000..3d56638
--- /dev/null
@@ -0,0 +1,49 @@
+name: Linux
+on: [push]
+jobs:
+  gcc:
+    runs-on: ubuntu-20.04
+    strategy:
+      matrix:
+        cfgopt:
+          - ""
+          - "--disable-shared"
+          - "--enable-symbols"
+          - "--enable-symbols=mem"
+          - "CFLAGS=-DTCL_UTF_MAX=4"
+          - "CFLAGS=-DTCL_UTF_MAX=6"
+    defaults:
+      run:
+        shell: bash
+        working-directory: unix
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Prepare
+        run: |
+          touch tclStubInit.c tclOOStubInit.c
+        working-directory: generic
+      - name: Configure ${{ matrix.cfgopt }}
+        run: |
+          mkdir "${HOME}/install dir"
+          ./configure ${CFGOPT} "--prefix=$HOME/install dir" || (cat config.log && exit 1)
+        env:
+          CFGOPT: ${{ matrix.cfgopt }}
+      - name: Build
+        run: |
+          make all
+      - name: Build Test Harness
+        run: |
+          make tcltest
+      - name: Run Tests
+        run: |
+          make test
+      - name: Test-Drive Installation
+        run: |
+          make install
+      - name: Create Distribution Package
+        run: |
+          make dist
+      - name: Convert Documentation to HTML
+        run: |
+          make html-tcl
diff --git a/.github/workflows/mac-build.yml b/.github/workflows/mac-build.yml
new file mode 100644 (file)
index 0000000..c1144ab
--- /dev/null
@@ -0,0 +1,58 @@
+name: macOS
+on: [push]
+jobs:
+  xcode:
+    runs-on: macos-11.0
+    defaults:
+      run:
+        shell: bash
+        working-directory: macosx
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Prepare
+        run: |
+          touch tclStubInit.c tclOOStubInit.c
+        working-directory: generic
+      - name: Build
+        run: make all
+      - name: Run Tests
+        run: make test styles=develop
+        env:
+          ERROR_ON_FAILURES: 1
+          MAC_CI: 1
+  clang:
+    runs-on: macos-11.0
+    strategy:
+      matrix:
+        cfgopt:
+          - ""
+          - "--disable-shared"
+          - "--enable-symbols"
+          - "--enable-symbols=mem"
+    defaults:
+      run:
+        shell: bash
+        working-directory: unix
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Prepare
+        run: |
+          touch tclStubInit.c tclOOStubInit.c
+          mkdir "$HOME/install dir"
+        working-directory: generic
+      - name: Configure ${{ matrix.cfgopt }}
+        # Note that macOS is always a 64 bit platform
+        run: ./configure --enable-64bit --enable-dtrace --enable-framework ${CFGOPT} "--prefix=$HOME/install" || (cat config.log && exit 1)
+        env:
+          CFGOPT: ${{ matrix.cfgopt }}
+      - name: Build
+        run: |
+          make all tcltest
+      - name: Run Tests
+        run: |
+          make test
+        env:
+          ERROR_ON_FAILURES: 1
+          MAC_CI: 1
diff --git a/.github/workflows/win-build.yml b/.github/workflows/win-build.yml
new file mode 100644 (file)
index 0000000..8e35798
--- /dev/null
@@ -0,0 +1,79 @@
+name: Windows
+on: [push]
+jobs:
+  msvc:
+    runs-on: windows-latest
+    defaults:
+      run:
+        shell: powershell
+        working-directory: win
+    strategy:
+      matrix:
+        cfgopt:
+          - ""
+          - "OPTS=static,msvcrt"
+          - "OPTS=symbols"
+          - "OPTS=memdbg"
+    # Using powershell means we need to explicitly stop on failure
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Init MSVC
+        uses: ilammy/msvc-dev-cmd@v1
+      - name: Build ${{ matrix.cfgopt }}
+        run: |
+          &nmake -f makefile.vc ${{ matrix.cfgopt }} all
+          if ($lastexitcode -ne 0) {
+             throw "nmake exit code: $lastexitcode"
+          }
+      - name: Build Test Harness ${{ matrix.cfgopt }}
+        run: |
+          &nmake -f makefile.vc ${{ matrix.cfgopt }} tcltest
+          if ($lastexitcode -ne 0) {
+             throw "nmake exit code: $lastexitcode"
+          }
+      - name: Run Tests ${{ matrix.cfgopt }}
+        run: |
+          &nmake -f makefile.vc ${{ matrix.cfgopt }} test
+          if ($lastexitcode -ne 0) {
+             throw "nmake exit code: $lastexitcode"
+          }
+        env:
+          ERROR_ON_FAILURES: 1
+  gcc:
+    runs-on: windows-latest
+    defaults:
+      run:
+        shell: bash
+        working-directory: win
+    strategy:
+      matrix:
+        cfgopt:
+          - ""
+          - "--disable-shared"
+          - "--enable-symbols"
+          - "--enable-symbols=mem"
+    # Using powershell means we need to explicitly stop on failure
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Install MSYS2 and Make
+        run: choco install msys2 make
+      - name: Prepare
+        run: |
+          touch tclStubInit.c tclOOStubInit.c
+          mkdir "${HOME}/install dir"
+        working-directory: generic
+      - name: Configure ${{ matrix.cfgopt }}
+        run: |
+          ./configure ${CFGOPT} "--prefix=$HOME/install dir" || (cat config.log && exit 1)
+        env:
+          CFGOPT: --enable-64bit ${{ matrix.cfgopt }}
+      - name: Build
+        run: make all
+      - name: Build Test Harness
+        run: make tcltest
+      - name: Run Tests
+        run: make test
+        env:
+          ERROR_ON_FAILURES: 1
diff --git a/.travis.yml b/.travis.yml
new file mode 100644 (file)
index 0000000..eb1ec0c
--- /dev/null
@@ -0,0 +1,385 @@
+language: c
+addons:
+  apt:
+    sources:
+      - ubuntu-toolchain-r-test
+    packages:
+      - binutils-mingw-w64-i686
+      - binutils-mingw-w64-x86-64
+      - gcc-mingw-w64
+      - gcc-mingw-w64-base
+      - gcc-mingw-w64-i686
+      - gcc-mingw-w64-x86-64
+      - gcc-multilib
+jobs:
+  include:
+# Testing on Linux GCC
+    - name: "Linux/GCC/Shared"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+    - name: "Linux/GCC/Shared: UTF_MAX=4"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT=CFLAGS=-DTCL_UTF_MAX=4
+    - name: "Linux/GCC/Shared: UTF_MAX=6"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT=CFLAGS=-DTCL_UTF_MAX=6
+    - name: "Linux/GCC/Static"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - CFGOPT="--disable-shared"
+        - BUILD_DIR=unix
+    - name: "Linux/GCC/Debug"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT="--enable-symbols"
+    - name: "Linux/GCC/Mem-Debug"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT="--enable-symbols=mem"
+# Newer/Older versions of GCC
+    - name: "Linux/GCC 10/Shared"
+      os: linux
+      dist: focal
+      compiler: gcc-10
+      addons:
+        apt:
+          packages:
+            - g++-10
+      env:
+        - BUILD_DIR=unix
+    - name: "Linux/GCC 5/Shared"
+      os: linux
+      dist: bionic
+      compiler: gcc-5
+      addons:
+        apt:
+          packages:
+            - g++-5
+      env:
+        - BUILD_DIR=unix
+# Testing on Linux Clang
+    - name: "Linux/Clang/Shared"
+      os: linux
+      dist: focal
+      compiler: clang
+      env:
+        - BUILD_DIR=unix
+    - name: "Linux/Clang/Static"
+      os: linux
+      dist: focal
+      compiler: clang
+      env:
+        - CFGOPT="--disable-shared"
+        - BUILD_DIR=unix
+    - name: "Linux/Clang/Debug"
+      os: linux
+      dist: focal
+      compiler: clang
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT="--enable-symbols"
+    - name: "Linux/Clang/Mem-Debug"
+      os: linux
+      dist: focal
+      compiler: clang
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT="--enable-symbols=mem"
+# Testing on Mac, various styles
+    - name: "macOS/Xcode 12/Shared"
+      os: osx
+      osx_image: xcode12.2
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: &mactest
+        - make all
+        # The styles=develop avoids some weird problems on OSX
+        - make test styles=develop
+    - name: "macOS/Xcode 12/Shared/Unix-like"
+      os: osx
+      osx_image: xcode12.2
+      env:
+        - BUILD_DIR=unix
+        - CFGOPT="--enable-dtrace"
+# Newer MacOS versions
+    - name: "macOS/Xcode 12/Universal Apps/Shared"
+      os: osx
+      osx_image: xcode12u
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: *mactest
+# Older MacOS versions
+    - name: "macOS/Xcode 11/Shared"
+      os: osx
+      osx_image: xcode11.7
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: *mactest
+    - name: "macOS/Xcode 10/Shared"
+      os: osx
+      osx_image: xcode10.3
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: *mactest
+    - name: "macOS/Xcode 9/Shared"
+      os: osx
+      osx_image: xcode9.4
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: *mactest
+    - name: "macOS/Xcode 8/Shared"
+      os: osx
+      osx_image: xcode8.3
+      env:
+        - BUILD_DIR=macosx
+      install: []
+      script: *mactest
+# Test with mingw-w64 cross-compile
+# Doesn't run tests because wine is only an imperfect Windows emulation
+    - name: "Linux-cross-Windows/GCC/Shared/no test"
+      os: linux
+      dist: focal
+      compiler: x86_64-w64-mingw32-gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--host=x86_64-w64-mingw32 --enable-64bit"
+      script: &crosstest
+        - make all tcltest
+        # Include a high visibility marker that tests are skipped outright
+        - >
+          echo "`tput setaf 3`SKIPPED TEST: CROSS COMPILING`tput sgr0`"
+# Test with mingw-w64 (32 bit) cross-compile
+# Doesn't run tests because wine is only an imperfect Windows emulation
+    - name: "Linux-cross-Windows-32/GCC/Shared/no test"
+      os: linux
+      dist: focal
+      compiler: i686-w64-mingw32-gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT=--host=i686-w64-mingw32
+      script: *crosstest
+# Test on Windows with MSVC native
+    - name: "Windows/MSVC/Shared"
+      os: windows
+      compiler: cl
+      env: &vcenv
+        - BUILD_DIR=win
+        - VCDIR="/C/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC/Auxiliary/Build"
+      before_install: &vcpreinst
+        - touch generic/tclStubInit.c generic/tclOOStubInit.c
+        - PATH="$PATH:$VCDIR"
+        - cd ${BUILD_DIR}
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake '-f' makefile.vc test
+    - name: "Windows/MSVC/Shared: UTF_MAX=4"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=utfmax' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=utfmax' '-f' makefile.vc test
+    - name: "Windows/MSVC/Static"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=static,msvcrt' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=static,msvcrt' '-f' makefile.vc test
+    - name: "Windows/MSVC/StaticPackage"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=static,staticpkg,msvcrt' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=static,staticpkg,msvcrt' '-f' makefile.vc test
+    - name: "Windows/MSVC/Debug"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=symbols' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'OPTS=symbols' '-f' makefile.vc test
+    - name: "Windows/MSVC/Mem-Debug"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'STATS=memdbg' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x64 '&&' nmake 'STATS=memdbg' '-f' makefile.vc test
+# Test on Windows with MSVC native (32-bit)
+    - name: "Windows/MSVC-x86/Shared"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake '-f' makefile.vc test
+    - name: "Windows/MSVC-x86/Shared: UTF_MAX=4"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=utfmax' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=utfmax' '-f' makefile.vc test
+    - name: "Windows/MSVC-x86/Static"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=static,msvcrt' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=static,msvcrt' '-f' makefile.vc test
+    - name: "Windows/MSVC-x86/Debug"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=symbols' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'OPTS=symbols' '-f' makefile.vc test
+    - name: "Windows/MSVC-x86/Mem-Debug"
+      os: windows
+      compiler: cl
+      env: *vcenv
+      before_install: *vcpreinst
+      install: []
+      script:
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'STATS=memdbg' '-f' makefile.vc all tcltest
+        - cmd.exe //C vcvarsall.bat x86 '&&' nmake 'STATS=memdbg' '-f' makefile.vc test
+# Test on Windows with GCC native
+    - name: "Windows/GCC/Shared"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-64bit"
+      before_install: &makepreinst
+        - touch generic/tclStubInit.c generic/tclOOStubInit.c
+        - choco install -y make
+        - cd ${BUILD_DIR}
+    - name: "Windows/GCC/Shared: UTF_MAX=4"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-64bit CFLAGS=-DTCL_UTF_MAX=4"
+      before_install: *makepreinst
+    - name: "Windows/GCC/Static"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-64bit --disable-shared"
+      before_install: *makepreinst
+    - name: "Windows/GCC/Debug"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-64bit --enable-symbols"
+      before_install: *makepreinst
+    - name: "Windows/GCC/Mem-Debug"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-64bit --enable-symbols=mem"
+      before_install: *makepreinst
+# Test on Windows with GCC native (32-bit)
+    - name: "Windows/GCC-x86/Shared"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+      before_install: *makepreinst
+    - name: "Windows/GCC-x86/Shared: UTF_MAX=4"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="CFLAGS=-DTCL_UTF_MAX=4"
+      before_install: *makepreinst
+    - name: "Windows/GCC-x86/Static"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--disable-shared"
+      before_install: *makepreinst
+    - name: "Windows/GCC-x86/Debug"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-symbols"
+      before_install: *makepreinst
+    - name: "Windows/GCC-x86/Mem-Debug"
+      os: windows
+      compiler: gcc
+      env:
+        - BUILD_DIR=win
+        - CFGOPT="--enable-symbols=mem"
+      before_install: *makepreinst
+# "make dist" only
+    - name: "Linux: make dist"
+      os: linux
+      dist: focal
+      compiler: gcc
+      env:
+        - BUILD_DIR=unix
+      script:
+        - make dist
+before_install:
+  - touch generic/tclStubInit.c generic/tclOOStubInit.c
+  - cd ${BUILD_DIR}
+install:
+  - mkdir "$HOME/install dir"
+  - ./configure ${CFGOPT} "--prefix=$HOME/install dir" || (cat config.log && exit 1)
+before_script:
+  - export ERROR_ON_FAILURES=1
+script:
+  - make all tcltest || echo "Something wrong, maybe a hickup, let's try again"
+  - make test
+  - make install
index 84281bc..ec5e78f 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1847,7 +1847,7 @@ a better first place to look now.
 
        * tools/uniClass.tcl:    [FRQ 3473670]: Various Unicode-related
        * tools/uniParse.tcl:    speedups/robustness. Enhanced tools to be
-       * generic/tclUniData.c:  able to handle characters > 0xffff. Done in
+       * generic/tclUniData.c:  able to handle characters > 0xFFFF. Done in
        * generic/tclUtf.c:      all branches in order to simplify merges for
        * generic/regc_locale.c: new Unicode versions (such as 6.1)
 
index 5b62351..7e78c19 100644 (file)
        * generic/tclCmdMZ.c: Fixed infinite loop bug with [regexp -all]
        [Bug: 4981].
 
-       * tests/*.test: Changed all occurances of "namespace import
+       * tests/*.test: Changed all occurrences of "namespace import
        ::tcltest" to "namespace import -force ::tcltest" [Bug: 3948].
 
 2000-04-09  Brent Welch <welch@scriptics.com>
index 06e7c36..5fdff46 100644 (file)
 
        * mac/tclMacFile.c: fixed bug in permission checking code
 
-       * mac/tclMacLoad.c: corrected utf8 handling, comparison of package
+       * mac/tclMacLoad.c: corrected utf-8 handling, comparison of package
        names to code fragment names changed to only match on the length of
        package name, this allows for fragment names with version numbers
        appended.
        * generic/tclVar.c (Tcl_UnsetObjCmd): Rewrote argument parser to avoid
        a read off the end of the argument array that could occur when
        executing something like [unset -nocomplain] was executed. Improved
-       the error message given when too few arguments are given (-nocomplain
+       the error message given when not enough arguments are given (-nocomplain
        should obviously be *before* --, not after it) and also modified the
        test suite to take account of that and the documentation to use the
        same improvement. [Bug 405769]
index 9931657..fa31e42 100644 (file)
 
 2002-07-05  Reinhard Max  <max@suse.de>
 
-       * generic/tclClock.c (FormatClock): Convert the format string to UTF8
+       * generic/tclClock.c (FormatClock): Convert the format string to utf-8
        before calling TclpStrftime, so that non-ASCII characters don't get
        mangled when the result string is being converted back.
        * tests/clock.test: Added a test for that.
index daf124f..f7da18d 100644 (file)
        934511].
 
        * doc/CrtCommand.3: Added note that the arguments given to the command
-       proc of a Tcl_CreateCommand are in utf8 since Tcl 8.1. Closing [Patch
+       proc of a Tcl_CreateCommand are in utf-8 since Tcl 8.1. Closing [Patch
        414778].
 
        * doc/ChnlStack.3: Removed the declaration that the interp argument to
 2004-06-02  Jeff Hobbs <jeffh@ActiveState.com>
 
        * win/tclWinFile.c (TclpFindExecutable): when using GetModuleFileNameA
-       (Win9x), convert from CP_ACP to WCHAR then convert back to utf8.
+       (Win9x), convert from CP_ACP to WCHAR then convert back to utf-8.
        Adjunct to 2004-04-07 fix.
 
 2004-06-02  David Gravereaux <davygrvy@pobox.com>
index 0d1d7cf..109ea8e 100644 (file)
        * generic/tclCompCmds.c:        Updated callers to call new routine.
        * generic/tclDictObj.c: Updated callers to call new routine.
        * tests/obj.test:       Corrected bad tests that actually expected
-       values like "47" and "0xac" to be accepted as booleans.
+       values like "47" and "0xAC" to be accepted as booleans.
 
        * generic/tclLiteral.c: Disabled the code that forces some literals
        into the "int" Tcl_ObjType during registration. We can re-enable it if
index 3b192a5..c559a82 100644 (file)
--- a/README.md
+++ b/README.md
@@ -1,11 +1,13 @@
 # README:  Tcl
 
-This is the **Tcl 8.6.10** source distribution.
+This is the **Tcl 8.6.11** source distribution.
 
 You can get any source release of Tcl from [our distribution
 site](https://sourceforge.net/projects/tcl/files/Tcl/).
 
-[![Build Status](https://travis-ci.org/tcltk/tcl.svg?branch=core-8-6-branch)](https://travis-ci.org/tcltk/tcl)
+[![Build Status](https://github.com/tcltk/tcl/workflows/Linux/badge.svg?branch=core-8-6-branch)](https://github.com/tcltk/tcl/actions?query=workflow%3A%22Linux%22+branch%3Acore-8-6-branch)
+[![Build Status](https://github.com/tcltk/tcl/workflows/Windows/badge.svg?branch=core-8-6-branch)](https://github.com/tcltk/tcl/actions?query=workflow%3A%22Windows%22+branch%3Acore-8-6-branch)
+[![Build Status](https://github.com/tcltk/tcl/workflows/macOS/badge.svg?branch=core-8-6-branch)](https://github.com/tcltk/tcl/actions?query=workflow%3A%22macOS%22+branch%3Acore-8-6-branch)
 
 ## Contents
  1. [Introduction](#intro)
@@ -29,19 +31,19 @@ powerful command languages for applications.
 
 Tcl is maintained, enhanced, and distributed freely by the Tcl community.
 Source code development and tracking of bug reports and feature requests
-takes place at [core.tcl-lang.org](https://core.tcl-lang.org/).
+take place at [core.tcl-lang.org](https://core.tcl-lang.org/).
 Tcl/Tk release and mailing list services are [hosted by
 SourceForge](https://sourceforge.net/projects/tcl/)
 with the Tcl Developer Xchange hosted at
 [www.tcl-lang.org](https://www.tcl-lang.org).
 
-Tcl is a freely available open source package.  You can do virtually
+Tcl is a freely available open-source package.  You can do virtually
 anything you like with it, such as modifying it, redistributing it,
 and selling it either in whole or in part.  See the file
 `license.terms` for complete information.
 
 ## <a id="doc">2.</a> Documentation
-Extensive documentation is available at our website.
+Extensive documentation is available on our website.
 The home page for this release, including new features, is
 [here](https://www.tcl.tk/software/tcltk/8.6.html).
 Detailed release notes can be found at the
@@ -88,16 +90,16 @@ about building Tcl from sources
 [online](https://www.tcl-lang.org/doc/howto/compile.html).
 
 ## <a id="devtools">4.</a> Development tools
-ActiveState produces a high quality set of commercial quality development
+ActiveState produces a high-quality set of commercial quality development
 tools that is available to accelerate your Tcl application development.
 Tcl Dev Kit builds on the earlier TclPro toolset and provides a debugger,
-static code checker, single-file wrapping utility, bytecode compiler and
+static code checker, single-file wrapping utility, bytecode compiler, and
 more.  More information can be found at
 
        http://www.ActiveState.com/Tcl
 
 ## <a id="complangtcl">5.</a> Tcl newsgroup
-There is a USENET news group, "`comp.lang.tcl`", intended for the exchange of
+There is a USENET newsgroup, "`comp.lang.tcl`", intended for the exchange of
 information about Tcl, Tk, and related applications.  The newsgroup is a
 great place to ask general information questions.  For bug reports, please
 see the "Support and bug fixes" section below.
diff --git a/changes b/changes
index 1b5b483..f662037 100644 (file)
--- a/changes
+++ b/changes
@@ -2307,7 +2307,7 @@ to the standard channel, do not increment the refcount. The channel can
 be NULL if there is for example no standard input. (JL)
 
 9/6/96 (portability improvement) Changed parsing of backslash sequences
-like \n to translate directly to absolute values like 0xa instead of
+like \n to translate directly to absolute values like 0xA instead of
 letting the compiler do the translation.  This guarantees that the
 translation is done the same everywhere. (JO)
 
@@ -8945,3 +8945,132 @@ improvements to regexp engine from Postgres (lane,porter,fellows,seltenreich)
 => http 2.9.1
 
 - Released 8.6.10, Nov 21, 2019 - details at http://core.tcl-lang.org/tcl/ -
+
+2019-12-03 (bug)[3cd9be] Corner case in surrogate handling (nijtmans)
+
+2019-12-09 (new) Add tcltest::(Setup|Eval|Cleanup|)Test (coulter,sebres)
+=> tcltest 2.5.2
+
+2019-12-12 (new) Add 3 libtommath functions to stub table (nijtmans)
+
+2019-12-23 (bug)[ce3b9f] compilation errors with clang, windows msys2 (nijtmans)
+
+2019-12-27 (bug)[1de6b0] [expr 1e2147483648] => 0.0 (kbk)
+
+2020-01-04 (bug)[912886] tis-620 encoding fails to load (coulter)
+
+2020-01-13 (bug)[0b9332] Win: support system encoding init to utf-8 (jedlička)
+
+2020-01-17 (bug)[8cd2fe] [unload] corrupted list of loaded packages (berc)
+
+2020-01-17 (bug)[5d989f] segfault in lsort for large list length (sebres)
+
+2020-01-30 (bug) Reset WSAGetLastError()/errno in channel close (nijtmans)
+
+2020-02-17 (bug) Win: avoid create of legacy error-vars on init phase (sebres)
+
+2020-02-25 (bug) release refs when setting class's superclasses fails (dkf)
+
+2020-02-26 (bug) C++ compiler compatibility for registry and dde (nijtmans)
+=> registry 1.4.3
+=> dde 1.3.5
+
+2020-03-05 (new) Update to Unicode-13 (nijtmans)
+
+2020-03-16 (bug)[8f89e2] Win: env var encoding, env-2.5 (sebres, nijtmans)
+
+2020-03-27 (bug)[767e07] Tcl_Get(Range|UniChar) validate index inputs (nijtmans)
+
+2020-03-28 (bug)[8edfce] [binary encode base64] & multi-byte wrapchars (dgp)
+
+2020-03-28 (bug)[ffeb20] [binary decode base64] ignore invalid chars (dgp)
+See RFC 2045
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-03-31 (bug)[b8e82d] some -maxlen values break uuencode round trip (dgp)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-04-01 (bug)[f58371] Fileevent run in proper thread (bron,sebres)
+
+2020-04-13 (bug)[afa4b2] TclNeedSpace bug; tests util-8.5 .. util-8.11 (dgp)
+
+2020-04-13 (bug)[085913] Tcl_DStringAppendElement # quoting precision (dgp)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-04-13 (bug)[a7f685] test util-5.52 (dgp)
+
+2020-04-13 (bug)[c61818] Tcl_UtfPrev regression (dgp)
+
+2020-04-15 (bug)[8af92d] zlib transform issue, bad inflate (sebres)
+
+2020-04-16 (bug)[5e6346] Tcl_UtfPrev handling of overlong sequences (dgp)
+
+2020-04-27 (bug)[45ca23] [string tolower] inconsistency (dgp)
+
+2020-04-30 (bug)[da2352] init [info hostname] with DNS, not NetBIOS (nadkarni)
+
+2020-05-11 (bug)[d402ff] Win32 potential crash when using main() (werner)
+
+2020-05-13 (bug)[81242a] revised documentation for Tcl_UtfAtIndex() (nijtmans)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-05-13 (bug)[ed2980] Tcl_UtfToUniChar reads > TCL_UTF_MAX bytes (nijtmans)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-06-02 (bug) prevent segfault in parser (sebres)
+
+2020-06-21 (bug)[f81bec] http POST a binary file (alakendu,nash)
+=> http 2.9.2
+
+2020-06-23 (bug)[41c985] auto_path nonsense in Safe Base (nash)
+
+2020-06-24 (bug)[f70ce1] zlib multi-stream inflate acts only on first (sebres)
+
+2020-07-09 (bug)[a1bd37] [clock scan] new ISO format (clock-34.(19-24)) (sebres)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-07-10 (bug)[501974] [clock scan] +time zone (clock-34.(53-68)) (sebres)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-07-15 (bug)[3c6e47] compiled [lappend] performance, avoid copy (sebres)
+
+2020-07-16 (bug)[5bbd04] Fix index underflow (schwab)
+
+2020-07-27 (bug)[cb0373] http::geturl -keepalive fixes (nash)
+=> http 2.9.3
+
+2020-08-10 (bug)[29e884] cmd resolution cycle (namespace-57.0) (coulter,sebres)
+
+2020-08-12 (bug)[e87000] Tcl_BadChannelOption tolerate NULL (werner,nijtmans)
+
+2020-08-31 (TIP #581) disfavor Master/Slave terminology (nijtmans)
+=> opt 0.4.8
+
+2020-09-11 (bug)[3bc0f4] UBSan complains about body.chars[] usage (nijtmans)
+
+2020-09-17 (bug)[835c93] Support TIP 525 exit code for -singleproc 1 (nijtmans)
+=> tcltest 2.5.3
+
+2020-09-25 (new) force -eofchar \032 when evaluating library scripts (nijtmans)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-09-29 (bug)[0063cb] http::geturl -headers must be dict (oehlmann,nijtmans)
+
+2020-10-19 (bug)[cb4582] Update install-sh script (stu,nijtmans)
+
+2020-10-22 (bug)[c97593] Usage of gnu_printf in latest mingw-w64 (nijtmans)
+
+2020-10-26 (new)[48898a] improve error message consistency (stu)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-11-06 (new) revised case of module names (nijtmans)
+        *** POTENTIAL INCOMPATIBILITY ***
+
+2020-12-10 (bug)[ed5be7] Win: recognize "comx:" as serial port (oehlmann)
+
+2020-12-11 (new) support for msys2, Big Sur (nijtmans)
+=> platform 1.0.15
+
+2020-12-23 tzdata updated to Olson's tzdata2020e (jima)
+
+- Released 8.6.11, Dec 31, 2020 - details at http://core.tcl-lang.org/tcl/ -
index c8e6940..f308cd0 100644 (file)
@@ -217,7 +217,7 @@ fake_getaddrinfo(const char *hostname, const char *servname,
        }
 
        if (!hostname) {
-               *res = malloc_ai(port, htonl(0x7f000001), hints);
+               *res = malloc_ai(port, htonl(0x7F000001), hints);
                if (*res == NULL)
                        return (EAI_MEMORY);
                return (0);
index ca20cf8..f6651d4 100644 (file)
@@ -21,10 +21,11 @@ gettimeofday(
     struct timezone *tz)
 {
     struct timeb t;
+    (void)tz;
 
     ftime(&t);
     tp->tv_sec = t.time;
-    tp->tv_usec = t. millitm * 1000;
+    tp->tv_usec = t.millitm * 1000;
     return 0;
 }
 
index 1a44dfa..6807414 100644 (file)
@@ -36,7 +36,7 @@ mkstemp(
 {
     static const char alphanumerics[] =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-    register char *a, *b;
+    char *a, *b;
     int fd, count, alphanumericsLen = strlen(alphanumerics); /* == 62 */
 
     a = template + strlen(template);
index 22e8a3a..07ef572 100644 (file)
@@ -20,9 +20,9 @@ DIR *
 opendir(
     char *name)
 {
-    register DIR *dirp;
-    register int fd;
-    char *myname;
+    DIR *dirp;
+    int fd;
+    const char *myname;
 
     myname = ((*name == '\0') ? "." : name);
     if ((fd = open(myname, 0, 0)) == -1) {
@@ -65,9 +65,9 @@ struct olddirect {
 
 struct dirent *
 readdir(
-    register DIR *dirp)
+    DIR *dirp)
 {
-    register struct olddirect *dp;
+    struct olddirect *dp;
     static struct dirent dir;
 
     for (;;) {
@@ -101,10 +101,10 @@ readdir(
 
 void
 closedir(
-    register DIR *dirp)
+    DIR *dirp)
 {
     close(dirp->dd_fd);
     dirp->dd_fd = -1;
     dirp->dd_loc = 0;
-    ckfree((char *) dirp);
+    ckfree((char *)dirp);
 }
index e3b9b8d..35386d0 100644 (file)
 
 char *
 strstr(
-    register char *string,     /* String to search. */
-    char *substring)           /* Substring to try to find in string. */
+    const char *string,                /* String to search. */
+    const char *substring)             /* Substring to try to find in string. */
 {
-    register char *a, *b;
+    const char *a, *b;
 
     /*
      * First scan quickly through the two strings looking for a
@@ -49,7 +49,7 @@ strstr(
 
     b = substring;
     if (*b == 0) {
-       return string;
+       return (char *)string;
     }
     for ( ; *string != 0; string += 1) {
        if (*string != *b) {
@@ -58,7 +58,7 @@ strstr(
        a = string;
        while (1) {
            if (*b == 0) {
-               return string;
+               return (char *)string;
            }
            if (*a++ != *b++) {
                break;
index b7f6919..a9866f4 100644 (file)
@@ -45,7 +45,7 @@ strtol(
                                 * hex, "0" means octal, anything else means
                                 * decimal. */
 {
-    register const char *p;
+    const char *p;
     long result;
 
     /*
@@ -53,7 +53,7 @@ strtol(
      */
 
     p = string;
-    while (TclIsSpaceProc(*p)) {
+    while (isspace(UCHAR(*p))) {
        p += 1;
     }
 
index e37eb05..af63036 100644 (file)
@@ -62,9 +62,9 @@ strtoul(
                                 * hex, "0" means octal, anything else means
                                 * decimal. */
 {
-    register const char *p;
-    register unsigned long int result = 0;
-    register unsigned digit;
+    const char *p;
+    unsigned long int result = 0;
+    unsigned digit;
     int anyDigits = 0;
     int negative=0;
     int overflow=0;
@@ -74,7 +74,7 @@ strtoul(
      */
 
     p = string;
-    while (TclIsSpaceProc(*p)) {
+    while (isspace(UCHAR(*p))) {
        p += 1;
     }
     if (*p == '-') {
index e03275a..6f43934 100644 (file)
@@ -70,7 +70,7 @@ waitpid(
     int options)               /* OR'ed combination of WNOHANG and
                                 * WUNTRACED. */
 {
-    register WaitInfo *waitPtr, *prevPtr;
+    WaitInfo *waitPtr, *prevPtr;
     pid_t result;
     WAIT_STATUS_TYPE status;
 
index ea8ba06..4da804a 100644 (file)
@@ -37,6 +37,7 @@ static int decrypt_byte(unsigned long* pkeys, const z_crc_t* pcrc_32_tab)
     unsigned temp;  /* POTENTIAL BUG:  temp*(temp^1) may overflow in an
                      * unpredictable manner on 16-bit systems; not a problem
                      * with any known compiler so far, though */
+    (void)pcrc_32_tab;
 
     temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
     return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
diff --git a/compat/zlib/contrib/minizip/tinydir.h b/compat/zlib/contrib/minizip/tinydir.h
new file mode 100755 (executable)
index 0000000..eb34399
--- /dev/null
@@ -0,0 +1,816 @@
+/*
+Copyright (c) 2013-2017, tinydir authors:
+- Cong Xu
+- Lautis Sun
+- Baudouin Feildel
+- Andargor <andargor@yahoo.com>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+   list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+#ifndef TINYDIR_H
+#define TINYDIR_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if ((defined _UNICODE) && !(defined UNICODE))
+#define UNICODE
+#endif
+
+#if ((defined UNICODE) && !(defined _UNICODE))
+#define _UNICODE
+#endif
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef _MSC_VER
+# define WIN32_LEAN_AND_MEAN
+# include <windows.h>
+# include <tchar.h>
+# pragma warning(push)
+# pragma warning (disable : 4996)
+#else
+# include <dirent.h>
+# include <libgen.h>
+# include <sys/stat.h>
+# include <stddef.h>
+#endif
+#ifdef __MINGW32__
+# include <tchar.h>
+#endif
+
+
+/* types */
+
+/* Windows UNICODE wide character support */
+#if defined _MSC_VER || defined __MINGW32__
+# define _tinydir_char_t TCHAR
+# define TINYDIR_STRING(s) _TEXT(s)
+# define _tinydir_strlen _tcslen
+# define _tinydir_strcpy _tcscpy
+# define _tinydir_strcat _tcscat
+# define _tinydir_strcmp _tcscmp
+# define _tinydir_strrchr _tcsrchr
+# define _tinydir_strncmp _tcsncmp
+#else
+# define _tinydir_char_t char
+# define TINYDIR_STRING(s) s
+# define _tinydir_strlen strlen
+# define _tinydir_strcpy strcpy
+# define _tinydir_strcat strcat
+# define _tinydir_strcmp strcmp
+# define _tinydir_strrchr strrchr
+# define _tinydir_strncmp strncmp
+#endif
+
+#if (defined _MSC_VER || defined __MINGW32__)
+# include <windows.h>
+# define _TINYDIR_PATH_MAX MAX_PATH
+#elif defined  __linux__
+# include <limits.h>
+# define _TINYDIR_PATH_MAX PATH_MAX
+#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+# include <sys/param.h>
+# if defined(BSD)
+#  include <limits.h>
+#  define _TINYDIR_PATH_MAX PATH_MAX
+# endif
+#endif
+
+#ifndef _TINYDIR_PATH_MAX
+#define _TINYDIR_PATH_MAX 4096
+#endif
+
+#ifdef _MSC_VER
+/* extra chars for the "\\*" mask */
+# define _TINYDIR_PATH_EXTRA 2
+#else
+# define _TINYDIR_PATH_EXTRA 0
+#endif
+
+#define _TINYDIR_FILENAME_MAX 256
+
+#if (defined _MSC_VER || defined __MINGW32__)
+#define _TINYDIR_DRIVE_MAX 3
+#endif
+
+#ifdef _MSC_VER
+# define _TINYDIR_FUNC static __inline
+#elif !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L
+# define _TINYDIR_FUNC static __inline__
+#else
+# define _TINYDIR_FUNC static inline
+#endif
+
+/* readdir_r usage; define TINYDIR_USE_READDIR_R to use it (if supported) */
+#ifdef TINYDIR_USE_READDIR_R
+
+/* readdir_r is a POSIX-only function, and may not be available under various
+ * environments/settings, e.g. MinGW. Use readdir fallback */
+#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE ||\
+       _POSIX_SOURCE
+# define _TINYDIR_HAS_READDIR_R
+#endif
+#if _POSIX_C_SOURCE >= 200112L
+# define _TINYDIR_HAS_FPATHCONF
+# include <unistd.h>
+#endif
+#if _BSD_SOURCE || _SVID_SOURCE || \
+       (_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)
+# define _TINYDIR_HAS_DIRFD
+# include <sys/types.h>
+#endif
+#if defined _TINYDIR_HAS_FPATHCONF && defined _TINYDIR_HAS_DIRFD &&\
+       defined _PC_NAME_MAX
+# define _TINYDIR_USE_FPATHCONF
+#endif
+#if defined __MINGW32__ || !defined _TINYDIR_HAS_READDIR_R ||\
+       !(defined _TINYDIR_USE_FPATHCONF || defined NAME_MAX)
+# define _TINYDIR_USE_READDIR
+#endif
+
+/* Use readdir by default */
+#else
+# define _TINYDIR_USE_READDIR
+#endif
+
+/* MINGW32 has two versions of dirent, ASCII and UNICODE*/
+#ifndef _MSC_VER
+#if (defined __MINGW32__) && (defined _UNICODE)
+#define _TINYDIR_DIR _WDIR
+#define _tinydir_dirent _wdirent
+#define _tinydir_opendir _wopendir
+#define _tinydir_readdir _wreaddir
+#define _tinydir_closedir _wclosedir
+#else
+#define _TINYDIR_DIR DIR
+#define _tinydir_dirent dirent
+#define _tinydir_opendir opendir
+#define _tinydir_readdir readdir
+#define _tinydir_closedir closedir
+#endif
+#endif
+
+/* Allow user to use a custom allocator by defining _TINYDIR_MALLOC and _TINYDIR_FREE. */
+#if    defined(_TINYDIR_MALLOC) &&  defined(_TINYDIR_FREE)
+#elif !defined(_TINYDIR_MALLOC) && !defined(_TINYDIR_FREE)
+#else
+#error "Either define both alloc and free or none of them!"
+#endif
+
+#if !defined(_TINYDIR_MALLOC)
+       #define _TINYDIR_MALLOC(_size) malloc(_size)
+       #define _TINYDIR_FREE(_ptr)    free(_ptr)
+#endif /* !defined(_TINYDIR_MALLOC) */
+
+typedef struct tinydir_file
+{
+       _tinydir_char_t path[_TINYDIR_PATH_MAX];
+       _tinydir_char_t name[_TINYDIR_FILENAME_MAX];
+       _tinydir_char_t *extension;
+       int is_dir;
+       int is_reg;
+
+#ifndef _MSC_VER
+#ifdef __MINGW32__
+       struct _stat _s;
+#else
+       struct stat _s;
+#endif
+#endif
+} tinydir_file;
+
+typedef struct tinydir_dir
+{
+       _tinydir_char_t path[_TINYDIR_PATH_MAX];
+       int has_next;
+       size_t n_files;
+
+       tinydir_file *_files;
+#ifdef _MSC_VER
+       HANDLE _h;
+       WIN32_FIND_DATA _f;
+#else
+       _TINYDIR_DIR *_d;
+       struct _tinydir_dirent *_e;
+#ifndef _TINYDIR_USE_READDIR
+       struct _tinydir_dirent *_ep;
+#endif
+#endif
+} tinydir_dir;
+
+
+/* declarations */
+
+_TINYDIR_FUNC
+int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path);
+_TINYDIR_FUNC
+int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path);
+_TINYDIR_FUNC
+void tinydir_close(tinydir_dir *dir);
+
+_TINYDIR_FUNC
+int tinydir_next(tinydir_dir *dir);
+_TINYDIR_FUNC
+int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file);
+_TINYDIR_FUNC
+int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i);
+_TINYDIR_FUNC
+int tinydir_open_subdir_n(tinydir_dir *dir, size_t i);
+
+_TINYDIR_FUNC
+int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path);
+_TINYDIR_FUNC
+void _tinydir_get_ext(tinydir_file *file);
+_TINYDIR_FUNC
+int _tinydir_file_cmp(const void *a, const void *b);
+#ifndef _MSC_VER
+#ifndef _TINYDIR_USE_READDIR
+_TINYDIR_FUNC
+size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp);
+#endif
+#endif
+
+
+/* definitions*/
+
+_TINYDIR_FUNC
+int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path)
+{
+#ifndef _MSC_VER
+#ifndef _TINYDIR_USE_READDIR
+       int error;
+       int size;       /* using int size */
+#endif
+#else
+       _tinydir_char_t path_buf[_TINYDIR_PATH_MAX];
+#endif
+       _tinydir_char_t *pathp;
+
+       if (dir == NULL || path == NULL || _tinydir_strlen(path) == 0)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX)
+       {
+               errno = ENAMETOOLONG;
+               return -1;
+       }
+
+       /* initialise dir */
+       dir->_files = NULL;
+#ifdef _MSC_VER
+       dir->_h = INVALID_HANDLE_VALUE;
+#else
+       dir->_d = NULL;
+#ifndef _TINYDIR_USE_READDIR
+       dir->_ep = NULL;
+#endif
+#endif
+       tinydir_close(dir);
+
+       _tinydir_strcpy(dir->path, path);
+       /* Remove trailing slashes */
+       pathp = &dir->path[_tinydir_strlen(dir->path) - 1];
+       while (pathp != dir->path && (*pathp == TINYDIR_STRING('\\') || *pathp == TINYDIR_STRING('/')))
+       {
+               *pathp = TINYDIR_STRING('\0');
+               pathp++;
+       }
+#ifdef _MSC_VER
+       _tinydir_strcpy(path_buf, dir->path);
+       _tinydir_strcat(path_buf, TINYDIR_STRING("\\*"));
+#if (defined WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)
+       dir->_h = FindFirstFileEx(path_buf, FindExInfoStandard, &dir->_f, FindExSearchNameMatch, NULL, 0);
+#else
+       dir->_h = FindFirstFile(path_buf, &dir->_f);
+#endif
+       if (dir->_h == INVALID_HANDLE_VALUE)
+       {
+               errno = ENOENT;
+#else
+       dir->_d = _tinydir_opendir(path);
+       if (dir->_d == NULL)
+       {
+#endif
+               goto bail;
+       }
+
+       /* read first file */
+       dir->has_next = 1;
+#ifndef _MSC_VER
+#ifdef _TINYDIR_USE_READDIR
+       dir->_e = _tinydir_readdir(dir->_d);
+#else
+       /* allocate dirent buffer for readdir_r */
+       size = _tinydir_dirent_buf_size(dir->_d); /* conversion to int */
+       if (size == -1) return -1;
+       dir->_ep = (struct _tinydir_dirent*)_TINYDIR_MALLOC(size);
+       if (dir->_ep == NULL) return -1;
+
+       error = readdir_r(dir->_d, dir->_ep, &dir->_e);
+       if (error != 0) return -1;
+#endif
+       if (dir->_e == NULL)
+       {
+               dir->has_next = 0;
+       }
+#endif
+
+       return 0;
+
+bail:
+       tinydir_close(dir);
+       return -1;
+}
+
+_TINYDIR_FUNC
+int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path)
+{
+       /* Count the number of files first, to pre-allocate the files array */
+       size_t n_files = 0;
+       if (tinydir_open(dir, path) == -1)
+       {
+               return -1;
+       }
+       while (dir->has_next)
+       {
+               n_files++;
+               if (tinydir_next(dir) == -1)
+               {
+                       goto bail;
+               }
+       }
+       tinydir_close(dir);
+
+       if (tinydir_open(dir, path) == -1)
+       {
+               return -1;
+       }
+
+       dir->n_files = 0;
+       dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files);
+       if (dir->_files == NULL)
+       {
+               goto bail;
+       }
+       while (dir->has_next)
+       {
+               tinydir_file *p_file;
+               dir->n_files++;
+
+               p_file = &dir->_files[dir->n_files - 1];
+               if (tinydir_readfile(dir, p_file) == -1)
+               {
+                       goto bail;
+               }
+
+               if (tinydir_next(dir) == -1)
+               {
+                       goto bail;
+               }
+
+               /* Just in case the number of files has changed between the first and
+               second reads, terminate without writing into unallocated memory */
+               if (dir->n_files == n_files)
+               {
+                       break;
+               }
+       }
+
+       qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp);
+
+       return 0;
+
+bail:
+       tinydir_close(dir);
+       return -1;
+}
+
+_TINYDIR_FUNC
+void tinydir_close(tinydir_dir *dir)
+{
+       if (dir == NULL)
+       {
+               return;
+       }
+
+       memset(dir->path, 0, sizeof(dir->path));
+       dir->has_next = 0;
+       dir->n_files = 0;
+       _TINYDIR_FREE(dir->_files);
+       dir->_files = NULL;
+#ifdef _MSC_VER
+       if (dir->_h != INVALID_HANDLE_VALUE)
+       {
+               FindClose(dir->_h);
+       }
+       dir->_h = INVALID_HANDLE_VALUE;
+#else
+       if (dir->_d)
+       {
+               _tinydir_closedir(dir->_d);
+       }
+       dir->_d = NULL;
+       dir->_e = NULL;
+#ifndef _TINYDIR_USE_READDIR
+       _TINYDIR_FREE(dir->_ep);
+       dir->_ep = NULL;
+#endif
+#endif
+}
+
+_TINYDIR_FUNC
+int tinydir_next(tinydir_dir *dir)
+{
+       if (dir == NULL)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       if (!dir->has_next)
+       {
+               errno = ENOENT;
+               return -1;
+       }
+
+#ifdef _MSC_VER
+       if (FindNextFile(dir->_h, &dir->_f) == 0)
+#else
+#ifdef _TINYDIR_USE_READDIR
+       dir->_e = _tinydir_readdir(dir->_d);
+#else
+       if (dir->_ep == NULL)
+       {
+               return -1;
+       }
+       if (readdir_r(dir->_d, dir->_ep, &dir->_e) != 0)
+       {
+               return -1;
+       }
+#endif
+       if (dir->_e == NULL)
+#endif
+       {
+               dir->has_next = 0;
+#ifdef _MSC_VER
+               if (GetLastError() != ERROR_SUCCESS &&
+                       GetLastError() != ERROR_NO_MORE_FILES)
+               {
+                       tinydir_close(dir);
+                       errno = EIO;
+                       return -1;
+               }
+#endif
+       }
+
+       return 0;
+}
+
+_TINYDIR_FUNC
+int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file)
+{
+       if (dir == NULL || file == NULL)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+#ifdef _MSC_VER
+       if (dir->_h == INVALID_HANDLE_VALUE)
+#else
+       if (dir->_e == NULL)
+#endif
+       {
+               errno = ENOENT;
+               return -1;
+       }
+       if (_tinydir_strlen(dir->path) +
+               _tinydir_strlen(
+#ifdef _MSC_VER
+                       dir->_f.cFileName
+#else
+                       dir->_e->d_name
+#endif
+               ) + 1 + _TINYDIR_PATH_EXTRA >=
+               _TINYDIR_PATH_MAX)
+       {
+               /* the path for the file will be too long */
+               errno = ENAMETOOLONG;
+               return -1;
+       }
+       if (_tinydir_strlen(
+#ifdef _MSC_VER
+                       dir->_f.cFileName
+#else
+                       dir->_e->d_name
+#endif
+               ) >= _TINYDIR_FILENAME_MAX)
+       {
+               errno = ENAMETOOLONG;
+               return -1;
+       }
+
+       _tinydir_strcpy(file->path, dir->path);
+       _tinydir_strcat(file->path, TINYDIR_STRING("/"));
+       _tinydir_strcpy(file->name,
+#ifdef _MSC_VER
+               dir->_f.cFileName
+#else
+               dir->_e->d_name
+#endif
+       );
+       _tinydir_strcat(file->path, file->name);
+#ifndef _MSC_VER
+#ifdef __MINGW32__
+       if (_tstat(
+#else
+       if (stat(
+#endif
+               file->path, &file->_s) == -1)
+       {
+               return -1;
+       }
+#endif
+       _tinydir_get_ext(file);
+
+       file->is_dir =
+#ifdef _MSC_VER
+               !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
+#else
+               S_ISDIR(file->_s.st_mode);
+#endif
+       file->is_reg =
+#ifdef _MSC_VER
+               !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) ||
+               (
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) &&
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) &&
+#ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) &&
+#endif
+#ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) &&
+#endif
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) &&
+                       !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY));
+#else
+               S_ISREG(file->_s.st_mode);
+#endif
+
+       return 0;
+}
+
+_TINYDIR_FUNC
+int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i)
+{
+       if (dir == NULL || file == NULL)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       if (i >= dir->n_files)
+       {
+               errno = ENOENT;
+               return -1;
+       }
+
+       memcpy(file, &dir->_files[i], sizeof(tinydir_file));
+       _tinydir_get_ext(file);
+
+       return 0;
+}
+
+_TINYDIR_FUNC
+int tinydir_open_subdir_n(tinydir_dir *dir, size_t i)
+{
+       _tinydir_char_t path[_TINYDIR_PATH_MAX];
+       if (dir == NULL)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       if (i >= dir->n_files || !dir->_files[i].is_dir)
+       {
+               errno = ENOENT;
+               return -1;
+       }
+
+       _tinydir_strcpy(path, dir->_files[i].path);
+       tinydir_close(dir);
+       if (tinydir_open_sorted(dir, path) == -1)
+       {
+               return -1;
+       }
+
+       return 0;
+}
+
+/* Open a single file given its path */
+_TINYDIR_FUNC
+int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path)
+{
+       tinydir_dir dir;
+       int result = 0;
+       int found = 0;
+       _tinydir_char_t dir_name_buf[_TINYDIR_PATH_MAX];
+       _tinydir_char_t file_name_buf[_TINYDIR_FILENAME_MAX];
+       _tinydir_char_t *dir_name;
+       _tinydir_char_t *base_name;
+#if (defined _MSC_VER || defined __MINGW32__)
+       _tinydir_char_t drive_buf[_TINYDIR_PATH_MAX];
+       _tinydir_char_t ext_buf[_TINYDIR_FILENAME_MAX];
+#endif
+
+       if (file == NULL || path == NULL || _tinydir_strlen(path) == 0)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX)
+       {
+               errno = ENAMETOOLONG;
+               return -1;
+       }
+
+       /* Get the parent path */
+#if (defined _MSC_VER || defined __MINGW32__)
+#if ((defined _MSC_VER) && (_MSC_VER >= 1400))
+               _tsplitpath_s(
+                       path,
+                       drive_buf, _TINYDIR_DRIVE_MAX,
+                       dir_name_buf, _TINYDIR_FILENAME_MAX,
+                       file_name_buf, _TINYDIR_FILENAME_MAX,
+                       ext_buf, _TINYDIR_FILENAME_MAX);
+#else
+               _tsplitpath(
+                       path,
+                       drive_buf,
+                       dir_name_buf,
+                       file_name_buf,
+                       ext_buf);
+#endif
+
+/* _splitpath_s not work fine with only filename and widechar support */
+#ifdef _UNICODE
+               if (drive_buf[0] == L'\xFEFE')
+                       drive_buf[0] = '\0';
+               if (dir_name_buf[0] == L'\xFEFE')
+                       dir_name_buf[0] = '\0';
+#endif
+
+       if (errno)
+       {
+               errno = EINVAL;
+               return -1;
+       }
+       /* Emulate the behavior of dirname by returning "." for dir name if it's
+       empty */
+       if (drive_buf[0] == '\0' && dir_name_buf[0] == '\0')
+       {
+               _tinydir_strcpy(dir_name_buf, TINYDIR_STRING("."));
+       }
+       /* Concatenate the drive letter and dir name to form full dir name */
+       _tinydir_strcat(drive_buf, dir_name_buf);
+       dir_name = drive_buf;
+       /* Concatenate the file name and extension to form base name */
+       _tinydir_strcat(file_name_buf, ext_buf);
+       base_name = file_name_buf;
+#else
+       _tinydir_strcpy(dir_name_buf, path);
+       dir_name = dirname(dir_name_buf);
+       _tinydir_strcpy(file_name_buf, path);
+       base_name =basename(file_name_buf);
+#endif
+
+       /* Open the parent directory */
+       if (tinydir_open(&dir, dir_name) == -1)
+       {
+               return -1;
+       }
+
+       /* Read through the parent directory and look for the file */
+       while (dir.has_next)
+       {
+               if (tinydir_readfile(&dir, file) == -1)
+               {
+                       result = -1;
+                       goto bail;
+               }
+               if (_tinydir_strcmp(file->name, base_name) == 0)
+               {
+                       /* File found */
+                       found = 1;
+                       break;
+               }
+               tinydir_next(&dir);
+       }
+       if (!found)
+       {
+               result = -1;
+               errno = ENOENT;
+       }
+
+bail:
+       tinydir_close(&dir);
+       return result;
+}
+
+_TINYDIR_FUNC
+void _tinydir_get_ext(tinydir_file *file)
+{
+       _tinydir_char_t *period = _tinydir_strrchr(file->name, TINYDIR_STRING('.'));
+       if (period == NULL)
+       {
+               file->extension = &(file->name[_tinydir_strlen(file->name)]);
+       }
+       else
+       {
+               file->extension = period + 1;
+       }
+}
+
+_TINYDIR_FUNC
+int _tinydir_file_cmp(const void *a, const void *b)
+{
+       const tinydir_file *fa = (const tinydir_file *)a;
+       const tinydir_file *fb = (const tinydir_file *)b;
+       if (fa->is_dir != fb->is_dir)
+       {
+               return -(fa->is_dir - fb->is_dir);
+       }
+       return _tinydir_strncmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX);
+}
+
+#ifndef _MSC_VER
+#ifndef _TINYDIR_USE_READDIR
+/*
+The following authored by Ben Hutchings <ben@decadent.org.uk>
+from https://womble.decadent.org.uk/readdir_r-advisory.html
+*/
+/* Calculate the required buffer size (in bytes) for directory      *
+* entries read from the given directory handle.  Return -1 if this  *
+* this cannot be done.                                              *
+*                                                                   *
+* This code does not trust values of NAME_MAX that are less than    *
+* 255, since some systems (including at least HP-UX) incorrectly    *
+* define it to be a smaller value.                                  */
+_TINYDIR_FUNC
+size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp)
+{
+       long name_max;
+       size_t name_end;
+       /* parameter may be unused */
+       (void)dirp;
+
+#if defined _TINYDIR_USE_FPATHCONF
+       name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
+       if (name_max == -1)
+#if defined(NAME_MAX)
+               name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
+#else
+               return (size_t)(-1);
+#endif
+#elif defined(NAME_MAX)
+       name_max = (NAME_MAX > 255) ? NAME_MAX : 255;
+#else
+#error "buffer size for readdir_r cannot be determined"
+#endif
+       name_end = (size_t)offsetof(struct _tinydir_dirent, d_name) + name_max + 1;
+       return (name_end > sizeof(struct _tinydir_dirent) ?
+               name_end : sizeof(struct _tinydir_dirent));
+}
+#endif
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+# if defined (_MSC_VER)
+# pragma warning(pop)
+# endif
+
+#endif
index 6f6ffd5..6953136 100644 (file)
@@ -1,4 +1,4 @@
-\r
+\r
 Microsoft Visual Studio Solution File, Format Version 11.00\r
 # Visual Studio 2010\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
index 9fcbafd..7e340e6 100644 (file)
@@ -1,4 +1,4 @@
-\r
+\r
 Microsoft Visual Studio Solution File, Format Version 12.00\r
 # Visual Studio 2012\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
index dcda229..93b13c1 100644 (file)
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 2013
-VisualStudioVersion = 12.0.40629.0
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"
-EndProject
-Global
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution
-               Debug|Itanium = Debug|Itanium
-               Debug|Win32 = Debug|Win32
-               Debug|x64 = Debug|x64
-               Release|Itanium = Release|Itanium
-               Release|Win32 = Release|Win32
-               Release|x64 = Release|x64
-               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium
-               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32
-               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64
-       EndGlobalSection
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-       EndGlobalSection
-       GlobalSection(SolutionProperties) = preSolution
-               HideSolutionNode = FALSE
-       EndGlobalSection
-EndGlobal
+\r
+Microsoft Visual Studio Solution File, Format Version 12.00\r
+# Visual Studio 2013\r
+VisualStudioVersion = 12.0.40629.0\r
+MinimumVisualStudioVersion = 10.0.40219.1\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Itanium = Debug|Itanium\r
+               Debug|Win32 = Debug|Win32\r
+               Debug|x64 = Debug|x64\r
+               Release|Itanium = Release|Itanium\r
+               Release|Win32 = Release|Win32\r
+               Release|x64 = Release|x64\r
+               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium\r
+               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32\r
+               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
index 6f4a107..0f29237 100644 (file)
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"
-EndProject
-Global
-       GlobalSection(SolutionConfigurationPlatforms) = preSolution
-               Debug|Itanium = Debug|Itanium
-               Debug|Win32 = Debug|Win32
-               Debug|x64 = Debug|x64
-               Release|Itanium = Release|Itanium
-               Release|Win32 = Release|Win32
-               Release|x64 = Release|x64
-               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium
-               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32
-               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64
-       EndGlobalSection
-       GlobalSection(ProjectConfigurationPlatforms) = postSolution
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64
-               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32
-               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64
-       EndGlobalSection
-       GlobalSection(SolutionProperties) = preSolution
-               HideSolutionNode = FALSE
-       EndGlobalSection
-EndGlobal
+\r
+Microsoft Visual Studio Solution File, Format Version 12.00\r
+# Visual Studio 14\r
+VisualStudioVersion = 14.0.25420.1\r
+MinimumVisualStudioVersion = 10.0.40219.1\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcxproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibstat", "zlibstat.vcxproj", "{745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlib", "testzlib.vcxproj", "{AA6666AA-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "testzlibdll", "testzlibdll.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694366A}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "minizip", "minizip.vcxproj", "{48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}"\r
+EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "miniunz", "miniunz.vcxproj", "{C52F9E7B-498A-42BE-8DB4-85A15694382A}"\r
+EndProject\r
+Global\r
+       GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
+               Debug|Itanium = Debug|Itanium\r
+               Debug|Win32 = Debug|Win32\r
+               Debug|x64 = Debug|x64\r
+               Release|Itanium = Release|Itanium\r
+               Release|Win32 = Release|Win32\r
+               Release|x64 = Release|x64\r
+               ReleaseWithoutAsm|Itanium = ReleaseWithoutAsm|Itanium\r
+               ReleaseWithoutAsm|Win32 = ReleaseWithoutAsm|Win32\r
+               ReleaseWithoutAsm|x64 = ReleaseWithoutAsm|x64\r
+       EndGlobalSection\r
+       GlobalSection(ProjectConfigurationPlatforms) = postSolution\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|Win32.Build.0 = Debug|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.ActiveCfg = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Debug|x64.Build.0 = Debug|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.ActiveCfg = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|Win32.Build.0 = Release|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.ActiveCfg = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.Release|x64.Build.0 = Release|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {8FD826F8-3739-44E6-8CC8-997122E53B8D}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|Win32.Build.0 = Debug|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.ActiveCfg = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Debug|x64.Build.0 = Debug|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.ActiveCfg = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|Win32.Build.0 = Release|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.ActiveCfg = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.Release|x64.Build.0 = Release|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {745DEC58-EBB3-47A9-A9B8-4C6627C01BF8}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.Build.0 = ReleaseWithoutAsm|Win32\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = ReleaseWithoutAsm|x64\r
+               {AA6666AA-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.Build.0 = ReleaseWithoutAsm|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694366A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|Win32.Build.0 = Debug|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.ActiveCfg = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Debug|x64.Build.0 = Debug|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|Win32.Build.0 = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.ActiveCfg = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.Release|x64.Build.0 = Release|x64\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {48CDD9DC-E09F-4135-9C0C-4FE50C3C654B}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Itanium.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|Win32.Build.0 = Debug|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.ActiveCfg = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Debug|x64.Build.0 = Debug|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|Win32.Build.0 = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.ActiveCfg = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.Release|x64.Build.0 = Release|x64\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Itanium.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|Win32.ActiveCfg = Release|Win32\r
+               {C52F9E7B-498A-42BE-8DB4-85A15694382A}.ReleaseWithoutAsm|x64.ActiveCfg = Release|x64\r
+       EndGlobalSection\r
+       GlobalSection(SolutionProperties) = preSolution\r
+               HideSolutionNode = FALSE\r
+       EndGlobalSection\r
+EndGlobal\r
index b482967..20568fa 100644 (file)
@@ -1,4 +1,4 @@
-\r
+\r
 Microsoft Visual Studio Solution File, Format Version 10.00\r
 # Visual Studio 2008\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "zlibvc", "zlibvc.vcproj", "{8FD826F8-3739-44E6-8CC8-997122E53B8D}"\r
old mode 100755 (executable)
new mode 100644 (file)
index 766621a..33b8afc 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_CallWhenDeleted 3 7.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 25b372e..bb7532c 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_CommandComplete 3 "" Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 58a0fb6..e853fc3 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_Concat 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
similarity index 69%
rename from doc/CrtSlave.3
rename to doc/CrtAlias.3
index ac681bc..a642d08 100644 (file)
@@ -4,11 +4,11 @@
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 '\"
-.TH Tcl_CreateSlave 3 7.6 Tcl "Tcl Library Procedures"
+.TH Tcl_CreateAlias 3 7.6 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
 .SH NAME
-Tcl_IsSafe, Tcl_MakeSafe, Tcl_CreateSlave, Tcl_GetSlave, Tcl_GetMaster, Tcl_GetInterpPath, Tcl_CreateAlias, Tcl_CreateAliasObj, Tcl_GetAlias, Tcl_GetAliasObj, Tcl_ExposeCommand, Tcl_HideCommand \- manage multiple Tcl interpreters, aliases and hidden commands
+Tcl_IsSafe, Tcl_MakeSafe, Tcl_CreateChild, Tcl_CreateSlave, Tcl_GetChild, Tcl_GetSlave, Tcl_GetParent, Tcl_GetMaster, Tcl_GetInterpPath, Tcl_CreateAlias, Tcl_CreateAliasObj, Tcl_GetAlias, Tcl_GetAliasObj, Tcl_ExposeCommand, Tcl_HideCommand \- manage multiple Tcl interpreters, aliases and hidden commands
 .SH SYNOPSIS
 .nf
 \fB#include <tcl.h>\fR
@@ -19,32 +19,47 @@ int
 int
 \fBTcl_MakeSafe\fR(\fIinterp\fR)
 .sp
+.VS "TIP 581"
 Tcl_Interp *
-\fBTcl_CreateSlave\fR(\fIinterp, slaveName, isSafe\fR)
+\fBTcl_CreateChild\fR(\fIinterp, name, isSafe\fR)
+.VE "TIP 581"
 .sp
 Tcl_Interp *
-\fBTcl_GetSlave\fR(\fIinterp, slaveName\fR)
+\fBTcl_CreateSlave\fR(\fIinterp, name, isSafe\fR)
+.sp
+.VS "TIP 581"
+Tcl_Interp *
+\fBTcl_GetChild\fR(\fIinterp, name\fR)
+.VE "TIP 581"
+.sp
+Tcl_Interp *
+\fBTcl_GetSlave\fR(\fIinterp, name\fR)
+.sp
+.VS "TIP 581"
+Tcl_Interp *
+\fBTcl_GetParent\fR(\fIinterp\fR)
+.VE "TIP 581"
 .sp
 Tcl_Interp *
 \fBTcl_GetMaster\fR(\fIinterp\fR)
 .sp
 int
-\fBTcl_GetInterpPath\fR(\fIaskingInterp, slaveInterp\fR)
+\fBTcl_GetInterpPath\fR(\fIinterp, childInterp\fR)
 .sp
 int
-\fBTcl_CreateAlias\fR(\fIslaveInterp, slaveCmd, targetInterp, targetCmd,
+\fBTcl_CreateAlias\fR(\fIchildInterp, childCmd, targetInterp, targetCmd,
                 argc, argv\fR)
 .sp
 int
-\fBTcl_CreateAliasObj\fR(\fIslaveInterp, slaveCmd, targetInterp, targetCmd,
+\fBTcl_CreateAliasObj\fR(\fIchildInterp, childCmd, targetInterp, targetCmd,
                    objc, objv\fR)
 .sp
 int
-\fBTcl_GetAlias\fR(\fIinterp, slaveCmd, targetInterpPtr, targetCmdPtr,
+\fBTcl_GetAlias\fR(\fIinterp, childCmd, targetInterpPtr, targetCmdPtr,
              argcPtr, argvPtr\fR)
 .sp
 int
-\fBTcl_GetAliasObj\fR(\fIinterp, slaveCmd, targetInterpPtr, targetCmdPtr,
+\fBTcl_GetAliasObj\fR(\fIinterp, childCmd, targetInterpPtr, targetCmdPtr,
                 objcPtr, objvPtr\fR)
 .sp
 int
@@ -56,17 +71,17 @@ int
 .AS "const char *const" **targetInterpPtr out
 .AP Tcl_Interp *interp in
 Interpreter in which to execute the specified command.
-.AP "const char" *slaveName in
-Name of slave interpreter to create or manipulate.
+.AP "const char" *name in
+Name of child interpreter to create or manipulate.
 .AP int isSafe in
 If non-zero, a
 .QW safe
-slave that is suitable for running untrusted code
-is created, otherwise a trusted slave is created.
-.AP Tcl_Interp *slaveInterp in
+child that is suitable for running untrusted code
+is created, otherwise a trusted child is created.
+.AP Tcl_Interp *childInterp in
 Interpreter to use for creating the source command for an alias (see
 below).
-.AP "const char" *slaveCmd in
+.AP "const char" *childCmd in
 Name of source command for alias.
 .AP Tcl_Interp *targetInterp in
 Interpreter that contains the target command for an alias.
@@ -119,19 +134,23 @@ in a hierarchical relationship, and the management of aliases, commands
 that when invoked in one interpreter execute a command in another
 interpreter. The return value for those procedures that return an \fBint\fR
 is either \fBTCL_OK\fR or \fBTCL_ERROR\fR. If \fBTCL_ERROR\fR is returned
-then the \fBresult\fR field of the interpreter contains an error message.
+then the interpreter's result contains an error message.
 .PP
-\fBTcl_CreateSlave\fR creates a new interpreter as a slave of \fIinterp\fR.
-It also creates a slave command named \fIslaveName\fR in \fIinterp\fR which
-allows \fIinterp\fR to manipulate the new slave.
-If \fIisSafe\fR is zero, the command creates a trusted slave in which Tcl
+\fBTcl_CreateSlave\fR creates a new interpreter as a child of \fIinterp\fR.
+It also creates a child command named \fIchildName\fR in \fIinterp\fR which
+allows \fIinterp\fR to manipulate the new child.
+If \fIisSafe\fR is zero, the command creates a trusted child in which Tcl
 code has access to all the Tcl commands.
 If it is \fB1\fR, the command creates a
 .QW safe
-slave in which Tcl code has access only to set of Tcl commands defined as
+child in which Tcl code has access only to set of Tcl commands defined as
 .QW "Safe Tcl" ;
 see the manual entry for the Tcl \fBinterp\fR command for details.
-If the creation of the new slave interpreter failed, \fBNULL\fR is returned.
+If the creation of the new child interpreter failed, \fBNULL\fR is returned.
+.PP
+.VS "TIP 581"
+\fBTcl_CreateChild\fR is a synonym for \fBTcl_CreateSlave\fR.
+.VE "TIP 581"
 .PP
 \fBTcl_IsSafe\fR returns \fB1\fR if \fIinterp\fR is
 .QW safe
@@ -150,31 +169,39 @@ Callers will want to take care with their use of \fBTcl_MakeSafe\fR
 to avoid false claims of safety.  For many situations, \fBTcl_CreateSlave\fR
 may be a better choice, since it creates interpreters in a known-safe state.
 .PP
-\fBTcl_GetSlave\fR returns a pointer to a slave interpreter of
-\fIinterp\fR. The slave interpreter is identified by \fIslaveName\fR.
-If no such slave interpreter exists, \fBNULL\fR is returned.
+\fBTcl_GetSlave\fR returns a pointer to a child interpreter of
+\fIinterp\fR. The child interpreter is identified by \fIchildName\fR.
+If no such child interpreter exists, \fBNULL\fR is returned.
+.PP
+.VS "TIP 581"
+\fBTcl_GetChild\fR is a synonym for \fBTcl_GetSlave\fR.
+.VE "TIP 581"
 .PP
 \fBTcl_GetMaster\fR returns a pointer to the master interpreter of
 \fIinterp\fR. If \fIinterp\fR has no master (it is a
 top-level interpreter) then \fBNULL\fR is returned.
 .PP
-\fBTcl_GetInterpPath\fR sets the \fIresult\fR field in \fIaskingInterp\fR
-to the relative path between \fIaskingInterp\fR and \fIslaveInterp\fR;
-\fIslaveInterp\fR must be a slave of \fIaskingInterp\fR. If the computation
+.VS "TIP 581"
+\fBTcl_GetParent\fR is a synonym for \fBTcl_GetMaster\fR.
+.VE "TIP 581"
+.PP
+\fBTcl_GetInterpPath\fR stores in the result of \fIinterp\fR
+the relative path between \fIinterp\fR and \fIchildInterp\fR;
+\fIchildInterp\fR must be a child of \fIinterp\fR. If the computation
 of the relative path succeeds, \fBTCL_OK\fR is returned, else
-\fBTCL_ERROR\fR is returned and the \fIresult\fR field in
-\fIaskingInterp\fR contains the error message.
+\fBTCL_ERROR\fR is returned and an error message is stored as the
+result of \fIinterp\fR.
 .PP
-\fBTcl_CreateAlias\fR creates a command named \fIslaveCmd\fR in
-\fIslaveInterp\fR that when invoked, will cause the command \fItargetCmd\fR
+\fBTcl_CreateAlias\fR creates a command named \fIchildCmd\fR in
+\fIchildInterp\fR that when invoked, will cause the command \fItargetCmd\fR
 to be invoked in \fItargetInterp\fR. The arguments specified by the strings
 contained in \fIargv\fR are always prepended to any arguments supplied in the
-invocation of \fIslaveCmd\fR and passed to \fItargetCmd\fR.
+invocation of \fIchildCmd\fR and passed to \fItargetCmd\fR.
 This operation returns \fBTCL_OK\fR if it succeeds, or \fBTCL_ERROR\fR if
 it fails; in that case, an error message is left in the value result
-of \fIslaveInterp\fR.
+of \fIchildInterp\fR.
 Note that there are no restrictions on the ancestry relationship (as
-created by \fBTcl_CreateSlave\fR) between \fIslaveInterp\fR and
+created by \fBTcl_CreateSlave\fR) between \fIchildInterp\fR and
 \fItargetInterp\fR. Any two interpreters can be used, without any
 restrictions on how they are related.
 .PP
@@ -198,33 +225,33 @@ the set of hidden commands to the set of exposed commands, putting
 it under the name
 \fIcmdName\fR.
 \fIHiddenCmdName\fR must be the name of an existing hidden
-command, or the operation will return \fBTCL_ERROR\fR and leave an error
-message in the \fIresult\fR field in \fIinterp\fR.
+command, or the operation will return \fBTCL_ERROR\fR and
+leave an error message as the result of \fIinterp\fR.
 If an exposed command named \fIcmdName\fR already exists,
-the operation returns \fBTCL_ERROR\fR and leaves an error message in the
-value result of \fIinterp\fR.
+the operation returns \fBTCL_ERROR\fR and leaves an error message as
+the result of \fIinterp\fR.
 If the operation succeeds, it returns \fBTCL_OK\fR.
-After executing this command, attempts to use \fIcmdName\fR in a call to
-\fBTcl_Eval\fR or with the Tcl \fBeval\fR command will again succeed.
+After executing this command, attempts to use \fIcmdName\fR in any
+script evaluation mechanism will again succeed.
 .PP
 \fBTcl_HideCommand\fR moves the command named \fIcmdName\fR from the set of
 exposed commands to the set of hidden commands, under the name
 \fIhiddenCmdName\fR.
 \fICmdName\fR must be the name of an existing exposed
 command, or the operation will return \fBTCL_ERROR\fR and leave an error
-message in the value result of \fIinterp\fR.
+message as the result of \fIinterp\fR.
 Currently both \fIcmdName\fR and \fIhiddenCmdName\fR must not contain
 namespace qualifiers, or the operation will return \fBTCL_ERROR\fR and
-leave an error message in the value result of \fIinterp\fR.
+leave an error message as the result of \fIinterp\fR.
 The \fICmdName\fR will be looked up in the global namespace, and not
 relative to the current namespace, even if the current namespace is not the
 global one.
 If a hidden command whose name is \fIhiddenCmdName\fR already
-exists, the operation also returns \fBTCL_ERROR\fR and the \fIresult\fR
-field in \fIinterp\fR contains an error message.
+exists, the operation also returns \fBTCL_ERROR\fR and an error
+message is left as the result of \fIinterp\fR.
 If the operation succeeds, it returns \fBTCL_OK\fR.
-After executing this command, attempts to use \fIcmdName\fR in a call to
-\fBTcl_Eval\fR or with the Tcl \fBeval\fR command will fail.
+After executing this command, attempts to use \fIcmdName\fR in
+any script evaluation mechanism will fail.
 .PP
 For a description of the Tcl interface to multiple interpreters, see
 \fIinterp(n)\fR.
@@ -233,4 +260,4 @@ interp
 
 .SH KEYWORDS
 alias, command, exposed commands, hidden commands, interpreter, invoke,
-master, slave
+parent, child
index 6ef94b5..0092cfb 100644 (file)
@@ -259,7 +259,8 @@ outside this range, \fBTcl_SetChannelBufferSize\fR sets the buffer size to
 the generic layer that the events specified by \fImask\fR have
 occurred on the channel.  Channel drivers are responsible for invoking
 this function whenever the channel handlers need to be called for the
-channel.  See \fBWATCHPROC\fR below for more details.
+channel (or other pending tasks like a write flush should be performed).
+See \fBWATCHPROC\fR below for more details.
 .PP
 \fBTcl_BadChannelOption\fR is called from driver specific
 \fIsetOptionProc\fR or \fIgetOptionProc\fR to generate a complete
@@ -648,8 +649,8 @@ It should call \fBTcl_BadChannelOption\fR which itself returns
 unrecognized.
 If \fInewValue\fR specifies a value for the option that
 is not supported or if a system call error occurs,
-the function should leave an error message in the
-\fIresult\fR field of \fIinterp\fR if \fIinterp\fR is not NULL. The
+the function should leave an error message in the result
+of \fIinterp\fR if \fIinterp\fR is not NULL. The
 function should also call \fBTcl_SetErrno\fR to store an appropriate POSIX
 error code.
 .PP
index c1bc1fa..f1b8df7 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_CreateFileHandler 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 679795e..1d49158 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_CreateInterp 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index f3957c7..c229a23 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_CreateTimerHandler 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index d5353ac..b1e6483 100644 (file)
@@ -1,7 +1,7 @@
 '\"
 '\" Copyright (c) 1989-1993 The Regents of the University of California.
 '\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
-'\" Copyright (c) 2002 by Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
+'\" Copyright (c) 2002 Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 39a51d3..26075c3 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_DetachPids 3 "" Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 90ca9e3..2c111c4 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_DictObj 3 8.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 3e28b4d..cfdbff9 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_DoWhenIdle 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 43333da..226209a 100644 (file)
@@ -1,6 +1,6 @@
 '\"
-'\" Copyright (c) 1992-1999 Karl Lehenbauer and Mark Diekhans.
-'\" Copyright (c) 2000 by Scriptics Corporation.
+'\" Copyright (c) 1992-1999 Karl Lehenbauer & Mark Diekhans.
+'\" Copyright (c) 2000 Scriptics Corporation.
 '\" All rights reserved.
 '\"
 .TH "Tcl_DumpActiveMemory" 3 8.1 Tcl "Tcl Library Procedures"
index 85880b4..7a5e396 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_PutEnv 3 "7.5" Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 35edb5f..837e0a8 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_ExprLongObj 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 28ee8f0..4a57743 100644 (file)
@@ -1350,11 +1350,11 @@ is considered to be owned by the filesystem (not by Tcl's core), but
 should be given a reference count for Tcl. Tcl will use the contents of the
 list and then decrement that reference count. This allows filesystems to
 choose whether they actually want to retain a
-.QW "master list"
+.QW "global list"
 of volumes
 or not (if not, they generate the list on the fly and pass it to Tcl
 with a reference count of 1 and then forget about the list, if yes, then
-they simply increment the reference count of their master list and pass it
+they simply increment the reference count of their global list and pass it
 to Tcl which will copy the contents and then decrement the count back
 to where it was).
 .PP
index b01315c..1fd57db 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_FindExecutable 3 8.1 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 58abcde..f4f37a1 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_GetCwd 3 8.1 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 73432d3..8e43f8e 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1998-2000 by Scriptics Corporation.
+'\" Copyright (c) 1998-2000 Scriptics Corporation.
 '\" All rights reserved.
 '\"
 .TH Tcl_GetHostName 3 8.3 Tcl "Tcl Library Procedures"
index fc6f40b..17a31d4 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_GetIndexFromObj 3 8.1 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 86d1b94..a450b02 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_GetOpenFile 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index be0e79f..3472fee 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1996 by Sun Microsystems, Inc.
+'\" Copyright (c) 1996 Sun Microsystems, Inc.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 6b885ee..9dc4056 100644 (file)
@@ -1,9 +1,9 @@
 '\"
-'\" Copyright (c) 2001 by Kevin B. Kenny <kennykb@acm.org>.
+'\" Copyright (c) 2001 Kevin B. Kenny <kennykb@acm.org>.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_GetTime 3 8.4 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 33c27a3..d9fc2e1 100644 (file)
@@ -1,7 +1,7 @@
 '\"
-'\" Copyright (c) 1998-2000 by Scriptics Corporation.
+'\" Copyright (c) 1998-2000 Scriptics Corporation.
 '\" All rights reserved.
-'\" 
+'\"
 .TH Tcl_Init 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 73c3437..fbb3f56 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_InitStubs 3 8.1 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 20a2e02..3d202fc 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_LimitCheck 3 8.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
@@ -116,7 +116,7 @@ execution of the callbacks is unspecified) execution in the limited
 interpreter is stopped by raising an error and setting a flag that
 prevents the \fBcatch\fR command in that interpreter from trapping
 that error.  It is up to the context that started execution in that
-interpreter (typically a master interpreter) to handle the error.
+interpreter (typically the main interpreter) to handle the error.
 .SH "LIMIT CHECKING API"
 .PP
 To check the resource limits for an interpreter, call
index dc1ba53..ab836d8 100644 (file)
@@ -138,7 +138,9 @@ create a new value or modify an existing value to hold
 the \fIobjc\fR elements of the array referenced by \fIobjv\fR
 where each element is a pointer to a Tcl value.
 If \fIobjc\fR is less than or equal to zero,
-they return an empty value.
+they return an empty value. If \fIobjv\fR is NULL, the resulting list
+contains 0 elements, with reserved space in an internal representation
+for \fIobjc\fR more elements (to avoid its reallocation later).
 The new value's string representation is left invalid.
 The two procedures increment the reference counts
 of the elements in \fIobjc\fR since the list value now refers to them.
index 0ffaf57..1d0d738 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Load 3 8.6 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 6078a53..20efe2f 100644 (file)
--- a/doc/NRE.3
+++ b/doc/NRE.3
@@ -1,6 +1,6 @@
 .\"
-.\" Copyright (c) 2008 by Kevin B. Kenny.
-.\" Copyright (c) 2018 by Nathan Coulter. 
+.\" Copyright (c) 2008 Kevin B. Kenny.
+.\" Copyright (c) 2018 Nathan Coulter.
 .\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -232,5 +232,5 @@ Tcl_CreateCommand(3), Tcl_CreateObjCommand(3), Tcl_EvalObjEx(3), Tcl_GetCommandF
 .SH KEYWORDS
 stackless, nonrecursive, execute, command, global, value, result, script
 .SH COPYRIGHT
-Copyright (c) 2008 by Kevin B. Kenny.
-Copyright (c) 2018 by Nathan Coulter.
+Copyright \(co 2008 Kevin B. Kenny.
+Copyright \(co 2018 Nathan Coulter.
index be89597..a037442 100644 (file)
@@ -3,10 +3,10 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 '\" Note that some of these functions do not seem to belong, but they
 '\" were all introduced with the same TIP (#139)
-'\" 
+'\"
 .TH Tcl_Namespace 3 8.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index bf414ac..67f5174 100644 (file)
@@ -85,14 +85,12 @@ unless \fIinterp\fR is NULL.
 Otherwise, it returns \fBTCL_OK\fR.
 Passing a NULL \fIinterp\fR allows this procedure to be used
 as a test whether the conversion can be done (and in fact was done).
-.VS 8.5
 .PP
 In many cases, the \fItypePtr->setFromAnyProc\fR routine will
 set \fIobjPtr->typePtr\fR to the argument value \fItypePtr\fR,
 but that is no longer guaranteed.  The \fIsetFromAnyProc\fR is
 free to set the internal representation for \fIobjPtr\fR to make
 use of another related Tcl_ObjType, if it sees fit.
-.VE 8.5
 .SH "THE TCL_OBJTYPE STRUCTURE"
 .PP
 Extension writers can define new value types by defining four
index 9fe2615..4a7dc1e 100644 (file)
@@ -130,7 +130,7 @@ for the new channel, \fIhostName\fR points to a string containing
 the name of the client host making the connection, and \fIport\fR
 will contain the client's port number.
 The new channel
-is opened for both input and output. 
+is opened for both input and output.
 If \fIproc\fR raises an error, the connection is closed automatically.
 \fIProc\fR has no return value, but if it wishes to reject the
 connection it can close \fIchannel\fR.
index af86665..5f4763f 100644 (file)
@@ -50,7 +50,7 @@ In a freshly loaded Tcl library, \fBTcl_Panic\fR prints the formatted
 error message to the standard error file of the process, and then
 calls \fBabort\fR to terminate the process.  \fBTcl_Panic\fR does not
 return. On Windows, when a debugger is running, the formatted error
-message is sent to the debugger in stead. If the windows executable
+message is sent to the debugger instead. If the windows executable
 does not have a stderr channel (e.g. \fBwish.exe\fR), then a
 system dialog box is used to display the panic message.
 .PP
index 667d697..40a0818 100644 (file)
@@ -302,7 +302,7 @@ The \fInumComponents\fR field is always 0.
 .TP
 \fBTCL_TOKEN_BS\fR
 .
-The token describes a backslash sequence such as \fB\en\fR or \fB\e0xa3\fR.
+The token describes a backslash sequence such as \fB\en\fR or \fB\e0xA3\fR.
 The \fInumComponents\fR field is always 0.
 .TP
 \fBTCL_TOKEN_COMMAND\fR
index 970bded..c8f34a2 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_Preserve 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 730794f..896b6eb 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_PrintDouble 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 387cc44..1b0f292 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_RecordAndEvalObj 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index e1625ff..36ef6b9 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_RecordAndEval 3 7.4 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 6dd6cb6..918941e 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1997 by Sun Microsystems, Inc.
+'\" Copyright (c) 1997 Sun Microsystems, Inc.
 '\" Contributions from Don Porter, NIST, 2004. (not subject to US copyright)
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
index 21648b1..c202e2e 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SetErrno 3 8.3 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 904d4ab..ec55794 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SetRecursionLimit 3 7.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index e5b81d7..e50650e 100644 (file)
@@ -5,7 +5,7 @@
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 '\"
-.TH Tcl_SetResult 3 8.0 Tcl "Tcl Library Procedures"
+.TH Tcl_SetResult 3 8.6 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
 .SH NAME
@@ -31,7 +31,7 @@ const char *
 \fBTcl_ResetResult\fR(\fIinterp\fR)
 .sp
 .VS 8.6
-\fBTcl_TransferResult\fR(\fIsourceInterp, result, targetInterp\fR)
+\fBTcl_TransferResult\fR(\fIsourceInterp, code, targetInterp\fR)
 .VE 8.6
 .sp
 \fBTcl_AppendElement\fR(\fIinterp, element\fR)
@@ -58,16 +58,15 @@ An argument list which must have been initialized using
 \fBva_start\fR, and cleared using \fBva_end\fR.
 .AP Tcl_Interp *sourceInterp in
 .VS 8.6
-Interpreter that the result and error information should be copied from.
+Interpreter that the result and return options should be transferred from.
 .VE 8.6
 .AP Tcl_Interp *targetInterp in
 .VS 8.6
-Interpreter that the result and error information should be copied to.
+Interpreter that the result and return options should be transferred to.
 .VE 8.6
-.AP int result in
+.AP int code in
 .VS 8.6
-If \fBTCL_OK\fR, only copy the result. If \fBTCL_ERROR\fR, copy the error
-information as well.
+Return code value that controls transfer of return options.
 .VE 8.6
 .BE
 .SH DESCRIPTION
@@ -156,10 +155,14 @@ call; the last argument in the list must be a NULL pointer.
 instead of taking a variable number of arguments it takes an argument list.
 .PP
 .VS 8.6
-\fBTcl_TransferResult\fR moves a result from one interpreter to another,
-optionally (dependent on the \fIresult\fR parameter) including the error
-information dictionary as well. The interpreters must be in the same thread.
-The source interpreter will have its result reset by this operation.
+\fBTcl_TransferResult\fR transfers interpreter state from \fIsourceInterp\fR
+to \fItargetInterp\fR. The two interpreters must have been created in the
+same thread.  If \fIsourceInterp\fR and \fItargetInterp\fR are the same,
+nothing is done. Otherwise, \fBTcl_TransferResult\fR moves the result
+from \fIsourceInterp\fR to \fItargetInterp\fR, and resets the result
+in \fIsourceInterp\fR. It also moves the return options dictionary as
+controlled by the return code value \fIcode\fR in the same manner
+as \fBTcl_GetReturnOptions\fR.
 .VE 8.6
 .SH "DEPRECATED INTERFACES"
 .SS "OLD STRING PROCEDURES"
@@ -250,6 +253,7 @@ typedef void \fBTcl_FreeProc\fR(
 When \fIfreeProc\fR is called, its \fIblockPtr\fR will be set to
 the value of \fIresult\fR passed to \fBTcl_SetResult\fR.
 .SH "SEE ALSO"
-Tcl_AddErrorInfo, Tcl_CreateObjCommand, Tcl_SetErrorCode, Tcl_Interp
+Tcl_AddErrorInfo, Tcl_CreateObjCommand, Tcl_SetErrorCode, Tcl_Interp,
+Tcl_GetReturnOptions
 .SH KEYWORDS
 append, command, element, list, value, result, return value, interpreter
index 70b9d91..0a280f9 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SignalId 3 8.3 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 2d36697..656d72a 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_Sleep 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 0afb66b..bf8c527 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1998-2000 by Scriptics Corporation.
+'\" Copyright (c) 1998-2000 Scriptics Corporation.
 '\" All rights reserved.
 '\"
 .TH Tcl_SourceRCFile 3 8.3 Tcl "Tcl Library Procedures"
index 3439f2e..d19ca14 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SplitList 3 8.0 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 19cee05..c011194 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SplitPath 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 5700ea7..41e2d65 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_StaticPackage 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 651ad7d..d3ecff2 100644 (file)
@@ -1,9 +1,9 @@
 '\"
-'\" Copyright (c) 2001 by ActiveState Corporation
+'\" Copyright (c) 2001 ActiveState Corporation
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH "Standard Channels" 3 7.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index f9c2be3..d664067 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_StringMatch 3 8.5 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index c23706f..7870b21 100644 (file)
@@ -204,7 +204,8 @@ where the caller does not need the length of the unicode string
 representation.
 .PP
 \fBTcl_GetUniChar\fR returns the \fIindex\fR'th character in the
-value's Unicode representation.
+value's Unicode representation. The index is assumed to be in the
+appropriate range.
 .PP
 \fBTcl_GetRange\fR returns a newly created value comprised of the
 characters between \fIfirst\fR and \fIlast\fR (inclusive) in the
index f582c5a..a2b6214 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH Tcl_SubstObj 3 8.4 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index e3a6809..59af6ba 100644 (file)
@@ -1,8 +1,8 @@
-'\" 
-'\" Copyright (c) 1992-1999 Karl Lehenbauer and Mark Diekhans.
-'\" Copyright (c) 2000 by Scriptics Corporation.
+'\"
+'\" Copyright (c) 1992-1999 Karl Lehenbauer & Mark Diekhans.
+'\" Copyright (c) 2000 Scriptics Corporation.
 '\" All rights reserved.
-'\" 
+'\"
 .TH TCL_MEM_DEBUG 3 8.1 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index c6a6417..4a5df89 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH TclZlib 3 8.6 Tcl "Tcl Library Procedures"
 .so man.macros
 .BS
index 3ec33d1..2eae4b8 100644 (file)
@@ -79,7 +79,7 @@ against the standard Tcl library.  Extensions (stub-enabled or
 not) are not intended to call \fBTcl_Main\fR.
 .PP
 \fBTcl_Main\fR is not thread-safe.  It should only be called by
-a single master thread of a multi-threaded application.  This
+a single main thread of a multi-threaded application.  This
 restriction is not a problem with normal use described above.
 .PP
 \fBTcl_Main\fR and therefore all applications based upon it, like
@@ -112,7 +112,7 @@ The file name and encoding values managed by the routines
 \fBTcl_SetStartupScript\fR and \fBTcl_GetStartupScript\fR
 are stored per-thread.  Although the storage and retrieval
 functions of these routines work in any thread, only those
-calls in the same master thread as \fBTcl_Main\fR can have
+calls in the same main thread as \fBTcl_Main\fR can have
 any influence on it.
 .PP
 The caller of \fBTcl_Main\fR may call \fBTcl_SetStartupScript\fR
@@ -126,7 +126,7 @@ a \fIstartup script\fR, and \fIname\fR is taken to be the name
 of the encoding of the contents of that file.  \fBTcl_Main\fR
 then calls \fBTcl_SetStartupScript\fR with these values.
 .PP
-\fBTcl_Main\fR then defines in its master interpreter
+\fBTcl_Main\fR then defines in its main interpreter
 the Tcl variables \fIargc\fR, \fIargv\fR, \fIargv0\fR, and
 \fItcl_interactive\fR, as described in the documentation for \fBtclsh\fR.
 .PP
@@ -154,9 +154,9 @@ When the \fIappInitProc\fR is finished, \fBTcl_Main\fR calls
 been requested, if any.  If a startup script has been provided,
 \fBTcl_Main\fR attempts to evaluate it.  Otherwise, interactive
 mode begins with examination of the variable \fItcl_rcFileName\fR
-in the master interpreter.  If that variable exists and holds the
+in the main interpreter.  If that variable exists and holds the
 name of a readable file, the contents of that file are evaluated
-in the master interpreter.  Then interactive operations begin,
+in the main interpreter.  Then interactive operations begin,
 with prompts and command evaluation results written to the standard
 output channel, and commands read from the standard input channel
 and then evaluated.  The prompts written to the standard output
@@ -164,7 +164,7 @@ channel may be customized by defining the Tcl variables \fItcl_prompt1\fR
 and \fItcl_prompt2\fR as described in the documentation for \fBtclsh\fR.
 The prompts and command evaluation results are written to the standard
 output channel only if the Tcl variable \fItcl_interactive\fR in the
-master interpreter holds a non-zero integer value.
+main interpreter holds a non-zero integer value.
 .PP
 \fBTcl_SetMainLoop\fR allows setting an event loop procedure to be run.
 This allows, for example, Tk to be dynamically loaded and set its event
index 0647b85..a281e2c 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1997 by Sun Microsystems, Inc.
+'\" Copyright (c) 1997 Sun Microsystems, Inc.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -81,7 +81,7 @@ and all following characters into their lower-case equivalents.
 .SH BUGS
 .PP
 At this time, the case conversions are only defined for the Unicode
-plane 0 characters.  The result for Unicode characters above 0xffff
+plane 0 characters.  The result for Unicode characters above 0xFFFF
 is undefined, but - actually - only the lower 16 bits of the
 character value is handled.
 
index 9d0c617..d8debf5 100644 (file)
--- a/doc/Utf.3
+++ b/doc/Utf.3
@@ -141,8 +141,8 @@ source buffer is long enough such that this routine does not run off the
 end and dereference non-existent or random memory; if the source buffer
 is known to be null-terminated, this will not happen.  If the input is
 not in proper UTF-8 format, \fBTcl_UtfToUniChar\fR will store the first
-byte of \fIsrc\fR in \fI*chPtr\fR as a Tcl_UniChar between 0x0000 and
-0x00ff and return 1.
+byte of \fIsrc\fR in \fI*chPtr\fR as a Tcl_UniChar between 0x0080 and
+0x00FF and return 1.
 .PP
 \fBTcl_UniCharToUtfDString\fR converts the given Unicode string
 to UTF-8, storing the result in a previously initialized \fBTcl_DString\fR.
@@ -223,13 +223,27 @@ string.  The caller must not ask for the next character after the last
 character in the string if the string is not terminated by a null
 character.
 .PP
-Given \fIsrc\fR, a pointer to some location in a UTF-8 string (or to a
-null byte immediately following such a string), \fBTcl_UtfPrev\fR
-returns a pointer to the closest preceding byte that starts a UTF-8
-character.
-This function will not back up to a position before \fIstart\fR,
-the start of the UTF-8 string.  If \fIsrc\fR was already at \fIstart\fR, the
-return value will be \fIstart\fR.
+\fBTcl_UtfPrev\fR is used to step backward through but not beyond the
+UTF-8 string that begins at \fIstart\fR.  If the UTF-8 string is made
+up entirely of complete and well-formed characters, and \fIsrc\fR points
+to the lead byte of one of those characters (or to the location one byte
+past the end of the string), then repeated calls of \fBTcl_UtfPrev\fR will
+return pointers to the lead bytes of each character in the string, one
+character at a time, terminating when it returns \fIstart\fR.
+.PP
+When the conditions of completeness and well-formedness may not be satisfied,
+a more precise description of the function of \fBTcl_UtfPrev\fR is necessary.
+It always returns a pointer greater than or equal to \fIstart\fR; that is,
+always a pointer to a location in the string. It always returns a pointer to
+a byte that begins a character when scanning for characters beginning
+from \fIstart\fR. When \fIsrc\fR is greater than \fIstart\fR, it
+always returns a pointer less than \fIsrc\fR and greater than or
+equal to (\fIsrc\fR - \fBTCL_UTF_MAX\fR).  The character that begins
+at the returned pointer is the first one that either includes the
+byte \fIsrc[-1]\fR, or might include it if the right trail bytes are
+present at \fIsrc\fR and greater. \fBTcl_UtfPrev\fR never reads the
+byte \fIsrc[0]\fR nor the byte \fIstart[-1]\fR nor the byte
+\fIsrc[-\fBTCL_UTF_MAX\fI-1]\fR.
 .PP
 \fBTcl_UniCharAtIndex\fR corresponds to a C string array dereference or the
 Pascal Ord() function.  It returns the Tcl_UniChar represented at the
@@ -240,7 +254,7 @@ characters.  Behavior is undefined if a negative \fIindex\fR is given.
 \fBTcl_UtfAtIndex\fR returns a pointer to the specified character (not
 byte) \fIindex\fR in the UTF-8 string \fIsrc\fR.  The source string must
 contain at least \fIindex\fR characters.  This is equivalent to calling
-\fBTcl_UtfNext\fR \fIindex\fR times.  If a negative \fIindex\fR is given,
+\fBTcl_UtfToUniChar\fR \fIindex\fR times.  If a negative \fIindex\fR is given,
 the return pointer points to the first character in the source string.
 .PP
 \fBTcl_UtfBackslash\fR is a utility procedure used by several of the Tcl
index 5f25d65..fd6b356 100644 (file)
@@ -1,6 +1,6 @@
 '\"
-'\" Copyright (c) 1997 by Sun Microsystems, Inc.
-'\" Copyright (c) 2008 by Donal K. Fellows
+'\" Copyright (c) 1997 Sun Microsystems, Inc.
+'\" Copyright (c) 2008 Donal K. Fellows
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -78,7 +78,9 @@ During decoding, the following options are supported:
 .TP
 \fB\-strict\fR
 .
-Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them.
+Instructs the decoder to throw an error if it encounters any characters
+that are not strictly part of the encoding itself. Otherwise it ignores them.
+RFC 2045 calls for base64 decoders to be non-strict.
 .RE
 .TP
 \fBhex\fR
@@ -92,7 +94,8 @@ options are supported:
 .TP
 \fB\-strict\fR
 .
-Instructs the decoder to throw an error if it encounters whitespace characters. Otherwise it ignores them.
+Instructs the decoder to throw an error if it encounters whitespace characters.
+Otherwise it ignores them.
 .RE
 .TP
 \fBuuencode\fR
@@ -107,23 +110,27 @@ produce files that other implementations of decoders cannot process):
 .TP
 \fB\-maxlen \fIlength\fR
 .
-Indicates that the output should be split into lines of no more than
-\fIlength\fR characters. By default, lines are split every 61 characters, and
-this must be in the range 3 to 85 due to limitations in the encoding.
+Indicates the maximum number of characters to produce for each encoded line.
+The valid range is 5 to 85. Line lengths outside that range cannot be
+accommodated by the encoding format. The default value is 61.
 .TP
 \fB\-wrapchar \fIcharacter\fR
 .
-Indicates that, when lines are split because of the \fB\-maxlen\fR option,
-\fIcharacter\fR should be used to separate lines. By default, this is a
-newline character,
-.QW \en .
+Indicates the character(s) to use to mark the end of each encoded line.
+Acceptable values are a sequence of zero or more characters from the
+set { \\x09 (TAB), \\x0B (VT), \\x0C (FF), \\x0D (CR) } followed
+by zero or one newline \\x0A (LF).  Any other values are rejected because
+they would generate encoded text that could not be decoded. The default value
+is a single newline.
 .PP
 During decoding, the following options are supported:
 .TP
 \fB\-strict\fR
 .
-Instructs the decoder to throw an error if it encounters unexpected whitespace
-characters. Otherwise it ignores them.
+Instructs the decoder to throw an error if it encounters anything
+outside of the standard encoding format. Without this option, the
+decoder tolerates some deviations, mostly to forgive reflows of lines
+between the encoder and decoder.
 .PP
 Note that neither the encoder nor the decoder handle the header and footer of
 the uuencode format.
@@ -653,7 +660,7 @@ stored in \fIvar2\fR.  Note that the integers returned are signed, but
 they can be converted to unsigned 8-bit quantities using an expression
 like:
 .CS
-set num [expr { $num & 0xff }]
+set num [expr { $num & 0xFF }]
 .CE
 .RE
 .IP \fBs\fR 5
@@ -672,7 +679,7 @@ stored in \fIvar2\fR.  Note that the integers returned are signed, but
 they can be converted to unsigned 16-bit quantities using an expression
 like:
 .CS
-set num [expr { $num & 0xffff }]
+set num [expr { $num & 0xFFFF }]
 .CE
 .RE
 .IP \fBS\fR 5
@@ -709,7 +716,7 @@ stored in \fIvar2\fR.  Note that the integers returned are signed, but
 they can be converted to unsigned 32-bit quantities using an expression
 like:
 .CS
-set num [expr { $num & 0xffffffff }]
+set num [expr { $num & 0xFFFFFFFF }]
 .CE
 .RE
 .IP \fBI\fR 5
index 3e4ce5f..78fd005 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH break n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 54d5bf4..c48d634 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH case n 7.0 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 67cdd17..dceb075 100644 (file)
--- a/doc/cd.n
+++ b/doc/cd.n
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH cd n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 81aa9f4..77e9326 100644 (file)
@@ -179,7 +179,7 @@ operating system, as returned by \fBencoding system\fR.
 .TP
 \fB\-eofchar\fR \fB{\fIinChar outChar\fB}\fR
 .
-This option supports DOS file systems that use Control-z (\ex1a) as an
+This option supports DOS file systems that use Control-z (\ex1A) as an
 end of file marker.  If \fIchar\fR is not an empty string, then this
 character signals end-of-file when it is encountered during input.
 For output, the end-of-file character is output when the channel is
@@ -192,7 +192,7 @@ will apply to both reading and writing.  When querying the end-of-file
 character of a read-write channel, a two-element list will always be
 returned.  The default value for \fB\-eofchar\fR is the empty string
 in all cases except for files under Windows.  In that case the
-\fB\-eofchar\fR is Control-z (\ex1a) for reading and the empty string
+\fB\-eofchar\fR is Control-z (\ex1A) for reading and the empty string
 for writing.
 The acceptable range for \fB\-eofchar\fR values is \ex01 - \ex7f;
 attempting to set \fB\-eofchar\fR to a value outside of this range will
index 6efa722..b8f2a0c 100644 (file)
@@ -465,43 +465,43 @@ a Daylight Saving Time change skips over that time, or an ambiguous
 time because a Daylight Saving Time change skips back so that the clock
 observes the given time twice, and no time zone specifier (\fB%z\fR
 or \fB%Z\fR) is present in the format, the time is interpreted as
-if the clock had not changed. 
+if the clock had not changed.
 .SH "FORMAT GROUPS"
 .PP
 The following format groups are recognized by the \fBclock scan\fR and
 \fBclock format\fR commands.
 .TP
 \fB%a\fR
-On output, receives an abbreviation (\fIe.g.,\fR \fBMon\fR) for the day
+On output, produces an abbreviation (\fIe.g.,\fR \fBMon\fR) for the day
 of the week in the given locale.  On input, matches the name of the day
 of the week in the given locale (in either abbreviated or full form, or
 any unique prefix of either form).
 .TP
 \fB%A\fR
-On output, receives the full name (\fIe.g.,\fR \fBMonday\fR) of the day
+On output, produces the full name (\fIe.g.,\fR \fBMonday\fR) of the day
 of the week in the given locale.  On input, matches the name of the day
 of the week in the given locale (in either abbreviated or full form, or
 any unique prefix of either form).
 .TP
 \fB%b\fR
-On output, receives an abbreviation (\fIe.g.,\fR \fBJan\fR) for the name
+On output, produces an abbreviation (\fIe.g.,\fR \fBJan\fR) for the name
 of the month in the given locale.  On input, matches the name of the month
 in the given locale (in either abbreviated or full form, or
 any unique prefix of either form).
 .TP
 \fB%B\fR
-On output, receives the full name (\fIe.g.,\fR \fBJanuary\fR)
+On output, produces the full name (\fIe.g.,\fR \fBJanuary\fR)
 of the month in the given locale.  On input, matches the name of the month
 in the given locale (in either abbreviated or full form, or
 any unique prefix of either form).
 .TP
 \fB%c\fR
-On output, receives a localized representation of date and time of day;
+On output, produces a localized representation of date and time of day;
 the localized representation is expected to use the Gregorian calendar.
 On input, matches whatever \fB%c\fR produces.
 .TP
 \fB%C\fR
-On output, receives the number of the century in Indo-Arabic numerals.
+On output, produces the number of the century in Indo-Arabic numerals.
 On input, matches one or two digits, possibly with leading whitespace,
 that are expected to be the number of the century.
 .TP
@@ -913,9 +913,10 @@ An ISO 8601 point-in-time specification, such as
 where \fBT\fR is the literal
 .QW T ,
 .QW "\fICCyymmdd hhmmss\fR" ,
+.QW \fICCyymmdd\fBT\fIhh:mm:ss\fR ,
 or
-.QW \fICCyymmdd\fBT\fIhh:mm:ss\fR .
-Note that only these three formats are accepted.
+.QW \fICCyy-mm-dd\fBT\fIhh:mm:ss\fR.
+Note that only these four formats are accepted.
 The command does \fInot\fR accept the full range of point-in-time
 specifications specified in ISO8601.  Other formats can be recognized by
 giving an explicit \fB\-format\fR option to the \fBclock scan\fR command.
@@ -945,7 +946,7 @@ msgcat(n)
 .SH KEYWORDS
 clock, date, time
 .SH "COPYRIGHT"
-Copyright (c) 2004 Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
+Copyright \(co 2004 Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
 '\" Local Variables:
 '\" mode: nroff
 '\" End:
index 63da75b..5daf3e2 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH close n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 23c6c91..d10f092 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH concat n 8.3 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 17d16b4..92ff3b4 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH continue n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 789a76c..706be54 100644 (file)
@@ -33,9 +33,9 @@ as the empty string, a new name is chosen. Names, unless specified, are
 chosen with the same algorithm used by the \fBnew\fR method of
 \fBoo::class\fR.
 .VE TIP473
-The copied object will be of the same class as the source object, and will have 
-all its per-object methods copied. If it is a class, it will also have all the 
-class methods in the class copied, but it will not have any of its instances 
+The copied object will be of the same class as the source object, and will have
+all its per-object methods copied. If it is a class, it will also have all the
+class methods in the class copied, but it will not have any of its instances
 copied.
 .PP
 .VS
index c99f8d3..52775ef 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH coroutine n 8.6 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index cd7e94c..db4b656 100644 (file)
@@ -58,7 +58,7 @@ of the given patterns (in the style of \fBstring match\fR.)
 .
 The script rule tests for matching by assigning the key to the
 \fIkeyVariable\fR and the value to the \fIvalueVariable\fR, and then evaluating
-the given script which should return a boolean value (with the
+the given script which should result in a boolean value (with the
 key/value pair only being included in the result of the \fBdict
 filter\fR when a true value is returned.)  Note that the first
 argument after the rule selection word is a two-element list.  If the
index 50ad083..5aac181 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 1998 by Scriptics Corporation.
+'\" Copyright (c) 1998 Scriptics Corporation.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 75f3c48..a150464 100644 (file)
--- a/doc/eof.n
+++ b/doc/eof.n
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH eof n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 3ef5023..9fc2ae4 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH eval n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 99dfdc5..04b5269 100644 (file)
@@ -246,15 +246,6 @@ the backslash character.  If an argument contains forward slashes as the
 path separator, it may or may not be recognized as a path name, depending on
 the program.
 .PP
-Additionally, when calling a 16-bit DOS or Windows 3.X application, all path
-names must use the short, cryptic, path format (e.g., using
-.QW applba~1.def
-instead of
-.QW applbakery.default ),
-which can be obtained with the
-.QW "\fBfile attributes\fI fileName \fB\-shortname\fR"
-command.
-.PP
 Two or more forward or backward slashes in a row in a path refer to a
 network path.  For example, a simple concatenation of the root directory
 \fBc:/\fR with a subdirectory \fB/windows/system\fR will yield
@@ -295,11 +286,9 @@ The directory from which the Tcl executable was loaded.
 .IP \(bu 3
 The current directory.
 .IP \(bu 3
-The Windows NT 32-bit system directory.
-.IP \(bu 3
-The Windows NT 16-bit system directory.
+The Windows 32-bit system directory.
 .IP \(bu 3
-The Windows NT home directory.
+The Windows home directory.
 .IP \(bu 3
 The directories listed in the path.
 .PP
index 9b4ad20..a005c08 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH exit n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 1fd4c4e..b2b1d66 100644 (file)
@@ -1,7 +1,7 @@
 '\"
 '\" Copyright (c) 1993 The Regents of the University of California.
 '\" Copyright (c) 1994-2000 Sun Microsystems, Inc.
-'\" Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved
+'\" Copyright (c) 2005 Kevin B. Kenny <kennykb@acm.org>. All rights reserved
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -107,9 +107,9 @@ will produce the value on the right side of the line:
 .PP
 .CS
 .ta 9c
-\fBexpr\fR 3.1 + $a    \fI6.1\fR
-\fBexpr\fR 2 + "$a.$b" \fI5.6\fR
-\fBexpr\fR 4*[llength "6 2"]   \fI8\fR
+\fBexpr\fR {3.1 + $a}  \fI6.1\fR
+\fBexpr\fR {2 + "$a.$b"}       \fI5.6\fR
+\fBexpr\fR {4*[llength "6 2"]} \fI8\fR
 \fBexpr\fR {{word one} < "word $a"}    \fI0\fR
 .CE
 .SS OPERATORS
@@ -246,7 +246,7 @@ just as in C, which means that operands are not evaluated if they are
 not needed to determine the outcome.  For example, in the command
 .PP
 .CS
-\fBexpr\fR {$v ? [a] : [b]}
+\fBexpr\fR {$v?[a]:[b]}
 .CE
 .PP
 only one of
@@ -490,10 +490,11 @@ string(n), Tcl(n), while(n)
 arithmetic, boolean, compare, expression, fuzzy comparison
 .SH COPYRIGHT
 .nf
-Copyright (c) 1993 The Regents of the University of California.
-Copyright (c) 1994-2000 Sun Microsystems Incorporated.
-Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
+Copyright \(co 1993 The Regents of the University of California.
+Copyright \(co 1994-2000 Sun Microsystems Incorporated.
+Copyright \(co 2005 Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
 .fi
 '\" Local Variables:
 '\" mode: nroff
+'\" fill-column: 78
 '\" End:
index 2841aee..93cfe87 100644 (file)
@@ -1,4 +1,4 @@
-'\" 
+'\"
 '\" Copyright (c) 1996 Sun Microsystems, Inc.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
index 8da76c6..2926777 100644 (file)
@@ -105,7 +105,7 @@ system, as returned by \fBencoding system\fR.
 .TP
 \fB\-eofchar\fR \fB{\fIinChar outChar\fB}\fR
 .
-This option supports DOS file systems that use Control-z (\ex1a) as an
+This option supports DOS file systems that use Control-z (\ex1A) as an
 end of file marker.  If \fIchar\fR is not an empty string, then this
 character signals end-of-file when it is encountered during input.  For
 output, the end-of-file character is output when the channel is closed.
@@ -117,9 +117,9 @@ channel you can specify a single value that will apply to both reading
 and writing.  When querying the end-of-file character of a read-write
 channel, a two-element list will always be returned.  The default value
 for \fB\-eofchar\fR is the empty string in all cases except for files
-under Windows.  In that case the \fB\-eofchar\fR is Control-z (\ex1a) for
+under Windows.  In that case the \fB\-eofchar\fR is Control-z (\ex1A) for
 reading and the empty string for writing.
-The acceptable range for \fB\-eofchar\fR values is \ex01 - \ex7f;
+The acceptable range for \fB\-eofchar\fR values is \ex01 - \ex7F;
 attempting to set \fB\-eofchar\fR to a value outside of this range will
 generate an error.
 .TP
index d266d91..6b98ab7 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH flush n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 89a11f6..925ec1f 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH foreach n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 0150f29..57532c0 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH gets n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index e1f9781..0391948 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH history n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 7e633b3..181b48b 100644 (file)
@@ -1,6 +1,6 @@
 '\"
 '\" Copyright (c) 1995-1997 Sun Microsystems, Inc.
-'\" Copyright (c) 1998-2000 by Ajuba Solutions.
+'\" Copyright (c) 1998-2000 Ajuba Solutions.
 '\" Copyright (c) 2004 ActiveState Corporation.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
@@ -13,7 +13,7 @@
 .SH NAME
 http \- Client-side implementation of the HTTP/1.1 protocol
 .SH SYNOPSIS
-\fBpackage require http ?2.8?\fR
+\fBpackage require http ?2.9?\fR
 .\" See Also -useragent option documentation in body!
 .sp
 \fB::http::config ?\fI\-option value\fR ...?
@@ -78,6 +78,9 @@ when the transaction completes.  For this to work, the Tcl event loop
 must be active.  In Tk applications this is always true.  For pure-Tcl
 applications, the caller can use \fB::http::wait\fR after calling
 \fB::http::geturl\fR to start the event loop.
+.PP
+\fBNote:\fR The event queue is even used without the \fB-command\fR option.
+As a side effect, arbitrary commands may be processed while \fBhttp::geturl\fR is running.
 .SH COMMANDS
 .TP
 \fB::http::config\fR ?\fIoptions\fR?
@@ -161,7 +164,7 @@ throwing an error processing non-latin-1 characters.
 The value of the User-Agent header in the HTTP request.  In an unsafe
 interpreter, the default value depends upon the operating system, and
 the version numbers of \fBhttp\fR and \fBTcl\fR, and is (for example)
-.QW "\fBMozilla/5.0 (Windows; U; Windows NT 10.0) http/2.8.12 Tcl/8.6.8\fR" .
+.QW "\fBMozilla/5.0 (Windows; U; Windows NT 10.0) http/2.9.0 Tcl/8.6.9\fR" .
 A safe interpreter cannot determine its operating system, and so the default
 in a safe interpreter is to use a Windows 10 value with the current version
 numbers of \fBhttp\fR and \fBTcl\fR.
@@ -250,6 +253,10 @@ proc httpHandlerCallback {socket token} {
     return $nbytes
 }
 .CE
+.PP
+The \fBhttp::geturl\fR code for the \fB-handler\fR option is not compatible with either compression or chunked transfer-encoding.  If \fB-handler\fR is specified, then to work around these issues \fBhttp::geturl\fR will reduce the HTTP protocol to 1.0, and override the \fB-zip\fR option (i.e. it will not send the header "\fBAccept-Encoding: gzip,deflate,compress\fR").
+.PP
+If options \fB-handler\fR and \fB-channel\fR are used together, the handler is responsible for copying the data from the HTTP socket to the specified channel.  The name of the channel is available to the handler as element \fB-channel\fR of the token array.
 .RE
 .TP
 \fB\-headers\fR \fIkeyvaluelist\fR
@@ -312,9 +319,11 @@ otherwise complain about HTTP/1.1.
 \fB\-query\fR \fIquery\fR
 .
 This flag causes \fB::http::geturl\fR to do a POST request that passes the
-\fIquery\fR to the server. The \fIquery\fR must be an x-url-encoding
-formatted query.  The \fB::http::formatQuery\fR procedure can be used to
-do the formatting.
+\fIquery\fR as payload verbatim to the server.
+The content format (and encoding) of \fIquery\fR is announced by the header
+field \fBcontent-type\fR set by the option \fB-type\fR.
+\fIquery\fR is an x-url-encoding formatted query, if used for html forms.
+The \fB::http::formatQuery\fR procedure can be used to do the formatting.
 .TP
 \fB\-queryblocksize\fR \fIsize\fR
 .
@@ -538,6 +547,14 @@ is raised, but the status of the transaction will be \fBeof\fR.
 .
 The error message will also be stored in the \fBerror\fR status
 array element, accessible via \fB::http::error\fR.
+.TP
+\fBtimeout\fR
+.
+A timeout occurred before the transaction could complete
+.TP
+\fBreset\fR
+.
+user-reset
 .PP
 Another error possibility is that \fB::http::geturl\fR is unable to
 write all the post query data to the server before the server
@@ -653,10 +670,9 @@ the post query data to the server.
 .TP
 \fBstatus\fR
 .
-Either \fBok\fR, for successful completion, \fBreset\fR for
-user-reset, \fBtimeout\fR if a timeout occurred before the transaction
-could complete, or \fBerror\fR for an error condition.  During the
-transaction this value is the empty string.
+See description in the chapter \fBERRORS\fR above for a
+list and description of \fBstatus\fR.
+During the transaction this value is the empty string.
 .TP
 \fBtotalsize\fR
 .
index 776f811..ff2518d 100644 (file)
--- a/doc/if.n
+++ b/doc/if.n
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH if n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 9052c5a..b4be95c 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH incr n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 1ad908d..477e272 100644 (file)
@@ -7,7 +7,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH info n 8.4 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 1c9618a..1127632 100644 (file)
@@ -5,7 +5,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH interp n 8.6 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
@@ -19,18 +19,18 @@ interp \- Create and manipulate Tcl interpreters
 .PP
 This command makes it possible to create one or more new Tcl
 interpreters that co-exist with the creating interpreter in the
-same application.  The creating interpreter is called the \fImaster\fR
-and the new interpreter is called a \fIslave\fR.
-A master can create any number of slaves, and each slave can
-itself create additional slaves for which it is master, resulting
+same application.  The creating interpreter is called the \fIparent\fR
+and the new interpreter is called a \fIchild\fR.
+A parent can create any number of children, and each child can
+itself create additional children for which it is parent, resulting
 in a hierarchy of interpreters.
 .PP
 Each interpreter is independent from the others: it has its own name
 space for commands, procedures, and global variables.
-A master interpreter may create connections between its slaves and
+A parent interpreter may create connections between its children and
 itself using a mechanism called an \fIalias\fR.  An \fIalias\fR is
-a command in a slave interpreter which, when invoked, causes a
-command to be invoked in its master interpreter or in another slave
+a command in a child interpreter which, when invoked, causes a
+command to be invoked in its parent interpreter or in another child
 interpreter.  The only other connections between interpreters are
 through environment variables (the \fBenv\fR variable), which are
 normally shared among all interpreters in the application,
@@ -41,7 +41,7 @@ share files and to transfer references to open files from one interpreter
 to another.
 .PP
 The \fBinterp\fR command also provides support for \fIsafe\fR
-interpreters.  A safe interpreter is a slave whose functions have
+interpreters.  A safe interpreter is a child whose functions have
 been greatly restricted, so that it is safe to execute untrusted
 scripts without fear of them damaging other interpreters or the
 application's environment. For example, all IO channel creation
@@ -54,18 +54,18 @@ instead, it is \fIhidden\fR, so that only trusted interpreters can obtain
 access to it. For a detailed explanation of hidden commands, see
 \fBHIDDEN COMMANDS\fR, below.
 The alias mechanism can be used for protected communication (analogous to a
-kernel call) between a slave interpreter and its master.
+kernel call) between a child interpreter and its parent.
 See \fBALIAS INVOCATION\fR, below, for more details
 on how the alias mechanism works.
 .PP
-A qualified interpreter name is a proper Tcl lists containing a subset of its
+A qualified interpreter name is a proper Tcl list containing a subset of its
 ancestors in the interpreter hierarchy, terminated by the string naming the
-interpreter in its immediate master. Interpreter names are relative to the
+interpreter in its immediate parent. Interpreter names are relative to the
 interpreter in which they are used. For example, if
 .QW \fBa\fR
-is a slave of the current interpreter and it has a slave
+is a child of the current interpreter and it has a child
 .QW \fBa1\fR ,
-which in turn has a slave
+which in turn has a child
 .QW \fBa11\fR ,
 the qualified name of
 .QW \fBa11\fR
@@ -77,14 +77,14 @@ is the list
 The \fBinterp\fR command, described below, accepts qualified interpreter
 names as arguments; the interpreter in which the command is being evaluated
 can always be referred to as \fB{}\fR (the empty list or string). Note that
-it is impossible to refer to a master (ancestor) interpreter by name in a
-slave interpreter except through aliases. Also, there is no global name by
+it is impossible to refer to a parent (ancestor) interpreter by name in a
+child interpreter except through aliases. Also, there is no global name by
 which one can refer to the first interpreter created in an application.
 Both restrictions are motivated by safety concerns.
 .SH "THE INTERP COMMAND"
 .PP
 The \fBinterp\fR command is used to create, delete, and manipulate
-slave interpreters, and to share or transfer
+child interpreters, and to share or transfer
 channels between interpreters.  It can have any of several forms, depending
 on the \fIsubcommand\fR argument:
 .TP
@@ -94,11 +94,11 @@ Returns a Tcl list whose elements are the \fItargetCmd\fR and
 \fIarg\fRs associated with the alias represented by \fIsrcToken\fR
 (this is the value returned when the alias was
 created; it is possible that the name of the source command in the
-slave is different from \fIsrcToken\fR).
+child is different from \fIsrcToken\fR).
 .TP
 \fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcToken\fR \fB{}\fR
 .
-Deletes the alias for \fIsrcToken\fR in the slave interpreter identified by
+Deletes the alias for \fIsrcToken\fR in the child interpreter identified by
 \fIsrcPath\fR.
 \fIsrcToken\fR refers to the value returned when the alias
 was created;  if the source command has been renamed, the renamed
@@ -106,9 +106,9 @@ command will be deleted.
 .TP
 \fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcCmd\fR \fItargetPath\fR \fItargetCmd \fR?\fIarg arg ...\fR?
 .
-This command creates an alias between one slave and another (see the
-\fBalias\fR slave command below for creating aliases between a slave
-and its master).  In this command, either of the slave interpreters
+This command creates an alias between one child and another (see the
+\fBalias\fR child command below for creating aliases between a child
+and its parent).  In this command, either of the child interpreters
 may be anywhere in the hierarchy of interpreters under the interpreter
 invoking the command.
 \fISrcPath\fR and \fIsrcCmd\fR identify the source of the alias.
@@ -117,9 +117,9 @@ interpreter.  For example,
 .QW "\fBa b\fR"
 identifies an interpreter
 .QW \fBb\fR ,
-which is a slave of interpreter
+which is a child of interpreter
 .QW \fBa\fR ,
-which is a slave of the invoking interpreter.  An empty list specifies
+which is a child of the invoking interpreter.  An empty list specifies
 the interpreter invoking the command.  \fIsrcCmd\fR gives the name of
 a new command, which will be created in the source interpreter.
 \fITargetPath\fR and \fItargetCmd\fR specify a target interpreter
@@ -171,33 +171,33 @@ used.
 .TP
 \fBinterp\fR \fBcreate \fR?\fB\-safe\fR? ?\fB\-\|\-\fR? ?\fIpath\fR?
 .
-Creates a slave interpreter identified by \fIpath\fR and a new command,
-called a \fIslave command\fR. The name of the slave command is the last
-component of \fIpath\fR. The new slave interpreter and the slave command
+Creates a child interpreter identified by \fIpath\fR and a new command,
+called a \fIchild command\fR. The name of the child command is the last
+component of \fIpath\fR. The new child interpreter and the child command
 are created in the interpreter identified by the path obtained by removing
 the last component from \fIpath\fR. For example, if \fIpath\fR is \fBa b
-c\fR then a new slave interpreter and slave command named \fBc\fR are
+c\fR then a new child interpreter and child command named \fBc\fR are
 created in the interpreter identified by the path \fBa b\fR.
-The slave command may be used to manipulate the new interpreter as
+The child command may be used to manipulate the new interpreter as
 described below. If \fIpath\fR is omitted, Tcl creates a unique name of the
 form \fBinterp\fIx\fR, where \fIx\fR is an integer, and uses it for the
-interpreter and the slave command. If the \fB\-safe\fR switch is specified
-(or if the master interpreter is a safe interpreter), the new slave
+interpreter and the child command. If the \fB\-safe\fR switch is specified
+(or if the parent interpreter is a safe interpreter), the new child
 interpreter will be created as a safe interpreter with limited
-functionality; otherwise the slave will include the full set of Tcl
+functionality; otherwise the child will include the full set of Tcl
 built-in commands and variables. The \fB\-\|\-\fR switch can be used to
 mark the end of switches;  it may be needed if \fIpath\fR is an unusual
 value such as \fB\-safe\fR. The result of the command is the name of the
-new interpreter. The name of a slave interpreter must be unique among all
-the slaves for its master;  an error occurs if a slave interpreter by the
-given name already exists in this master.
-The initial recursion limit of the slave interpreter is set to the
+new interpreter. The name of a child interpreter must be unique among all
+the children for its parent;  an error occurs if a child interpreter by the
+given name already exists in this parent.
+The initial recursion limit of the child interpreter is set to the
 current recursion limit of its parent interpreter.
 .TP
 \fBinterp\fR \fBdebug \fIpath\fR ?\fB\-frame\fR ?\fIbool\fR??
 .
 Controls whether frame-level stack information is captured in the
-slave interpreter identified by \fIpath\fR.  If no arguments are
+child interpreter identified by \fIpath\fR.  If no arguments are
 given, option and current setting are returned.  If \fB\-frame\fR
 is given, the debug setting is set to the given boolean if provided
 and the current setting is returned.
@@ -239,8 +239,8 @@ consistency of the underlying interpreter's state.
 \fBinterp\fR \fBdelete \fR?\fIpath ...?\fR
 .
 Deletes zero or more interpreters given by the optional \fIpath\fR
-arguments, and for each interpreter, it also deletes its slaves. The
-command also deletes the slave command for each interpreter deleted.
+arguments, and for each interpreter, it also deletes its children. The
+command also deletes the child command for each interpreter deleted.
 For each \fIpath\fR argument, if no interpreter by that name
 exists, the command raises an error.
 .TP
@@ -248,20 +248,20 @@ exists, the command raises an error.
 .
 This command concatenates all of the \fIarg\fR arguments in the same
 fashion as the \fBconcat\fR command, then evaluates the resulting string as
-a Tcl script in the slave interpreter identified by \fIpath\fR. The result
+a Tcl script in the child interpreter identified by \fIpath\fR. The result
 of this evaluation (including all \fBreturn\fR options,
 such as \fB\-errorinfo\fR and \fB\-errorcode\fR information, if an
 error occurs) is returned to the invoking interpreter.
 Note that the script will be executed in the current context stack frame of the
-\fIpath\fR interpreter; this is so that the implementations (in a master
-interpreter) of aliases in a slave interpreter can execute scripts in
-the slave that find out information about the slave's current state
+\fIpath\fR interpreter; this is so that the implementations (in a parent
+interpreter) of aliases in a child interpreter can execute scripts in
+the child that find out information about the child's current state
 and stack frame.
 .TP
 \fBinterp exists \fIpath\fR
 .
-Returns \fB1\fR if a slave interpreter by the specified \fIpath\fR
-exists in this master, \fB0\fR otherwise. If \fIpath\fR is omitted, the
+Returns \fB1\fR if a child interpreter by the specified \fIpath\fR
+exists in this parent, \fB0\fR otherwise. If \fIpath\fR is omitted, the
 invoking interpreter is used.
 .TP
 \fBinterp expose \fIpath\fR \fIhiddenName\fR ?\fIexposedCmdName\fR?
@@ -287,7 +287,7 @@ Currently both \fIexposedCmdName\fR and \fIhiddenCmdName\fR can
 not contain namespace qualifiers, or an error is raised.
 Commands to be hidden by \fBinterp hide\fR are looked up in the global
 namespace even if the current namespace is not the global one. This
-prevents slaves from fooling a master interpreter into hiding the wrong
+prevents children from fooling a parent interpreter into hiding the wrong
 command, by making the current namespace be different from the global one.
 Hidden commands are explained in more detail in \fBHIDDEN COMMANDS\fR, below.
 .TP
@@ -373,9 +373,15 @@ interpreter is destroyed.
 .TP
 \fBinterp\fR \fBslaves\fR ?\fIpath\fR?
 .
-Returns a Tcl list of the names of all the slave interpreters associated
+Returns a Tcl list of the names of all the child interpreters associated
 with the interpreter identified by \fIpath\fR. If \fIpath\fR is omitted,
 the invoking interpreter is used.
+.VS "TIP 581"
+.TP
+\fBinterp\fR \fBchildren\fR ?\fIpath\fR?
+.
+Synonym for . \fBinterp\fR \fBslaves\fR ?\fIpath\fR?
+.VE "TIP 581"
 .TP
 \fBinterp\fR \fBtarget\fR \fIpath alias\fR
 .
@@ -393,48 +399,48 @@ The target command does not have to be defined at the time of this invocation.
 Causes the IO channel identified by \fIchannelId\fR to become available in
 the interpreter identified by \fIdestPath\fR and unavailable in the
 interpreter identified by \fIsrcPath\fR.
-.SH "SLAVE COMMAND"
+.SH "child COMMAND"
 .PP
-For each slave interpreter created with the \fBinterp\fR command, a
-new Tcl command is created in the master interpreter with the same
+For each child interpreter created with the \fBinterp\fR command, a
+new Tcl command is created in the parent interpreter with the same
 name as the new interpreter. This command may be used to invoke
 various operations on the interpreter.  It has the following
 general form:
 .PP
 .CS
-\fIslave command \fR?\fIarg arg ...\fR?
+\fIchild command \fR?\fIarg arg ...\fR?
 .CE
 .PP
-\fISlave\fR is the name of the interpreter, and \fIcommand\fR
+\fIchild\fR is the name of the interpreter, and \fIcommand\fR
 and the \fIarg\fRs determine the exact behavior of the command.
 The valid forms of this command are:
 .TP
-\fIslave \fBaliases\fR
+\fIchild \fBaliases\fR
 .
 Returns a Tcl list whose elements are the tokens of all the
-aliases in \fIslave\fR.  The tokens correspond to the values returned when
+aliases in \fIchild\fR.  The tokens correspond to the values returned when
 the aliases were created (which may not be the same
 as the current names of the commands).
 .TP
-\fIslave \fBalias \fIsrcToken\fR
+\fIchild \fBalias \fIsrcToken\fR
 .
 Returns a Tcl list whose elements are the \fItargetCmd\fR and
 \fIarg\fRs associated with the alias represented by \fIsrcToken\fR
 (this is the value returned when the alias was
 created; it is possible that the actual source command in the
-slave is different from \fIsrcToken\fR).
+child is different from \fIsrcToken\fR).
 .TP
-\fIslave \fBalias \fIsrcToken \fB{}\fR
+\fIchild \fBalias \fIsrcToken \fB{}\fR
 .
-Deletes the alias for \fIsrcToken\fR in the slave interpreter.
+Deletes the alias for \fIsrcToken\fR in the child interpreter.
 \fIsrcToken\fR refers to the value returned when the alias
 was created;  if the source command has been renamed, the renamed
 command will be deleted.
 .TP
-\fIslave \fBalias \fIsrcCmd targetCmd \fR?\fIarg ..\fR?
+\fIchild \fBalias \fIsrcCmd targetCmd \fR?\fIarg ..\fR?
 .
 Creates an alias such that whenever \fIsrcCmd\fR is invoked
-in \fIslave\fR, \fItargetCmd\fR is invoked in the master.
+in \fIchild\fR, \fItargetCmd\fR is invoked in the parent.
 The \fIarg\fR arguments will be passed to \fItargetCmd\fR as additional
 arguments, prepended before any arguments passed in the invocation of
 \fIsrcCmd\fR.
@@ -443,69 +449,69 @@ The command returns a token that uniquely identifies the command created
 \fIsrcCmd\fR, even if the command is renamed afterwards. The token may but
 does not have to be equal to \fIsrcCmd\fR.
 .TP
-\fIslave \fBbgerror\fR ?\fIcmdPrefix\fR?
+\fIchild \fBbgerror\fR ?\fIcmdPrefix\fR?
 .
 This command either gets or sets the current background exception handler
-for the \fIslave\fR interpreter. If \fIcmdPrefix\fR is
+for the \fIchild\fR interpreter. If \fIcmdPrefix\fR is
 absent, the current background exception handler is returned, and if it is
 present, it is a list of words (of minimum length one) that describes
 what to set the interpreter's background exception handler to. See the
 \fBBACKGROUND EXCEPTION HANDLING\fR section for more details.
 .TP
-\fIslave \fBeval \fIarg \fR?\fIarg ..\fR?
+\fIchild \fBeval \fIarg \fR?\fIarg ..\fR?
 .
 This command concatenates all of the \fIarg\fR arguments in
 the same fashion as the \fBconcat\fR command, then evaluates
-the resulting string as a Tcl script in \fIslave\fR.
+the resulting string as a Tcl script in \fIchild\fR.
 The result of this evaluation (including all \fBreturn\fR options,
 such as \fB\-errorinfo\fR and \fB\-errorcode\fR information, if an
 error occurs) is returned to the invoking interpreter.
 Note that the script will be executed in the current context stack frame
-of \fIslave\fR; this is so that the implementations (in a master
-interpreter) of aliases in a slave interpreter can execute scripts in
-the slave that find out information about the slave's current state
+of \fIchild\fR; this is so that the implementations (in a parent
+interpreter) of aliases in a child interpreter can execute scripts in
+the child that find out information about the child's current state
 and stack frame.
 .TP
-\fIslave \fBexpose \fIhiddenName \fR?\fIexposedCmdName\fR?
+\fIchild \fBexpose \fIhiddenName \fR?\fIexposedCmdName\fR?
 .
 This command exposes the hidden command \fIhiddenName\fR, eventually bringing
 it back under a new \fIexposedCmdName\fR name (this name is currently
 accepted only if it is a valid global name space name without any ::),
-in \fIslave\fR.
+in \fIchild\fR.
 If an exposed command with the targeted name already exists, this command
 fails.
 For more details on hidden commands, see \fBHIDDEN COMMANDS\fR, below.
 .TP
-\fIslave \fBhide \fIexposedCmdName\fR ?\fIhiddenCmdName\fR?
+\fIchild \fBhide \fIexposedCmdName\fR ?\fIhiddenCmdName\fR?
 .
 This command hides the exposed command \fIexposedCmdName\fR, renaming it to
 the hidden command \fIhiddenCmdName\fR, or keeping the same name if the
-argument is not given, in the \fIslave\fR interpreter.
+argument is not given, in the \fIchild\fR interpreter.
 If a hidden command with the targeted name already exists, this command
 fails.
 Currently both \fIexposedCmdName\fR and \fIhiddenCmdName\fR can
 not contain namespace qualifiers, or an error is raised.
 Commands to be hidden are looked up in the global
 namespace even if the current namespace is not the global one. This
-prevents slaves from fooling a master interpreter into hiding the wrong
+prevents children from fooling a parent interpreter into hiding the wrong
 command, by making the current namespace be different from the global one.
 For more details on hidden commands, see \fBHIDDEN COMMANDS\fR, below.
 .TP
-\fIslave \fBhidden\fR
+\fIchild \fBhidden\fR
 .
-Returns a list of the names of all hidden commands in \fIslave\fR.
+Returns a list of the names of all hidden commands in \fIchild\fR.
 .TP
-\fIslave \fBinvokehidden\fR ?\fI\-option ...\fR? \fIhiddenName \fR?\fIarg ..\fR?
+\fIchild \fBinvokehidden\fR ?\fI\-option ...\fR? \fIhiddenName \fR?\fIarg ..\fR?
 .
 This command invokes the hidden command \fIhiddenName\fR with the
-supplied arguments, in \fIslave\fR. No substitutions or evaluations are
+supplied arguments, in \fIchild\fR. No substitutions or evaluations are
 applied to the arguments. Three \fI\-option\fRs are supported, all
 of which start with \fB\-\fR: \fB\-namespace\fR (which takes a single
 argument afterwards, \fInsName\fR), \fB\-global\fR, and \fB\-\|\-\fR.
 If the \fB\-namespace\fR flag is given, the hidden command is invoked in
-the specified namespace in the slave.
+the specified namespace in the child.
 If the \fB\-global\fR flag is given, the command is invoked at the global
-level in the slave; otherwise it is invoked at the current call frame and
+level in the child; otherwise it is invoked at the current call frame and
 can access local variables in that or outer call frames.
 The \fB\-\|\-\fR flag allows the \fIhiddenCmdName\fR argument to start with a
 .QW \-
@@ -513,37 +519,37 @@ character, and is otherwise unnecessary.
 If both the \fB\-namespace\fR and \fB\-global\fR flags are given, the
 \fB\-namespace\fR flag is ignored.
 Note that the hidden command will be executed (by default) in the
-current context stack frame of \fIslave\fR.
+current context stack frame of \fIchild\fR.
 For more details on hidden commands,
 see \fBHIDDEN COMMANDS\fR, below.
 .TP
-\fIslave \fBissafe\fR
+\fIchild \fBissafe\fR
 .
-Returns  \fB1\fR if the slave interpreter is safe, \fB0\fR otherwise.
+Returns  \fB1\fR if the child interpreter is safe, \fB0\fR otherwise.
 .TP
-\fIslave \fBlimit\fR \fIlimitType\fR ?\fI\-option\fR? ?\fIvalue\fR \fI...\fR?
+\fIchild \fBlimit\fR \fIlimitType\fR ?\fI\-option\fR? ?\fIvalue\fR \fI...\fR?
 .
 Sets up, manipulates and queries the configuration of the resource
-limit \fIlimitType\fR for the slave interpreter.  If no \fI\-option\fR
+limit \fIlimitType\fR for the child interpreter.  If no \fI\-option\fR
 is specified, return the current configuration of the limit.  If
 \fI\-option\fR is the sole argument, return the value of that option.
 Otherwise, a list of \fI\-option\fR/\fIvalue\fR argument pairs must
 supplied. See \fBRESOURCE LIMITS\fR below for a more detailed explanation of
 what limits and options are supported.
 .TP
-\fIslave \fBmarktrusted\fR
+\fIchild \fBmarktrusted\fR
 .
-Marks the slave interpreter as trusted. Can only be invoked by a
+Marks the child interpreter as trusted. Can only be invoked by a
 trusted interpreter. This command does not expose any hidden
-commands in the slave interpreter. The command has no effect if the slave
+commands in the child interpreter. The command has no effect if the child
 is already trusted.
 .TP
-\fIslave\fR \fBrecursionlimit\fR ?\fInewlimit\fR?
+\fIchild\fR \fBrecursionlimit\fR ?\fInewlimit\fR?
 .
-Returns the maximum allowable nesting depth for the \fIslave\fR interpreter.
-If \fInewlimit\fR is specified, the recursion limit in \fIslave\fR will be
+Returns the maximum allowable nesting depth for the \fIchild\fR interpreter.
+If \fInewlimit\fR is specified, the recursion limit in \fIchild\fR will be
 set so that nesting of more than \fInewlimit\fR calls to \fBTcl_Eval()\fR
-and related procedures in \fIslave\fR will return an error.
+and related procedures in \fIchild\fR will return an error.
 The \fInewlimit\fR value is also returned.
 The \fInewlimit\fR value must be a positive integer between 1 and the
 maximum value of a non-long integer on the platform.
@@ -567,14 +573,14 @@ For example, commands to create files on disk are removed, and the
 \fBexec\fR command is removed, since it could be used to cause damage
 through subprocesses.
 Limited access to these facilities can be provided, by creating
-aliases to the master interpreter which check their arguments carefully
+aliases to the parent interpreter which check their arguments carefully
 and provide restricted access to a safe subset of facilities.
 For example, file creation might be allowed in a particular subdirectory
 and subprocess invocation might be allowed for a carefully selected and
 fixed set of programs.
 .PP
 A safe interpreter is created by specifying the \fB\-safe\fR switch
-to the \fBinterp create\fR command.  Furthermore, any slave created
+to the \fBinterp create\fR command.  Furthermore, any child created
 by a safe interpreter will also be safe.
 .PP
 A safe interpreter is created with exactly the following set of
@@ -661,15 +667,15 @@ including itself.
 .SH "ALIAS INVOCATION"
 .PP
 The alias mechanism has been carefully designed so that it can
-be used safely when an untrusted script is executing
-in a safe slave and the target of the alias is a trusted
-master.  The most important thing in guaranteeing safety is to
-ensure that information passed from the slave to the master is
-never evaluated or substituted in the master;  if this were to
-occur, it would enable an evil script in the slave to invoke
-arbitrary functions in the master, which would compromise security.
-.PP
-When the source for an alias is invoked in the slave interpreter, the
+be used safely in an untrusted script which is being executed in a
+safe interpreter even if the target of the alias is not a safe
+interpreter.  The most important thing in guaranteeing safety is to
+ensure that information passed from the child to the parent is
+never evaluated or substituted in the parent;  if this were to
+occur, it would enable an evil script in the child to invoke
+arbitrary functions in the parent, which would compromise security.
+.PP
+When the source for an alias is invoked in the child interpreter, the
 usual Tcl substitutions are performed when parsing that command.
 These substitutions are carried out in the source interpreter just
 as they would be for any other command invoked in that interpreter.
@@ -696,8 +702,8 @@ the alias's source command is parsed in the source interpreter.
 When writing the \fItargetCmd\fRs for aliases in safe interpreters,
 it is very important that the arguments to that command never be
 evaluated or substituted, since this would provide an escape
-mechanism whereby the slave interpreter could execute arbitrary
-code in the master.  This in turn would compromise the security
+mechanism whereby the child interpreter could execute arbitrary
+code in the parent.  This in turn would compromise the security
 of the system.
 .SH "HIDDEN COMMANDS"
 .PP
@@ -724,28 +730,28 @@ invoke\fR. Hidden commands and exposed commands reside in separate name
 spaces. It is possible to define a hidden command and an exposed command by
 the same name within one interpreter.
 .PP
-Hidden commands in a slave interpreter can be invoked in the body of
-procedures called in the master during alias invocation. For example, an
-alias for \fBsource\fR could be created in a slave interpreter. When it is
-invoked in the slave interpreter, a procedure is called in the master
+Hidden commands in a child interpreter can be invoked in the body of
+procedures called in the parent during alias invocation. For example, an
+alias for \fBsource\fR could be created in a child interpreter. When it is
+invoked in the child interpreter, a procedure is called in the parent
 interpreter to check that the operation is allowable (e.g. it asks to
-source a file that the slave interpreter is allowed to access). The
-procedure then it invokes the hidden \fBsource\fR command in the slave
+source a file that the child interpreter is allowed to access). The
+procedure then it invokes the hidden \fBsource\fR command in the child
 interpreter to actually source in the contents of the file. Note that two
-commands named \fBsource\fR exist in the slave interpreter: the alias, and
+commands named \fBsource\fR exist in the child interpreter: the alias, and
 the hidden command.
 .PP
-Because a master interpreter may invoke a hidden command as part of
+Because a parent interpreter may invoke a hidden command as part of
 handling an alias invocation, great care must be taken to avoid evaluating
 any arguments passed in through the alias invocation.
-Otherwise, malicious slave interpreters could cause a trusted master
+Otherwise, malicious child interpreters could cause a trusted parent
 interpreter to execute dangerous commands on their behalf. See the section
 on \fBALIAS INVOCATION\fR for a more complete discussion of this topic.
 To help avoid this problem, no substitutions or evaluations are
 applied to arguments of \fBinterp invokehidden\fR.
 .PP
 Safe interpreters are not allowed to invoke hidden commands in themselves
-or in their descendants. This prevents safe slaves from gaining access to
+or in their descendants. This prevents them from gaining access to
 hidden functionality in themselves or their descendants.
 .PP
 The set of hidden commands in an interpreter can be manipulated by a trusted
@@ -764,12 +770,12 @@ qualifiers, and you must first rename a command in a namespace to the
 global namespace before you can hide it.
 Commands to be hidden by \fBinterp hide\fR are looked up in the global
 namespace even if the current namespace is not the global one. This
-prevents slaves from fooling a master interpreter into hiding the wrong
+prevents children from fooling a parent interpreter into hiding the wrong
 command, by making the current namespace be different from the global one.
 .SH "RESOURCE LIMITS"
 .PP
 Every interpreter has two kinds of resource limits that may be imposed by any
-master interpreter upon its slaves. Command limits (of type \fBcommand\fR)
+parent interpreter upon its children. Command limits (of type \fBcommand\fR)
 restrict the total number of Tcl commands that may be executed by an
 interpreter (as can be inspected via the \fBinfo cmdcount\fR command), and
 time limits (of type \fBtime\fR) place a limit by which execution within the
@@ -778,7 +784,7 @@ interpreter must complete. Note that time limits are expressed as
 \fBafter\fR) because they may be modified after creation.
 .PP
 When a limit is exceeded for an interpreter, first any handler callbacks
-defined by master interpreters are called. If those callbacks increase or
+defined by parent interpreters are called. If those callbacks increase or
 remove the limit, execution within the (previously) limited interpreter
 continues. If the limit is still in force, an error is generated at that point
 and normal processing of errors within the interpreter (by the \fBcatch\fR
@@ -835,13 +841,13 @@ This option specifies the number of commands that the interpreter may execute
 before triggering the command limit. This option may be the empty string,
 which indicates that a command limit is not set for the interpreter.
 .PP
-Where an interpreter with a resource limit set on it creates a slave
-interpreter, that slave interpreter will have resource limits imposed on it
-that are at least as restrictive as the limits on the creating master
-interpreter. If the master interpreter of the limited master wishes to relax
+Where an interpreter with a resource limit set on it creates a child
+interpreter, that child interpreter will have resource limits imposed on it
+that are at least as restrictive as the limits on the creating parent
+interpreter. If the parent interpreter of the limited parent wishes to relax
 these conditions, it should hide the \fBinterp\fR command in the child and
 then use aliases and the \fBinterp invokehidden\fR subcommand to provide such
-access as it chooses to the \fBinterp\fR command to the limited master as
+access as it chooses to the \fBinterp\fR command to the limited parent as
 necessary.
 .SH "BACKGROUND EXCEPTION HANDLING"
 .PP
@@ -902,9 +908,9 @@ set i [\fBinterp create\fR]
 }
 .CE
 .SH "SEE ALSO"
-bgerror(n), load(n), safe(n), Tcl_CreateSlave(3), Tcl_Eval(3), Tcl_BackgroundException(3)
+bgerror(n), load(n), safe(n), Tcl_CreateChild(3), Tcl_Eval(3), Tcl_BackgroundException(3)
 .SH KEYWORDS
-alias, master interpreter, safe interpreter, slave interpreter
+alias, parent interpreter, safe interpreter, child interpreter
 '\"Local Variables:
 '\"mode: nroff
 '\"End:
index c8179bb..23a7697 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH join n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index a324ca3..80d075a 100644 (file)
@@ -5,7 +5,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH lappend n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index e250729..5620de6 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH lassign n 8.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 6f8f265..87f13bd 100644 (file)
@@ -124,7 +124,7 @@ will read all the \fB.tcl\fR files in subdirectory \fBfoo\fR and
 generate a new index file \fBfoo/tclIndex\fR.
 .PP
 \fBAuto_mkindex\fR parses the Tcl scripts by sourcing them into a
-slave interpreter and monitoring the proc and namespace commands that
+child interpreter and monitoring the proc and namespace commands that
 are executed.  Extensions can use the (undocumented)
 auto_mkindex_parser package to register other commands that can
 contribute to the auto_load index. You will have to read through
index d5605bc..5b04b26 100644 (file)
@@ -1,7 +1,7 @@
 '\"
 '\" Copyright (c) 1993 The Regents of the University of California.
 '\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
-'\" Copyright (c) 2001 by Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
+'\" Copyright (c) 2001 Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index c2797f3..a182fc8 100644 (file)
@@ -5,7 +5,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH list n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 2ab8f2e..b592bb3 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH load n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 466339d..52a17f0 100644 (file)
@@ -1,9 +1,9 @@
 '\"
-'\" Copyright (c) 2003 by Simon Geard.  All rights reserved.
+'\" Copyright (c) 2003 Simon Geard.  All rights reserved.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH lrepeat n 8.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 51a9e57..a2a02a5 100644 (file)
@@ -1,9 +1,9 @@
 '\"
-'\" Copyright (c) 2006 by Donal K. Fellows.  All rights reserved.
+'\" Copyright (c) 2006 Donal K. Fellows.  All rights reserved.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH lreverse n 8.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index c2644b8..efe1792 100644 (file)
@@ -22,7 +22,8 @@ This command searches the elements of \fIlist\fR to see if one
 of them matches \fIpattern\fR.  If so, the command returns the index
 of the first matching element
 (unless the options \fB\-all\fR or \fB\-inline\fR are specified.)
-If not, the command returns \fB\-1\fR.  The \fIoption\fR arguments
+If not, the command returns \fB\-1\fR or (if options \fB\-all\fR
+or \fB\-inline\fR are specified) the empty string.  The \fIoption\fR arguments
 indicates how the elements of the list are to be matched against
 \fIpattern\fR and must have one of the values below:
 .SS "MATCHING STYLE OPTIONS"
index e425274..e509641 100644 (file)
@@ -1,5 +1,5 @@
 '\"
-'\" Copyright (c) 2001 by Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
+'\" Copyright (c) 2001 Kevin B. Kenny <kennykb@acm.org>.  All rights reserved.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 7233d46..7a16961 100644 (file)
@@ -1,7 +1,7 @@
 '\"
 '\" Copyright (c) 1993 The Regents of the University of California.
 '\" Copyright (c) 1994-2000 Sun Microsystems, Inc.
-'\" Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved
+'\" Copyright (c) 2005 Kevin B. Kenny <kennykb@acm.org>. All rights reserved
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -295,9 +295,9 @@ are returned as an integer value.
 expr(n), mathop(n), namespace(n)
 .SH "COPYRIGHT"
 .nf
-Copyright (c) 1993 The Regents of the University of California.
-Copyright (c) 1994-2000 Sun Microsystems Incorporated.
-Copyright (c) 2005, 2006 by Kevin B. Kenny <kennykb@acm.org>.
+Copyright \(co 1993 The Regents of the University of California.
+Copyright \(co 1994-2000 Sun Microsystems Incorporated.
+Copyright \(co 2005, 2006 Kevin B. Kenny <kennykb@acm.org>.
 .fi
 '\" Local Variables:
 '\" mode: nroff
index c8cdb21..4d6a7d1 100644 (file)
@@ -1,6 +1,6 @@
 '\"
-'\" Copyright (c) 1992-1999 by Karl Lehenbauer and Mark Diekhans
-'\" Copyright (c) 2000 by Scriptics Corporation.
+'\" Copyright (c) 1992-1999 Karl Lehenbauer & Mark Diekhans
+'\" Copyright (c) 2000 Scriptics Corporation.
 '\" All rights reserved.
 '\"
 .TH memory n 8.1 Tcl "Tcl Built-In Commands"
index 1f4e85f..b0b6e25 100644 (file)
@@ -303,7 +303,7 @@ used for qualified namespace or variable names.
 Sets or returns the unknown command handler for the current namespace.
 The handler is invoked when a command called from within the namespace
 cannot be found in the current namespace, the namespace's path nor in
-the global namespace. 
+the global namespace.
 The \fIscript\fR argument, if given, should be a well
 formed list representing a command name and optional arguments. When
 the handler is invoked, the full invocation line will be appended to the
index 62782e5..db846be 100644 (file)
@@ -138,7 +138,7 @@ before chaining from subclass, args = x 1 2 3 y
 in the superclass, args = a x 1 2 3 y b
 in the superclass, args = pureSynthesis
 after chaining from subclass
-before chaining from subclass, args = 
+before chaining from subclass, args =
 in the superclass, args = a b
 in the superclass, args = pureSynthesis
 after chaining from subclass
index 61e7eca..bce22fe 100644 (file)
@@ -1,7 +1,7 @@
 '\"
-'\" Copyright (c) 1998-2000 by Scriptics Corporation.
+'\" Copyright (c) 1998-2000 Scriptics Corporation.
 '\" All rights reserved.
-'\" 
+'\"
 .TH pkg::create n 8.3 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index a4df2f3..6f8c399 100644 (file)
--- a/doc/pid.n
+++ b/doc/pid.n
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH pid n 7.0 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index ec39be9..5a6b905 100644 (file)
@@ -42,7 +42,7 @@ The default pattern is \fB*.tcl\fR and \fB*.[info sharedlibextension]\fR.
 \fBPkg_mkIndex\fR will create a file \fBpkgIndex.tcl\fR in \fIdir\fR
 with package information about all the files given by the \fIpattern\fR
 arguments.
-It does this by loading each file into a slave
+It does this by loading each file into a child
 interpreter and seeing what packages
 and new commands appear (this is why it is essential to have
 \fBpackage provide\fR commands or \fBTcl_PkgProvide\fR calls
@@ -109,7 +109,7 @@ the use of \fIauto_reset\fR, and therefore its use is discouraged.
 .TP 15
 \fB\-load \fIpkgPat\fR
 The index process will pre-load any packages that exist in the
-current interpreter and match \fIpkgPat\fR into the slave interpreter used to
+current interpreter and match \fIpkgPat\fR into the child interpreter used to
 generate the index.  The pattern match uses string match rules, but without
 making case distinctions.
 See \fBCOMPLEX CASES\fR below.
index 6abc289..5380ff4 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH "platform" n 1.0.4 platform "Tcl Bundled Packages"
 .so man.macros
 .BS
index 64a2e46..330afa9 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH "platform::shell" n 1.1.4 platform::shell "Tcl Bundled Packages"
 .so man.macros
 .BS
index 344ade7..50aa2fb 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH prefix n 8.6 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 01ca122..f4e1040 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH puts n 7.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 31d378f..85dd390 100644 (file)
--- a/doc/pwd.n
+++ b/doc/pwd.n
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH pwd n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 7988071..4504a58 100644 (file)
@@ -293,12 +293,12 @@ treatment is as if the enclosing delimiters were
 .QW \fB[.\fR \&
 and
 .QW \fB.]\fR .)
-For example, if \fBo\fR and \fB\*(qo\fR are the members of an
+For example, if \fBo\fR and \fB\(^o\fR are the members of an
 equivalence class, then
 .QW \fB[[=o=]]\fR ,
-.QW \fB[[=\*(qo=]]\fR ,
+.QW \fB[[=\(^o=]]\fR ,
 and
-.QW \fB[o\*(qo]\fR \&
+.QW \fB[o\(^o]\fR \&
 are all synonymous. An equivalence class may not be an endpoint of a range.
 .RS
 .PP
index 2232d50..8737556 100644 (file)
@@ -1,4 +1,4 @@
-'\" 
+'\"
 '\" Copyright (c) 2006 Andreas Kupries <andreas_kupries@users.sourceforge.net>
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
index 001def9..ec5910c 100644 (file)
@@ -152,7 +152,7 @@ nulls.
 .TP
 \fBsz\fR
 .
-The registry value contains a null-terminated string.  The data is 
+The registry value contains a null-terminated string.  The data is
 represented in Tcl as a string.
 .TP
 \fBexpand_sz\fR
index 744bf5a..f74db5f 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH rename n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index b39f2c2..819287d 100644 (file)
 .SH NAME
 safe \- Creating and manipulating safe interpreters
 .SH SYNOPSIS
-\fB::safe::interpCreate\fR ?\fIslave\fR? ?\fIoptions...\fR?
+\fB::safe::interpCreate\fR ?\fIchild\fR? ?\fIoptions...\fR?
 .sp
-\fB::safe::interpInit\fR \fIslave\fR ?\fIoptions...\fR?
+\fB::safe::interpInit\fR \fIchild\fR ?\fIoptions...\fR?
 .sp
-\fB::safe::interpConfigure\fR \fIslave\fR ?\fIoptions...\fR?
+\fB::safe::interpConfigure\fR \fIchild\fR ?\fIoptions...\fR?
 .sp
-\fB::safe::interpDelete\fR \fIslave\fR
+\fB::safe::interpDelete\fR \fIchild\fR
 .sp
-\fB::safe::interpAddToAccessPath\fR \fIslave\fR \fIdirectory\fR
+\fB::safe::interpAddToAccessPath\fR \fIchild\fR \fIdirectory\fR
 .sp
-\fB::safe::interpFindInAccessPath\fR \fIslave\fR \fIdirectory\fR
+\fB::safe::interpFindInAccessPath\fR \fIchild\fR \fIdirectory\fR
 .sp
 \fB::safe::setLogCmd\fR ?\fIcmd arg...\fR?
 .SS OPTIONS
@@ -44,7 +44,7 @@ application or computer. Untrusted scripts are also prevented from
 disclosing information stored on the hosting computer or in the
 hosting application to any party.
 .PP
-Safe Tcl allows a master interpreter to create safe, restricted
+Safe Tcl allows a parent interpreter to create safe, restricted
 interpreters that contain a set of predefined aliases for the \fBsource\fR,
 \fBload\fR, \fBfile\fR, \fBencoding\fR, and \fBexit\fR commands and
 are able to use the auto-loading and package mechanisms.
@@ -53,39 +53,47 @@ No knowledge of the file system structure is leaked to the
 safe interpreter, because it has access only to a virtualized path
 containing tokens. When the safe interpreter requests to source a file, it
 uses the token in the virtual path as part of the file name to source; the
-master interpreter transparently
+parent interpreter transparently
 translates the token into a real directory name and executes the
 requested operation (see the section \fBSECURITY\fR below for details).
 Different levels of security can be selected by using the optional flags
 of the commands described below.
 .PP
-All commands provided in the master interpreter by Safe Tcl reside in
+All commands provided in the parent interpreter by Safe Tcl reside in
 the \fBsafe\fR namespace.
 .SH COMMANDS
-The following commands are provided in the master interpreter:
+The following commands are provided in the parent interpreter:
 .TP
-\fB::safe::interpCreate\fR ?\fIslave\fR? ?\fIoptions...\fR?
+\fB::safe::interpCreate\fR ?\fIchild\fR? ?\fIoptions...\fR?
 Creates a safe interpreter, installs the aliases described in the section
 \fBALIASES\fR and initializes the auto-loading and package mechanism as
 specified by the supplied \fIoptions\fR.
 See the \fBOPTIONS\fR section below for a description of the
 optional arguments.
-If the \fIslave\fR argument is omitted, a name will be generated.
+If the \fIchild\fR argument is omitted, a name will be generated.
 \fB::safe::interpCreate\fR always returns the interpreter name.
+.sp
+The interpreter name \fIchild\fR may include namespace separators,
+but may not have leading or trailing namespace separators, or excess
+colon characters in namespace separators.  The interpreter name is
+qualified relative to the global namespace ::, not the namespace in which
+the \fB::safe::interpCreate\fR command is evaluated.
 .TP
-\fB::safe::interpInit\fR \fIslave\fR ?\fIoptions...\fR?
+\fB::safe::interpInit\fR \fIchild\fR ?\fIoptions...\fR?
 This command is similar to \fBinterpCreate\fR except it that does not
-create the safe interpreter. \fIslave\fR must have been created by some
-other means, like \fBinterp create\fR \fB\-safe\fR.
+create the safe interpreter. \fIchild\fR must have been created by some
+other means, like \fBinterp create\fR \fB\-safe\fR.  The interpreter
+name \fIchild\fR may include namespace separators, subject to the same
+restrictions as for \fBinterpCreate\fR.
 .TP
-\fB::safe::interpConfigure\fR \fIslave\fR ?\fIoptions...\fR?
+\fB::safe::interpConfigure\fR \fIchild\fR ?\fIoptions...\fR?
 If no \fIoptions\fR are given, returns the settings for all options for the
 named safe interpreter as a list of options and their current values
-for that \fIslave\fR.
+for that \fIchild\fR.
 If a single additional argument is provided,
 it will return a list of 2 elements \fIname\fR and \fIvalue\fR where
 \fIname\fR is the full name of that option and \fIvalue\fR the current value
-for that option and the \fIslave\fR.
+for that option and the \fIchild\fR.
 If more than two additional arguments are provided, it will reconfigure the
 safe interpreter and change each and only the provided options.
 See the section on \fBOPTIONS\fR below for options description.
@@ -105,14 +113,14 @@ safe::interpConfigure $i0  \-delete {foo bar} \-statics 0
 .CE
 .RE
 .TP
-\fB::safe::interpDelete\fR \fIslave\fR
+\fB::safe::interpDelete\fR \fIchild\fR
 Deletes the safe interpreter and cleans up the corresponding
-master interpreter data structures.
+parent interpreter data structures.
 If a \fIdeleteHook\fR script was specified for this interpreter it is
 evaluated before the interpreter is deleted, with the name of the
 interpreter as an additional argument.
 .TP
-\fB::safe::interpFindInAccessPath\fR \fIslave\fR \fIdirectory\fR
+\fB::safe::interpFindInAccessPath\fR \fIchild\fR \fIdirectory\fR
 This command finds and returns the token for the real directory
 \fIdirectory\fR in the safe interpreter's current virtual access path.
 It generates an error if the directory is not found.
@@ -120,14 +128,14 @@ Example of use:
 .RS
 .PP
 .CS
-$slave eval [list set tk_library \e
+$child eval [list set tk_library \e
       [::safe::interpFindInAccessPath $name $tk_library]]
 .CE
 .RE
 .TP
-\fB::safe::interpAddToAccessPath\fR \fIslave\fR \fIdirectory\fR
+\fB::safe::interpAddToAccessPath\fR \fIchild\fR \fIdirectory\fR
 This command adds \fIdirectory\fR to the virtual path maintained for the
-safe interpreter in the master, and returns the token that can be used in
+safe interpreter in the parent, and returns the token that can be used in
 the safe interpreter to obtain access to files in that directory.
 If the directory is already in the virtual path, it only returns the token
 without adding the directory to the virtual path again.
@@ -135,7 +143,7 @@ Example of use:
 .RS
 .PP
 .CS
-$slave eval [list set tk_library \e
+$child eval [list set tk_library \e
       [::safe::interpAddToAccessPath $name $tk_library]]
 .CE
 .RE
@@ -168,10 +176,10 @@ Note that the safe interpreter only received an error message saying that
 the file was not found:
 .PP
 .CS
-NOTICE for slave interp10 : Created
-NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
-NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
-ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory
+NOTICE for child interp10 : Created
+NOTICE for child interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
+NOTICE for child interp10 : auto_path in interp10 has been set to {$p(:0:)}
+ERROR for child interp10 : /foo/bar/init.tcl: no such file or directory
 .CE
 .RE
 .SS OPTIONS
@@ -187,7 +195,7 @@ This option sets the list of directories from which the safe interpreter
 can \fBsource\fR and \fBload\fR files.
 If this option is not specified, or if it is given as the
 empty list, the safe interpreter will use the same directories as its
-master for auto-loading.
+parent for auto-loading.
 See the section \fBSECURITY\fR below for more detail about virtual paths,
 tokens and access control.
 .TP
@@ -216,7 +224,7 @@ to load packages into its own sub-interpreters.
 .TP
 \fB\-deleteHook\fR \fIscript\fR
 When this option is given a non-empty \fIscript\fR, it will be
-evaluated in the master with the name of
+evaluated in the parent with the name of
 the safe interpreter as an additional argument
 just before actually deleting the safe interpreter.
 Giving an empty value removes any currently installed deletion hook
@@ -281,8 +289,8 @@ potential for information leakage about its directory structure.
 To prevent this, commands that take file names as arguments in a safe
 interpreter use tokens instead of the real directory names.
 These tokens are translated to the real directory name while a request to,
-e.g., source a file is mediated by the master interpreter.
-This virtual path system is maintained in the master interpreter for each safe
+e.g., source a file is mediated by the parent interpreter.
+This virtual path system is maintained in the parent interpreter for each safe
 interpreter created by \fB::safe::interpCreate\fR or initialized by
 \fB::safe::interpInit\fR and
 the path maps tokens accessible in the safe interpreter into real path
@@ -291,7 +299,7 @@ from gaining knowledge about the
 structure of the file system of the host on which the interpreter is
 executing.
 The only valid file names arguments
-for the \fBsource\fR and \fBload\fR aliases provided to the slave
+for the \fBsource\fR and \fBload\fR aliases provided to the child
 are path in the form of
 \fB[file join \fItoken filename\fB]\fR (i.e. when using the
 native file path formats: \fItoken\fB/\fIfilename\fR
@@ -320,26 +328,26 @@ or be called
 .PP
 Each element of the initial access path
 list will be assigned a token that will be set in
-the slave \fBauto_path\fR and the first element of that list will be set as
-the \fBtcl_library\fR for that slave.
+the child \fBauto_path\fR and the first element of that list will be set as
+the \fBtcl_library\fR for that child.
 .PP
 If the access path argument is not given or is the empty list,
-the default behavior is to let the slave access the same packages
-as the master has access to (Or to be more precise:
+the default behavior is to let the child access the same packages
+as the parent has access to (Or to be more precise:
 only packages written in Tcl (which by definition cannot be dangerous
-as they run in the slave interpreter) and C extensions that
-provides a _SafeInit entry point). For that purpose, the master's
-\fBauto_path\fR will be used to construct the slave access path.
-In order that the slave successfully loads the Tcl library files
+as they run in the child interpreter) and C extensions that
+provides a _SafeInit entry point). For that purpose, the parent's
+\fBauto_path\fR will be used to construct the child access path.
+In order that the child successfully loads the Tcl library files
 (which includes the auto-loading mechanism itself) the \fBtcl_library\fR will be
 added or moved to the first position if necessary, in the
-slave access path, so the slave
-\fBtcl_library\fR will be the same as the master's (its real
-path will still be invisible to the slave though).
-In order that auto-loading works the same for the slave and
-the master in this by default case, the first-level
-sub directories of each directory in the master \fBauto_path\fR will
-also be added (if not already included) to the slave access path.
+child access path, so the child
+\fBtcl_library\fR will be the same as the parent's (its real
+path will still be invisible to the child though).
+In order that auto-loading works the same for the child and
+the parent in this by default case, the first-level
+sub directories of each directory in the parent \fBauto_path\fR will
+also be added (if not already included) to the child access path.
 You can always specify a more
 restrictive path for which sub directories will never be searched by
 explicitly specifying your directory list with the \fB\-accessPath\fR flag
@@ -352,8 +360,8 @@ to synchronize its \fBauto_index\fR with the new token list.
 .SH "SEE ALSO"
 interp(n), library(n), load(n), package(n), source(n), unknown(n)
 .SH KEYWORDS
-alias, auto\-loading, auto_mkindex, load, master interpreter, safe
-interpreter, slave interpreter, source
+alias, auto\-loading, auto_mkindex, load, parent interpreter, safe
+interpreter, child interpreter, source
 '\" Local Variables:
 '\" mode: nroff
 '\" End:
index 02c5341..3b206d1 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH seek n 8.1 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 3efdb37..aa25bd4 100644 (file)
@@ -1,6 +1,6 @@
 '\"
 '\" Copyright (c) 1996 Sun Microsystems, Inc.
-'\" Copyright (c) 1998-1999 by Scriptics Corporation.
+'\" Copyright (c) 1998-1999 Scriptics Corporation.
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 67d4b6b..82fefa6 100644 (file)
@@ -5,7 +5,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH source n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index f1c66d0..e977d7c 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH split n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 6e27f56..70eeb09 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH switch n 8.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 926c608..24eb902 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH tailcall n 8.6 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 6ed5eb6..fa0ecc2 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH tclsh 1 "" Tcl "Tcl Applications"
 .so man.macros
 .BS
@@ -44,7 +44,7 @@ If this character is present in the file, the \fBtclsh\fR application
 will read text up to but not including the character.  An application
 that requires this character in the file may safely encode it as
 .QW \e032 ,
-.QW \ex1a ,
+.QW \ex1A ,
 or
 .QW \eu001a ;
 or may generate it by use of commands such as \fBformat\fR or \fBbinary\fR.
index b161a2b..25e5e5e 100644 (file)
@@ -203,7 +203,7 @@ array. Returns an empty string.
 .TP
 \fBrunAllTests\fR
 .
-This is a master command meant to run an entire suite of tests,
+This is a main command meant to run an entire suite of tests,
 spanning multiple files and/or directories, as governed by
 the configurable options of \fBtcltest\fR.  See \fBRUNNING ALL TESTS\fR
 below for a complete description of the many variations possible
@@ -804,17 +804,17 @@ then a copy of \fBinterpreter\fR will be \fBexec\fR'd to
 evaluate each file.  The multi-process operation is useful
 when testing can cause errors so severe that a process
 terminates.  Although such an error may terminate a child
-process evaluating one file, the master process can continue
+process evaluating one file, the main process can continue
 with the rest of the test suite.  In multi-process operation,
-the configuration of \fBtcltest\fR in the master process is
+the configuration of \fBtcltest\fR in the main process is
 passed to the child processes as command line arguments,
 with the exception of \fBconfigure \-outfile\fR.  The
 \fBrunAllTests\fR command in the
-master process collects all output from the child processes
-and collates their results into one master report.  Any
+main process collects all output from the child processes
+and collates their results into one main report.  Any
 reports of individual test failures, or messages requested
 by a \fBconfigure \-verbose\fR setting are passed directly
-on to \fBoutputChannel\fR by the master process.
+on to \fBoutputChannel\fR by the main process.
 .PP
 After evaluating all selected test files, a summary of the
 results is printed to \fBoutputChannel\fR.  The summary
@@ -1134,7 +1134,7 @@ A good namespace to use is a child namespace \fBtest\fR of the namespace
 of the module you are testing.
 .PP
 A test file should also be able to be evaluated directly as a script,
-not depending on being called by a master \fBrunAllTests\fR.  This
+not depending on being called by a main \fBrunAllTests\fR.  This
 means that each test file should process command line arguments to give
 the tester all the configuration control that \fBtcltest\fR provides.
 .PP
@@ -1145,7 +1145,7 @@ Here is a sketch of a sample test file illustrating those points:
 .RS
 .PP
 .CS
-package require tcltest 2.2
+package require tcltest 2.5
 eval \fB::tcltest::configure\fR $argv
 package require example
 namespace eval ::example::test {
@@ -1175,12 +1175,12 @@ doing any necessary setup.  This script is usually named \fBall.tcl\fR
 because that is the default name used by \fBrunAllTests\fR when combining
 multiple test suites into one testing run.
 .IP [8]
-Here is a sketch of a sample test suite master script:
+Here is a sketch of a sample test suite main script:
 .RS
 .PP
 .CS
-package require Tcl 8.4
-package require tcltest 2.2
+package require Tcl 8.6
+package require tcltest 2.5
 package require example
 \fB::tcltest::configure\fR -testdir \e
         [file dirname [file normalize [info script]]]
index e8bf3af..1da240d 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH tell n 8.1 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 0d1df78..0d096f4 100644 (file)
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH throw n 8.6 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 35b41c4..bea974f 100644 (file)
@@ -4,7 +4,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH time n "" Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index 5602686..d5c3cc7 100644 (file)
--- a/doc/tm.n
+++ b/doc/tm.n
@@ -3,7 +3,7 @@
 '\"
 '\" See the file "license.terms" for information on usage and redistribution
 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-'\" 
+'\"
 .TH tm n 8.5 Tcl "Tcl Built-In Commands"
 .so man.macros
 .BS
index fd29e0d..3714fc1 100644 (file)
@@ -193,10 +193,18 @@ How hard to compress the data. Must be an integer from 0 (uncompressed) to 9
 .TP
 \fB\-limit\fI readaheadLimit\fR
 .
-The maximum number of bytes ahead to read when decompressing. This defaults to
-1, which ensures that data is always decompressed correctly, but may be
-increased to improve performance. This is more useful when the channel is
-non-blocking.
+The maximum number of bytes ahead to read when decompressing.
+.RS
+.PP
+This option has become \fBirrelevant\fR. It was originally introduced
+to prevent Tcl from reading beyond the end of a compressed stream in
+multi-stream channels to ensure that the data after was left alone for
+further reading, at the cost of speed.
+.PP
+Tcl now automatically returns any bytes it has read beyond the end of
+a compressed stream back to the channel, making them appear as unread
+to further readers.
+.RE
 .PP
 Both compressing and decompressing channel transformations add extra
 configuration options that may be accessed through \fBchan configure\fR. The
@@ -238,10 +246,8 @@ off the data stream.
 \fB\-limit\fI readaheadLimit\fR
 .
 This read-write option is used by decompressing channels to control the
-maximum number of bytes ahead to read from the underlying data source. This
-defaults to 1, which ensures that data is always decompressed correctly, but
-may be increased to improve performance. This is more useful when the channel
-is non-blocking.
+maximum number of bytes ahead to read from the underlying data source. See
+above for more information.
 .RE
 .SS "STREAMING SUBCOMMAND"
 .TP
index fba2fc7..1b00b71 100644 (file)
@@ -259,15 +259,15 @@ static const chr brbacks[] = {    /* \s within brackets */
 
 #define PUNCT_CONN \
        CHR('_'), \
-       0x203f /* UNDERTIE */, \
+       0x203F /* UNDERTIE */, \
        0x2040 /* CHARACTER TIE */,\
        0x2054 /* INVERTED UNDERTIE */,\
-       0xfe33 /* PRESENTATION FORM FOR VERTICAL LOW LINE */, \
-       0xfe34 /* PRESENTATION FORM FOR VERTICAL WAVY LOW LINE */, \
-       0xfe4d /* DASHED LOW LINE */, \
-       0xfe4e /* CENTRELINE LOW LINE */, \
-       0xfe4f /* WAVY LOW LINE */, \
-       0xff3f /* FULLWIDTH LOW LINE */
+       0xFE33 /* PRESENTATION FORM FOR VERTICAL LOW LINE */, \
+       0xFE34 /* PRESENTATION FORM FOR VERTICAL WAVY LOW LINE */, \
+       0xFE4D /* DASHED LOW LINE */, \
+       0xFE4E /* CENTRELINE LOW LINE */, \
+       0xFE4F /* WAVY LOW LINE */, \
+       0xFF3F /* FULLWIDTH LOW LINE */
 
 static const chr backw[] = {   /* \w */
     CHR('['), CHR('['), CHR(':'),
@@ -914,7 +914,7 @@ lexescape(
        if (ISERR()) {
            FAILW(REG_EESCAPE);
        }
-       if (c > 0xff) {
+       if (c > 0xFF) {
            /* out of range, so we handled one digit too much */
            v->now--;
            c >>= 3;
@@ -948,7 +948,7 @@ lexdigits(
 
     n = 0;
     for (len = 0; len < maxlen && !ATEOS(); len++) {
-       if (n > 0x10fff) {
+       if (n > 0x10FFF) {
            /* Stop when continuing would otherwise overflow */
            break;
        }
index 6efab07..493f1bb 100644 (file)
@@ -134,149 +134,152 @@ typedef struct {
  */
 
 static const crange alphaRangeTable[] = {
-    {0x41, 0x5a}, {0x61, 0x7a}, {0xc0, 0xd6}, {0xd8, 0xf6},
-    {0xf8, 0x2c1}, {0x2c6, 0x2d1}, {0x2e0, 0x2e4}, {0x370, 0x374},
-    {0x37a, 0x37d}, {0x388, 0x38a}, {0x38e, 0x3a1}, {0x3a3, 0x3f5},
-    {0x3f7, 0x481}, {0x48a, 0x52f}, {0x531, 0x556}, {0x560, 0x588},
-    {0x5d0, 0x5ea}, {0x5ef, 0x5f2}, {0x620, 0x64a}, {0x671, 0x6d3},
-    {0x6fa, 0x6fc}, {0x712, 0x72f}, {0x74d, 0x7a5}, {0x7ca, 0x7ea},
-    {0x800, 0x815}, {0x840, 0x858}, {0x860, 0x86a}, {0x8a0, 0x8b4},
-    {0x8b6, 0x8bd}, {0x904, 0x939}, {0x958, 0x961}, {0x971, 0x980},
-    {0x985, 0x98c}, {0x993, 0x9a8}, {0x9aa, 0x9b0}, {0x9b6, 0x9b9},
-    {0x9df, 0x9e1}, {0xa05, 0xa0a}, {0xa13, 0xa28}, {0xa2a, 0xa30},
-    {0xa59, 0xa5c}, {0xa72, 0xa74}, {0xa85, 0xa8d}, {0xa8f, 0xa91},
-    {0xa93, 0xaa8}, {0xaaa, 0xab0}, {0xab5, 0xab9}, {0xb05, 0xb0c},
-    {0xb13, 0xb28}, {0xb2a, 0xb30}, {0xb35, 0xb39}, {0xb5f, 0xb61},
-    {0xb85, 0xb8a}, {0xb8e, 0xb90}, {0xb92, 0xb95}, {0xba8, 0xbaa},
-    {0xbae, 0xbb9}, {0xc05, 0xc0c}, {0xc0e, 0xc10}, {0xc12, 0xc28},
-    {0xc2a, 0xc39}, {0xc58, 0xc5a}, {0xc85, 0xc8c}, {0xc8e, 0xc90},
-    {0xc92, 0xca8}, {0xcaa, 0xcb3}, {0xcb5, 0xcb9}, {0xd05, 0xd0c},
-    {0xd0e, 0xd10}, {0xd12, 0xd3a}, {0xd54, 0xd56}, {0xd5f, 0xd61},
-    {0xd7a, 0xd7f}, {0xd85, 0xd96}, {0xd9a, 0xdb1}, {0xdb3, 0xdbb},
-    {0xdc0, 0xdc6}, {0xe01, 0xe30}, {0xe40, 0xe46}, {0xe86, 0xe8a},
-    {0xe8c, 0xea3}, {0xea7, 0xeb0}, {0xec0, 0xec4}, {0xedc, 0xedf},
-    {0xf40, 0xf47}, {0xf49, 0xf6c}, {0xf88, 0xf8c}, {0x1000, 0x102a},
-    {0x1050, 0x1055}, {0x105a, 0x105d}, {0x106e, 0x1070}, {0x1075, 0x1081},
-    {0x10a0, 0x10c5}, {0x10d0, 0x10fa}, {0x10fc, 0x1248}, {0x124a, 0x124d},
-    {0x1250, 0x1256}, {0x125a, 0x125d}, {0x1260, 0x1288}, {0x128a, 0x128d},
-    {0x1290, 0x12b0}, {0x12b2, 0x12b5}, {0x12b8, 0x12be}, {0x12c2, 0x12c5},
-    {0x12c8, 0x12d6}, {0x12d8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135a},
-    {0x1380, 0x138f}, {0x13a0, 0x13f5}, {0x13f8, 0x13fd}, {0x1401, 0x166c},
-    {0x166f, 0x167f}, {0x1681, 0x169a}, {0x16a0, 0x16ea}, {0x16f1, 0x16f8},
-    {0x1700, 0x170c}, {0x170e, 0x1711}, {0x1720, 0x1731}, {0x1740, 0x1751},
-    {0x1760, 0x176c}, {0x176e, 0x1770}, {0x1780, 0x17b3}, {0x1820, 0x1878},
-    {0x1880, 0x1884}, {0x1887, 0x18a8}, {0x18b0, 0x18f5}, {0x1900, 0x191e},
-    {0x1950, 0x196d}, {0x1970, 0x1974}, {0x1980, 0x19ab}, {0x19b0, 0x19c9},
-    {0x1a00, 0x1a16}, {0x1a20, 0x1a54}, {0x1b05, 0x1b33}, {0x1b45, 0x1b4b},
-    {0x1b83, 0x1ba0}, {0x1bba, 0x1be5}, {0x1c00, 0x1c23}, {0x1c4d, 0x1c4f},
-    {0x1c5a, 0x1c7d}, {0x1c80, 0x1c88}, {0x1c90, 0x1cba}, {0x1cbd, 0x1cbf},
-    {0x1ce9, 0x1cec}, {0x1cee, 0x1cf3}, {0x1d00, 0x1dbf}, {0x1e00, 0x1f15},
-    {0x1f18, 0x1f1d}, {0x1f20, 0x1f45}, {0x1f48, 0x1f4d}, {0x1f50, 0x1f57},
-    {0x1f5f, 0x1f7d}, {0x1f80, 0x1fb4}, {0x1fb6, 0x1fbc}, {0x1fc2, 0x1fc4},
-    {0x1fc6, 0x1fcc}, {0x1fd0, 0x1fd3}, {0x1fd6, 0x1fdb}, {0x1fe0, 0x1fec},
-    {0x1ff2, 0x1ff4}, {0x1ff6, 0x1ffc}, {0x2090, 0x209c}, {0x210a, 0x2113},
-    {0x2119, 0x211d}, {0x212a, 0x212d}, {0x212f, 0x2139}, {0x213c, 0x213f},
-    {0x2145, 0x2149}, {0x2c00, 0x2c2e}, {0x2c30, 0x2c5e}, {0x2c60, 0x2ce4},
-    {0x2ceb, 0x2cee}, {0x2d00, 0x2d25}, {0x2d30, 0x2d67}, {0x2d80, 0x2d96},
-    {0x2da0, 0x2da6}, {0x2da8, 0x2dae}, {0x2db0, 0x2db6}, {0x2db8, 0x2dbe},
-    {0x2dc0, 0x2dc6}, {0x2dc8, 0x2dce}, {0x2dd0, 0x2dd6}, {0x2dd8, 0x2dde},
-    {0x3031, 0x3035}, {0x3041, 0x3096}, {0x309d, 0x309f}, {0x30a1, 0x30fa},
-    {0x30fc, 0x30ff}, {0x3105, 0x312f}, {0x3131, 0x318e}, {0x31a0, 0x31ba},
-    {0x31f0, 0x31ff}, {0x3400, 0x4db5}, {0x4e00, 0x9fef}, {0xa000, 0xa48c},
-    {0xa4d0, 0xa4fd}, {0xa500, 0xa60c}, {0xa610, 0xa61f}, {0xa640, 0xa66e},
-    {0xa67f, 0xa69d}, {0xa6a0, 0xa6e5}, {0xa717, 0xa71f}, {0xa722, 0xa788},
-    {0xa78b, 0xa7bf}, {0xa7c2, 0xa7c6}, {0xa7f7, 0xa801}, {0xa803, 0xa805},
-    {0xa807, 0xa80a}, {0xa80c, 0xa822}, {0xa840, 0xa873}, {0xa882, 0xa8b3},
-    {0xa8f2, 0xa8f7}, {0xa90a, 0xa925}, {0xa930, 0xa946}, {0xa960, 0xa97c},
-    {0xa984, 0xa9b2}, {0xa9e0, 0xa9e4}, {0xa9e6, 0xa9ef}, {0xa9fa, 0xa9fe},
-    {0xaa00, 0xaa28}, {0xaa40, 0xaa42}, {0xaa44, 0xaa4b}, {0xaa60, 0xaa76},
-    {0xaa7e, 0xaaaf}, {0xaab9, 0xaabd}, {0xaadb, 0xaadd}, {0xaae0, 0xaaea},
-    {0xaaf2, 0xaaf4}, {0xab01, 0xab06}, {0xab09, 0xab0e}, {0xab11, 0xab16},
-    {0xab20, 0xab26}, {0xab28, 0xab2e}, {0xab30, 0xab5a}, {0xab5c, 0xab67},
-    {0xab70, 0xabe2}, {0xac00, 0xd7a3}, {0xd7b0, 0xd7c6}, {0xd7cb, 0xd7fb},
-    {0xf900, 0xfa6d}, {0xfa70, 0xfad9}, {0xfb00, 0xfb06}, {0xfb13, 0xfb17},
-    {0xfb1f, 0xfb28}, {0xfb2a, 0xfb36}, {0xfb38, 0xfb3c}, {0xfb46, 0xfbb1},
-    {0xfbd3, 0xfd3d}, {0xfd50, 0xfd8f}, {0xfd92, 0xfdc7}, {0xfdf0, 0xfdfb},
-    {0xfe70, 0xfe74}, {0xfe76, 0xfefc}, {0xff21, 0xff3a}, {0xff41, 0xff5a},
-    {0xff66, 0xffbe}, {0xffc2, 0xffc7}, {0xffca, 0xffcf}, {0xffd2, 0xffd7},
-    {0xffda, 0xffdc}
+    {0x41, 0x5A}, {0x61, 0x7A}, {0xC0, 0xD6}, {0xD8, 0xF6},
+    {0xF8, 0x2C1}, {0x2C6, 0x2D1}, {0x2E0, 0x2E4}, {0x370, 0x374},
+    {0x37A, 0x37D}, {0x388, 0x38A}, {0x38E, 0x3A1}, {0x3A3, 0x3F5},
+    {0x3F7, 0x481}, {0x48A, 0x52F}, {0x531, 0x556}, {0x560, 0x588},
+    {0x5D0, 0x5EA}, {0x5EF, 0x5F2}, {0x620, 0x64A}, {0x671, 0x6D3},
+    {0x6FA, 0x6FC}, {0x712, 0x72F}, {0x74D, 0x7A5}, {0x7CA, 0x7EA},
+    {0x800, 0x815}, {0x840, 0x858}, {0x860, 0x86A}, {0x8A0, 0x8B4},
+    {0x8B6, 0x8C7}, {0x904, 0x939}, {0x958, 0x961}, {0x971, 0x980},
+    {0x985, 0x98C}, {0x993, 0x9A8}, {0x9AA, 0x9B0}, {0x9B6, 0x9B9},
+    {0x9DF, 0x9E1}, {0xA05, 0xA0A}, {0xA13, 0xA28}, {0xA2A, 0xA30},
+    {0xA59, 0xA5C}, {0xA72, 0xA74}, {0xA85, 0xA8D}, {0xA8F, 0xA91},
+    {0xA93, 0xAA8}, {0xAAA, 0xAB0}, {0xAB5, 0xAB9}, {0xB05, 0xB0C},
+    {0xB13, 0xB28}, {0xB2A, 0xB30}, {0xB35, 0xB39}, {0xB5F, 0xB61},
+    {0xB85, 0xB8A}, {0xB8E, 0xB90}, {0xB92, 0xB95}, {0xBA8, 0xBAA},
+    {0xBAE, 0xBB9}, {0xC05, 0xC0C}, {0xC0E, 0xC10}, {0xC12, 0xC28},
+    {0xC2A, 0xC39}, {0xC58, 0xC5A}, {0xC85, 0xC8C}, {0xC8E, 0xC90},
+    {0xC92, 0xCA8}, {0xCAA, 0xCB3}, {0xCB5, 0xCB9}, {0xD04, 0xD0C},
+    {0xD0E, 0xD10}, {0xD12, 0xD3A}, {0xD54, 0xD56}, {0xD5F, 0xD61},
+    {0xD7A, 0xD7F}, {0xD85, 0xD96}, {0xD9A, 0xDB1}, {0xDB3, 0xDBB},
+    {0xDC0, 0xDC6}, {0xE01, 0xE30}, {0xE40, 0xE46}, {0xE86, 0xE8A},
+    {0xE8C, 0xEA3}, {0xEA7, 0xEB0}, {0xEC0, 0xEC4}, {0xEDC, 0xEDF},
+    {0xF40, 0xF47}, {0xF49, 0xF6C}, {0xF88, 0xF8C}, {0x1000, 0x102A},
+    {0x1050, 0x1055}, {0x105A, 0x105D}, {0x106E, 0x1070}, {0x1075, 0x1081},
+    {0x10A0, 0x10C5}, {0x10D0, 0x10FA}, {0x10FC, 0x1248}, {0x124A, 0x124D},
+    {0x1250, 0x1256}, {0x125A, 0x125D}, {0x1260, 0x1288}, {0x128A, 0x128D},
+    {0x1290, 0x12B0}, {0x12B2, 0x12B5}, {0x12B8, 0x12BE}, {0x12C2, 0x12C5},
+    {0x12C8, 0x12D6}, {0x12D8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135A},
+    {0x1380, 0x138F}, {0x13A0, 0x13F5}, {0x13F8, 0x13FD}, {0x1401, 0x166C},
+    {0x166F, 0x167F}, {0x1681, 0x169A}, {0x16A0, 0x16EA}, {0x16F1, 0x16F8},
+    {0x1700, 0x170C}, {0x170E, 0x1711}, {0x1720, 0x1731}, {0x1740, 0x1751},
+    {0x1760, 0x176C}, {0x176E, 0x1770}, {0x1780, 0x17B3}, {0x1820, 0x1878},
+    {0x1880, 0x1884}, {0x1887, 0x18A8}, {0x18B0, 0x18F5}, {0x1900, 0x191E},
+    {0x1950, 0x196D}, {0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9},
+    {0x1A00, 0x1A16}, {0x1A20, 0x1A54}, {0x1B05, 0x1B33}, {0x1B45, 0x1B4B},
+    {0x1B83, 0x1BA0}, {0x1BBA, 0x1BE5}, {0x1C00, 0x1C23}, {0x1C4D, 0x1C4F},
+    {0x1C5A, 0x1C7D}, {0x1C80, 0x1C88}, {0x1C90, 0x1CBA}, {0x1CBD, 0x1CBF},
+    {0x1CE9, 0x1CEC}, {0x1CEE, 0x1CF3}, {0x1D00, 0x1DBF}, {0x1E00, 0x1F15},
+    {0x1F18, 0x1F1D}, {0x1F20, 0x1F45}, {0x1F48, 0x1F4D}, {0x1F50, 0x1F57},
+    {0x1F5F, 0x1F7D}, {0x1F80, 0x1FB4}, {0x1FB6, 0x1FBC}, {0x1FC2, 0x1FC4},
+    {0x1FC6, 0x1FCC}, {0x1FD0, 0x1FD3}, {0x1FD6, 0x1FDB}, {0x1FE0, 0x1FEC},
+    {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFC}, {0x2090, 0x209C}, {0x210A, 0x2113},
+    {0x2119, 0x211D}, {0x212A, 0x212D}, {0x212F, 0x2139}, {0x213C, 0x213F},
+    {0x2145, 0x2149}, {0x2C00, 0x2C2E}, {0x2C30, 0x2C5E}, {0x2C60, 0x2CE4},
+    {0x2CEB, 0x2CEE}, {0x2D00, 0x2D25}, {0x2D30, 0x2D67}, {0x2D80, 0x2D96},
+    {0x2DA0, 0x2DA6}, {0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE},
+    {0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE}, {0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE},
+    {0x3031, 0x3035}, {0x3041, 0x3096}, {0x309D, 0x309F}, {0x30A1, 0x30FA},
+    {0x30FC, 0x30FF}, {0x3105, 0x312F}, {0x3131, 0x318E}, {0x31A0, 0x31BF},
+    {0x31F0, 0x31FF}, {0x3400, 0x4DBF}, {0x4E00, 0x9FFC}, {0xA000, 0xA48C},
+    {0xA4D0, 0xA4FD}, {0xA500, 0xA60C}, {0xA610, 0xA61F}, {0xA640, 0xA66E},
+    {0xA67F, 0xA69D}, {0xA6A0, 0xA6E5}, {0xA717, 0xA71F}, {0xA722, 0xA788},
+    {0xA78B, 0xA7BF}, {0xA7C2, 0xA7CA}, {0xA7F5, 0xA801}, {0xA803, 0xA805},
+    {0xA807, 0xA80A}, {0xA80C, 0xA822}, {0xA840, 0xA873}, {0xA882, 0xA8B3},
+    {0xA8F2, 0xA8F7}, {0xA90A, 0xA925}, {0xA930, 0xA946}, {0xA960, 0xA97C},
+    {0xA984, 0xA9B2}, {0xA9E0, 0xA9E4}, {0xA9E6, 0xA9EF}, {0xA9FA, 0xA9FE},
+    {0xAA00, 0xAA28}, {0xAA40, 0xAA42}, {0xAA44, 0xAA4B}, {0xAA60, 0xAA76},
+    {0xAA7E, 0xAAAF}, {0xAAB9, 0xAABD}, {0xAADB, 0xAADD}, {0xAAE0, 0xAAEA},
+    {0xAAF2, 0xAAF4}, {0xAB01, 0xAB06}, {0xAB09, 0xAB0E}, {0xAB11, 0xAB16},
+    {0xAB20, 0xAB26}, {0xAB28, 0xAB2E}, {0xAB30, 0xAB5A}, {0xAB5C, 0xAB69},
+    {0xAB70, 0xABE2}, {0xAC00, 0xD7A3}, {0xD7B0, 0xD7C6}, {0xD7CB, 0xD7FB},
+    {0xF900, 0xFA6D}, {0xFA70, 0xFAD9}, {0xFB00, 0xFB06}, {0xFB13, 0xFB17},
+    {0xFB1F, 0xFB28}, {0xFB2A, 0xFB36}, {0xFB38, 0xFB3C}, {0xFB46, 0xFBB1},
+    {0xFBD3, 0xFD3D}, {0xFD50, 0xFD8F}, {0xFD92, 0xFDC7}, {0xFDF0, 0xFDFB},
+    {0xFE70, 0xFE74}, {0xFE76, 0xFEFC}, {0xFF21, 0xFF3A}, {0xFF41, 0xFF5A},
+    {0xFF66, 0xFFBE}, {0xFFC2, 0xFFC7}, {0xFFCA, 0xFFCF}, {0xFFD2, 0xFFD7},
+    {0xFFDA, 0xFFDC}
 #if CHRBITS > 16
-    ,{0x10000, 0x1000b}, {0x1000d, 0x10026}, {0x10028, 0x1003a}, {0x1003f, 0x1004d},
-    {0x10050, 0x1005d}, {0x10080, 0x100fa}, {0x10280, 0x1029c}, {0x102a0, 0x102d0},
-    {0x10300, 0x1031f}, {0x1032d, 0x10340}, {0x10342, 0x10349}, {0x10350, 0x10375},
-    {0x10380, 0x1039d}, {0x103a0, 0x103c3}, {0x103c8, 0x103cf}, {0x10400, 0x1049d},
-    {0x104b0, 0x104d3}, {0x104d8, 0x104fb}, {0x10500, 0x10527}, {0x10530, 0x10563},
+    ,{0x10000, 0x1000B}, {0x1000D, 0x10026}, {0x10028, 0x1003A}, {0x1003F, 0x1004D},
+    {0x10050, 0x1005D}, {0x10080, 0x100FA}, {0x10280, 0x1029C}, {0x102A0, 0x102D0},
+    {0x10300, 0x1031F}, {0x1032D, 0x10340}, {0x10342, 0x10349}, {0x10350, 0x10375},
+    {0x10380, 0x1039D}, {0x103A0, 0x103C3}, {0x103C8, 0x103CF}, {0x10400, 0x1049D},
+    {0x104B0, 0x104D3}, {0x104D8, 0x104FB}, {0x10500, 0x10527}, {0x10530, 0x10563},
     {0x10600, 0x10736}, {0x10740, 0x10755}, {0x10760, 0x10767}, {0x10800, 0x10805},
-    {0x1080a, 0x10835}, {0x1083f, 0x10855}, {0x10860, 0x10876}, {0x10880, 0x1089e},
-    {0x108e0, 0x108f2}, {0x10900, 0x10915}, {0x10920, 0x10939}, {0x10980, 0x109b7},
-    {0x10a10, 0x10a13}, {0x10a15, 0x10a17}, {0x10a19, 0x10a35}, {0x10a60, 0x10a7c},
-    {0x10a80, 0x10a9c}, {0x10ac0, 0x10ac7}, {0x10ac9, 0x10ae4}, {0x10b00, 0x10b35},
-    {0x10b40, 0x10b55}, {0x10b60, 0x10b72}, {0x10b80, 0x10b91}, {0x10c00, 0x10c48},
-    {0x10c80, 0x10cb2}, {0x10cc0, 0x10cf2}, {0x10d00, 0x10d23}, {0x10f00, 0x10f1c},
-    {0x10f30, 0x10f45}, {0x10fe0, 0x10ff6}, {0x11003, 0x11037}, {0x11083, 0x110af},
-    {0x110d0, 0x110e8}, {0x11103, 0x11126}, {0x11150, 0x11172}, {0x11183, 0x111b2},
-    {0x111c1, 0x111c4}, {0x11200, 0x11211}, {0x11213, 0x1122b}, {0x11280, 0x11286},
-    {0x1128a, 0x1128d}, {0x1128f, 0x1129d}, {0x1129f, 0x112a8}, {0x112b0, 0x112de},
-    {0x11305, 0x1130c}, {0x11313, 0x11328}, {0x1132a, 0x11330}, {0x11335, 0x11339},
-    {0x1135d, 0x11361}, {0x11400, 0x11434}, {0x11447, 0x1144a}, {0x11480, 0x114af},
-    {0x11580, 0x115ae}, {0x115d8, 0x115db}, {0x11600, 0x1162f}, {0x11680, 0x116aa},
-    {0x11700, 0x1171a}, {0x11800, 0x1182b}, {0x118a0, 0x118df}, {0x119a0, 0x119a7},
-    {0x119aa, 0x119d0}, {0x11a0b, 0x11a32}, {0x11a5c, 0x11a89}, {0x11ac0, 0x11af8},
-    {0x11c00, 0x11c08}, {0x11c0a, 0x11c2e}, {0x11c72, 0x11c8f}, {0x11d00, 0x11d06},
-    {0x11d0b, 0x11d30}, {0x11d60, 0x11d65}, {0x11d6a, 0x11d89}, {0x11ee0, 0x11ef2},
-    {0x12000, 0x12399}, {0x12480, 0x12543}, {0x13000, 0x1342e}, {0x14400, 0x14646},
-    {0x16800, 0x16a38}, {0x16a40, 0x16a5e}, {0x16ad0, 0x16aed}, {0x16b00, 0x16b2f},
-    {0x16b40, 0x16b43}, {0x16b63, 0x16b77}, {0x16b7d, 0x16b8f}, {0x16e40, 0x16e7f},
-    {0x16f00, 0x16f4a}, {0x16f93, 0x16f9f}, {0x17000, 0x187f7}, {0x18800, 0x18af2},
-    {0x1b000, 0x1b11e}, {0x1b150, 0x1b152}, {0x1b164, 0x1b167}, {0x1b170, 0x1b2fb},
-    {0x1bc00, 0x1bc6a}, {0x1bc70, 0x1bc7c}, {0x1bc80, 0x1bc88}, {0x1bc90, 0x1bc99},
-    {0x1d400, 0x1d454}, {0x1d456, 0x1d49c}, {0x1d4a9, 0x1d4ac}, {0x1d4ae, 0x1d4b9},
-    {0x1d4bd, 0x1d4c3}, {0x1d4c5, 0x1d505}, {0x1d507, 0x1d50a}, {0x1d50d, 0x1d514},
-    {0x1d516, 0x1d51c}, {0x1d51e, 0x1d539}, {0x1d53b, 0x1d53e}, {0x1d540, 0x1d544},
-    {0x1d54a, 0x1d550}, {0x1d552, 0x1d6a5}, {0x1d6a8, 0x1d6c0}, {0x1d6c2, 0x1d6da},
-    {0x1d6dc, 0x1d6fa}, {0x1d6fc, 0x1d714}, {0x1d716, 0x1d734}, {0x1d736, 0x1d74e},
-    {0x1d750, 0x1d76e}, {0x1d770, 0x1d788}, {0x1d78a, 0x1d7a8}, {0x1d7aa, 0x1d7c2},
-    {0x1d7c4, 0x1d7cb}, {0x1e100, 0x1e12c}, {0x1e137, 0x1e13d}, {0x1e2c0, 0x1e2eb},
-    {0x1e800, 0x1e8c4}, {0x1e900, 0x1e943}, {0x1ee00, 0x1ee03}, {0x1ee05, 0x1ee1f},
-    {0x1ee29, 0x1ee32}, {0x1ee34, 0x1ee37}, {0x1ee4d, 0x1ee4f}, {0x1ee67, 0x1ee6a},
-    {0x1ee6c, 0x1ee72}, {0x1ee74, 0x1ee77}, {0x1ee79, 0x1ee7c}, {0x1ee80, 0x1ee89},
-    {0x1ee8b, 0x1ee9b}, {0x1eea1, 0x1eea3}, {0x1eea5, 0x1eea9}, {0x1eeab, 0x1eebb},
-    {0x20000, 0x2a6d6}, {0x2a700, 0x2b734}, {0x2b740, 0x2b81d}, {0x2b820, 0x2cea1},
-    {0x2ceb0, 0x2ebe0}, {0x2f800, 0x2fa1d}
+    {0x1080A, 0x10835}, {0x1083F, 0x10855}, {0x10860, 0x10876}, {0x10880, 0x1089E},
+    {0x108E0, 0x108F2}, {0x10900, 0x10915}, {0x10920, 0x10939}, {0x10980, 0x109B7},
+    {0x10A10, 0x10A13}, {0x10A15, 0x10A17}, {0x10A19, 0x10A35}, {0x10A60, 0x10A7C},
+    {0x10A80, 0x10A9C}, {0x10AC0, 0x10AC7}, {0x10AC9, 0x10AE4}, {0x10B00, 0x10B35},
+    {0x10B40, 0x10B55}, {0x10B60, 0x10B72}, {0x10B80, 0x10B91}, {0x10C00, 0x10C48},
+    {0x10C80, 0x10CB2}, {0x10CC0, 0x10CF2}, {0x10D00, 0x10D23}, {0x10E80, 0x10EA9},
+    {0x10F00, 0x10F1C}, {0x10F30, 0x10F45}, {0x10FB0, 0x10FC4}, {0x10FE0, 0x10FF6},
+    {0x11003, 0x11037}, {0x11083, 0x110AF}, {0x110D0, 0x110E8}, {0x11103, 0x11126},
+    {0x11150, 0x11172}, {0x11183, 0x111B2}, {0x111C1, 0x111C4}, {0x11200, 0x11211},
+    {0x11213, 0x1122B}, {0x11280, 0x11286}, {0x1128A, 0x1128D}, {0x1128F, 0x1129D},
+    {0x1129F, 0x112A8}, {0x112B0, 0x112DE}, {0x11305, 0x1130C}, {0x11313, 0x11328},
+    {0x1132A, 0x11330}, {0x11335, 0x11339}, {0x1135D, 0x11361}, {0x11400, 0x11434},
+    {0x11447, 0x1144A}, {0x1145F, 0x11461}, {0x11480, 0x114AF}, {0x11580, 0x115AE},
+    {0x115D8, 0x115DB}, {0x11600, 0x1162F}, {0x11680, 0x116AA}, {0x11700, 0x1171A},
+    {0x11800, 0x1182B}, {0x118A0, 0x118DF}, {0x118FF, 0x11906}, {0x1190C, 0x11913},
+    {0x11918, 0x1192F}, {0x119A0, 0x119A7}, {0x119AA, 0x119D0}, {0x11A0B, 0x11A32},
+    {0x11A5C, 0x11A89}, {0x11AC0, 0x11AF8}, {0x11C00, 0x11C08}, {0x11C0A, 0x11C2E},
+    {0x11C72, 0x11C8F}, {0x11D00, 0x11D06}, {0x11D0B, 0x11D30}, {0x11D60, 0x11D65},
+    {0x11D6A, 0x11D89}, {0x11EE0, 0x11EF2}, {0x12000, 0x12399}, {0x12480, 0x12543},
+    {0x13000, 0x1342E}, {0x14400, 0x14646}, {0x16800, 0x16A38}, {0x16A40, 0x16A5E},
+    {0x16AD0, 0x16AED}, {0x16B00, 0x16B2F}, {0x16B40, 0x16B43}, {0x16B63, 0x16B77},
+    {0x16B7D, 0x16B8F}, {0x16E40, 0x16E7F}, {0x16F00, 0x16F4A}, {0x16F93, 0x16F9F},
+    {0x17000, 0x187F7}, {0x18800, 0x18CD5}, {0x18D00, 0x18D08}, {0x1B000, 0x1B11E},
+    {0x1B150, 0x1B152}, {0x1B164, 0x1B167}, {0x1B170, 0x1B2FB}, {0x1BC00, 0x1BC6A},
+    {0x1BC70, 0x1BC7C}, {0x1BC80, 0x1BC88}, {0x1BC90, 0x1BC99}, {0x1D400, 0x1D454},
+    {0x1D456, 0x1D49C}, {0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B9}, {0x1D4BD, 0x1D4C3},
+    {0x1D4C5, 0x1D505}, {0x1D507, 0x1D50A}, {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C},
+    {0x1D51E, 0x1D539}, {0x1D53B, 0x1D53E}, {0x1D540, 0x1D544}, {0x1D54A, 0x1D550},
+    {0x1D552, 0x1D6A5}, {0x1D6A8, 0x1D6C0}, {0x1D6C2, 0x1D6DA}, {0x1D6DC, 0x1D6FA},
+    {0x1D6FC, 0x1D714}, {0x1D716, 0x1D734}, {0x1D736, 0x1D74E}, {0x1D750, 0x1D76E},
+    {0x1D770, 0x1D788}, {0x1D78A, 0x1D7A8}, {0x1D7AA, 0x1D7C2}, {0x1D7C4, 0x1D7CB},
+    {0x1E100, 0x1E12C}, {0x1E137, 0x1E13D}, {0x1E2C0, 0x1E2EB}, {0x1E800, 0x1E8C4},
+    {0x1E900, 0x1E943}, {0x1EE00, 0x1EE03}, {0x1EE05, 0x1EE1F}, {0x1EE29, 0x1EE32},
+    {0x1EE34, 0x1EE37}, {0x1EE4D, 0x1EE4F}, {0x1EE67, 0x1EE6A}, {0x1EE6C, 0x1EE72},
+    {0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C}, {0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B},
+    {0x1EEA1, 0x1EEA3}, {0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB}, {0x20000, 0x2A6DD},
+    {0x2A700, 0x2B734}, {0x2B740, 0x2B81D}, {0x2B820, 0x2CEA1}, {0x2CEB0, 0x2EBE0},
+    {0x2F800, 0x2FA1D}, {0x30000, 0x3134A}
 #endif
 };
 
 #define NUM_ALPHA_RANGE (sizeof(alphaRangeTable)/sizeof(crange))
 
 static const chr alphaCharTable[] = {
-    0xaa, 0xb5, 0xba, 0x2ec, 0x2ee, 0x376, 0x377, 0x37f, 0x386,
-    0x38c, 0x559, 0x66e, 0x66f, 0x6d5, 0x6e5, 0x6e6, 0x6ee, 0x6ef,
-    0x6ff, 0x710, 0x7b1, 0x7f4, 0x7f5, 0x7fa, 0x81a, 0x824, 0x828,
-    0x93d, 0x950, 0x98f, 0x990, 0x9b2, 0x9bd, 0x9ce, 0x9dc, 0x9dd,
-    0x9f0, 0x9f1, 0x9fc, 0xa0f, 0xa10, 0xa32, 0xa33, 0xa35, 0xa36,
-    0xa38, 0xa39, 0xa5e, 0xab2, 0xab3, 0xabd, 0xad0, 0xae0, 0xae1,
-    0xaf9, 0xb0f, 0xb10, 0xb32, 0xb33, 0xb3d, 0xb5c, 0xb5d, 0xb71,
-    0xb83, 0xb99, 0xb9a, 0xb9c, 0xb9e, 0xb9f, 0xba3, 0xba4, 0xbd0,
-    0xc3d, 0xc60, 0xc61, 0xc80, 0xcbd, 0xcde, 0xce0, 0xce1, 0xcf1,
-    0xcf2, 0xd3d, 0xd4e, 0xdbd, 0xe32, 0xe33, 0xe81, 0xe82, 0xe84,
-    0xea5, 0xeb2, 0xeb3, 0xebd, 0xec6, 0xf00, 0x103f, 0x1061, 0x1065,
-    0x1066, 0x108e, 0x10c7, 0x10cd, 0x1258, 0x12c0, 0x17d7, 0x17dc, 0x18aa,
-    0x1aa7, 0x1bae, 0x1baf, 0x1cf5, 0x1cf6, 0x1cfa, 0x1f59, 0x1f5b, 0x1f5d,
-    0x1fbe, 0x2071, 0x207f, 0x2102, 0x2107, 0x2115, 0x2124, 0x2126, 0x2128,
-    0x214e, 0x2183, 0x2184, 0x2cf2, 0x2cf3, 0x2d27, 0x2d2d, 0x2d6f, 0x2e2f,
-    0x3005, 0x3006, 0x303b, 0x303c, 0xa62a, 0xa62b, 0xa8fb, 0xa8fd, 0xa8fe,
-    0xa9cf, 0xaa7a, 0xaab1, 0xaab5, 0xaab6, 0xaac0, 0xaac2, 0xfb1d, 0xfb3e,
-    0xfb40, 0xfb41, 0xfb43, 0xfb44
+    0xAA, 0xB5, 0xBA, 0x2EC, 0x2EE, 0x376, 0x377, 0x37F, 0x386,
+    0x38C, 0x559, 0x66E, 0x66F, 0x6D5, 0x6E5, 0x6E6, 0x6EE, 0x6EF,
+    0x6FF, 0x710, 0x7B1, 0x7F4, 0x7F5, 0x7FA, 0x81A, 0x824, 0x828,
+    0x93D, 0x950, 0x98F, 0x990, 0x9B2, 0x9BD, 0x9CE, 0x9DC, 0x9DD,
+    0x9F0, 0x9F1, 0x9FC, 0xA0F, 0xA10, 0xA32, 0xA33, 0xA35, 0xA36,
+    0xA38, 0xA39, 0xA5E, 0xAB2, 0xAB3, 0xABD, 0xAD0, 0xAE0, 0xAE1,
+    0xAF9, 0xB0F, 0xB10, 0xB32, 0xB33, 0xB3D, 0xB5C, 0xB5D, 0xB71,
+    0xB83, 0xB99, 0xB9A, 0xB9C, 0xB9E, 0xB9F, 0xBA3, 0xBA4, 0xBD0,
+    0xC3D, 0xC60, 0xC61, 0xC80, 0xCBD, 0xCDE, 0xCE0, 0xCE1, 0xCF1,
+    0xCF2, 0xD3D, 0xD4E, 0xDBD, 0xE32, 0xE33, 0xE81, 0xE82, 0xE84,
+    0xEA5, 0xEB2, 0xEB3, 0xEBD, 0xEC6, 0xF00, 0x103F, 0x1061, 0x1065,
+    0x1066, 0x108E, 0x10C7, 0x10CD, 0x1258, 0x12C0, 0x17D7, 0x17DC, 0x18AA,
+    0x1AA7, 0x1BAE, 0x1BAF, 0x1CF5, 0x1CF6, 0x1CFA, 0x1F59, 0x1F5B, 0x1F5D,
+    0x1FBE, 0x2071, 0x207F, 0x2102, 0x2107, 0x2115, 0x2124, 0x2126, 0x2128,
+    0x214E, 0x2183, 0x2184, 0x2CF2, 0x2CF3, 0x2D27, 0x2D2D, 0x2D6F, 0x2E2F,
+    0x3005, 0x3006, 0x303B, 0x303C, 0xA62A, 0xA62B, 0xA8FB, 0xA8FD, 0xA8FE,
+    0xA9CF, 0xAA7A, 0xAAB1, 0xAAB5, 0xAAB6, 0xAAC0, 0xAAC2, 0xFB1D, 0xFB3E,
+    0xFB40, 0xFB41, 0xFB43, 0xFB44
 #if CHRBITS > 16
-    ,0x1003c, 0x1003d, 0x10808, 0x10837, 0x10838, 0x1083c, 0x108f4, 0x108f5, 0x109be,
-    0x109bf, 0x10a00, 0x10f27, 0x11144, 0x11176, 0x111da, 0x111dc, 0x11288, 0x1130f,
-    0x11310, 0x11332, 0x11333, 0x1133d, 0x11350, 0x1145f, 0x114c4, 0x114c5, 0x114c7,
-    0x11644, 0x116b8, 0x118ff, 0x119e1, 0x119e3, 0x11a00, 0x11a3a, 0x11a50, 0x11a9d,
-    0x11c40, 0x11d08, 0x11d09, 0x11d46, 0x11d67, 0x11d68, 0x11d98, 0x16f50, 0x16fe0,
-    0x16fe1, 0x16fe3, 0x1d49e, 0x1d49f, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d4bb, 0x1d546,
-    0x1e14e, 0x1e94b, 0x1ee21, 0x1ee22, 0x1ee24, 0x1ee27, 0x1ee39, 0x1ee3b, 0x1ee42,
-    0x1ee47, 0x1ee49, 0x1ee4b, 0x1ee51, 0x1ee52, 0x1ee54, 0x1ee57, 0x1ee59, 0x1ee5b,
-    0x1ee5d, 0x1ee5f, 0x1ee61, 0x1ee62, 0x1ee64, 0x1ee7e
+    ,0x1003C, 0x1003D, 0x10808, 0x10837, 0x10838, 0x1083C, 0x108F4, 0x108F5, 0x109BE,
+    0x109BF, 0x10A00, 0x10EB0, 0x10EB1, 0x10F27, 0x11144, 0x11147, 0x11176, 0x111DA,
+    0x111DC, 0x11288, 0x1130F, 0x11310, 0x11332, 0x11333, 0x1133D, 0x11350, 0x114C4,
+    0x114C5, 0x114C7, 0x11644, 0x116B8, 0x11909, 0x11915, 0x11916, 0x1193F, 0x11941,
+    0x119E1, 0x119E3, 0x11A00, 0x11A3A, 0x11A50, 0x11A9D, 0x11C40, 0x11D08, 0x11D09,
+    0x11D46, 0x11D67, 0x11D68, 0x11D98, 0x11FB0, 0x16F50, 0x16FE0, 0x16FE1, 0x16FE3,
+    0x1D49E, 0x1D49F, 0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D4BB, 0x1D546, 0x1E14E, 0x1E94B,
+    0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49,
+    0x1EE4B, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F,
+    0x1EE61, 0x1EE62, 0x1EE64, 0x1EE7E
 #endif
 };
 
@@ -287,21 +290,21 @@ static const chr alphaCharTable[] = {
  */
 
 static const crange controlRangeTable[] = {
-    {0x0, 0x1f}, {0x7f, 0x9f}, {0x600, 0x605}, {0x200b, 0x200f},
-    {0x202a, 0x202e}, {0x2060, 0x2064}, {0x2066, 0x206f}, {0xe000, 0xf8ff},
-    {0xfff9, 0xfffb}
+    {0x0, 0x1F}, {0x7F, 0x9F}, {0x600, 0x605}, {0x200B, 0x200F},
+    {0x202A, 0x202E}, {0x2060, 0x2064}, {0x2066, 0x206F}, {0xE000, 0xF8FF},
+    {0xFFF9, 0xFFFB}
 #if CHRBITS > 16
-    ,{0x13430, 0x13438}, {0x1bca0, 0x1bca3}, {0x1d173, 0x1d17a}, {0xe0020, 0xe007f},
-    {0xf0000, 0xffffd}, {0x100000, 0x10fffd}
+    ,{0x13430, 0x13438}, {0x1BCA0, 0x1BCA3}, {0x1D173, 0x1D17A}, {0xE0020, 0xE007F},
+    {0xF0000, 0xFFFFD}, {0x100000, 0x10FFFD}
 #endif
 };
 
 #define NUM_CONTROL_RANGE (sizeof(controlRangeTable)/sizeof(crange))
 
 static const chr controlCharTable[] = {
-    0xad, 0x61c, 0x6dd, 0x70f, 0x8e2, 0x180e, 0xfeff
+    0xAD, 0x61C, 0x6DD, 0x70F, 0x8E2, 0x180E, 0xFEFF
 #if CHRBITS > 16
-    ,0x110bd, 0x110cd, 0xe0001
+    ,0x110BD, 0x110CD, 0xE0001
 #endif
 };
 
@@ -312,23 +315,23 @@ static const chr controlCharTable[] = {
  */
 
 static const crange digitRangeTable[] = {
-    {0x30, 0x39}, {0x660, 0x669}, {0x6f0, 0x6f9}, {0x7c0, 0x7c9},
-    {0x966, 0x96f}, {0x9e6, 0x9ef}, {0xa66, 0xa6f}, {0xae6, 0xaef},
-    {0xb66, 0xb6f}, {0xbe6, 0xbef}, {0xc66, 0xc6f}, {0xce6, 0xcef},
-    {0xd66, 0xd6f}, {0xde6, 0xdef}, {0xe50, 0xe59}, {0xed0, 0xed9},
-    {0xf20, 0xf29}, {0x1040, 0x1049}, {0x1090, 0x1099}, {0x17e0, 0x17e9},
-    {0x1810, 0x1819}, {0x1946, 0x194f}, {0x19d0, 0x19d9}, {0x1a80, 0x1a89},
-    {0x1a90, 0x1a99}, {0x1b50, 0x1b59}, {0x1bb0, 0x1bb9}, {0x1c40, 0x1c49},
-    {0x1c50, 0x1c59}, {0xa620, 0xa629}, {0xa8d0, 0xa8d9}, {0xa900, 0xa909},
-    {0xa9d0, 0xa9d9}, {0xa9f0, 0xa9f9}, {0xaa50, 0xaa59}, {0xabf0, 0xabf9},
-    {0xff10, 0xff19}
+    {0x30, 0x39}, {0x660, 0x669}, {0x6F0, 0x6F9}, {0x7C0, 0x7C9},
+    {0x966, 0x96F}, {0x9E6, 0x9EF}, {0xA66, 0xA6F}, {0xAE6, 0xAEF},
+    {0xB66, 0xB6F}, {0xBE6, 0xBEF}, {0xC66, 0xC6F}, {0xCE6, 0xCEF},
+    {0xD66, 0xD6F}, {0xDE6, 0xDEF}, {0xE50, 0xE59}, {0xED0, 0xED9},
+    {0xF20, 0xF29}, {0x1040, 0x1049}, {0x1090, 0x1099}, {0x17E0, 0x17E9},
+    {0x1810, 0x1819}, {0x1946, 0x194F}, {0x19D0, 0x19D9}, {0x1A80, 0x1A89},
+    {0x1A90, 0x1A99}, {0x1B50, 0x1B59}, {0x1BB0, 0x1BB9}, {0x1C40, 0x1C49},
+    {0x1C50, 0x1C59}, {0xA620, 0xA629}, {0xA8D0, 0xA8D9}, {0xA900, 0xA909},
+    {0xA9D0, 0xA9D9}, {0xA9F0, 0xA9F9}, {0xAA50, 0xAA59}, {0xABF0, 0xABF9},
+    {0xFF10, 0xFF19}
 #if CHRBITS > 16
-    ,{0x104a0, 0x104a9}, {0x10d30, 0x10d39}, {0x11066, 0x1106f}, {0x110f0, 0x110f9},
-    {0x11136, 0x1113f}, {0x111d0, 0x111d9}, {0x112f0, 0x112f9}, {0x11450, 0x11459},
-    {0x114d0, 0x114d9}, {0x11650, 0x11659}, {0x116c0, 0x116c9}, {0x11730, 0x11739},
-    {0x118e0, 0x118e9}, {0x11c50, 0x11c59}, {0x11d50, 0x11d59}, {0x11da0, 0x11da9},
-    {0x16a60, 0x16a69}, {0x16b50, 0x16b59}, {0x1d7ce, 0x1d7ff}, {0x1e140, 0x1e149},
-    {0x1e2f0, 0x1e2f9}, {0x1e950, 0x1e959}
+    ,{0x104A0, 0x104A9}, {0x10D30, 0x10D39}, {0x11066, 0x1106F}, {0x110F0, 0x110F9},
+    {0x11136, 0x1113F}, {0x111D0, 0x111D9}, {0x112F0, 0x112F9}, {0x11450, 0x11459},
+    {0x114D0, 0x114D9}, {0x11650, 0x11659}, {0x116C0, 0x116C9}, {0x11730, 0x11739},
+    {0x118E0, 0x118E9}, {0x11950, 0x11959}, {0x11C50, 0x11C59}, {0x11D50, 0x11D59},
+    {0x11DA0, 0x11DA9}, {0x16A60, 0x16A69}, {0x16B50, 0x16B59}, {0x1D7CE, 0x1D7FF},
+    {0x1E140, 0x1E149}, {0x1E2F0, 0x1E2F9}, {0x1E950, 0x1E959}, {0x1FBF0, 0x1FBF9}
 #endif
 };
 
@@ -343,52 +346,52 @@ static const crange digitRangeTable[] = {
  */
 
 static const crange punctRangeTable[] = {
-    {0x21, 0x23}, {0x25, 0x2a}, {0x2c, 0x2f}, {0x5b, 0x5d},
-    {0x55a, 0x55f}, {0x66a, 0x66d}, {0x700, 0x70d}, {0x7f7, 0x7f9},
-    {0x830, 0x83e}, {0xf04, 0xf12}, {0xf3a, 0xf3d}, {0xfd0, 0xfd4},
-    {0x104a, 0x104f}, {0x1360, 0x1368}, {0x16eb, 0x16ed}, {0x17d4, 0x17d6},
-    {0x17d8, 0x17da}, {0x1800, 0x180a}, {0x1aa0, 0x1aa6}, {0x1aa8, 0x1aad},
-    {0x1b5a, 0x1b60}, {0x1bfc, 0x1bff}, {0x1c3b, 0x1c3f}, {0x1cc0, 0x1cc7},
-    {0x2010, 0x2027}, {0x2030, 0x2043}, {0x2045, 0x2051}, {0x2053, 0x205e},
-    {0x2308, 0x230b}, {0x2768, 0x2775}, {0x27e6, 0x27ef}, {0x2983, 0x2998},
-    {0x29d8, 0x29db}, {0x2cf9, 0x2cfc}, {0x2e00, 0x2e2e}, {0x2e30, 0x2e4f},
-    {0x3001, 0x3003}, {0x3008, 0x3011}, {0x3014, 0x301f}, {0xa60d, 0xa60f},
-    {0xa6f2, 0xa6f7}, {0xa874, 0xa877}, {0xa8f8, 0xa8fa}, {0xa9c1, 0xa9cd},
-    {0xaa5c, 0xaa5f}, {0xfe10, 0xfe19}, {0xfe30, 0xfe52}, {0xfe54, 0xfe61},
-    {0xff01, 0xff03}, {0xff05, 0xff0a}, {0xff0c, 0xff0f}, {0xff3b, 0xff3d},
-    {0xff5f, 0xff65}
+    {0x21, 0x23}, {0x25, 0x2A}, {0x2C, 0x2F}, {0x5B, 0x5D},
+    {0x55A, 0x55F}, {0x66A, 0x66D}, {0x700, 0x70D}, {0x7F7, 0x7F9},
+    {0x830, 0x83E}, {0xF04, 0xF12}, {0xF3A, 0xF3D}, {0xFD0, 0xFD4},
+    {0x104A, 0x104F}, {0x1360, 0x1368}, {0x16EB, 0x16ED}, {0x17D4, 0x17D6},
+    {0x17D8, 0x17DA}, {0x1800, 0x180A}, {0x1AA0, 0x1AA6}, {0x1AA8, 0x1AAD},
+    {0x1B5A, 0x1B60}, {0x1BFC, 0x1BFF}, {0x1C3B, 0x1C3F}, {0x1CC0, 0x1CC7},
+    {0x2010, 0x2027}, {0x2030, 0x2043}, {0x2045, 0x2051}, {0x2053, 0x205E},
+    {0x2308, 0x230B}, {0x2768, 0x2775}, {0x27E6, 0x27EF}, {0x2983, 0x2998},
+    {0x29D8, 0x29DB}, {0x2CF9, 0x2CFC}, {0x2E00, 0x2E2E}, {0x2E30, 0x2E4F},
+    {0x3001, 0x3003}, {0x3008, 0x3011}, {0x3014, 0x301F}, {0xA60D, 0xA60F},
+    {0xA6F2, 0xA6F7}, {0xA874, 0xA877}, {0xA8F8, 0xA8FA}, {0xA9C1, 0xA9CD},
+    {0xAA5C, 0xAA5F}, {0xFE10, 0xFE19}, {0xFE30, 0xFE52}, {0xFE54, 0xFE61},
+    {0xFF01, 0xFF03}, {0xFF05, 0xFF0A}, {0xFF0C, 0xFF0F}, {0xFF3B, 0xFF3D},
+    {0xFF5F, 0xFF65}
 #if CHRBITS > 16
-    ,{0x10100, 0x10102}, {0x10a50, 0x10a58}, {0x10af0, 0x10af6}, {0x10b39, 0x10b3f},
-    {0x10b99, 0x10b9c}, {0x10f55, 0x10f59}, {0x11047, 0x1104d}, {0x110be, 0x110c1},
-    {0x11140, 0x11143}, {0x111c5, 0x111c8}, {0x111dd, 0x111df}, {0x11238, 0x1123d},
-    {0x1144b, 0x1144f}, {0x115c1, 0x115d7}, {0x11641, 0x11643}, {0x11660, 0x1166c},
-    {0x1173c, 0x1173e}, {0x11a3f, 0x11a46}, {0x11a9a, 0x11a9c}, {0x11a9e, 0x11aa2},
-    {0x11c41, 0x11c45}, {0x12470, 0x12474}, {0x16b37, 0x16b3b}, {0x16e97, 0x16e9a},
-    {0x1da87, 0x1da8b}
+    ,{0x10100, 0x10102}, {0x10A50, 0x10A58}, {0x10AF0, 0x10AF6}, {0x10B39, 0x10B3F},
+    {0x10B99, 0x10B9C}, {0x10F55, 0x10F59}, {0x11047, 0x1104D}, {0x110BE, 0x110C1},
+    {0x11140, 0x11143}, {0x111C5, 0x111C8}, {0x111DD, 0x111DF}, {0x11238, 0x1123D},
+    {0x1144B, 0x1144F}, {0x115C1, 0x115D7}, {0x11641, 0x11643}, {0x11660, 0x1166C},
+    {0x1173C, 0x1173E}, {0x11944, 0x11946}, {0x11A3F, 0x11A46}, {0x11A9A, 0x11A9C},
+    {0x11A9E, 0x11AA2}, {0x11C41, 0x11C45}, {0x12470, 0x12474}, {0x16B37, 0x16B3B},
+    {0x16E97, 0x16E9A}, {0x1DA87, 0x1DA8B}
 #endif
 };
 
 #define NUM_PUNCT_RANGE (sizeof(punctRangeTable)/sizeof(crange))
 
 static const chr punctCharTable[] = {
-    0x3a, 0x3b, 0x3f, 0x40, 0x5f, 0x7b, 0x7d, 0xa1, 0xa7,
-    0xab, 0xb6, 0xb7, 0xbb, 0xbf, 0x37e, 0x387, 0x589, 0x58a,
-    0x5be, 0x5c0, 0x5c3, 0x5c6, 0x5f3, 0x5f4, 0x609, 0x60a, 0x60c,
-    0x60d, 0x61b, 0x61e, 0x61f, 0x6d4, 0x85e, 0x964, 0x965, 0x970,
-    0x9fd, 0xa76, 0xaf0, 0xc77, 0xc84, 0xdf4, 0xe4f, 0xe5a, 0xe5b,
-    0xf14, 0xf85, 0xfd9, 0xfda, 0x10fb, 0x1400, 0x166e, 0x169b, 0x169c,
-    0x1735, 0x1736, 0x1944, 0x1945, 0x1a1e, 0x1a1f, 0x1c7e, 0x1c7f, 0x1cd3,
-    0x207d, 0x207e, 0x208d, 0x208e, 0x2329, 0x232a, 0x27c5, 0x27c6, 0x29fc,
-    0x29fd, 0x2cfe, 0x2cff, 0x2d70, 0x3030, 0x303d, 0x30a0, 0x30fb, 0xa4fe,
-    0xa4ff, 0xa673, 0xa67e, 0xa8ce, 0xa8cf, 0xa8fc, 0xa92e, 0xa92f, 0xa95f,
-    0xa9de, 0xa9df, 0xaade, 0xaadf, 0xaaf0, 0xaaf1, 0xabeb, 0xfd3e, 0xfd3f,
-    0xfe63, 0xfe68, 0xfe6a, 0xfe6b, 0xff1a, 0xff1b, 0xff1f, 0xff20, 0xff3f,
-    0xff5b, 0xff5d
+    0x3A, 0x3B, 0x3F, 0x40, 0x5F, 0x7B, 0x7D, 0xA1, 0xA7,
+    0xAB, 0xB6, 0xB7, 0xBB, 0xBF, 0x37E, 0x387, 0x589, 0x58A,
+    0x5BE, 0x5C0, 0x5C3, 0x5C6, 0x5F3, 0x5F4, 0x609, 0x60A, 0x60C,
+    0x60D, 0x61B, 0x61E, 0x61F, 0x6D4, 0x85E, 0x964, 0x965, 0x970,
+    0x9FD, 0xA76, 0xAF0, 0xC77, 0xC84, 0xDF4, 0xE4F, 0xE5A, 0xE5B,
+    0xF14, 0xF85, 0xFD9, 0xFDA, 0x10FB, 0x1400, 0x166E, 0x169B, 0x169C,
+    0x1735, 0x1736, 0x1944, 0x1945, 0x1A1E, 0x1A1F, 0x1C7E, 0x1C7F, 0x1CD3,
+    0x207D, 0x207E, 0x208D, 0x208E, 0x2329, 0x232A, 0x27C5, 0x27C6, 0x29FC,
+    0x29FD, 0x2CFE, 0x2CFF, 0x2D70, 0x2E52, 0x3030, 0x303D, 0x30A0, 0x30FB,
+    0xA4FE, 0xA4FF, 0xA673, 0xA67E, 0xA8CE, 0xA8CF, 0xA8FC, 0xA92E, 0xA92F,
+    0xA95F, 0xA9DE, 0xA9DF, 0xAADE, 0xAADF, 0xAAF0, 0xAAF1, 0xABEB, 0xFD3E,
+    0xFD3F, 0xFE63, 0xFE68, 0xFE6A, 0xFE6B, 0xFF1A, 0xFF1B, 0xFF1F, 0xFF20,
+    0xFF3F, 0xFF5B, 0xFF5D
 #if CHRBITS > 16
-    ,0x1039f, 0x103d0, 0x1056f, 0x10857, 0x1091f, 0x1093f, 0x10a7f, 0x110bb, 0x110bc,
-    0x11174, 0x11175, 0x111cd, 0x111db, 0x112a9, 0x1145b, 0x1145d, 0x114c6, 0x1183b,
-    0x119e2, 0x11c70, 0x11c71, 0x11ef7, 0x11ef8, 0x11fff, 0x16a6e, 0x16a6f, 0x16af5,
-    0x16b44, 0x16fe2, 0x1bc9f, 0x1e95e, 0x1e95f
+    ,0x1039F, 0x103D0, 0x1056F, 0x10857, 0x1091F, 0x1093F, 0x10A7F, 0x10EAD, 0x110BB,
+    0x110BC, 0x11174, 0x11175, 0x111CD, 0x111DB, 0x112A9, 0x1145A, 0x1145B, 0x1145D,
+    0x114C6, 0x1183B, 0x119E2, 0x11C70, 0x11C71, 0x11EF7, 0x11EF8, 0x11FFF, 0x16A6E,
+    0x16A6F, 0x16AF5, 0x16B44, 0x16FE2, 0x1BC9F, 0x1E95E, 0x1E95F
 #endif
 };
 
@@ -399,14 +402,14 @@ static const chr punctCharTable[] = {
  */
 
 static const crange spaceRangeTable[] = {
-    {0x9, 0xd}, {0x2000, 0x200b}
+    {0x9, 0xD}, {0x2000, 0x200B}
 };
 
 #define NUM_SPACE_RANGE (sizeof(spaceRangeTable)/sizeof(crange))
 
 static const chr spaceCharTable[] = {
-    0x20, 0x85, 0xa0, 0x1680, 0x180e, 0x2028, 0x2029, 0x202f, 0x205f,
-    0x2060, 0x3000, 0xfeff
+    0x20, 0x85, 0xA0, 0x1680, 0x180E, 0x2028, 0x2029, 0x202F, 0x205F,
+    0x2060, 0x3000, 0xFEFF
 };
 
 #define NUM_SPACE_CHAR (sizeof(spaceCharTable)/sizeof(chr))
@@ -416,100 +419,101 @@ static const chr spaceCharTable[] = {
  */
 
 static const crange lowerRangeTable[] = {
-    {0x61, 0x7a}, {0xdf, 0xf6}, {0xf8, 0xff}, {0x17e, 0x180},
-    {0x199, 0x19b}, {0x1bd, 0x1bf}, {0x233, 0x239}, {0x24f, 0x293},
-    {0x295, 0x2af}, {0x37b, 0x37d}, {0x3ac, 0x3ce}, {0x3d5, 0x3d7},
-    {0x3ef, 0x3f3}, {0x430, 0x45f}, {0x560, 0x588}, {0x10d0, 0x10fa},
-    {0x10fd, 0x10ff}, {0x13f8, 0x13fd}, {0x1c80, 0x1c88}, {0x1d00, 0x1d2b},
-    {0x1d6b, 0x1d77}, {0x1d79, 0x1d9a}, {0x1e95, 0x1e9d}, {0x1eff, 0x1f07},
-    {0x1f10, 0x1f15}, {0x1f20, 0x1f27}, {0x1f30, 0x1f37}, {0x1f40, 0x1f45},
-    {0x1f50, 0x1f57}, {0x1f60, 0x1f67}, {0x1f70, 0x1f7d}, {0x1f80, 0x1f87},
-    {0x1f90, 0x1f97}, {0x1fa0, 0x1fa7}, {0x1fb0, 0x1fb4}, {0x1fc2, 0x1fc4},
-    {0x1fd0, 0x1fd3}, {0x1fe0, 0x1fe7}, {0x1ff2, 0x1ff4}, {0x2146, 0x2149},
-    {0x2c30, 0x2c5e}, {0x2c76, 0x2c7b}, {0x2d00, 0x2d25}, {0xa72f, 0xa731},
-    {0xa771, 0xa778}, {0xa793, 0xa795}, {0xab30, 0xab5a}, {0xab60, 0xab67},
-    {0xab70, 0xabbf}, {0xfb00, 0xfb06}, {0xfb13, 0xfb17}, {0xff41, 0xff5a}
+    {0x61, 0x7A}, {0xDF, 0xF6}, {0xF8, 0xFF}, {0x17E, 0x180},
+    {0x199, 0x19B}, {0x1BD, 0x1BF}, {0x233, 0x239}, {0x24F, 0x293},
+    {0x295, 0x2AF}, {0x37B, 0x37D}, {0x3AC, 0x3CE}, {0x3D5, 0x3D7},
+    {0x3EF, 0x3F3}, {0x430, 0x45F}, {0x560, 0x588}, {0x10D0, 0x10FA},
+    {0x10FD, 0x10FF}, {0x13F8, 0x13FD}, {0x1C80, 0x1C88}, {0x1D00, 0x1D2B},
+    {0x1D6B, 0x1D77}, {0x1D79, 0x1D9A}, {0x1E95, 0x1E9D}, {0x1EFF, 0x1F07},
+    {0x1F10, 0x1F15}, {0x1F20, 0x1F27}, {0x1F30, 0x1F37}, {0x1F40, 0x1F45},
+    {0x1F50, 0x1F57}, {0x1F60, 0x1F67}, {0x1F70, 0x1F7D}, {0x1F80, 0x1F87},
+    {0x1F90, 0x1F97}, {0x1FA0, 0x1FA7}, {0x1FB0, 0x1FB4}, {0x1FC2, 0x1FC4},
+    {0x1FD0, 0x1FD3}, {0x1FE0, 0x1FE7}, {0x1FF2, 0x1FF4}, {0x2146, 0x2149},
+    {0x2C30, 0x2C5E}, {0x2C76, 0x2C7B}, {0x2D00, 0x2D25}, {0xA72F, 0xA731},
+    {0xA771, 0xA778}, {0xA793, 0xA795}, {0xAB30, 0xAB5A}, {0xAB60, 0xAB68},
+    {0xAB70, 0xABBF}, {0xFB00, 0xFB06}, {0xFB13, 0xFB17}, {0xFF41, 0xFF5A}
 #if CHRBITS > 16
-    ,{0x10428, 0x1044f}, {0x104d8, 0x104fb}, {0x10cc0, 0x10cf2}, {0x118c0, 0x118df},
-    {0x16e60, 0x16e7f}, {0x1d41a, 0x1d433}, {0x1d44e, 0x1d454}, {0x1d456, 0x1d467},
-    {0x1d482, 0x1d49b}, {0x1d4b6, 0x1d4b9}, {0x1d4bd, 0x1d4c3}, {0x1d4c5, 0x1d4cf},
-    {0x1d4ea, 0x1d503}, {0x1d51e, 0x1d537}, {0x1d552, 0x1d56b}, {0x1d586, 0x1d59f},
-    {0x1d5ba, 0x1d5d3}, {0x1d5ee, 0x1d607}, {0x1d622, 0x1d63b}, {0x1d656, 0x1d66f},
-    {0x1d68a, 0x1d6a5}, {0x1d6c2, 0x1d6da}, {0x1d6dc, 0x1d6e1}, {0x1d6fc, 0x1d714},
-    {0x1d716, 0x1d71b}, {0x1d736, 0x1d74e}, {0x1d750, 0x1d755}, {0x1d770, 0x1d788},
-    {0x1d78a, 0x1d78f}, {0x1d7aa, 0x1d7c2}, {0x1d7c4, 0x1d7c9}, {0x1e922, 0x1e943}
+    ,{0x10428, 0x1044F}, {0x104D8, 0x104FB}, {0x10CC0, 0x10CF2}, {0x118C0, 0x118DF},
+    {0x16E60, 0x16E7F}, {0x1D41A, 0x1D433}, {0x1D44E, 0x1D454}, {0x1D456, 0x1D467},
+    {0x1D482, 0x1D49B}, {0x1D4B6, 0x1D4B9}, {0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D4CF},
+    {0x1D4EA, 0x1D503}, {0x1D51E, 0x1D537}, {0x1D552, 0x1D56B}, {0x1D586, 0x1D59F},
+    {0x1D5BA, 0x1D5D3}, {0x1D5EE, 0x1D607}, {0x1D622, 0x1D63B}, {0x1D656, 0x1D66F},
+    {0x1D68A, 0x1D6A5}, {0x1D6C2, 0x1D6DA}, {0x1D6DC, 0x1D6E1}, {0x1D6FC, 0x1D714},
+    {0x1D716, 0x1D71B}, {0x1D736, 0x1D74E}, {0x1D750, 0x1D755}, {0x1D770, 0x1D788},
+    {0x1D78A, 0x1D78F}, {0x1D7AA, 0x1D7C2}, {0x1D7C4, 0x1D7C9}, {0x1E922, 0x1E943}
 #endif
 };
 
 #define NUM_LOWER_RANGE (sizeof(lowerRangeTable)/sizeof(crange))
 
 static const chr lowerCharTable[] = {
-    0xb5, 0x101, 0x103, 0x105, 0x107, 0x109, 0x10b, 0x10d, 0x10f,
-    0x111, 0x113, 0x115, 0x117, 0x119, 0x11b, 0x11d, 0x11f, 0x121,
-    0x123, 0x125, 0x127, 0x129, 0x12b, 0x12d, 0x12f, 0x131, 0x133,
-    0x135, 0x137, 0x138, 0x13a, 0x13c, 0x13e, 0x140, 0x142, 0x144,
-    0x146, 0x148, 0x149, 0x14b, 0x14d, 0x14f, 0x151, 0x153, 0x155,
-    0x157, 0x159, 0x15b, 0x15d, 0x15f, 0x161, 0x163, 0x165, 0x167,
-    0x169, 0x16b, 0x16d, 0x16f, 0x171, 0x173, 0x175, 0x177, 0x17a,
-    0x17c, 0x183, 0x185, 0x188, 0x18c, 0x18d, 0x192, 0x195, 0x19e,
-    0x1a1, 0x1a3, 0x1a5, 0x1a8, 0x1aa, 0x1ab, 0x1ad, 0x1b0, 0x1b4,
-    0x1b6, 0x1b9, 0x1ba, 0x1c6, 0x1c9, 0x1cc, 0x1ce, 0x1d0, 0x1d2,
-    0x1d4, 0x1d6, 0x1d8, 0x1da, 0x1dc, 0x1dd, 0x1df, 0x1e1, 0x1e3,
-    0x1e5, 0x1e7, 0x1e9, 0x1eb, 0x1ed, 0x1ef, 0x1f0, 0x1f3, 0x1f5,
-    0x1f9, 0x1fb, 0x1fd, 0x1ff, 0x201, 0x203, 0x205, 0x207, 0x209,
-    0x20b, 0x20d, 0x20f, 0x211, 0x213, 0x215, 0x217, 0x219, 0x21b,
-    0x21d, 0x21f, 0x221, 0x223, 0x225, 0x227, 0x229, 0x22b, 0x22d,
-    0x22f, 0x231, 0x23c, 0x23f, 0x240, 0x242, 0x247, 0x249, 0x24b,
-    0x24d, 0x371, 0x373, 0x377, 0x390, 0x3d0, 0x3d1, 0x3d9, 0x3db,
-    0x3dd, 0x3df, 0x3e1, 0x3e3, 0x3e5, 0x3e7, 0x3e9, 0x3eb, 0x3ed,
-    0x3f5, 0x3f8, 0x3fb, 0x3fc, 0x461, 0x463, 0x465, 0x467, 0x469,
-    0x46b, 0x46d, 0x46f, 0x471, 0x473, 0x475, 0x477, 0x479, 0x47b,
-    0x47d, 0x47f, 0x481, 0x48b, 0x48d, 0x48f, 0x491, 0x493, 0x495,
-    0x497, 0x499, 0x49b, 0x49d, 0x49f, 0x4a1, 0x4a3, 0x4a5, 0x4a7,
-    0x4a9, 0x4ab, 0x4ad, 0x4af, 0x4b1, 0x4b3, 0x4b5, 0x4b7, 0x4b9,
-    0x4bb, 0x4bd, 0x4bf, 0x4c2, 0x4c4, 0x4c6, 0x4c8, 0x4ca, 0x4cc,
-    0x4ce, 0x4cf, 0x4d1, 0x4d3, 0x4d5, 0x4d7, 0x4d9, 0x4db, 0x4dd,
-    0x4df, 0x4e1, 0x4e3, 0x4e5, 0x4e7, 0x4e9, 0x4eb, 0x4ed, 0x4ef,
-    0x4f1, 0x4f3, 0x4f5, 0x4f7, 0x4f9, 0x4fb, 0x4fd, 0x4ff, 0x501,
-    0x503, 0x505, 0x507, 0x509, 0x50b, 0x50d, 0x50f, 0x511, 0x513,
-    0x515, 0x517, 0x519, 0x51b, 0x51d, 0x51f, 0x521, 0x523, 0x525,
-    0x527, 0x529, 0x52b, 0x52d, 0x52f, 0x1e01, 0x1e03, 0x1e05, 0x1e07,
-    0x1e09, 0x1e0b, 0x1e0d, 0x1e0f, 0x1e11, 0x1e13, 0x1e15, 0x1e17, 0x1e19,
-    0x1e1b, 0x1e1d, 0x1e1f, 0x1e21, 0x1e23, 0x1e25, 0x1e27, 0x1e29, 0x1e2b,
-    0x1e2d, 0x1e2f, 0x1e31, 0x1e33, 0x1e35, 0x1e37, 0x1e39, 0x1e3b, 0x1e3d,
-    0x1e3f, 0x1e41, 0x1e43, 0x1e45, 0x1e47, 0x1e49, 0x1e4b, 0x1e4d, 0x1e4f,
-    0x1e51, 0x1e53, 0x1e55, 0x1e57, 0x1e59, 0x1e5b, 0x1e5d, 0x1e5f, 0x1e61,
-    0x1e63, 0x1e65, 0x1e67, 0x1e69, 0x1e6b, 0x1e6d, 0x1e6f, 0x1e71, 0x1e73,
-    0x1e75, 0x1e77, 0x1e79, 0x1e7b, 0x1e7d, 0x1e7f, 0x1e81, 0x1e83, 0x1e85,
-    0x1e87, 0x1e89, 0x1e8b, 0x1e8d, 0x1e8f, 0x1e91, 0x1e93, 0x1e9f, 0x1ea1,
-    0x1ea3, 0x1ea5, 0x1ea7, 0x1ea9, 0x1eab, 0x1ead, 0x1eaf, 0x1eb1, 0x1eb3,
-    0x1eb5, 0x1eb7, 0x1eb9, 0x1ebb, 0x1ebd, 0x1ebf, 0x1ec1, 0x1ec3, 0x1ec5,
-    0x1ec7, 0x1ec9, 0x1ecb, 0x1ecd, 0x1ecf, 0x1ed1, 0x1ed3, 0x1ed5, 0x1ed7,
-    0x1ed9, 0x1edb, 0x1edd, 0x1edf, 0x1ee1, 0x1ee3, 0x1ee5, 0x1ee7, 0x1ee9,
-    0x1eeb, 0x1eed, 0x1eef, 0x1ef1, 0x1ef3, 0x1ef5, 0x1ef7, 0x1ef9, 0x1efb,
-    0x1efd, 0x1fb6, 0x1fb7, 0x1fbe, 0x1fc6, 0x1fc7, 0x1fd6, 0x1fd7, 0x1ff6,
-    0x1ff7, 0x210a, 0x210e, 0x210f, 0x2113, 0x212f, 0x2134, 0x2139, 0x213c,
-    0x213d, 0x214e, 0x2184, 0x2c61, 0x2c65, 0x2c66, 0x2c68, 0x2c6a, 0x2c6c,
-    0x2c71, 0x2c73, 0x2c74, 0x2c81, 0x2c83, 0x2c85, 0x2c87, 0x2c89, 0x2c8b,
-    0x2c8d, 0x2c8f, 0x2c91, 0x2c93, 0x2c95, 0x2c97, 0x2c99, 0x2c9b, 0x2c9d,
-    0x2c9f, 0x2ca1, 0x2ca3, 0x2ca5, 0x2ca7, 0x2ca9, 0x2cab, 0x2cad, 0x2caf,
-    0x2cb1, 0x2cb3, 0x2cb5, 0x2cb7, 0x2cb9, 0x2cbb, 0x2cbd, 0x2cbf, 0x2cc1,
-    0x2cc3, 0x2cc5, 0x2cc7, 0x2cc9, 0x2ccb, 0x2ccd, 0x2ccf, 0x2cd1, 0x2cd3,
-    0x2cd5, 0x2cd7, 0x2cd9, 0x2cdb, 0x2cdd, 0x2cdf, 0x2ce1, 0x2ce3, 0x2ce4,
-    0x2cec, 0x2cee, 0x2cf3, 0x2d27, 0x2d2d, 0xa641, 0xa643, 0xa645, 0xa647,
-    0xa649, 0xa64b, 0xa64d, 0xa64f, 0xa651, 0xa653, 0xa655, 0xa657, 0xa659,
-    0xa65b, 0xa65d, 0xa65f, 0xa661, 0xa663, 0xa665, 0xa667, 0xa669, 0xa66b,
-    0xa66d, 0xa681, 0xa683, 0xa685, 0xa687, 0xa689, 0xa68b, 0xa68d, 0xa68f,
-    0xa691, 0xa693, 0xa695, 0xa697, 0xa699, 0xa69b, 0xa723, 0xa725, 0xa727,
-    0xa729, 0xa72b, 0xa72d, 0xa733, 0xa735, 0xa737, 0xa739, 0xa73b, 0xa73d,
-    0xa73f, 0xa741, 0xa743, 0xa745, 0xa747, 0xa749, 0xa74b, 0xa74d, 0xa74f,
-    0xa751, 0xa753, 0xa755, 0xa757, 0xa759, 0xa75b, 0xa75d, 0xa75f, 0xa761,
-    0xa763, 0xa765, 0xa767, 0xa769, 0xa76b, 0xa76d, 0xa76f, 0xa77a, 0xa77c,
-    0xa77f, 0xa781, 0xa783, 0xa785, 0xa787, 0xa78c, 0xa78e, 0xa791, 0xa797,
-    0xa799, 0xa79b, 0xa79d, 0xa79f, 0xa7a1, 0xa7a3, 0xa7a5, 0xa7a7, 0xa7a9,
-    0xa7af, 0xa7b5, 0xa7b7, 0xa7b9, 0xa7bb, 0xa7bd, 0xa7bf, 0xa7c3, 0xa7fa
+    0xB5, 0x101, 0x103, 0x105, 0x107, 0x109, 0x10B, 0x10D, 0x10F,
+    0x111, 0x113, 0x115, 0x117, 0x119, 0x11B, 0x11D, 0x11F, 0x121,
+    0x123, 0x125, 0x127, 0x129, 0x12B, 0x12D, 0x12F, 0x131, 0x133,
+    0x135, 0x137, 0x138, 0x13A, 0x13C, 0x13E, 0x140, 0x142, 0x144,
+    0x146, 0x148, 0x149, 0x14B, 0x14D, 0x14F, 0x151, 0x153, 0x155,
+    0x157, 0x159, 0x15B, 0x15D, 0x15F, 0x161, 0x163, 0x165, 0x167,
+    0x169, 0x16B, 0x16D, 0x16F, 0x171, 0x173, 0x175, 0x177, 0x17A,
+    0x17C, 0x183, 0x185, 0x188, 0x18C, 0x18D, 0x192, 0x195, 0x19E,
+    0x1A1, 0x1A3, 0x1A5, 0x1A8, 0x1AA, 0x1AB, 0x1AD, 0x1B0, 0x1B4,
+    0x1B6, 0x1B9, 0x1BA, 0x1C6, 0x1C9, 0x1CC, 0x1CE, 0x1D0, 0x1D2,
+    0x1D4, 0x1D6, 0x1D8, 0x1DA, 0x1DC, 0x1DD, 0x1DF, 0x1E1, 0x1E3,
+    0x1E5, 0x1E7, 0x1E9, 0x1EB, 0x1ED, 0x1EF, 0x1F0, 0x1F3, 0x1F5,
+    0x1F9, 0x1FB, 0x1FD, 0x1FF, 0x201, 0x203, 0x205, 0x207, 0x209,
+    0x20B, 0x20D, 0x20F, 0x211, 0x213, 0x215, 0x217, 0x219, 0x21B,
+    0x21D, 0x21F, 0x221, 0x223, 0x225, 0x227, 0x229, 0x22B, 0x22D,
+    0x22F, 0x231, 0x23C, 0x23F, 0x240, 0x242, 0x247, 0x249, 0x24B,
+    0x24D, 0x371, 0x373, 0x377, 0x390, 0x3D0, 0x3D1, 0x3D9, 0x3DB,
+    0x3DD, 0x3DF, 0x3E1, 0x3E3, 0x3E5, 0x3E7, 0x3E9, 0x3EB, 0x3ED,
+    0x3F5, 0x3F8, 0x3FB, 0x3FC, 0x461, 0x463, 0x465, 0x467, 0x469,
+    0x46B, 0x46D, 0x46F, 0x471, 0x473, 0x475, 0x477, 0x479, 0x47B,
+    0x47D, 0x47F, 0x481, 0x48B, 0x48D, 0x48F, 0x491, 0x493, 0x495,
+    0x497, 0x499, 0x49B, 0x49D, 0x49F, 0x4A1, 0x4A3, 0x4A5, 0x4A7,
+    0x4A9, 0x4AB, 0x4AD, 0x4AF, 0x4B1, 0x4B3, 0x4B5, 0x4B7, 0x4B9,
+    0x4BB, 0x4BD, 0x4BF, 0x4C2, 0x4C4, 0x4C6, 0x4C8, 0x4CA, 0x4CC,
+    0x4CE, 0x4CF, 0x4D1, 0x4D3, 0x4D5, 0x4D7, 0x4D9, 0x4DB, 0x4DD,
+    0x4DF, 0x4E1, 0x4E3, 0x4E5, 0x4E7, 0x4E9, 0x4EB, 0x4ED, 0x4EF,
+    0x4F1, 0x4F3, 0x4F5, 0x4F7, 0x4F9, 0x4FB, 0x4FD, 0x4FF, 0x501,
+    0x503, 0x505, 0x507, 0x509, 0x50B, 0x50D, 0x50F, 0x511, 0x513,
+    0x515, 0x517, 0x519, 0x51B, 0x51D, 0x51F, 0x521, 0x523, 0x525,
+    0x527, 0x529, 0x52B, 0x52D, 0x52F, 0x1E01, 0x1E03, 0x1E05, 0x1E07,
+    0x1E09, 0x1E0B, 0x1E0D, 0x1E0F, 0x1E11, 0x1E13, 0x1E15, 0x1E17, 0x1E19,
+    0x1E1B, 0x1E1D, 0x1E1F, 0x1E21, 0x1E23, 0x1E25, 0x1E27, 0x1E29, 0x1E2B,
+    0x1E2D, 0x1E2F, 0x1E31, 0x1E33, 0x1E35, 0x1E37, 0x1E39, 0x1E3B, 0x1E3D,
+    0x1E3F, 0x1E41, 0x1E43, 0x1E45, 0x1E47, 0x1E49, 0x1E4B, 0x1E4D, 0x1E4F,
+    0x1E51, 0x1E53, 0x1E55, 0x1E57, 0x1E59, 0x1E5B, 0x1E5D, 0x1E5F, 0x1E61,
+    0x1E63, 0x1E65, 0x1E67, 0x1E69, 0x1E6B, 0x1E6D, 0x1E6F, 0x1E71, 0x1E73,
+    0x1E75, 0x1E77, 0x1E79, 0x1E7B, 0x1E7D, 0x1E7F, 0x1E81, 0x1E83, 0x1E85,
+    0x1E87, 0x1E89, 0x1E8B, 0x1E8D, 0x1E8F, 0x1E91, 0x1E93, 0x1E9F, 0x1EA1,
+    0x1EA3, 0x1EA5, 0x1EA7, 0x1EA9, 0x1EAB, 0x1EAD, 0x1EAF, 0x1EB1, 0x1EB3,
+    0x1EB5, 0x1EB7, 0x1EB9, 0x1EBB, 0x1EBD, 0x1EBF, 0x1EC1, 0x1EC3, 0x1EC5,
+    0x1EC7, 0x1EC9, 0x1ECB, 0x1ECD, 0x1ECF, 0x1ED1, 0x1ED3, 0x1ED5, 0x1ED7,
+    0x1ED9, 0x1EDB, 0x1EDD, 0x1EDF, 0x1EE1, 0x1EE3, 0x1EE5, 0x1EE7, 0x1EE9,
+    0x1EEB, 0x1EED, 0x1EEF, 0x1EF1, 0x1EF3, 0x1EF5, 0x1EF7, 0x1EF9, 0x1EFB,
+    0x1EFD, 0x1FB6, 0x1FB7, 0x1FBE, 0x1FC6, 0x1FC7, 0x1FD6, 0x1FD7, 0x1FF6,
+    0x1FF7, 0x210A, 0x210E, 0x210F, 0x2113, 0x212F, 0x2134, 0x2139, 0x213C,
+    0x213D, 0x214E, 0x2184, 0x2C61, 0x2C65, 0x2C66, 0x2C68, 0x2C6A, 0x2C6C,
+    0x2C71, 0x2C73, 0x2C74, 0x2C81, 0x2C83, 0x2C85, 0x2C87, 0x2C89, 0x2C8B,
+    0x2C8D, 0x2C8F, 0x2C91, 0x2C93, 0x2C95, 0x2C97, 0x2C99, 0x2C9B, 0x2C9D,
+    0x2C9F, 0x2CA1, 0x2CA3, 0x2CA5, 0x2CA7, 0x2CA9, 0x2CAB, 0x2CAD, 0x2CAF,
+    0x2CB1, 0x2CB3, 0x2CB5, 0x2CB7, 0x2CB9, 0x2CBB, 0x2CBD, 0x2CBF, 0x2CC1,
+    0x2CC3, 0x2CC5, 0x2CC7, 0x2CC9, 0x2CCB, 0x2CCD, 0x2CCF, 0x2CD1, 0x2CD3,
+    0x2CD5, 0x2CD7, 0x2CD9, 0x2CDB, 0x2CDD, 0x2CDF, 0x2CE1, 0x2CE3, 0x2CE4,
+    0x2CEC, 0x2CEE, 0x2CF3, 0x2D27, 0x2D2D, 0xA641, 0xA643, 0xA645, 0xA647,
+    0xA649, 0xA64B, 0xA64D, 0xA64F, 0xA651, 0xA653, 0xA655, 0xA657, 0xA659,
+    0xA65B, 0xA65D, 0xA65F, 0xA661, 0xA663, 0xA665, 0xA667, 0xA669, 0xA66B,
+    0xA66D, 0xA681, 0xA683, 0xA685, 0xA687, 0xA689, 0xA68B, 0xA68D, 0xA68F,
+    0xA691, 0xA693, 0xA695, 0xA697, 0xA699, 0xA69B, 0xA723, 0xA725, 0xA727,
+    0xA729, 0xA72B, 0xA72D, 0xA733, 0xA735, 0xA737, 0xA739, 0xA73B, 0xA73D,
+    0xA73F, 0xA741, 0xA743, 0xA745, 0xA747, 0xA749, 0xA74B, 0xA74D, 0xA74F,
+    0xA751, 0xA753, 0xA755, 0xA757, 0xA759, 0xA75B, 0xA75D, 0xA75F, 0xA761,
+    0xA763, 0xA765, 0xA767, 0xA769, 0xA76B, 0xA76D, 0xA76F, 0xA77A, 0xA77C,
+    0xA77F, 0xA781, 0xA783, 0xA785, 0xA787, 0xA78C, 0xA78E, 0xA791, 0xA797,
+    0xA799, 0xA79B, 0xA79D, 0xA79F, 0xA7A1, 0xA7A3, 0xA7A5, 0xA7A7, 0xA7A9,
+    0xA7AF, 0xA7B5, 0xA7B7, 0xA7B9, 0xA7BB, 0xA7BD, 0xA7BF, 0xA7C3, 0xA7C8,
+    0xA7CA, 0xA7F6, 0xA7FA
 #if CHRBITS > 16
-    ,0x1d4bb, 0x1d7cb
+    ,0x1D4BB, 0x1D7CB
 #endif
 };
 
@@ -520,99 +524,99 @@ static const chr lowerCharTable[] = {
  */
 
 static const crange upperRangeTable[] = {
-    {0x41, 0x5a}, {0xc0, 0xd6}, {0xd8, 0xde}, {0x189, 0x18b},
-    {0x18e, 0x191}, {0x196, 0x198}, {0x1b1, 0x1b3}, {0x1f6, 0x1f8},
-    {0x243, 0x246}, {0x388, 0x38a}, {0x391, 0x3a1}, {0x3a3, 0x3ab},
-    {0x3d2, 0x3d4}, {0x3fd, 0x42f}, {0x531, 0x556}, {0x10a0, 0x10c5},
-    {0x13a0, 0x13f5}, {0x1c90, 0x1cba}, {0x1cbd, 0x1cbf}, {0x1f08, 0x1f0f},
-    {0x1f18, 0x1f1d}, {0x1f28, 0x1f2f}, {0x1f38, 0x1f3f}, {0x1f48, 0x1f4d},
-    {0x1f68, 0x1f6f}, {0x1fb8, 0x1fbb}, {0x1fc8, 0x1fcb}, {0x1fd8, 0x1fdb},
-    {0x1fe8, 0x1fec}, {0x1ff8, 0x1ffb}, {0x210b, 0x210d}, {0x2110, 0x2112},
-    {0x2119, 0x211d}, {0x212a, 0x212d}, {0x2130, 0x2133}, {0x2c00, 0x2c2e},
-    {0x2c62, 0x2c64}, {0x2c6d, 0x2c70}, {0x2c7e, 0x2c80}, {0xa7aa, 0xa7ae},
-    {0xa7b0, 0xa7b4}, {0xa7c4, 0xa7c6}, {0xff21, 0xff3a}
+    {0x41, 0x5A}, {0xC0, 0xD6}, {0xD8, 0xDE}, {0x189, 0x18B},
+    {0x18E, 0x191}, {0x196, 0x198}, {0x1B1, 0x1B3}, {0x1F6, 0x1F8},
+    {0x243, 0x246}, {0x388, 0x38A}, {0x391, 0x3A1}, {0x3A3, 0x3AB},
+    {0x3D2, 0x3D4}, {0x3FD, 0x42F}, {0x531, 0x556}, {0x10A0, 0x10C5},
+    {0x13A0, 0x13F5}, {0x1C90, 0x1CBA}, {0x1CBD, 0x1CBF}, {0x1F08, 0x1F0F},
+    {0x1F18, 0x1F1D}, {0x1F28, 0x1F2F}, {0x1F38, 0x1F3F}, {0x1F48, 0x1F4D},
+    {0x1F68, 0x1F6F}, {0x1FB8, 0x1FBB}, {0x1FC8, 0x1FCB}, {0x1FD8, 0x1FDB},
+    {0x1FE8, 0x1FEC}, {0x1FF8, 0x1FFB}, {0x210B, 0x210D}, {0x2110, 0x2112},
+    {0x2119, 0x211D}, {0x212A, 0x212D}, {0x2130, 0x2133}, {0x2C00, 0x2C2E},
+    {0x2C62, 0x2C64}, {0x2C6D, 0x2C70}, {0x2C7E, 0x2C80}, {0xA7AA, 0xA7AE},
+    {0xA7B0, 0xA7B4}, {0xA7C4, 0xA7C7}, {0xFF21, 0xFF3A}
 #if CHRBITS > 16
-    ,{0x10400, 0x10427}, {0x104b0, 0x104d3}, {0x10c80, 0x10cb2}, {0x118a0, 0x118bf},
-    {0x16e40, 0x16e5f}, {0x1d400, 0x1d419}, {0x1d434, 0x1d44d}, {0x1d468, 0x1d481},
-    {0x1d4a9, 0x1d4ac}, {0x1d4ae, 0x1d4b5}, {0x1d4d0, 0x1d4e9}, {0x1d507, 0x1d50a},
-    {0x1d50d, 0x1d514}, {0x1d516, 0x1d51c}, {0x1d53b, 0x1d53e}, {0x1d540, 0x1d544},
-    {0x1d54a, 0x1d550}, {0x1d56c, 0x1d585}, {0x1d5a0, 0x1d5b9}, {0x1d5d4, 0x1d5ed},
-    {0x1d608, 0x1d621}, {0x1d63c, 0x1d655}, {0x1d670, 0x1d689}, {0x1d6a8, 0x1d6c0},
-    {0x1d6e2, 0x1d6fa}, {0x1d71c, 0x1d734}, {0x1d756, 0x1d76e}, {0x1d790, 0x1d7a8},
-    {0x1e900, 0x1e921}
+    ,{0x10400, 0x10427}, {0x104B0, 0x104D3}, {0x10C80, 0x10CB2}, {0x118A0, 0x118BF},
+    {0x16E40, 0x16E5F}, {0x1D400, 0x1D419}, {0x1D434, 0x1D44D}, {0x1D468, 0x1D481},
+    {0x1D4A9, 0x1D4AC}, {0x1D4AE, 0x1D4B5}, {0x1D4D0, 0x1D4E9}, {0x1D507, 0x1D50A},
+    {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C}, {0x1D53B, 0x1D53E}, {0x1D540, 0x1D544},
+    {0x1D54A, 0x1D550}, {0x1D56C, 0x1D585}, {0x1D5A0, 0x1D5B9}, {0x1D5D4, 0x1D5ED},
+    {0x1D608, 0x1D621}, {0x1D63C, 0x1D655}, {0x1D670, 0x1D689}, {0x1D6A8, 0x1D6C0},
+    {0x1D6E2, 0x1D6FA}, {0x1D71C, 0x1D734}, {0x1D756, 0x1D76E}, {0x1D790, 0x1D7A8},
+    {0x1E900, 0x1E921}
 #endif
 };
 
 #define NUM_UPPER_RANGE (sizeof(upperRangeTable)/sizeof(crange))
 
 static const chr upperCharTable[] = {
-    0x100, 0x102, 0x104, 0x106, 0x108, 0x10a, 0x10c, 0x10e, 0x110,
-    0x112, 0x114, 0x116, 0x118, 0x11a, 0x11c, 0x11e, 0x120, 0x122,
-    0x124, 0x126, 0x128, 0x12a, 0x12c, 0x12e, 0x130, 0x132, 0x134,
-    0x136, 0x139, 0x13b, 0x13d, 0x13f, 0x141, 0x143, 0x145, 0x147,
-    0x14a, 0x14c, 0x14e, 0x150, 0x152, 0x154, 0x156, 0x158, 0x15a,
-    0x15c, 0x15e, 0x160, 0x162, 0x164, 0x166, 0x168, 0x16a, 0x16c,
-    0x16e, 0x170, 0x172, 0x174, 0x176, 0x178, 0x179, 0x17b, 0x17d,
-    0x181, 0x182, 0x184, 0x186, 0x187, 0x193, 0x194, 0x19c, 0x19d,
-    0x19f, 0x1a0, 0x1a2, 0x1a4, 0x1a6, 0x1a7, 0x1a9, 0x1ac, 0x1ae,
-    0x1af, 0x1b5, 0x1b7, 0x1b8, 0x1bc, 0x1c4, 0x1c7, 0x1ca, 0x1cd,
-    0x1cf, 0x1d1, 0x1d3, 0x1d5, 0x1d7, 0x1d9, 0x1db, 0x1de, 0x1e0,
-    0x1e2, 0x1e4, 0x1e6, 0x1e8, 0x1ea, 0x1ec, 0x1ee, 0x1f1, 0x1f4,
-    0x1fa, 0x1fc, 0x1fe, 0x200, 0x202, 0x204, 0x206, 0x208, 0x20a,
-    0x20c, 0x20e, 0x210, 0x212, 0x214, 0x216, 0x218, 0x21a, 0x21c,
-    0x21e, 0x220, 0x222, 0x224, 0x226, 0x228, 0x22a, 0x22c, 0x22e,
-    0x230, 0x232, 0x23a, 0x23b, 0x23d, 0x23e, 0x241, 0x248, 0x24a,
-    0x24c, 0x24e, 0x370, 0x372, 0x376, 0x37f, 0x386, 0x38c, 0x38e,
-    0x38f, 0x3cf, 0x3d8, 0x3da, 0x3dc, 0x3de, 0x3e0, 0x3e2, 0x3e4,
-    0x3e6, 0x3e8, 0x3ea, 0x3ec, 0x3ee, 0x3f4, 0x3f7, 0x3f9, 0x3fa,
-    0x460, 0x462, 0x464, 0x466, 0x468, 0x46a, 0x46c, 0x46e, 0x470,
-    0x472, 0x474, 0x476, 0x478, 0x47a, 0x47c, 0x47e, 0x480, 0x48a,
-    0x48c, 0x48e, 0x490, 0x492, 0x494, 0x496, 0x498, 0x49a, 0x49c,
-    0x49e, 0x4a0, 0x4a2, 0x4a4, 0x4a6, 0x4a8, 0x4aa, 0x4ac, 0x4ae,
-    0x4b0, 0x4b2, 0x4b4, 0x4b6, 0x4b8, 0x4ba, 0x4bc, 0x4be, 0x4c0,
-    0x4c1, 0x4c3, 0x4c5, 0x4c7, 0x4c9, 0x4cb, 0x4cd, 0x4d0, 0x4d2,
-    0x4d4, 0x4d6, 0x4d8, 0x4da, 0x4dc, 0x4de, 0x4e0, 0x4e2, 0x4e4,
-    0x4e6, 0x4e8, 0x4ea, 0x4ec, 0x4ee, 0x4f0, 0x4f2, 0x4f4, 0x4f6,
-    0x4f8, 0x4fa, 0x4fc, 0x4fe, 0x500, 0x502, 0x504, 0x506, 0x508,
-    0x50a, 0x50c, 0x50e, 0x510, 0x512, 0x514, 0x516, 0x518, 0x51a,
-    0x51c, 0x51e, 0x520, 0x522, 0x524, 0x526, 0x528, 0x52a, 0x52c,
-    0x52e, 0x10c7, 0x10cd, 0x1e00, 0x1e02, 0x1e04, 0x1e06, 0x1e08, 0x1e0a,
-    0x1e0c, 0x1e0e, 0x1e10, 0x1e12, 0x1e14, 0x1e16, 0x1e18, 0x1e1a, 0x1e1c,
-    0x1e1e, 0x1e20, 0x1e22, 0x1e24, 0x1e26, 0x1e28, 0x1e2a, 0x1e2c, 0x1e2e,
-    0x1e30, 0x1e32, 0x1e34, 0x1e36, 0x1e38, 0x1e3a, 0x1e3c, 0x1e3e, 0x1e40,
-    0x1e42, 0x1e44, 0x1e46, 0x1e48, 0x1e4a, 0x1e4c, 0x1e4e, 0x1e50, 0x1e52,
-    0x1e54, 0x1e56, 0x1e58, 0x1e5a, 0x1e5c, 0x1e5e, 0x1e60, 0x1e62, 0x1e64,
-    0x1e66, 0x1e68, 0x1e6a, 0x1e6c, 0x1e6e, 0x1e70, 0x1e72, 0x1e74, 0x1e76,
-    0x1e78, 0x1e7a, 0x1e7c, 0x1e7e, 0x1e80, 0x1e82, 0x1e84, 0x1e86, 0x1e88,
-    0x1e8a, 0x1e8c, 0x1e8e, 0x1e90, 0x1e92, 0x1e94, 0x1e9e, 0x1ea0, 0x1ea2,
-    0x1ea4, 0x1ea6, 0x1ea8, 0x1eaa, 0x1eac, 0x1eae, 0x1eb0, 0x1eb2, 0x1eb4,
-    0x1eb6, 0x1eb8, 0x1eba, 0x1ebc, 0x1ebe, 0x1ec0, 0x1ec2, 0x1ec4, 0x1ec6,
-    0x1ec8, 0x1eca, 0x1ecc, 0x1ece, 0x1ed0, 0x1ed2, 0x1ed4, 0x1ed6, 0x1ed8,
-    0x1eda, 0x1edc, 0x1ede, 0x1ee0, 0x1ee2, 0x1ee4, 0x1ee6, 0x1ee8, 0x1eea,
-    0x1eec, 0x1eee, 0x1ef0, 0x1ef2, 0x1ef4, 0x1ef6, 0x1ef8, 0x1efa, 0x1efc,
-    0x1efe, 0x1f59, 0x1f5b, 0x1f5d, 0x1f5f, 0x2102, 0x2107, 0x2115, 0x2124,
-    0x2126, 0x2128, 0x213e, 0x213f, 0x2145, 0x2183, 0x2c60, 0x2c67, 0x2c69,
-    0x2c6b, 0x2c72, 0x2c75, 0x2c82, 0x2c84, 0x2c86, 0x2c88, 0x2c8a, 0x2c8c,
-    0x2c8e, 0x2c90, 0x2c92, 0x2c94, 0x2c96, 0x2c98, 0x2c9a, 0x2c9c, 0x2c9e,
-    0x2ca0, 0x2ca2, 0x2ca4, 0x2ca6, 0x2ca8, 0x2caa, 0x2cac, 0x2cae, 0x2cb0,
-    0x2cb2, 0x2cb4, 0x2cb6, 0x2cb8, 0x2cba, 0x2cbc, 0x2cbe, 0x2cc0, 0x2cc2,
-    0x2cc4, 0x2cc6, 0x2cc8, 0x2cca, 0x2ccc, 0x2cce, 0x2cd0, 0x2cd2, 0x2cd4,
-    0x2cd6, 0x2cd8, 0x2cda, 0x2cdc, 0x2cde, 0x2ce0, 0x2ce2, 0x2ceb, 0x2ced,
-    0x2cf2, 0xa640, 0xa642, 0xa644, 0xa646, 0xa648, 0xa64a, 0xa64c, 0xa64e,
-    0xa650, 0xa652, 0xa654, 0xa656, 0xa658, 0xa65a, 0xa65c, 0xa65e, 0xa660,
-    0xa662, 0xa664, 0xa666, 0xa668, 0xa66a, 0xa66c, 0xa680, 0xa682, 0xa684,
-    0xa686, 0xa688, 0xa68a, 0xa68c, 0xa68e, 0xa690, 0xa692, 0xa694, 0xa696,
-    0xa698, 0xa69a, 0xa722, 0xa724, 0xa726, 0xa728, 0xa72a, 0xa72c, 0xa72e,
-    0xa732, 0xa734, 0xa736, 0xa738, 0xa73a, 0xa73c, 0xa73e, 0xa740, 0xa742,
-    0xa744, 0xa746, 0xa748, 0xa74a, 0xa74c, 0xa74e, 0xa750, 0xa752, 0xa754,
-    0xa756, 0xa758, 0xa75a, 0xa75c, 0xa75e, 0xa760, 0xa762, 0xa764, 0xa766,
-    0xa768, 0xa76a, 0xa76c, 0xa76e, 0xa779, 0xa77b, 0xa77d, 0xa77e, 0xa780,
-    0xa782, 0xa784, 0xa786, 0xa78b, 0xa78d, 0xa790, 0xa792, 0xa796, 0xa798,
-    0xa79a, 0xa79c, 0xa79e, 0xa7a0, 0xa7a2, 0xa7a4, 0xa7a6, 0xa7a8, 0xa7b6,
-    0xa7b8, 0xa7ba, 0xa7bc, 0xa7be, 0xa7c2
+    0x100, 0x102, 0x104, 0x106, 0x108, 0x10A, 0x10C, 0x10E, 0x110,
+    0x112, 0x114, 0x116, 0x118, 0x11A, 0x11C, 0x11E, 0x120, 0x122,
+    0x124, 0x126, 0x128, 0x12A, 0x12C, 0x12E, 0x130, 0x132, 0x134,
+    0x136, 0x139, 0x13B, 0x13D, 0x13F, 0x141, 0x143, 0x145, 0x147,
+    0x14A, 0x14C, 0x14E, 0x150, 0x152, 0x154, 0x156, 0x158, 0x15A,
+    0x15C, 0x15E, 0x160, 0x162, 0x164, 0x166, 0x168, 0x16A, 0x16C,
+    0x16E, 0x170, 0x172, 0x174, 0x176, 0x178, 0x179, 0x17B, 0x17D,
+    0x181, 0x182, 0x184, 0x186, 0x187, 0x193, 0x194, 0x19C, 0x19D,
+    0x19F, 0x1A0, 0x1A2, 0x1A4, 0x1A6, 0x1A7, 0x1A9, 0x1AC, 0x1AE,
+    0x1AF, 0x1B5, 0x1B7, 0x1B8, 0x1BC, 0x1C4, 0x1C7, 0x1CA, 0x1CD,
+    0x1CF, 0x1D1, 0x1D3, 0x1D5, 0x1D7, 0x1D9, 0x1DB, 0x1DE, 0x1E0,
+    0x1E2, 0x1E4, 0x1E6, 0x1E8, 0x1EA, 0x1EC, 0x1EE, 0x1F1, 0x1F4,
+    0x1FA, 0x1FC, 0x1FE, 0x200, 0x202, 0x204, 0x206, 0x208, 0x20A,
+    0x20C, 0x20E, 0x210, 0x212, 0x214, 0x216, 0x218, 0x21A, 0x21C,
+    0x21E, 0x220, 0x222, 0x224, 0x226, 0x228, 0x22A, 0x22C, 0x22E,
+    0x230, 0x232, 0x23A, 0x23B, 0x23D, 0x23E, 0x241, 0x248, 0x24A,
+    0x24C, 0x24E, 0x370, 0x372, 0x376, 0x37F, 0x386, 0x38C, 0x38E,
+    0x38F, 0x3CF, 0x3D8, 0x3DA, 0x3DC, 0x3DE, 0x3E0, 0x3E2, 0x3E4,
+    0x3E6, 0x3E8, 0x3EA, 0x3EC, 0x3EE, 0x3F4, 0x3F7, 0x3F9, 0x3FA,
+    0x460, 0x462, 0x464, 0x466, 0x468, 0x46A, 0x46C, 0x46E, 0x470,
+    0x472, 0x474, 0x476, 0x478, 0x47A, 0x47C, 0x47E, 0x480, 0x48A,
+    0x48C, 0x48E, 0x490, 0x492, 0x494, 0x496, 0x498, 0x49A, 0x49C,
+    0x49E, 0x4A0, 0x4A2, 0x4A4, 0x4A6, 0x4A8, 0x4AA, 0x4AC, 0x4AE,
+    0x4B0, 0x4B2, 0x4B4, 0x4B6, 0x4B8, 0x4BA, 0x4BC, 0x4BE, 0x4C0,
+    0x4C1, 0x4C3, 0x4C5, 0x4C7, 0x4C9, 0x4CB, 0x4CD, 0x4D0, 0x4D2,
+    0x4D4, 0x4D6, 0x4D8, 0x4DA, 0x4DC, 0x4DE, 0x4E0, 0x4E2, 0x4E4,
+    0x4E6, 0x4E8, 0x4EA, 0x4EC, 0x4EE, 0x4F0, 0x4F2, 0x4F4, 0x4F6,
+    0x4F8, 0x4FA, 0x4FC, 0x4FE, 0x500, 0x502, 0x504, 0x506, 0x508,
+    0x50A, 0x50C, 0x50E, 0x510, 0x512, 0x514, 0x516, 0x518, 0x51A,
+    0x51C, 0x51E, 0x520, 0x522, 0x524, 0x526, 0x528, 0x52A, 0x52C,
+    0x52E, 0x10C7, 0x10CD, 0x1E00, 0x1E02, 0x1E04, 0x1E06, 0x1E08, 0x1E0A,
+    0x1E0C, 0x1E0E, 0x1E10, 0x1E12, 0x1E14, 0x1E16, 0x1E18, 0x1E1A, 0x1E1C,
+    0x1E1E, 0x1E20, 0x1E22, 0x1E24, 0x1E26, 0x1E28, 0x1E2A, 0x1E2C, 0x1E2E,
+    0x1E30, 0x1E32, 0x1E34, 0x1E36, 0x1E38, 0x1E3A, 0x1E3C, 0x1E3E, 0x1E40,
+    0x1E42, 0x1E44, 0x1E46, 0x1E48, 0x1E4A, 0x1E4C, 0x1E4E, 0x1E50, 0x1E52,
+    0x1E54, 0x1E56, 0x1E58, 0x1E5A, 0x1E5C, 0x1E5E, 0x1E60, 0x1E62, 0x1E64,
+    0x1E66, 0x1E68, 0x1E6A, 0x1E6C, 0x1E6E, 0x1E70, 0x1E72, 0x1E74, 0x1E76,
+    0x1E78, 0x1E7A, 0x1E7C, 0x1E7E, 0x1E80, 0x1E82, 0x1E84, 0x1E86, 0x1E88,
+    0x1E8A, 0x1E8C, 0x1E8E, 0x1E90, 0x1E92, 0x1E94, 0x1E9E, 0x1EA0, 0x1EA2,
+    0x1EA4, 0x1EA6, 0x1EA8, 0x1EAA, 0x1EAC, 0x1EAE, 0x1EB0, 0x1EB2, 0x1EB4,
+    0x1EB6, 0x1EB8, 0x1EBA, 0x1EBC, 0x1EBE, 0x1EC0, 0x1EC2, 0x1EC4, 0x1EC6,
+    0x1EC8, 0x1ECA, 0x1ECC, 0x1ECE, 0x1ED0, 0x1ED2, 0x1ED4, 0x1ED6, 0x1ED8,
+    0x1EDA, 0x1EDC, 0x1EDE, 0x1EE0, 0x1EE2, 0x1EE4, 0x1EE6, 0x1EE8, 0x1EEA,
+    0x1EEC, 0x1EEE, 0x1EF0, 0x1EF2, 0x1EF4, 0x1EF6, 0x1EF8, 0x1EFA, 0x1EFC,
+    0x1EFE, 0x1F59, 0x1F5B, 0x1F5D, 0x1F5F, 0x2102, 0x2107, 0x2115, 0x2124,
+    0x2126, 0x2128, 0x213E, 0x213F, 0x2145, 0x2183, 0x2C60, 0x2C67, 0x2C69,
+    0x2C6B, 0x2C72, 0x2C75, 0x2C82, 0x2C84, 0x2C86, 0x2C88, 0x2C8A, 0x2C8C,
+    0x2C8E, 0x2C90, 0x2C92, 0x2C94, 0x2C96, 0x2C98, 0x2C9A, 0x2C9C, 0x2C9E,
+    0x2CA0, 0x2CA2, 0x2CA4, 0x2CA6, 0x2CA8, 0x2CAA, 0x2CAC, 0x2CAE, 0x2CB0,
+    0x2CB2, 0x2CB4, 0x2CB6, 0x2CB8, 0x2CBA, 0x2CBC, 0x2CBE, 0x2CC0, 0x2CC2,
+    0x2CC4, 0x2CC6, 0x2CC8, 0x2CCA, 0x2CCC, 0x2CCE, 0x2CD0, 0x2CD2, 0x2CD4,
+    0x2CD6, 0x2CD8, 0x2CDA, 0x2CDC, 0x2CDE, 0x2CE0, 0x2CE2, 0x2CEB, 0x2CED,
+    0x2CF2, 0xA640, 0xA642, 0xA644, 0xA646, 0xA648, 0xA64A, 0xA64C, 0xA64E,
+    0xA650, 0xA652, 0xA654, 0xA656, 0xA658, 0xA65A, 0xA65C, 0xA65E, 0xA660,
+    0xA662, 0xA664, 0xA666, 0xA668, 0xA66A, 0xA66C, 0xA680, 0xA682, 0xA684,
+    0xA686, 0xA688, 0xA68A, 0xA68C, 0xA68E, 0xA690, 0xA692, 0xA694, 0xA696,
+    0xA698, 0xA69A, 0xA722, 0xA724, 0xA726, 0xA728, 0xA72A, 0xA72C, 0xA72E,
+    0xA732, 0xA734, 0xA736, 0xA738, 0xA73A, 0xA73C, 0xA73E, 0xA740, 0xA742,
+    0xA744, 0xA746, 0xA748, 0xA74A, 0xA74C, 0xA74E, 0xA750, 0xA752, 0xA754,
+    0xA756, 0xA758, 0xA75A, 0xA75C, 0xA75E, 0xA760, 0xA762, 0xA764, 0xA766,
+    0xA768, 0xA76A, 0xA76C, 0xA76E, 0xA779, 0xA77B, 0xA77D, 0xA77E, 0xA780,
+    0xA782, 0xA784, 0xA786, 0xA78B, 0xA78D, 0xA790, 0xA792, 0xA796, 0xA798,
+    0xA79A, 0xA79C, 0xA79E, 0xA7A0, 0xA7A2, 0xA7A4, 0xA7A6, 0xA7A8, 0xA7B6,
+    0xA7B8, 0xA7BA, 0xA7BC, 0xA7BE, 0xA7C2, 0xA7C9, 0xA7F5
 #if CHRBITS > 16
-    ,0x1d49c, 0x1d49e, 0x1d49f, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d504, 0x1d505, 0x1d538,
-    0x1d539, 0x1d546, 0x1d7ca
+    ,0x1D49C, 0x1D49E, 0x1D49F, 0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D504, 0x1D505, 0x1D538,
+    0x1D539, 0x1D546, 0x1D7CA
 #endif
 };
 
@@ -623,173 +627,176 @@ static const chr upperCharTable[] = {
  */
 
 static const crange graphRangeTable[] = {
-    {0x21, 0x7e}, {0xa1, 0xac}, {0xae, 0x377}, {0x37a, 0x37f},
-    {0x384, 0x38a}, {0x38e, 0x3a1}, {0x3a3, 0x52f}, {0x531, 0x556},
-    {0x559, 0x58a}, {0x58d, 0x58f}, {0x591, 0x5c7}, {0x5d0, 0x5ea},
-    {0x5ef, 0x5f4}, {0x606, 0x61b}, {0x61e, 0x6dc}, {0x6de, 0x70d},
-    {0x710, 0x74a}, {0x74d, 0x7b1}, {0x7c0, 0x7fa}, {0x7fd, 0x82d},
-    {0x830, 0x83e}, {0x840, 0x85b}, {0x860, 0x86a}, {0x8a0, 0x8b4},
-    {0x8b6, 0x8bd}, {0x8d3, 0x8e1}, {0x8e3, 0x983}, {0x985, 0x98c},
-    {0x993, 0x9a8}, {0x9aa, 0x9b0}, {0x9b6, 0x9b9}, {0x9bc, 0x9c4},
-    {0x9cb, 0x9ce}, {0x9df, 0x9e3}, {0x9e6, 0x9fe}, {0xa01, 0xa03},
-    {0xa05, 0xa0a}, {0xa13, 0xa28}, {0xa2a, 0xa30}, {0xa3e, 0xa42},
-    {0xa4b, 0xa4d}, {0xa59, 0xa5c}, {0xa66, 0xa76}, {0xa81, 0xa83},
-    {0xa85, 0xa8d}, {0xa8f, 0xa91}, {0xa93, 0xaa8}, {0xaaa, 0xab0},
-    {0xab5, 0xab9}, {0xabc, 0xac5}, {0xac7, 0xac9}, {0xacb, 0xacd},
-    {0xae0, 0xae3}, {0xae6, 0xaf1}, {0xaf9, 0xaff}, {0xb01, 0xb03},
-    {0xb05, 0xb0c}, {0xb13, 0xb28}, {0xb2a, 0xb30}, {0xb35, 0xb39},
-    {0xb3c, 0xb44}, {0xb4b, 0xb4d}, {0xb5f, 0xb63}, {0xb66, 0xb77},
-    {0xb85, 0xb8a}, {0xb8e, 0xb90}, {0xb92, 0xb95}, {0xba8, 0xbaa},
-    {0xbae, 0xbb9}, {0xbbe, 0xbc2}, {0xbc6, 0xbc8}, {0xbca, 0xbcd},
-    {0xbe6, 0xbfa}, {0xc00, 0xc0c}, {0xc0e, 0xc10}, {0xc12, 0xc28},
-    {0xc2a, 0xc39}, {0xc3d, 0xc44}, {0xc46, 0xc48}, {0xc4a, 0xc4d},
-    {0xc58, 0xc5a}, {0xc60, 0xc63}, {0xc66, 0xc6f}, {0xc77, 0xc8c},
-    {0xc8e, 0xc90}, {0xc92, 0xca8}, {0xcaa, 0xcb3}, {0xcb5, 0xcb9},
-    {0xcbc, 0xcc4}, {0xcc6, 0xcc8}, {0xcca, 0xccd}, {0xce0, 0xce3},
-    {0xce6, 0xcef}, {0xd00, 0xd03}, {0xd05, 0xd0c}, {0xd0e, 0xd10},
-    {0xd12, 0xd44}, {0xd46, 0xd48}, {0xd4a, 0xd4f}, {0xd54, 0xd63},
-    {0xd66, 0xd7f}, {0xd85, 0xd96}, {0xd9a, 0xdb1}, {0xdb3, 0xdbb},
-    {0xdc0, 0xdc6}, {0xdcf, 0xdd4}, {0xdd8, 0xddf}, {0xde6, 0xdef},
-    {0xdf2, 0xdf4}, {0xe01, 0xe3a}, {0xe3f, 0xe5b}, {0xe86, 0xe8a},
-    {0xe8c, 0xea3}, {0xea7, 0xebd}, {0xec0, 0xec4}, {0xec8, 0xecd},
-    {0xed0, 0xed9}, {0xedc, 0xedf}, {0xf00, 0xf47}, {0xf49, 0xf6c},
-    {0xf71, 0xf97}, {0xf99, 0xfbc}, {0xfbe, 0xfcc}, {0xfce, 0xfda},
-    {0x1000, 0x10c5}, {0x10d0, 0x1248}, {0x124a, 0x124d}, {0x1250, 0x1256},
-    {0x125a, 0x125d}, {0x1260, 0x1288}, {0x128a, 0x128d}, {0x1290, 0x12b0},
-    {0x12b2, 0x12b5}, {0x12b8, 0x12be}, {0x12c2, 0x12c5}, {0x12c8, 0x12d6},
-    {0x12d8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135a}, {0x135d, 0x137c},
-    {0x1380, 0x1399}, {0x13a0, 0x13f5}, {0x13f8, 0x13fd}, {0x1400, 0x167f},
-    {0x1681, 0x169c}, {0x16a0, 0x16f8}, {0x1700, 0x170c}, {0x170e, 0x1714},
-    {0x1720, 0x1736}, {0x1740, 0x1753}, {0x1760, 0x176c}, {0x176e, 0x1770},
-    {0x1780, 0x17dd}, {0x17e0, 0x17e9}, {0x17f0, 0x17f9}, {0x1800, 0x180d},
-    {0x1810, 0x1819}, {0x1820, 0x1878}, {0x1880, 0x18aa}, {0x18b0, 0x18f5},
-    {0x1900, 0x191e}, {0x1920, 0x192b}, {0x1930, 0x193b}, {0x1944, 0x196d},
-    {0x1970, 0x1974}, {0x1980, 0x19ab}, {0x19b0, 0x19c9}, {0x19d0, 0x19da},
-    {0x19de, 0x1a1b}, {0x1a1e, 0x1a5e}, {0x1a60, 0x1a7c}, {0x1a7f, 0x1a89},
-    {0x1a90, 0x1a99}, {0x1aa0, 0x1aad}, {0x1ab0, 0x1abe}, {0x1b00, 0x1b4b},
-    {0x1b50, 0x1b7c}, {0x1b80, 0x1bf3}, {0x1bfc, 0x1c37}, {0x1c3b, 0x1c49},
-    {0x1c4d, 0x1c88}, {0x1c90, 0x1cba}, {0x1cbd, 0x1cc7}, {0x1cd0, 0x1cfa},
-    {0x1d00, 0x1df9}, {0x1dfb, 0x1f15}, {0x1f18, 0x1f1d}, {0x1f20, 0x1f45},
-    {0x1f48, 0x1f4d}, {0x1f50, 0x1f57}, {0x1f5f, 0x1f7d}, {0x1f80, 0x1fb4},
-    {0x1fb6, 0x1fc4}, {0x1fc6, 0x1fd3}, {0x1fd6, 0x1fdb}, {0x1fdd, 0x1fef},
-    {0x1ff2, 0x1ff4}, {0x1ff6, 0x1ffe}, {0x2010, 0x2027}, {0x2030, 0x205e},
-    {0x2074, 0x208e}, {0x2090, 0x209c}, {0x20a0, 0x20bf}, {0x20d0, 0x20f0},
-    {0x2100, 0x218b}, {0x2190, 0x2426}, {0x2440, 0x244a}, {0x2460, 0x2b73},
-    {0x2b76, 0x2b95}, {0x2b98, 0x2c2e}, {0x2c30, 0x2c5e}, {0x2c60, 0x2cf3},
-    {0x2cf9, 0x2d25}, {0x2d30, 0x2d67}, {0x2d7f, 0x2d96}, {0x2da0, 0x2da6},
-    {0x2da8, 0x2dae}, {0x2db0, 0x2db6}, {0x2db8, 0x2dbe}, {0x2dc0, 0x2dc6},
-    {0x2dc8, 0x2dce}, {0x2dd0, 0x2dd6}, {0x2dd8, 0x2dde}, {0x2de0, 0x2e4f},
-    {0x2e80, 0x2e99}, {0x2e9b, 0x2ef3}, {0x2f00, 0x2fd5}, {0x2ff0, 0x2ffb},
-    {0x3001, 0x303f}, {0x3041, 0x3096}, {0x3099, 0x30ff}, {0x3105, 0x312f},
-    {0x3131, 0x318e}, {0x3190, 0x31ba}, {0x31c0, 0x31e3}, {0x31f0, 0x321e},
-    {0x3220, 0x4db5}, {0x4dc0, 0x9fef}, {0xa000, 0xa48c}, {0xa490, 0xa4c6},
-    {0xa4d0, 0xa62b}, {0xa640, 0xa6f7}, {0xa700, 0xa7bf}, {0xa7c2, 0xa7c6},
-    {0xa7f7, 0xa82b}, {0xa830, 0xa839}, {0xa840, 0xa877}, {0xa880, 0xa8c5},
-    {0xa8ce, 0xa8d9}, {0xa8e0, 0xa953}, {0xa95f, 0xa97c}, {0xa980, 0xa9cd},
-    {0xa9cf, 0xa9d9}, {0xa9de, 0xa9fe}, {0xaa00, 0xaa36}, {0xaa40, 0xaa4d},
-    {0xaa50, 0xaa59}, {0xaa5c, 0xaac2}, {0xaadb, 0xaaf6}, {0xab01, 0xab06},
-    {0xab09, 0xab0e}, {0xab11, 0xab16}, {0xab20, 0xab26}, {0xab28, 0xab2e},
-    {0xab30, 0xab67}, {0xab70, 0xabed}, {0xabf0, 0xabf9}, {0xac00, 0xd7a3},
-    {0xd7b0, 0xd7c6}, {0xd7cb, 0xd7fb}, {0xf900, 0xfa6d}, {0xfa70, 0xfad9},
-    {0xfb00, 0xfb06}, {0xfb13, 0xfb17}, {0xfb1d, 0xfb36}, {0xfb38, 0xfb3c},
-    {0xfb46, 0xfbc1}, {0xfbd3, 0xfd3f}, {0xfd50, 0xfd8f}, {0xfd92, 0xfdc7},
-    {0xfdf0, 0xfdfd}, {0xfe00, 0xfe19}, {0xfe20, 0xfe52}, {0xfe54, 0xfe66},
-    {0xfe68, 0xfe6b}, {0xfe70, 0xfe74}, {0xfe76, 0xfefc}, {0xff01, 0xffbe},
-    {0xffc2, 0xffc7}, {0xffca, 0xffcf}, {0xffd2, 0xffd7}, {0xffda, 0xffdc},
-    {0xffe0, 0xffe6}, {0xffe8, 0xffee}
+    {0x21, 0x7E}, {0xA1, 0xAC}, {0xAE, 0x377}, {0x37A, 0x37F},
+    {0x384, 0x38A}, {0x38E, 0x3A1}, {0x3A3, 0x52F}, {0x531, 0x556},
+    {0x559, 0x58A}, {0x58D, 0x58F}, {0x591, 0x5C7}, {0x5D0, 0x5EA},
+    {0x5EF, 0x5F4}, {0x606, 0x61B}, {0x61E, 0x6DC}, {0x6DE, 0x70D},
+    {0x710, 0x74A}, {0x74D, 0x7B1}, {0x7C0, 0x7FA}, {0x7FD, 0x82D},
+    {0x830, 0x83E}, {0x840, 0x85B}, {0x860, 0x86A}, {0x8A0, 0x8B4},
+    {0x8B6, 0x8C7}, {0x8D3, 0x8E1}, {0x8E3, 0x983}, {0x985, 0x98C},
+    {0x993, 0x9A8}, {0x9AA, 0x9B0}, {0x9B6, 0x9B9}, {0x9BC, 0x9C4},
+    {0x9CB, 0x9CE}, {0x9DF, 0x9E3}, {0x9E6, 0x9FE}, {0xA01, 0xA03},
+    {0xA05, 0xA0A}, {0xA13, 0xA28}, {0xA2A, 0xA30}, {0xA3E, 0xA42},
+    {0xA4B, 0xA4D}, {0xA59, 0xA5C}, {0xA66, 0xA76}, {0xA81, 0xA83},
+    {0xA85, 0xA8D}, {0xA8F, 0xA91}, {0xA93, 0xAA8}, {0xAAA, 0xAB0},
+    {0xAB5, 0xAB9}, {0xABC, 0xAC5}, {0xAC7, 0xAC9}, {0xACB, 0xACD},
+    {0xAE0, 0xAE3}, {0xAE6, 0xAF1}, {0xAF9, 0xAFF}, {0xB01, 0xB03},
+    {0xB05, 0xB0C}, {0xB13, 0xB28}, {0xB2A, 0xB30}, {0xB35, 0xB39},
+    {0xB3C, 0xB44}, {0xB4B, 0xB4D}, {0xB55, 0xB57}, {0xB5F, 0xB63},
+    {0xB66, 0xB77}, {0xB85, 0xB8A}, {0xB8E, 0xB90}, {0xB92, 0xB95},
+    {0xBA8, 0xBAA}, {0xBAE, 0xBB9}, {0xBBE, 0xBC2}, {0xBC6, 0xBC8},
+    {0xBCA, 0xBCD}, {0xBE6, 0xBFA}, {0xC00, 0xC0C}, {0xC0E, 0xC10},
+    {0xC12, 0xC28}, {0xC2A, 0xC39}, {0xC3D, 0xC44}, {0xC46, 0xC48},
+    {0xC4A, 0xC4D}, {0xC58, 0xC5A}, {0xC60, 0xC63}, {0xC66, 0xC6F},
+    {0xC77, 0xC8C}, {0xC8E, 0xC90}, {0xC92, 0xCA8}, {0xCAA, 0xCB3},
+    {0xCB5, 0xCB9}, {0xCBC, 0xCC4}, {0xCC6, 0xCC8}, {0xCCA, 0xCCD},
+    {0xCE0, 0xCE3}, {0xCE6, 0xCEF}, {0xD00, 0xD0C}, {0xD0E, 0xD10},
+    {0xD12, 0xD44}, {0xD46, 0xD48}, {0xD4A, 0xD4F}, {0xD54, 0xD63},
+    {0xD66, 0xD7F}, {0xD81, 0xD83}, {0xD85, 0xD96}, {0xD9A, 0xDB1},
+    {0xDB3, 0xDBB}, {0xDC0, 0xDC6}, {0xDCF, 0xDD4}, {0xDD8, 0xDDF},
+    {0xDE6, 0xDEF}, {0xDF2, 0xDF4}, {0xE01, 0xE3A}, {0xE3F, 0xE5B},
+    {0xE86, 0xE8A}, {0xE8C, 0xEA3}, {0xEA7, 0xEBD}, {0xEC0, 0xEC4},
+    {0xEC8, 0xECD}, {0xED0, 0xED9}, {0xEDC, 0xEDF}, {0xF00, 0xF47},
+    {0xF49, 0xF6C}, {0xF71, 0xF97}, {0xF99, 0xFBC}, {0xFBE, 0xFCC},
+    {0xFCE, 0xFDA}, {0x1000, 0x10C5}, {0x10D0, 0x1248}, {0x124A, 0x124D},
+    {0x1250, 0x1256}, {0x125A, 0x125D}, {0x1260, 0x1288}, {0x128A, 0x128D},
+    {0x1290, 0x12B0}, {0x12B2, 0x12B5}, {0x12B8, 0x12BE}, {0x12C2, 0x12C5},
+    {0x12C8, 0x12D6}, {0x12D8, 0x1310}, {0x1312, 0x1315}, {0x1318, 0x135A},
+    {0x135D, 0x137C}, {0x1380, 0x1399}, {0x13A0, 0x13F5}, {0x13F8, 0x13FD},
+    {0x1400, 0x167F}, {0x1681, 0x169C}, {0x16A0, 0x16F8}, {0x1700, 0x170C},
+    {0x170E, 0x1714}, {0x1720, 0x1736}, {0x1740, 0x1753}, {0x1760, 0x176C},
+    {0x176E, 0x1770}, {0x1780, 0x17DD}, {0x17E0, 0x17E9}, {0x17F0, 0x17F9},
+    {0x1800, 0x180D}, {0x1810, 0x1819}, {0x1820, 0x1878}, {0x1880, 0x18AA},
+    {0x18B0, 0x18F5}, {0x1900, 0x191E}, {0x1920, 0x192B}, {0x1930, 0x193B},
+    {0x1944, 0x196D}, {0x1970, 0x1974}, {0x1980, 0x19AB}, {0x19B0, 0x19C9},
+    {0x19D0, 0x19DA}, {0x19DE, 0x1A1B}, {0x1A1E, 0x1A5E}, {0x1A60, 0x1A7C},
+    {0x1A7F, 0x1A89}, {0x1A90, 0x1A99}, {0x1AA0, 0x1AAD}, {0x1AB0, 0x1AC0},
+    {0x1B00, 0x1B4B}, {0x1B50, 0x1B7C}, {0x1B80, 0x1BF3}, {0x1BFC, 0x1C37},
+    {0x1C3B, 0x1C49}, {0x1C4D, 0x1C88}, {0x1C90, 0x1CBA}, {0x1CBD, 0x1CC7},
+    {0x1CD0, 0x1CFA}, {0x1D00, 0x1DF9}, {0x1DFB, 0x1F15}, {0x1F18, 0x1F1D},
+    {0x1F20, 0x1F45}, {0x1F48, 0x1F4D}, {0x1F50, 0x1F57}, {0x1F5F, 0x1F7D},
+    {0x1F80, 0x1FB4}, {0x1FB6, 0x1FC4}, {0x1FC6, 0x1FD3}, {0x1FD6, 0x1FDB},
+    {0x1FDD, 0x1FEF}, {0x1FF2, 0x1FF4}, {0x1FF6, 0x1FFE}, {0x2010, 0x2027},
+    {0x2030, 0x205E}, {0x2074, 0x208E}, {0x2090, 0x209C}, {0x20A0, 0x20BF},
+    {0x20D0, 0x20F0}, {0x2100, 0x218B}, {0x2190, 0x2426}, {0x2440, 0x244A},
+    {0x2460, 0x2B73}, {0x2B76, 0x2B95}, {0x2B97, 0x2C2E}, {0x2C30, 0x2C5E},
+    {0x2C60, 0x2CF3}, {0x2CF9, 0x2D25}, {0x2D30, 0x2D67}, {0x2D7F, 0x2D96},
+    {0x2DA0, 0x2DA6}, {0x2DA8, 0x2DAE}, {0x2DB0, 0x2DB6}, {0x2DB8, 0x2DBE},
+    {0x2DC0, 0x2DC6}, {0x2DC8, 0x2DCE}, {0x2DD0, 0x2DD6}, {0x2DD8, 0x2DDE},
+    {0x2DE0, 0x2E52}, {0x2E80, 0x2E99}, {0x2E9B, 0x2EF3}, {0x2F00, 0x2FD5},
+    {0x2FF0, 0x2FFB}, {0x3001, 0x303F}, {0x3041, 0x3096}, {0x3099, 0x30FF},
+    {0x3105, 0x312F}, {0x3131, 0x318E}, {0x3190, 0x31E3}, {0x31F0, 0x321E},
+    {0x3220, 0x9FFC}, {0xA000, 0xA48C}, {0xA490, 0xA4C6}, {0xA4D0, 0xA62B},
+    {0xA640, 0xA6F7}, {0xA700, 0xA7BF}, {0xA7C2, 0xA7CA}, {0xA7F5, 0xA82C},
+    {0xA830, 0xA839}, {0xA840, 0xA877}, {0xA880, 0xA8C5}, {0xA8CE, 0xA8D9},
+    {0xA8E0, 0xA953}, {0xA95F, 0xA97C}, {0xA980, 0xA9CD}, {0xA9CF, 0xA9D9},
+    {0xA9DE, 0xA9FE}, {0xAA00, 0xAA36}, {0xAA40, 0xAA4D}, {0xAA50, 0xAA59},
+    {0xAA5C, 0xAAC2}, {0xAADB, 0xAAF6}, {0xAB01, 0xAB06}, {0xAB09, 0xAB0E},
+    {0xAB11, 0xAB16}, {0xAB20, 0xAB26}, {0xAB28, 0xAB2E}, {0xAB30, 0xAB6B},
+    {0xAB70, 0xABED}, {0xABF0, 0xABF9}, {0xAC00, 0xD7A3}, {0xD7B0, 0xD7C6},
+    {0xD7CB, 0xD7FB}, {0xF900, 0xFA6D}, {0xFA70, 0xFAD9}, {0xFB00, 0xFB06},
+    {0xFB13, 0xFB17}, {0xFB1D, 0xFB36}, {0xFB38, 0xFB3C}, {0xFB46, 0xFBC1},
+    {0xFBD3, 0xFD3F}, {0xFD50, 0xFD8F}, {0xFD92, 0xFDC7}, {0xFDF0, 0xFDFD},
+    {0xFE00, 0xFE19}, {0xFE20, 0xFE52}, {0xFE54, 0xFE66}, {0xFE68, 0xFE6B},
+    {0xFE70, 0xFE74}, {0xFE76, 0xFEFC}, {0xFF01, 0xFFBE}, {0xFFC2, 0xFFC7},
+    {0xFFCA, 0xFFCF}, {0xFFD2, 0xFFD7}, {0xFFDA, 0xFFDC}, {0xFFE0, 0xFFE6},
+    {0xFFE8, 0xFFEE}
 #if CHRBITS > 16
-    ,{0x10000, 0x1000b}, {0x1000d, 0x10026}, {0x10028, 0x1003a}, {0x1003f, 0x1004d},
-    {0x10050, 0x1005d}, {0x10080, 0x100fa}, {0x10100, 0x10102}, {0x10107, 0x10133},
-    {0x10137, 0x1018e}, {0x10190, 0x1019b}, {0x101d0, 0x101fd}, {0x10280, 0x1029c},
-    {0x102a0, 0x102d0}, {0x102e0, 0x102fb}, {0x10300, 0x10323}, {0x1032d, 0x1034a},
-    {0x10350, 0x1037a}, {0x10380, 0x1039d}, {0x1039f, 0x103c3}, {0x103c8, 0x103d5},
-    {0x10400, 0x1049d}, {0x104a0, 0x104a9}, {0x104b0, 0x104d3}, {0x104d8, 0x104fb},
+    ,{0x10000, 0x1000B}, {0x1000D, 0x10026}, {0x10028, 0x1003A}, {0x1003F, 0x1004D},
+    {0x10050, 0x1005D}, {0x10080, 0x100FA}, {0x10100, 0x10102}, {0x10107, 0x10133},
+    {0x10137, 0x1018E}, {0x10190, 0x1019C}, {0x101D0, 0x101FD}, {0x10280, 0x1029C},
+    {0x102A0, 0x102D0}, {0x102E0, 0x102FB}, {0x10300, 0x10323}, {0x1032D, 0x1034A},
+    {0x10350, 0x1037A}, {0x10380, 0x1039D}, {0x1039F, 0x103C3}, {0x103C8, 0x103D5},
+    {0x10400, 0x1049D}, {0x104A0, 0x104A9}, {0x104B0, 0x104D3}, {0x104D8, 0x104FB},
     {0x10500, 0x10527}, {0x10530, 0x10563}, {0x10600, 0x10736}, {0x10740, 0x10755},
-    {0x10760, 0x10767}, {0x10800, 0x10805}, {0x1080a, 0x10835}, {0x1083f, 0x10855},
-    {0x10857, 0x1089e}, {0x108a7, 0x108af}, {0x108e0, 0x108f2}, {0x108fb, 0x1091b},
-    {0x1091f, 0x10939}, {0x10980, 0x109b7}, {0x109bc, 0x109cf}, {0x109d2, 0x10a03},
-    {0x10a0c, 0x10a13}, {0x10a15, 0x10a17}, {0x10a19, 0x10a35}, {0x10a38, 0x10a3a},
-    {0x10a3f, 0x10a48}, {0x10a50, 0x10a58}, {0x10a60, 0x10a9f}, {0x10ac0, 0x10ae6},
-    {0x10aeb, 0x10af6}, {0x10b00, 0x10b35}, {0x10b39, 0x10b55}, {0x10b58, 0x10b72},
-    {0x10b78, 0x10b91}, {0x10b99, 0x10b9c}, {0x10ba9, 0x10baf}, {0x10c00, 0x10c48},
-    {0x10c80, 0x10cb2}, {0x10cc0, 0x10cf2}, {0x10cfa, 0x10d27}, {0x10d30, 0x10d39},
-    {0x10e60, 0x10e7e}, {0x10f00, 0x10f27}, {0x10f30, 0x10f59}, {0x10fe0, 0x10ff6},
-    {0x11000, 0x1104d}, {0x11052, 0x1106f}, {0x1107f, 0x110bc}, {0x110be, 0x110c1},
-    {0x110d0, 0x110e8}, {0x110f0, 0x110f9}, {0x11100, 0x11134}, {0x11136, 0x11146},
-    {0x11150, 0x11176}, {0x11180, 0x111cd}, {0x111d0, 0x111df}, {0x111e1, 0x111f4},
-    {0x11200, 0x11211}, {0x11213, 0x1123e}, {0x11280, 0x11286}, {0x1128a, 0x1128d},
-    {0x1128f, 0x1129d}, {0x1129f, 0x112a9}, {0x112b0, 0x112ea}, {0x112f0, 0x112f9},
-    {0x11300, 0x11303}, {0x11305, 0x1130c}, {0x11313, 0x11328}, {0x1132a, 0x11330},
-    {0x11335, 0x11339}, {0x1133b, 0x11344}, {0x1134b, 0x1134d}, {0x1135d, 0x11363},
-    {0x11366, 0x1136c}, {0x11370, 0x11374}, {0x11400, 0x11459}, {0x1145d, 0x1145f},
-    {0x11480, 0x114c7}, {0x114d0, 0x114d9}, {0x11580, 0x115b5}, {0x115b8, 0x115dd},
-    {0x11600, 0x11644}, {0x11650, 0x11659}, {0x11660, 0x1166c}, {0x11680, 0x116b8},
-    {0x116c0, 0x116c9}, {0x11700, 0x1171a}, {0x1171d, 0x1172b}, {0x11730, 0x1173f},
-    {0x11800, 0x1183b}, {0x118a0, 0x118f2}, {0x119a0, 0x119a7}, {0x119aa, 0x119d7},
-    {0x119da, 0x119e4}, {0x11a00, 0x11a47}, {0x11a50, 0x11aa2}, {0x11ac0, 0x11af8},
-    {0x11c00, 0x11c08}, {0x11c0a, 0x11c36}, {0x11c38, 0x11c45}, {0x11c50, 0x11c6c},
-    {0x11c70, 0x11c8f}, {0x11c92, 0x11ca7}, {0x11ca9, 0x11cb6}, {0x11d00, 0x11d06},
-    {0x11d0b, 0x11d36}, {0x11d3f, 0x11d47}, {0x11d50, 0x11d59}, {0x11d60, 0x11d65},
-    {0x11d6a, 0x11d8e}, {0x11d93, 0x11d98}, {0x11da0, 0x11da9}, {0x11ee0, 0x11ef8},
-    {0x11fc0, 0x11ff1}, {0x11fff, 0x12399}, {0x12400, 0x1246e}, {0x12470, 0x12474},
-    {0x12480, 0x12543}, {0x13000, 0x1342e}, {0x14400, 0x14646}, {0x16800, 0x16a38},
-    {0x16a40, 0x16a5e}, {0x16a60, 0x16a69}, {0x16ad0, 0x16aed}, {0x16af0, 0x16af5},
-    {0x16b00, 0x16b45}, {0x16b50, 0x16b59}, {0x16b5b, 0x16b61}, {0x16b63, 0x16b77},
-    {0x16b7d, 0x16b8f}, {0x16e40, 0x16e9a}, {0x16f00, 0x16f4a}, {0x16f4f, 0x16f87},
-    {0x16f8f, 0x16f9f}, {0x16fe0, 0x16fe3}, {0x17000, 0x187f7}, {0x18800, 0x18af2},
-    {0x1b000, 0x1b11e}, {0x1b150, 0x1b152}, {0x1b164, 0x1b167}, {0x1b170, 0x1b2fb},
-    {0x1bc00, 0x1bc6a}, {0x1bc70, 0x1bc7c}, {0x1bc80, 0x1bc88}, {0x1bc90, 0x1bc99},
-    {0x1bc9c, 0x1bc9f}, {0x1d000, 0x1d0f5}, {0x1d100, 0x1d126}, {0x1d129, 0x1d172},
-    {0x1d17b, 0x1d1e8}, {0x1d200, 0x1d245}, {0x1d2e0, 0x1d2f3}, {0x1d300, 0x1d356},
-    {0x1d360, 0x1d378}, {0x1d400, 0x1d454}, {0x1d456, 0x1d49c}, {0x1d4a9, 0x1d4ac},
-    {0x1d4ae, 0x1d4b9}, {0x1d4bd, 0x1d4c3}, {0x1d4c5, 0x1d505}, {0x1d507, 0x1d50a},
-    {0x1d50d, 0x1d514}, {0x1d516, 0x1d51c}, {0x1d51e, 0x1d539}, {0x1d53b, 0x1d53e},
-    {0x1d540, 0x1d544}, {0x1d54a, 0x1d550}, {0x1d552, 0x1d6a5}, {0x1d6a8, 0x1d7cb},
-    {0x1d7ce, 0x1da8b}, {0x1da9b, 0x1da9f}, {0x1daa1, 0x1daaf}, {0x1e000, 0x1e006},
-    {0x1e008, 0x1e018}, {0x1e01b, 0x1e021}, {0x1e026, 0x1e02a}, {0x1e100, 0x1e12c},
-    {0x1e130, 0x1e13d}, {0x1e140, 0x1e149}, {0x1e2c0, 0x1e2f9}, {0x1e800, 0x1e8c4},
-    {0x1e8c7, 0x1e8d6}, {0x1e900, 0x1e94b}, {0x1e950, 0x1e959}, {0x1ec71, 0x1ecb4},
-    {0x1ed01, 0x1ed3d}, {0x1ee00, 0x1ee03}, {0x1ee05, 0x1ee1f}, {0x1ee29, 0x1ee32},
-    {0x1ee34, 0x1ee37}, {0x1ee4d, 0x1ee4f}, {0x1ee67, 0x1ee6a}, {0x1ee6c, 0x1ee72},
-    {0x1ee74, 0x1ee77}, {0x1ee79, 0x1ee7c}, {0x1ee80, 0x1ee89}, {0x1ee8b, 0x1ee9b},
-    {0x1eea1, 0x1eea3}, {0x1eea5, 0x1eea9}, {0x1eeab, 0x1eebb}, {0x1f000, 0x1f02b},
-    {0x1f030, 0x1f093}, {0x1f0a0, 0x1f0ae}, {0x1f0b1, 0x1f0bf}, {0x1f0c1, 0x1f0cf},
-    {0x1f0d1, 0x1f0f5}, {0x1f100, 0x1f10c}, {0x1f110, 0x1f16c}, {0x1f170, 0x1f1ac},
-    {0x1f1e6, 0x1f202}, {0x1f210, 0x1f23b}, {0x1f240, 0x1f248}, {0x1f260, 0x1f265},
-    {0x1f300, 0x1f6d5}, {0x1f6e0, 0x1f6ec}, {0x1f6f0, 0x1f6fa}, {0x1f700, 0x1f773},
-    {0x1f780, 0x1f7d8}, {0x1f7e0, 0x1f7eb}, {0x1f800, 0x1f80b}, {0x1f810, 0x1f847},
-    {0x1f850, 0x1f859}, {0x1f860, 0x1f887}, {0x1f890, 0x1f8ad}, {0x1f900, 0x1f90b},
-    {0x1f90d, 0x1f971}, {0x1f973, 0x1f976}, {0x1f97a, 0x1f9a2}, {0x1f9a5, 0x1f9aa},
-    {0x1f9ae, 0x1f9ca}, {0x1f9cd, 0x1fa53}, {0x1fa60, 0x1fa6d}, {0x1fa70, 0x1fa73},
-    {0x1fa78, 0x1fa7a}, {0x1fa80, 0x1fa82}, {0x1fa90, 0x1fa95}, {0x20000, 0x2a6d6},
-    {0x2a700, 0x2b734}, {0x2b740, 0x2b81d}, {0x2b820, 0x2cea1}, {0x2ceb0, 0x2ebe0},
-    {0x2f800, 0x2fa1d}, {0xe0100, 0xe01ef}
+    {0x10760, 0x10767}, {0x10800, 0x10805}, {0x1080A, 0x10835}, {0x1083F, 0x10855},
+    {0x10857, 0x1089E}, {0x108A7, 0x108AF}, {0x108E0, 0x108F2}, {0x108FB, 0x1091B},
+    {0x1091F, 0x10939}, {0x10980, 0x109B7}, {0x109BC, 0x109CF}, {0x109D2, 0x10A03},
+    {0x10A0C, 0x10A13}, {0x10A15, 0x10A17}, {0x10A19, 0x10A35}, {0x10A38, 0x10A3A},
+    {0x10A3F, 0x10A48}, {0x10A50, 0x10A58}, {0x10A60, 0x10A9F}, {0x10AC0, 0x10AE6},
+    {0x10AEB, 0x10AF6}, {0x10B00, 0x10B35}, {0x10B39, 0x10B55}, {0x10B58, 0x10B72},
+    {0x10B78, 0x10B91}, {0x10B99, 0x10B9C}, {0x10BA9, 0x10BAF}, {0x10C00, 0x10C48},
+    {0x10C80, 0x10CB2}, {0x10CC0, 0x10CF2}, {0x10CFA, 0x10D27}, {0x10D30, 0x10D39},
+    {0x10E60, 0x10E7E}, {0x10E80, 0x10EA9}, {0x10EAB, 0x10EAD}, {0x10F00, 0x10F27},
+    {0x10F30, 0x10F59}, {0x10FB0, 0x10FCB}, {0x10FE0, 0x10FF6}, {0x11000, 0x1104D},
+    {0x11052, 0x1106F}, {0x1107F, 0x110BC}, {0x110BE, 0x110C1}, {0x110D0, 0x110E8},
+    {0x110F0, 0x110F9}, {0x11100, 0x11134}, {0x11136, 0x11147}, {0x11150, 0x11176},
+    {0x11180, 0x111DF}, {0x111E1, 0x111F4}, {0x11200, 0x11211}, {0x11213, 0x1123E},
+    {0x11280, 0x11286}, {0x1128A, 0x1128D}, {0x1128F, 0x1129D}, {0x1129F, 0x112A9},
+    {0x112B0, 0x112EA}, {0x112F0, 0x112F9}, {0x11300, 0x11303}, {0x11305, 0x1130C},
+    {0x11313, 0x11328}, {0x1132A, 0x11330}, {0x11335, 0x11339}, {0x1133B, 0x11344},
+    {0x1134B, 0x1134D}, {0x1135D, 0x11363}, {0x11366, 0x1136C}, {0x11370, 0x11374},
+    {0x11400, 0x1145B}, {0x1145D, 0x11461}, {0x11480, 0x114C7}, {0x114D0, 0x114D9},
+    {0x11580, 0x115B5}, {0x115B8, 0x115DD}, {0x11600, 0x11644}, {0x11650, 0x11659},
+    {0x11660, 0x1166C}, {0x11680, 0x116B8}, {0x116C0, 0x116C9}, {0x11700, 0x1171A},
+    {0x1171D, 0x1172B}, {0x11730, 0x1173F}, {0x11800, 0x1183B}, {0x118A0, 0x118F2},
+    {0x118FF, 0x11906}, {0x1190C, 0x11913}, {0x11918, 0x11935}, {0x1193B, 0x11946},
+    {0x11950, 0x11959}, {0x119A0, 0x119A7}, {0x119AA, 0x119D7}, {0x119DA, 0x119E4},
+    {0x11A00, 0x11A47}, {0x11A50, 0x11AA2}, {0x11AC0, 0x11AF8}, {0x11C00, 0x11C08},
+    {0x11C0A, 0x11C36}, {0x11C38, 0x11C45}, {0x11C50, 0x11C6C}, {0x11C70, 0x11C8F},
+    {0x11C92, 0x11CA7}, {0x11CA9, 0x11CB6}, {0x11D00, 0x11D06}, {0x11D0B, 0x11D36},
+    {0x11D3F, 0x11D47}, {0x11D50, 0x11D59}, {0x11D60, 0x11D65}, {0x11D6A, 0x11D8E},
+    {0x11D93, 0x11D98}, {0x11DA0, 0x11DA9}, {0x11EE0, 0x11EF8}, {0x11FC0, 0x11FF1},
+    {0x11FFF, 0x12399}, {0x12400, 0x1246E}, {0x12470, 0x12474}, {0x12480, 0x12543},
+    {0x13000, 0x1342E}, {0x14400, 0x14646}, {0x16800, 0x16A38}, {0x16A40, 0x16A5E},
+    {0x16A60, 0x16A69}, {0x16AD0, 0x16AED}, {0x16AF0, 0x16AF5}, {0x16B00, 0x16B45},
+    {0x16B50, 0x16B59}, {0x16B5B, 0x16B61}, {0x16B63, 0x16B77}, {0x16B7D, 0x16B8F},
+    {0x16E40, 0x16E9A}, {0x16F00, 0x16F4A}, {0x16F4F, 0x16F87}, {0x16F8F, 0x16F9F},
+    {0x16FE0, 0x16FE4}, {0x17000, 0x187F7}, {0x18800, 0x18CD5}, {0x18D00, 0x18D08},
+    {0x1B000, 0x1B11E}, {0x1B150, 0x1B152}, {0x1B164, 0x1B167}, {0x1B170, 0x1B2FB},
+    {0x1BC00, 0x1BC6A}, {0x1BC70, 0x1BC7C}, {0x1BC80, 0x1BC88}, {0x1BC90, 0x1BC99},
+    {0x1BC9C, 0x1BC9F}, {0x1D000, 0x1D0F5}, {0x1D100, 0x1D126}, {0x1D129, 0x1D172},
+    {0x1D17B, 0x1D1E8}, {0x1D200, 0x1D245}, {0x1D2E0, 0x1D2F3}, {0x1D300, 0x1D356},
+    {0x1D360, 0x1D378}, {0x1D400, 0x1D454}, {0x1D456, 0x1D49C}, {0x1D4A9, 0x1D4AC},
+    {0x1D4AE, 0x1D4B9}, {0x1D4BD, 0x1D4C3}, {0x1D4C5, 0x1D505}, {0x1D507, 0x1D50A},
+    {0x1D50D, 0x1D514}, {0x1D516, 0x1D51C}, {0x1D51E, 0x1D539}, {0x1D53B, 0x1D53E},
+    {0x1D540, 0x1D544}, {0x1D54A, 0x1D550}, {0x1D552, 0x1D6A5}, {0x1D6A8, 0x1D7CB},
+    {0x1D7CE, 0x1DA8B}, {0x1DA9B, 0x1DA9F}, {0x1DAA1, 0x1DAAF}, {0x1E000, 0x1E006},
+    {0x1E008, 0x1E018}, {0x1E01B, 0x1E021}, {0x1E026, 0x1E02A}, {0x1E100, 0x1E12C},
+    {0x1E130, 0x1E13D}, {0x1E140, 0x1E149}, {0x1E2C0, 0x1E2F9}, {0x1E800, 0x1E8C4},
+    {0x1E8C7, 0x1E8D6}, {0x1E900, 0x1E94B}, {0x1E950, 0x1E959}, {0x1EC71, 0x1ECB4},
+    {0x1ED01, 0x1ED3D}, {0x1EE00, 0x1EE03}, {0x1EE05, 0x1EE1F}, {0x1EE29, 0x1EE32},
+    {0x1EE34, 0x1EE37}, {0x1EE4D, 0x1EE4F}, {0x1EE67, 0x1EE6A}, {0x1EE6C, 0x1EE72},
+    {0x1EE74, 0x1EE77}, {0x1EE79, 0x1EE7C}, {0x1EE80, 0x1EE89}, {0x1EE8B, 0x1EE9B},
+    {0x1EEA1, 0x1EEA3}, {0x1EEA5, 0x1EEA9}, {0x1EEAB, 0x1EEBB}, {0x1F000, 0x1F02B},
+    {0x1F030, 0x1F093}, {0x1F0A0, 0x1F0AE}, {0x1F0B1, 0x1F0BF}, {0x1F0C1, 0x1F0CF},
+    {0x1F0D1, 0x1F0F5}, {0x1F100, 0x1F1AD}, {0x1F1E6, 0x1F202}, {0x1F210, 0x1F23B},
+    {0x1F240, 0x1F248}, {0x1F260, 0x1F265}, {0x1F300, 0x1F6D7}, {0x1F6E0, 0x1F6EC},
+    {0x1F6F0, 0x1F6FC}, {0x1F700, 0x1F773}, {0x1F780, 0x1F7D8}, {0x1F7E0, 0x1F7EB},
+    {0x1F800, 0x1F80B}, {0x1F810, 0x1F847}, {0x1F850, 0x1F859}, {0x1F860, 0x1F887},
+    {0x1F890, 0x1F8AD}, {0x1F900, 0x1F978}, {0x1F97A, 0x1F9CB}, {0x1F9CD, 0x1FA53},
+    {0x1FA60, 0x1FA6D}, {0x1FA70, 0x1FA74}, {0x1FA78, 0x1FA7A}, {0x1FA80, 0x1FA86},
+    {0x1FA90, 0x1FAA8}, {0x1FAB0, 0x1FAB6}, {0x1FAC0, 0x1FAC2}, {0x1FAD0, 0x1FAD6},
+    {0x1FB00, 0x1FB92}, {0x1FB94, 0x1FBCA}, {0x1FBF0, 0x1FBF9}, {0x20000, 0x2A6DD},
+    {0x2A700, 0x2B734}, {0x2B740, 0x2B81D}, {0x2B820, 0x2CEA1}, {0x2CEB0, 0x2EBE0},
+    {0x2F800, 0x2FA1D}, {0x30000, 0x3134A}, {0xE0100, 0xE01EF}
 #endif
 };
 
 #define NUM_GRAPH_RANGE (sizeof(graphRangeTable)/sizeof(crange))
 
 static const chr graphCharTable[] = {
-    0x38c, 0x85e, 0x98f, 0x990, 0x9b2, 0x9c7, 0x9c8, 0x9d7, 0x9dc,
-    0x9dd, 0xa0f, 0xa10, 0xa32, 0xa33, 0xa35, 0xa36, 0xa38, 0xa39,
-    0xa3c, 0xa47, 0xa48, 0xa51, 0xa5e, 0xab2, 0xab3, 0xad0, 0xb0f,
-    0xb10, 0xb32, 0xb33, 0xb47, 0xb48, 0xb56, 0xb57, 0xb5c, 0xb5d,
-    0xb82, 0xb83, 0xb99, 0xb9a, 0xb9c, 0xb9e, 0xb9f, 0xba3, 0xba4,
-    0xbd0, 0xbd7, 0xc55, 0xc56, 0xcd5, 0xcd6, 0xcde, 0xcf1, 0xcf2,
-    0xd82, 0xd83, 0xdbd, 0xdca, 0xdd6, 0xe81, 0xe82, 0xe84, 0xea5,
-    0xec6, 0x10c7, 0x10cd, 0x1258, 0x12c0, 0x1772, 0x1773, 0x1940, 0x1f59,
-    0x1f5b, 0x1f5d, 0x2070, 0x2071, 0x2d27, 0x2d2d, 0x2d6f, 0x2d70, 0xfb3e,
-    0xfb40, 0xfb41, 0xfb43, 0xfb44, 0xfffc, 0xfffd
+    0x38C, 0x85E, 0x98F, 0x990, 0x9B2, 0x9C7, 0x9C8, 0x9D7, 0x9DC,
+    0x9DD, 0xA0F, 0xA10, 0xA32, 0xA33, 0xA35, 0xA36, 0xA38, 0xA39,
+    0xA3C, 0xA47, 0xA48, 0xA51, 0xA5E, 0xAB2, 0xAB3, 0xAD0, 0xB0F,
+    0xB10, 0xB32, 0xB33, 0xB47, 0xB48, 0xB5C, 0xB5D, 0xB82, 0xB83,
+    0xB99, 0xB9A, 0xB9C, 0xB9E, 0xB9F, 0xBA3, 0xBA4, 0xBD0, 0xBD7,
+    0xC55, 0xC56, 0xCD5, 0xCD6, 0xCDE, 0xCF1, 0xCF2, 0xDBD, 0xDCA,
+    0xDD6, 0xE81, 0xE82, 0xE84, 0xEA5, 0xEC6, 0x10C7, 0x10CD, 0x1258,
+    0x12C0, 0x1772, 0x1773, 0x1940, 0x1F59, 0x1F5B, 0x1F5D, 0x2070, 0x2071,
+    0x2D27, 0x2D2D, 0x2D6F, 0x2D70, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44,
+    0xFFFC, 0xFFFD
 #if CHRBITS > 16
-    ,0x1003c, 0x1003d, 0x101a0, 0x1056f, 0x10808, 0x10837, 0x10838, 0x1083c, 0x108f4,
-    0x108f5, 0x1093f, 0x10a05, 0x10a06, 0x11288, 0x1130f, 0x11310, 0x11332, 0x11333,
-    0x11347, 0x11348, 0x11350, 0x11357, 0x1145b, 0x118ff, 0x11d08, 0x11d09, 0x11d3a,
-    0x11d3c, 0x11d3d, 0x11d67, 0x11d68, 0x11d90, 0x11d91, 0x16a6e, 0x16a6f, 0x1d49e,
-    0x1d49f, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d4bb, 0x1d546, 0x1e023, 0x1e024, 0x1e14e,
-    0x1e14f, 0x1e2ff, 0x1e95e, 0x1e95f, 0x1ee21, 0x1ee22, 0x1ee24, 0x1ee27, 0x1ee39,
-    0x1ee3b, 0x1ee42, 0x1ee47, 0x1ee49, 0x1ee4b, 0x1ee51, 0x1ee52, 0x1ee54, 0x1ee57,
-    0x1ee59, 0x1ee5b, 0x1ee5d, 0x1ee5f, 0x1ee61, 0x1ee62, 0x1ee64, 0x1ee7e, 0x1eef0,
-    0x1eef1, 0x1f250, 0x1f251
+    ,0x1003C, 0x1003D, 0x101A0, 0x1056F, 0x10808, 0x10837, 0x10838, 0x1083C, 0x108F4,
+    0x108F5, 0x1093F, 0x10A05, 0x10A06, 0x10EB0, 0x10EB1, 0x11288, 0x1130F, 0x11310,
+    0x11332, 0x11333, 0x11347, 0x11348, 0x11350, 0x11357, 0x11909, 0x11915, 0x11916,
+    0x11937, 0x11938, 0x11D08, 0x11D09, 0x11D3A, 0x11D3C, 0x11D3D, 0x11D67, 0x11D68,
+    0x11D90, 0x11D91, 0x11FB0, 0x16A6E, 0x16A6F, 0x16FF0, 0x16FF1, 0x1D49E, 0x1D49F,
+    0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D4BB, 0x1D546, 0x1E023, 0x1E024, 0x1E14E, 0x1E14F,
+    0x1E2FF, 0x1E95E, 0x1E95F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE39, 0x1EE3B,
+    0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59,
+    0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE7E, 0x1EEF0, 0x1EEF1,
+    0x1F250, 0x1F251, 0x1F8B0, 0x1F8B1
 #endif
 };
 
@@ -1068,7 +1075,7 @@ cclass(
     case CC_ASCII:
        cv = getcvec(v, 0, 1);
        if (cv) {
-           addrange(cv, 0, 0x7f);
+           addrange(cv, 0, 0x7F);
        }
        break;
     case CC_BLANK:
index 219c16a..d828b44 100644 (file)
@@ -341,13 +341,13 @@ compile(
     re->re_info = 0;           /* bits get set during parse */
     re->re_csize = sizeof(chr);
     re->re_guts = NULL;
-    re->re_fns = VS(&functions);
+    re->re_fns = (char *)&functions;
 
     /*
      * More complex setup, malloced things.
      */
 
-    re->re_guts = VS(MALLOC(sizeof(struct guts)));
+    re->re_guts = (char *)(MALLOC(sizeof(struct guts)));
     if (re->re_guts == NULL) {
        return freev(v, REG_ESPACE);
     }
@@ -512,7 +512,7 @@ freev(
     struct vars *v,
     int err)
 {
-    register int ret;
+    int ret;
 
     if (v->re != NULL) {
        rfree(v->re);
index e7bdca7..f6bf60c 100644 (file)
@@ -92,11 +92,11 @@ typedef int celt;           /* Type to hold chr, or NOCELT */
 #if TCL_UTF_MAX > 4
 #define        CHRBITS 32              /* Bits in a chr; must not use sizeof */
 #define        CHR_MIN 0x00000000      /* Smallest and largest chr; the value */
-#define        CHR_MAX 0xffffffff      /* CHR_MAX-CHR_MIN+1 should fit in uchr */
+#define        CHR_MAX 0xFFFFFFFF      /* CHR_MAX-CHR_MIN+1 should fit in uchr */
 #else
 #define        CHRBITS 16              /* Bits in a chr; must not use sizeof */
 #define        CHR_MIN 0x0000          /* Smallest and largest chr; the value */
-#define        CHR_MAX 0xffff          /* CHR_MAX-CHR_MIN+1 should fit in uchr */
+#define        CHR_MAX 0xFFFF          /* CHR_MAX-CHR_MIN+1 should fit in uchr */
 #endif
 
 /*
index f174420..d0d5680 100644 (file)
@@ -73,7 +73,7 @@ struct dfa {
     chr *lastnopr;             /* location of last cache-flushed NOPROGRESS */
     struct sset *search;       /* replacement-search-pointer memory */
     int cptsmalloced;          /* were the areas individually malloced? */
-    char *mallocarea;          /* self, or master malloced area, or NULL */
+    char *mallocarea;          /* self, or malloced area, or NULL */
 };
 
 #define        WORK    1               /* number of work bitvectors needed */
index e10711d..71d04f3 100644 (file)
 #define        DUPMAX  _POSIX2_RE_DUP_MAX
 #define        DUPINF  (DUPMAX+1)
 
-#define        REMAGIC 0xfed7          /* magic number for main struct */
+#define        REMAGIC 0xFED7          /* magic number for main struct */
 
 /*
  * debugging facilities
@@ -417,7 +417,7 @@ struct fns {
 
 struct guts {
     int magic;
-#define        GUTSMAGIC       0xfed9
+#define        GUTSMAGIC       0xFED9
     int cflags;                        /* copy of compile flags */
     long info;                 /* copy of re_info */
     size_t nsub;               /* copy of re_nsub */
index c2a9c89..23e8f6a 100644 (file)
@@ -316,12 +316,12 @@ declare 85 {
            int flags)
 }
 declare 86 {
-    int Tcl_CreateAlias(Tcl_Interp *slave, const char *slaveCmd,
+    int Tcl_CreateAlias(Tcl_Interp *childInterp, const char *childCmd,
            Tcl_Interp *target, const char *targetCmd, int argc,
            CONST84 char *const *argv)
 }
 declare 87 {
-    int Tcl_CreateAliasObj(Tcl_Interp *slave, const char *slaveCmd,
+    int Tcl_CreateAliasObj(Tcl_Interp *childInterp, const char *childCmd,
            Tcl_Interp *target, const char *targetCmd, int objc,
            Tcl_Obj *const objv[])
 }
@@ -364,7 +364,7 @@ declare 96 {
            Tcl_CmdDeleteProc *deleteProc)
 }
 declare 97 {
-    Tcl_Interp *Tcl_CreateSlave(Tcl_Interp *interp, const char *slaveName,
+    Tcl_Interp *Tcl_CreateSlave(Tcl_Interp *interp, const char *name,
            int isSafe)
 }
 declare 98 {
@@ -527,12 +527,12 @@ declare 147 {
     void Tcl_FreeResult(Tcl_Interp *interp)
 }
 declare 148 {
-    int Tcl_GetAlias(Tcl_Interp *interp, const char *slaveCmd,
+    int Tcl_GetAlias(Tcl_Interp *interp, const char *childCmd,
            Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr,
            int *argcPtr, CONST84 char ***argvPtr)
 }
 declare 149 {
-    int Tcl_GetAliasObj(Tcl_Interp *interp, const char *slaveCmd,
+    int Tcl_GetAliasObj(Tcl_Interp *interp, const char *childCmd,
            Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr,
            int *objcPtr, Tcl_Obj ***objv)
 }
@@ -582,7 +582,7 @@ declare 162 {
     CONST84_RETURN char *Tcl_GetHostName(void)
 }
 declare 163 {
-    int Tcl_GetInterpPath(Tcl_Interp *askInterp, Tcl_Interp *slaveInterp)
+    int Tcl_GetInterpPath(Tcl_Interp *interp, Tcl_Interp *childInterp)
 }
 declare 164 {
     Tcl_Interp *Tcl_GetMaster(Tcl_Interp *interp)
@@ -595,7 +595,7 @@ declare 166 {
 }
 
 # Tcl_GetOpenFile is only available on unix, but it is a part of the old
-# generic interface, so we inlcude it here for compatibility reasons.
+# generic interface, so we include it here for compatibility reasons.
 
 declare 167 unix {
     int Tcl_GetOpenFile(Tcl_Interp *interp, const char *chanID, int forWriting,
@@ -616,7 +616,7 @@ declare 171 {
     int Tcl_GetServiceMode(void)
 }
 declare 172 {
-    Tcl_Interp *Tcl_GetSlave(Tcl_Interp *interp, const char *slaveName)
+    Tcl_Interp *Tcl_GetSlave(Tcl_Interp *interp, const char *name)
 }
 declare 173 {
     Tcl_Channel Tcl_GetStdChannel(int type)
@@ -2223,7 +2223,7 @@ declare 606 {
 
 # TIP#307 (move results between interpreters) dkf
 declare 607 {
-    void Tcl_TransferResult(Tcl_Interp *sourceInterp, int result,
+    void Tcl_TransferResult(Tcl_Interp *sourceInterp, int code,
            Tcl_Interp *targetInterp)
 }
 
@@ -2323,12 +2323,12 @@ declare 630 {
            Tcl_Obj *compressionDictionaryObj)
 }
 
-declare 648 {
+# ----- BASELINE -- FOR -- 8.6.0 ----- #
+
+declare 649 {
     void TclUnusedStubEntry(void)
 }
 
-# ----- BASELINE -- FOR -- 8.6.0 ----- #
-
 ##############################################################################
 
 # Define the platform specific public Tcl interface. These functions are only
index 458072a..822d17b 100644 (file)
@@ -51,10 +51,10 @@ extern "C" {
 #define TCL_MAJOR_VERSION   8
 #define TCL_MINOR_VERSION   6
 #define TCL_RELEASE_LEVEL   TCL_FINAL_RELEASE
-#define TCL_RELEASE_SERIAL  10
+#define TCL_RELEASE_SERIAL  11
 
 #define TCL_VERSION        "8.6"
-#define TCL_PATCH_LEVEL            "8.6.10"
+#define TCL_PATCH_LEVEL            "8.6.11"
 \f
 /*
  *----------------------------------------------------------------------------
@@ -384,7 +384,7 @@ typedef long LONG;
  */
 
 #if !defined(TCL_WIDE_INT_TYPE)&&!defined(TCL_WIDE_INT_IS_LONG)
-#   if defined(_WIN32)
+#   if defined(_WIN32) && (!defined(__USE_MINGW_ANSI_STDIO) || !__USE_MINGW_ANSI_STDIO)
 #      define TCL_WIDE_INT_TYPE __int64
 #      ifdef __BORLANDC__
 #         define TCL_LL_MODIFIER       "L"
@@ -2517,7 +2517,7 @@ EXTERN void               Tcl_GetMemoryInfo(Tcl_DString *dsPtr);
 #   define Tcl_DecrRefCount(objPtr) \
        do { \
            Tcl_Obj *_objPtr = (objPtr); \
-           if ((_objPtr)->refCount-- <= 1) { \
+           if (_objPtr->refCount-- <= 1) { \
                TclFreeObj(_objPtr); \
            } \
        } while(0)
index cda1f38..cc683b6 100644 (file)
@@ -24,7 +24,7 @@
 #include "tclInt.h"
 #if !defined(TCL_THREADS) || !defined(USE_THREAD_ALLOC)
 
-#if USE_TCLALLOC
+#if defined(USE_TCLALLOC) && USE_TCLALLOC
 
 /*
  * We should really make use of AC_CHECK_TYPE(caddr_t) here, but it can wait
@@ -68,7 +68,7 @@ union overhead {
 };
 
 
-#define MAGIC          0xef    /* magic # on accounting info */
+#define MAGIC          0xEF    /* magic # on accounting info */
 #define RMAGIC         0x5555  /* magic # on range info */
 
 #ifndef NDEBUG
@@ -253,9 +253,9 @@ char *
 TclpAlloc(
     unsigned int numBytes)     /* Number of bytes to allocate. */
 {
-    register union overhead *overPtr;
-    register long bucket;
-    register unsigned amount;
+    union overhead *overPtr;
+    long bucket;
+    unsigned amount;
     struct block *bigBlockPtr = NULL;
 
     if (!allocInit) {
@@ -274,7 +274,7 @@ TclpAlloc(
 
     if (numBytes >= MAXMALLOC - OVERHEAD) {
        if (numBytes <= UINT_MAX - OVERHEAD -sizeof(struct block)) {
-           bigBlockPtr = (struct block *) TclpSysAlloc((unsigned)
+           bigBlockPtr = (struct block *) TclpSysAlloc(
                    (sizeof(struct block) + OVERHEAD + numBytes), 0);
        }
        if (bigBlockPtr == NULL) {
@@ -288,7 +288,7 @@ TclpAlloc(
 
        overPtr = (union overhead *) (bigBlockPtr + 1);
        overPtr->overMagic0 = overPtr->overMagic1 = MAGIC;
-       overPtr->bucketIndex = 0xff;
+       overPtr->bucketIndex = 0xFF;
 #ifdef MSTATS
        numMallocs[NBUCKETS]++;
 #endif
@@ -345,7 +345,7 @@ TclpAlloc(
 
     nextf[bucket] = overPtr->next;
     overPtr->overMagic0 = overPtr->overMagic1 = MAGIC;
-    overPtr->bucketIndex = (unsigned char) bucket;
+    overPtr->bucketIndex = UCHAR(bucket);
 
 #ifdef MSTATS
     numMallocs[bucket]++;
@@ -387,8 +387,8 @@ static void
 MoreCore(
     int bucket)                        /* What bucket to allocat to. */
 {
-    register union overhead *overPtr;
-    register long size;                /* size of desired block */
+    union overhead *overPtr;
+    long size;         /* size of desired block */
     long amount;               /* amount to allocate */
     int numBlocks;             /* how many blocks we get */
     struct block *blockPtr;
@@ -405,7 +405,7 @@ MoreCore(
     numBlocks = amount / size;
     ASSERT(numBlocks*size == amount);
 
-    blockPtr = (struct block *) TclpSysAlloc((unsigned)
+    blockPtr = (struct block *) TclpSysAlloc(
            (sizeof(struct block) + amount), 1);
     /* no more room! */
     if (blockPtr == NULL) {
@@ -448,8 +448,8 @@ void
 TclpFree(
     char *oldPtr)              /* Pointer to memory to free. */
 {
-    register long size;
-    register union overhead *overPtr;
+    long size;
+    union overhead *overPtr;
     struct block *bigBlockPtr;
 
     if (oldPtr == NULL) {
@@ -469,7 +469,7 @@ TclpFree(
     RANGE_ASSERT(overPtr->rangeCheckMagic == RMAGIC);
     RANGE_ASSERT(BLOCK_END(overPtr) == RMAGIC);
     size = overPtr->bucketIndex;
-    if (size == 0xff) {
+    if (size == 0xFF) {
 #ifdef MSTATS
        numMallocs[NBUCKETS]--;
 #endif
@@ -543,7 +543,7 @@ TclpRealloc(
      * If the block isn't in a bin, just realloc it.
      */
 
-    if (i == 0xff) {
+    if (i == 0xFF) {
        struct block *prevPtr, *nextPtr;
        bigBlockPtr = (struct block *) overPtr - 1;
        prevPtr = bigBlockPtr->prevPtr;
@@ -604,7 +604,7 @@ TclpRealloc(
        if (maxSize < numBytes) {
            numBytes = maxSize;
        }
-       memcpy(newPtr, oldPtr, (size_t) numBytes);
+       memcpy(newPtr, oldPtr, numBytes);
        TclpFree(oldPtr);
        return newPtr;
     }
@@ -645,8 +645,8 @@ void
 mstats(
     char *s)                   /* Where to write info. */
 {
-    register int i, j;
-    register union overhead *overPtr;
+    int i, j;
+    union overhead *overPtr;
     int totalFree = 0, totalUsed = 0;
 
     Tcl_MutexLock(allocMutexPtr);
index f05814f..94cb53c 100644 (file)
@@ -663,7 +663,7 @@ BBEmitOpcode(
                                /* Compilation environment */
     BasicBlock* bbPtr = assemEnvPtr->curr_bb;
                                /* Current basic block */
-    int op = TalInstructionTable[tblIdx].tclInstCode & 0xff;
+    int op = TalInstructionTable[tblIdx].tclInstCode & 0xFF;
 
     /*
      * If this is the first instruction in a basic block, record its line
@@ -725,13 +725,13 @@ BBEmitInst1or4(
                                /* Current basic block */
     int op = TalInstructionTable[tblIdx].tclInstCode;
 
-    if (param <= 0xff) {
+    if (param <= 0xFF) {
        op >>= 8;
     } else {
-       op &= 0xff;
+       op &= 0xFF;
     }
     TclEmitInt1(op, envPtr);
-    if (param <= 0xff) {
+    if (param <= 0xFF) {
        TclEmitInt1(param, envPtr);
     } else {
        TclEmitInt4(param, envPtr);
@@ -803,7 +803,7 @@ TclNRAssembleObjCmd(
        Tcl_AddErrorInfo(interp, "\n    (\"");
        Tcl_AppendObjToErrorInfo(interp, objv[0]);
        Tcl_AddErrorInfo(interp, "\" body, line ");
-       backtrace = Tcl_NewIntObj(Tcl_GetErrorLine(interp));
+       TclNewIntObj(backtrace, Tcl_GetErrorLine(interp));
        Tcl_AppendObjToErrorInfo(interp, backtrace);
        Tcl_AddErrorInfo(interp, ")");
        return TCL_ERROR;
@@ -840,7 +840,7 @@ CompileAssembleObj(
     Interp *iPtr = (Interp *) interp;
                                /* Internals of the interpreter */
     CompileEnv compEnv;                /* Compilation environment structure */
-    register ByteCode *codePtr = NULL;
+    ByteCode *codePtr = NULL;
                                /* Bytecode resulting from the assembly */
     Namespace* namespacePtr;   /* Namespace in which variable and command
                                 * names in the bytecode resolve */
@@ -1697,9 +1697,7 @@ AssembleOneLine(
            goto cleanup;
        }
        {
-           int flags = TCL_REG_ADVANCED | (opnd ? TCL_REG_NOCASE : 0);
-
-           BBEmitInstInt1(assemEnvPtr, tblIdx, flags, 0);
+           BBEmitInstInt1(assemEnvPtr, tblIdx, TCL_REG_ADVANCED | (opnd ? TCL_REG_NOCASE : 0), 0);
        }
        break;
 
@@ -2091,8 +2089,9 @@ GetNextOperand(
                                 * with \-substitutions done. */
 {
     Tcl_Interp* interp = (Tcl_Interp*) assemEnvPtr->envPtr->iPtr;
-    Tcl_Obj* operandObj = Tcl_NewObj();
+    Tcl_Obj* operandObj;
 
+    TclNewObj(operandObj);
     if (!TclWordKnownAtCompileTime(*tokenPtrPtr, operandObj)) {
        Tcl_DecrRefCount(operandObj);
        if (assemEnvPtr->flags & TCL_EVAL_DIRECT) {
@@ -2226,7 +2225,7 @@ GetIntegerOperand(
  *     TCL_ERROR (with an appropriate error message) if the parse fails.
  *
  * Side effects:
- *     Stores the list index at '*index'. Values between -1 and 0x7fffffff
+ *     Stores the list index at '*index'. Values between -1 and 0x7FFFFFFF
  *     have their natural meaning; values between -2 and -0x80000000
  *     represent 'end-2-N'.
  *
@@ -2389,7 +2388,7 @@ CheckOneByte(
 {
     Tcl_Obj* result;           /* Error message */
 
-    if (value < 0 || value > 0xff) {
+    if (value < 0 || value > 0xFF) {
        result = Tcl_NewStringObj("operand does not fit in one byte", -1);
        Tcl_SetObjResult(interp, result);
        Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", NULL);
@@ -2424,7 +2423,7 @@ CheckSignedOneByte(
 {
     Tcl_Obj* result;           /* Error message */
 
-    if (value > 0x7f || value < -0x80) {
+    if (value > 0x7F || value < -0x80) {
        result = Tcl_NewStringObj("operand does not fit in one byte", -1);
        Tcl_SetObjResult(interp, result);
        Tcl_SetErrorCode(interp, "TCL", "ASSEM", "1BYTE", NULL);
@@ -2838,7 +2837,7 @@ CalculateJumpRelocations(
                if (bbPtr->flags & BB_JUMP1) {
                    offset = jumpTarget->startOffset
                            - (bbPtr->jumpOffset + motion);
-                   if (offset < -0x80 || offset > 0x7f) {
+                   if (offset < -0x80 || offset > 0x7F) {
                        opcode = TclGetUInt1AtPtr(envPtr->codeStart
                                + bbPtr->jumpOffset);
                        ++opcode;
@@ -4262,7 +4261,7 @@ AddBasicBlockRangeToErrorInfo(
     Tcl_Obj* lineNo;           /* Line number in the source */
 
     Tcl_AddErrorInfo(interp, "\n    in assembly code between lines ");
-    lineNo = Tcl_NewIntObj(bbPtr->startLine);
+    TclNewIntObj(lineNo, bbPtr->startLine);
     Tcl_IncrRefCount(lineNo);
     Tcl_AppendObjToErrorInfo(interp, lineNo);
     Tcl_AddErrorInfo(interp, " and ");
index a03f131..895d160 100644 (file)
@@ -1036,7 +1036,7 @@ int
 TclHideUnsafeCommands(
     Tcl_Interp *interp)                /* Hide commands in this interpreter. */
 {
-    register const CmdInfo *cmdInfoPtr;
+    const CmdInfo *cmdInfoPtr;
 
     if (interp == NULL) {
        return TCL_ERROR;
@@ -2485,7 +2485,7 @@ int
 TclInvokeStringCommand(
     ClientData clientData,     /* Points to command's Command structure. */
     Tcl_Interp *interp,                /* Current interpreter. */
-    register int objc,         /* Number of arguments. */
+    int objc,          /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     Command *cmdPtr = clientData;
@@ -2534,7 +2534,7 @@ TclInvokeObjectCommand(
     ClientData clientData,     /* Points to command's Command structure. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int argc,                  /* Number of arguments. */
-    register const char **argv)        /* Argument strings. */
+    const char **argv) /* Argument strings. */
 {
     Command *cmdPtr = clientData;
     Tcl_Obj *objPtr;
@@ -3025,7 +3025,7 @@ Tcl_GetCommandFullName(
 
 {
     Interp *iPtr = (Interp *) interp;
-    register Command *cmdPtr = (Command *) command;
+    Command *cmdPtr = (Command *) command;
     char *name;
 
     /*
@@ -3268,6 +3268,7 @@ Tcl_DeleteCommandFromToken(
      * TclNRExecuteByteCode looks up the command in the command hashtable).
      */
 
+    cmdPtr->flags |= CMD_DEAD;
     TclCleanupCommandMacro(cmdPtr);
     return 0;
 }
@@ -3301,7 +3302,7 @@ CallCommandTraces(
                                 * trigger, either TCL_TRACE_DELETE or
                                 * TCL_TRACE_RENAME. */
 {
-    register CommandTrace *tracePtr;
+    CommandTrace *tracePtr;
     ActiveCommandTrace active;
     char *result;
     Tcl_Obj *oldNamePtr = NULL;
@@ -3443,11 +3444,11 @@ CancelEvalProc(
            TclSetCancelFlags(iPtr, cancelInfo->flags | CANCELED);
 
            /*
-            * Now, we must set the script cancellation flags on all the slave
+            * Now, we must set the script cancellation flags on all the child
             * interpreters belonging to this one.
             */
 
-           TclSetSlaveCancelFlags((Tcl_Interp *) iPtr,
+           TclSetChildCancelFlags((Tcl_Interp *) iPtr,
                    cancelInfo->flags | CANCELED, 0);
 
            /*
@@ -3491,7 +3492,7 @@ CancelEvalProc(
 
 void
 TclCleanupCommand(
-    register Command *cmdPtr)  /* Points to the Command structure to
+    Command *cmdPtr)   /* Points to the Command structure to
                                 * be freed. */
 {
     cmdPtr->refCount--;
@@ -3876,7 +3877,7 @@ int
 TclInterpReady(
     Tcl_Interp *interp)
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     /*
      * Reset both the interpreter's string and object results and clear out
@@ -3948,7 +3949,7 @@ TclResetCancellation(
     Tcl_Interp *interp,
     int force)
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     if (iPtr == NULL) {
        return TCL_ERROR;
@@ -3966,7 +3967,7 @@ TclResetCancellation(
  * Tcl_Canceled --
  *
  *     Check if the script in progress has been canceled, i.e.,
- *     Tcl_CancelEval was called for this interpreter or any of its master
+ *     Tcl_CancelEval was called for this interpreter or any of its parent
  *     interpreters.
  *
  * Results:
@@ -3990,7 +3991,7 @@ Tcl_Canceled(
     Tcl_Interp *interp,
     int flags)
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     /*
      * Has the current script in progress for this interpreter been canceled
@@ -4138,7 +4139,7 @@ Tcl_CancelEval(
     if (resultObjPtr != NULL) {
        result = Tcl_GetStringFromObj(resultObjPtr, &cancelInfo->length);
        cancelInfo->result = ckrealloc(cancelInfo->result,cancelInfo->length);
-       memcpy(cancelInfo->result, result, (size_t) cancelInfo->length);
+       memcpy(cancelInfo->result, result, cancelInfo->length);
        TclDecrRefCount(resultObjPtr);  /* Discard their result object. */
     } else {
        cancelInfo->result = NULL;
@@ -4331,7 +4332,7 @@ EvalObjvCore(
          * Caller gave it to us.
          */
 
-       if (!(preCmdPtr->flags & CMD_IS_DELETED)) {
+       if (!(preCmdPtr->flags & CMD_DEAD)) {
            /*
              * So long as it exists, use it.
              */
@@ -4719,7 +4720,7 @@ TEOV_NotFound(
        newObjv[i] = handlerObjv[i];
        Tcl_IncrRefCount(newObjv[i]);
     }
-    memcpy(newObjv+handlerObjc, objv, sizeof(Tcl_Obj *) * (unsigned)objc);
+    memcpy(newObjv+handlerObjc, objv, sizeof(Tcl_Obj *) * objc);
 
     /*
      * Look up and invoke the handler (by recursive call to this function). If
@@ -5046,7 +5047,7 @@ TclEvalEx(
                                 * the embedded command, which is refered to
                                 * by 'script'. The 'clNextOuter' refers to
                                 * the current entry in the table of
-                                * continuation lines in this "master script",
+                                * continuation lines in this "main script",
                                 * and the character offsets are relative to
                                 * the 'outerScript' as well.
                                 *
@@ -5505,7 +5506,7 @@ TclAdvanceLines(
     const char *start,
     const char *end)
 {
-    register const char *p;
+    const char *p;
 
     for (p = start; p < end; p++) {
        if (*p == '\n') {
@@ -6030,7 +6031,7 @@ int
 Tcl_EvalObjEx(
     Tcl_Interp *interp,                /* Token for command interpreter (returned by
                                 * a previous call to Tcl_CreateInterp). */
-    register Tcl_Obj *objPtr,  /* Pointer to object containing commands to
+    Tcl_Obj *objPtr,   /* Pointer to object containing commands to
                                 * execute. */
     int flags)                 /* Collection of OR-ed bits that control the
                                 * evaluation of the script. Supported values
@@ -6043,7 +6044,7 @@ int
 TclEvalObjEx(
     Tcl_Interp *interp,                /* Token for command interpreter (returned by
                                 * a previous call to Tcl_CreateInterp). */
-    register Tcl_Obj *objPtr,  /* Pointer to object containing commands to
+    Tcl_Obj *objPtr,   /* Pointer to object containing commands to
                                 * execute. */
     int flags,                 /* Collection of OR-ed bits that control the
                                 * evaluation of the script. Supported values
@@ -6062,7 +6063,7 @@ int
 TclNREvalObjEx(
     Tcl_Interp *interp,                /* Token for command interpreter (returned by
                                 * a previous call to Tcl_CreateInterp). */
-    register Tcl_Obj *objPtr,  /* Pointer to object containing commands to
+    Tcl_Obj *objPtr,   /* Pointer to object containing commands to
                                 * execute. */
     int flags,                 /* Collection of OR-ed bits that control the
                                 * evaluation of the script. Supported values
@@ -6370,7 +6371,7 @@ Tcl_ExprLong(
     const char *exprstring,    /* Expression to evaluate. */
     long *ptr)                 /* Where to store result. */
 {
-    register Tcl_Obj *exprPtr;
+    Tcl_Obj *exprPtr;
     int result = TCL_OK;
     if (*exprstring == '\0') {
        /*
@@ -6397,7 +6398,7 @@ Tcl_ExprDouble(
     const char *exprstring,    /* Expression to evaluate. */
     double *ptr)               /* Where to store result. */
 {
-    register Tcl_Obj *exprPtr;
+    Tcl_Obj *exprPtr;
     int result = TCL_OK;
 
     if (*exprstring == '\0') {
@@ -6477,7 +6478,7 @@ int
 Tcl_ExprLongObj(
     Tcl_Interp *interp,                /* Context in which to evaluate the
                                 * expression. */
-    register Tcl_Obj *objPtr,  /* Expression to evaluate. */
+    Tcl_Obj *objPtr,   /* Expression to evaluate. */
     long *ptr)                 /* Where to store long result. */
 {
     Tcl_Obj *resultPtr;
@@ -6525,7 +6526,7 @@ int
 Tcl_ExprDoubleObj(
     Tcl_Interp *interp,                /* Context in which to evaluate the
                                 * expression. */
-    register Tcl_Obj *objPtr,  /* Expression to evaluate. */
+    Tcl_Obj *objPtr,   /* Expression to evaluate. */
     double *ptr)               /* Where to store double result. */
 {
     Tcl_Obj *resultPtr;
@@ -6561,7 +6562,7 @@ int
 Tcl_ExprBooleanObj(
     Tcl_Interp *interp,                /* Context in which to evaluate the
                                 * expression. */
-    register Tcl_Obj *objPtr,  /* Expression to evaluate. */
+    Tcl_Obj *objPtr,   /* Expression to evaluate. */
     int *ptr)                  /* Where to store 0/1 result. */
 {
     Tcl_Obj *resultPtr;
@@ -6673,7 +6674,7 @@ TclNRInvoke(
     int objc,
     Tcl_Obj *const objv[])
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     Tcl_HashTable *hTblPtr;    /* Table of hidden commands. */
     const char *cmdName;       /* Name of the command from objv[0]. */
     Tcl_HashEntry *hPtr = NULL;
@@ -6867,7 +6868,7 @@ Tcl_AddObjErrorInfo(
     int length)                        /* The number of bytes in the message. If < 0,
                                 * then append all bytes up to a NULL byte. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     /*
      * If we are just starting to log an error, errorInfo is initialized from
@@ -7015,7 +7016,7 @@ Tcl_GlobalEval(
                                 * command. */
     const char *command)       /* Command to evaluate. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     int result;
     CallFrame *savedVarFramePtr;
 
@@ -7547,7 +7548,7 @@ ExprAbsFunc(
        if (mp_cmp_d((const mp_int *) ptr, 0) == MP_LT) {
            Tcl_GetBignumFromObj(NULL, objv[1], &big);
        tooLarge:
-           mp_neg(&big, &big);
+           (void)mp_neg(&big, &big);
            Tcl_SetObjResult(interp, Tcl_NewBignumObj(&big));
        } else {
        unChanged:
@@ -7779,8 +7780,8 @@ ExprRandFunc(
         * Make sure 1 <= randSeed <= (2^31) - 2. See below.
         */
 
-       iPtr->randSeed &= (unsigned long) 0x7fffffff;
-       if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7fffffff)) {
+       iPtr->randSeed &= (unsigned long) 0x7FFFFFFF;
+       if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7FFFFFFF)) {
            iPtr->randSeed ^= 123459876;
        }
     }
@@ -7957,8 +7958,8 @@ ExprSrandFunc(
 
     iPtr->flags |= RAND_SEED_INITIALIZED;
     iPtr->randSeed = i;
-    iPtr->randSeed &= (unsigned long) 0x7fffffff;
-    if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7fffffff)) {
+    iPtr->randSeed &= (unsigned long) 0x7FFFFFFF;
+    if ((iPtr->randSeed == 0) || (iPtr->randSeed == 0x7FFFFFFF)) {
        iPtr->randSeed ^= 123459876;
     }
 
@@ -8006,8 +8007,8 @@ MathFuncWrongNumArgs(
        }
     }
     Tcl_SetObjResult(interp, Tcl_ObjPrintf(
-           "too %s arguments for math function \"%s\"",
-           (found < expected ? "few" : "many"), name));
+           "%s arguments for math function \"%s\"",
+           (found < expected ? "not enough" : "too many"), name));
     Tcl_SetErrorCode(interp, "TCL", "WRONGARGS", NULL);
 }
 \f
index 8bd65a8..8520ec7 100644 (file)
@@ -199,7 +199,7 @@ typedef struct ByteArray {
                                 * array. */
     int allocated;             /* The amount of space actually allocated
                                 * minus 1 byte. */
-    unsigned char bytes[1];    /* The array of bytes. The actual size of this
+    unsigned char bytes[TCLFLEXARRAY]; /* The array of bytes. The actual size of this
                                 * field depends on the 'allocated' field
                                 * above. */
 } ByteArray;
@@ -334,12 +334,12 @@ Tcl_SetByteArrayObj(
     if (length < 0) {
        length = 0;
     }
-    byteArrayPtr = ckalloc(BYTEARRAY_SIZE(length));
+    byteArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(length));
     byteArrayPtr->used = length;
     byteArrayPtr->allocated = length;
 
     if ((bytes != NULL) && (length > 0)) {
-       memcpy(byteArrayPtr->bytes, bytes, (size_t) length);
+       memcpy(byteArrayPtr->bytes, bytes, length);
     }
     objPtr->typePtr = &tclByteArrayType;
     SET_BYTEARRAY(objPtr, byteArrayPtr);
@@ -460,7 +460,7 @@ SetByteArrayFromAny(
        src = TclGetStringFromObj(objPtr, &length);
        srcEnd = src + length;
 
-       byteArrayPtr = ckalloc(BYTEARRAY_SIZE(length));
+       byteArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(length));
        for (dst = byteArrayPtr->bytes; src < srcEnd; ) {
            src += TclUtfToUniChar(src, &ch);
            *dst++ = UCHAR(ch);
@@ -529,10 +529,10 @@ DupByteArrayInternalRep(
     srcArrayPtr = GET_BYTEARRAY(srcPtr);
     length = srcArrayPtr->used;
 
-    copyArrayPtr = ckalloc(BYTEARRAY_SIZE(length));
+    copyArrayPtr = (ByteArray *)ckalloc(BYTEARRAY_SIZE(length));
     copyArrayPtr->used = length;
     copyArrayPtr->allocated = length;
-    memcpy(copyArrayPtr->bytes, srcArrayPtr->bytes, (size_t) length);
+    memcpy(copyArrayPtr->bytes, srcArrayPtr->bytes, length);
     SET_BYTEARRAY(copyPtr, copyArrayPtr);
 
     copyPtr->typePtr = &tclByteArrayType;
@@ -588,12 +588,12 @@ UpdateStringOfByteArray(
        Tcl_Panic("max size for a Tcl value (%d bytes) exceeded", INT_MAX);
     }
 
-    dst = ckalloc(size + 1);
+    dst = (char *)ckalloc(size + 1);
     objPtr->bytes = dst;
     objPtr->length = size;
 
     if (size == length) {
-       memcpy(dst, src, (size_t) size);
+       memcpy(dst, src, size);
        dst[size] = '\0';
     } else {
        for (i = 0; i < length; i++) {
@@ -945,7 +945,7 @@ BinaryFormatCmd(
 
     resultPtr = Tcl_NewObj();
     buffer = Tcl_SetByteArrayLength(resultPtr, length);
-    memset(buffer, 0, (size_t) length);
+    memset(buffer, 0, length);
 
     /*
      * Pack the data into the result object. Note that we can skip the error
@@ -982,10 +982,10 @@ BinaryFormatCmd(
                count = 1;
            }
            if (length >= count) {
-               memcpy(cursor, bytes, (size_t) count);
+               memcpy(cursor, bytes, count);
            } else {
-               memcpy(cursor, bytes, (size_t) length);
-               memset(cursor + length, pad, (size_t) (count - length));
+               memcpy(cursor, bytes, length);
+               memset(cursor + length, pad, count - length);
            }
            cursor += count;
            break;
@@ -1084,7 +1084,7 @@ BinaryFormatCmd(
                    if (c > 16) {
                        c += ('A' - 'a');
                    }
-                   value |= (c & 0xf);
+                   value |= (c & 0xF);
                    if (offset % 2) {
                        *cursor++ = (char) value;
                        value = 0;
@@ -1106,9 +1106,9 @@ BinaryFormatCmd(
                    if (c > 16) {
                        c += ('A' - 'a');
                    }
-                   value |= ((c << 4) & 0xf0);
+                   value |= ((c << 4) & 0xF0);
                    if (offset % 2) {
-                       *cursor++ = UCHAR(value & 0xff);
+                       *cursor++ = UCHAR(value & 0xFF);
                        value = 0;
                    }
                }
@@ -1174,7 +1174,7 @@ BinaryFormatCmd(
            if (count == BINARY_NOCOUNT) {
                count = 1;
            }
-           memset(cursor, 0, (size_t) count);
+           memset(cursor, 0, count);
            cursor += count;
            break;
        case 'X':
@@ -1222,11 +1222,11 @@ BinaryFormatCmd(
 
  badField:
     {
-       Tcl_UniChar ch = 0;
-       char buf[TCL_UTF_MAX + 1] = "";
+       int ch;
+       char buf[8] = "";
 
-       TclUtfToUniChar(errorString, &ch);
-       buf[Tcl_UniCharToUtf(ch, buf)] = '\0';
+       TclUtfToUCS4(errorString, &ch);
+       buf[TclUCS4ToUtf(ch, buf)] = '\0';
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "bad field specifier \"%s\"", buf));
        return TCL_ERROR;
@@ -1442,7 +1442,7 @@ BinaryScanCmd(
                    } else {
                        value = *src++;
                    }
-                   *dest++ = hexdigit[value & 0xf];
+                   *dest++ = hexdigit[value & 0xF];
                }
            } else {
                for (i = 0; i < count; i++) {
@@ -1451,7 +1451,7 @@ BinaryScanCmd(
                    } else {
                        value = *src++;
                    }
-                   *dest++ = hexdigit[(value >> 4) & 0xf];
+                   *dest++ = hexdigit[(value >> 4) & 0xF];
                }
            }
 
@@ -1592,11 +1592,11 @@ BinaryScanCmd(
 
  badField:
     {
-       Tcl_UniChar ch = 0;
-       char buf[TCL_UTF_MAX + 1] = "";
+       int ch;
+       char buf[8] = "";
 
-       TclUtfToUniChar(errorString, &ch);
-       buf[Tcl_UniCharToUtf(ch, buf)] = '\0';
+       TclUtfToUCS4(errorString, &ch);
+       buf[TclUCS4ToUtf(ch, buf)] = '\0';
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "bad field specifier \"%s\"", buf));
        return TCL_ERROR;
@@ -2146,8 +2146,8 @@ ScanNumber(
        if (*numberCachePtrPtr == NULL) {
            return Tcl_NewLongObj(value);
        } else {
-           register Tcl_HashTable *tablePtr = *numberCachePtrPtr;
-           register Tcl_HashEntry *hPtr;
+           Tcl_HashTable *tablePtr = *numberCachePtrPtr;
+           Tcl_HashEntry *hPtr;
            int isNew;
 
            hPtr = Tcl_CreateHashEntry(tablePtr, INT2PTR(value), &isNew);
@@ -2155,7 +2155,7 @@ ScanNumber(
                return Tcl_GetHashValue(hPtr);
            }
            if (tablePtr->numEntries <= BINARY_SCAN_MAX_CACHE) {
-               register Tcl_Obj *objPtr = Tcl_NewLongObj(value);
+               Tcl_Obj *objPtr = Tcl_NewLongObj(value);
 
                Tcl_IncrRefCount(objPtr);
                Tcl_SetHashValue(hPtr, objPtr);
@@ -2274,7 +2274,7 @@ DeleteScanNumberCache(
 
     hEntry = Tcl_FirstHashEntry(numberCachePtr, &search);
     while (hEntry != NULL) {
-       register Tcl_Obj *value = Tcl_GetHashValue(hEntry);
+       Tcl_Obj *value = Tcl_GetHashValue(hEntry);
 
        if (value != NULL) {
            Tcl_DecrRefCount(value);
@@ -2339,8 +2339,8 @@ BinaryEncodeHex(
     data = Tcl_GetByteArrayFromObj(objv[1], &count);
     cursor = Tcl_SetByteArrayLength(resultObj, count * 2);
     for (offset = 0; offset < count; ++offset) {
-       *cursor++ = HexDigits[(data[offset] >> 4) & 0x0f];
-       *cursor++ = HexDigits[data[offset] & 0x0f];
+       *cursor++ = HexDigits[(data[offset] >> 4) & 0x0F];
+       *cursor++ = HexDigits[data[offset] & 0x0F];
     }
     Tcl_SetObjResult(interp, resultObj);
     return TCL_OK;
@@ -2372,7 +2372,8 @@ BinaryDecodeHex(
     Tcl_Obj *resultObj = NULL;
     unsigned char *data, *datastart, *dataend;
     unsigned char *begin, *cursor, c;
-    int i, index, value, size, count = 0, cut = 0, strict = 0;
+    int i, index, value, size, pure, count = 0, cut = 0, strict = 0;
+    Tcl_UniChar ch = 0;
     enum {OPT_STRICT };
     static const char *const optStrings[] = { "-strict", NULL };
 
@@ -2393,8 +2394,9 @@ BinaryDecodeHex(
     }
 
     TclNewObj(resultObj);
-    datastart = data = (unsigned char *)
-           TclGetStringFromObj(objv[objc - 1], &count);
+    pure = TclIsPureByteArray(objv[objc - 1]);
+    datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
+           : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
     dataend = data + count;
     size = (count + 1) / 2;
     begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
@@ -2423,7 +2425,7 @@ BinaryDecodeHex(
            if (c > 16) {
                c += ('A' - 'a');
            }
-           value |= c & 0xf;
+           value |= c & 0xF;
        }
        if (i < 2) {
            cut++;
@@ -2439,10 +2441,16 @@ BinaryDecodeHex(
     return TCL_OK;
 
   badChar:
+    if (pure) {
+       ch = c;
+    } else {
+       TclUtfToUniChar((const char *)(data - 1), &ch);
+    }
     TclDecrRefCount(resultObj);
     Tcl_SetObjResult(interp, Tcl_ObjPrintf(
            "invalid hexadecimal digit \"%c\" at position %d",
-           c, (int) (data - datastart - 1)));
+           ch, (int) (data - datastart - 1)));
+    Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", NULL);
     return TCL_ERROR;
 }
 \f
@@ -2451,16 +2459,10 @@ BinaryDecodeHex(
  *
  * BinaryEncode64 --
  *
- *     This implements a generic 6 bit binary encoding. Input is broken into
- *     6 bit chunks and a lookup table passed in via clientData is used to
- *     turn these values into output characters. This is used to implement
- *     base64 binary encodings.
+ *     This procedure implements the "binary encode base64" Tcl command.
  *
  * Results:
- *     Interp result set to an encoded byte array object
- *
- * Side effects:
- *     None
+ *     The base64 encoded value prescribed by the input arguments.
  *
  *----------------------------------------------------------------------
  */
@@ -2489,11 +2491,11 @@ BinaryEncode64(
     Tcl_Obj *const objv[])
 {
     Tcl_Obj *resultObj;
-    unsigned char *data, *cursor, *limit;
+    unsigned char *data, *limit;
     int maxlen = 0;
     const char *wrapchar = "\n";
     int wrapcharlen = 1;
-    int offset, i, index, size, outindex = 0, count = 0;
+    int offset, i, index, size, outindex = 0, count = 0, purewrap = 1;
     enum { OPT_MAXLEN, OPT_WRAPCHAR };
     static const char *const optStrings[] = { "-maxlen", "-wrapchar", NULL };
 
@@ -2521,17 +2523,25 @@ BinaryEncode64(
            }
            break;
        case OPT_WRAPCHAR:
-           wrapchar = Tcl_GetStringFromObj(objv[i + 1], &wrapcharlen);
-           if (wrapcharlen == 0) {
-               maxlen = 0;
+           purewrap = TclIsPureByteArray(objv[i + 1]);
+           if (purewrap) {
+               wrapchar = (const char *) Tcl_GetByteArrayFromObj(
+                       objv[i + 1], &wrapcharlen);
+           } else {
+               wrapchar = Tcl_GetStringFromObj(objv[i + 1], &wrapcharlen);
            }
            break;
        }
     }
+    if (wrapcharlen == 0) {
+       maxlen = 0;
+    }
 
     resultObj = Tcl_NewObj();
     data = Tcl_GetByteArrayFromObj(objv[objc - 1], &count);
     if (count > 0) {
+       unsigned char *cursor = NULL;
+
        size = (((count * 4) / 3) + 3) & ~3;    /* ensure 4 byte chunks */
        if (maxlen > 0 && size > maxlen) {
            int adjusted = size + (wrapcharlen * (size / maxlen));
@@ -2540,8 +2550,17 @@ BinaryEncode64(
                adjusted -= wrapcharlen;
            }
            size = adjusted;
+
+           if (purewrap == 0) {
+               /* Wrapchar is (possibly) non-byte, so build result as
+                * general string, not bytearray */
+               Tcl_SetObjLength(resultObj, size);
+               cursor = (unsigned char *) TclGetString(resultObj);
+           }
+       }
+       if (cursor == NULL) {
+           cursor = Tcl_SetByteArrayLength(resultObj, size);
        }
-       cursor = Tcl_SetByteArrayLength(resultObj, size);
        limit = cursor + size;
        for (offset = 0; offset < count; offset += 3) {
            unsigned char d[3] = {0, 0, 0};
@@ -2552,12 +2571,12 @@ BinaryEncode64(
            OUTPUT(B64Digits[d[0] >> 2]);
            OUTPUT(B64Digits[((d[0] & 0x03) << 4) | (d[1] >> 4)]);
            if (offset + 1 < count) {
-               OUTPUT(B64Digits[((d[1] & 0x0f) << 2) | (d[2] >> 6)]);
+               OUTPUT(B64Digits[((d[1] & 0x0F) << 2) | (d[2] >> 6)]);
            } else {
                OUTPUT(B64Digits[64]);
            }
            if (offset+2 < count) {
-               OUTPUT(B64Digits[d[2] & 0x3f]);
+               OUTPUT(B64Digits[d[2] & 0x3F]);
            } else {
                OUTPUT(B64Digits[64]);
            }
@@ -2598,7 +2617,7 @@ BinaryEncodeUu(
     unsigned char *data, *start, *cursor;
     int offset, count, rawLength, n, i, j, bits, index;
     int lineLength = 61;
-    const unsigned char SingleNewline[] = { (unsigned char) '\n' };
+    const unsigned char SingleNewline[] = { UCHAR('\n') };
     const unsigned char *wrapchar = SingleNewline;
     int wrapcharlen = sizeof(SingleNewline);
     enum { OPT_MAXLEN, OPT_WRAPCHAR };
@@ -2620,16 +2639,47 @@ BinaryEncodeUu(
                    &lineLength) != TCL_OK) {
                return TCL_ERROR;
            }
-           if (lineLength < 3 || lineLength > 85) {
+           if (lineLength < 5 || lineLength > 85) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "line length out of range", -1));
                Tcl_SetErrorCode(interp, "TCL", "BINARY", "ENCODE",
                        "LINE_LENGTH", NULL);
                return TCL_ERROR;
            }
+           lineLength = ((lineLength - 1) & -4) + 1; /* 5, 9, 13 ... */
            break;
        case OPT_WRAPCHAR:
-           wrapchar = Tcl_GetByteArrayFromObj(objv[i + 1], &wrapcharlen);
+           wrapchar = (const unsigned char *) TclGetStringFromObj(
+                   objv[i + 1], &wrapcharlen);
+           {
+               const unsigned char *p = wrapchar;
+               int numBytes = wrapcharlen;
+
+               while (numBytes) {
+                   switch (*p) {
+                       case '\t':
+                       case '\v':
+                       case '\f':
+                       case '\r':
+                           p++; numBytes--;
+                           continue;
+                       case '\n':
+                           numBytes--;
+                           break;
+                       default:
+                       badwrap:
+                           Tcl_SetObjResult(interp, Tcl_NewStringObj(
+                                   "invalid wrapchar; will defeat decoding",
+                                   -1));
+                           Tcl_SetErrorCode(interp, "TCL", "BINARY",
+                                   "ENCODE", "WRAPCHAR", NULL);
+                           return TCL_ERROR;
+                   }
+               }
+               if (numBytes) {
+                   goto badwrap;
+               }
+           }
            break;
        }
     }
@@ -2666,12 +2716,12 @@ BinaryEncodeUu(
            n <<= 8;
            n |= data[offset++];
            for (bits += 8; bits > 6 ; bits -= 6) {
-               *cursor++ = UueDigits[(n >> (bits - 6)) & 0x3f];
+               *cursor++ = UueDigits[(n >> (bits - 6)) & 0x3F];
            }
        }
        if (bits > 0) {
            n <<= 8;
-           *cursor++ = UueDigits[(n >> (bits + 2)) & 0x3f];
+           *cursor++ = UueDigits[(n >> (bits + 2)) & 0x3F];
            bits = 0;
        }
        for (j = 0 ; j < wrapcharlen ; ++j) {
@@ -2714,8 +2764,9 @@ BinaryDecodeUu(
     Tcl_Obj *resultObj = NULL;
     unsigned char *data, *datastart, *dataend;
     unsigned char *begin, *cursor;
-    int i, index, size, count = 0, strict = 0, lineLen;
+    int i, index, size, pure, count = 0, strict = 0, lineLen;
     unsigned char c;
+    Tcl_UniChar ch = 0;
     enum { OPT_STRICT };
     static const char *const optStrings[] = { "-strict", NULL };
 
@@ -2736,8 +2787,9 @@ BinaryDecodeUu(
     }
 
     TclNewObj(resultObj);
-    datastart = data = (unsigned char *)
-           TclGetStringFromObj(objv[objc - 1], &count);
+    pure = TclIsPureByteArray(objv[objc - 1]);
+    datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
+           : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
     dataend = data + count;
     size = ((count + 3) & ~3) * 3 / 4;
     begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
@@ -2762,7 +2814,7 @@ BinaryDecodeUu(
                i--;
                continue;
            }
-           lineLen = (c - 32) & 0x3f;
+           lineLen = (c - 32) & 0x3F;
        }
 
        /*
@@ -2791,14 +2843,14 @@ BinaryDecodeUu(
         */
 
        if (lineLen > 0) {
-           *cursor++ = (((d[0] - 0x20) & 0x3f) << 2)
-                   | (((d[1] - 0x20) & 0x3f) >> 4);
+           *cursor++ = (((d[0] - 0x20) & 0x3F) << 2)
+                   | (((d[1] - 0x20) & 0x3F) >> 4);
            if (--lineLen > 0) {
-               *cursor++ = (((d[1] - 0x20) & 0x3f) << 4)
-                       | (((d[2] - 0x20) & 0x3f) >> 2);
+               *cursor++ = (((d[1] - 0x20) & 0x3F) << 4)
+                       | (((d[2] - 0x20) & 0x3F) >> 2);
                if (--lineLen > 0) {
-                   *cursor++ = (((d[2] - 0x20) & 0x3f) << 6)
-                           | (((d[3] - 0x20) & 0x3f));
+                   *cursor++ = (((d[2] - 0x20) & 0x3F) << 6)
+                           | (((d[3] - 0x20) & 0x3F));
                    lineLen--;
                }
            }
@@ -2843,9 +2895,14 @@ BinaryDecodeUu(
     return TCL_ERROR;
 
   badUu:
+    if (pure) {
+       ch = c;
+    } else {
+       TclUtfToUniChar((const char *)(data - 1), &ch);
+    }
     Tcl_SetObjResult(interp, Tcl_ObjPrintf(
            "invalid uuencode character \"%c\" at position %d",
-           c, (int) (data - datastart - 1)));
+           ch, (int) (data - datastart - 1)));
     Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", NULL);
     TclDecrRefCount(resultObj);
     return TCL_ERROR;
@@ -2878,8 +2935,9 @@ BinaryDecode64(
     unsigned char *data, *datastart, *dataend, c = '\0';
     unsigned char *begin = NULL;
     unsigned char *cursor = NULL;
-    int strict = 0;
+    int pure, strict = 0;
     int i, index, size, cut = 0, count = 0;
+    Tcl_UniChar ch = 0;
     enum { OPT_STRICT };
     static const char *const optStrings[] = { "-strict", NULL };
 
@@ -2900,8 +2958,9 @@ BinaryDecode64(
     }
 
     TclNewObj(resultObj);
-    datastart = data = (unsigned char *)
-           TclGetStringFromObj(objv[objc - 1], &count);
+    pure = TclIsPureByteArray(objv[objc - 1]);
+    datastart = data = pure ? Tcl_GetByteArrayFromObj(objv[objc - 1], &count)
+           : (unsigned char *) TclGetStringFromObj(objv[objc - 1], &count);
     dataend = data + count;
     size = ((count + 3) & ~3) * 3 / 4;
     begin = cursor = Tcl_SetByteArrayLength(resultObj, size);
@@ -2951,21 +3010,21 @@ BinaryDecode64(
                if (c == '=' && i > 1) {
                    value <<= 6;
                    cut++;
-               } else if (!strict && TclIsSpaceProc(c)) {
+               } else if (!strict) {
                    i--;
                } else {
                    goto bad64;
                }
            } else if (c >= 'A' && c <= 'Z') {
-               value = (value << 6) | ((c - 'A') & 0x3f);
+               value = (value << 6) | ((c - 'A') & 0x3F);
            } else if (c >= 'a' && c <= 'z') {
-               value = (value << 6) | ((c - 'a' + 26) & 0x3f);
+               value = (value << 6) | ((c - 'a' + 26) & 0x3F);
            } else if (c >= '0' && c <= '9') {
-               value = (value << 6) | ((c - '0' + 52) & 0x3f);
+               value = (value << 6) | ((c - '0' + 52) & 0x3F);
            } else if (c == '+') {
-               value = (value << 6) | 0x3e;
+               value = (value << 6) | 0x3E;
            } else if (c == '/') {
-               value = (value << 6) | 0x3f;
+               value = (value << 6) | 0x3F;
            } else if (c == '=' && (!strict || i > 1)) {
                /*
                 * "=" and "a=" is rather bad64 error case in strict mode.
@@ -2975,15 +3034,15 @@ BinaryDecode64(
                if (i) {
                    cut++;
                }
-           } else if (strict || !TclIsSpaceProc(c)) {
+           } else if (strict) {
                goto bad64;
            } else {
                i--;
            }
        }
-       *cursor++ = UCHAR((value >> 16) & 0xff);
-       *cursor++ = UCHAR((value >> 8) & 0xff);
-       *cursor++ = UCHAR(value & 0xff);
+       *cursor++ = UCHAR((value >> 16) & 0xFF);
+       *cursor++ = UCHAR((value >> 8) & 0xFF);
+       *cursor++ = UCHAR(value & 0xFF);
 
        /*
         * Since = is only valid within the final block, if it was encountered
@@ -2995,11 +3054,6 @@ BinaryDecode64(
            if (strict) {
                goto bad64;
            }
-           for (; data < dataend; data++) {
-               if (!TclIsSpaceProc(*data)) {
-                   goto bad64;
-               }
-           }
        }
     }
     Tcl_SetByteArrayLength(resultObj, cursor - begin - cut);
@@ -3007,9 +3061,21 @@ BinaryDecode64(
     return TCL_OK;
 
   bad64:
+    if (pure) {
+       ch = c;
+    } else {
+       /* The decoder is byte-oriented. If we saw a byte that's not a
+        * valid member of the base64 alphabet, it could be the lead byte
+        * of a multi-byte character. */
+
+       /* Safe because we know data is NUL-terminated */
+       TclUtfToUniChar((const char *)(data - 1), &ch);
+    }
+
     Tcl_SetObjResult(interp, Tcl_ObjPrintf(
-           "invalid base64 character \"%c\" at position %d",
-           (char) c, (int) (data - datastart - 1)));
+           "invalid base64 character \"%c\" at position %d", ch,
+           (int) (data - datastart - 1)));
+    Tcl_SetErrorCode(interp, "TCL", "BINARY", "DECODE", "INVALID", NULL);
     TclDecrRefCount(resultObj);
     return TCL_ERROR;
 }
index 26f092f..6d661f6 100644 (file)
@@ -244,7 +244,7 @@ ValidateMemory(
        if (byte != GUARD_VALUE) {
            guard_failed = TRUE;
            fflush(stdout);
-           byte &= 0xff;
+           byte &= 0xFF;
            fprintf(stderr, "low guard byte %d is 0x%x  \t%c\n", (int)idx, byte,
                    (isprint(UCHAR(byte)) ? byte : ' ')); /* INTL: bytes */
        }
@@ -265,7 +265,7 @@ ValidateMemory(
        if (byte != GUARD_VALUE) {
            guard_failed = TRUE;
            fflush(stdout);
-           byte &= 0xff;
+           byte &= 0xFF;
            fprintf(stderr, "hi guard byte %d is 0x%x  \t%c\n", (int)idx, byte,
                    (isprint(UCHAR(byte)) ? byte : ' ')); /* INTL: bytes */
        }
@@ -406,7 +406,7 @@ Tcl_DbCkalloc(
 
     /* Don't let size argument to TclpAlloc overflow */
     if (size <= UINT_MAX - HIGH_GUARD_SIZE -sizeof(struct mem_header)) {
-       result = (struct mem_header *) TclpAlloc((unsigned)size +
+       result = (struct mem_header *) TclpAlloc(size +
                sizeof(struct mem_header) + HIGH_GUARD_SIZE);
     }
     if (result == NULL) {
@@ -496,7 +496,7 @@ Tcl_AttemptDbCkalloc(
 
     /* Don't let size argument to TclpAlloc overflow */
     if (size <= UINT_MAX - HIGH_GUARD_SIZE - sizeof(struct mem_header)) {
-       result = (struct mem_header *) TclpAlloc((unsigned)size +
+       result = (struct mem_header *) TclpAlloc(size +
                sizeof(struct mem_header) + HIGH_GUARD_SIZE);
     }
     if (result == NULL) {
@@ -623,7 +623,7 @@ Tcl_DbCkfree(
     Tcl_MutexLock(ckallocMutexPtr);
     ValidateMemory(memp, file, line, TRUE);
     if (init_malloced_bodies) {
-       memset(ptr, GUARD_VALUE, (size_t) memp->length);
+       memset(ptr, GUARD_VALUE, memp->length);
     }
 
     total_frees++;
@@ -693,7 +693,7 @@ Tcl_DbCkrealloc(
        copySize = memp->length;
     }
     newPtr = Tcl_DbCkalloc(size, file, line);
-    memcpy(newPtr, ptr, (size_t) copySize);
+    memcpy(newPtr, ptr, copySize);
     Tcl_DbCkfree(ptr, file, line);
     return newPtr;
 }
@@ -727,7 +727,7 @@ Tcl_AttemptDbCkrealloc(
     if (newPtr == NULL) {
        return NULL;
     }
-    memcpy(newPtr, ptr, (size_t) copySize);
+    memcpy(newPtr, ptr, copySize);
     Tcl_DbCkfree(ptr, file, line);
     return newPtr;
 }
@@ -1324,7 +1324,7 @@ TclFinalizeMemorySubsystem(void)
     Tcl_MutexUnlock(ckallocMutexPtr);
 #endif
 
-#if USE_TCLALLOC
+#if defined(USE_TCLALLOC) && USE_TCLALLOC
     TclFinalizeAllocSubsystem();
 #endif
 }
index b531d3b..bab9fa5 100644 (file)
@@ -5,7 +5,7 @@
  *     the time and date facilities of TclX, by Mark Diekhans and Karl
  *     Lehenbauer.
  *
- * Copyright 1991-1995 Karl Lehenbauer and Mark Diekhans.
+ * Copyright (c) 1991-1995 Karl Lehenbauer & Mark Diekhans.
  * Copyright (c) 1995 Sun Microsystems, Inc.
  * Copyright (c) 2004 by Kevin B. Kenny. All rights reserved.
  *
@@ -263,7 +263,7 @@ TclClockInit(
     };
 
     /*
-     * Safe interps get [::clock] as alias to a master, so do not need their
+     * Safe interps get [::clock] as alias to a parent, so do not need their
      * own copies of the support routines.
      */
 
@@ -337,7 +337,7 @@ ClockConvertlocaltoutcObjCmd(
     Tcl_Obj *const *objv)      /* Parameter vector */
 {
     ClockClientData *data = clientData;
-    Tcl_Obj *const *literals = data->literals;
+    Tcl_Obj *const *lit = data->literals;
     Tcl_Obj *secondsObj;
     Tcl_Obj *dict;
     int changeover;
@@ -354,7 +354,7 @@ ClockConvertlocaltoutcObjCmd(
        return TCL_ERROR;
     }
     dict = objv[1];
-    if (Tcl_DictObjGet(interp, dict, literals[LIT_LOCALSECONDS],
+    if (Tcl_DictObjGet(interp, dict, lit[LIT_LOCALSECONDS],
            &secondsObj)!= TCL_OK) {
        return TCL_ERROR;
     }
@@ -380,7 +380,7 @@ ClockConvertlocaltoutcObjCmd(
        created = 1;
        Tcl_IncrRefCount(dict);
     }
-    status = Tcl_DictObjPut(interp, dict, literals[LIT_SECONDS],
+    status = Tcl_DictObjPut(interp, dict, lit[LIT_SECONDS],
            Tcl_NewWideIntObj(fields.seconds));
     if (status == TCL_OK) {
        Tcl_SetObjResult(interp, dict);
@@ -431,7 +431,7 @@ ClockGetdatefieldsObjCmd(
     TclDateFields fields;
     Tcl_Obj *dict;
     ClockClientData *data = clientData;
-    Tcl_Obj *const *literals = data->literals;
+    Tcl_Obj *const *lit = data->literals;
     int changeover;
 
     /*
@@ -453,7 +453,7 @@ ClockGetdatefieldsObjCmd(
      */
 
     if (objv[1]->typePtr == &tclBignumType) {
-       Tcl_SetObjResult(interp, literals[LIT_INTEGER_VALUE_TOO_LARGE]);
+       Tcl_SetObjResult(interp, lit[LIT_INTEGER_VALUE_TOO_LARGE]);
        return TCL_ERROR;
     }
 
@@ -481,33 +481,33 @@ ClockGetdatefieldsObjCmd(
     GetYearWeekDay(&fields, changeover);
 
     dict = Tcl_NewDictObj();
-    Tcl_DictObjPut(NULL, dict, literals[LIT_LOCALSECONDS],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_LOCALSECONDS],
            Tcl_NewWideIntObj(fields.localSeconds));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_SECONDS],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_SECONDS],
            Tcl_NewWideIntObj(fields.seconds));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_TZNAME], fields.tzName);
+    Tcl_DictObjPut(NULL, dict, lit[LIT_TZNAME], fields.tzName);
     Tcl_DecrRefCount(fields.tzName);
-    Tcl_DictObjPut(NULL, dict, literals[LIT_TZOFFSET],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_TZOFFSET],
            Tcl_NewIntObj(fields.tzOffset));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_JULIANDAY],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_JULIANDAY],
            Tcl_NewIntObj(fields.julianDay));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_GREGORIAN],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_GREGORIAN],
            Tcl_NewIntObj(fields.gregorian));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_ERA],
-           literals[fields.era ? LIT_BCE : LIT_CE]);
-    Tcl_DictObjPut(NULL, dict, literals[LIT_YEAR],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_ERA],
+           lit[fields.era ? LIT_BCE : LIT_CE]);
+    Tcl_DictObjPut(NULL, dict, lit[LIT_YEAR],
            Tcl_NewIntObj(fields.year));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_DAYOFYEAR],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_DAYOFYEAR],
            Tcl_NewIntObj(fields.dayOfYear));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_MONTH],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_MONTH],
            Tcl_NewIntObj(fields.month));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_DAYOFMONTH],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_DAYOFMONTH],
            Tcl_NewIntObj(fields.dayOfMonth));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_ISO8601YEAR],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_ISO8601YEAR],
            Tcl_NewIntObj(fields.iso8601Year));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_ISO8601WEEK],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_ISO8601WEEK],
            Tcl_NewIntObj(fields.iso8601Week));
-    Tcl_DictObjPut(NULL, dict, literals[LIT_DAYOFWEEK],
+    Tcl_DictObjPut(NULL, dict, lit[LIT_DAYOFWEEK],
            Tcl_NewIntObj(fields.dayOfWeek));
     Tcl_SetObjResult(interp, dict);
 
@@ -585,7 +585,7 @@ ClockGetjuliandayfromerayearmonthdayObjCmd(
     TclDateFields fields;
     Tcl_Obj *dict;
     ClockClientData *data = clientData;
-    Tcl_Obj *const *literals = data->literals;
+    Tcl_Obj *const *lit = data->literals;
     int changeover;
     int copied = 0;
     int status;
@@ -600,12 +600,12 @@ ClockGetjuliandayfromerayearmonthdayObjCmd(
        return TCL_ERROR;
     }
     dict = objv[1];
-    if (FetchEraField(interp, dict, literals[LIT_ERA], &era) != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_YEAR], &fields.year)
+    if (FetchEraField(interp, dict, lit[LIT_ERA], &era) != TCL_OK
+           || FetchIntField(interp, dict, lit[LIT_YEAR], &fields.year)
                != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_MONTH], &fields.month)
+           || FetchIntField(interp, dict, lit[LIT_MONTH], &fields.month)
                != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_DAYOFMONTH],
+           || FetchIntField(interp, dict, lit[LIT_DAYOFMONTH],
                &fields.dayOfMonth) != TCL_OK
            || TclGetIntFromObj(interp, objv[2], &changeover) != TCL_OK) {
        return TCL_ERROR;
@@ -627,7 +627,7 @@ ClockGetjuliandayfromerayearmonthdayObjCmd(
        Tcl_IncrRefCount(dict);
        copied = 1;
     }
-    status = Tcl_DictObjPut(interp, dict, literals[LIT_JULIANDAY],
+    status = Tcl_DictObjPut(interp, dict, lit[LIT_JULIANDAY],
            Tcl_NewIntObj(fields.julianDay));
     if (status == TCL_OK) {
        Tcl_SetObjResult(interp, dict);
@@ -669,7 +669,7 @@ ClockGetjuliandayfromerayearweekdayObjCmd(
     TclDateFields fields;
     Tcl_Obj *dict;
     ClockClientData *data = clientData;
-    Tcl_Obj *const *literals = data->literals;
+    Tcl_Obj *const *lit = data->literals;
     int changeover;
     int copied = 0;
     int status;
@@ -684,12 +684,12 @@ ClockGetjuliandayfromerayearweekdayObjCmd(
        return TCL_ERROR;
     }
     dict = objv[1];
-    if (FetchEraField(interp, dict, literals[LIT_ERA], &era) != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_ISO8601YEAR],
+    if (FetchEraField(interp, dict, lit[LIT_ERA], &era) != TCL_OK
+           || FetchIntField(interp, dict, lit[LIT_ISO8601YEAR],
                &fields.iso8601Year) != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_ISO8601WEEK],
+           || FetchIntField(interp, dict, lit[LIT_ISO8601WEEK],
                &fields.iso8601Week) != TCL_OK
-           || FetchIntField(interp, dict, literals[LIT_DAYOFWEEK],
+           || FetchIntField(interp, dict, lit[LIT_DAYOFWEEK],
                &fields.dayOfWeek) != TCL_OK
            || TclGetIntFromObj(interp, objv[2], &changeover) != TCL_OK) {
        return TCL_ERROR;
@@ -711,7 +711,7 @@ ClockGetjuliandayfromerayearweekdayObjCmd(
        Tcl_IncrRefCount(dict);
        copied = 1;
     }
-    status = Tcl_DictObjPut(interp, dict, literals[LIT_JULIANDAY],
+    status = Tcl_DictObjPut(interp, dict, lit[LIT_JULIANDAY],
            Tcl_NewIntObj(fields.julianDay));
     if (status == TCL_OK) {
        Tcl_SetObjResult(interp, dict);
@@ -1052,7 +1052,7 @@ ConvertUTCToLocalUsingC(
     time_t tock;
     struct tm *timeVal;                /* Time after conversion */
     int diff;                  /* Time zone diff local-Greenwich */
-    char buffer[8];            /* Buffer for time zone name */
+    char buffer[16];           /* Buffer for time zone name */
 
     /*
      * Use 'localtime' to determine local year, month, day, time of day.
index 40a10ba..58749fc 100644 (file)
@@ -173,7 +173,7 @@ Tcl_CaseObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register int i;
+    int i;
     int body, result, caseObjc;
     const char *stringPtr, *arg;
     Tcl_Obj *const *caseObjv;
@@ -228,7 +228,7 @@ Tcl_CaseObjCmd(
 
        pat = TclGetString(caseObjv[i]);
        for (p = pat; *p != '\0'; p++) {
-           if (TclIsSpaceProc(*p) || (*p == '\\')) {
+           if (TclIsSpaceProcM(*p) || (*p == '\\')) {
                break;
            }
        }
@@ -982,7 +982,7 @@ TclNREvalObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
     Interp *iPtr = (Interp *) interp;
     CmdFrame *invoker = NULL;
     int word = 0;
@@ -2493,7 +2493,7 @@ StoreStatData(
                                 * store in varName. */
 {
     Tcl_Obj *field, *value;
-    register unsigned short mode;
+    unsigned short mode;
 
     /*
      * Assume Tcl_ObjSetVar2() does not keep a copy of the field name!
@@ -2870,7 +2870,7 @@ EachloopCmd(
     Tcl_Obj *const objv[])
 {
     int numLists = (objc-2) / 2;
-    register struct ForeachState *statePtr;
+    struct ForeachState *statePtr;
     int i, j, result;
 
     if (objc < 4 || (objc%2 != 0)) {
@@ -2995,7 +2995,7 @@ ForeachLoopStep(
     Tcl_Interp *interp,
     int result)
 {
-    register struct ForeachState *statePtr = data[0];
+    struct ForeachState *statePtr = data[0];
 
     /*
      * Process the result code from this run of the [foreach] body. Note that
index 94c5413..85416a1 100644 (file)
@@ -401,7 +401,7 @@ Tcl_IncrObjCmd(
     if (objc == 3) {
        incrPtr = objv[2];
     } else {
-       incrPtr = Tcl_NewIntObj(1);
+       TclNewIntObj(incrPtr, 1);
     }
     Tcl_IncrRefCount(incrPtr);
     newValuePtr = TclIncrObjVar2(interp, objv[1], NULL,
@@ -472,7 +472,7 @@ InfoArgsCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     const char *name;
     Proc *procPtr;
     CompiledLocal *localPtr;
@@ -535,7 +535,7 @@ InfoBodyCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     const char *name;
     Proc *procPtr;
     Tcl_Obj *bodyPtr, *resultPtr;
@@ -650,7 +650,7 @@ InfoCommandsCmd(
 {
     const char *cmdName, *pattern;
     const char *simplePattern;
-    register Tcl_HashEntry *entryPtr;
+    Tcl_HashEntry *entryPtr;
     Tcl_HashSearch search;
     Namespace *nsPtr;
     Namespace *globalNsPtr = (Namespace *) Tcl_GetGlobalNamespace(interp);
@@ -719,7 +719,7 @@ InfoCommandsCmd(
        if (entryPtr != NULL) {
            if (specificNsInPattern) {
                cmd = Tcl_GetHashValue(entryPtr);
-               elemObjPtr = Tcl_NewObj();
+               TclNewObj(elemObjPtr);
                Tcl_GetCommandFullName(interp, cmd, elemObjPtr);
            } else {
                cmdName = Tcl_GetHashKey(&nsPtr->cmdTable, entryPtr);
@@ -770,7 +770,7 @@ InfoCommandsCmd(
                    || Tcl_StringMatch(cmdName, simplePattern)) {
                if (specificNsInPattern) {
                    cmd = Tcl_GetHashValue(entryPtr);
-                   elemObjPtr = Tcl_NewObj();
+                   TclNewObj(elemObjPtr);
                    Tcl_GetCommandFullName(interp, cmd, elemObjPtr);
                } else {
                    elemObjPtr = Tcl_NewStringObj(cmdName, -1);
@@ -997,8 +997,9 @@ InfoDefaultCmd(
                }
                Tcl_SetObjResult(interp, Tcl_NewIntObj(1));
            } else {
-               Tcl_Obj *nullObjPtr = Tcl_NewObj();
+               Tcl_Obj *nullObjPtr;
 
+               TclNewObj(nullObjPtr);
                valueObjPtr = Tcl_ObjSetVar2(interp, objv[3], NULL,
                        nullObjPtr, TCL_LEAVE_ERR_MSG);
                if (valueObjPtr == NULL) {
@@ -1054,7 +1055,7 @@ InfoErrorStackCmd(
 
     target = interp;
     if (objc == 2) {
-       target = Tcl_GetSlave(interp, Tcl_GetString(objv[1]));
+       target = Tcl_GetChild(interp, Tcl_GetString(objv[1]));
        if (target == NULL) {
            return TCL_ERROR;
        }
@@ -1845,7 +1846,7 @@ InfoProcsCmd(
     Namespace *currNsPtr = (Namespace *) Tcl_GetCurrentNamespace(interp);
     Tcl_Obj *listPtr, *elemObjPtr;
     int specificNsInPattern = 0;/* Init. to avoid compiler warning. */
-    register Tcl_HashEntry *entryPtr;
+    Tcl_HashEntry *entryPtr;
     Tcl_HashSearch search;
     Command *cmdPtr, *realCmdPtr;
 
@@ -1908,7 +1909,7 @@ InfoProcsCmd(
            } else {
            simpleProcOK:
                if (specificNsInPattern) {
-                   elemObjPtr = Tcl_NewObj();
+                   TclNewObj(elemObjPtr);
                    Tcl_GetCommandFullName(interp, (Tcl_Command) cmdPtr,
                            elemObjPtr);
                } else {
@@ -1936,7 +1937,7 @@ InfoProcsCmd(
                } else {
                procOK:
                    if (specificNsInPattern) {
-                       elemObjPtr = Tcl_NewObj();
+                       TclNewObj(elemObjPtr);
                        Tcl_GetCommandFullName(interp, (Tcl_Command) cmdPtr,
                                elemObjPtr);
                    } else {
@@ -2169,7 +2170,7 @@ Tcl_JoinObjCmd(
     joinObjPtr = (objc == 2) ? Tcl_NewStringObj(" ", 1) : objv[2];
     Tcl_IncrRefCount(joinObjPtr);
 
-    resObjPtr = Tcl_NewObj();
+    TclNewObj(resObjPtr);
     for (i = 0;  i < listLen;  i++) {
        if (i > 0) {
 
@@ -2343,7 +2344,7 @@ int
 Tcl_LinsertObjCmd(
     ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
-    register int objc,         /* Number of arguments. */
+    int objc,          /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     Tcl_Obj *listPtr;
@@ -2425,8 +2426,8 @@ int
 Tcl_ListObjCmd(
     ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
-    register int objc,         /* Number of arguments. */
-    register Tcl_Obj *const objv[])
+    int objc,          /* Number of arguments. */
+    Tcl_Obj *const objv[])
                                /* The argument objects. */
 {
     /*
@@ -2462,7 +2463,7 @@ Tcl_LlengthObjCmd(
     ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
-    register Tcl_Obj *const objv[])
+    Tcl_Obj *const objv[])
                                /* Argument objects. */
 {
     int listLen, result;
@@ -2508,7 +2509,7 @@ Tcl_LrangeObjCmd(
     ClientData notUsed,                /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
-    register Tcl_Obj *const objv[])
+    Tcl_Obj *const objv[])
                                /* Argument objects. */
 {
     Tcl_Obj **elemPtrs;
@@ -2602,8 +2603,8 @@ int
 Tcl_LrepeatObjCmd(
     ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
-    register int objc,         /* Number of arguments. */
-    register Tcl_Obj *const objv[])
+    int objc,          /* Number of arguments. */
+    Tcl_Obj *const objv[])
                                /* The argument objects. */
 {
     int elementCount, i, totalElems;
@@ -2668,7 +2669,7 @@ Tcl_LrepeatObjCmd(
 
     CLANG_ASSERT(dataArray || totalElems == 0 );
     if (objc == 1) {
-       register Tcl_Obj *tmpPtr = objv[0];
+       Tcl_Obj *tmpPtr = objv[0];
 
        tmpPtr->refCount += elementCount;
        for (i=0 ; i<elementCount ; i++) {
@@ -2714,7 +2715,7 @@ Tcl_LreplaceObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Tcl_Obj *listPtr;
+    Tcl_Obj *listPtr;
     int first, last, listLen, numToDelete, result;
 
     if (objc < 4) {
@@ -3328,11 +3329,11 @@ Tcl_LsearchObjCmd(
                /*
                 * Normally, binary search is written to stop when it finds a
                 * match. If there are duplicates of an element in the list,
-                * our first match might not be the first occurance.
+                * our first match might not be the first occurrence.
                 * Consider: 0 0 0 1 1 1 2 2 2
                 *
                 * To maintain consistancy with standard lsearch semantics, we
-                * must find the leftmost occurance of the pattern in the
+                * must find the leftmost occurrence of the pattern in the
                 * list. Thus we don't just stop searching here. This
                 * variation means that a search always makes log n
                 * comparisons (normal binary search might "get lucky" with an
@@ -3485,7 +3486,7 @@ Tcl_LsearchObjCmd(
            } else if (returnSubindices) {
                int j;
 
-               itemPtr = Tcl_NewIntObj(i);
+               TclNewIntObj(itemPtr, i);
                for (j=0 ; j<sortInfo.indexc ; j++) {
                    Tcl_ListObjAppendElement(interp, itemPtr, Tcl_NewIntObj(
                            TclIndexDecode(sortInfo.indexv[j], listc)));
@@ -3507,7 +3508,7 @@ Tcl_LsearchObjCmd(
        if (returnSubindices) {
            int j;
 
-           itemPtr = Tcl_NewIntObj(index);
+           TclNewIntObj(itemPtr, index);
            for (j=0 ; j<sortInfo.indexc ; j++) {
                Tcl_ListObjAppendElement(interp, itemPtr, Tcl_NewIntObj(
                        TclIndexDecode(sortInfo.indexv[j], listc)));
@@ -3652,9 +3653,11 @@ Tcl_LsortObjCmd(
     int sortMode = SORTMODE_ASCII;
     int group, groupSize, groupOffset, idx, allocatedIndexVector = 0;
     Tcl_Obj *resultPtr, *cmdPtr, **listObjPtrs, *listObj, *indexPtr;
+    size_t elmArrSize;
     SortElement *elementArray = NULL, *elementPtr;
     SortInfo sortInfo;         /* Information about this sort that needs to
                                 * be passed to the comparison function. */
+#   define MAXCALLOC 1024000
 #   define NUM_LISTS 30
     SortElement *subList[NUM_LISTS+1];
                                /* This array holds pointers to temporary
@@ -3727,7 +3730,7 @@ Tcl_LsortObjCmd(
            sortInfo.isIncreasing = 1;
            break;
        case LSORT_INDEX: {
-           int indexc;
+           int sortindex;
            Tcl_Obj **indexv;
 
            if (i == objc-2) {
@@ -3738,7 +3741,7 @@ Tcl_LsortObjCmd(
                sortInfo.resultCode = TCL_ERROR;
                goto done;
            }
-           if (TclListObjGetElements(interp, objv[i+1], &indexc,
+           if (TclListObjGetElements(interp, objv[i+1], &sortindex,
                    &indexv) != TCL_OK) {
                sortInfo.resultCode = TCL_ERROR;
                goto done;
@@ -3752,7 +3755,7 @@ Tcl_LsortObjCmd(
             * options is done.
             */
 
-           for (j=0 ; j<indexc ; j++) {
+           for (j=0 ; j<sortindex ; j++) {
                int encoded = 0;
                int result = TclIndexEncode(interp, indexv[j],
                        TCL_INDEX_BEFORE, TCL_INDEX_AFTER, &encoded);
@@ -3977,7 +3980,19 @@ Tcl_LsortObjCmd(
      * begins sorting it into the sublists as it appears.
      */
 
-    elementArray = ckalloc(length * sizeof(SortElement));
+    elmArrSize = length * sizeof(SortElement);
+    if (elmArrSize <= MAXCALLOC) {
+       elementArray = ckalloc(elmArrSize);
+    } else {
+       elementArray = malloc(elmArrSize);
+    }
+    if (!elementArray) {
+       Tcl_SetObjResult(interp, Tcl_ObjPrintf(
+               "no enough memory to proccess sort of %d items", length));
+       Tcl_SetErrorCode(interp, "TCL", "MEMORY", NULL);
+       sortInfo.resultCode = TCL_ERROR;
+       goto done;
+    }
 
     for (i=0; i < length; i++){
        idx = groupSize * i + groupOffset;
@@ -4073,7 +4088,7 @@ Tcl_LsortObjCmd(
                idx = elementPtr->payload.index;
                for (j = 0; j < groupSize; j++) {
                    if (indices) {
-                       objPtr = Tcl_NewIntObj(idx + j - groupOffset);
+                       TclNewIntObj(objPtr, idx + j - groupOffset);
                        newArray[i++] = objPtr;
                        Tcl_IncrRefCount(objPtr);
                    } else {
@@ -4085,7 +4100,7 @@ Tcl_LsortObjCmd(
            }
        } else if (indices) {
            for (i=0; elementPtr != NULL ; elementPtr = elementPtr->nextPtr) {
-               objPtr = Tcl_NewIntObj(elementPtr->payload.index);
+               TclNewIntObj(objPtr, elementPtr->payload.index);
                newArray[i++] = objPtr;
                Tcl_IncrRefCount(objPtr);
            }
@@ -4110,7 +4125,11 @@ Tcl_LsortObjCmd(
        TclStackFree(interp, sortInfo.indexv);
     }
     if (elementArray) {
-       ckfree(elementArray);
+       if (elmArrSize <= MAXCALLOC) {
+           ckfree((char *)elementArray);
+       } else {
+           free((char *)elementArray);
+       }
     }
     return sortInfo.resultCode;
 }
@@ -4352,7 +4371,7 @@ static int
 DictionaryCompare(
     const char *left, const char *right)       /* The strings to compare. */
 {
-    Tcl_UniChar uniLeft = 0, uniRight = 0, uniLeftLower, uniRightLower;
+    int uniLeft = 0, uniRight = 0, uniLeftLower, uniRightLower;
     int diff, zeros;
     int secondaryDiff = 0;
 
@@ -4421,8 +4440,8 @@ DictionaryCompare(
         */
 
        if ((*left != '\0') && (*right != '\0')) {
-           left += TclUtfToUniChar(left, &uniLeft);
-           right += TclUtfToUniChar(right, &uniRight);
+           left += TclUtfToUCS4(left, &uniLeft);
+           right += TclUtfToUCS4(right, &uniRight);
 
            /*
             * Convert both chars to lower for the comparison, because
@@ -4431,8 +4450,8 @@ DictionaryCompare(
             * other interesting punctuations occur).
             */
 
-           uniLeftLower = Tcl_UniCharToLower(uniLeft);
-           uniRightLower = Tcl_UniCharToLower(uniRight);
+           uniLeftLower = TclUCS4ToLower(uniLeft);
+           uniRightLower = TclUCS4ToLower(uniRight);
        } else {
            diff = UCHAR(*left) - UCHAR(*right);
            break;
index 193eac4..ee30a7a 100644 (file)
@@ -36,31 +36,31 @@ static int          UniCharIsHexDigit(int character);
  */
 
 const char tclDefaultTrimSet[] =
-       "\x09\x0a\x0b\x0c\x0d " /* ASCII */
-       "\xc0\x80" /*     nul (U+0000) */
-       "\xc2\x85" /*     next line (U+0085) */
-       "\xc2\xa0" /*     non-breaking space (U+00a0) */
-       "\xe1\x9a\x80" /* ogham space mark (U+1680) */
-       "\xe1\xa0\x8e" /* mongolian vowel separator (U+180e) */
-       "\xe2\x80\x80" /* en quad (U+2000) */
-       "\xe2\x80\x81" /* em quad (U+2001) */
-       "\xe2\x80\x82" /* en space (U+2002) */
-       "\xe2\x80\x83" /* em space (U+2003) */
-       "\xe2\x80\x84" /* three-per-em space (U+2004) */
-       "\xe2\x80\x85" /* four-per-em space (U+2005) */
-       "\xe2\x80\x86" /* six-per-em space (U+2006) */
-       "\xe2\x80\x87" /* figure space (U+2007) */
-       "\xe2\x80\x88" /* punctuation space (U+2008) */
-       "\xe2\x80\x89" /* thin space (U+2009) */
-       "\xe2\x80\x8a" /* hair space (U+200a) */
-       "\xe2\x80\x8b" /* zero width space (U+200b) */
-       "\xe2\x80\xa8" /* line separator (U+2028) */
-       "\xe2\x80\xa9" /* paragraph separator (U+2029) */
-       "\xe2\x80\xaf" /* narrow no-break space (U+202f) */
-       "\xe2\x81\x9f" /* medium mathematical space (U+205f) */
-       "\xe2\x81\xa0" /* word joiner (U+2060) */
-       "\xe3\x80\x80" /* ideographic space (U+3000) */
-       "\xef\xbb\xbf" /* zero width no-break space (U+feff) */
+       "\x09\x0A\x0B\x0C\x0D " /* ASCII */
+       "\xC0\x80" /*     nul (U+0000) */
+       "\xC2\x85" /*     next line (U+0085) */
+       "\xC2\xA0" /*     non-breaking space (U+00a0) */
+       "\xE1\x9A\x80" /* ogham space mark (U+1680) */
+       "\xE1\xA0\x8E" /* mongolian vowel separator (U+180e) */
+       "\xE2\x80\x80" /* en quad (U+2000) */
+       "\xE2\x80\x81" /* em quad (U+2001) */
+       "\xE2\x80\x82" /* en space (U+2002) */
+       "\xE2\x80\x83" /* em space (U+2003) */
+       "\xE2\x80\x84" /* three-per-em space (U+2004) */
+       "\xE2\x80\x85" /* four-per-em space (U+2005) */
+       "\xE2\x80\x86" /* six-per-em space (U+2006) */
+       "\xE2\x80\x87" /* figure space (U+2007) */
+       "\xE2\x80\x88" /* punctuation space (U+2008) */
+       "\xE2\x80\x89" /* thin space (U+2009) */
+       "\xE2\x80\x8A" /* hair space (U+200a) */
+       "\xE2\x80\x8B" /* zero width space (U+200b) */
+       "\xE2\x80\xA8" /* line separator (U+2028) */
+       "\xE2\x80\xA9" /* paragraph separator (U+2029) */
+       "\xE2\x80\xAF" /* narrow no-break space (U+202f) */
+       "\xE2\x81\x9F" /* medium mathematical space (U+205f) */
+       "\xE2\x81\xA0" /* word joiner (U+2060) */
+       "\xE3\x80\x80" /* ideographic space (U+3000) */
+       "\xEF\xBB\xBF" /* zero width no-break space (U+feff) */
 ;
 \f
 /*
@@ -357,7 +357,7 @@ Tcl_RegexpObjCmd(
 
            objc = info.nsubs + 1;
            if (all <= 1) {
-               resultPtr = Tcl_NewObj();
+               TclNewObj(resultPtr);
            }
        }
        for (i = 0; i < objc; i++) {
@@ -399,7 +399,7 @@ Tcl_RegexpObjCmd(
                            offset + info.matches[i].start,
                            offset + info.matches[i].end - 1);
                } else {
-                   newPtr = Tcl_NewObj();
+                   TclNewObj(newPtr);
                }
            }
            if (doinline) {
@@ -1058,7 +1058,7 @@ Tcl_SplitObjCmd(
 
     stringPtr = TclGetStringFromObj(objv[1], &stringLen);
     end = stringPtr + stringLen;
-    listPtr = Tcl_NewObj();
+    TclNewObj(listPtr);
 
     if (stringLen == 0) {
        /*
@@ -1081,23 +1081,10 @@ Tcl_SplitObjCmd(
        Tcl_InitHashTable(&charReuseTable, TCL_ONE_WORD_KEYS);
 
        for ( ; stringPtr < end; stringPtr += len) {
-           int fullchar;
-           len = TclUtfToUniChar(stringPtr, &ch);
-           fullchar = ch;
+           int ucs4;
 
-#if TCL_UTF_MAX == 4
-           if ((ch >= 0xD800) && (len < 3)) {
-               len += TclUtfToUniChar(stringPtr + len, &ch);
-               fullchar = (((fullchar & 0x3ff) << 10) | (ch & 0x3ff)) + 0x10000;
-           }
-#endif
-
-           /*
-            * Assume Tcl_UniChar is an integral type...
-            */
-
-           hPtr = Tcl_CreateHashEntry(&charReuseTable, INT2PTR(fullchar),
-                   &isNew);
+           len = TclUtfToUCS4(stringPtr, &ucs4);
+           hPtr = Tcl_CreateHashEntry(&charReuseTable, INT2PTR(ucs4), &isNew);
            if (isNew) {
                TclNewStringObj(objPtr, stringPtr, len);
 
@@ -1244,7 +1231,7 @@ StringFirstCmd(
      */
 
     if (needleLen > 0 && needleLen <= haystackLen) {
-       register Tcl_UniChar *p, *end;
+       Tcl_UniChar *p, *end;
 
        end = haystackStr + haystackLen - needleLen + 1;
        for (p = haystackStr;  p < end;  p++) {
@@ -1414,7 +1401,7 @@ StringIndexCmd(
     }
 
     if ((index >= 0) && (index < length)) {
-       Tcl_UniChar ch = Tcl_GetUniChar(objv[1], index);
+       int ch = TclGetUCS4(objv[1], index);
 
        /*
         * If we have a ByteArray object, we're careful to generate a new
@@ -1422,18 +1409,13 @@ StringIndexCmd(
         */
 
        if (TclIsPureByteArray(objv[1])) {
-           unsigned char uch = (unsigned char) ch;
+           unsigned char uch = UCHAR(ch);
 
            Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(&uch, 1));
        } else {
-           char buf[TCL_UTF_MAX] = "";
+           char buf[8] = "";
 
-           length = Tcl_UniCharToUtf(ch, buf);
-#if TCL_UTF_MAX > 3
-           if ((ch >= 0xD800) && (length < 3)) {
-               length += Tcl_UniCharToUtf(-1, buf + length);
-           }
-#endif
+           length = TclUCS4ToUtf(ch, buf);
            Tcl_SetObjResult(interp, Tcl_NewStringObj(buf, length));
        }
     }
@@ -1466,7 +1448,6 @@ StringIsCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     const char *string1, *end, *stop;
-    Tcl_UniChar ch = 0;
     int (*chcomp)(int) = NULL; /* The UniChar comparison function. */
     int i, failat = 0, result = 1, strict = 0, index, length1, length2;
     Tcl_Obj *objPtr, *failVarObj = NULL;
@@ -1731,7 +1712,7 @@ StringIsCmd(
 
            const char *elemStart, *nextElem;
            int lenRemain, elemSize;
-           register const char *p;
+           const char *p;
 
            string1 = TclGetStringFromObj(objPtr, &length1);
            end = string1 + length1;
@@ -1752,7 +1733,7 @@ StringIsCmd(
                     * if it is the first "element" that has the failure.
                     */
 
-                   while (TclIsSpaceProc(*p)) {
+                   while (TclIsSpaceProcM(*p)) {
                        p++;
                    }
                    TclNewStringObj(tmpStr, string1, p-string1);
@@ -1797,16 +1778,10 @@ StringIsCmd(
        }
        end = string1 + length1;
        for (; string1 < end; string1 += length2, failat++) {
-           int fullchar;
-           length2 = TclUtfToUniChar(string1, &ch);
-           fullchar = ch;
-#if TCL_UTF_MAX == 4
-           if ((ch >= 0xD800) && (length2 < 3)) {
-               length2 += TclUtfToUniChar(string1 + length2, &ch);
-               fullchar = (((fullchar & 0x3ff) << 10) | (ch & 0x3ff)) + 0x10000;
-           }
-#endif
-           if (!chcomp(fullchar)) {
+           int ucs4;
+
+           length2 = TclUtfToUCS4(string1, &ucs4);
+           if (!chcomp(ucs4)) {
                result = 0;
                break;
            }
@@ -2060,7 +2035,7 @@ StringMapCmd(
                        (Tcl_UniCharToLower(*ustring1) == u2lc[index/2]))) &&
                        /* Restrict max compare length. */
                        (end-ustring1 >= length2) && ((length2 == 1) ||
-                       !strCmpFn(ustring2, ustring1, (unsigned) length2))) {
+                       !strCmpFn(ustring2, ustring1, length2))) {
                    if (p != ustring1) {
                        /*
                         * Put the skipped chars onto the result first.
@@ -2297,7 +2272,7 @@ StringReptCmd(
      * Include space for the NUL.
      */
 
-    string2 = attemptckalloc((unsigned) length2 + 1);
+    string2 = attemptckalloc(length2 + 1);
     if (string2 == NULL) {
        /*
         * Alloc failed. Note that in this case we try to do an error message
@@ -2313,7 +2288,7 @@ StringReptCmd(
        return TCL_ERROR;
     }
     for (index = 0; index < count; index++) {
-       memcpy(string2 + (length1 * index), string1, (size_t) length1);
+       memcpy(string2 + (length1 * index), string1, length1);
     }
     string2[length2] = '\0';
 
@@ -2446,7 +2421,7 @@ StringRevCmd(
        return TCL_ERROR;
     }
 
-    Tcl_SetObjResult(interp, TclStringObjReverse(objv[1]));
+    Tcl_SetObjResult(interp, TclStringReverse(objv[1]));
     return TCL_OK;
 }
 \f
@@ -2497,12 +2472,22 @@ StringStartCmd(
     cur = 0;
     if (index > 0) {
        p = Tcl_UtfAtIndex(string, index);
+
+       TclUtfToUniChar(p, &ch);
        for (cur = index; cur >= 0; cur--) {
-           TclUtfToUniChar(p, &ch);
+           int delta = 0;
+           const char *next;
+
            if (!Tcl_UniCharIsWordChar(ch)) {
                break;
            }
-           p = Tcl_UtfPrev(p, string);
+
+           next = TclUtfPrev(p, string);
+           do {
+               next += delta;
+               delta = TclUtfToUniChar(next, &ch);
+           } while (next + delta < p);
+           p = next;
        }
        if (cur != index) {
            cur += 1;
@@ -2865,7 +2850,7 @@ TclStringCmp(
         * The comparison function should compare up to the minimum byte
         * length only.
         */
-       match = memCmpFn(s1, s2, (size_t) length);
+       match = memCmpFn(s1, s2, length);
     }
     if ((match == 0) && (reqlength > length)) {
        match = s1len - s2len;
@@ -3930,7 +3915,8 @@ TclNRSwitchObjCmd(
                    rangeObjAry[0] = Tcl_NewLongObj(info.matches[j].start);
                    rangeObjAry[1] = Tcl_NewLongObj(info.matches[j].end-1);
                } else {
-                   rangeObjAry[0] = rangeObjAry[1] = Tcl_NewIntObj(-1);
+                   TclNewIntObj(rangeObjAry[1], -1);
+                   rangeObjAry[0] = rangeObjAry[1];
                }
 
                /*
@@ -4200,9 +4186,9 @@ Tcl_TimeObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
     Tcl_Obj *objs[4];
-    register int i, result;
+    int i, result;
     int count;
     double totalMicroSec;
 #ifndef TCL_WIDE_CLICKS
@@ -4301,8 +4287,8 @@ Tcl_TimeRateObjCmd(
     static double measureOverhead = 0;
                                /* global measure-overhead */
     double overhead = -1;      /* given measure-overhead */
-    register Tcl_Obj *objPtr;
-    register int result, i;
+    Tcl_Obj *objPtr;
+    int result, i;
     Tcl_Obj *calibrate = NULL, *direct = NULL;
     TclWideMUInt count = 0;    /* Holds repetition count */
     Tcl_WideInt maxms = WIDE_MIN;
@@ -4316,7 +4302,7 @@ Tcl_TimeRateObjCmd(
                                 * zero (i.e., never < 1) */
     unsigned short factor = 50;        /* Factor (4..50) limiting threshold to avoid
                                 * growth of execution time. */
-    register Tcl_WideInt start, middle, stop;
+    Tcl_WideInt start, middle, stop;
 #ifndef TCL_WIDE_CLICKS
     Tcl_Time now;
 #endif /* !TCL_WIDE_CLICKS */
@@ -4872,7 +4858,7 @@ TclNRTryObjCmd(
        return TCL_ERROR;
     }
     bodyObj = objv[1];
-    handlersObj = Tcl_NewObj();
+    TclNewObj(handlersObj);
     bodyShared = 0;
     haveHandlers = 0;
     for (i=2 ; i<objc ; i++) {
index d8f0aeb..c8970ce 100644 (file)
@@ -138,9 +138,9 @@ TclCompileAppendCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr, *valueTokenPtr;
     int isScalar, localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
 
     /* TODO: Consider support for compiling expanded args. */
     numWords = parsePtr->numWords;
@@ -403,9 +403,9 @@ TclCompileArraySetCmd(
     keyVar = AnonymousLocal(envPtr);
     valVar = AnonymousLocal(envPtr);
 
-    infoPtr = ckalloc(sizeof(ForeachInfo));
+    infoPtr = ckalloc(TclOffset(ForeachInfo, varLists) + sizeof(ForeachVarList *));
     infoPtr->numLists = 1;
-    infoPtr->varLists[0] = ckalloc(sizeof(ForeachVarList) + sizeof(int));
+    infoPtr->varLists[0] = ckalloc(TclOffset(ForeachVarList, varIndexes) + 2 * sizeof(int));
     infoPtr->varLists[0]->numVars = 2;
     infoPtr->varLists[0]->varIndexes[0] = keyVar;
     infoPtr->varLists[0]->varIndexes[1] = valVar;
@@ -587,10 +587,10 @@ TclCompileCatchCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     JumpFixup jumpFixup;
     Tcl_Token *cmdTokenPtr, *resultNameTokenPtr, *optsNameTokenPtr;
     int resultIndex, optsIndex, range, dropScript = 0;
-    DefineLineInformation;     /* TIP #280 */
     int depth = TclGetStackDepth(envPtr);
 
     /*
@@ -620,13 +620,11 @@ TclCompileCatchCmd(
     cmdTokenPtr = TokenAfter(parsePtr->tokenPtr);
     if (parsePtr->numWords >= 3) {
        resultNameTokenPtr = TokenAfter(cmdTokenPtr);
-       /* DGP */
        resultIndex = LocalScalarFromToken(resultNameTokenPtr, envPtr);
        if (resultIndex < 0) {
            return TCL_ERROR;
        }
 
-       /* DKF */
        if (parsePtr->numWords == 4) {
            optsNameTokenPtr = TokenAfter(resultNameTokenPtr);
            optsIndex = LocalScalarFromToken(optsNameTokenPtr, envPtr);
@@ -1022,10 +1020,9 @@ TclCompileDictSetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr;
-    int i, dictVarIndex;
     DefineLineInformation;     /* TIP #280 */
-    Tcl_Token *varTokenPtr;
+    Tcl_Token *tokenPtr, *varTokenPtr;
+    int i, dictVarIndex;
 
     /*
      * There must be at least one argument after the command.
@@ -1148,9 +1145,9 @@ TclCompileDictGetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr;
     int i;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * There must be at least two arguments after the command (the single-arg
@@ -1185,9 +1182,9 @@ TclCompileDictExistsCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr;
     int i;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * There must be at least two arguments after the command (the single-arg
@@ -1222,8 +1219,8 @@ TclCompileDictUnsetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
     int i, dictVarIndex;
 
     /*
@@ -1779,7 +1776,7 @@ TclCompileDictUpdateCmd(
      * that are to be used.
      */
 
-    duiPtr = ckalloc(sizeof(DictUpdateInfo) + sizeof(int) * (numVars - 1));
+    duiPtr = ckalloc(TclOffset(DictUpdateInfo, varIndices) + sizeof(int) * numVars);
     duiPtr->length = numVars;
     keyTokenPtrs = TclStackAlloc(interp, sizeof(Tcl_Token *) * numVars);
     tokenPtr = TokenAfter(dictVarTokenPtr);
@@ -2261,7 +2258,7 @@ DupDictUpdateInfo(
     unsigned len;
 
     dui1Ptr = clientData;
-    len = sizeof(DictUpdateInfo) + sizeof(int) * (dui1Ptr->length - 1);
+    len = TclOffset(DictUpdateInfo, varIndices) + sizeof(int) * dui1Ptr->length;
     dui2Ptr = ckalloc(len);
     memcpy(dui2Ptr, dui1Ptr, len);
     return dui2Ptr;
@@ -2338,13 +2335,13 @@ TclCompileErrorCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
+
     /*
      * General syntax: [error message ?errorInfo? ?errorCode?]
      */
 
-    Tcl_Token *tokenPtr;
-    DefineLineInformation;     /* TIP #280 */
-
     if (parsePtr->numWords < 2 || parsePtr->numWords > 4) {
        return TCL_ERROR;
     }
@@ -2457,11 +2454,11 @@ TclCompileForCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *startTokenPtr, *testTokenPtr, *nextTokenPtr, *bodyTokenPtr;
     JumpFixup jumpEvalCondFixup;
     int bodyCodeOffset, nextCodeOffset, jumpDist;
     int bodyRange, nextRange;
-    DefineLineInformation;     /* TIP #280 */
 
     if (parsePtr->numWords != 5) {
        return TCL_ERROR;
@@ -2670,6 +2667,7 @@ CompileEachloopCmd(
     int collect)               /* Select collecting or accumulating mode
                                 * (TCL_EACH_*) */
 {
+    DefineLineInformation;     /* TIP #280 */
     Proc *procPtr = envPtr->procPtr;
     ForeachInfo *infoPtr=NULL; /* Points to the structure describing this
                                 * foreach command. Stored in a AuxData
@@ -2679,7 +2677,6 @@ CompileEachloopCmd(
     int jumpBackOffset, infoIndex, range;
     int numWords, numLists, i, j, code = TCL_OK;
     Tcl_Obj *varListObj = NULL;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * If the foreach command isn't in a procedure, don't compile it inline:
@@ -2715,8 +2712,8 @@ CompileEachloopCmd(
      */
 
     numLists = (numWords - 2)/2;
-    infoPtr = ckalloc(sizeof(ForeachInfo)
-           + (numLists - 1) * sizeof(ForeachVarList *));
+    infoPtr = ckalloc(TclOffset(ForeachInfo, varLists)
+           + numLists * sizeof(ForeachVarList *));
     infoPtr->numLists = 0;     /* Count this up as we go */
 
     /*
@@ -2749,8 +2746,8 @@ CompileEachloopCmd(
            goto done;
        }
 
-       varListPtr = ckalloc(sizeof(ForeachVarList)
-               + (numVars - 1) * sizeof(int));
+       varListPtr = ckalloc(TclOffset(ForeachVarList, varIndexes)
+               + numVars * sizeof(int));
        varListPtr->numVars = numVars;
        infoPtr->varLists[i/2] = varListPtr;
        infoPtr->numLists++;
@@ -2880,12 +2877,12 @@ DupForeachInfo(
     ClientData clientData)     /* The foreach command's compilation auxiliary
                                 * data to duplicate. */
 {
-    register ForeachInfo *srcPtr = clientData;
+    ForeachInfo *srcPtr = clientData;
     ForeachInfo *dupPtr;
-    register ForeachVarList *srcListPtr, *dupListPtr;
+    ForeachVarList *srcListPtr, *dupListPtr;
     int numVars, i, j, numLists = srcPtr->numLists;
 
-    dupPtr = ckalloc(sizeof(ForeachInfo)
+    dupPtr = ckalloc(TclOffset(ForeachInfo, varLists)
            + numLists * sizeof(ForeachVarList *));
     dupPtr->numLists = numLists;
     dupPtr->firstValueTemp = srcPtr->firstValueTemp;
@@ -2894,7 +2891,7 @@ DupForeachInfo(
     for (i = 0;  i < numLists;  i++) {
        srcListPtr = srcPtr->varLists[i];
        numVars = srcListPtr->numVars;
-       dupListPtr = ckalloc(sizeof(ForeachVarList)
+       dupListPtr = ckalloc(TclOffset(ForeachVarList, varIndexes)
                + numVars * sizeof(int));
        dupListPtr->numVars = numVars;
        for (j = 0;  j < numVars;  j++) {
@@ -2929,10 +2926,10 @@ FreeForeachInfo(
     ClientData clientData)     /* The foreach command's compilation auxiliary
                                 * data to free. */
 {
-    register ForeachInfo *infoPtr = clientData;
-    register ForeachVarList *listPtr;
+    ForeachInfo *infoPtr = clientData;
+    ForeachVarList *listPtr;
     int numLists = infoPtr->numLists;
-    register int i;
+    int i;
 
     for (i = 0;  i < numLists;  i++) {
        listPtr = infoPtr->varLists[i];
@@ -2965,8 +2962,8 @@ PrintForeachInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register ForeachInfo *infoPtr = clientData;
-    register ForeachVarList *varsPtr;
+    ForeachInfo *infoPtr = clientData;
+    ForeachVarList *varsPtr;
     int i, j;
 
     Tcl_AppendToObj(appendObj, "data=[", -1);
@@ -3005,8 +3002,8 @@ PrintNewForeachInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register ForeachInfo *infoPtr = clientData;
-    register ForeachVarList *varsPtr;
+    ForeachInfo *infoPtr = clientData;
+    ForeachVarList *varsPtr;
     int i, j;
 
     Tcl_AppendPrintfToObj(appendObj, "jumpOffset=%+d, vars=",
@@ -3035,8 +3032,8 @@ DisassembleForeachInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register ForeachInfo *infoPtr = clientData;
-    register ForeachVarList *varsPtr;
+    ForeachInfo *infoPtr = clientData;
+    ForeachVarList *varsPtr;
     int i, j;
     Tcl_Obj *objPtr, *innerPtr;
 
@@ -3082,8 +3079,8 @@ DisassembleNewForeachInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register ForeachInfo *infoPtr = clientData;
-    register ForeachVarList *varsPtr;
+    ForeachInfo *infoPtr = clientData;
+    ForeachVarList *varsPtr;
     int i, j;
     Tcl_Obj *objPtr, *innerPtr;
 
@@ -3407,9 +3404,9 @@ TclPushVarName(
     int *localIndexPtr,                /* Must not be NULL. */
     int *isScalarPtr)          /* Must not be NULL. */
 {
-    register const char *p;
+    const char *p;
     const char *last, *name, *elName;
-    register int n;
+    int n;
     Tcl_Token *elemTokenPtr = NULL;
     int nameLen, elNameLen, simpleVarName, localIndex;
     int elemTokenCount = 0, allocedTokens = 0, removedParen = 0;
@@ -3441,10 +3438,10 @@ TclPushVarName(
            /*
             * last char is ')' => potential array reference.
             */
-           last = Tcl_UtfPrev(name + nameLen, name);
+           last = &name[nameLen-1];
 
            if (*last == ')') {
-               for (p = name;  p < last;  p = Tcl_UtfNext(p)) {
+               for (p = name;  p < last;  p++) {
                    if (*p == '(') {
                        elName = p + 1;
                        elNameLen = last - elName;
@@ -3472,15 +3469,14 @@ TclPushVarName(
     } else if (interp && ((n = varTokenPtr->numComponents) > 1)
            && (varTokenPtr[1].type == TCL_TOKEN_TEXT)
            && (varTokenPtr[n].type == TCL_TOKEN_TEXT)
-           && (*((p = varTokenPtr[n].start + varTokenPtr[n].size)-1) == ')')
-           && (*Tcl_UtfPrev(p, varTokenPtr[n].start) == ')')) {
+           && (*(varTokenPtr[n].start + varTokenPtr[n].size - 1) == ')')) {
        /*
         * Check for parentheses inside first token.
         */
 
        simpleVarName = 0;
        for (p = varTokenPtr[1].start,
-            last = p + varTokenPtr[1].size;  p < last;  p = Tcl_UtfNext(p)) {
+            last = p + varTokenPtr[1].size;  p < last;  p++) {
            if (*p == '(') {
                simpleVarName = 1;
                break;
@@ -3548,7 +3544,7 @@ TclPushVarName(
 
        int hasNsQualifiers = 0;
 
-       for (p = name, last = p + nameLen-1;  p < last;  p = Tcl_UtfNext(p)) {
+       for (p = name, last = p + nameLen-1;  p < last;  p++) {
            if ((*p == ':') && (*(p+1) == ':')) {
                hasNsQualifiers = 1;
                break;
index 324db41..c453878 100644 (file)
@@ -91,9 +91,9 @@ TclCompileGlobalCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr;
     int localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
 
     /* TODO: Consider support for compiling expanded args. */
     numWords = parsePtr->numWords;
@@ -170,6 +170,7 @@ TclCompileIfCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     JumpFixupArray jumpFalseFixupArray;
                                /* Used to fix the ifFalse jump after each
                                 * test when its target PC is determined. */
@@ -185,7 +186,6 @@ TclCompileIfCmd(
                                 * "if 0 {..}" */
     int boolVal;               /* Value of static condition. */
     int compileScripts = 1;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * Only compile the "if" command if all arguments are simple words, in
@@ -473,9 +473,9 @@ TclCompileIncrCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr, *incrTokenPtr;
     int isScalar, localIndex, haveImmValue, immValue;
-    DefineLineInformation;     /* TIP #280 */
 
     if ((parsePtr->numWords != 2) && (parsePtr->numWords != 3)) {
        return TCL_ERROR;
@@ -670,9 +670,9 @@ TclCompileInfoExistsCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr;
     int isScalar, localIndex;
-    DefineLineInformation;     /* TIP #280 */
 
     if (parsePtr->numWords != 2) {
        return TCL_ERROR;
@@ -848,9 +848,9 @@ TclCompileLappendCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr, *valueTokenPtr;
     int isScalar, localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
 
     /* TODO: Consider support for compiling expanded args. */
     numWords = parsePtr->numWords;
@@ -881,7 +881,7 @@ TclCompileLappendCmd(
      */
 
     if (numWords > 2) {
-       Tcl_Token *valueTokenPtr = TokenAfter(varTokenPtr);
+       valueTokenPtr = TokenAfter(varTokenPtr);
 
        CompileWord(envPtr, valueTokenPtr, interp, 2);
     }
@@ -964,9 +964,9 @@ TclCompileLassignCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr;
     int isScalar, localIndex, numWords, idx;
-    DefineLineInformation;     /* TIP #280 */
 
     numWords = parsePtr->numWords;
 
@@ -1068,12 +1068,12 @@ TclCompileLindexCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *idxTokenPtr, *valTokenPtr;
     int i, idx, numWords = parsePtr->numWords;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
-     * Quit if too few args.
+     * Quit if not enough args.
      */
 
     /* TODO: Consider support for compiling expanded args. */
@@ -1273,8 +1273,8 @@ TclCompileLlengthCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *varTokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *varTokenPtr;
 
     if (parsePtr->numWords != 2) {
        return TCL_ERROR;
@@ -1306,8 +1306,8 @@ TclCompileLrangeCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
-    Tcl_Token *tokenPtr, *listTokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr, *listTokenPtr;
     int idx1, idx2;
 
     if (parsePtr->numWords != 4) {
@@ -1367,8 +1367,8 @@ TclCompileLinsertCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
-    Tcl_Token *tokenPtr, *listTokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr, *listTokenPtr;
     int idx, i;
 
     if (parsePtr->numWords < 3) {
@@ -1470,8 +1470,8 @@ TclCompileLreplaceCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
-    Tcl_Token *tokenPtr, *listTokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr, *listTokenPtr;
     int idx1, idx2, i;
     int emptyPrefix=1, suffixStart = 0;
 
@@ -1634,6 +1634,7 @@ TclCompileLsetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     int tempDepth;             /* Depth used for emitting one part of the
                                 * code burst. */
     Tcl_Token *varTokenPtr;    /* Pointer to the Tcl_Token representing the
@@ -1641,7 +1642,6 @@ TclCompileLsetCmd(
     int localIndex;            /* Index of var in local var table. */
     int isScalar;              /* Flag == 1 if scalar, 0 if array. */
     int i;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * Check argument count.
@@ -1806,8 +1806,8 @@ TclCompileNamespaceCodeCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
 
     if (parsePtr->numWords != 2) {
        return TCL_ERROR;
@@ -1856,8 +1856,8 @@ TclCompileNamespaceOriginCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
 
     if (parsePtr->numWords != 2) {
        return TCL_ERROR;
@@ -1878,8 +1878,8 @@ TclCompileNamespaceQualifiersCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
     int off;
 
     if (parsePtr->numWords != 2) {
@@ -1914,8 +1914,8 @@ TclCompileNamespaceTailCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
-    Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
     JumpFixup jumpFixup;
 
     if (parsePtr->numWords != 2) {
@@ -1951,9 +1951,9 @@ TclCompileNamespaceUpvarCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr, *otherTokenPtr, *localTokenPtr;
     int localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
 
     if (envPtr->procPtr == NULL) {
        return TCL_ERROR;
@@ -2076,11 +2076,11 @@ TclCompileRegexpCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr;    /* Pointer to the Tcl_Token representing the
                                 * parse of the RE or string. */
     int i, len, nocase, exact, sawLast, simple;
     const char *str;
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * We are only interested in compiling simple regexp cases. Currently
@@ -2119,7 +2119,7 @@ TclCompileRegexpCmd(
            sawLast++;
            i++;
            break;
-       } else if ((len > 1) && (strncmp(str,"-nocase",(unsigned)len) == 0)) {
+       } else if ((len > 1) && (strncmp(str, "-nocase", len) == 0)) {
            nocase = 1;
        } else {
            /*
@@ -2416,6 +2416,7 @@ TclCompileReturnCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     /*
      * General syntax: [return ?-option value ...? ?result?]
      * An even number of words means an explicit result argument is present.
@@ -2426,7 +2427,6 @@ TclCompileReturnCmd(
     int numOptionWords = numWords - 1 - explicitResult;
     Tcl_Obj *returnOpts, **objv;
     Tcl_Token *wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
-    DefineLineInformation;     /* TIP #280 */
 
     /*
      * Check for special case which can always be compiled:
@@ -2668,9 +2668,9 @@ TclCompileUpvarCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr, *otherTokenPtr, *localTokenPtr;
     int localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
     Tcl_Obj *objPtr;
 
     if (envPtr->procPtr == NULL) {
@@ -2775,9 +2775,9 @@ TclCompileVariableCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr, *valueTokenPtr;
     int localIndex, numWords, i;
-    DefineLineInformation;     /* TIP #280 */
 
     numWords = parsePtr->numWords;
     if (numWords < 2) {
index 1d59cc6..ddfe0dc 100644 (file)
@@ -135,9 +135,9 @@ TclCompileSetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr, *valueTokenPtr;
     int isAssignment, isScalar, localIndex, numWords;
-    DefineLineInformation;     /* TIP #280 */
 
     numWords = parsePtr->numWords;
     if ((numWords != 2) && (numWords != 3)) {
@@ -229,10 +229,10 @@ TclCompileStringCatCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     int i, numWords = parsePtr->numWords, numArgs;
     Tcl_Token *wordTokenPtr;
     Tcl_Obj *obj, *folded;
-    DefineLineInformation;     /* TIP #280 */
 
     /* Trivial case, no arg */
 
@@ -637,6 +637,7 @@ TclCompileStringIsCmd(
            OP(         LNOT);
            return TCL_OK;
        }
+    break;
 
     case STR_IS_DOUBLE: {
        int satisfied, isEmpty;
@@ -755,7 +756,7 @@ TclCompileStringMatchCmd(
        }
        str = tokenPtr[1].start;
        length = tokenPtr[1].size;
-       if ((length <= 1) || strncmp(str, "-nocase", (size_t) length)) {
+       if ((length <= 1) || strncmp(str, "-nocase", length)) {
            /*
             * Fail at run time, not in compilation.
             */
@@ -995,8 +996,8 @@ TclCompileStringReplaceCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds the resulting instructions. */
 {
-    Tcl_Token *tokenPtr, *valueTokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr, *valueTokenPtr;
     int first, last;
 
     if (parsePtr->numWords < 4 || parsePtr->numWords > 5) {
@@ -1402,13 +1403,13 @@ TclCompileSubstCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     int numArgs = parsePtr->numWords - 1;
     int numOpts = numArgs - 1;
     int objc, flags = TCL_SUBST_ALL;
     Tcl_Obj **objv/*, *toSubst = NULL*/;
     Tcl_Token *wordTokenPtr = TokenAfter(parsePtr->tokenPtr);
     int code = TCL_ERROR;
-    DefineLineInformation;     /* TIP #280 */
 
     if (numArgs == 0) {
        return TCL_ERROR;
@@ -1735,6 +1736,7 @@ TclCompileSwitchCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *tokenPtr;       /* Pointer to tokens in command. */
     int numWords;              /* Number of words in command. */
 
@@ -1751,7 +1753,6 @@ TclCompileSwitchCmd(
     int foundMode = 0;         /* Have we seen a mode flag yet? */
     int i, valueIndex;
     int result = TCL_ERROR;
-    DefineLineInformation;     /* TIP #280 */
     int *clNext = envPtr->clNext;
 
     /*
@@ -1799,8 +1800,8 @@ TclCompileSwitchCmd(
      */
 
     for (; numWords>=3 ; tokenPtr=TokenAfter(tokenPtr),numWords--) {
-       register unsigned size = tokenPtr[1].size;
-       register const char *chrs = tokenPtr[1].start;
+       unsigned size = tokenPtr[1].size;
+       const char *chrs = tokenPtr[1].start;
 
        /*
         * We only process literal options, and we assume that -e, -g and -n
@@ -2539,7 +2540,7 @@ PrintJumptableInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register JumptableInfo *jtPtr = clientData;
+    JumptableInfo *jtPtr = clientData;
     Tcl_HashEntry *hPtr;
     Tcl_HashSearch search;
     const char *keyPtr;
@@ -2568,7 +2569,7 @@ DisassembleJumptableInfo(
     ByteCode *codePtr,
     unsigned int pcOffset)
 {
-    register JumptableInfo *jtPtr = clientData;
+    JumptableInfo *jtPtr = clientData;
     Tcl_Obj *mapping = Tcl_NewObj();
     Tcl_HashEntry *hPtr;
     Tcl_HashSearch search;
@@ -3573,9 +3574,9 @@ TclCompileUnsetCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *varTokenPtr;
     int isScalar, localIndex, flags = 1, i, varCount = 0, haveFlags = 0;
-    DefineLineInformation;     /* TIP #280 */
 
     /* TODO: Consider support for compiling expanded args. */
 
@@ -3711,13 +3712,13 @@ TclCompileWhileCmd(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;     /* TIP #280 */
     Tcl_Token *testTokenPtr, *bodyTokenPtr;
     JumpFixup jumpEvalCondFixup;
     int testCodeOffset, bodyCodeOffset, jumpDist, range, code, boolVal;
     int loopMayEnd = 1;                /* This is set to 0 if it is recognized as an
                                 * infinite loop. */
     Tcl_Obj *boolObj;
-    DefineLineInformation;     /* TIP #280 */
 
     if (parsePtr->numWords != 3) {
        return TCL_ERROR;
@@ -3975,8 +3976,8 @@ CompileUnaryOpCmd(
     int instruction,
     CompileEnv *envPtr)
 {
-    Tcl_Token *tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
 
     if (parsePtr->numWords != 2) {
        return TCL_ERROR;
@@ -4017,8 +4018,8 @@ CompileAssociativeBinaryOpCmd(
     int instruction,
     CompileEnv *envPtr)
 {
-    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     int words;
 
     /* TODO: Consider support for compiling expanded args. */
@@ -4102,8 +4103,8 @@ CompileComparisonOpCmd(
     int instruction,
     CompileEnv *envPtr)
 {
-    Tcl_Token *tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr;
 
     /* TODO: Consider support for compiling expanded args. */
     if (parsePtr->numWords < 3) {
@@ -4264,15 +4265,15 @@ TclCompilePowOpCmd(
                                 * compiled. */
     CompileEnv *envPtr)
 {
+    DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
+    int words;
+
     /*
      * This one has its own implementation because the ** operator is the only
      * one with right associativity.
      */
 
-    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
-    DefineLineInformation;     /* TIP #280 */
-    int words;
-
     for (words=1 ; words<parsePtr->numWords ; words++) {
        tokenPtr = TokenAfter(tokenPtr);
        CompileWord(envPtr, tokenPtr, interp, words);
@@ -4439,8 +4440,8 @@ TclCompileMinusOpCmd(
                                 * compiled. */
     CompileEnv *envPtr)
 {
-    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     int words;
 
     /* TODO: Consider support for compiling expanded args. */
@@ -4485,8 +4486,8 @@ TclCompileDivOpCmd(
                                 * compiled. */
     CompileEnv *envPtr)
 {
-    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     DefineLineInformation;     /* TIP #280 */
+    Tcl_Token *tokenPtr = parsePtr->tokenPtr;
     int words;
 
     /* TODO: Consider support for compiling expanded args. */
index 9c7ab8d..1ffe099 100644 (file)
@@ -2068,7 +2068,7 @@ ParseLexeme(
        } else {
            char utfBytes[TCL_UTF_MAX];
 
-           memcpy(utfBytes, start, (size_t) numBytes);
+           memcpy(utfBytes, start, numBytes);
            utfBytes[numBytes] = '\0';
            scanned = TclUtfToUniChar(utfBytes, &ch);
        }
@@ -2424,8 +2424,8 @@ CompileExprTree(
            if (optimize) {
                int length;
                const char *bytes = TclGetStringFromObj(literal, &length);
-               int index = TclRegisterNewLiteral(envPtr, bytes, length);
-               Tcl_Obj *objPtr = TclFetchLiteral(envPtr, index);
+               int idx = TclRegisterNewLiteral(envPtr, bytes, length);
+               Tcl_Obj *objPtr = TclFetchLiteral(envPtr, idx);
 
                if ((objPtr->typePtr == NULL) && (literal->typePtr != NULL)) {
                    /*
@@ -2445,7 +2445,7 @@ CompileExprTree(
                    objPtr->internalRep = literal->internalRep;
                    literal->typePtr = NULL;
                }
-               TclEmitPush(index, envPtr);
+               TclEmitPush(idx, envPtr);
            } else {
                /*
                 * When optimize==0, we know the expression is a one-off and
@@ -2471,7 +2471,7 @@ CompileExprTree(
 
                if (ExecConstantExprTree(interp, nodes, next, litObjvPtr)
                        == TCL_OK) {
-                   int index;
+                   int idx;
                    Tcl_Obj *objPtr = Tcl_GetObjResult(interp);
 
                    /*
@@ -2482,9 +2482,9 @@ CompileExprTree(
                    if (objPtr->bytes) {
                        Tcl_Obj *tableValue;
 
-                       index = TclRegisterNewLiteral(envPtr, objPtr->bytes,
+                       idx = TclRegisterNewLiteral(envPtr, objPtr->bytes,
                                objPtr->length);
-                       tableValue = TclFetchLiteral(envPtr, index);
+                       tableValue = TclFetchLiteral(envPtr, idx);
                        if ((tableValue->typePtr == NULL) &&
                                (objPtr->typePtr != NULL)) {
                            /*
@@ -2496,9 +2496,9 @@ CompileExprTree(
                            objPtr->typePtr = NULL;
                        }
                    } else {
-                       index = TclAddLiteralObj(envPtr, objPtr, NULL);
+                       idx = TclAddLiteralObj(envPtr, objPtr, NULL);
                    }
-                   TclEmitPush(index, envPtr);
+                   TclEmitPush(idx, envPtr);
                } else {
                    TclCompileSyntaxError(interp, envPtr);
                }
@@ -2689,7 +2689,7 @@ TclVariadicOpCmd(
        Tcl_Obj *const *litObjPtrPtr = litObjv;
 
        if (lexeme == EXPON) {
-           litObjv[1] = Tcl_NewIntObj(occdPtr->i.identity);
+           TclNewIntObj(litObjv[1], occdPtr->i.identity);
            Tcl_IncrRefCount(litObjv[1]);
            decrMe = 1;
            litObjv[0] = objv[1];
@@ -2705,7 +2705,7 @@ TclVariadicOpCmd(
            if (lexeme == DIVIDE) {
                litObjv[0] = Tcl_NewDoubleObj(1.0);
            } else {
-               litObjv[0] = Tcl_NewIntObj(occdPtr->i.identity);
+               TclNewIntObj(litObjv[0], occdPtr->i.identity);
            }
            Tcl_IncrRefCount(litObjv[0]);
            litObjv[1] = objv[1];
index 41c81af..6761c09 100644 (file)
@@ -827,7 +827,7 @@ TclSetByteCodeFromAny(
      * faster code in some cases, and more compact code in more.
      */
 
-    if (Tcl_GetMaster(interp) == NULL &&
+    if (Tcl_GetParent(interp) == NULL &&
            !Tcl_LimitTypeEnabled(interp, TCL_LIMIT_COMMANDS|TCL_LIMIT_TIME)
            && IsCompactibleCompileEnv(interp, &compEnv)) {
        TclFreeCompileEnv(&compEnv);
@@ -968,9 +968,9 @@ DupByteCodeInternalRep(
 
 static void
 FreeByteCodeInternalRep(
-    register Tcl_Obj *objPtr)  /* Object whose internal rep to free. */
+    Tcl_Obj *objPtr)   /* Object whose internal rep to free. */
 {
-    register ByteCode *codePtr = objPtr->internalRep.twoPtrValue.ptr1;
+    ByteCode *codePtr = objPtr->internalRep.twoPtrValue.ptr1;
 
     objPtr->typePtr = NULL;
     if (codePtr->refCount-- <= 1) {
@@ -999,14 +999,14 @@ FreeByteCodeInternalRep(
 
 void
 TclCleanupByteCode(
-    register ByteCode *codePtr)        /* Points to the ByteCode to free. */
+    ByteCode *codePtr) /* Points to the ByteCode to free. */
 {
     Tcl_Interp *interp = (Tcl_Interp *) *codePtr->interpHandle;
     Interp *iPtr = (Interp *) interp;
     int numLitObjects = codePtr->numLitObjects;
     int numAuxDataItems = codePtr->numAuxDataItems;
-    register Tcl_Obj **objArrayPtr, *objPtr;
-    register const AuxData *auxDataPtr;
+    Tcl_Obj **objArrayPtr, *objPtr;
+    const AuxData *auxDataPtr;
     int i;
 #ifdef TCL_COMPILE_STATS
 
@@ -1354,9 +1354,9 @@ CompileSubstObj(
 
 static void
 FreeSubstCodeInternalRep(
-    register Tcl_Obj *objPtr)  /* Object whose internal rep to free. */
+    Tcl_Obj *objPtr)   /* Object whose internal rep to free. */
 {
-    register ByteCode *codePtr = objPtr->internalRep.twoPtrValue.ptr1;
+    ByteCode *codePtr = objPtr->internalRep.twoPtrValue.ptr1;
 
     objPtr->typePtr = NULL;
     if (codePtr->refCount-- <= 1) {
@@ -1405,7 +1405,7 @@ void
 TclInitCompileEnv(
     Tcl_Interp *interp,                /* The interpreter for which a CompileEnv
                                 * structure is initialized. */
-    register CompileEnv *envPtr,/* Points to the CompileEnv structure to
+    CompileEnv *envPtr,/* Points to the CompileEnv structure to
                                 * initialize. */
     const char *stringPtr,     /* The source string to be compiled. */
     int numBytes,              /* Number of bytes in source string. */
@@ -1612,7 +1612,7 @@ TclInitCompileEnv(
 
 void
 TclFreeCompileEnv(
-    register CompileEnv *envPtr)/* Points to the CompileEnv structure. */
+    CompileEnv *envPtr)/* Points to the CompileEnv structure. */
 {
     if (envPtr->localLitTable.buckets != envPtr->localLitTable.staticBuckets){
        ckfree(envPtr->localLitTable.buckets);
@@ -1812,8 +1812,8 @@ TclCompileInvocation(
     int numWords,
     CompileEnv *envPtr)
 {
-    int wordIdx = 0, depth = TclGetStackDepth(envPtr);
     DefineLineInformation;
+    int wordIdx = 0, depth = TclGetStackDepth(envPtr);
 
     if (cmdObj) {
        CompileCmdLiteral(interp, cmdObj, envPtr);
@@ -1856,8 +1856,8 @@ CompileExpanded(
     int numWords,
     CompileEnv *envPtr)
 {
-    int wordIdx = 0;
     DefineLineInformation;
+    int wordIdx = 0;
     int depth = TclGetStackDepth(envPtr);
 
     StartExpanding(envPtr);
@@ -1915,8 +1915,8 @@ CompileCmdCompileProc(
     Command *cmdPtr,
     CompileEnv *envPtr)
 {
-    int unwind = 0, incrOffset = -1;
     DefineLineInformation;
+    int unwind = 0, incrOffset = -1;
     int depth = TclGetStackDepth(envPtr);
 
     /*
@@ -2749,13 +2749,13 @@ TclInitByteCodeObj(
     Tcl_Obj *objPtr,           /* Points object that should be initialized,
                                 * and whose string rep contains the source
                                 * code. */
-    register CompileEnv *envPtr)/* Points to the CompileEnv structure from
+    CompileEnv *envPtr)/* Points to the CompileEnv structure from
                                 * which to create a ByteCode structure. */
 {
-    register ByteCode *codePtr;
+    ByteCode *codePtr;
     size_t codeBytes, objArrayBytes, exceptArrayBytes, cmdLocBytes;
     size_t auxDataArrayBytes, structureSize;
-    register unsigned char *p;
+    unsigned char *p;
 #ifdef TCL_COMPILE_DEBUG
     unsigned char *nextPtr;
 #endif
@@ -2820,7 +2820,7 @@ TclInitByteCodeObj(
 
     p += sizeof(ByteCode);
     codePtr->codeStart = p;
-    memcpy(p, envPtr->codeStart, (size_t) codeBytes);
+    memcpy(p, envPtr->codeStart, codeBytes);
 
     p += TCL_ALIGN(codeBytes);         /* align object array */
     codePtr->objArrayPtr = (Tcl_Obj **) p;
@@ -2853,7 +2853,7 @@ TclInitByteCodeObj(
     p += TCL_ALIGN(objArrayBytes);     /* align exception range array */
     if (exceptArrayBytes > 0) {
        codePtr->exceptArrayPtr = (ExceptionRange *) p;
-       memcpy(p, envPtr->exceptArrayPtr, (size_t) exceptArrayBytes);
+       memcpy(p, envPtr->exceptArrayPtr, exceptArrayBytes);
     } else {
        codePtr->exceptArrayPtr = NULL;
     }
@@ -2861,7 +2861,7 @@ TclInitByteCodeObj(
     p += TCL_ALIGN(exceptArrayBytes);  /* align AuxData array */
     if (auxDataArrayBytes > 0) {
        codePtr->auxDataArrayPtr = (AuxData *) p;
-       memcpy(p, envPtr->auxDataArrayPtr, (size_t) auxDataArrayBytes);
+       memcpy(p, envPtr->auxDataArrayPtr, auxDataArrayBytes);
     } else {
        codePtr->auxDataArrayPtr = NULL;
     }
@@ -2940,7 +2940,7 @@ TclInitByteCodeObj(
 
 int
 TclFindCompiledLocal(
-    register const char *name, /* Points to first character of the name of a
+    const char *name,  /* Points to first character of the name of a
                                 * scalar or array variable. If NULL, a
                                 * temporary var should be created. */
     int nameBytes,             /* Number of bytes in the name. */
@@ -2948,9 +2948,9 @@ TclFindCompiledLocal(
                                 * variable if it is new. */
     CompileEnv *envPtr)                /* Points to the current compile environment*/
 {
-    register CompiledLocal *localPtr;
+    CompiledLocal *localPtr;
     int localVar = -1;
-    register int i;
+    int i;
     Proc *procPtr;
 
     /*
@@ -2996,7 +2996,7 @@ TclFindCompiledLocal(
                char *localName = localPtr->name;
 
                if ((nameBytes == localPtr->nameLength) &&
-                       (strncmp(name,localName,(unsigned)nameBytes) == 0)) {
+                       (strncmp(name, localName, nameBytes) == 0)) {
                    return i;
                }
            }
@@ -3028,7 +3028,7 @@ TclFindCompiledLocal(
        localPtr->resolveInfo = NULL;
 
        if (name != NULL) {
-           memcpy(localPtr->name, name, (size_t) nameBytes);
+           memcpy(localPtr->name, name, nameBytes);
        }
        localPtr->name[nameBytes] = '\0';
        procPtr->numCompiledLocals++;
@@ -3322,11 +3322,11 @@ EnterCmdWordData(
 int
 TclCreateExceptRange(
     ExceptionRangeType type,   /* The kind of ExceptionRange desired. */
-    register CompileEnv *envPtr)/* Points to CompileEnv for which to create a
+    CompileEnv *envPtr)/* Points to CompileEnv for which to create a
                                 * new ExceptionRange structure. */
 {
-    register ExceptionRange *rangePtr;
-    register ExceptionAux *auxPtr;
+    ExceptionRange *rangePtr;
+    ExceptionAux *auxPtr;
     int index = envPtr->exceptArrayNext;
 
     if (index >= envPtr->exceptArrayEnd) {
@@ -3690,11 +3690,11 @@ TclCreateAuxData(
                                 * the new aux data record. */
     const AuxDataType *typePtr,        /* Pointer to the type to attach to this
                                 * AuxData */
-    register CompileEnv *envPtr)/* Points to the CompileEnv for which a new
+    CompileEnv *envPtr)/* Points to the CompileEnv for which a new
                                 * aux data structure is to be allocated. */
 {
     int index;                 /* Index for the new AuxData structure. */
-    register AuxData *auxDataPtr;
+    AuxData *auxDataPtr;
                                /* Points to the new AuxData structure */
 
     index = envPtr->auxDataArrayNext;
@@ -3753,7 +3753,7 @@ TclCreateAuxData(
 
 void
 TclInitJumpFixupArray(
-    register JumpFixupArray *fixupArrayPtr)
+    JumpFixupArray *fixupArrayPtr)
                                /* Points to the JumpFixupArray structure to
                                 * initialize. */
 {
@@ -3785,7 +3785,7 @@ TclInitJumpFixupArray(
 
 void
 TclExpandJumpFixupArray(
-    register JumpFixupArray *fixupArrayPtr)
+    JumpFixupArray *fixupArrayPtr)
                                /* Points to the JumpFixupArray structure to
                                 * enlarge. */
 {
@@ -3834,7 +3834,7 @@ TclExpandJumpFixupArray(
 
 void
 TclFreeJumpFixupArray(
-    register JumpFixupArray *fixupArrayPtr)
+    JumpFixupArray *fixupArrayPtr)
                                /* Points to the JumpFixupArray structure to
                                 * free. */
 {
@@ -4281,7 +4281,7 @@ GetCmdLocEncodingSize(
                                 * containing the CmdLocation structure to
                                 * encode. */
 {
-    register CmdLocation *mapPtr = envPtr->cmdMapPtr;
+    CmdLocation *mapPtr = envPtr->cmdMapPtr;
     int numCmds = envPtr->numCommands;
     int codeDelta, codeLen, srcDelta, srcLen;
     int codeDeltaNext, codeLengthNext, srcDeltaNext, srcLengthNext;
@@ -4365,11 +4365,11 @@ EncodeCmdLocMap(
                                 * memory block where the location information
                                 * is to be stored. */
 {
-    register CmdLocation *mapPtr = envPtr->cmdMapPtr;
+    CmdLocation *mapPtr = envPtr->cmdMapPtr;
     int numCmds = envPtr->numCommands;
-    register unsigned char *p = startPtr;
+    unsigned char *p = startPtr;
     int codeDelta, codeLen, srcDelta, srcLen, prevOffset;
-    register int i;
+    int i;
 
     /*
      * Encode the code offset for each command as a sequence of deltas.
@@ -4483,7 +4483,7 @@ RecordByteCodeStats(
                                 * to add to accumulated statistics. */
 {
     Interp *iPtr = (Interp *) *codePtr->interpHandle;
-    register ByteCodeStats *statsPtr;
+    ByteCodeStats *statsPtr;
 
     if (iPtr == NULL) {
        /* Avoid segfaulting in case we're called in a deleted interp */
index 1d657a7..03b4a90 100644 (file)
@@ -966,7 +966,7 @@ typedef struct JumpFixupArray {
 
 typedef struct ForeachVarList {
     int numVars;               /* The number of variables in the list. */
-    int varIndexes[1];         /* An array of the indexes ("slot numbers")
+    int varIndexes[TCLFLEXARRAY];/* An array of the indexes ("slot numbers")
                                 * for each variable in the procedure's array
                                 * of local variables. Only scalar variables
                                 * are supported. The actual size of this
@@ -990,7 +990,7 @@ typedef struct ForeachInfo {
                                 * the loop's iteration count. Used to
                                 * determine next value list element to assign
                                 * each loop var. */
-    ForeachVarList *varLists[1];/* An array of pointers to ForeachVarList
+    ForeachVarList *varLists[TCLFLEXARRAY];/* An array of pointers to ForeachVarList
                                 * structures describing each var list. The
                                 * actual size of this field will be large
                                 * enough to numVars indexes. THIS MUST BE THE
@@ -1021,7 +1021,7 @@ MODULE_SCOPE const AuxDataType tclJumptableInfoType;
 
 typedef struct {
     int length;                        /* Size of array */
-    int varIndices[1];         /* Array of variable indices to manage when
+    int varIndices[TCLFLEXARRAY];              /* Array of variable indices to manage when
                                 * processing the start and end of a [dict
                                 * update]. There is really more than one
                                 * entry, and the structure is allocated to
index 717a1b3..aa199c3 100644 (file)
@@ -1,14 +1,13 @@
-/* A Bison parser, made by GNU Bison 2.3.  */
+/* A Bison parser, made by GNU Bison 3.1.  */
 
-/* Skeleton implementation for Bison's Yacc-like parsers in C
+/* Bison implementation for Yacc-like parsers in C
 
-   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
-   Free Software Foundation, Inc.
+   Copyright (C) 1984, 1989-1990, 2000-2015, 2018 Free Software Foundation, Inc.
 
-   This program is free software; you can redistribute it and/or modify
+   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.
+   the Free Software Foundation, either version 3 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
@@ -16,9 +15,7 @@
    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.  */
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
 
 /* As a special exception, you may create a larger work that contains
    part or all of the Bison parser skeleton and distribute that work
@@ -47,7 +44,7 @@
 #define YYBISON 1
 
 /* Bison version.  */
-#define YYBISON_VERSION "2.3"
+#define YYBISON_VERSION "3.1"
 
 /* Skeleton name.  */
 #define YYSKELETON_NAME "yacc.c"
 /* Pure parsers.  */
 #define YYPURE 1
 
-/* Using locations.  */
-#define YYLSP_NEEDED 1
+/* Push parsers.  */
+#define YYPUSH 0
 
-/* Substitute the variable and function names.  */
-#define yyparse TclDateparse
-#define yylex   TclDatelex
-#define yyerror TclDateerror
-#define yylval  TclDatelval
-#define yychar  TclDatechar
-#define yydebug TclDatedebug
-#define yynerrs TclDatenerrs
-#define yylloc TclDatelloc
-
-/* Tokens.  */
-#ifndef YYTOKENTYPE
-# define YYTOKENTYPE
-   /* Put the tokens into the symbol table, so that GDB and other debuggers
-      know about them.  */
-   enum yytokentype {
-     tAGO = 258,
-     tDAY = 259,
-     tDAYZONE = 260,
-     tID = 261,
-     tMERIDIAN = 262,
-     tMONTH = 263,
-     tMONTH_UNIT = 264,
-     tSTARDATE = 265,
-     tSEC_UNIT = 266,
-     tSNUMBER = 267,
-     tUNUMBER = 268,
-     tZONE = 269,
-     tEPOCH = 270,
-     tDST = 271,
-     tISOBASE = 272,
-     tDAY_UNIT = 273,
-     tNEXT = 274
-   };
-#endif
-/* Tokens.  */
-#define tAGO 258
-#define tDAY 259
-#define tDAYZONE 260
-#define tID 261
-#define tMERIDIAN 262
-#define tMONTH 263
-#define tMONTH_UNIT 264
-#define tSTARDATE 265
-#define tSEC_UNIT 266
-#define tSNUMBER 267
-#define tUNUMBER 268
-#define tZONE 269
-#define tEPOCH 270
-#define tDST 271
-#define tISOBASE 272
-#define tDAY_UNIT 273
-#define tNEXT 274
+/* Pull parsers.  */
+#define YYPULL 1
 
 
+/* Substitute the variable and function names.  */
+#define yyparse         TclDateparse
+#define yylex           TclDatelex
+#define yyerror         TclDateerror
+#define yydebug         TclDatedebug
+#define yynerrs         TclDatenerrs
 
 
 /* Copy the first part of user declarations.  */
  *     This file is generated from a yacc grammar defined in the file
  *     tclGetDate.y. It should not be edited directly.
  *
- * Copyright (c) 1992-1995 Karl Lehenbauer and Mark Diekhans.
+ * Copyright (c) 1992-1995 Karl Lehenbauer & Mark Diekhans.
  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
  *
  * See the file "license.terms" for information on usage and redistribution of
  * this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ *
  */
 #include "tclInt.h"
 
 #endif /* _MSC_VER */
 
 /*
+ * Meridian: am, pm, or 24-hour style.
+ */
+
+typedef enum _MERIDIAN {
+    MERam, MERpm, MER24
+} MERIDIAN;
+
+/*
  * yyparse will accept a 'struct DateInfo' as its parameter; that's where the
  * parsed fields will be returned.
  */
@@ -159,7 +120,7 @@ typedef struct DateInfo {
     time_t dateHour;
     time_t dateMinutes;
     time_t dateSeconds;
-    int dateMeridian;
+    MERIDIAN dateMeridian;
     int dateHaveTime;
 
     time_t dateTimezone;
@@ -246,20 +207,16 @@ typedef enum _DSTMODE {
     DSTon, DSToff, DSTmaybe
 } DSTMODE;
 
-/*
- * Meridian: am, pm, or 24-hour style.
- */
 
-typedef enum _MERIDIAN {
-    MERam, MERpm, MER24
-} MERIDIAN;
 
 
-
-/* Enabling traces.  */
-#ifndef YYDEBUG
-# define YYDEBUG 0
-#endif
+# ifndef YY_NULLPTR
+#  if defined __cplusplus && 201103L <= __cplusplus
+#   define YY_NULLPTR nullptr
+#  else
+#   define YY_NULLPTR 0
+#  endif
+# endif
 
 /* Enabling verbose error messages.  */
 #ifdef YYERROR_VERBOSE
@@ -269,40 +226,78 @@ typedef enum _MERIDIAN {
 # define YYERROR_VERBOSE 0
 #endif
 
-/* Enabling the token table.  */
-#ifndef YYTOKEN_TABLE
-# define YYTOKEN_TABLE 0
+
+/* Debug traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+#if YYDEBUG
+extern int TclDatedebug;
 #endif
 
+/* Token type.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+  enum yytokentype
+  {
+    tAGO = 258,
+    tDAY = 259,
+    tDAYZONE = 260,
+    tID = 261,
+    tMERIDIAN = 262,
+    tMONTH = 263,
+    tMONTH_UNIT = 264,
+    tSTARDATE = 265,
+    tSEC_UNIT = 266,
+    tSNUMBER = 267,
+    tUNUMBER = 268,
+    tZONE = 269,
+    tEPOCH = 270,
+    tDST = 271,
+    tISOBASE = 272,
+    tDAY_UNIT = 273,
+    tNEXT = 274
+  };
+#endif
+
+/* Value type.  */
 #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
-typedef union YYSTYPE
 
+union YYSTYPE
 {
+
+
     time_t Number;
     enum _MERIDIAN Meridian;
-}
-/* Line 187 of yacc.c.  */
 
-       YYSTYPE;
-# define yystype YYSTYPE /* obsolescent; will be withdrawn */
-# define YYSTYPE_IS_DECLARED 1
+
+};
+
+typedef union YYSTYPE YYSTYPE;
 # define YYSTYPE_IS_TRIVIAL 1
+# define YYSTYPE_IS_DECLARED 1
 #endif
 
+/* Location type.  */
 #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
-typedef struct YYLTYPE
+typedef struct YYLTYPE YYLTYPE;
+struct YYLTYPE
 {
   int first_line;
   int first_column;
   int last_line;
   int last_column;
-} YYLTYPE;
-# define yyltype YYLTYPE /* obsolescent; will be withdrawn */
+};
 # define YYLTYPE_IS_DECLARED 1
 # define YYLTYPE_IS_TRIVIAL 1
 #endif
 
 
+
+int TclDateparse (DateInfo* info);
+
+
+
 /* Copy the second part of user declarations.  */
 
 
@@ -322,8 +317,6 @@ MODULE_SCOPE int    yyparse(DateInfo*);
 \f
 
 
-/* Line 216 of yacc.c.  */
-
 
 #ifdef short
 # undef short
@@ -337,72 +330,103 @@ typedef unsigned char yytype_uint8;
 
 #ifdef YYTYPE_INT8
 typedef YYTYPE_INT8 yytype_int8;
-#elif (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-typedef signed char yytype_int8;
 #else
-typedef short int yytype_int8;
+typedef signed char yytype_int8;
 #endif
 
 #ifdef YYTYPE_UINT16
 typedef YYTYPE_UINT16 yytype_uint16;
 #else
-typedef unsigned short int yytype_uint16;
+typedef unsigned short yytype_uint16;
 #endif
 
 #ifdef YYTYPE_INT16
 typedef YYTYPE_INT16 yytype_int16;
 #else
-typedef short int yytype_int16;
+typedef short yytype_int16;
 #endif
 
 #ifndef YYSIZE_T
 # ifdef __SIZE_TYPE__
 #  define YYSIZE_T __SIZE_TYPE__
-# else
+# elif defined size_t
 #  define YYSIZE_T size_t
+# elif ! defined YYSIZE_T
+#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYSIZE_T size_t
+# else
+#  define YYSIZE_T unsigned
 # endif
 #endif
 
 #define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
 
 #ifndef YY_
-# if YYENABLE_NLS
+# if defined YYENABLE_NLS && YYENABLE_NLS
 #  if ENABLE_NLS
 #   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
-#   define YY_(msgid) dgettext ("bison-runtime", msgid)
+#   define YY_(Msgid) dgettext ("bison-runtime", Msgid)
 #  endif
 # endif
 # ifndef YY_
-#  define YY_(msgid) msgid
+#  define YY_(Msgid) Msgid
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE
+# if (defined __GNUC__                                               \
+      && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__)))  \
+     || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
+#  define YY_ATTRIBUTE(Spec) __attribute__(Spec)
+# else
+#  define YY_ATTRIBUTE(Spec) /* empty */
+# endif
+#endif
+
+#ifndef YY_ATTRIBUTE_PURE
+# define YY_ATTRIBUTE_PURE   YY_ATTRIBUTE ((__pure__))
+#endif
+
+#ifndef YY_ATTRIBUTE_UNUSED
+# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
+#endif
+
+#if !defined _Noreturn \
+     && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
+# if defined _MSC_VER && 1200 <= _MSC_VER
+#  define _Noreturn __declspec (noreturn)
+# else
+#  define _Noreturn YY_ATTRIBUTE ((__noreturn__))
 # endif
 #endif
 
 /* Suppress unused-variable warnings by "using" E.  */
 #if ! defined lint || defined __GNUC__
-# define YYUSE(e) ((void) (e))
+# define YYUSE(E) ((void) (E))
 #else
-# define YYUSE(e) /* empty */
+# define YYUSE(E) /* empty */
 #endif
 
-/* Identity function, used to suppress warnings about constant conditions.  */
-#ifndef lint
-# define YYID(n) (n)
+#if defined __GNUC__ && ! defined __ICC && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
+/* Suppress an incorrect diagnostic about yylval being uninitialized.  */
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
+    _Pragma ("GCC diagnostic push") \
+    _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
+    _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
+    _Pragma ("GCC diagnostic pop")
 #else
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static int
-YYID (int i)
-#else
-static int
-YYID (i)
-    int i;
+# define YY_INITIAL_VALUE(Value) Value
 #endif
-{
-  return i;
-}
+#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+# define YY_IGNORE_MAYBE_UNINITIALIZED_END
+#endif
+#ifndef YY_INITIAL_VALUE
+# define YY_INITIAL_VALUE(Value) /* Nothing. */
 #endif
 
+
 #if ! defined yyoverflow || YYERROR_VERBOSE
 
 /* The parser invokes alloca or malloc; define the necessary symbols.  */
@@ -420,11 +444,11 @@ YYID (i)
 #    define alloca _alloca
 #   else
 #    define YYSTACK_ALLOC alloca
-#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
+#    if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
 #     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#     ifndef _STDLIB_H
-#      define _STDLIB_H 1
+      /* Use EXIT_SUCCESS as a witness for stdlib.h.  */
+#     ifndef EXIT_SUCCESS
+#      define EXIT_SUCCESS 0
 #     endif
 #    endif
 #   endif
@@ -432,8 +456,8 @@ YYID (i)
 # endif
 
 # ifdef YYSTACK_ALLOC
-   /* Pacify GCC's `empty if-body' warning.  */
-#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
+   /* Pacify GCC's 'empty if-body' warning.  */
+#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
 #  ifndef YYSTACK_ALLOC_MAXIMUM
     /* The OS might guarantee only one guard page at the bottom of the stack,
        and a page size can be as small as 4096 bytes.  So we cannot safely
@@ -447,25 +471,23 @@ YYID (i)
 #  ifndef YYSTACK_ALLOC_MAXIMUM
 #   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
 #  endif
-#  if (defined __cplusplus && ! defined _STDLIB_H \
+#  if (defined __cplusplus && ! defined EXIT_SUCCESS \
        && ! ((defined YYMALLOC || defined malloc) \
-            && (defined YYFREE || defined free)))
+             && (defined YYFREE || defined free)))
 #   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
-#   ifndef _STDLIB_H
-#    define _STDLIB_H 1
+#   ifndef EXIT_SUCCESS
+#    define EXIT_SUCCESS 0
 #   endif
 #  endif
 #  ifndef YYMALLOC
 #   define YYMALLOC malloc
-#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
+#   if ! defined malloc && ! defined EXIT_SUCCESS
 void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
 #   endif
 #  endif
 #  ifndef YYFREE
 #   define YYFREE free
-#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
+#   if ! defined free && ! defined EXIT_SUCCESS
 void free (void *); /* INFRINGES ON USER NAME SPACE */
 #   endif
 #  endif
@@ -475,15 +497,15 @@ void free (void *); /* INFRINGES ON USER NAME SPACE */
 
 #if (! defined yyoverflow \
      && (! defined __cplusplus \
-        || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \
-            && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+         || (defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL \
+             && defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
 
 /* A type that is properly aligned for any stack member.  */
 union yyalloc
 {
-  yytype_int16 yyss;
-  YYSTYPE yyvs;
-    YYLTYPE yyls;
+  yytype_int16 yyss_alloc;
+  YYSTYPE yyvs_alloc;
+  YYLTYPE yyls_alloc;
 };
 
 /* The size of the maximum gap between one aligned stack and the next.  */
@@ -495,46 +517,50 @@ union yyalloc
      ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE) + sizeof (YYLTYPE)) \
       + 2 * YYSTACK_GAP_MAXIMUM)
 
-/* Copy COUNT objects from FROM to TO.  The source and destination do
-   not overlap.  */
-# ifndef YYCOPY
-#  if defined __GNUC__ && 1 < __GNUC__
-#   define YYCOPY(To, From, Count) \
-      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
-#  else
-#   define YYCOPY(To, From, Count)             \
-      do                                       \
-       {                                       \
-         YYSIZE_T yyi;                         \
-         for (yyi = 0; yyi < (Count); yyi++)   \
-           (To)[yyi] = (From)[yyi];            \
-       }                                       \
-      while (YYID (0))
-#  endif
-# endif
+# define YYCOPY_NEEDED 1
 
 /* Relocate STACK from its old location to the new one.  The
    local variables YYSIZE and YYSTACKSIZE give the old and new number of
    elements in the stack, and YYPTR gives the new location of the
    stack.  Advance YYPTR to a properly aligned location for the next
    stack.  */
-# define YYSTACK_RELOCATE(Stack)                                       \
-    do                                                                 \
-      {                                                                        \
-       YYSIZE_T yynewbytes;                                            \
-       YYCOPY (&yyptr->Stack, Stack, yysize);                          \
-       Stack = &yyptr->Stack;                                          \
-       yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
-       yyptr += yynewbytes / sizeof (*yyptr);                          \
-      }                                                                        \
-    while (YYID (0))
+# define YYSTACK_RELOCATE(Stack_alloc, Stack)                           \
+    do                                                                  \
+      {                                                                 \
+        YYSIZE_T yynewbytes;                                            \
+        YYCOPY (&yyptr->Stack_alloc, Stack, yysize);                    \
+        Stack = &yyptr->Stack_alloc;                                    \
+        yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+        yyptr += yynewbytes / sizeof (*yyptr);                          \
+      }                                                                 \
+    while (0)
 
 #endif
 
+#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
+/* Copy COUNT objects from SRC to DST.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(Dst, Src, Count) \
+      __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
+#  else
+#   define YYCOPY(Dst, Src, Count)              \
+      do                                        \
+        {                                       \
+          YYSIZE_T yyi;                         \
+          for (yyi = 0; yyi < (Count); yyi++)   \
+            (Dst)[yyi] = (Src)[yyi];            \
+        }                                       \
+      while (0)
+#  endif
+# endif
+#endif /* !YYCOPY_NEEDED */
+
 /* YYFINAL -- State number of the termination state.  */
 #define YYFINAL  2
 /* YYLAST -- Last index in YYTABLE.  */
-#define YYLAST   79
+#define YYLAST   81
 
 /* YYNTOKENS -- Number of terminals.  */
 #define YYNTOKENS  26
@@ -542,24 +568,26 @@ union yyalloc
 #define YYNNTS  16
 /* YYNRULES -- Number of rules.  */
 #define YYNRULES  56
-/* YYNRULES -- Number of states.  */
-#define YYNSTATES  83
+/* YYNSTATES -- Number of states.  */
+#define YYNSTATES  85
 
-/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
+/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
+   by yylex, with out-of-bounds checking.  */
 #define YYUNDEFTOK  2
 #define YYMAXUTOK   274
 
-#define YYTRANSLATE(YYX)                                               \
-  ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+#define YYTRANSLATE(YYX)                                                \
+  ((unsigned) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
 
-/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
+/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
+   as returned by yylex, without out-of-bounds checking.  */
 static const yytype_uint8 yytranslate[] =
 {
        0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
-       2,     2,     2,    25,    22,    21,    24,    23,     2,     2,
+       2,     2,     2,    25,    21,    23,    24,    22,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,    20,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
        2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
@@ -586,54 +614,19 @@ static const yytype_uint8 yytranslate[] =
 };
 
 #if YYDEBUG
-/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
-   YYRHS.  */
-static const yytype_uint8 yyprhs[] =
-{
-       0,     0,     3,     4,     7,     9,    11,    13,    15,    17,
-      19,    21,    23,    25,    28,    33,    39,    46,    54,    57,
-      59,    61,    63,    66,    69,    73,    76,    80,    86,    88,
-      94,   100,   103,   108,   111,   113,   117,   120,   124,   128,
-     136,   139,   144,   147,   149,   153,   156,   159,   163,   165,
-     167,   169,   171,   173,   175,   177,   178
-};
-
-/* YYRHS -- A `-1'-separated list of the rules' RHS.  */
-static const yytype_int8 yyrhs[] =
-{
-      27,     0,    -1,    -1,    27,    28,    -1,    29,    -1,    30,
-      -1,    32,    -1,    33,    -1,    31,    -1,    36,    -1,    34,
-      -1,    35,    -1,    40,    -1,    13,     7,    -1,    13,    20,
-      13,    41,    -1,    13,    20,    13,    21,    13,    -1,    13,
-      20,    13,    20,    13,    41,    -1,    13,    20,    13,    20,
-      13,    21,    13,    -1,    14,    16,    -1,    14,    -1,     5,
-      -1,     4,    -1,     4,    22,    -1,    13,     4,    -1,    38,
-      13,     4,    -1,    19,     4,    -1,    13,    23,    13,    -1,
-      13,    23,    13,    23,    13,    -1,    17,    -1,    13,    21,
-       8,    21,    13,    -1,    13,    21,    13,    21,    13,    -1,
-       8,    13,    -1,     8,    13,    22,    13,    -1,    13,     8,
-      -1,    15,    -1,    13,     8,    13,    -1,    19,     8,    -1,
-      19,    13,     8,    -1,    17,    14,    17,    -1,    17,    14,
-      13,    20,    13,    20,    13,    -1,    17,    17,    -1,    10,
-      13,    24,    13,    -1,    37,     3,    -1,    37,    -1,    38,
-      13,    39,    -1,    13,    39,    -1,    19,    39,    -1,    19,
-      13,    39,    -1,    39,    -1,    21,    -1,    25,    -1,    11,
-      -1,    18,    -1,     9,    -1,    13,    -1,    -1,     7,    -1
-};
-
-/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
+  /* YYRLINE[YYN] -- Source line where rule number YYN was defined.  */
 static const yytype_uint16 yyrline[] =
 {
-       0,   225,   225,   226,   229,   232,   235,   238,   241,   244,
-     247,   251,   256,   259,   265,   271,   279,   285,   296,   300,
-     304,   310,   314,   318,   322,   326,   332,   336,   341,   346,
-     351,   356,   360,   365,   369,   374,   381,   385,   391,   400,
-     409,   419,   433,   438,   441,   444,   447,   450,   453,   458,
-     461,   466,   470,   474,   480,   498,   501
+       0,   223,   223,   224,   227,   230,   233,   236,   239,   242,
+     245,   249,   254,   257,   263,   269,   277,   282,   287,   291,
+     297,   301,   305,   309,   313,   319,   323,   328,   333,   338,
+     343,   347,   352,   356,   361,   368,   372,   378,   388,   397,
+     406,   416,   430,   435,   438,   441,   444,   447,   450,   455,
+     458,   463,   467,   471,   477,   495,   498
 };
 #endif
 
-#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+#if YYDEBUG || YYERROR_VERBOSE || 0
 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
    First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
 static const char *const yytname[] =
@@ -641,286 +634,296 @@ static const char *const yytname[] =
   "$end", "error", "$undefined", "tAGO", "tDAY", "tDAYZONE", "tID",
   "tMERIDIAN", "tMONTH", "tMONTH_UNIT", "tSTARDATE", "tSEC_UNIT",
   "tSNUMBER", "tUNUMBER", "tZONE", "tEPOCH", "tDST", "tISOBASE",
-  "tDAY_UNIT", "tNEXT", "':'", "'-'", "','", "'/'", "'.'", "'+'",
+  "tDAY_UNIT", "tNEXT", "':'", "','", "'/'", "'-'", "'.'", "'+'",
   "$accept", "spec", "item", "time", "zone", "day", "date", "ordMonth",
   "iso", "trek", "relspec", "relunits", "sign", "unit", "number",
-  "o_merid", 0
+  "o_merid", YY_NULLPTR
 };
 #endif
 
 # ifdef YYPRINT
-/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
-   token YYLEX-NUM.  */
+/* YYTOKNUM[NUM] -- (External) token number corresponding to the
+   (internal) symbol number NUM (which must be that of a token).  */
 static const yytype_uint16 yytoknum[] =
 {
        0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
      265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
-      58,    45,    44,    47,    46,    43
+      58,    44,    47,    45,    46,    43
 };
 # endif
 
-/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
-static const yytype_uint8 yyr1[] =
-{
-       0,    26,    27,    27,    28,    28,    28,    28,    28,    28,
-      28,    28,    28,    29,    29,    29,    29,    29,    30,    30,
-      30,    31,    31,    31,    31,    31,    32,    32,    32,    32,
-      32,    32,    32,    32,    32,    32,    33,    33,    34,    34,
-      34,    35,    36,    36,    37,    37,    37,    37,    37,    38,
-      38,    39,    39,    39,    40,    41,    41
-};
+#define YYPACT_NINF -18
 
-/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
-static const yytype_uint8 yyr2[] =
+#define yypact_value_is_default(Yystate) \
+  (!!((Yystate) == (-18)))
+
+#define YYTABLE_NINF -1
+
+#define yytable_value_is_error(Yytable_value) \
+  0
+
+  /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+     STATE-NUM.  */
+static const yytype_int8 yypact[] =
 {
-       0,     2,     0,     2,     1,     1,     1,     1,     1,     1,
-       1,     1,     1,     2,     4,     5,     6,     7,     2,     1,
-       1,     1,     2,     2,     3,     2,     3,     5,     1,     5,
-       5,     2,     4,     2,     1,     3,     2,     3,     3,     7,
-       2,     4,     2,     1,     3,     2,     2,     3,     1,     1,
-       1,     1,     1,     1,     1,     0,     1
+     -18,     2,   -18,   -17,   -18,    -4,   -18,    10,   -18,    22,
+       8,   -18,    18,   -18,    39,   -18,   -18,   -18,   -18,   -18,
+     -18,   -18,   -18,   -18,   -18,   -18,    25,    21,   -18,   -18,
+     -18,    16,    14,   -18,   -18,    28,    36,    41,    -5,   -18,
+     -18,     5,   -18,   -18,   -18,    47,   -18,   -18,    42,    46,
+      48,   -18,    -6,    40,    43,    44,    49,   -18,   -18,   -18,
+     -18,   -18,   -18,   -18,   -18,    50,   -18,    51,    55,    57,
+      58,    65,   -18,   -18,    59,    54,   -18,    62,    63,    60,
+     -18,    64,    61,    66,   -18
 };
 
-/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
-   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
-   means the default is an error.  */
+  /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
+     Performed when YYTABLE does not specify something else to do.  Zero
+     means the default is an error.  */
 static const yytype_uint8 yydefact[] =
 {
-       2,     0,     1,    21,    20,     0,    53,     0,    51,    54,
-      19,    34,    28,    52,     0,    49,    50,     3,     4,     5,
+       2,     0,     1,    20,    18,     0,    53,     0,    51,    54,
+      17,    33,    27,    52,     0,    49,    50,     3,     4,     5,
        8,     6,     7,    10,    11,     9,    43,     0,    48,    12,
-      22,    31,     0,    23,    13,    33,     0,     0,     0,    45,
-      18,     0,    40,    25,    36,     0,    46,    42,     0,     0,
-       0,    35,    55,     0,     0,    26,     0,    38,    37,    47,
-      24,    44,    32,    41,    56,     0,     0,    14,     0,     0,
-       0,     0,    55,    15,    29,    30,    27,     0,     0,    16,
-       0,    17,    39
+      21,    30,     0,    22,    13,    32,     0,     0,     0,    45,
+      16,     0,    40,    24,    35,     0,    46,    42,    19,     0,
+       0,    34,    55,    25,     0,     0,     0,    38,    36,    47,
+      23,    44,    31,    41,    56,     0,    14,     0,     0,     0,
+       0,    55,    26,    28,    29,     0,    15,     0,     0,     0,
+      39,     0,     0,     0,    37
 };
 
-/* YYDEFGOTO[NTERM-NUM].  */
-static const yytype_int8 yydefgoto[] =
-{
-      -1,     1,    17,    18,    19,    20,    21,    22,    23,    24,
-      25,    26,    27,    28,    29,    67
-};
-
-/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
-   STATE-NUM.  */
-#define YYPACT_NINF -22
-static const yytype_int8 yypact[] =
+  /* YYPGOTO[NTERM-NUM].  */
+static const yytype_int8 yypgoto[] =
 {
-     -22,     2,   -22,   -21,   -22,    -4,   -22,     1,   -22,    22,
-      18,   -22,     8,   -22,    40,   -22,   -22,   -22,   -22,   -22,
-     -22,   -22,   -22,   -22,   -22,   -22,    32,    28,   -22,   -22,
-     -22,    24,    26,   -22,   -22,    42,    47,    -5,    49,   -22,
-     -22,    15,   -22,   -22,   -22,    48,   -22,   -22,    43,    50,
-      51,   -22,    17,    44,    46,    45,    52,   -22,   -22,   -22,
-     -22,   -22,   -22,   -22,   -22,    56,    57,   -22,    58,    60,
-      61,    62,    -3,   -22,   -22,   -22,   -22,    59,    63,   -22,
-      64,   -22,   -22
+     -18,   -18,   -18,   -18,   -18,   -18,   -18,   -18,   -18,   -18,
+     -18,   -18,   -18,    -9,   -18,     7
 };
 
-/* YYPGOTO[NTERM-NUM].  */
-static const yytype_int8 yypgoto[] =
+  /* YYDEFGOTO[NTERM-NUM].  */
+static const yytype_int8 yydefgoto[] =
 {
-     -22,   -22,   -22,   -22,   -22,   -22,   -22,   -22,   -22,   -22,
-     -22,   -22,   -22,    -9,   -22,     6
+      -1,     1,    17,    18,    19,    20,    21,    22,    23,    24,
+      25,    26,    27,    28,    29,    66
 };
 
-/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
-   positive, shift that token.  If negative, reduce the rule which
-   number is the opposite.  If zero, do what YYDEFACT says.
-   If YYTABLE_NINF, syntax error.  */
-#define YYTABLE_NINF -1
+  /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM.  If
+     positive, shift that token.  If negative, reduce the rule whose
+     number is the opposite.  If YYTABLE_NINF, syntax error.  */
 static const yytype_uint8 yytable[] =
 {
-      39,    30,     2,    53,    64,    46,     3,     4,    54,    31,
-       5,     6,     7,     8,    32,     9,    10,    11,    78,    12,
-      13,    14,    41,    15,    64,    42,    33,    16,    56,    34,
-      35,     6,    57,     8,    40,    47,    59,    65,    66,    61,
-      13,    48,    36,    37,    43,    38,    49,    60,    44,     6,
-      50,     8,     6,    45,     8,    51,    58,     6,    13,     8,
-      52,    13,    55,    62,    63,    68,    13,    69,    70,    72,
-      73,    74,    71,    75,    76,    77,    81,    82,    79,    80
+      39,    64,     2,    54,    30,    46,     3,     4,    55,    31,
+       5,     6,     7,     8,    65,     9,    10,    11,    56,    12,
+      13,    14,    57,    32,    40,    15,    33,    16,    47,    34,
+      35,     6,    41,     8,    48,    42,    59,    49,    50,    61,
+      13,    51,    36,    43,    37,    38,    60,    44,     6,    52,
+       8,     6,    45,     8,    53,    58,     6,    13,     8,    62,
+      13,    63,    67,    71,    72,    13,    68,    69,    73,    70,
+      74,    75,    64,    77,    78,    79,    80,    82,    76,    84,
+      81,    83
 };
 
 static const yytype_uint8 yycheck[] =
 {
-       9,    22,     0,     8,     7,    14,     4,     5,    13,    13,
-       8,     9,    10,    11,    13,    13,    14,    15,    21,    17,
-      18,    19,    14,    21,     7,    17,     4,    25,    13,     7,
-       8,     9,    17,    11,    16,     3,    45,    20,    21,    48,
-      18,    13,    20,    21,     4,    23,    22,     4,     8,     9,
-      24,    11,     9,    13,    11,    13,     8,     9,    18,    11,
-      13,    18,    13,    13,    13,    21,    18,    21,    23,    13,
-      13,    13,    20,    13,    13,    13,    13,    13,    72,    20
+       9,     7,     0,     8,    21,    14,     4,     5,    13,    13,
+       8,     9,    10,    11,    20,    13,    14,    15,    13,    17,
+      18,    19,    17,    13,    16,    23,     4,    25,     3,     7,
+       8,     9,    14,    11,    13,    17,    45,    21,    24,    48,
+      18,    13,    20,     4,    22,    23,     4,     8,     9,    13,
+      11,     9,    13,    11,    13,     8,     9,    18,    11,    13,
+      18,    13,    22,    13,    13,    18,    23,    23,    13,    20,
+      13,    13,     7,    14,    20,    13,    13,    13,    71,    13,
+      20,    20
 };
 
-/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
-   symbol of state STATE-NUM.  */
+  /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+     symbol of state STATE-NUM.  */
 static const yytype_uint8 yystos[] =
 {
        0,    27,     0,     4,     5,     8,     9,    10,    11,    13,
-      14,    15,    17,    18,    19,    21,    25,    28,    29,    30,
+      14,    15,    17,    18,    19,    23,    25,    28,    29,    30,
       31,    32,    33,    34,    35,    36,    37,    38,    39,    40,
-      22,    13,    13,     4,     7,     8,    20,    21,    23,    39,
-      16,    14,    17,     4,     8,    13,    39,     3,    13,    22,
-      24,    13,    13,     8,    13,    13,    13,    17,     8,    39,
-       4,    39,    13,    13,     7,    20,    21,    41,    21,    21,
-      23,    20,    13,    13,    13,    13,    13,    13,    21,    41,
-      20,    13,    13
+      21,    13,    13,     4,     7,     8,    20,    22,    23,    39,
+      16,    14,    17,     4,     8,    13,    39,     3,    13,    21,
+      24,    13,    13,    13,     8,    13,    13,    17,     8,    39,
+       4,    39,    13,    13,     7,    20,    41,    22,    23,    23,
+      20,    13,    13,    13,    13,    13,    41,    14,    20,    13,
+      13,    20,    13,    20,    13
 };
 
-#define yyerrok                (yyerrstatus = 0)
-#define yyclearin      (yychar = YYEMPTY)
-#define YYEMPTY                (-2)
-#define YYEOF          0
+  /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
+static const yytype_uint8 yyr1[] =
+{
+       0,    26,    27,    27,    28,    28,    28,    28,    28,    28,
+      28,    28,    28,    29,    29,    29,    30,    30,    30,    30,
+      31,    31,    31,    31,    31,    32,    32,    32,    32,    32,
+      32,    32,    32,    32,    32,    33,    33,    34,    34,    34,
+      34,    35,    36,    36,    37,    37,    37,    37,    37,    38,
+      38,    39,    39,    39,    40,    41,    41
+};
+
+  /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.  */
+static const yytype_uint8 yyr2[] =
+{
+       0,     2,     0,     2,     1,     1,     1,     1,     1,     1,
+       1,     1,     1,     2,     4,     6,     2,     1,     1,     2,
+       1,     2,     2,     3,     2,     3,     5,     1,     5,     5,
+       2,     4,     2,     1,     3,     2,     3,    11,     3,     7,
+       2,     4,     2,     1,     3,     2,     2,     3,     1,     1,
+       1,     1,     1,     1,     1,     0,     1
+};
 
-#define YYACCEPT       goto yyacceptlab
-#define YYABORT                goto yyabortlab
-#define YYERROR                goto yyerrorlab
 
+#define yyerrok         (yyerrstatus = 0)
+#define yyclearin       (yychar = YYEMPTY)
+#define YYEMPTY         (-2)
+#define YYEOF           0
 
-/* Like YYERROR except do call yyerror.  This remains here temporarily
-   to ease the transition to the new meaning of YYERROR, for GCC.
-   Once GCC version 2 has supplanted version 1, this can go.  */
+#define YYACCEPT        goto yyacceptlab
+#define YYABORT         goto yyabortlab
+#define YYERROR         goto yyerrorlab
 
-#define YYFAIL         goto yyerrlab
 
 #define YYRECOVERING()  (!!yyerrstatus)
 
-#define YYBACKUP(Token, Value)                                 \
-do                                                             \
-  if (yychar == YYEMPTY && yylen == 1)                         \
-    {                                                          \
-      yychar = (Token);                                                \
-      yylval = (Value);                                                \
-      yytoken = YYTRANSLATE (yychar);                          \
-      YYPOPSTACK (1);                                          \
-      goto yybackup;                                           \
-    }                                                          \
-  else                                                         \
-    {                                                          \
+#define YYBACKUP(Token, Value)                                  \
+do                                                              \
+  if (yychar == YYEMPTY)                                        \
+    {                                                           \
+      yychar = (Token);                                         \
+      yylval = (Value);                                         \
+      YYPOPSTACK (yylen);                                       \
+      yystate = *yyssp;                                         \
+      goto yybackup;                                            \
+    }                                                           \
+  else                                                          \
+    {                                                           \
       yyerror (&yylloc, info, YY_("syntax error: cannot back up")); \
-      YYERROR;                                                 \
-    }                                                          \
-while (YYID (0))
+      YYERROR;                                                  \
+    }                                                           \
+while (0)
 
-
-#define YYTERROR       1
-#define YYERRCODE      256
+/* Error token number */
+#define YYTERROR        1
+#define YYERRCODE       256
 
 
 /* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
    If N is 0, then set CURRENT to the empty location which ends
    the previous symbol: RHS[0] (always defined).  */
 
-#define YYRHSLOC(Rhs, K) ((Rhs)[K])
 #ifndef YYLLOC_DEFAULT
-# define YYLLOC_DEFAULT(Current, Rhs, N)                               \
-    do                                                                 \
-      if (YYID (N))                                                    \
-       {                                                               \
-         (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;        \
-         (Current).first_column = YYRHSLOC (Rhs, 1).first_column;      \
-         (Current).last_line    = YYRHSLOC (Rhs, N).last_line;         \
-         (Current).last_column  = YYRHSLOC (Rhs, N).last_column;       \
-       }                                                               \
-      else                                                             \
-       {                                                               \
-         (Current).first_line   = (Current).last_line   =              \
-           YYRHSLOC (Rhs, 0).last_line;                                \
-         (Current).first_column = (Current).last_column =              \
-           YYRHSLOC (Rhs, 0).last_column;                              \
-       }                                                               \
-    while (YYID (0))
+# define YYLLOC_DEFAULT(Current, Rhs, N)                                \
+    do                                                                  \
+      if (N)                                                            \
+        {                                                               \
+          (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;        \
+          (Current).first_column = YYRHSLOC (Rhs, 1).first_column;      \
+          (Current).last_line    = YYRHSLOC (Rhs, N).last_line;         \
+          (Current).last_column  = YYRHSLOC (Rhs, N).last_column;       \
+        }                                                               \
+      else                                                              \
+        {                                                               \
+          (Current).first_line   = (Current).last_line   =              \
+            YYRHSLOC (Rhs, 0).last_line;                                \
+          (Current).first_column = (Current).last_column =              \
+            YYRHSLOC (Rhs, 0).last_column;                              \
+        }                                                               \
+    while (0)
 #endif
 
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+
+
+/* Enable debugging if requested.  */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args)                        \
+do {                                            \
+  if (yydebug)                                  \
+    YYFPRINTF Args;                             \
+} while (0)
+
 
 /* YY_LOCATION_PRINT -- Print the location on the stream.
    This macro was not mandated originally: define only if we know
    we won't break user code: when these are the locations we know.  */
 
 #ifndef YY_LOCATION_PRINT
-# if YYLTYPE_IS_TRIVIAL
-#  define YY_LOCATION_PRINT(File, Loc)                 \
-     fprintf (File, "%d.%d-%d.%d",                     \
-             (Loc).first_line, (Loc).first_column,     \
-             (Loc).last_line,  (Loc).last_column)
-# else
-#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
-# endif
-#endif
+# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
 
+/* Print *YYLOCP on YYO.  Private, do not rely on its existence. */
 
-/* YYLEX -- calling `yylex' with the right arguments.  */
-
-#ifdef YYLEX_PARAM
-# define YYLEX yylex (&yylval, &yylloc, YYLEX_PARAM)
-#else
-# define YYLEX yylex (&yylval, &yylloc, info)
-#endif
+YY_ATTRIBUTE_UNUSED
+static unsigned
+yy_location_print_ (FILE *yyo, YYLTYPE const * const yylocp)
+{
+  unsigned res = 0;
+  int end_col = 0 != yylocp->last_column ? yylocp->last_column - 1 : 0;
+  if (0 <= yylocp->first_line)
+    {
+      res += YYFPRINTF (yyo, "%d", yylocp->first_line);
+      if (0 <= yylocp->first_column)
+        res += YYFPRINTF (yyo, ".%d", yylocp->first_column);
+    }
+  if (0 <= yylocp->last_line)
+    {
+      if (yylocp->first_line < yylocp->last_line)
+        {
+          res += YYFPRINTF (yyo, "-%d", yylocp->last_line);
+          if (0 <= end_col)
+            res += YYFPRINTF (yyo, ".%d", end_col);
+        }
+      else if (0 <= end_col && yylocp->first_column < end_col)
+        res += YYFPRINTF (yyo, "-%d", end_col);
+    }
+  return res;
+ }
 
-/* Enable debugging if requested.  */
-#if YYDEBUG
+#  define YY_LOCATION_PRINT(File, Loc)          \
+  yy_location_print_ (File, &(Loc))
 
-# ifndef YYFPRINTF
-#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
-#  define YYFPRINTF fprintf
+# else
+#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
 # endif
+#endif
 
-# define YYDPRINTF(Args)                       \
-do {                                           \
-  if (yydebug)                                 \
-    YYFPRINTF Args;                            \
-} while (YYID (0))
 
-# define YY_SYMBOL_PRINT(Title, Type, Value, Location)                   \
-do {                                                                     \
-  if (yydebug)                                                           \
-    {                                                                    \
-      YYFPRINTF (stderr, "%s ", Title);                                          \
-      yy_symbol_print (stderr,                                           \
-                 Type, Value, Location, info); \
-      YYFPRINTF (stderr, "\n");                                                  \
-    }                                                                    \
-} while (YYID (0))
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)                    \
+do {                                                                      \
+  if (yydebug)                                                            \
+    {                                                                     \
+      YYFPRINTF (stderr, "%s ", Title);                                   \
+      yy_symbol_print (stderr,                                            \
+                  Type, Value, Location, info); \
+      YYFPRINTF (stderr, "\n");                                           \
+    }                                                                     \
+} while (0)
 
 
-/*--------------------------------.
-| Print this symbol on YYOUTPUT.  |
-`--------------------------------*/
+/*----------------------------------------.
+| Print this symbol's value on YYOUTPUT.  |
+`----------------------------------------*/
 
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static void
 yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, DateInfo* info)
-#else
-static void
-yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, info)
-    FILE *yyoutput;
-    int yytype;
-    YYSTYPE const * const yyvaluep;
-    YYLTYPE const * const yylocationp;
-    DateInfo* info;
-#endif
 {
-  if (!yyvaluep)
-    return;
+  FILE *yyo = yyoutput;
+  YYUSE (yyo);
   YYUSE (yylocationp);
   YYUSE (info);
+  if (!yyvaluep)
+    return;
 # ifdef YYPRINT
   if (yytype < YYNTOKENS)
     YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
-# else
-  YYUSE (yyoutput);
 # endif
-  switch (yytype)
-    {
-      default:
-       break;
-    }
+  YYUSE (yytype);
 }
 
 
@@ -928,24 +931,11 @@ yy_symbol_value_print (yyoutput, yytype, yyvaluep, yylocationp, info)
 | Print this symbol on YYOUTPUT.  |
 `--------------------------------*/
 
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static void
 yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, YYLTYPE const * const yylocationp, DateInfo* info)
-#else
-static void
-yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, info)
-    FILE *yyoutput;
-    int yytype;
-    YYSTYPE const * const yyvaluep;
-    YYLTYPE const * const yylocationp;
-    DateInfo* info;
-#endif
 {
-  if (yytype < YYNTOKENS)
-    YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
-  else
-    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+  YYFPRINTF (yyoutput, "%s %s (",
+             yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
 
   YY_LOCATION_PRINT (yyoutput, *yylocationp);
   YYFPRINTF (yyoutput, ": ");
@@ -958,68 +948,54 @@ yy_symbol_print (yyoutput, yytype, yyvaluep, yylocationp, info)
 | TOP (included).                                                   |
 `------------------------------------------------------------------*/
 
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static void
-yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
-#else
-static void
-yy_stack_print (bottom, top)
-    yytype_int16 *bottom;
-    yytype_int16 *top;
-#endif
+yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
 {
   YYFPRINTF (stderr, "Stack now");
-  for (; bottom <= top; ++bottom)
-    YYFPRINTF (stderr, " %d", *bottom);
+  for (; yybottom <= yytop; yybottom++)
+    {
+      int yybot = *yybottom;
+      YYFPRINTF (stderr, " %d", yybot);
+    }
   YYFPRINTF (stderr, "\n");
 }
 
-# define YY_STACK_PRINT(Bottom, Top)                           \
-do {                                                           \
-  if (yydebug)                                                 \
-    yy_stack_print ((Bottom), (Top));                          \
-} while (YYID (0))
+# define YY_STACK_PRINT(Bottom, Top)                            \
+do {                                                            \
+  if (yydebug)                                                  \
+    yy_stack_print ((Bottom), (Top));                           \
+} while (0)
 
 
 /*------------------------------------------------.
 | Report that the YYRULE is going to be reduced.  |
 `------------------------------------------------*/
 
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-static void
-yy_reduce_print (YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, DateInfo* info)
-#else
 static void
-yy_reduce_print (yyvsp, yylsp, yyrule, info)
-    YYSTYPE *yyvsp;
-    YYLTYPE *yylsp;
-    int yyrule;
-    DateInfo* info;
-#endif
+yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, YYLTYPE *yylsp, int yyrule, DateInfo* info)
 {
+  unsigned long yylno = yyrline[yyrule];
   int yynrhs = yyr2[yyrule];
   int yyi;
-  unsigned long int yylno = yyrline[yyrule];
   YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
-            yyrule - 1, yylno);
+             yyrule - 1, yylno);
   /* The symbols being reduced.  */
   for (yyi = 0; yyi < yynrhs; yyi++)
     {
-      fprintf (stderr, "   $%d = ", yyi + 1);
-      yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
-                      &(yyvsp[(yyi + 1) - (yynrhs)])
-                      , &(yylsp[(yyi + 1) - (yynrhs)])                , info);
-      fprintf (stderr, "\n");
+      YYFPRINTF (stderr, "   $%d = ", yyi + 1);
+      yy_symbol_print (stderr,
+                       yystos[yyssp[yyi + 1 - yynrhs]],
+                       &(yyvsp[(yyi + 1) - (yynrhs)])
+                       , &(yylsp[(yyi + 1) - (yynrhs)])                       , info);
+      YYFPRINTF (stderr, "\n");
     }
 }
 
-# define YY_REDUCE_PRINT(Rule)         \
-do {                                   \
-  if (yydebug)                         \
-    yy_reduce_print (yyvsp, yylsp, Rule, info); \
-} while (YYID (0))
+# define YY_REDUCE_PRINT(Rule)          \
+do {                                    \
+  if (yydebug)                          \
+    yy_reduce_print (yyssp, yyvsp, yylsp, Rule, info); \
+} while (0)
 
 /* Nonzero means print parse trace.  It is left uninitialized so that
    multiple parsers can coexist.  */
@@ -1033,7 +1009,7 @@ int yydebug;
 
 
 /* YYINITDEPTH -- initial size of the parser's stacks.  */
-#ifndef        YYINITDEPTH
+#ifndef YYINITDEPTH
 # define YYINITDEPTH 200
 #endif
 
@@ -1048,7 +1024,6 @@ int yydebug;
 # define YYMAXDEPTH 10000
 #endif
 
-\f
 
 #if YYERROR_VERBOSE
 
@@ -1057,15 +1032,8 @@ int yydebug;
 #   define yystrlen strlen
 #  else
 /* Return the length of YYSTR.  */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static YYSIZE_T
 yystrlen (const char *yystr)
-#else
-static YYSIZE_T
-yystrlen (yystr)
-    const char *yystr;
-#endif
 {
   YYSIZE_T yylen;
   for (yylen = 0; yystr[yylen]; yylen++)
@@ -1081,16 +1049,8 @@ yystrlen (yystr)
 #  else
 /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
    YYDEST.  */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static char *
 yystpcpy (char *yydest, const char *yysrc)
-#else
-static char *
-yystpcpy (yydest, yysrc)
-    char *yydest;
-    const char *yysrc;
-#endif
 {
   char *yyd = yydest;
   const char *yys = yysrc;
@@ -1120,27 +1080,27 @@ yytnamerr (char *yyres, const char *yystr)
       char const *yyp = yystr;
 
       for (;;)
-       switch (*++yyp)
-         {
-         case '\'':
-         case ',':
-           goto do_not_strip_quotes;
-
-         case '\\':
-           if (*++yyp != '\\')
-             goto do_not_strip_quotes;
-           /* Fall through.  */
-         default:
-           if (yyres)
-             yyres[yyn] = *yyp;
-           yyn++;
-           break;
-
-         case '"':
-           if (yyres)
-             yyres[yyn] = '\0';
-           return yyn;
-         }
+        switch (*++yyp)
+          {
+          case '\'':
+          case ',':
+            goto do_not_strip_quotes;
+
+          case '\\':
+            if (*++yyp != '\\')
+              goto do_not_strip_quotes;
+            /* Fall through.  */
+          default:
+            if (yyres)
+              yyres[yyn] = *yyp;
+            yyn++;
+            break;
+
+          case '"':
+            if (yyres)
+              yyres[yyn] = '\0';
+            return yyn;
+          }
     do_not_strip_quotes: ;
     }
 
@@ -1151,169 +1111,161 @@ yytnamerr (char *yyres, const char *yystr)
 }
 # endif
 
-/* Copy into YYRESULT an error message about the unexpected token
-   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
-   including the terminating null byte.  If YYRESULT is null, do not
-   copy anything; just return the number of bytes that would be
-   copied.  As a special case, return 0 if an ordinary "syntax error"
-   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
-   size calculation.  */
-static YYSIZE_T
-yysyntax_error (char *yyresult, int yystate, int yychar)
+/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
+   about the unexpected token YYTOKEN for the state stack whose top is
+   YYSSP.
+
+   Return 0 if *YYMSG was successfully written.  Return 1 if *YYMSG is
+   not large enough to hold the message.  In that case, also set
+   *YYMSG_ALLOC to the required number of bytes.  Return 2 if the
+   required number of bytes is too large to store.  */
+static int
+yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
+                yytype_int16 *yyssp, int yytoken)
 {
-  int yyn = yypact[yystate];
+  YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
+  YYSIZE_T yysize = yysize0;
+  enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+  /* Internationalized format string. */
+  const char *yyformat = YY_NULLPTR;
+  /* Arguments of yyformat. */
+  char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+  /* Number of reported tokens (one for the "unexpected", one per
+     "expected"). */
+  int yycount = 0;
+
+  /* There are many possibilities here to consider:
+     - If this state is a consistent state with a default action, then
+       the only way this function was invoked is if the default action
+       is an error action.  In that case, don't check for expected
+       tokens because there are none.
+     - The only way there can be no lookahead present (in yychar) is if
+       this state is a consistent state with a default action.  Thus,
+       detecting the absence of a lookahead is sufficient to determine
+       that there is no unexpected or expected token to report.  In that
+       case, just report a simple "syntax error".
+     - Don't assume there isn't a lookahead just because this state is a
+       consistent state with a default action.  There might have been a
+       previous inconsistent state, consistent state with a non-default
+       action, or user semantic action that manipulated yychar.
+     - Of course, the expected token list depends on states to have
+       correct lookahead information, and it depends on the parser not
+       to perform extra reductions after fetching a lookahead from the
+       scanner and before detecting a syntax error.  Thus, state merging
+       (from LALR or IELR) and default reductions corrupt the expected
+       token list.  However, the list is correct for canonical LR with
+       one exception: it will still contain any token that will not be
+       accepted due to an error action in a later state.
+  */
+  if (yytoken != YYEMPTY)
+    {
+      int yyn = yypact[*yyssp];
+      yyarg[yycount++] = yytname[yytoken];
+      if (!yypact_value_is_default (yyn))
+        {
+          /* Start YYX at -YYN if negative to avoid negative indexes in
+             YYCHECK.  In other words, skip the first -YYN actions for
+             this state because they are default actions.  */
+          int yyxbegin = yyn < 0 ? -yyn : 0;
+          /* Stay within bounds of both yycheck and yytname.  */
+          int yychecklim = YYLAST - yyn + 1;
+          int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+          int yyx;
+
+          for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+            if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
+                && !yytable_value_is_error (yytable[yyx + yyn]))
+              {
+                if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+                  {
+                    yycount = 1;
+                    yysize = yysize0;
+                    break;
+                  }
+                yyarg[yycount++] = yytname[yyx];
+                {
+                  YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
+                  if (! (yysize <= yysize1
+                         && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+                    return 2;
+                  yysize = yysize1;
+                }
+              }
+        }
+    }
 
-  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
-    return 0;
-  else
+  switch (yycount)
+    {
+# define YYCASE_(N, S)                      \
+      case N:                               \
+        yyformat = S;                       \
+      break
+    default: /* Avoid compiler warnings. */
+      YYCASE_(0, YY_("syntax error"));
+      YYCASE_(1, YY_("syntax error, unexpected %s"));
+      YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
+      YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
+      YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
+      YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
+# undef YYCASE_
+    }
+
+  {
+    YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
+    if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
+      return 2;
+    yysize = yysize1;
+  }
+
+  if (*yymsg_alloc < yysize)
     {
-      int yytype = YYTRANSLATE (yychar);
-      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
-      YYSIZE_T yysize = yysize0;
-      YYSIZE_T yysize1;
-      int yysize_overflow = 0;
-      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
-      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
-      int yyx;
-
-# if 0
-      /* This is so xgettext sees the translatable formats that are
-        constructed on the fly.  */
-      YY_("syntax error, unexpected %s");
-      YY_("syntax error, unexpected %s, expecting %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
-      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
-# endif
-      char *yyfmt;
-      char const *yyf;
-      static char const yyunexpected[] = "syntax error, unexpected %s";
-      static char const yyexpecting[] = ", expecting %s";
-      static char const yyor[] = " or %s";
-      char yyformat[sizeof yyunexpected
-                   + sizeof yyexpecting - 1
-                   + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
-                      * (sizeof yyor - 1))];
-      char const *yyprefix = yyexpecting;
-
-      /* Start YYX at -YYN if negative to avoid negative indexes in
-        YYCHECK.  */
-      int yyxbegin = yyn < 0 ? -yyn : 0;
-
-      /* Stay within bounds of both yycheck and yytname.  */
-      int yychecklim = YYLAST - yyn + 1;
-      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
-      int yycount = 1;
-
-      yyarg[0] = yytname[yytype];
-      yyfmt = yystpcpy (yyformat, yyunexpected);
-
-      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
-       if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
-         {
-           if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
-             {
-               yycount = 1;
-               yysize = yysize0;
-               yyformat[sizeof yyunexpected - 1] = '\0';
-               break;
-             }
-           yyarg[yycount++] = yytname[yyx];
-           yysize1 = yysize + yytnamerr (0, yytname[yyx]);
-           yysize_overflow |= (yysize1 < yysize);
-           yysize = yysize1;
-           yyfmt = yystpcpy (yyfmt, yyprefix);
-           yyprefix = yyor;
-         }
-
-      yyf = YY_(yyformat);
-      yysize1 = yysize + yystrlen (yyf);
-      yysize_overflow |= (yysize1 < yysize);
-      yysize = yysize1;
-
-      if (yysize_overflow)
-       return YYSIZE_MAXIMUM;
-
-      if (yyresult)
-       {
-         /* Avoid sprintf, as that infringes on the user's name space.
-            Don't have undefined behavior even if the translation
-            produced a string with the wrong number of "%s"s.  */
-         char *yyp = yyresult;
-         int yyi = 0;
-         while ((*yyp = *yyf) != '\0')
-           {
-             if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
-               {
-                 yyp += yytnamerr (yyp, yyarg[yyi++]);
-                 yyf += 2;
-               }
-             else
-               {
-                 yyp++;
-                 yyf++;
-               }
-           }
-       }
-      return yysize;
+      *yymsg_alloc = 2 * yysize;
+      if (! (yysize <= *yymsg_alloc
+             && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
+        *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
+      return 1;
     }
+
+  /* Avoid sprintf, as that infringes on the user's name space.
+     Don't have undefined behavior even if the translation
+     produced a string with the wrong number of "%s"s.  */
+  {
+    char *yyp = *yymsg;
+    int yyi = 0;
+    while ((*yyp = *yyformat) != '\0')
+      if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
+        {
+          yyp += yytnamerr (yyp, yyarg[yyi++]);
+          yyformat += 2;
+        }
+      else
+        {
+          yyp++;
+          yyformat++;
+        }
+  }
+  return 0;
 }
 #endif /* YYERROR_VERBOSE */
-\f
 
 /*-----------------------------------------------.
 | Release the memory associated to this symbol.  |
 `-----------------------------------------------*/
 
-/*ARGSUSED*/
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 static void
 yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, YYLTYPE *yylocationp, DateInfo* info)
-#else
-static void
-yydestruct (yymsg, yytype, yyvaluep, yylocationp, info)
-    const char *yymsg;
-    int yytype;
-    YYSTYPE *yyvaluep;
-    YYLTYPE *yylocationp;
-    DateInfo* info;
-#endif
 {
   YYUSE (yyvaluep);
   YYUSE (yylocationp);
   YYUSE (info);
-
   if (!yymsg)
     yymsg = "Deleting";
   YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
 
-  switch (yytype)
-    {
-
-      default:
-       break;
-    }
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
+  YYUSE (yytype);
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
 }
-\f
-
-/* Prevent warnings from -Wmissing-prototypes.  */
-
-#ifdef YYPARSE_PARAM
-#if defined __STDC__ || defined __cplusplus
-int yyparse (void *YYPARSE_PARAM);
-#else
-int yyparse ();
-#endif
-#else /* ! YYPARSE_PARAM */
-#if defined __STDC__ || defined __cplusplus
-int yyparse (DateInfo* info);
-#else
-int yyparse ();
-#endif
-#endif /* ! YYPARSE_PARAM */
-
-
 
 
 
@@ -1322,112 +1274,96 @@ int yyparse ();
 | yyparse.  |
 `----------*/
 
-#ifdef YYPARSE_PARAM
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
-int
-yyparse (void *YYPARSE_PARAM)
-#else
-int
-yyparse (YYPARSE_PARAM)
-    void *YYPARSE_PARAM;
-#endif
-#else /* ! YYPARSE_PARAM */
-#if (defined __STDC__ || defined __C99__FUNC__ \
-     || defined __cplusplus || defined _MSC_VER)
 int
 yyparse (DateInfo* info)
-#else
-int
-yyparse (info)
-    DateInfo* info;
-#endif
-#endif
 {
-  /* The look-ahead symbol.  */
+/* The lookahead symbol.  */
 int yychar;
 
-/* The semantic value of the look-ahead symbol.  */
-YYSTYPE yylval = {0};
 
-/* Number of syntax errors so far.  */
-int yynerrs;
-/* Location data for the look-ahead symbol.  */
-YYLTYPE yylloc;
+/* The semantic value of the lookahead symbol.  */
+/* Default value used for initialization, for pacifying older GCCs
+   or non-GCC compilers.  */
+YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
+YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
 
-  int yystate;
-  int yyn;
-  int yyresult;
-  /* Number of tokens to shift before error messages enabled.  */
-  int yyerrstatus;
-  /* Look-ahead token as an internal (translated) token number.  */
-  int yytoken = 0;
-#if YYERROR_VERBOSE
-  /* Buffer for error messages, and its allocated size.  */
-  char yymsgbuf[128];
-  char *yymsg = yymsgbuf;
-  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
-#endif
+/* Location data for the lookahead symbol.  */
+static YYLTYPE yyloc_default
+# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL
+  = { 1, 1, 1, 1 }
+# endif
+;
+YYLTYPE yylloc = yyloc_default;
 
-  /* Three stacks and their tools:
-     `yyss': related to states,
-     `yyvs': related to semantic values,
-     `yyls': related to locations.
+    /* Number of syntax errors so far.  */
+    int yynerrs;
 
-     Refer to the stacks thru separate pointers, to allow yyoverflow
-     to reallocate them elsewhere.  */
+    int yystate;
+    /* Number of tokens to shift before error messages enabled.  */
+    int yyerrstatus;
 
-  /* The state stack.  */
-  yytype_int16 yyssa[YYINITDEPTH];
-  yytype_int16 *yyss = yyssa;
-  yytype_int16 *yyssp;
+    /* The stacks and their tools:
+       'yyss': related to states.
+       'yyvs': related to semantic values.
+       'yyls': related to locations.
 
-  /* The semantic value stack.  */
-  YYSTYPE yyvsa[YYINITDEPTH];
-  YYSTYPE *yyvs = yyvsa;
-  YYSTYPE *yyvsp;
+       Refer to the stacks through separate pointers, to allow yyoverflow
+       to reallocate them elsewhere.  */
 
-  /* The location stack.  */
-  YYLTYPE yylsa[YYINITDEPTH];
-  YYLTYPE *yyls = yylsa;
-  YYLTYPE *yylsp;
-  /* The locations where the error started and ended.  */
-  YYLTYPE yyerror_range[2];
+    /* The state stack.  */
+    yytype_int16 yyssa[YYINITDEPTH];
+    yytype_int16 *yyss;
+    yytype_int16 *yyssp;
 
-#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N), yylsp -= (N))
+    /* The semantic value stack.  */
+    YYSTYPE yyvsa[YYINITDEPTH];
+    YYSTYPE *yyvs;
+    YYSTYPE *yyvsp;
+
+    /* The location stack.  */
+    YYLTYPE yylsa[YYINITDEPTH];
+    YYLTYPE *yyls;
+    YYLTYPE *yylsp;
+
+    /* The locations where the error started and ended.  */
+    YYLTYPE yyerror_range[3];
 
-  YYSIZE_T yystacksize = YYINITDEPTH;
+    YYSIZE_T yystacksize;
 
+  int yyn;
+  int yyresult;
+  /* Lookahead token as an internal (translated) token number.  */
+  int yytoken = 0;
   /* The variables used to return semantic value and location from the
      action routines.  */
   YYSTYPE yyval;
   YYLTYPE yyloc;
 
+#if YYERROR_VERBOSE
+  /* Buffer for error messages, and its allocated size.  */
+  char yymsgbuf[128];
+  char *yymsg = yymsgbuf;
+  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N), yylsp -= (N))
+
   /* The number of symbols on the RHS of the reduced rule.
      Keep to zero when no symbol should be popped.  */
   int yylen = 0;
 
+  yyssp = yyss = yyssa;
+  yyvsp = yyvs = yyvsa;
+  yylsp = yyls = yylsa;
+  yystacksize = YYINITDEPTH;
+
   YYDPRINTF ((stderr, "Starting parse\n"));
 
   yystate = 0;
   yyerrstatus = 0;
   yynerrs = 0;
-  yychar = YYEMPTY;            /* Cause a token to be read.  */
-
-  /* Initialize stack pointers.
-     Waste one element of value and location stack
-     so that they stay on the same level as the state stack.
-     The wasted elements are never initialized.  */
-
-  yyssp = yyss;
-  yyvsp = yyvs;
-  yylsp = yyls;
-#if YYLTYPE_IS_TRIVIAL
-  /* Initialize the default location before parsing starts.  */
-  yylloc.first_line   = yylloc.last_line   = 1;
-  yylloc.first_column = yylloc.last_column = 0;
-#endif
-
+  yychar = YYEMPTY; /* Cause a token to be read.  */
+  yylsp[0] = yylloc;
   goto yysetstate;
 
 /*------------------------------------------------------------.
@@ -1448,25 +1384,26 @@ YYLTYPE yylloc;
 
 #ifdef yyoverflow
       {
-       /* Give user a chance to reallocate the stack.  Use copies of
-          these so that the &'s don't force the real ones into
-          memory.  */
-       YYSTYPE *yyvs1 = yyvs;
-       yytype_int16 *yyss1 = yyss;
-       YYLTYPE *yyls1 = yyls;
-
-       /* Each stack pointer address is followed by the size of the
-          data in use in that stack, in bytes.  This used to be a
-          conditional around just the two extra args, but that might
-          be undefined if yyoverflow is a macro.  */
-       yyoverflow (YY_("memory exhausted"),
-                   &yyss1, yysize * sizeof (*yyssp),
-                   &yyvs1, yysize * sizeof (*yyvsp),
-                   &yyls1, yysize * sizeof (*yylsp),
-                   &yystacksize);
-       yyls = yyls1;
-       yyss = yyss1;
-       yyvs = yyvs1;
+        /* Give user a chance to reallocate the stack.  Use copies of
+           these so that the &'s don't force the real ones into
+           memory.  */
+        YYSTYPE *yyvs1 = yyvs;
+        yytype_int16 *yyss1 = yyss;
+        YYLTYPE *yyls1 = yyls;
+
+        /* Each stack pointer address is followed by the size of the
+           data in use in that stack, in bytes.  This used to be a
+           conditional around just the two extra args, but that might
+           be undefined if yyoverflow is a macro.  */
+        yyoverflow (YY_("memory exhausted"),
+                    &yyss1, yysize * sizeof (*yyssp),
+                    &yyvs1, yysize * sizeof (*yyvsp),
+                    &yyls1, yysize * sizeof (*yylsp),
+                    &yystacksize);
+
+        yyls = yyls1;
+        yyss = yyss1;
+        yyvs = yyvs1;
       }
 #else /* no yyoverflow */
 # ifndef YYSTACK_RELOCATE
@@ -1474,23 +1411,23 @@ YYLTYPE yylloc;
 # else
       /* Extend the stack our own way.  */
       if (YYMAXDEPTH <= yystacksize)
-       goto yyexhaustedlab;
+        goto yyexhaustedlab;
       yystacksize *= 2;
       if (YYMAXDEPTH < yystacksize)
-       yystacksize = YYMAXDEPTH;
+        yystacksize = YYMAXDEPTH;
 
       {
-       yytype_int16 *yyss1 = yyss;
-       union yyalloc *yyptr =
-         (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
-       if (! yyptr)
-         goto yyexhaustedlab;
-       YYSTACK_RELOCATE (yyss);
-       YYSTACK_RELOCATE (yyvs);
-       YYSTACK_RELOCATE (yyls);
+        yytype_int16 *yyss1 = yyss;
+        union yyalloc *yyptr =
+          (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+        if (! yyptr)
+          goto yyexhaustedlab;
+        YYSTACK_RELOCATE (yyss_alloc, yyss);
+        YYSTACK_RELOCATE (yyvs_alloc, yyvs);
+        YYSTACK_RELOCATE (yyls_alloc, yyls);
 #  undef YYSTACK_RELOCATE
-       if (yyss1 != yyssa)
-         YYSTACK_FREE (yyss1);
+        if (yyss1 != yyssa)
+          YYSTACK_FREE (yyss1);
       }
 # endif
 #endif /* no yyoverflow */
@@ -1500,14 +1437,17 @@ YYLTYPE yylloc;
       yylsp = yyls + yysize - 1;
 
       YYDPRINTF ((stderr, "Stack size increased to %lu\n",
-                 (unsigned long int) yystacksize));
+                  (unsigned long) yystacksize));
 
       if (yyss + yystacksize - 1 <= yyssp)
-       YYABORT;
+        YYABORT;
     }
 
   YYDPRINTF ((stderr, "Entering state %d\n", yystate));
 
+  if (yystate == YYFINAL)
+    YYACCEPT;
+
   goto yybackup;
 
 /*-----------.
@@ -1516,20 +1456,20 @@ YYLTYPE yylloc;
 yybackup:
 
   /* Do appropriate processing given the current state.  Read a
-     look-ahead token if we need one and don't already have one.  */
+     lookahead token if we need one and don't already have one.  */
 
-  /* First try to decide what to do without reference to look-ahead token.  */
+  /* First try to decide what to do without reference to lookahead token.  */
   yyn = yypact[yystate];
-  if (yyn == YYPACT_NINF)
+  if (yypact_value_is_default (yyn))
     goto yydefault;
 
-  /* Not known => get a look-ahead token if don't already have one.  */
+  /* Not known => get a lookahead token if don't already have one.  */
 
-  /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol.  */
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol.  */
   if (yychar == YYEMPTY)
     {
       YYDPRINTF ((stderr, "Reading a token: "));
-      yychar = YYLEX;
+      yychar = yylex (&yylval, &yylloc, info);
     }
 
   if (yychar <= YYEOF)
@@ -1551,29 +1491,27 @@ yybackup:
   yyn = yytable[yyn];
   if (yyn <= 0)
     {
-      if (yyn == 0 || yyn == YYTABLE_NINF)
-       goto yyerrlab;
+      if (yytable_value_is_error (yyn))
+        goto yyerrlab;
       yyn = -yyn;
       goto yyreduce;
     }
 
-  if (yyn == YYFINAL)
-    YYACCEPT;
-
   /* Count tokens shifted since error; after three, turn off error
      status.  */
   if (yyerrstatus)
     yyerrstatus--;
 
-  /* Shift the look-ahead token.  */
+  /* Shift the lookahead token.  */
   YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
 
-  /* Discard the shifted token unless it is eof.  */
-  if (yychar != YYEOF)
-    yychar = YYEMPTY;
+  /* Discard the shifted token.  */
+  yychar = YYEMPTY;
 
   yystate = yyn;
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
   *++yylsp = yylloc;
   goto yynewstate;
 
@@ -1596,7 +1534,7 @@ yyreduce:
   yylen = yyr2[yyn];
 
   /* If YYLEN is nonzero, implement the default value of the action:
-     `$$ = $1'.
+     '$$ = $1'.
 
      Otherwise, the following line sets YYVAL to garbage.
      This behavior is undocumented and Bison
@@ -1605,8 +1543,9 @@ yyreduce:
      GCC warning that YYVAL may be used uninitialized.  */
   yyval = yyvsp[1-yylen];
 
-  /* Default location.  */
+  /* Default location. */
   YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen);
+  yyerror_range[1] = yyloc;
   YY_REDUCE_PRINT (yyn);
   switch (yyn)
     {
@@ -1614,42 +1553,48 @@ yyreduce:
 
     {
            yyHaveTime++;
-       ;}
+       }
+
     break;
 
   case 5:
 
     {
            yyHaveZone++;
-       ;}
+       }
+
     break;
 
   case 6:
 
     {
            yyHaveDate++;
-       ;}
+       }
+
     break;
 
   case 7:
 
     {
            yyHaveOrdinalMonth++;
-       ;}
+       }
+
     break;
 
   case 8:
 
     {
            yyHaveDay++;
-       ;}
+       }
+
     break;
 
   case 9:
 
     {
            yyHaveRel++;
-       ;}
+       }
+
     break;
 
   case 10:
@@ -1657,7 +1602,8 @@ yyreduce:
     {
            yyHaveTime++;
            yyHaveDate++;
-       ;}
+       }
+
     break;
 
   case 11:
@@ -1666,267 +1612,294 @@ yyreduce:
            yyHaveTime++;
            yyHaveDate++;
            yyHaveRel++;
-       ;}
+       }
+
     break;
 
   case 13:
 
     {
-           yyHour = (yyvsp[(1) - (2)].Number);
+           yyHour = (yyvsp[-1].Number);
            yyMinutes = 0;
            yySeconds = 0;
-           yyMeridian = (yyvsp[(2) - (2)].Meridian);
-       ;}
+           yyMeridian = (yyvsp[0].Meridian);
+       }
+
     break;
 
   case 14:
 
     {
-           yyHour = (yyvsp[(1) - (4)].Number);
-           yyMinutes = (yyvsp[(3) - (4)].Number);
+           yyHour = (yyvsp[-3].Number);
+           yyMinutes = (yyvsp[-1].Number);
            yySeconds = 0;
-           yyMeridian = (yyvsp[(4) - (4)].Meridian);
-       ;}
+           yyMeridian = (yyvsp[0].Meridian);
+       }
+
     break;
 
   case 15:
 
     {
-           yyHour = (yyvsp[(1) - (5)].Number);
-           yyMinutes = (yyvsp[(3) - (5)].Number);
-           yyMeridian = MER24;
-           yyDSTmode = DSToff;
-           yyTimezone = ((yyvsp[(5) - (5)].Number) % 100 + ((yyvsp[(5) - (5)].Number) / 100) * 60);
-           ++yyHaveZone;
-       ;}
+           yyHour = (yyvsp[-5].Number);
+           yyMinutes = (yyvsp[-3].Number);
+           yySeconds = (yyvsp[-1].Number);
+           yyMeridian = (yyvsp[0].Meridian);
+       }
+
     break;
 
   case 16:
 
     {
-           yyHour = (yyvsp[(1) - (6)].Number);
-           yyMinutes = (yyvsp[(3) - (6)].Number);
-           yySeconds = (yyvsp[(5) - (6)].Number);
-           yyMeridian = (yyvsp[(6) - (6)].Meridian);
-       ;}
+           yyTimezone = (yyvsp[-1].Number);
+           if (yyTimezone > HOUR( 12)) yyTimezone -= HOUR(100);
+           yyDSTmode = DSTon;
+       }
+
     break;
 
   case 17:
 
     {
-           yyHour = (yyvsp[(1) - (7)].Number);
-           yyMinutes = (yyvsp[(3) - (7)].Number);
-           yySeconds = (yyvsp[(5) - (7)].Number);
-           yyMeridian = MER24;
+           yyTimezone = (yyvsp[0].Number);
+           if (yyTimezone > HOUR( 12)) yyTimezone -= HOUR(100);
            yyDSTmode = DSToff;
-           yyTimezone = ((yyvsp[(7) - (7)].Number) % 100 + ((yyvsp[(7) - (7)].Number) / 100) * 60);
-           ++yyHaveZone;
-       ;}
+       }
+
     break;
 
   case 18:
 
     {
-           yyTimezone = (yyvsp[(1) - (2)].Number);
+           yyTimezone = (yyvsp[0].Number);
            yyDSTmode = DSTon;
-       ;}
+       }
+
     break;
 
   case 19:
 
     {
-           yyTimezone = (yyvsp[(1) - (1)].Number);
+           yyTimezone = -(yyvsp[-1].Number)*((yyvsp[0].Number) % 100 + ((yyvsp[0].Number) / 100) * 60);
            yyDSTmode = DSToff;
-       ;}
+       }
+
     break;
 
   case 20:
 
     {
-           yyTimezone = (yyvsp[(1) - (1)].Number);
-           yyDSTmode = DSTon;
-       ;}
+           yyDayOrdinal = 1;
+           yyDayNumber = (yyvsp[0].Number);
+       }
+
     break;
 
   case 21:
 
     {
            yyDayOrdinal = 1;
-           yyDayNumber = (yyvsp[(1) - (1)].Number);
-       ;}
+           yyDayNumber = (yyvsp[-1].Number);
+       }
+
     break;
 
   case 22:
 
     {
-           yyDayOrdinal = 1;
-           yyDayNumber = (yyvsp[(1) - (2)].Number);
-       ;}
+           yyDayOrdinal = (yyvsp[-1].Number);
+           yyDayNumber = (yyvsp[0].Number);
+       }
+
     break;
 
   case 23:
 
     {
-           yyDayOrdinal = (yyvsp[(1) - (2)].Number);
-           yyDayNumber = (yyvsp[(2) - (2)].Number);
-       ;}
+           yyDayOrdinal = (yyvsp[-2].Number) * (yyvsp[-1].Number);
+           yyDayNumber = (yyvsp[0].Number);
+       }
+
     break;
 
   case 24:
 
     {
-           yyDayOrdinal = (yyvsp[(1) - (3)].Number) * (yyvsp[(2) - (3)].Number);
-           yyDayNumber = (yyvsp[(3) - (3)].Number);
-       ;}
+           yyDayOrdinal = 2;
+           yyDayNumber = (yyvsp[0].Number);
+       }
+
     break;
 
   case 25:
 
     {
-           yyDayOrdinal = 2;
-           yyDayNumber = (yyvsp[(2) - (2)].Number);
-       ;}
+           yyMonth = (yyvsp[-2].Number);
+           yyDay = (yyvsp[0].Number);
+       }
+
     break;
 
   case 26:
 
     {
-           yyMonth = (yyvsp[(1) - (3)].Number);
-           yyDay = (yyvsp[(3) - (3)].Number);
-       ;}
+           yyMonth = (yyvsp[-4].Number);
+           yyDay = (yyvsp[-2].Number);
+           yyYear = (yyvsp[0].Number);
+       }
+
     break;
 
   case 27:
 
     {
-           yyMonth = (yyvsp[(1) - (5)].Number);
-           yyDay = (yyvsp[(3) - (5)].Number);
-           yyYear = (yyvsp[(5) - (5)].Number);
-       ;}
+           yyYear = (yyvsp[0].Number) / 10000;
+           yyMonth = ((yyvsp[0].Number) % 10000)/100;
+           yyDay = (yyvsp[0].Number) % 100;
+       }
+
     break;
 
   case 28:
 
     {
-           yyYear = (yyvsp[(1) - (1)].Number) / 10000;
-           yyMonth = ((yyvsp[(1) - (1)].Number) % 10000)/100;
-           yyDay = (yyvsp[(1) - (1)].Number) % 100;
-       ;}
+           yyDay = (yyvsp[-4].Number);
+           yyMonth = (yyvsp[-2].Number);
+           yyYear = (yyvsp[0].Number);
+       }
+
     break;
 
   case 29:
 
     {
-           yyDay = (yyvsp[(1) - (5)].Number);
-           yyMonth = (yyvsp[(3) - (5)].Number);
-           yyYear = (yyvsp[(5) - (5)].Number);
-       ;}
+           yyMonth = (yyvsp[-2].Number);
+           yyDay = (yyvsp[0].Number);
+           yyYear = (yyvsp[-4].Number);
+       }
+
     break;
 
   case 30:
 
     {
-           yyMonth = (yyvsp[(3) - (5)].Number);
-           yyDay = (yyvsp[(5) - (5)].Number);
-           yyYear = (yyvsp[(1) - (5)].Number);
-       ;}
+           yyMonth = (yyvsp[-1].Number);
+           yyDay = (yyvsp[0].Number);
+       }
+
     break;
 
   case 31:
 
     {
-           yyMonth = (yyvsp[(1) - (2)].Number);
-           yyDay = (yyvsp[(2) - (2)].Number);
-       ;}
+           yyMonth = (yyvsp[-3].Number);
+           yyDay = (yyvsp[-2].Number);
+           yyYear = (yyvsp[0].Number);
+       }
+
     break;
 
   case 32:
 
     {
-           yyMonth = (yyvsp[(1) - (4)].Number);
-           yyDay = (yyvsp[(2) - (4)].Number);
-           yyYear = (yyvsp[(4) - (4)].Number);
-       ;}
+           yyMonth = (yyvsp[0].Number);
+           yyDay = (yyvsp[-1].Number);
+       }
+
     break;
 
   case 33:
 
     {
-           yyMonth = (yyvsp[(2) - (2)].Number);
-           yyDay = (yyvsp[(1) - (2)].Number);
-       ;}
+           yyMonth = 1;
+           yyDay = 1;
+           yyYear = EPOCH;
+       }
+
     break;
 
   case 34:
 
     {
-           yyMonth = 1;
-           yyDay = 1;
-           yyYear = EPOCH;
-       ;}
+           yyMonth = (yyvsp[-1].Number);
+           yyDay = (yyvsp[-2].Number);
+           yyYear = (yyvsp[0].Number);
+       }
+
     break;
 
   case 35:
 
     {
-           yyMonth = (yyvsp[(2) - (3)].Number);
-           yyDay = (yyvsp[(1) - (3)].Number);
-           yyYear = (yyvsp[(3) - (3)].Number);
-       ;}
+           yyMonthOrdinal = 1;
+           yyMonth = (yyvsp[0].Number);
+       }
+
     break;
 
   case 36:
 
     {
-           yyMonthOrdinal = 1;
-           yyMonth = (yyvsp[(2) - (2)].Number);
-       ;}
+           yyMonthOrdinal = (yyvsp[-1].Number);
+           yyMonth = (yyvsp[0].Number);
+       }
+
     break;
 
   case 37:
 
     {
-           yyMonthOrdinal = (yyvsp[(2) - (3)].Number);
-           yyMonth = (yyvsp[(3) - (3)].Number);
-       ;}
+           if ((yyvsp[-5].Number) != HOUR( 7) + HOUR(100)) YYABORT;
+           yyYear = (yyvsp[-10].Number);
+           yyMonth = (yyvsp[-8].Number);
+           yyDay = (yyvsp[-6].Number);
+           yyHour = (yyvsp[-4].Number);
+           yyMinutes = (yyvsp[-2].Number);
+           yySeconds = (yyvsp[0].Number);
+       }
+
     break;
 
   case 38:
 
     {
-           if ((yyvsp[(2) - (3)].Number) != HOUR( 7)) YYABORT;
-           yyYear = (yyvsp[(1) - (3)].Number) / 10000;
-           yyMonth = ((yyvsp[(1) - (3)].Number) % 10000)/100;
-           yyDay = (yyvsp[(1) - (3)].Number) % 100;
-           yyHour = (yyvsp[(3) - (3)].Number) / 10000;
-           yyMinutes = ((yyvsp[(3) - (3)].Number) % 10000)/100;
-           yySeconds = (yyvsp[(3) - (3)].Number) % 100;
-       ;}
+           if ((yyvsp[-1].Number) != HOUR( 7) + HOUR(100)) YYABORT;
+           yyYear = (yyvsp[-2].Number) / 10000;
+           yyMonth = ((yyvsp[-2].Number) % 10000)/100;
+           yyDay = (yyvsp[-2].Number) % 100;
+           yyHour = (yyvsp[0].Number) / 10000;
+           yyMinutes = ((yyvsp[0].Number) % 10000)/100;
+           yySeconds = (yyvsp[0].Number) % 100;
+       }
+
     break;
 
   case 39:
 
     {
-           if ((yyvsp[(2) - (7)].Number) != HOUR( 7)) YYABORT;
-           yyYear = (yyvsp[(1) - (7)].Number) / 10000;
-           yyMonth = ((yyvsp[(1) - (7)].Number) % 10000)/100;
-           yyDay = (yyvsp[(1) - (7)].Number) % 100;
-           yyHour = (yyvsp[(3) - (7)].Number);
-           yyMinutes = (yyvsp[(5) - (7)].Number);
-           yySeconds = (yyvsp[(7) - (7)].Number);
-       ;}
+           if ((yyvsp[-5].Number) != HOUR( 7) + HOUR(100)) YYABORT;
+           yyYear = (yyvsp[-6].Number) / 10000;
+           yyMonth = ((yyvsp[-6].Number) % 10000)/100;
+           yyDay = (yyvsp[-6].Number) % 100;
+           yyHour = (yyvsp[-4].Number);
+           yyMinutes = (yyvsp[-2].Number);
+           yySeconds = (yyvsp[0].Number);
+       }
+
     break;
 
   case 40:
 
     {
-           yyYear = (yyvsp[(1) - (2)].Number) / 10000;
-           yyMonth = ((yyvsp[(1) - (2)].Number) % 10000)/100;
-           yyDay = (yyvsp[(1) - (2)].Number) % 100;
-           yyHour = (yyvsp[(2) - (2)].Number) / 10000;
-           yyMinutes = ((yyvsp[(2) - (2)].Number) % 10000)/100;
-           yySeconds = (yyvsp[(2) - (2)].Number) % 100;
-       ;}
+           yyYear = (yyvsp[-1].Number) / 10000;
+           yyMonth = ((yyvsp[-1].Number) % 10000)/100;
+           yyDay = (yyvsp[-1].Number) % 100;
+           yyHour = (yyvsp[0].Number) / 10000;
+           yyMinutes = ((yyvsp[0].Number) % 10000)/100;
+           yySeconds = (yyvsp[0].Number) % 100;
+       }
+
     break;
 
   case 41:
@@ -1937,12 +1910,13 @@ yyreduce:
             * in a range accessible with a 32 bit clock seconds value.
             */
 
-           yyYear = (yyvsp[(2) - (4)].Number)/1000 + 2323 - 377;
+           yyYear = (yyvsp[-2].Number)/1000 + 2323 - 377;
            yyDay  = 1;
            yyMonth = 1;
-           yyRelDay += (((yyvsp[(2) - (4)].Number)%1000)*(365 + IsLeapYear(yyYear)))/1000;
-           yyRelSeconds += (yyvsp[(4) - (4)].Number) * 144 * 60;
-       ;}
+           yyRelDay += (((yyvsp[-2].Number)%1000)*(365 + IsLeapYear(yyYear)))/1000;
+           yyRelSeconds += (yyvsp[0].Number) * 144 * 60;
+       }
+
     break;
 
   case 42:
@@ -1951,121 +1925,145 @@ yyreduce:
            yyRelSeconds *= -1;
            yyRelMonth *= -1;
            yyRelDay *= -1;
-       ;}
+       }
+
     break;
 
   case 44:
 
     {
-           *yyRelPointer += (yyvsp[(1) - (3)].Number) * (yyvsp[(2) - (3)].Number) * (yyvsp[(3) - (3)].Number);
-       ;}
+           *yyRelPointer += (yyvsp[-2].Number) * (yyvsp[-1].Number) * (yyvsp[0].Number);
+       }
+
     break;
 
   case 45:
 
     {
-           *yyRelPointer += (yyvsp[(1) - (2)].Number) * (yyvsp[(2) - (2)].Number);
-       ;}
+           *yyRelPointer += (yyvsp[-1].Number) * (yyvsp[0].Number);
+       }
+
     break;
 
   case 46:
 
     {
-           *yyRelPointer += (yyvsp[(2) - (2)].Number);
-       ;}
+           *yyRelPointer += (yyvsp[0].Number);
+       }
+
     break;
 
   case 47:
 
     {
-           *yyRelPointer += (yyvsp[(2) - (3)].Number) * (yyvsp[(3) - (3)].Number);
-       ;}
+           *yyRelPointer += (yyvsp[-1].Number) * (yyvsp[0].Number);
+       }
+
     break;
 
   case 48:
 
     {
-           *yyRelPointer += (yyvsp[(1) - (1)].Number);
-       ;}
+           *yyRelPointer += (yyvsp[0].Number);
+       }
+
     break;
 
   case 49:
 
     {
            (yyval.Number) = -1;
-       ;}
+       }
+
     break;
 
   case 50:
 
     {
            (yyval.Number) =  1;
-       ;}
+       }
+
     break;
 
   case 51:
 
     {
-           (yyval.Number) = (yyvsp[(1) - (1)].Number);
+           (yyval.Number) = (yyvsp[0].Number);
            yyRelPointer = &yyRelSeconds;
-       ;}
+       }
+
     break;
 
   case 52:
 
     {
-           (yyval.Number) = (yyvsp[(1) - (1)].Number);
+           (yyval.Number) = (yyvsp[0].Number);
            yyRelPointer = &yyRelDay;
-       ;}
+       }
+
     break;
 
   case 53:
 
     {
-           (yyval.Number) = (yyvsp[(1) - (1)].Number);
+           (yyval.Number) = (yyvsp[0].Number);
            yyRelPointer = &yyRelMonth;
-       ;}
+       }
+
     break;
 
   case 54:
 
     {
            if (yyHaveTime && yyHaveDate && !yyHaveRel) {
-               yyYear = (yyvsp[(1) - (1)].Number);
+               yyYear = (yyvsp[0].Number);
            } else {
                yyHaveTime++;
                if (yyDigitCount <= 2) {
-                   yyHour = (yyvsp[(1) - (1)].Number);
+                   yyHour = (yyvsp[0].Number);
                    yyMinutes = 0;
                } else {
-                   yyHour = (yyvsp[(1) - (1)].Number) / 100;
-                   yyMinutes = (yyvsp[(1) - (1)].Number) % 100;
+                   yyHour = (yyvsp[0].Number) / 100;
+                   yyMinutes = (yyvsp[0].Number) % 100;
                }
                yySeconds = 0;
                yyMeridian = MER24;
            }
-       ;}
+       }
+
     break;
 
   case 55:
 
     {
            (yyval.Meridian) = MER24;
-       ;}
+       }
+
     break;
 
   case 56:
 
     {
-           (yyval.Meridian) = (yyvsp[(1) - (1)].Meridian);
-       ;}
+           (yyval.Meridian) = (yyvsp[0].Meridian);
+       }
+
     break;
 
 
-/* Line 1267 of yacc.c.  */
 
       default: break;
     }
+  /* User semantic actions sometimes alter yychar, and that requires
+     that yytoken be updated with the new translation.  We take the
+     approach of translating immediately before every use of yytoken.
+     One alternative is translating here after every semantic action,
+     but that translation would be missed if the semantic action invokes
+     YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
+     if it invokes YYBACKUP.  In the case of YYABORT or YYACCEPT, an
+     incorrect destructor might then be invoked immediately.  In the
+     case of YYERROR or YYBACKUP, subsequent parser actions might lead
+     to an incorrect destructor call or verbose syntax error message
+     before the lookahead is translated.  */
   YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
 
   YYPOPSTACK (yylen);
@@ -2075,7 +2073,7 @@ yyreduce:
   *++yyvsp = yyval;
   *++yylsp = yyloc;
 
-  /* Now `shift' the result of the reduction.  Determine what state
+  /* Now 'shift' the result of the reduction.  Determine what state
      that goes to, based on the state we popped back to and the rule
      number reduced by.  */
 
@@ -2090,10 +2088,14 @@ yyreduce:
   goto yynewstate;
 
 
-/*------------------------------------.
-| yyerrlab -- here on detecting error |
-`------------------------------------*/
+/*--------------------------------------.
+| yyerrlab -- here on detecting error |
+`--------------------------------------*/
 yyerrlab:
+  /* Make sure we have latest lookahead translation.  See comments at
+     user semantic actions for why this is necessary.  */
+  yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
+
   /* If not already recovering from an error, report this error.  */
   if (!yyerrstatus)
     {
@@ -2101,62 +2103,61 @@ yyerrlab:
 #if ! YYERROR_VERBOSE
       yyerror (&yylloc, info, YY_("syntax error"));
 #else
+# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
+                                        yyssp, yytoken)
       {
-       YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
-       if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
-         {
-           YYSIZE_T yyalloc = 2 * yysize;
-           if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
-             yyalloc = YYSTACK_ALLOC_MAXIMUM;
-           if (yymsg != yymsgbuf)
-             YYSTACK_FREE (yymsg);
-           yymsg = (char *) YYSTACK_ALLOC (yyalloc);
-           if (yymsg)
-             yymsg_alloc = yyalloc;
-           else
-             {
-               yymsg = yymsgbuf;
-               yymsg_alloc = sizeof yymsgbuf;
-             }
-         }
-
-       if (0 < yysize && yysize <= yymsg_alloc)
-         {
-           (void) yysyntax_error (yymsg, yystate, yychar);
-           yyerror (&yylloc, info, yymsg);
-         }
-       else
-         {
-           yyerror (&yylloc, info, YY_("syntax error"));
-           if (yysize != 0)
-             goto yyexhaustedlab;
-         }
+        char const *yymsgp = YY_("syntax error");
+        int yysyntax_error_status;
+        yysyntax_error_status = YYSYNTAX_ERROR;
+        if (yysyntax_error_status == 0)
+          yymsgp = yymsg;
+        else if (yysyntax_error_status == 1)
+          {
+            if (yymsg != yymsgbuf)
+              YYSTACK_FREE (yymsg);
+            yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
+            if (!yymsg)
+              {
+                yymsg = yymsgbuf;
+                yymsg_alloc = sizeof yymsgbuf;
+                yysyntax_error_status = 2;
+              }
+            else
+              {
+                yysyntax_error_status = YYSYNTAX_ERROR;
+                yymsgp = yymsg;
+              }
+          }
+        yyerror (&yylloc, info, yymsgp);
+        if (yysyntax_error_status == 2)
+          goto yyexhaustedlab;
       }
+# undef YYSYNTAX_ERROR
 #endif
     }
 
-  yyerror_range[0] = yylloc;
+  yyerror_range[1] = yylloc;
 
   if (yyerrstatus == 3)
     {
-      /* If just tried and failed to reuse look-ahead token after an
-        error, discard it.  */
+      /* If just tried and failed to reuse lookahead token after an
+         error, discard it.  */
 
       if (yychar <= YYEOF)
-       {
-         /* Return failure if at end of input.  */
-         if (yychar == YYEOF)
-           YYABORT;
-       }
+        {
+          /* Return failure if at end of input.  */
+          if (yychar == YYEOF)
+            YYABORT;
+        }
       else
-       {
-         yydestruct ("Error: discarding",
-                     yytoken, &yylval, &yylloc, info);
-         yychar = YYEMPTY;
-       }
+        {
+          yydestruct ("Error: discarding",
+                      yytoken, &yylval, &yylloc, info);
+          yychar = YYEMPTY;
+        }
     }
 
-  /* Else will try to reuse look-ahead token after shifting the error
+  /* Else will try to reuse lookahead token after shifting the error
      token.  */
   goto yyerrlab1;
 
@@ -2172,8 +2173,7 @@ yyerrorlab:
   if (/*CONSTCOND*/ 0)
      goto yyerrorlab;
 
-  yyerror_range[0] = yylsp[1-yylen];
-  /* Do not reclaim the symbols of the rule which action triggered
+  /* Do not reclaim the symbols of the rule whose action triggered
      this YYERROR.  */
   YYPOPSTACK (yylen);
   yylen = 0;
@@ -2186,43 +2186,42 @@ yyerrorlab:
 | yyerrlab1 -- common code for both syntax error and YYERROR.  |
 `-------------------------------------------------------------*/
 yyerrlab1:
-  yyerrstatus = 3;     /* Each real token shifted decrements this.  */
+  yyerrstatus = 3;      /* Each real token shifted decrements this.  */
 
   for (;;)
     {
       yyn = yypact[yystate];
-      if (yyn != YYPACT_NINF)
-       {
-         yyn += YYTERROR;
-         if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
-           {
-             yyn = yytable[yyn];
-             if (0 < yyn)
-               break;
-           }
-       }
+      if (!yypact_value_is_default (yyn))
+        {
+          yyn += YYTERROR;
+          if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+            {
+              yyn = yytable[yyn];
+              if (0 < yyn)
+                break;
+            }
+        }
 
       /* Pop the current state because it cannot handle the error token.  */
       if (yyssp == yyss)
-       YYABORT;
+        YYABORT;
 
-      yyerror_range[0] = *yylsp;
+      yyerror_range[1] = *yylsp;
       yydestruct ("Error: popping",
-                 yystos[yystate], yyvsp, yylsp, info);
+                  yystos[yystate], yyvsp, yylsp, info);
       YYPOPSTACK (1);
       yystate = *yyssp;
       YY_STACK_PRINT (yyss, yyssp);
     }
 
-  if (yyn == YYFINAL)
-    YYACCEPT;
-
+  YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
   *++yyvsp = yylval;
+  YY_IGNORE_MAYBE_UNINITIALIZED_END
 
-  yyerror_range[1] = yylloc;
+  yyerror_range[2] = yylloc;
   /* Using YYLLOC is tempting, but would change the location of
-     the look-ahead.  YYLOC is available though.  */
-  YYLLOC_DEFAULT (yyloc, (yyerror_range - 1), 2);
+     the lookahead.  YYLOC is available though.  */
+  YYLLOC_DEFAULT (yyloc, yyerror_range, 2);
   *++yylsp = yyloc;
 
   /* Shift the error token.  */
@@ -2246,7 +2245,7 @@ yyabortlab:
   yyresult = 1;
   goto yyreturn;
 
-#ifndef yyoverflow
+#if !defined yyoverflow || YYERROR_VERBOSE
 /*-------------------------------------------------.
 | yyexhaustedlab -- memory exhaustion comes here.  |
 `-------------------------------------------------*/
@@ -2257,17 +2256,22 @@ yyexhaustedlab:
 #endif
 
 yyreturn:
-  if (yychar != YYEOF && yychar != YYEMPTY)
-     yydestruct ("Cleanup: discarding lookahead",
-                yytoken, &yylval, &yylloc, info);
-  /* Do not reclaim the symbols of the rule which action triggered
+  if (yychar != YYEMPTY)
+    {
+      /* Make sure we have latest lookahead translation.  See comments at
+         user semantic actions for why this is necessary.  */
+      yytoken = YYTRANSLATE (yychar);
+      yydestruct ("Cleanup: discarding lookahead",
+                  yytoken, &yylval, &yylloc, info);
+    }
+  /* Do not reclaim the symbols of the rule whose action triggered
      this YYABORT or YYACCEPT.  */
   YYPOPSTACK (yylen);
   YY_STACK_PRINT (yyss, yyssp);
   while (yyssp != yyss)
     {
       yydestruct ("Cleanup: popping",
-                 yystos[*yyssp], yyvsp, yylsp, info);
+                  yystos[*yyssp], yyvsp, yylsp, info);
       YYPOPSTACK (1);
     }
 #ifndef yyoverflow
@@ -2278,13 +2282,10 @@ yyreturn:
   if (yymsg != yymsgbuf)
     YYSTACK_FREE (yymsg);
 #endif
-  /* Make sure YYID is used.  */
-  return YYID (yyresult);
+  return yyresult;
 }
 
 
-
-
 /*
  * Month and day table.
  */
@@ -2458,31 +2459,31 @@ static const TABLE TimezoneTable[] = {
  */
 
 static const TABLE MilitaryTable[] = {
-    { "a",     tZONE,  -HOUR( 1) },
-    { "b",     tZONE,  -HOUR( 2) },
-    { "c",     tZONE,  -HOUR( 3) },
-    { "d",     tZONE,  -HOUR( 4) },
-    { "e",     tZONE,  -HOUR( 5) },
-    { "f",     tZONE,  -HOUR( 6) },
-    { "g",     tZONE,  -HOUR( 7) },
-    { "h",     tZONE,  -HOUR( 8) },
-    { "i",     tZONE,  -HOUR( 9) },
-    { "k",     tZONE,  -HOUR(10) },
-    { "l",     tZONE,  -HOUR(11) },
-    { "m",     tZONE,  -HOUR(12) },
-    { "n",     tZONE,  HOUR(  1) },
-    { "o",     tZONE,  HOUR(  2) },
-    { "p",     tZONE,  HOUR(  3) },
-    { "q",     tZONE,  HOUR(  4) },
-    { "r",     tZONE,  HOUR(  5) },
-    { "s",     tZONE,  HOUR(  6) },
-    { "t",     tZONE,  HOUR(  7) },
-    { "u",     tZONE,  HOUR(  8) },
-    { "v",     tZONE,  HOUR(  9) },
-    { "w",     tZONE,  HOUR( 10) },
-    { "x",     tZONE,  HOUR( 11) },
-    { "y",     tZONE,  HOUR( 12) },
-    { "z",     tZONE,  HOUR( 0) },
+    { "a",     tZONE,  -HOUR( 1) + HOUR(100) },
+    { "b",     tZONE,  -HOUR( 2) + HOUR(100) },
+    { "c",     tZONE,  -HOUR( 3) + HOUR(100) },
+    { "d",     tZONE,  -HOUR( 4) + HOUR(100) },
+    { "e",     tZONE,  -HOUR( 5) + HOUR(100) },
+    { "f",     tZONE,  -HOUR( 6) + HOUR(100) },
+    { "g",     tZONE,  -HOUR( 7) + HOUR(100) },
+    { "h",     tZONE,  -HOUR( 8) + HOUR(100) },
+    { "i",     tZONE,  -HOUR( 9) + HOUR(100) },
+    { "k",     tZONE,  -HOUR(10) + HOUR(100) },
+    { "l",     tZONE,  -HOUR(11) + HOUR(100) },
+    { "m",     tZONE,  -HOUR(12) + HOUR(100) },
+    { "n",     tZONE,  HOUR(  1) + HOUR(100) },
+    { "o",     tZONE,  HOUR(  2) + HOUR(100) },
+    { "p",     tZONE,  HOUR(  3) + HOUR(100) },
+    { "q",     tZONE,  HOUR(  4) + HOUR(100) },
+    { "r",     tZONE,  HOUR(  5) + HOUR(100) },
+    { "s",     tZONE,  HOUR(  6) + HOUR(100) },
+    { "t",     tZONE,  HOUR(  7) + HOUR(100) },
+    { "u",     tZONE,  HOUR(  8) + HOUR(100) },
+    { "v",     tZONE,  HOUR(  9) + HOUR(100) },
+    { "w",     tZONE,  HOUR( 10) + HOUR(100) },
+    { "x",     tZONE,  HOUR( 11) + HOUR(100) },
+    { "y",     tZONE,  HOUR( 12) + HOUR(100) },
+    { "z",     tZONE,  HOUR( 0)  + HOUR(100) },
     { NULL, 0, 0 }
 };
 
@@ -2500,12 +2501,12 @@ TclDateerror(
     Tcl_AppendToObj(infoPtr->messages, infoPtr->separatrix, -1);
     Tcl_AppendToObj(infoPtr->messages, s, -1);
     Tcl_AppendToObj(infoPtr->messages, " (characters ", -1);
-    t = Tcl_NewIntObj(location->first_column);
+    TclNewIntObj(t, location->first_column);
     Tcl_IncrRefCount(t);
     Tcl_AppendObjToObj(infoPtr->messages, t);
     Tcl_DecrRefCount(t);
     Tcl_AppendToObj(infoPtr->messages, "-", -1);
-    t = Tcl_NewIntObj(location->last_column);
+    TclNewIntObj(t, location->last_column);
     Tcl_IncrRefCount(t);
     Tcl_AppendObjToObj(infoPtr->messages, t);
     Tcl_DecrRefCount(t);
@@ -2548,9 +2549,9 @@ LookupWord(
     YYSTYPE* yylvalPtr,
     char *buff)
 {
-    register char *p;
-    register char *q;
-    register const TABLE *tp;
+    char *p;
+    char *q;
+    const TABLE *tp;
     int i, abbrev;
 
     /*
@@ -2673,14 +2674,14 @@ TclDatelex(
     YYLTYPE* location,
     DateInfo *info)
 {
-    register char c;
-    register char *p;
+    char c;
+    char *p;
     char buff[20];
     int Count;
 
     location->first_column = yyInput - info->dateStart;
     for ( ; ; ) {
-       while (TclIsSpaceProc(*yyInput)) {
+       while (TclIsSpaceProcM(*yyInput)) {
            yyInput++;
        }
 
@@ -2743,7 +2744,7 @@ TclDatelex(
 
 int
 TclClockOldscanObjCmd(
-    ClientData clientData,     /* Unused */
+    void *dummy,               /* Unused */
     Tcl_Interp *interp,                /* Tcl interpreter */
     int objc,                  /* Count of paraneters */
     Tcl_Obj *const *objv)      /* Parameters */
@@ -2753,6 +2754,7 @@ TclClockOldscanObjCmd(
     DateInfo dateInfo;
     DateInfo* info = &dateInfo;
     int status;
+    (void)dummy;
 
     if (objc != 5) {
        Tcl_WrongNumArgs(interp, 1, objv,
@@ -2786,7 +2788,7 @@ TclClockOldscanObjCmd(
     yyHaveRel = 0;
     yyRelMonth = 0; yyRelDay = 0; yyRelSeconds = 0; yyRelPointer = NULL;
 
-    dateInfo.messages = Tcl_NewObj();
+    TclNewObj(dateInfo.messages);
     dateInfo.separatrix = "";
     Tcl_IncrRefCount(dateInfo.messages);
 
@@ -2843,8 +2845,8 @@ TclClockOldscanObjCmd(
        return TCL_ERROR;
     }
 
-    result = Tcl_NewObj();
-    resultElement = Tcl_NewObj();
+    TclNewObj(result);
+    TclNewObj(resultElement);
     if (yyHaveDate) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyYear));
@@ -2857,12 +2859,12 @@ TclClockOldscanObjCmd(
 
     if (yyHaveTime) {
        Tcl_ListObjAppendElement(interp, result, Tcl_NewIntObj((int)
-               ToSeconds(yyHour, yyMinutes, yySeconds, yyMeridian)));
+               ToSeconds(yyHour, yyMinutes, yySeconds, (MERIDIAN)yyMeridian)));
     } else {
        Tcl_ListObjAppendElement(interp, result, Tcl_NewObj());
     }
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveZone) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) -yyTimezone));
@@ -2871,7 +2873,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveRel) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyRelMonth));
@@ -2882,7 +2884,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveDay && !yyHaveDate) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyDayOrdinal));
@@ -2891,7 +2893,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveOrdinalMonth) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyMonthOrdinal));
@@ -2911,4 +2913,3 @@ TclClockOldscanObjCmd(
  * fill-column: 78
  * End:
  */
-
index 719cdf3..0f18dd4 100644 (file)
@@ -279,13 +279,13 @@ EXTERN int                Tcl_ConvertElement(const char *src, char *dst,
 EXTERN int             Tcl_ConvertCountedElement(const char *src,
                                int length, char *dst, int flags);
 /* 86 */
-EXTERN int             Tcl_CreateAlias(Tcl_Interp *slave,
-                               const char *slaveCmd, Tcl_Interp *target,
+EXTERN int             Tcl_CreateAlias(Tcl_Interp *childInterp,
+                               const char *childCmd, Tcl_Interp *target,
                                const char *targetCmd, int argc,
                                CONST84 char *const *argv);
 /* 87 */
-EXTERN int             Tcl_CreateAliasObj(Tcl_Interp *slave,
-                               const char *slaveCmd, Tcl_Interp *target,
+EXTERN int             Tcl_CreateAliasObj(Tcl_Interp *childInterp,
+                               const char *childCmd, Tcl_Interp *target,
                                const char *targetCmd, int objc,
                                Tcl_Obj *const objv[]);
 /* 88 */
@@ -323,8 +323,8 @@ EXTERN Tcl_Command  Tcl_CreateObjCommand(Tcl_Interp *interp,
                                ClientData clientData,
                                Tcl_CmdDeleteProc *deleteProc);
 /* 97 */
-EXTERN Tcl_Interp *    Tcl_CreateSlave(Tcl_Interp *interp,
-                               const char *slaveName, int isSafe);
+EXTERN Tcl_Interp *    Tcl_CreateSlave(Tcl_Interp *interp, const char *name,
+                               int isSafe);
 /* 98 */
 EXTERN Tcl_TimerToken  Tcl_CreateTimerHandler(int milliseconds,
                                Tcl_TimerProc *proc, ClientData clientData);
@@ -458,13 +458,13 @@ EXTERN int                Tcl_Flush(Tcl_Channel chan);
 EXTERN void            Tcl_FreeResult(Tcl_Interp *interp);
 /* 148 */
 EXTERN int             Tcl_GetAlias(Tcl_Interp *interp,
-                               const char *slaveCmd,
+                               const char *childCmd,
                                Tcl_Interp **targetInterpPtr,
                                CONST84 char **targetCmdPtr, int *argcPtr,
                                CONST84 char ***argvPtr);
 /* 149 */
 EXTERN int             Tcl_GetAliasObj(Tcl_Interp *interp,
-                               const char *slaveCmd,
+                               const char *childCmd,
                                Tcl_Interp **targetInterpPtr,
                                CONST84 char **targetCmdPtr, int *objcPtr,
                                Tcl_Obj ***objv);
@@ -503,8 +503,8 @@ EXTERN int          Tcl_GetErrno(void);
 /* 162 */
 EXTERN CONST84_RETURN char * Tcl_GetHostName(void);
 /* 163 */
-EXTERN int             Tcl_GetInterpPath(Tcl_Interp *askInterp,
-                               Tcl_Interp *slaveInterp);
+EXTERN int             Tcl_GetInterpPath(Tcl_Interp *interp,
+                               Tcl_Interp *childInterp);
 /* 164 */
 EXTERN Tcl_Interp *    Tcl_GetMaster(Tcl_Interp *interp);
 /* 165 */
@@ -532,8 +532,7 @@ EXTERN int          Tcl_GetsObj(Tcl_Channel chan, Tcl_Obj *objPtr);
 /* 171 */
 EXTERN int             Tcl_GetServiceMode(void);
 /* 172 */
-EXTERN Tcl_Interp *    Tcl_GetSlave(Tcl_Interp *interp,
-                               const char *slaveName);
+EXTERN Tcl_Interp *    Tcl_GetSlave(Tcl_Interp *interp, const char *name);
 /* 173 */
 EXTERN Tcl_Channel     Tcl_GetStdChannel(int type);
 /* 174 */
@@ -1749,7 +1748,7 @@ EXTERN int                Tcl_GetErrorLine(Tcl_Interp *interp);
 EXTERN void            Tcl_SetErrorLine(Tcl_Interp *interp, int lineNum);
 /* 607 */
 EXTERN void            Tcl_TransferResult(Tcl_Interp *sourceInterp,
-                               int result, Tcl_Interp *targetInterp);
+                               int code, Tcl_Interp *targetInterp);
 /* 608 */
 EXTERN int             Tcl_InterpActive(Tcl_Interp *interp);
 /* 609 */
@@ -1833,7 +1832,8 @@ EXTERN void               Tcl_ZlibStreamSetCompressionDictionary(
 /* Slot 645 is reserved */
 /* Slot 646 is reserved */
 /* Slot 647 is reserved */
-/* 648 */
+/* Slot 648 is reserved */
+/* 649 */
 EXTERN void            TclUnusedStubEntry(void);
 
 typedef struct {
@@ -1948,8 +1948,8 @@ typedef struct TclStubs {
     char * (*tcl_Concat) (int argc, CONST84 char *const *argv); /* 83 */
     int (*tcl_ConvertElement) (const char *src, char *dst, int flags); /* 84 */
     int (*tcl_ConvertCountedElement) (const char *src, int length, char *dst, int flags); /* 85 */
-    int (*tcl_CreateAlias) (Tcl_Interp *slave, const char *slaveCmd, Tcl_Interp *target, const char *targetCmd, int argc, CONST84 char *const *argv); /* 86 */
-    int (*tcl_CreateAliasObj) (Tcl_Interp *slave, const char *slaveCmd, Tcl_Interp *target, const char *targetCmd, int objc, Tcl_Obj *const objv[]); /* 87 */
+    int (*tcl_CreateAlias) (Tcl_Interp *childInterp, const char *childCmd, Tcl_Interp *target, const char *targetCmd, int argc, CONST84 char *const *argv); /* 86 */
+    int (*tcl_CreateAliasObj) (Tcl_Interp *childInterp, const char *childCmd, Tcl_Interp *target, const char *targetCmd, int objc, Tcl_Obj *const objv[]); /* 87 */
     Tcl_Channel (*tcl_CreateChannel) (const Tcl_ChannelType *typePtr, const char *chanName, ClientData instanceData, int mask); /* 88 */
     void (*tcl_CreateChannelHandler) (Tcl_Channel chan, int mask, Tcl_ChannelProc *proc, ClientData clientData); /* 89 */
     void (*tcl_CreateCloseHandler) (Tcl_Channel chan, Tcl_CloseProc *proc, ClientData clientData); /* 90 */
@@ -1959,7 +1959,7 @@ typedef struct TclStubs {
     Tcl_Interp * (*tcl_CreateInterp) (void); /* 94 */
     void (*tcl_CreateMathFunc) (Tcl_Interp *interp, const char *name, int numArgs, Tcl_ValueType *argTypes, Tcl_MathProc *proc, ClientData clientData); /* 95 */
     Tcl_Command (*tcl_CreateObjCommand) (Tcl_Interp *interp, const char *cmdName, Tcl_ObjCmdProc *proc, ClientData clientData, Tcl_CmdDeleteProc *deleteProc); /* 96 */
-    Tcl_Interp * (*tcl_CreateSlave) (Tcl_Interp *interp, const char *slaveName, int isSafe); /* 97 */
+    Tcl_Interp * (*tcl_CreateSlave) (Tcl_Interp *interp, const char *name, int isSafe); /* 97 */
     Tcl_TimerToken (*tcl_CreateTimerHandler) (int milliseconds, Tcl_TimerProc *proc, ClientData clientData); /* 98 */
     Tcl_Trace (*tcl_CreateTrace) (Tcl_Interp *interp, int level, Tcl_CmdTraceProc *proc, ClientData clientData); /* 99 */
     void (*tcl_DeleteAssocData) (Tcl_Interp *interp, const char *name); /* 100 */
@@ -2010,8 +2010,8 @@ typedef struct TclStubs {
     Tcl_HashEntry * (*tcl_FirstHashEntry) (Tcl_HashTable *tablePtr, Tcl_HashSearch *searchPtr); /* 145 */
     int (*tcl_Flush) (Tcl_Channel chan); /* 146 */
     void (*tcl_FreeResult) (Tcl_Interp *interp); /* 147 */
-    int (*tcl_GetAlias) (Tcl_Interp *interp, const char *slaveCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *argcPtr, CONST84 char ***argvPtr); /* 148 */
-    int (*tcl_GetAliasObj) (Tcl_Interp *interp, const char *slaveCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *objcPtr, Tcl_Obj ***objv); /* 149 */
+    int (*tcl_GetAlias) (Tcl_Interp *interp, const char *childCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *argcPtr, CONST84 char ***argvPtr); /* 148 */
+    int (*tcl_GetAliasObj) (Tcl_Interp *interp, const char *childCmd, Tcl_Interp **targetInterpPtr, CONST84 char **targetCmdPtr, int *objcPtr, Tcl_Obj ***objv); /* 149 */
     ClientData (*tcl_GetAssocData) (Tcl_Interp *interp, const char *name, Tcl_InterpDeleteProc **procPtr); /* 150 */
     Tcl_Channel (*tcl_GetChannel) (Tcl_Interp *interp, const char *chanName, int *modePtr); /* 151 */
     int (*tcl_GetChannelBufferSize) (Tcl_Channel chan); /* 152 */
@@ -2025,7 +2025,7 @@ typedef struct TclStubs {
     CONST84_RETURN char * (*tcl_GetCommandName) (Tcl_Interp *interp, Tcl_Command command); /* 160 */
     int (*tcl_GetErrno) (void); /* 161 */
     CONST84_RETURN char * (*tcl_GetHostName) (void); /* 162 */
-    int (*tcl_GetInterpPath) (Tcl_Interp *askInterp, Tcl_Interp *slaveInterp); /* 163 */
+    int (*tcl_GetInterpPath) (Tcl_Interp *interp, Tcl_Interp *childInterp); /* 163 */
     Tcl_Interp * (*tcl_GetMaster) (Tcl_Interp *interp); /* 164 */
     const char * (*tcl_GetNameOfExecutable) (void); /* 165 */
     Tcl_Obj * (*tcl_GetObjResult) (Tcl_Interp *interp); /* 166 */
@@ -2042,7 +2042,7 @@ typedef struct TclStubs {
     int (*tcl_Gets) (Tcl_Channel chan, Tcl_DString *dsPtr); /* 169 */
     int (*tcl_GetsObj) (Tcl_Channel chan, Tcl_Obj *objPtr); /* 170 */
     int (*tcl_GetServiceMode) (void); /* 171 */
-    Tcl_Interp * (*tcl_GetSlave) (Tcl_Interp *interp, const char *slaveName); /* 172 */
+    Tcl_Interp * (*tcl_GetSlave) (Tcl_Interp *interp, const char *name); /* 172 */
     Tcl_Channel (*tcl_GetStdChannel) (int type); /* 173 */
     CONST84_RETURN char * (*tcl_GetStringResult) (Tcl_Interp *interp); /* 174 */
     CONST84_RETURN char * (*tcl_GetVar) (Tcl_Interp *interp, const char *varName, int flags); /* 175 */
@@ -2477,7 +2477,7 @@ typedef struct TclStubs {
     int (*tcl_ParseArgsObjv) (Tcl_Interp *interp, const Tcl_ArgvInfo *argTable, int *objcPtr, Tcl_Obj *const *objv, Tcl_Obj ***remObjv); /* 604 */
     int (*tcl_GetErrorLine) (Tcl_Interp *interp); /* 605 */
     void (*tcl_SetErrorLine) (Tcl_Interp *interp, int lineNum); /* 606 */
-    void (*tcl_TransferResult) (Tcl_Interp *sourceInterp, int result, Tcl_Interp *targetInterp); /* 607 */
+    void (*tcl_TransferResult) (Tcl_Interp *sourceInterp, int code, Tcl_Interp *targetInterp); /* 607 */
     int (*tcl_InterpActive) (Tcl_Interp *interp); /* 608 */
     void (*tcl_BackgroundException) (Tcl_Interp *interp, int code); /* 609 */
     int (*tcl_ZlibDeflate) (Tcl_Interp *interp, int format, Tcl_Obj *data, int level, Tcl_Obj *gzipHeaderDictObj); /* 610 */
@@ -2518,7 +2518,8 @@ typedef struct TclStubs {
     void (*reserved645)(void);
     void (*reserved646)(void);
     void (*reserved647)(void);
-    void (*tclUnusedStubEntry) (void); /* 648 */
+    void (*reserved648)(void);
+    void (*tclUnusedStubEntry) (void); /* 649 */
 } TclStubs;
 
 extern const TclStubs *tclStubsPtr;
@@ -3828,8 +3829,9 @@ extern const TclStubs *tclStubsPtr;
 /* Slot 645 is reserved */
 /* Slot 646 is reserved */
 /* Slot 647 is reserved */
+/* Slot 648 is reserved */
 #define TclUnusedStubEntry \
-       (tclStubsPtr->tclUnusedStubEntry) /* 648 */
+       (tclStubsPtr->tclUnusedStubEntry) /* 649 */
 
 #endif /* defined(USE_TCL_STUBS) */
 
@@ -3971,5 +3973,8 @@ extern const TclStubs *tclStubsPtr;
 #undef Tcl_GlobalEvalObj
 #define Tcl_GlobalEvalObj(interp,objPtr) \
     Tcl_EvalObjEx((interp),(objPtr),TCL_EVAL_GLOBAL)
+#define Tcl_CreateChild Tcl_CreateSlave
+#define Tcl_GetChild Tcl_GetSlave
+#define Tcl_GetParent Tcl_GetMaster
 
 #endif /* _TCLDECLS */
index a42c123..becc029 100644 (file)
@@ -2142,8 +2142,9 @@ DictIncrCmd(
        if (objc == 4) {
            code = TclIncrObj(interp, valuePtr, objv[3]);
        } else {
-           Tcl_Obj *incrPtr = Tcl_NewIntObj(1);
+           Tcl_Obj *incrPtr;
 
+           TclNewIntObj(incrPtr, 1);
            Tcl_IncrRefCount(incrPtr);
            code = TclIncrObj(interp, valuePtr, incrPtr);
            TclDecrRefCount(incrPtr);
index f62c260..8236d20 100644 (file)
@@ -533,7 +533,7 @@ FormatInstruction(
 {
     Proc *procPtr = codePtr->procPtr;
     unsigned char opCode = *pc;
-    register const InstructionDesc *instDesc = &tclInstructionTable[opCode];
+    const InstructionDesc *instDesc = &tclInstructionTable[opCode];
     unsigned char *codeStart = codePtr->codeStart;
     unsigned pcOffset = pc - codeStart;
     int opnd = 0, i, j, numBytes = 1;
@@ -853,9 +853,8 @@ PrintSourceToObj(
     const char *stringPtr,     /* The string to print. */
     int maxChars)              /* Maximum number of chars to print. */
 {
-    register const char *p;
-    register int i = 0, len;
-    Tcl_UniChar ch = 0;
+    const char *p;
+    int i = 0, len;
 
     if (stringPtr == NULL) {
        Tcl_AppendToObj(appendObj, "\"\"", -1);
@@ -865,9 +864,10 @@ PrintSourceToObj(
     Tcl_AppendToObj(appendObj, "\"", -1);
     p = stringPtr;
     for (;  (*p != '\0') && (i < maxChars);  p+=len) {
+       int ucs4;
 
-       len = TclUtfToUniChar(p, &ch);
-       switch (ch) {
+       len = TclUtfToUCS4(p, &ucs4);
+       switch (ucs4) {
        case '"':
            Tcl_AppendToObj(appendObj, "\\\"", -1);
            i += 2;
@@ -893,28 +893,14 @@ PrintSourceToObj(
            i += 2;
            continue;
        default:
-#if TCL_UTF_MAX > 4
-           if (ch > 0xffff) {
-               Tcl_AppendPrintfToObj(appendObj, "\\U%08x", ch);
+           if (ucs4 > 0xFFFF) {
+               Tcl_AppendPrintfToObj(appendObj, "\\U%08x", ucs4);
                i += 10;
-           } else
-#elif TCL_UTF_MAX > 3
-           /* If len == 0, this means we have a char > 0xffff, resulting in
-            * TclUtfToUniChar producing a surrogate pair. We want to output
-            * this pair as a single Unicode character.
-            */
-           if (len == 0) {
-               int upper = ((ch & 0x3ff) + 1) << 10;
-               len = TclUtfToUniChar(p, &ch);
-               Tcl_AppendPrintfToObj(appendObj, "\\U%08x", upper + (ch & 0x3ff));
-               i += 10;
-           } else
-#endif
-           if (ch < 0x20 || ch >= 0x7f) {
-               Tcl_AppendPrintfToObj(appendObj, "\\u%04x", ch);
+           } else if (ucs4 < 0x20 || ucs4 >= 0x7F) {
+               Tcl_AppendPrintfToObj(appendObj, "\\u%04x", ucs4);
                i += 6;
            } else {
-               Tcl_AppendPrintfToObj(appendObj, "%c", ch);
+               Tcl_AppendPrintfToObj(appendObj, "%c", ucs4);
                i++;
            }
            continue;
index 9e1d262..557f241 100644 (file)
@@ -18,7 +18,7 @@ typedef size_t (LengthProc)(const char *src);
  * convert between various character sets and UTF-8.
  */
 
-typedef struct Encoding {
+typedef struct {
     char *name;                        /* Name of encoding. Malloced because (1) hash
                                 * table entry that owns this encoding may be
                                 * freed prior to this encoding being freed,
@@ -57,7 +57,7 @@ typedef struct Encoding {
  * encoding.
  */
 
-typedef struct TableEncodingData {
+typedef struct {
     int fallback;              /* Character (in this encoding) to substitute
                                 * when this encoding cannot represent a UTF-8
                                 * character. */
@@ -83,7 +83,7 @@ typedef struct TableEncodingData {
 } TableEncodingData;
 
 /*
- * The following structures is the clientData for a dynamically-loaded,
+ * Each of the following structures is the clientData for a dynamically-loaded
  * escape-driven encoding that is itself comprised of other simpler encodings.
  * An example is "iso-2022-jp", which uses escape sequences to switch between
  * ascii, jis0208, jis0212, gb2312, and ksc5601. Note that "escape-driven"
@@ -91,7 +91,7 @@ typedef struct TableEncodingData {
  * for switching character sets.
  */
 
-typedef struct EscapeSubTable {
+typedef struct {
     unsigned sequenceLen;      /* Length of following string. */
     char sequence[16];         /* Escape code that marks this encoding. */
     char name[32];             /* Name for encoding. */
@@ -100,7 +100,7 @@ typedef struct EscapeSubTable {
                                 * yet. */
 } EscapeSubTable;
 
-typedef struct EscapeEncodingData {
+typedef struct {
     int fallback;              /* Character (in this encoding) to substitute
                                 * when this encoding cannot represent a UTF-8
                                 * character. */
@@ -116,9 +116,9 @@ typedef struct EscapeEncodingData {
                                 * entry in this array is 1, otherwise it is
                                 * 0. */
     int numSubTables;          /* Length of following array. */
-    EscapeSubTable subTables[1];/* Information about each EscapeSubTable used
-                                * by this encoding type. The actual size will
-                                * be as large as necessary to hold all
+    EscapeSubTable subTables[TCLFLEXARRAY];/* Information about each EscapeSubTable used
+                                * by this encoding type. The actual size is
+                                * as large as necessary to hold all
                                 * EscapeSubTables. */
 } EscapeEncodingData;
 
@@ -156,7 +156,7 @@ static ProcessGlobalValue encodingFileMap = {
  * A list of directories making up the "library path". Historically this
  * search path has served many uses, but the only one remaining is a base for
  * the encodingSearchPath above. If the application does not explicitly set
- * the encodingSearchPath, then it will be initialized by appending /encoding
+ * the encodingSearchPath, then it is initialized by appending /encoding
  * to each directory in this "libraryPath".
  */
 
@@ -177,7 +177,7 @@ TCL_DECLARE_MUTEX(encodingMutex)
 /*
  * The following are used to hold the default and current system encodings.
  * If NULL is passed to one of the conversion routines, the current setting of
- * the system encoding will be used to perform the conversion.
+ * the system encoding is used to perform the conversion.
  */
 
 static Tcl_Encoding defaultEncoding = NULL;
@@ -195,35 +195,25 @@ static unsigned short emptyPage[256];
  * Functions used only in this module.
  */
 
-static int             BinaryProc(ClientData clientData,
-                           const char *src, int srcLen, int flags,
-                           Tcl_EncodingState *statePtr, char *dst, int dstLen,
-                           int *srcReadPtr, int *dstWrotePtr,
-                           int *dstCharsPtr);
-static void            DupEncodingIntRep(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr);
-static void            EscapeFreeProc(ClientData clientData);
-static int             EscapeFromUtfProc(ClientData clientData,
-                           const char *src, int srcLen, int flags,
-                           Tcl_EncodingState *statePtr, char *dst, int dstLen,
-                           int *srcReadPtr, int *dstWrotePtr,
-                           int *dstCharsPtr);
-static int             EscapeToUtfProc(ClientData clientData,
-                           const char *src, int srcLen, int flags,
-                           Tcl_EncodingState *statePtr, char *dst, int dstLen,
-                           int *srcReadPtr, int *dstWrotePtr,
-                           int *dstCharsPtr);
-static void            FillEncodingFileMap(void);
-static void            FreeEncoding(Tcl_Encoding encoding);
-static void            FreeEncodingIntRep(Tcl_Obj *objPtr);
-static Encoding *      GetTableEncoding(EscapeEncodingData *dataPtr,
-                           int state);
-static Tcl_Encoding    LoadEncodingFile(Tcl_Interp *interp, const char *name);
-static Tcl_Encoding    LoadTableEncoding(const char *name, int type,
-                           Tcl_Channel chan);
-static Tcl_Encoding    LoadEscapeEncoding(const char *name, Tcl_Channel chan);
-static Tcl_Channel     OpenEncodingFileChannel(Tcl_Interp *interp,
-                           const char *name);
-static void            TableFreeProc(ClientData clientData);
+static Tcl_EncodingConvertProc BinaryProc;
+static Tcl_DupInternalRepProc  DupEncodingIntRep;
+static Tcl_EncodingFreeProc    EscapeFreeProc;
+static Tcl_EncodingConvertProc EscapeFromUtfProc;
+static Tcl_EncodingConvertProc EscapeToUtfProc;
+static void                    FillEncodingFileMap(void);
+static void                    FreeEncoding(Tcl_Encoding encoding);
+static Tcl_FreeInternalRepProc FreeEncodingIntRep;
+static Encoding *              GetTableEncoding(EscapeEncodingData *dataPtr,
+                                   int state);
+static Tcl_Encoding            LoadEncodingFile(Tcl_Interp *interp,
+                                   const char *name);
+static Tcl_Encoding            LoadTableEncoding(const char *name, int type,
+                                   Tcl_Channel chan);
+static Tcl_Encoding            LoadEscapeEncoding(const char *name,
+                                   Tcl_Channel chan);
+static Tcl_Channel             OpenEncodingFileChannel(Tcl_Interp *interp,
+                                   const char *name);
+static Tcl_EncodingFreeProc    TableFreeProc;
 static int             TableFromUtfProc(ClientData clientData,
                            const char *src, int srcLen, int flags,
                            Tcl_EncodingState *statePtr, char *dst, int dstLen,
@@ -335,7 +325,7 @@ static void
 FreeEncodingIntRep(
     Tcl_Obj *objPtr)
 {
-    Tcl_FreeEncoding(objPtr->internalRep.twoPtrValue.ptr1);
+    Tcl_FreeEncoding((Tcl_Encoding)objPtr->internalRep.twoPtrValue.ptr1);
     objPtr->typePtr = NULL;
 }
 \f
@@ -429,9 +419,8 @@ TclGetLibraryPath(void)
  *     Keeps the per-thread copy of the library path current with changes to
  *     the global copy.
  *
- *     NOTE: this routine returns void, so there's no way to report the error
- *     that searchPath is not a valid list. In that case, this routine will
- *     silently do nothing.
+ *     Since the result of this routine is void, if searchPath is not a valid
+ *     list this routine silently does nothing.
  *
  *----------------------------------------------------------------------
  */
@@ -453,17 +442,16 @@ TclSetLibraryPath(
  *
  * FillEncodingFileMap --
  *
- *     Called to bring the encoding file map in sync with the current value
+ *     Called to update the encoding file map with the current value
  *     of the encoding search path.
  *
- *     Scan the directories on the encoding search path, find the *.enc
- *     files, and store the found pathnames in a map associated with the
- *     encoding name.
+ *     Finds *.end files in the directories on the encoding search path and
+ *     stores the found pathnames in a map associated with the encoding name.
  *
- *     In particular, if $dir is on the encoding search path, and the file
- *     $dir/foo.enc is found, then store a "foo" -> $dir entry in the map.
- *     Later, any need for the "foo" encoding will quickly * be able to
- *     construct the $dir/foo.enc pathname for reading the encoding data.
+ *     If $dir is on the encoding search path and the file $dir/foo.enc is
+ *     found, stores a "foo" -> $dir entry in the map.  if the "foo" encoding
+ *     is needed later, the $dir/foo.enc name can be quickly constructed in
+ *     order to read the encoding data.
  *
  * Results:
  *     None.
@@ -547,19 +535,24 @@ TclInitEncodingSubsystem(void)
     TableEncodingData *dataPtr;
     unsigned size;
     unsigned short i;
+    union {
+        char c;
+        short s;
+    } isLe;
 
     if (encodingsInitialized) {
        return;
     }
 
+    isLe.s = 1;
     Tcl_MutexLock(&encodingMutex);
     Tcl_InitHashTable(&encodingTable, TCL_STRING_KEYS);
     Tcl_MutexUnlock(&encodingMutex);
 
     /*
-     * Create a few initial encodings. Note that the UTF-8 to UTF-8
-     * translation is not a no-op, because it will turn a stream of improperly
-     * formed UTF-8 into a properly formed stream.
+     * Create a few initial encodings.  UTF-8 to UTF-8 translation is not a
+     * no-op because it turns a stream of improperly formed UTF-8 into a
+     * properly formed stream.
      */
 
     type.encodingName  = "identity";
@@ -583,7 +576,7 @@ TclInitEncodingSubsystem(void)
     type.fromUtfProc    = UtfToUnicodeProc;
     type.freeProc      = NULL;
     type.nullSize      = 2;
-    type.clientData    = NULL;
+    type.clientData    = INT2PTR(isLe.c);
     Tcl_CreateEncoding(&type);
 
     /*
@@ -593,14 +586,14 @@ TclInitEncodingSubsystem(void)
      * code to duplicate the structure of a table encoding here.
      */
 
-    dataPtr = ckalloc(sizeof(TableEncodingData));
+    dataPtr = (TableEncodingData *)ckalloc(sizeof(TableEncodingData));
     memset(dataPtr, 0, sizeof(TableEncodingData));
     dataPtr->fallback = '?';
 
     size = 256*(sizeof(unsigned short *) + sizeof(unsigned short));
-    dataPtr->toUnicode = ckalloc(size);
+    dataPtr->toUnicode = (unsigned short **)ckalloc(size);
     memset(dataPtr->toUnicode, 0, size);
-    dataPtr->fromUnicode = ckalloc(size);
+    dataPtr->fromUnicode = (unsigned short **)ckalloc(size);
     memset(dataPtr->fromUnicode, 0, size);
 
     dataPtr->toUnicode[0] = (unsigned short *) (dataPtr->toUnicode + 256);
@@ -666,7 +659,7 @@ TclFinalizeEncodingSubsystem(void)
         * cleaned up.
         */
 
-       FreeEncoding(Tcl_GetHashValue(hPtr));
+       FreeEncoding((Tcl_Encoding)Tcl_GetHashValue(hPtr));
        hPtr = Tcl_FirstHashEntry(&encodingTable, &search);
     }
 
@@ -752,11 +745,7 @@ Tcl_SetDefaultEncodingDir(
  *     interp was NULL.
  *
  * Side effects:
- *     The new encoding type is entered into a table visible to all
- *     interpreters, keyed off the encoding's name. For each call to this
- *     function, there should eventually be a call to Tcl_FreeEncoding, so
- *     that the database can be cleaned up when encodings aren't needed
- *     anymore.
+ *     LoadEncodingFile is called if necessary.
  *
  *-------------------------------------------------------------------------
  */
@@ -779,7 +768,7 @@ Tcl_GetEncoding(
 
     hPtr = Tcl_FindHashEntry(&encodingTable, name);
     if (hPtr != NULL) {
-       encodingPtr = Tcl_GetHashValue(hPtr);
+       encodingPtr = (Encoding *)Tcl_GetHashValue(hPtr);
        encodingPtr->refCount++;
        Tcl_MutexUnlock(&encodingMutex);
        return (Tcl_Encoding) encodingPtr;
@@ -794,15 +783,15 @@ Tcl_GetEncoding(
  *
  * Tcl_FreeEncoding --
  *
- *     This function is called to release an encoding allocated by
- *     Tcl_CreateEncoding() or Tcl_GetEncoding().
+ *     Releases an encoding allocated by Tcl_CreateEncoding() or
+ *     Tcl_GetEncoding().
  *
  * Results:
  *     None.
  *
  * Side effects:
  *     The reference count associated with the encoding is decremented and
- *     the encoding may be deleted if nothing is using it anymore.
+ *     the encoding is deleted if nothing is using it anymore.
  *
  *---------------------------------------------------------------------------
  */
@@ -821,13 +810,14 @@ Tcl_FreeEncoding(
  *
  * FreeEncoding --
  *
- *     This function is called to release an encoding by functions that
- *     already have the encodingMutex.
+ *     Decrements the reference count of an encoding.  The caller must hold
+ *     encodingMutes.
  *
  * Results:
  *     None.
  *
  * Side effects:
+ *     Releases the resource for an encoding if it is now unused.
  *     The reference count associated with the encoding is decremented and
  *     the encoding may be deleted if nothing is using it anymore.
  *
@@ -846,15 +836,16 @@ FreeEncoding(
     if (encodingPtr->refCount<=0) {
        Tcl_Panic("FreeEncoding: refcount problem !!!");
     }
-    encodingPtr->refCount--;
-    if (encodingPtr->refCount == 0) {
+    if (encodingPtr->refCount-- <= 1) {
        if (encodingPtr->freeProc != NULL) {
            encodingPtr->freeProc(encodingPtr->clientData);
        }
        if (encodingPtr->hPtr != NULL) {
            Tcl_DeleteHashEntry(encodingPtr->hPtr);
        }
-       ckfree(encodingPtr->name);
+       if (encodingPtr->name) {
+           ckfree(encodingPtr->name);
+       }
        ckfree(encodingPtr);
     }
 }
@@ -925,7 +916,7 @@ Tcl_GetEncodingNames(
     Tcl_MutexLock(&encodingMutex);
     for (hPtr = Tcl_FirstHashEntry(&encodingTable, &search); hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&search)) {
-       Encoding *encodingPtr = Tcl_GetHashValue(hPtr);
+       Encoding *encodingPtr = (Encoding *)Tcl_GetHashValue(hPtr);
 
        Tcl_CreateHashEntry(&table,
                Tcl_NewStringObj(encodingPtr->name, -1), &dummy);
@@ -1017,23 +1008,22 @@ Tcl_SetSystemEncoding(
  *
  * Tcl_CreateEncoding --
  *
- *     This function is called to define a new encoding and the functions
- *     that are used to convert between the specified encoding and Unicode.
+ *     Defines a new encoding, along with the functions that are used to
+ *     convert to and from Unicode.
  *
  * Results:
  *     Returns a token that represents the encoding. If an encoding with the
  *     same name already existed, the old encoding token remains valid and
- *     continues to behave as it used to, and will eventually be garbage
- *     collected when the last reference to it goes away. Any subsequent
- *     calls to Tcl_GetEncoding with the specified name will retrieve the
- *     most recent encoding token.
+ *     continues to behave as it used to, and is eventually garbage collected
+ *     when the last reference to it goes away. Any subsequent calls to
+ *     Tcl_GetEncoding with the specified name retrieve the most recent
+ *     encoding token.
  *
  * Side effects:
- *     The new encoding type is entered into a table visible to all
- *     interpreters, keyed off the encoding's name. For each call to this
- *     function, there should eventually be a call to Tcl_FreeEncoding, so
- *     that the database can be cleaned up when encodings aren't needed
- *     anymore.
+ *     A new record having the name of the encoding is entered into a table of
+ *     encodings visible to all interpreters.  For each call to this function,
+ *     there should eventually be a call to Tcl_FreeEncoding, which cleans
+ *     deletes the record in the table when an encoding is no longer needed.
  *
  *---------------------------------------------------------------------------
  */
@@ -1056,13 +1046,13 @@ Tcl_CreateEncoding(
         * reference goes away.
         */
 
-       encodingPtr = Tcl_GetHashValue(hPtr);
+       encodingPtr = (Encoding *)Tcl_GetHashValue(hPtr);
        encodingPtr->hPtr = NULL;
     }
 
-    name = ckalloc(strlen(typePtr->encodingName) + 1);
+    name = (char *)ckalloc(strlen(typePtr->encodingName) + 1);
 
-    encodingPtr = ckalloc(sizeof(Encoding));
+    encodingPtr = (Encoding *)ckalloc(sizeof(Encoding));
     encodingPtr->name          = strcpy(name, typePtr->encodingName);
     encodingPtr->toUtfProc     = typePtr->toUtfProc;
     encodingPtr->fromUtfProc   = typePtr->fromUtfProc;
@@ -1278,10 +1268,9 @@ Tcl_ExternalToUtf(
  *
  * Tcl_UtfToExternalDString --
  *
- *     Convert a source buffer from UTF-8 into the specified encoding. If any
+ *     Convert a source buffer from UTF-8 to the specified encoding. If any
  *     of the bytes in the source buffer are invalid or cannot be represented
- *     in the target encoding, a default fallback character will be
- *     substituted.
+ *     in the target encoding, a default fallback character is substituted.
  *
  * Results:
  *     The converted bytes are stored in the DString, which is then NULL
@@ -1592,13 +1581,13 @@ OpenEncodingFileChannel(
  *     the data.
  *
  * Results:
- *     The return value is the newly loaded Encoding, or NULL if the file
- *     didn't exist of was in the incorrect format. If NULL was returned, an
- *     error message is left in interp's result object, unless interp was
- *     NULL.
+ *     The return value is the newly loaded Tcl_Encoding or NULL if the file
+ *     didn't exist or could not be processed. If NULL is returned and interp
+ *     is not NULL, an error message is left in interp's result object.
  *
  * Side effects:
- *     File read from disk.
+ *     A corresponding encoding file might be read from persistent storage, in
+ *     which case LoadTableEncoding is called.
  *
  *---------------------------------------------------------------------------
  */
@@ -1606,8 +1595,8 @@ OpenEncodingFileChannel(
 static Tcl_Encoding
 LoadEncodingFile(
     Tcl_Interp *interp,                /* Interp for error reporting, if not NULL. */
-    const char *name)          /* The name of the encoding file on disk and
-                                * also the name for new encoding. */
+    const char *name)          /* The name of both the encoding file
+                                * and the new encoding. */
 {
     Tcl_Channel chan = NULL;
     Tcl_Encoding encoding = NULL;
@@ -1661,27 +1650,27 @@ LoadEncodingFile(
  *
  * LoadTableEncoding --
  *
- *     Helper function for LoadEncodingTable(). Loads a table to that
- *     converts between Unicode and some other encoding and creates an
- *     encoding (using a TableEncoding structure) from that information.
+ *     Helper function for LoadEncodingFile().  Creates a Tcl_EncodingType
+ *     structure along with its corresponding TableEncodingData structure, and
+ *     passes it to Tcl_Createncoding.
  *
- *     File contains binary data, but begins with a marker to indicate
- *     byte-ordering, so that same binary file can be read on either endian
- *     platforms.
+ *     The file contains binary data but begins with a marker to indicate
+ *     byte-ordering so a single binary file can be read on big or
+ *     little-endian systems.
  *
  * Results:
- *     The return value is the new encoding, or NULL if the encoding could
- *     not be created (because the file contained invalid data).
+ *     Returns the new Tcl_Encoding,  or NULL if it could could
+ *     not be created because the file contained invalid data.
  *
  * Side effects:
- *     None.
+ *     See Tcl_CreateEncoding().
  *
  *-------------------------------------------------------------------------
  */
 
 static Tcl_Encoding
 LoadTableEncoding(
-    const char *name,          /* Name for new encoding. */
+    const char *name,          /* Name of the new encoding. */
     int type,                  /* Type of encoding (ENCODING_?????). */
     Tcl_Channel chan)          /* File containing new encoding. */
 {
@@ -1741,7 +1730,7 @@ LoadTableEncoding(
 #undef PAGESIZE
 #define PAGESIZE    (256 * sizeof(unsigned short))
 
-    dataPtr = ckalloc(sizeof(TableEncodingData));
+    dataPtr = (TableEncodingData *)ckalloc(sizeof(TableEncodingData));
     memset(dataPtr, 0, sizeof(TableEncodingData));
 
     dataPtr->fallback = fallback;
@@ -1753,7 +1742,7 @@ LoadTableEncoding(
      */
 
     size = 256 * sizeof(unsigned short *) + numPages * PAGESIZE;
-    dataPtr->toUnicode = ckalloc(size);
+    dataPtr->toUnicode = (unsigned short **)ckalloc(size);
     memset(dataPtr->toUnicode, 0, size);
     pageMemPtr = (unsigned short *) (dataPtr->toUnicode + 256);
 
@@ -1772,7 +1761,7 @@ LoadTableEncoding(
        dataPtr->toUnicode[hi] = pageMemPtr;
        p += 2;
        for (lo = 0; lo < 256; lo++) {
-           if ((lo & 0x0f) == 0) {
+           if ((lo & 0x0F) == 0) {
                p++;
            }
            ch = (staticHex[UCHAR(p[0])] << 12) + (staticHex[UCHAR(p[1])] << 8)
@@ -1798,10 +1787,10 @@ LoadTableEncoding(
     }
 
     /*
-     * Invert toUnicode array to produce the fromUnicode array. Performs a
+     * Invert the toUnicode array to produce the fromUnicode array. Performs a
      * single malloc to get the memory for the array and all the pages needed
-     * by the array. While reading in the toUnicode array, we remembered what
-     * pages that would be needed for the fromUnicode array.
+     * by the array. While reading in the toUnicode array remember what
+     * pages are needed for the fromUnicode array.
      */
 
     if (symbol) {
@@ -1814,7 +1803,7 @@ LoadTableEncoding(
        }
     }
     size = 256 * sizeof(unsigned short *) + numPages * PAGESIZE;
-    dataPtr->fromUnicode = ckalloc(size);
+    dataPtr->fromUnicode = (unsigned short **)ckalloc(size);
     memset(dataPtr->fromUnicode, 0, size);
     pageMemPtr = (unsigned short *) (dataPtr->fromUnicode + 256);
 
@@ -1833,15 +1822,15 @@ LoadTableEncoding(
                    pageMemPtr += 256;
                    dataPtr->fromUnicode[ch >> 8] = page;
                }
-               page[ch & 0xff] = (unsigned short) ((hi << 8) + lo);
+               page[ch & 0xFF] = (unsigned short) ((hi << 8) + lo);
            }
        }
     }
     if (type == ENCODING_MULTIBYTE) {
        /*
         * If multibyte encodings don't have a backslash character, define
-        * one. Otherwise, on Windows, native file names won't work because
-        * the backslash in the file name will map to the unknown character
+        * one. Otherwise, on Windows, native file names don't work because
+        * the backslash in the file name maps to the unknown character
         * (question mark) when converting from UTF-8 to external encoding.
         */
 
@@ -1853,13 +1842,13 @@ LoadTableEncoding(
     }
     if (symbol) {
        /*
-        * Make a special symbol encoding that not only maps the symbol
-        * characters from their Unicode code points down into page 0, but
-        * also ensure that the characters on page 0 map to themselves. This
-        * is so that a symbol font can be used to display a simple string
-        * like "abcd" and have alpha, beta, chi, delta show up, rather than
-        * have "unknown" chars show up because strictly speaking the symbol
-        * font doesn't have glyphs for those low ASCII chars.
+        * Make a special symbol encoding that maps each symbol character from
+        * its Unicode code point down into page 0, and also ensure that each
+        * characters on page 0 maps to itself so that a symbol font can be
+        * used to display a simple string like "abcd" and have alpha, beta,
+        * chi, delta show up, rather than have "unknown" chars show up because
+        * strictly speaking the symbol font doesn't have glyphs for those low
+        * ASCII chars.
         */
 
        page = dataPtr->fromUnicode[0];
@@ -1906,7 +1895,7 @@ LoadTableEncoding(
     }
 
     /*
-     * Read lines from the encoding until EOF.
+     * Read lines until EOF.
      */
 
     for (TclDStringClear(&lineString);
@@ -1939,7 +1928,7 @@ LoadTableEncoding(
            if (from == 0) {
                continue;
            }
-           dataPtr->fromUnicode[from >> 8][from & 0xff] = to;
+           dataPtr->fromUnicode[from >> 8][from & 0xFF] = to;
        }
     }
   doneParse:
@@ -1983,7 +1972,7 @@ LoadTableEncoding(
 
 static Tcl_Encoding
 LoadEscapeEncoding(
-    const char *name,          /* Name for new encoding. */
+    const char *name,          /* Name of the new encoding. */
     Tcl_Channel chan)          /* File containing new encoding. */
 {
     int i;
@@ -2050,9 +2039,9 @@ LoadEscapeEncoding(
        Tcl_DStringFree(&lineString);
     }
 
-    size = sizeof(EscapeEncodingData) - sizeof(EscapeSubTable)
+    size = TclOffset(EscapeEncodingData, subTables)
            + Tcl_DStringLength(&escapeData);
-    dataPtr = ckalloc(size);
+    dataPtr = (EscapeEncodingData *)ckalloc(size);
     dataPtr->initLen = strlen(init);
     memcpy(dataPtr->init, init, dataPtr->initLen + 1);
     dataPtr->finalLen = strlen(final);
@@ -2158,7 +2147,7 @@ BinaryProc(
  * UtfIntToUtfExtProc --
  *
  *     Convert from UTF-8 to UTF-8. While converting null-bytes from the
- *     Tcl's internal representation (0xc0, 0x80) to the official
+ *     Tcl's internal representation (0xC0, 0x80) to the official
  *     representation (0x00). See UtfToUtfProc for details.
  *
  * Results:
@@ -2207,7 +2196,7 @@ UtfIntToUtfExtProc(
  * UtfExtToUtfIntProc --
  *
  *     Convert from UTF-8 to UTF-8 while converting null-bytes from the
- *     official representation (0x00) to Tcl's internal representation (0xc0,
+ *     official representation (0x00) to Tcl's internal representation (0xC0,
  *     0x80). See UtfToUtfProc for details.
  *
  * Results:
@@ -2338,17 +2327,19 @@ UtfToUtfProc(
        if (UCHAR(*src) < 0x80 && !(UCHAR(*src) == 0 && pureNullMode == 0)) {
            /*
             * Copy 7bit characters, but skip null-bytes when we are in input
-            * mode, so that they get converted to 0xc080.
+            * mode, so that they get converted to 0xC080.
             */
 
            *dst++ = *src++;
-       } else if (pureNullMode == 1 && UCHAR(*src) == 0xc0 &&
+           *chPtr = 0; /* reset surrogate handling */
+       } else if (pureNullMode == 1 && UCHAR(*src) == 0xC0 &&
                (src + 1 < srcEnd) && UCHAR(*(src+1)) == 0x80) {
            /*
-            * Convert 0xc080 to real nulls when we are in output mode.
+            * Convert 0xC080 to real nulls when we are in output mode.
             */
 
            *dst++ = 0;
+           *chPtr = 0; /* reset surrogate handling */
            src += 2;
        } else if (!Tcl_UtfCharComplete(src, srcEnd - src)) {
            /*
@@ -2357,27 +2348,39 @@ UtfToUtfProc(
             * incomplete char its bytes are made to represent themselves.
             */
 
-           *chPtr = (unsigned char) *src;
+           *chPtr = UCHAR(*src);
            src += 1;
            dst += Tcl_UniCharToUtf(*chPtr, dst);
        } else {
-           src += TclUtfToUniChar(src, chPtr);
-           if ((*chPtr & 0xFC00) == 0xD800) {
-               /* A high surrogate character is detected, handle especially */
-               Tcl_UniChar low = *chPtr;
-               size_t len = (src <= srcEnd-3) ? Tcl_UtfToUniChar(src, &low) : 0;
-               if ((low & 0xFC00) != 0xDC00) {
-                       *dst++ = (char) (((*chPtr >> 12) | 0xE0) & 0xEF);
-                       *dst++ = (char) (((*chPtr >> 6) | 0x80) & 0xBF);
-                       *dst++ = (char) ((*chPtr | 0x80) & 0xBF);
-                       continue;
-               } else if (pureNullMode == 1) {
+           size_t len = TclUtfToUniChar(src, chPtr);
+
+           src += len;
+           if ((*chPtr & ~0x7FF) == 0xD800) {
+               Tcl_UniChar low;
+               /* A surrogate character is detected, handle especially */
+#if TCL_UTF_MAX <= 4
+           if ((len < 3) && ((src[3 - len] & 0xC0) != 0x80)) {
+           /* It's invalid. See [ed29806ba] */
+               *chPtr = UCHAR(src[-1]);
+               dst += Tcl_UniCharToUtf(*chPtr, dst);
+               continue;
+           }
+#endif
+               low = *chPtr;
+               len = (src <= srcEnd-3) ? Tcl_UtfToUniChar(src, &low) : 0;
+               if (((low & ~0x3FF) != 0xDC00) || (*chPtr & 0x400)) {
+                   *dst++ = (char) (((*chPtr >> 12) | 0xE0) & 0xEF);
+                   *dst++ = (char) (((*chPtr >> 6) | 0x80) & 0xBF);
+                   *dst++ = (char) ((*chPtr | 0x80) & 0xBF);
+                   *chPtr = 0; /* reset surrogate handling */
+                   continue;
+               } else if ((TCL_UTF_MAX > 3) || (pureNullMode == 1)) {
                    int full = (((*chPtr & 0x3FF) << 10) | (low & 0x3FF)) + 0x10000;
                    *dst++ = (char) (((full >> 18) | 0xF0) & 0xF7);
                    *dst++ = (char) (((full >> 12) | 0x80) & 0xBF);
                    *dst++ = (char) (((full >> 6) | 0x80) & 0xBF);
                    *dst++ = (char) ((full | 0x80) & 0xBF);
-                       *chPtr = 0;
+                       *chPtr = 0; /* reset surrogate handling */
                    src += len;
                    continue;
                }
@@ -2397,7 +2400,7 @@ UtfToUtfProc(
  *
  * UnicodeToUtfProc --
  *
- *     Convert from Unicode to UTF-8.
+ *     Convert from UTF-16 to UTF-8.
  *
  * Results:
  *     Returns TCL_OK if conversion was successful.
@@ -2410,7 +2413,7 @@ UtfToUtfProc(
 
 static int
 UnicodeToUtfProc(
-    ClientData clientData,     /* Not used. */
+    ClientData clientData,     /* != NULL means LE, == NUL means BE */
     const char *src,           /* Source string in Unicode. */
     int srcLen,                        /* Source string length in bytes. */
     int flags,                 /* Conversion control flags. */
@@ -2438,16 +2441,22 @@ UnicodeToUtfProc(
     const char *srcStart, *srcEnd;
     const char *dstEnd, *dstStart;
     int result, numChars, charLimit = INT_MAX;
-    Tcl_UniChar ch;
+    unsigned short ch;
 
     if (flags & TCL_ENCODING_CHAR_LIMIT) {
        charLimit = *dstCharsPtr;
     }
     result = TCL_OK;
-    if ((srcLen % sizeof(Tcl_UniChar)) != 0) {
+
+    /* check alignment with utf-16 (2 == sizeof(UTF-16)) */
+    if ((srcLen % 2) != 0) {
+       result = TCL_CONVERT_MULTIBYTE;
+       srcLen--;
+    }
+    /* If last code point is a high surrogate, we cannot handle that yet */
+    if ((srcLen >= 2) && ((src[srcLen - (clientData?1:2)] & 0xFC) == 0xD8)) {
        result = TCL_CONVERT_MULTIBYTE;
-       srcLen /= sizeof(Tcl_UniChar);
-       srcLen *= sizeof(Tcl_UniChar);
+       srcLen-= 2;
     }
 
     srcStart = src;
@@ -2462,18 +2471,21 @@ UnicodeToUtfProc(
            break;
        }
 
+       if (clientData) {
+           ch = (src[1] & 0xFF) << 8 | (src[0] & 0xFF);
+       } else {
+           ch = (src[0] & 0xFF) << 8 | (src[1] & 0xFF);
+       }
        /*
         * Special case for 1-byte utf chars for speed. Make sure we work with
-        * Tcl_UniChar-size data.
+        * unsigned short-size data.
         */
-
-       ch = *(Tcl_UniChar *)src;
        if (ch && ch < 0x80) {
            *dst++ = (ch & 0xFF);
        } else {
            dst += Tcl_UniCharToUtf(ch, dst);
        }
-       src += sizeof(Tcl_UniChar);
+       src += sizeof(unsigned short);
     }
 
     *srcReadPtr = src - srcStart;
@@ -2487,7 +2499,7 @@ UnicodeToUtfProc(
  *
  * UtfToUnicodeProc --
  *
- *     Convert from UTF-8 to Unicode.
+ *     Convert from UTF-8 to UTF-16.
  *
  * Results:
  *     Returns TCL_OK if conversion was successful.
@@ -2500,8 +2512,7 @@ UnicodeToUtfProc(
 
 static int
 UtfToUnicodeProc(
-    ClientData clientData,     /* TableEncodingData that specifies
-                                * encoding. */
+    ClientData clientData,     /* != NULL means LE, == NUL means BE */
     const char *src,           /* Source string in UTF-8. */
     int srcLen,                        /* Source string length in bytes. */
     int flags,                 /* Conversion control flags. */
@@ -2560,32 +2571,37 @@ UtfToUnicodeProc(
        }
        src += TclUtfToUniChar(src, chPtr);
 
-       /*
-        * Need to handle this in a way that won't cause misalignment by
-        * casting dst to a Tcl_UniChar. [Bug 1122671]
-        */
-
-#ifdef WORDS_BIGENDIAN
+       if (clientData) {
 #if TCL_UTF_MAX > 4
-       *dst++ = (*chPtr >> 24);
-       *dst++ = ((*chPtr >> 16) & 0xFF);
-       *dst++ = ((*chPtr >> 8) & 0xFF);
-       *dst++ = (*chPtr & 0xFF);
+           if (*chPtr <= 0xFFFF) {
+               *dst++ = (*chPtr & 0xFF);
+               *dst++ = (*chPtr >> 8);
+           } else {
+               *dst++ = (((*chPtr - 0x10000) >> 10) & 0xFF);
+               *dst++ = (((*chPtr - 0x10000) >> 18) & 0x3) | 0xD8;
+               *dst++ = (*chPtr & 0xFF);
+               *dst++ = ((*chPtr & 0x3) >> 8) | 0xDC;
+           }
 #else
-       *dst++ = (*chPtr >> 8);
-       *dst++ = (*chPtr & 0xFF);
+           *dst++ = (*chPtr & 0xFF);
+           *dst++ = (*chPtr >> 8);
 #endif
-#else
+       } else {
 #if TCL_UTF_MAX > 4
-       *dst++ = (*chPtr & 0xFF);
-       *dst++ = ((*chPtr >> 8) & 0xFF);
-       *dst++ = ((*chPtr >> 16) & 0xFF);
-       *dst++ = (*chPtr >> 24);
+           if (*chPtr <= 0xFFFF) {
+               *dst++ = (*chPtr >> 8);
+               *dst++ = (*chPtr & 0xFF);
+           } else {
+               *dst++ = ((*chPtr & 0x3) >> 8) | 0xDC;
+               *dst++ = (*chPtr & 0xFF);
+               *dst++ = (((*chPtr - 0x10000) >> 18) & 0x3) | 0xD8;
+               *dst++ = (((*chPtr - 0x10000) >> 10) & 0xFF);
+           }
 #else
-       *dst++ = (*chPtr & 0xFF);
-       *dst++ = (*chPtr >> 8);
-#endif
+           *dst++ = (*chPtr >> 8);
+           *dst++ = (*chPtr & 0xFF);
 #endif
+       }
     }
     *srcReadPtr = src - srcStart;
     *dstWrotePtr = dst - dstStart;
@@ -2644,7 +2660,7 @@ TableToUtfProc(
     Tcl_UniChar ch = 0;
     const unsigned short *const *toUnicode;
     const unsigned short *pageZero;
-    TableEncodingData *dataPtr = clientData;
+    TableEncodingData *dataPtr = (TableEncodingData *)clientData;
 
     if (flags & TCL_ENCODING_CHAR_LIMIT) {
        charLimit = *dstCharsPtr;
@@ -2755,7 +2771,7 @@ TableFromUtfProc(
     const char *dstStart, *dstEnd, *prefixBytes;
     Tcl_UniChar ch = 0;
     int result, len, word, numChars;
-    TableEncodingData *dataPtr = clientData;
+    TableEncodingData *dataPtr = (TableEncodingData *)clientData;
     const unsigned short *const *fromUnicode;
 
     result = TCL_OK;
@@ -2786,12 +2802,8 @@ TableFromUtfProc(
        len = TclUtfToUniChar(src, &ch);
 
 #if TCL_UTF_MAX > 4
-       /*
-        * This prevents a crash condition. More evaluation is required for
-        * full support of int Tcl_UniChar. [Bug 1004065]
-        */
-
-       if (ch & 0xffff0000) {
+       /* Unicode chars > +U0FFFF cannot be represented in any table encoding */
+       if (ch & 0xFFFF0000) {
            word = 0;
        } else
 #elif TCL_UTF_MAX == 4
@@ -2799,7 +2811,7 @@ TableFromUtfProc(
            word = 0;
        } else
 #endif
-           word = fromUnicode[(ch >> 8)][ch & 0xff];
+           word = fromUnicode[(ch >> 8)][ch & 0xFF];
 
        if ((word == 0) && (ch != 0)) {
            if (flags & TCL_ENCODING_STOPONERROR) {
@@ -2962,11 +2974,9 @@ Iso88591FromUtfProc(
 {
     const char *srcStart, *srcEnd, *srcClose;
     const char *dstStart, *dstEnd;
-    int result, numChars;
+    int result = TCL_OK, numChars;
     Tcl_UniChar ch = 0;
 
-    result = TCL_OK;
-
     srcStart = src;
     srcEnd = src + srcLen;
     srcClose = srcEnd;
@@ -2995,7 +3005,7 @@ Iso88591FromUtfProc(
         * Check for illegal characters.
         */
 
-       if (ch > 0xff
+       if (ch > 0xFF
 #if TCL_UTF_MAX == 4
                || ((ch >= 0xD800) && (len < 3))
 #endif
@@ -3007,7 +3017,6 @@ Iso88591FromUtfProc(
 #if TCL_UTF_MAX == 4
            if ((ch >= 0xD800) && (len < 3)) len = 4;
 #endif
-
            /*
             * Plunge on, using '?' as a fallback character.
             */
@@ -3051,7 +3060,7 @@ TableFreeProc(
     ClientData clientData)     /* TableEncodingData that specifies
                                 * encoding. */
 {
-    TableEncodingData *dataPtr = clientData;
+    TableEncodingData *dataPtr = (TableEncodingData *)clientData;
 
     /*
      * Make sure we aren't freeing twice on shutdown. [Bug 219314]
@@ -3109,7 +3118,7 @@ EscapeToUtfProc(
                                 * correspond to the bytes stored in the
                                 * output buffer. */
 {
-    EscapeEncodingData *dataPtr = clientData;
+    EscapeEncodingData *dataPtr = (EscapeEncodingData *)clientData;
     const char *prefixBytes, *tablePrefixBytes, *srcStart, *srcEnd;
     const unsigned short *const *tableToUnicode;
     const Encoding *encodingPtr;
@@ -3120,8 +3129,8 @@ EscapeToUtfProc(
        charLimit = *dstCharsPtr;
     }
     result = TCL_OK;
-    tablePrefixBytes = NULL;   /* lint. */
-    tableToUnicode = NULL;     /* lint. */
+    tablePrefixBytes = NULL;
+    tableToUnicode = NULL;
     prefixBytes = dataPtr->prefixBytes;
     encodingPtr = NULL;
 
@@ -3245,7 +3254,7 @@ EscapeToUtfProc(
            TableEncodingData *tableDataPtr;
 
            encodingPtr = GetTableEncoding(dataPtr, state);
-           tableDataPtr = encodingPtr->clientData;
+           tableDataPtr = (TableEncodingData *)encodingPtr->clientData;
            tablePrefixBytes = tableDataPtr->prefixBytes;
            tableToUnicode = (const unsigned short *const*)
                    tableDataPtr->toUnicode;
@@ -3323,7 +3332,7 @@ EscapeFromUtfProc(
                                 * correspond to the bytes stored in the
                                 * output buffer. */
 {
-    EscapeEncodingData *dataPtr = clientData;
+    EscapeEncodingData *dataPtr = (EscapeEncodingData *)clientData;
     const Encoding *encodingPtr;
     const char *srcStart, *srcEnd, *srcClose;
     const char *dstStart, *dstEnd;
@@ -3364,7 +3373,7 @@ EscapeFromUtfProc(
     }
 
     encodingPtr = GetTableEncoding(dataPtr, state);
-    tableDataPtr = encodingPtr->clientData;
+    tableDataPtr = (const TableEncodingData *)encodingPtr->clientData;
     tablePrefixBytes = tableDataPtr->prefixBytes;
     tableFromUnicode = (const unsigned short *const *)
            tableDataPtr->fromUnicode;
@@ -3383,7 +3392,7 @@ EscapeFromUtfProc(
            break;
        }
        len = TclUtfToUniChar(src, &ch);
-       word = tableFromUnicode[(ch >> 8)][ch & 0xff];
+       word = tableFromUnicode[(ch >> 8)][ch & 0xFF];
 
        if ((word == 0) && (ch != 0)) {
            int oldState;
@@ -3392,8 +3401,8 @@ EscapeFromUtfProc(
            oldState = state;
            for (state = 0; state < dataPtr->numSubTables; state++) {
                encodingPtr = GetTableEncoding(dataPtr, state);
-               tableDataPtr = encodingPtr->clientData;
-               word = tableDataPtr->fromUnicode[(ch >> 8)][ch & 0xff];
+               tableDataPtr = (const TableEncodingData *)encodingPtr->clientData;
+               word = tableDataPtr->fromUnicode[(ch >> 8)][ch & 0xFF];
                if (word != 0) {
                    break;
                }
@@ -3406,7 +3415,7 @@ EscapeFromUtfProc(
                    break;
                }
                encodingPtr = GetTableEncoding(dataPtr, state);
-               tableDataPtr = encodingPtr->clientData;
+               tableDataPtr = (const TableEncodingData *)encodingPtr->clientData;
                word = tableDataPtr->fallback;
            }
 
@@ -3496,14 +3505,13 @@ EscapeFromUtfProc(
  *
  * EscapeFreeProc --
  *
- *     This function is invoked when an EscapeEncodingData encoding is
- *     deleted. It deletes the memory used by the encoding.
+ *     Frees resources used by the encoding.
  *
  * Results:
  *     None.
  *
  * Side effects:
- *     Memory freed.
+ *     Memory is freed.
  *
  *---------------------------------------------------------------------------
  */
@@ -3513,7 +3521,7 @@ EscapeFreeProc(
     ClientData clientData)     /* EscapeEncodingData that specifies
                                 * encoding. */
 {
-    EscapeEncodingData *dataPtr = clientData;
+    EscapeEncodingData *dataPtr = (EscapeEncodingData *)clientData;
     EscapeSubTable *subTablePtr;
     int i;
 
@@ -3678,8 +3686,8 @@ InitializeEncodingSearchPath(
     bytes = Tcl_GetStringFromObj(searchPathObj, &numBytes);
 
     *lengthPtr = numBytes;
-    *valuePtr = ckalloc(numBytes + 1);
-    memcpy(*valuePtr, bytes, (size_t) numBytes + 1);
+    *valuePtr = (char *)ckalloc(numBytes + 1);
+    memcpy(*valuePtr, bytes, numBytes + 1);
     Tcl_DecrRefCount(searchPathObj);
 }
 \f
index 03bbf03..ea32e8a 100644 (file)
@@ -107,7 +107,7 @@ static inline Tcl_Obj *
 NewNsObj(
     Tcl_Namespace *namespacePtr)
 {
-    register Namespace *nsPtr = (Namespace *) namespacePtr;
+    Namespace *nsPtr = (Namespace *) namespacePtr;
 
     if (namespacePtr == TclGetGlobalNamespace(nsPtr->interp)) {
        return Tcl_NewStringObj("::", 2);
@@ -1805,7 +1805,7 @@ NsEnsembleImplementationCmdNR(
 
        subcmdName = Tcl_GetStringFromObj(subObj, &stringLength);
        for (i=0 ; i<tableLength ; i++) {
-           register int cmp = strncmp(subcmdName,
+           int cmp = strncmp(subcmdName,
                    ensemblePtr->subcommandArrayPtr[i],
                    (unsigned) stringLength);
 
@@ -2396,7 +2396,7 @@ MakeCachedEnsembleCommand(
     Tcl_HashEntry *hPtr,
     Tcl_Obj *fix)
 {
-    register EnsembleCmdRep *ensembleCmd;
+    EnsembleCmdRep *ensembleCmd;
 
     if (objPtr->typePtr == &ensembleCmdType) {
        ensembleCmd = objPtr->internalRep.twoPtrValue.ptr1;
@@ -2892,6 +2892,7 @@ TclCompileEnsemble(
                                 * compiled. */
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;
     Tcl_Token *tokenPtr = TokenAfter(parsePtr->tokenPtr);
     Tcl_Obj *mapObj, *subcmdObj, *targetCmdObj, *listObj, **elems;
     Tcl_Obj *replaced = Tcl_NewObj(), *replacement;
@@ -2901,7 +2902,6 @@ TclCompileEnsemble(
     int ourResult = TCL_ERROR;
     unsigned numBytes;
     const char *word;
-    DefineLineInformation;
 
     Tcl_IncrRefCount(replaced);
     if (parsePtr->numWords < depth + 1) {
@@ -3230,6 +3230,7 @@ TclAttemptCompileProc(
     Command *cmdPtr,
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;
     int result, i;
     Tcl_Token *saveTokenPtr = parsePtr->tokenPtr;
     int savedStackDepth = envPtr->currStackDepth;
@@ -3239,7 +3240,6 @@ TclAttemptCompileProc(
 #ifdef TCL_COMPILE_DEBUG
     int savedExceptDepth = envPtr->exceptDepth;
 #endif
-    DefineLineInformation;
 
     if (cmdPtr->compileProc == NULL) {
        return TCL_ERROR;
@@ -3363,11 +3363,11 @@ CompileToInvokedCommand(
     Command *cmdPtr,
     CompileEnv *envPtr)                /* Holds resulting instructions. */
 {
+    DefineLineInformation;
     Tcl_Token *tokPtr;
     Tcl_Obj *objPtr, **words;
     char *bytes;
     int length, i, numWords, cmdLit, extraLiteralFlags = LITERAL_CMD_NAME;
-    DefineLineInformation;
 
     /*
      * Push the words of the command. Take care; the command words may be
index da05f93..15dd8b5 100644 (file)
 
 TCL_DECLARE_MUTEX(envMutex)    /* To serialize access to environ. */
 
+#if defined(_WIN32)
+#  define tenviron _wenviron
+#  define tenviron2utfdstr(tenvstr, len, dstr) \
+               Tcl_WinTCharToUtf((TCHAR *)tenvstr, len, dstr)
+#  define utf2tenvirondstr(str, len, dstr) \
+               (const WCHAR *)Tcl_WinUtfToTChar(str, len, dstr)
+#  define techar WCHAR
+#  ifdef USE_PUTENV
+#    define putenv(env) _wputenv((const wchar_t *)env)
+#  endif
+#else
+#  define tenviron environ
+#  define tenviron2utfdstr(tenvstr, len, dstr) \
+               Tcl_ExternalToUtfDString(NULL, tenvstr, len, dstr)
+#  define utf2tenvirondstr(str, len, dstr) \
+               Tcl_UtfToExternalDString(NULL, str, len, dstr)
+#  define techar char
+#endif
+
 static struct {
     int cacheSize;             /* Number of env strings in cache. */
     char **cache;              /* Array containing all of the environment
                                 * strings that Tcl has allocated. */
 #ifndef USE_PUTENV
-    char **ourEnviron;         /* Cache of the array that we allocate. We
+    techar **ourEnviron;               /* Cache of the array that we allocate. We
                                 * need to track this in case another
                                 * subsystem swaps around the environ array
                                 * like we do. */
@@ -34,6 +53,8 @@ static struct {
 #endif
 } env;
 
+#define tNTL sizeof(techar)
+
 /*
  * Declarations for local functions defined in this file:
  */
@@ -106,6 +127,17 @@ TclSetupEnv(
            /*msg*/ 0, /*createPart1*/ 0, /*createPart2*/ 0, &arrayPtr);
     TclFindArrayPtrElements(varPtr, &namesHash);
 
+#if defined(_WIN32)
+    if (tenviron == NULL) {
+       /*
+        * When we are started from main(), the _wenviron array could
+        * be NULL and will be initialized by the first _wgetenv() call.
+        */
+
+       (void) _wgetenv(L"WINDIR");
+    }
+#endif
+
     /*
      * Go through the environment array and transfer its values into Tcl. At
      * the same time, remove those elements we add/update from the hash table
@@ -113,17 +145,17 @@ TclSetupEnv(
      * will hold just the parts to remove.
      */
 
-    if (environ[0] != NULL) {
+    if (tenviron[0] != NULL) {
        int i;
 
        Tcl_MutexLock(&envMutex);
-       for (i = 0; environ[i] != NULL; i++) {
+       for (i = 0; tenviron[i] != NULL; i++) {
            Tcl_Obj *obj1, *obj2;
            const char *p1;
            char *p2;
 
-           p1 = Tcl_ExternalToUtfDString(NULL, environ[i], -1, &envString);
-           p2 = strchr(p1, '=');
+           p1 = tenviron2utfdstr(tenviron[i], -1, &envString);
+           p2 = (char *)strchr(p1, '=');
            if (p2 == NULL) {
                /*
                 * This condition seem to happen occasionally under some
@@ -172,7 +204,7 @@ TclSetupEnv(
 
     for (hPtr=Tcl_FirstHashEntry(&namesHash, &search); hPtr!=NULL;
            hPtr=Tcl_NextHashEntry(&search)) {
-       Tcl_Obj *elemName = Tcl_GetHashValue(hPtr);
+       Tcl_Obj *elemName = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
 
        TclObjUnsetVar2(interp, varNamePtr, elemName, TCL_GLOBAL_ONLY);
     }
@@ -219,7 +251,7 @@ TclSetEnv(
     unsigned nameLength, valueLength;
     int index, length;
     char *p, *oldValue;
-    const char *p2;
+    const techar *p2;
 
     /*
      * Figure out where the entry is going to go. If the name doesn't already
@@ -238,23 +270,23 @@ TclSetEnv(
         * environment is the one we allocated. [Bug 979640]
         */
 
-       if ((env.ourEnviron != environ) || (length+2 > env.ourEnvironSize)) {
-           char **newEnviron = ckalloc((length + 5) * sizeof(char *));
+       if ((env.ourEnviron != tenviron) || (length+2 > env.ourEnvironSize)) {
+           techar **newEnviron = (techar **)ckalloc((length + 5) * sizeof(techar *));
 
-           memcpy(newEnviron, environ, length * sizeof(char *));
+           memcpy(newEnviron, tenviron, length * sizeof(techar *));
            if ((env.ourEnvironSize != 0) && (env.ourEnviron != NULL)) {
                ckfree(env.ourEnviron);
            }
-           environ = env.ourEnviron = newEnviron;
+           tenviron = (env.ourEnviron = newEnviron);
            env.ourEnvironSize = length + 5;
        }
        index = length;
-       environ[index + 1] = NULL;
+       tenviron[index + 1] = NULL;
 #endif /* USE_PUTENV */
        oldValue = NULL;
        nameLength = strlen(name);
     } else {
-       const char *env;
+       const char *oldEnv;
 
        /*
         * Compare the new value to the existing value. If they're the same
@@ -264,16 +296,16 @@ TclSetEnv(
         * interpreters.
         */
 
-       env = Tcl_ExternalToUtfDString(NULL, environ[index], -1, &envString);
-       if (strcmp(value, env + (length + 1)) == 0) {
+       oldEnv = tenviron2utfdstr(tenviron[index], -1, &envString);
+       if (strcmp(value, oldEnv + (length + 1)) == 0) {
            Tcl_DStringFree(&envString);
            Tcl_MutexUnlock(&envMutex);
            return;
        }
        Tcl_DStringFree(&envString);
 
-       oldValue = environ[index];
-       nameLength = (unsigned) length;
+       oldValue = (char *)tenviron[index];
+       nameLength = length;
     }
 
     /*
@@ -283,18 +315,18 @@ TclSetEnv(
      */
 
     valueLength = strlen(value);
-    p = ckalloc(nameLength + valueLength + 2);
+    p = (char *)ckalloc(nameLength + valueLength + 2);
     memcpy(p, name, nameLength);
     p[nameLength] = '=';
     memcpy(p+nameLength+1, value, valueLength+1);
-    p2 = Tcl_UtfToExternalDString(NULL, p, -1, &envString);
+    p2 = utf2tenvirondstr(p, -1, &envString);
 
     /*
      * Copy the native string to heap memory.
      */
 
-    p = ckrealloc(p, Tcl_DStringLength(&envString) + 1);
-    memcpy(p, p2, (unsigned) Tcl_DStringLength(&envString) + 1);
+    p = (char *)ckrealloc(p, Tcl_DStringLength(&envString) + tNTL);
+    memcpy(p, p2, Tcl_DStringLength(&envString) + tNTL);
     Tcl_DStringFree(&envString);
 
 #ifdef USE_PUTENV
@@ -305,7 +337,7 @@ TclSetEnv(
     putenv(p);
     index = TclpFindVariable(name, &length);
 #else
-    environ[index] = p;
+    tenviron[index] = (techar *)p;
 #endif /* USE_PUTENV */
 
     /*
@@ -314,7 +346,7 @@ TclSetEnv(
      * string in the cache.
      */
 
-    if ((index != -1) && (environ[index] == p)) {
+    if ((index != -1) && (tenviron[index] == (techar *)p)) {
        ReplaceString(oldValue, p);
 #ifdef HAVE_PUTENV_THAT_COPIES
     } else {
@@ -379,7 +411,7 @@ Tcl_PutEnv(
      */
 
     name = Tcl_ExternalToUtfDString(NULL, assignment, -1, &nameString);
-    value = strchr(name, '=');
+    value = (char *)strchr(name, '=');
 
     if ((value != NULL) && (value != name)) {
        value[0] = '\0';
@@ -440,7 +472,7 @@ TclUnsetEnv(
      * Remember the old value so we can free it if Tcl created the string.
      */
 
-    oldValue = environ[index];
+    oldValue = (char *)tenviron[index];
 
     /*
      * Update the system environment. This must be done before we update the
@@ -454,20 +486,20 @@ TclUnsetEnv(
      */
 
 #if defined(_WIN32)
-    string = ckalloc(length + 2);
-    memcpy(string, name, (size_t) length);
+    string = (char *)ckalloc(length + 2);
+    memcpy(string, name, length);
     string[length] = '=';
     string[length+1] = '\0';
 #else
-    string = ckalloc(length + 1);
-    memcpy(string, name, (size_t) length);
+    string = (char *)ckalloc(length + 1);
+    memcpy(string, name, length);
     string[length] = '\0';
 #endif /* _WIN32 */
 
-    Tcl_UtfToExternalDString(NULL, string, -1, &envString);
-    string = ckrealloc(string, Tcl_DStringLength(&envString) + 1);
+    utf2tenvirondstr(string, -1, &envString);
+    string = (char *)ckrealloc(string, Tcl_DStringLength(&envString) + tNTL);
     memcpy(string, Tcl_DStringValue(&envString),
-           (unsigned) Tcl_DStringLength(&envString)+1);
+           Tcl_DStringLength(&envString) + tNTL);
     Tcl_DStringFree(&envString);
 
     putenv(string);
@@ -478,7 +510,7 @@ TclUnsetEnv(
      * string in the cache.
      */
 
-    if (environ[index] == string) {
+    if (tenviron[index] == (techar *)string) {
        ReplaceString(oldValue, string);
 #ifdef HAVE_PUTENV_THAT_COPIES
     } else {
@@ -490,7 +522,7 @@ TclUnsetEnv(
 #endif /* HAVE_PUTENV_THAT_COPIES */
     }
 #else /* !USE_PUTENV_FOR_UNSET */
-    for (envPtr = environ+index+1; ; envPtr++) {
+    for (envPtr = (char **)(tenviron+index+1); ; envPtr++) {
        envPtr[-1] = *envPtr;
        if (*envPtr == NULL) {
            break;
@@ -539,7 +571,7 @@ TclGetEnv(
     if (index != -1) {
        Tcl_DString envStr;
 
-       result = Tcl_ExternalToUtfDString(NULL, environ[index], -1, &envStr);
+       result = tenviron2utfdstr(tenviron[index], -1, &envStr);
        result += length;
        if (*result == '=') {
            result++;
@@ -701,7 +733,7 @@ ReplaceString(
 
        const int growth = 5;
 
-       env.cache = ckrealloc(env.cache,
+       env.cache = (char **)ckrealloc(env.cache,
                (env.cacheSize + growth) * sizeof(char *));
        env.cache[env.cacheSize] = newStr;
        (void) memset(env.cache+env.cacheSize+1, 0,
index 79985ed..d8f5119 100644 (file)
@@ -1043,9 +1043,9 @@ TclInitSubsystems(void)
             * implementation of self-initializing locks.
             */
 
-           TclInitThreadStorage();     /* Creates master hash table for
+           TclInitThreadStorage();     /* Creates hash table for
                                         * thread local storage */
-#if USE_TCLALLOC
+#if defined(USE_TCLALLOC) && USE_TCLALLOC
            TclInitAlloc();             /* Process wide mutex init */
 #endif
 #ifdef TCL_MEM_DEBUG
@@ -1059,7 +1059,6 @@ TclInitSubsystems(void)
                                         * mutexes. */
            TclInitIOSubsystem();       /* Inits a tsd key (noop). */
            TclInitEncodingSubsystem(); /* Process wide encoding init. */
-           TclpSetInterfaces();
            TclInitNamespaceSubsystem();/* Register ns obj type (mutexed). */
            subsystemsInitialized = 1;
        }
@@ -1158,7 +1157,7 @@ Tcl_Finalize(void)
     TclFinalizeFilesystem();
 
     /*
-     * Undo all Tcl_ObjType registrations, and reset the master list of free
+     * Undo all Tcl_ObjType registrations, and reset the global list of free
      * Tcl_Obj's. After this returns, no more Tcl_Obj's should be allocated or
      * freed.
      *
index 6394eea..0a293bd 100644 (file)
@@ -317,12 +317,16 @@ VarHashCreateVar(
        switch (*pc) {                                                  \
        case INST_JUMP_FALSE1:                                          \
            NEXT_INST_F(((condition)? 2 : TclGetInt1AtPtr(pc+1)), (cleanup), 0); \
+       break; \
        case INST_JUMP_TRUE1:                                           \
            NEXT_INST_F(((condition)? TclGetInt1AtPtr(pc+1) : 2), (cleanup), 0); \
+       break; \
        case INST_JUMP_FALSE4:                                          \
            NEXT_INST_F(((condition)? 5 : TclGetInt4AtPtr(pc+1)), (cleanup), 0); \
+       break; \
        case INST_JUMP_TRUE4:                                           \
            NEXT_INST_F(((condition)? TclGetInt4AtPtr(pc+1) : 5), (cleanup), 0); \
+       break; \
        default:                                                        \
            if ((condition) < 0) {                                      \
                TclNewIntObj(objResultPtr, -1);                         \
@@ -330,6 +334,7 @@ VarHashCreateVar(
                objResultPtr = TCONST((condition) > 0);                 \
            }                                                           \
            NEXT_INST_F(0, (cleanup), 1);                               \
+       break; \
        }                                                               \
     } while (0)
 #define JUMP_PEEPHOLE_V(condition, pcAdjustment, cleanup) \
@@ -338,12 +343,16 @@ VarHashCreateVar(
        switch (*pc) {                                                  \
        case INST_JUMP_FALSE1:                                          \
            NEXT_INST_V(((condition)? 2 : TclGetInt1AtPtr(pc+1)), (cleanup), 0); \
+       break; \
        case INST_JUMP_TRUE1:                                           \
            NEXT_INST_V(((condition)? TclGetInt1AtPtr(pc+1) : 2), (cleanup), 0); \
+       break; \
        case INST_JUMP_FALSE4:                                          \
            NEXT_INST_V(((condition)? 5 : TclGetInt4AtPtr(pc+1)), (cleanup), 0); \
+       break; \
        case INST_JUMP_TRUE4:                                           \
            NEXT_INST_V(((condition)? TclGetInt4AtPtr(pc+1) : 5), (cleanup), 0); \
+       break; \
        default:                                                        \
            if ((condition) < 0) {                                      \
                TclNewIntObj(objResultPtr, -1);                         \
@@ -351,6 +360,7 @@ VarHashCreateVar(
                objResultPtr = TCONST((condition) > 0);                 \
            }                                                           \
            NEXT_INST_V(0, (cleanup), 1);                               \
+       break; \
        }                                                               \
     } while (0)
 #else /* TCL_COMPILE_DEBUG */
@@ -576,7 +586,7 @@ VarHashCreateVar(
  * Auxiliary tables used to compute powers of small integers.
  */
 
-#if (LONG_MAX == 0x7fffffff)
+#if (LONG_MAX == 0x7FFFFFFF)
 
 /*
  * Maximum base that, when raised to powers 2, 3, ... 8, fits in a 32-bit
@@ -606,9 +616,9 @@ static const long Exp32Value[] = {
     1000000000
 };
 static const size_t Exp32ValueSize = sizeof(Exp32Value)/sizeof(long);
-#endif /* LONG_MAX == 0x7fffffff -- 32 bit machine */
+#endif /* LONG_MAX == 0x7FFFFFFF -- 32 bit machine */
 
-#if (LONG_MAX > 0x7fffffff) || !defined(TCL_WIDE_INT_IS_LONG)
+#if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
 
 /*
  * Maximum base that, when raised to powers 2, 3, ..., 16, fits in a
@@ -713,7 +723,7 @@ static const Tcl_WideInt Exp64Value[] = {
     (Tcl_WideInt)371293*371293*371293*13*13
 };
 static const size_t Exp64ValueSize = sizeof(Exp64Value) / sizeof(Tcl_WideInt);
-#endif /* (LONG_MAX > 0x7fffffff) || !defined(TCL_WIDE_INT_IS_LONG) */
+#endif /* (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG) */
 
 /*
  * Markers for ExecuteExtendedBinaryMathOp.
@@ -904,8 +914,8 @@ TclCreateExecEnv(
                                 * [sizeof(Tcl_Obj*)] */
 {
     ExecEnv *eePtr = ckalloc(sizeof(ExecEnv));
-    ExecStack *esPtr = ckalloc(sizeof(ExecStack)
-           + (size_t) (size-1) * sizeof(Tcl_Obj *));
+    ExecStack *esPtr = ckalloc(TclOffset(ExecStack, stackWords)
+           + size * sizeof(Tcl_Obj *));
 
     eePtr->execStackPtr = esPtr;
     TclNewBooleanObj(eePtr->constants[0], 0);
@@ -1170,7 +1180,7 @@ GrowEvaluationStack(
     newElems = needed;
 #endif
 
-    newBytes = sizeof(ExecStack) + (newElems-1) * sizeof(Tcl_Obj *);
+    newBytes = TclOffset(ExecStack, stackWords) + newElems * sizeof(Tcl_Obj *);
 
     oldPtr = esPtr;
     esPtr = ckalloc(newBytes);
@@ -1397,7 +1407,7 @@ int
 Tcl_ExprObj(
     Tcl_Interp *interp,                /* Context in which to evaluate the
                                 * expression. */
-    register Tcl_Obj *objPtr,  /* Points to Tcl object containing expression
+    Tcl_Obj *objPtr,   /* Points to Tcl object containing expression
                                 * to evaluate. */
     Tcl_Obj **resultPtrPtr)    /* Where the Tcl_Obj* that is the expression
                                 * result is stored if no errors occur. */
@@ -1516,7 +1526,7 @@ CompileExprObj(
     Interp *iPtr = (Interp *) interp;
     CompileEnv compEnv;                /* Compilation environment structure allocated
                                 * in frame. */
-    register ByteCode *codePtr = NULL;
+    ByteCode *codePtr = NULL;
                                /* Tcl Internal type of bytecode. Initialized
                                 * to avoid compiler warning. */
 
@@ -1670,8 +1680,8 @@ TclCompileObj(
     const CmdFrame *invoker,
     int word)
 {
-    register Interp *iPtr = (Interp *) interp;
-    register ByteCode *codePtr;        /* Tcl Internal type of bytecode. */
+    Interp *iPtr = (Interp *) interp;
+    ByteCode *codePtr; /* Tcl Internal type of bytecode. */
     Namespace *namespacePtr = iPtr->varFramePtr->nsPtr;
 
     /*
@@ -2204,6 +2214,22 @@ TEBCresume(
     if (!pc) {
        /* bytecode is starting from scratch */
        pc = codePtr->codeStart;
+
+       /*
+        * Reset the interp's result to avoid possible duplications of large
+        * objects [3c6e47363e], [781585], [804681], This can happen by start
+        * also in nested compiled blocks (enclosed in parent cycle).
+        * See else branch below for opposite handling by continuation/resume.
+        */
+
+       objPtr = iPtr->objResultPtr;
+       if (objPtr->refCount > 1) {
+           TclDecrRefCount(objPtr);
+           TclNewObj(objPtr);
+           Tcl_IncrRefCount(objPtr);
+           iPtr->objResultPtr = objPtr;
+       }
+
        goto cleanup0;
     } else {
         /* resume from invocation */
@@ -2243,7 +2269,7 @@ TEBCresume(
                objc, cmdNameBuf), Tcl_GetObjResult(interp));
 
        /*
-        * Reset the interp's result to avoid possible duplications of large
+        * Obtain and reset interp's result to avoid possible duplications of
         * objects [Bug 781585]. We do not call Tcl_ResetResult to avoid any
         * side effects caused by the resetting of errorInfo and errorCode
         * [Bug 804681], which are not needed here. We chose instead to
@@ -2604,7 +2630,7 @@ TEBCresume(
 #ifdef TCL_COMPILE_DEBUG
        /* FIXME: What is the right thing to trace? */
        {
-           register int i;
+           int i;
 
            TRACE(("%d [", opnd));
            for (i=opnd-1 ; i>=0 ; i--) {
@@ -2669,23 +2695,27 @@ TEBCresume(
        objResultPtr = codePtr->objArrayPtr[TclGetUInt4AtPtr(pc+1)];
        TRACE_WITH_OBJ(("%u => ", TclGetUInt4AtPtr(pc+1)), objResultPtr);
        NEXT_INST_F(5, 0, 1);
+    break;
 
     case INST_POP:
        TRACE_WITH_OBJ(("=> discarding "), OBJ_AT_TOS);
        objPtr = POP_OBJECT();
        TclDecrRefCount(objPtr);
        NEXT_INST_F(1, 0, 0);
+    break;
 
     case INST_DUP:
        objResultPtr = OBJ_AT_TOS;
        TRACE_WITH_OBJ(("=> "), objResultPtr);
        NEXT_INST_F(1, 0, 1);
+    break;
 
     case INST_OVER:
        opnd = TclGetUInt4AtPtr(pc+1);
        objResultPtr = OBJ_AT_DEPTH(opnd);
        TRACE_WITH_OBJ(("%u => ", opnd), objResultPtr);
        NEXT_INST_F(5, 0, 1);
+    break;
 
     case INST_REVERSE: {
        Tcl_Obj **a, **b;
@@ -2702,6 +2732,7 @@ TEBCresume(
        TRACE(("%u => OK\n", opnd));
        NEXT_INST_F(5, 0, 0);
     }
+    break;
 
     case INST_STR_CONCAT1: {
        int appendLen = 0;
@@ -2807,7 +2838,7 @@ TEBCresume(
            for (; currPtr <= &OBJ_AT_TOS; currPtr++) {
                bytes = TclGetStringFromObj(*currPtr, &length);
                if (bytes != NULL) {
-                   memcpy(p, bytes, (size_t) length);
+                   memcpy(p, bytes, length);
                    p += length;
                }
            }
@@ -2842,7 +2873,7 @@ TEBCresume(
            for (; currPtr <= &OBJ_AT_TOS; currPtr++) {
                if ((*currPtr)->bytes != tclEmptyStringRep) {
                    bytes = (char *) Tcl_GetByteArrayFromObj(*currPtr,&length);
-                   memcpy(p, bytes, (size_t) length);
+                   memcpy(p, bytes, length);
                    p += length;
                }
            }
@@ -2883,6 +2914,7 @@ TEBCresume(
        PUSH_TAUX_OBJ(objPtr);
        TRACE(("=> mark depth as %d\n", (int) CURR_DEPTH));
        NEXT_INST_F(1, 0, 0);
+    break;
 
     case INST_EXPAND_DROP:
        /*
@@ -2961,6 +2993,7 @@ TEBCresume(
        Tcl_DecrRefCount(objPtr);
        NEXT_INST_F(5, 0, 0);
     }
+    break;
 
     case INST_EXPR_STK: {
        ByteCode *newCodePtr;
@@ -3008,6 +3041,7 @@ TEBCresume(
 
        TclNewObj(objResultPtr);
        NEXT_INST_F(1, 0, 1);
+    break;
 
     case INST_INVOKE_STK4:
        objc = TclGetUInt4AtPtr(pc+1);
@@ -3820,7 +3854,7 @@ TEBCresume(
     case INST_INCR_SCALAR_STK_IMM:
     case INST_INCR_STK_IMM:
        increment = TclGetInt1AtPtr(pc+1);
-       incrPtr = Tcl_NewIntObj(increment);
+       TclNewIntObj(incrPtr, increment);
        Tcl_IncrRefCount(incrPtr);
        pcAdjustment = 2;
 
@@ -3855,7 +3889,7 @@ TEBCresume(
     case INST_INCR_ARRAY1_IMM:
        opnd = TclGetUInt1AtPtr(pc+1);
        increment = TclGetInt1AtPtr(pc+2);
-       incrPtr = Tcl_NewIntObj(increment);
+       TclNewIntObj(incrPtr, increment);
        Tcl_IncrRefCount(incrPtr);
        pcAdjustment = 3;
 
@@ -4296,6 +4330,7 @@ TEBCresume(
        }
        NEXT_INST_F(5, 0, 0);
     }
+    break;
 
     /*
      *    End of INST_UNSET instructions.
@@ -4516,6 +4551,7 @@ TEBCresume(
        TRACE_APPEND(("link made\n"));
        NEXT_INST_F(5, 1, 0);
     }
+    break;
 
     /*
      *    End of variable linking instructions.
@@ -4527,6 +4563,7 @@ TEBCresume(
        TRACE(("%d => new pc %u\n", opnd,
                (unsigned)(pc + opnd - codePtr->codeStart)));
        NEXT_INST_F(opnd, 0, 0);
+    break;
 
     case INST_JUMP4:
        opnd = TclGetInt4AtPtr(pc+1);
@@ -4589,6 +4626,7 @@ TEBCresume(
 #endif
        NEXT_INST_F(jmpOffset[b], 1, 0);
     }
+    break;
 
     case INST_JUMP_TABLE: {
        Tcl_HashEntry *hPtr;
@@ -4614,6 +4652,7 @@ TEBCresume(
            NEXT_INST_F(5, 1, 0);
        }
     }
+    break;
 
     /*
      * These two instructions are now redundant: the complete logic of the LOR
@@ -4658,6 +4697,7 @@ TEBCresume(
        TRACE(("%.20s %.20s => %d\n", O2S(valuePtr),O2S(value2Ptr),iResult));
        NEXT_INST_F(1, 2, 1);
     }
+    break;
 
     /*
      * -----------------------------------------------------------------
@@ -4676,6 +4716,7 @@ TEBCresume(
        TRACE_WITH_OBJ(("=> "), objResultPtr);
        NEXT_INST_F(1, 0, 1);
     }
+    break;
     case INST_COROUTINE_NAME: {
        CoroutineData *corPtr = iPtr->execEnvPtr->corPtr;
 
@@ -4687,14 +4728,16 @@ TEBCresume(
        TRACE_WITH_OBJ(("=> "), objResultPtr);
        NEXT_INST_F(1, 0, 1);
     }
+    break;
     case INST_INFO_LEVEL_NUM:
        TclNewIntObj(objResultPtr, iPtr->varFramePtr->level);
        TRACE_WITH_OBJ(("=> "), objResultPtr);
        NEXT_INST_F(1, 0, 1);
+    break;
     case INST_INFO_LEVEL_ARGS: {
        int level;
-       register CallFrame *framePtr = iPtr->varFramePtr;
-       register CallFrame *rootFramePtr = iPtr->rootFramePtr;
+       CallFrame *framePtr = iPtr->varFramePtr;
+       CallFrame *rootFramePtr = iPtr->rootFramePtr;
 
        TRACE(("\"%.30s\" => ", O2S(OBJ_AT_TOS)));
        if (TclGetIntFromObj(interp, OBJ_AT_TOS, &level) != TCL_OK) {
@@ -4991,7 +5034,7 @@ TEBCresume(
        }
 
        {
-           register Method *const mPtr =
+           Method *const mPtr =
                    contextPtr->callPtr->chain[newDepth].mPtr;
 
            return mPtr->typePtr->callProc(mPtr->clientData, interp,
@@ -5544,16 +5587,10 @@ TEBCresume(
            objResultPtr = Tcl_NewStringObj((const char *)
                    valuePtr->bytes+index, 1);
        } else {
-           char buf[TCL_UTF_MAX] = "";
-           Tcl_UniChar ch = Tcl_GetUniChar(valuePtr, index);
-
-           /*
-            * This could be: Tcl_NewUnicodeObj((const Tcl_UniChar *)&ch, 1)
-            * but creating the object as a string seems to be faster in
-            * practical use.
-            */
+           char buf[8] = "";
+           int ch = TclGetUCS4(valuePtr, index);
 
-           length = Tcl_UniCharToUtf(ch, buf);
+           length = TclUCS4ToUtf(ch, buf);
            objResultPtr = Tcl_NewStringObj(buf, length);
        }
 
@@ -5894,9 +5931,11 @@ TEBCresume(
        ustring1 = Tcl_GetUnicodeFromObj(valuePtr, &length);
        match = 1;
        if (length > 0) {
+           int ch;
            end = ustring1 + length;
-           for (p=ustring1 ; p<end ; p++) {
-               if (!tclStringClassTable[opnd].comparator(*p)) {
+           for (p=ustring1 ; p<end ; ) {
+               p += TclUniCharToUCS4(p, &ch);
+               if (!tclStringClassTable[opnd].comparator(ch)) {
                    match = 0;
                    break;
                }
@@ -6248,6 +6287,7 @@ TEBCresume(
                    lResult = l1 - l2*lResult;
                    goto longResultOfArithmetic;
                }
+               break;
 
            case INST_RSHIFT:
                if (l2 < 0) {
@@ -6296,6 +6336,7 @@ TEBCresume(
                    lResult = l1 >> ((int) l2);
                    goto longResultOfArithmetic;
                }
+               break;
 
            case INST_LSHIFT:
                if (l2 < 0) {
@@ -6504,6 +6545,7 @@ TEBCresume(
                Tcl_SetWideIntObj(valuePtr, wResult);
                TRACE(("%s\n", O2S(valuePtr)));
                NEXT_INST_F(1, 1, 0);
+           break;
 
            case INST_DIV:
                if (l2 == 0) {
@@ -6643,6 +6685,7 @@ TEBCresume(
            /* -NaN => NaN */
            TRACE_APPEND(("%s\n", O2S(valuePtr)));
            NEXT_INST_F(1, 0, 0);
+       break;
        case TCL_NUMBER_LONG:
            l1 = *((const long *) ptr1);
            if (l1 != LONG_MIN) {
@@ -6751,6 +6794,7 @@ TEBCresume(
        TRACE_APPEND(("numeric, same Tcl_Obj\n"));
        NEXT_INST_F(1, 0, 0);
     }
+    break;
 
     /*
      *    End of numeric operator instructions.
@@ -6762,11 +6806,12 @@ TEBCresume(
        if (valuePtr->typePtr == &tclBooleanType) {
            objResultPtr = TCONST(1);
        } else {
-           int result = (TclSetBooleanFromAny(NULL, valuePtr) == TCL_OK);
-           objResultPtr = TCONST(result);
+           int res = (TclSetBooleanFromAny(NULL, valuePtr) == TCL_OK);
+           objResultPtr = TCONST(res);
        }
        TRACE_WITH_OBJ(("\"%.30s\" => ", O2S(valuePtr)), objResultPtr);
        NEXT_INST_F(1, 0, 1);
+    break;
 
     case INST_BREAK:
        /*
@@ -6955,7 +7000,7 @@ TEBCresume(
     }
     {
        ForeachInfo *infoPtr;
-       Tcl_Obj *listPtr, **elements, *tmpPtr;
+       Tcl_Obj *listPtr, **elements;
        ForeachVarList *varListPtr;
        int numLists, iterMax, listLen, numVars;
        int iterTmp, iterNum, listTmpDepth;
@@ -7146,6 +7191,7 @@ TEBCresume(
        Tcl_ListObjAppendElement(NULL, objPtr, OBJ_AT_TOS);
        NEXT_INST_F(1, 1, 0);
     }
+    break;
 
     case INST_BEGIN_CATCH4:
        /*
@@ -7159,6 +7205,7 @@ TEBCresume(
                TclGetUInt4AtPtr(pc+1), (int) (catchTop - initCatchTop - 1),
                (int) CURR_DEPTH));
        NEXT_INST_F(5, 0, 0);
+    break;
 
     case INST_END_CATCH:
        catchTop--;
@@ -7168,6 +7215,7 @@ TEBCresume(
        result = TCL_OK;
        TRACE(("=> catchTop=%d\n", (int) (catchTop - initCatchTop - 1)));
        NEXT_INST_F(1, 0, 0);
+    break;
 
     case INST_PUSH_RESULT:
        objResultPtr = Tcl_GetObjResult(interp);
@@ -7181,11 +7229,13 @@ TEBCresume(
        Tcl_IncrRefCount(objPtr);
        iPtr->objResultPtr = objPtr;
        NEXT_INST_F(1, 0, -1);
+    break;
 
     case INST_PUSH_RETURN_CODE:
        TclNewIntObj(objResultPtr, result);
        TRACE(("=> %u\n", result));
        NEXT_INST_F(1, 0, 1);
+    break;
 
     case INST_PUSH_RETURN_OPTIONS:
        DECACHE_STACK_INFO();
@@ -7193,6 +7243,7 @@ TEBCresume(
        CACHE_STACK_INFO();
        TRACE_WITH_OBJ(("=> "), objResultPtr);
        NEXT_INST_F(1, 0, 1);
+    break;
 
     case INST_RETURN_CODE_BRANCH: {
        int code;
@@ -7235,8 +7286,8 @@ TEBCresume(
 
     case INST_DICT_GET:
     case INST_DICT_EXISTS: {
-       register Tcl_Interp *interp2 = interp;
-       register int found;
+       Tcl_Interp *interp2 = interp;
+       int found;
 
        opnd = TclGetUInt4AtPtr(pc+1);
        TRACE(("%u => ", opnd));
@@ -7343,7 +7394,7 @@ TEBCresume(
            if (valuePtr == NULL) {
                Tcl_DictObjPut(NULL, dictPtr, OBJ_AT_TOS,Tcl_NewIntObj(opnd));
            } else {
-               value2Ptr = Tcl_NewIntObj(opnd);
+               TclNewIntObj(value2Ptr, opnd);
                Tcl_IncrRefCount(value2Ptr);
                if (Tcl_IsShared(valuePtr)) {
                    valuePtr = Tcl_DuplicateObj(valuePtr);
@@ -7816,6 +7867,7 @@ TEBCresume(
        TRACE_APPEND(("OK\n"));
        NEXT_INST_F(5, 2, 0);
     }
+    break;
 
     /*
      *    End of dictionary-related instructions.
@@ -7849,11 +7901,11 @@ TEBCresume(
            default:
                Tcl_Panic("clockRead instruction with unknown clock#");
            }
-           /* TclNewWideObj(objResultPtr, wval); doesn't exist */
            objResultPtr = Tcl_NewWideIntObj(wval);
            TRACE_WITH_OBJ(("=> "), objResultPtr);
            NEXT_INST_F(2, 0, 1);
        }
+       break;
 
     default:
        Tcl_Panic("TclNRExecuteByteCode: unrecognized opCode %u", *pc);
@@ -8258,7 +8310,7 @@ FinalizeOONextFilter(
  *
  * Helpers to calculate small powers of integers whose result is long or wide.
  */
-#if (LONG_MAX == 0x7fffffff)
+#if (LONG_MAX == 0x7FFFFFFF)
 static inline long
 LongPwrSmallExpon(long l1, long exponent) {
 
@@ -8521,7 +8573,7 @@ ExecuteExtendedBinaryMathOp(
        mp_init(&bigResult);
        mp_init(&bigRemainder);
        mp_div(&big1, &big2, &bigResult, &bigRemainder);
-       if ((bigRemainder.used) != 0 && (bigRemainder.sign != big2.sign)) {
+       if (!mp_iszero(&bigRemainder) && (bigRemainder.sign != big2.sign)) {
            /*
             * Convert to Tcl's integer division rules.
             */
@@ -8804,7 +8856,7 @@ ExecuteExtendedBinaryMathOp(
            Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
            negativeExponent = (mp_cmp_d(&big2, 0) == MP_LT);
            mp_mod_2d(&big2, 1, &big2);
-           oddExponent = big2.used != 0;
+           oddExponent = !mp_iszero(&big2);
            mp_clear(&big2);
            break;
        }
@@ -8852,7 +8904,6 @@ ExecuteExtendedBinaryMathOp(
                type1 = TCL_NUMBER_LONG;
                goto pwrLongBase;
            }
-       break;
 #endif
        }
        if (negativeExponent) {
@@ -8861,7 +8912,6 @@ ExecuteExtendedBinaryMathOp(
             * Integers with magnitude greater than 1 raise to a negative
             * power yield the answer zero (see TIP 123).
             */
-
            return constants[0];
        }
 
@@ -8872,7 +8922,7 @@ ExecuteExtendedBinaryMathOp(
 
        /*
         * We refuse to accept exponent arguments that exceed one mp_digit
-        * which means the max exponent value is 2**28-1 = 0x0fffffff =
+        * which means the max exponent value is 2**28-1 = 0x0FFFFFFF =
         * 268435455, which fits into a signed 32 bit int which is within the
         * range of the long int type. This means any numeric Tcl_Obj value
         * not using TCL_NUMBER_LONG type must hold a value larger than we
@@ -8920,7 +8970,7 @@ ExecuteExtendedBinaryMathOp(
 #endif
                goto overflowExpon;
            }
-#if (LONG_MAX == 0x7fffffff)
+#if (LONG_MAX == 0x7FFFFFFF)
            if (l2 - 2 < (long)MaxBase32Size
                    && l1 <= MaxBase32[l2 - 2]
                    && l1 >= -MaxBase32[l2 - 2]) {
@@ -8961,13 +9011,13 @@ ExecuteExtendedBinaryMathOp(
                }
            }
 #endif
-#if (LONG_MAX > 0x7fffffff) || !defined(TCL_WIDE_INT_IS_LONG)
+#if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
            /* Code below (up to overflowExpon) works with wide-int base */
            w1 = l1;
 #endif
        }
 
-#if (LONG_MAX > 0x7fffffff) || !defined(TCL_WIDE_INT_IS_LONG)
+#if (LONG_MAX > 0x7FFFFFFF) || !defined(TCL_WIDE_INT_IS_LONG)
 
        /* From here (up to overflowExpon) base is wide-int (w1). */
 
@@ -9192,7 +9242,7 @@ ExecuteExtendedBinaryMathOp(
            mp_mul(&big1, &big2, &bigResult);
            break;
        case INST_DIV:
-           if (big2.used == 0) {
+           if (mp_iszero(&big2)) {
                mp_clear(&big1);
                mp_clear(&big2);
                mp_clear(&bigResult);
@@ -9201,7 +9251,7 @@ ExecuteExtendedBinaryMathOp(
            mp_init(&bigRemainder);
            mp_div(&big1, &big2, &bigResult, &bigRemainder);
            /* TODO: internals intrusion */
-           if (bigRemainder.used != 0
+           if (!mp_iszero(&bigRemainder)
                    && (bigRemainder.sign != big2.sign)) {
                /*
                 * Convert to Tcl's integer division rules.
@@ -9245,7 +9295,7 @@ ExecuteExtendedUnaryMathOp(
 #endif
        Tcl_TakeBignumFromObj(NULL, valuePtr, &big);
        /* ~a = - a - 1 */
-       mp_neg(&big, &big);
+       (void)mp_neg(&big, &big);
        mp_sub_d(&big, 1, &big);
        BIG_RESULT(&big);
     case INST_UMINUS:
@@ -9271,7 +9321,7 @@ ExecuteExtendedUnaryMathOp(
        default:
            Tcl_TakeBignumFromObj(NULL, valuePtr, &big);
        }
-       mp_neg(&big, &big);
+       (void)mp_neg(&big, &big);
        BIG_RESULT(&big);
     }
 
@@ -9377,6 +9427,7 @@ TclCompareTwoNumbers(
            mp_clear(&big2);
            return compare;
        }
+    break;
 
 #ifndef TCL_WIDE_INT_IS_LONG
     case TCL_NUMBER_WIDE:
@@ -9407,7 +9458,7 @@ TclCompareTwoNumbers(
            goto wideCompare;
        case TCL_NUMBER_BIG:
            Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
-           if (mp_cmp_d(&big2, 0) == MP_LT) {
+           if (mp_isneg(&big2)) {
                compare = MP_GT;
            } else {
                compare = MP_LT;
@@ -9415,6 +9466,7 @@ TclCompareTwoNumbers(
            mp_clear(&big2);
            return compare;
        }
+    break;
 #endif
 
     case TCL_NUMBER_DOUBLE:
@@ -9462,7 +9514,7 @@ TclCompareTwoNumbers(
            }
            Tcl_TakeBignumFromObj(NULL, value2Ptr, &big2);
            if ((d1 < (double)LONG_MAX) && (d1 > (double)LONG_MIN)) {
-               if (mp_cmp_d(&big2, 0) == MP_LT) {
+               if (mp_isneg(&big2)) {
                    compare = MP_GT;
                } else {
                    compare = MP_LT;
@@ -9479,6 +9531,7 @@ TclCompareTwoNumbers(
            Tcl_InitBignumFromDouble(NULL, d1, &big1);
            goto bigCompare;
        }
+    break;
 
     case TCL_NUMBER_BIG:
        Tcl_TakeBignumFromObj(NULL, valuePtr, &big1);
@@ -9518,10 +9571,11 @@ TclCompareTwoNumbers(
            mp_clear(&big2);
            return compare;
        }
+    break;
     default:
        Tcl_Panic("unexpected number type");
-       return TCL_ERROR;
     }
+    return TCL_ERROR;
 }
 \f
 #ifdef TCL_COMPILE_DEBUG
@@ -9545,7 +9599,7 @@ TclCompareTwoNumbers(
 
 static void
 PrintByteCodeInfo(
-    register ByteCode *codePtr)        /* The bytecode whose summary is printed to
+    ByteCode *codePtr) /* The bytecode whose summary is printed to
                                 * stdout. */
 {
     Proc *procPtr = codePtr->procPtr;
@@ -9609,7 +9663,7 @@ PrintByteCodeInfo(
 #ifdef TCL_COMPILE_DEBUG
 static void
 ValidatePcAndStackTop(
-    register ByteCode *codePtr,        /* The bytecode whose summary is printed to
+    ByteCode *codePtr, /* The bytecode whose summary is printed to
                                 * stdout. */
     const unsigned char *pc,   /* Points to first byte of a bytecode
                                 * instruction. The program counter. */
@@ -9690,12 +9744,12 @@ IllegalExprOperandType(
     ClientData ptr;
     int type;
     const unsigned char opcode = *pc;
-    const char *description, *operator = "unknown";
+    const char *description, *op = "unknown";
 
     if (opcode == INST_EXPON) {
-       operator = "**";
+       op = "**";
     } else if (opcode <= INST_LNOT) {
-       operator = operatorStrings[opcode - INST_LOR];
+       op = operatorStrings[opcode - INST_LOR];
     }
 
     if (GetNumberFromObj(NULL, opndPtr, &ptr, &type) != TCL_OK) {
@@ -9719,7 +9773,7 @@ IllegalExprOperandType(
     }
 
     Tcl_SetObjResult(interp, Tcl_ObjPrintf(
-           "can't use %s as operand of \"%s\"", description, operator));
+           "can't use %s as operand of \"%s\"", description, op));
     Tcl_SetErrorCode(interp, "ARITH", "DOMAIN", description, NULL);
 }
 \f
@@ -9852,7 +9906,7 @@ GetSrcInfoForPc(
                                 * of the command containing the pc should
                                 * be stored. */
 {
-    register int pcOffset = (pc - codePtr->codeStart);
+    int pcOffset = (pc - codePtr->codeStart);
     int numCmds = codePtr->numCommands;
     unsigned char *codeDeltaNext, *codeLengthNext;
     unsigned char *srcDeltaNext, *srcLengthNext;
@@ -10005,9 +10059,9 @@ GetExceptRangeForPc(
 {
     ExceptionRange *rangeArrayPtr;
     int numRanges = codePtr->numExceptRanges;
-    register ExceptionRange *rangePtr;
+    ExceptionRange *rangePtr;
     int pcOffset = pc - codePtr->codeStart;
-    register int start;
+    int start;
 
     if (numRanges == 0) {
        return NULL;
@@ -10139,11 +10193,11 @@ TclExprFloatError(
 
 int
 TclLog2(
-    register int value)                /* The integer for which to compute the log
+    int value)         /* The integer for which to compute the log
                                 * base 2. */
 {
-    register int n = value;
-    register int result = 0;
+    int n = value;
+    int result = 0;
 
     while (n > 1) {
        n = n >> 1;
@@ -10194,7 +10248,7 @@ EvalStatsCmd(
 
 #define Percent(a,b) ((a) * 100.0 / (b))
 
-    objPtr = Tcl_NewObj();
+    TclNewObj(objPtr);
     Tcl_IncrRefCount(objPtr);
 
     numInstructions = 0.0;
index 99372c5..e2d4164 100644 (file)
@@ -904,7 +904,7 @@ FileBasename(
        }
     }
     if (resultPtr == NULL) {
-       resultPtr = Tcl_NewObj();
+       TclNewObj(resultPtr);
     }
     Tcl_IncrRefCount(resultPtr);
     Tcl_DecrRefCount(splitPtr);
index 7afcdaf..cfd76e6 100644 (file)
@@ -242,7 +242,7 @@ ExtractWinRoot(
 
                if (path[4] == '\0') {
                    abs = 4;
-               } else if (path [4] == ':' && path[5] == '\0') {
+               } else if (path[4] == ':' && path[5] == '\0') {
                    abs = 5;
                }
 
@@ -264,7 +264,7 @@ ExtractWinRoot(
 
                if (path[4] == '\0') {
                    abs = 4;
-               } else if (path [4] == ':' && path[5] == '\0') {
+               } else if (path[4] == ':' && path[5] == '\0') {
                    abs = 5;
                }
            }
@@ -587,7 +587,8 @@ Tcl_SplitPath(
      * plus the argv pointers and the terminating NULL pointer.
      */
 
-    *argvPtr = ckalloc((((*argcPtr) + 1) * sizeof(char *)) + size);
+    *argvPtr = (const char **)ckalloc(
+           ((((*argcPtr) + 1) * sizeof(char *)) + size));
 
     /*
      * Position p after the last argv pointer and copy the contents of the
@@ -598,7 +599,7 @@ Tcl_SplitPath(
     for (i = 0; i < *argcPtr; i++) {
        Tcl_ListObjIndex(NULL, resultPtr, i, &eltPtr);
        str = Tcl_GetStringFromObj(eltPtr, &len);
-       memcpy(p, str, (size_t) len+1);
+       memcpy(p, str, len + 1);
        p += len+1;
     }
 
@@ -644,12 +645,13 @@ SplitUnixPath(
 {
     int length;
     const char *origPath = path, *elementStart;
-    Tcl_Obj *result = Tcl_NewObj();
+    Tcl_Obj *result;
 
     /*
      * Deal with the root directory as a special case.
      */
 
+    TclNewObj(result);
     if (*path == '/') {
        Tcl_Obj *rootElt;
        ++path;
@@ -735,9 +737,10 @@ SplitWinPath(
     const char *p, *elementStart;
     Tcl_PathType type = TCL_PATH_ABSOLUTE;
     Tcl_DString buf;
-    Tcl_Obj *result = Tcl_NewObj();
+    Tcl_Obj *result;
     Tcl_DStringInit(&buf);
 
+    TclNewObj(result);
     p = ExtractWinRoot(path, &buf, 0, &type);
 
     /*
@@ -821,7 +824,7 @@ Tcl_FSJoinToPath(
        return TclJoinPath(2, pair, 0);
     } else {
        int elemc = objc + 1;
-       Tcl_Obj *ret, **elemv = ckalloc(elemc*sizeof(Tcl_Obj *));
+       Tcl_Obj *ret, **elemv = (Tcl_Obj**)ckalloc(elemc*sizeof(Tcl_Obj *));
 
        elemv[0] = pathPtr;
        memcpy(elemv+1, objv, objc*sizeof(Tcl_Obj *));
@@ -977,7 +980,7 @@ Tcl_JoinPath(
     Tcl_DString *resultPtr)    /* Pointer to previously initialized DString */
 {
     int i, len;
-    Tcl_Obj *listObj = Tcl_NewObj();
+    Tcl_Obj *listObj;
     Tcl_Obj *resultObj;
     const char *resultStr;
 
@@ -985,6 +988,7 @@ Tcl_JoinPath(
      * Build the list of paths.
      */
 
+    TclNewObj(listObj);
     for (i = 0; i < argc; i++) {
        Tcl_ListObjAppendElement(NULL, listObj,
                Tcl_NewStringObj(argv[i], -1));
@@ -1072,7 +1076,7 @@ Tcl_TranslateFileName(
      */
 
     if (tclPlatform == TCL_PLATFORM_WINDOWS) {
-       register char *p;
+       char *p;
        for (p = Tcl_DStringValue(bufferPtr); *p != '\0'; p++) {
            if (*p == '/') {
                *p = '\\';
@@ -1217,7 +1221,6 @@ DoTildeSubst(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 int
 Tcl_GlobObjCmd(
     ClientData dummy,          /* Not used. */
@@ -1235,12 +1238,13 @@ Tcl_GlobObjCmd(
        "-directory", "-join", "-nocomplain", "-path", "-tails",
        "-types", "--", NULL
     };
-    enum options {
+    enum globOptionsEnum {
        GLOB_DIR, GLOB_JOIN, GLOB_NOCOMPLAIN, GLOB_PATH, GLOB_TAILS,
        GLOB_TYPE, GLOB_LAST
     };
     enum pathDirOptions {PATH_NONE = -1 , PATH_GENERAL = 0, PATH_DIR = 1};
     Tcl_GlobTypeData *globTypes = NULL;
+    (void)dummy;
 
     globFlags = 0;
     join = 0;
@@ -1268,7 +1272,7 @@ Tcl_GlobObjCmd(
            }
        }
 
-       switch (index) {
+       switch ((enum globOptionsEnum) index) {
        case GLOB_NOCOMPLAIN:                   /* -nocomplain */
            globFlags |= TCL_GLOBMODE_NO_COMPLAIN;
            break;
@@ -1281,7 +1285,10 @@ Tcl_GlobObjCmd(
            }
            if (dir != PATH_NONE) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj(
-                       "\"-directory\" cannot be used with \"-path\"", -1));
+                       dir == PATH_DIR
+                           ? "\"-directory\" may only be used once"
+                           : "\"-directory\" cannot be used with \"-path\"",
+                       -1));
                Tcl_SetErrorCode(interp, "TCL", "OPERATION", "GLOB",
                        "BADOPTIONCOMBINATION", NULL);
                return TCL_ERROR;
@@ -1306,7 +1313,10 @@ Tcl_GlobObjCmd(
            }
            if (dir != PATH_NONE) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj(
-                       "\"-path\" cannot be used with \"-directory\"", -1));
+                       dir == PATH_GENERAL
+                           ? "\"-path\" may only be used once"
+                           : "\"-path\" cannot be used with \"-dictionary\"",
+                       -1));
                Tcl_SetErrorCode(interp, "TCL", "OPERATION", "GLOB",
                        "BADOPTIONCOMBINATION", NULL);
                return TCL_ERROR;
@@ -1344,7 +1354,7 @@ Tcl_GlobObjCmd(
        return TCL_ERROR;
     }
 
-    separators = NULL;         /* lint. */
+    separators = NULL;
     switch (tclPlatform) {
     case TCL_PLATFORM_UNIX:
        separators = "/";
@@ -1449,7 +1459,7 @@ Tcl_GlobObjCmd(
        if (length <= 0) {
            goto skipTypes;
        }
-       globTypes = TclStackAlloc(interp, sizeof(Tcl_GlobTypeData));
+       globTypes = (Tcl_GlobTypeData *)TclStackAlloc(interp, sizeof(Tcl_GlobTypeData));
        globTypes->type = 0;
        globTypes->perm = 0;
        globTypes->macType = NULL;
@@ -1680,9 +1690,8 @@ Tcl_GlobObjCmd(
  *
  * TclGlob --
  *
- *     This procedure prepares arguments for the DoGlob call. It sets the
- *     separator string based on the platform, performs * tilde substitution,
- *     and calls DoGlob.
+ *     Sets the separator string based on the platform, performs tilde
+ *     substitution, and calls DoGlob.
  *
  *     The interpreter's result, on entry to this function, must be a valid
  *     Tcl list (e.g. it could be empty), since we will lappend any new
@@ -1705,7 +1714,6 @@ Tcl_GlobObjCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 int
 TclGlob(
     Tcl_Interp *interp,                /* Interpreter for returning error message or
@@ -1724,7 +1732,7 @@ TclGlob(
     int result;
     Tcl_Obj *filenamesObj, *savedResultObj;
 
-    separators = NULL;         /* lint. */
+    separators = NULL;
     switch (tclPlatform) {
     case TCL_PLATFORM_UNIX:
        separators = "/";
@@ -2058,7 +2066,7 @@ TclGlob(
  * SkipToChar --
  *
  *     This function traverses a glob pattern looking for the next unquoted
- *     occurance of the specified character at the same braces nesting level.
+ *     occurrence of the specified character at the same braces nesting level.
  *
  * Results:
  *     Updates stringPtr to point to the matching character, or to the end of
@@ -2077,7 +2085,7 @@ SkipToChar(
     int match)                 /* Character to find. */
 {
     int quoted, level;
-    register char *p;
+    char *p;
 
     quoted = 0;
     level = 0;
@@ -2448,7 +2456,7 @@ DoGlob(
                int len;
                const char *joined = Tcl_GetStringFromObj(joinedPtr,&len);
 
-               if (strchr(separators, joined[len-1]) == NULL) {
+               if ((len > 0) && (strchr(separators, joined[len-1]) == NULL)) {
                    Tcl_AppendToObj(joinedPtr, "/", 1);
                }
            }
@@ -2485,7 +2493,7 @@ DoGlob(
            int len;
            const char *joined = Tcl_GetStringFromObj(joinedPtr,&len);
 
-           if (strchr(separators, joined[len-1]) == NULL) {
+           if ((len > 0) && (strchr(separators, joined[len-1]) == NULL)) {
                if (Tcl_FSGetPathType(pathPtr) != TCL_PATH_VOLUME_RELATIVE) {
                    Tcl_AppendToObj(joinedPtr, "/", 1);
                }
@@ -2523,7 +2531,7 @@ DoGlob(
 Tcl_StatBuf *
 Tcl_AllocStatBuf(void)
 {
-    return ckalloc(sizeof(Tcl_StatBuf));
+    return (Tcl_StatBuf *)ckalloc(sizeof(Tcl_StatBuf));
 }
 \f
 /*
@@ -2628,7 +2636,7 @@ Tcl_GetBlocksFromStat(
 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
     return (Tcl_WideUInt) statPtr->st_blocks;
 #else
-    register unsigned blksize = Tcl_GetBlockSizeFromStat(statPtr);
+    unsigned blksize = Tcl_GetBlockSizeFromStat(statPtr);
 
     return ((Tcl_WideUInt) statPtr->st_size + blksize - 1) / blksize;
 #endif
index ce7c2ce..e6748a4 100644 (file)
@@ -7,7 +7,7 @@
  *     only used when doing free-form date parsing, an ill-defined process
  *     anyway.
  *
- * Copyright (c) 1992-1995 Karl Lehenbauer and Mark Diekhans.
+ * Copyright (c) 1992-1995 Karl Lehenbauer & Mark Diekhans.
  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
  *
  * See the file "license.terms" for information on usage and redistribution of
@@ -16,7 +16,7 @@
 
 %parse-param {DateInfo* info}
 %lex-param {DateInfo* info}
-%pure-parser
+%define api.pure
  /* %error-verbose would be nice, but our token names are meaningless */
 %locations
 
@@ -27,7 +27,7 @@
  *     This file is generated from a yacc grammar defined in the file
  *     tclGetDate.y. It should not be edited directly.
  *
- * Copyright (c) 1992-1995 Karl Lehenbauer and Mark Diekhans.
+ * Copyright (c) 1992-1995 Karl Lehenbauer & Mark Diekhans.
  * Copyright (c) 1995-1997 Sun Microsystems, Inc.
  *
  * See the file "license.terms" for information on usage and redistribution of
 #endif /* _MSC_VER */
 
 /*
+ * Meridian: am, pm, or 24-hour style.
+ */
+
+typedef enum _MERIDIAN {
+    MERam, MERpm, MER24
+} MERIDIAN;
+
+/*
  * yyparse will accept a 'struct DateInfo' as its parameter; that's where the
  * parsed fields will be returned.
  */
@@ -63,7 +71,7 @@ typedef struct DateInfo {
     time_t dateHour;
     time_t dateMinutes;
     time_t dateSeconds;
-    int dateMeridian;
+    MERIDIAN dateMeridian;
     int dateHaveTime;
 
     time_t dateTimezone;
@@ -150,14 +158,6 @@ typedef enum _DSTMODE {
     DSTon, DSToff, DSTmaybe
 } DSTMODE;
 
-/*
- * Meridian: am, pm, or 24-hour style.
- */
-
-typedef enum _MERIDIAN {
-    MERam, MERpm, MER24
-} MERIDIAN;
-
 %}
 
 %union {
@@ -266,43 +266,32 @@ time      : tUNUMBER tMERIDIAN {
            yySeconds = 0;
            yyMeridian = $4;
        }
-       | tUNUMBER ':' tUNUMBER '-' tUNUMBER {
-           yyHour = $1;
-           yyMinutes = $3;
-           yyMeridian = MER24;
-           yyDSTmode = DSToff;
-           yyTimezone = ($5 % 100 + ($5 / 100) * 60);
-           ++yyHaveZone;
-       }
        | tUNUMBER ':' tUNUMBER ':' tUNUMBER o_merid {
            yyHour = $1;
            yyMinutes = $3;
            yySeconds = $5;
            yyMeridian = $6;
        }
-       | tUNUMBER ':' tUNUMBER ':' tUNUMBER '-' tUNUMBER {
-           yyHour = $1;
-           yyMinutes = $3;
-           yySeconds = $5;
-           yyMeridian = MER24;
-           yyDSTmode = DSToff;
-           yyTimezone = ($7 % 100 + ($7 / 100) * 60);
-           ++yyHaveZone;
-       }
        ;
 
 zone   : tZONE tDST {
            yyTimezone = $1;
+           if (yyTimezone > HOUR( 12)) yyTimezone -= HOUR(100);
            yyDSTmode = DSTon;
        }
        | tZONE {
            yyTimezone = $1;
+           if (yyTimezone > HOUR( 12)) yyTimezone -= HOUR(100);
            yyDSTmode = DSToff;
        }
        | tDAYZONE {
            yyTimezone = $1;
            yyDSTmode = DSTon;
        }
+       | sign tUNUMBER {
+           yyTimezone = -$1*($2 % 100 + ($2 / 100) * 60);
+           yyDSTmode = DSToff;
+       }
        ;
 
 day    : tDAY {
@@ -386,8 +375,18 @@ ordMonth: tNEXT tMONTH {
        }
        ;
 
-iso    : tISOBASE tZONE tISOBASE {
-           if ($2 != HOUR( 7)) YYABORT;
+iso    : tUNUMBER '-' tUNUMBER '-' tUNUMBER tZONE
+               tUNUMBER ':' tUNUMBER ':' tUNUMBER {
+           if ($6 != HOUR( 7) + HOUR(100)) YYABORT;
+           yyYear = $1;
+           yyMonth = $3;
+           yyDay = $5;
+           yyHour = $7;
+           yyMinutes = $9;
+           yySeconds = $11;
+       }
+       | tISOBASE tZONE tISOBASE {
+           if ($2 != HOUR( 7) + HOUR(100)) YYABORT;
            yyYear = $1 / 10000;
            yyMonth = ($1 % 10000)/100;
            yyDay = $1 % 100;
@@ -396,7 +395,7 @@ iso : tISOBASE tZONE tISOBASE {
            yySeconds = $3 % 100;
        }
        | tISOBASE tZONE tUNUMBER ':' tUNUMBER ':' tUNUMBER {
-           if ($2 != HOUR( 7)) YYABORT;
+           if ($2 != HOUR( 7) + HOUR(100)) YYABORT;
            yyYear = $1 / 10000;
            yyMonth = ($1 % 10000)/100;
            yyDay = $1 % 100;
@@ -675,31 +674,31 @@ static const TABLE TimezoneTable[] = {
  */
 
 static const TABLE MilitaryTable[] = {
-    { "a",     tZONE,  -HOUR( 1) },
-    { "b",     tZONE,  -HOUR( 2) },
-    { "c",     tZONE,  -HOUR( 3) },
-    { "d",     tZONE,  -HOUR( 4) },
-    { "e",     tZONE,  -HOUR( 5) },
-    { "f",     tZONE,  -HOUR( 6) },
-    { "g",     tZONE,  -HOUR( 7) },
-    { "h",     tZONE,  -HOUR( 8) },
-    { "i",     tZONE,  -HOUR( 9) },
-    { "k",     tZONE,  -HOUR(10) },
-    { "l",     tZONE,  -HOUR(11) },
-    { "m",     tZONE,  -HOUR(12) },
-    { "n",     tZONE,  HOUR(  1) },
-    { "o",     tZONE,  HOUR(  2) },
-    { "p",     tZONE,  HOUR(  3) },
-    { "q",     tZONE,  HOUR(  4) },
-    { "r",     tZONE,  HOUR(  5) },
-    { "s",     tZONE,  HOUR(  6) },
-    { "t",     tZONE,  HOUR(  7) },
-    { "u",     tZONE,  HOUR(  8) },
-    { "v",     tZONE,  HOUR(  9) },
-    { "w",     tZONE,  HOUR( 10) },
-    { "x",     tZONE,  HOUR( 11) },
-    { "y",     tZONE,  HOUR( 12) },
-    { "z",     tZONE,  HOUR( 0) },
+    { "a",     tZONE,  -HOUR( 1) + HOUR(100) },
+    { "b",     tZONE,  -HOUR( 2) + HOUR(100) },
+    { "c",     tZONE,  -HOUR( 3) + HOUR(100) },
+    { "d",     tZONE,  -HOUR( 4) + HOUR(100) },
+    { "e",     tZONE,  -HOUR( 5) + HOUR(100) },
+    { "f",     tZONE,  -HOUR( 6) + HOUR(100) },
+    { "g",     tZONE,  -HOUR( 7) + HOUR(100) },
+    { "h",     tZONE,  -HOUR( 8) + HOUR(100) },
+    { "i",     tZONE,  -HOUR( 9) + HOUR(100) },
+    { "k",     tZONE,  -HOUR(10) + HOUR(100) },
+    { "l",     tZONE,  -HOUR(11) + HOUR(100) },
+    { "m",     tZONE,  -HOUR(12) + HOUR(100) },
+    { "n",     tZONE,  HOUR(  1) + HOUR(100) },
+    { "o",     tZONE,  HOUR(  2) + HOUR(100) },
+    { "p",     tZONE,  HOUR(  3) + HOUR(100) },
+    { "q",     tZONE,  HOUR(  4) + HOUR(100) },
+    { "r",     tZONE,  HOUR(  5) + HOUR(100) },
+    { "s",     tZONE,  HOUR(  6) + HOUR(100) },
+    { "t",     tZONE,  HOUR(  7) + HOUR(100) },
+    { "u",     tZONE,  HOUR(  8) + HOUR(100) },
+    { "v",     tZONE,  HOUR(  9) + HOUR(100) },
+    { "w",     tZONE,  HOUR( 10) + HOUR(100) },
+    { "x",     tZONE,  HOUR( 11) + HOUR(100) },
+    { "y",     tZONE,  HOUR( 12) + HOUR(100) },
+    { "z",     tZONE,  HOUR( 0)  + HOUR(100) },
     { NULL, 0, 0 }
 };
 
@@ -717,12 +716,12 @@ TclDateerror(
     Tcl_AppendToObj(infoPtr->messages, infoPtr->separatrix, -1);
     Tcl_AppendToObj(infoPtr->messages, s, -1);
     Tcl_AppendToObj(infoPtr->messages, " (characters ", -1);
-    t = Tcl_NewIntObj(location->first_column);
+    TclNewIntObj(t, location->first_column);
     Tcl_IncrRefCount(t);
     Tcl_AppendObjToObj(infoPtr->messages, t);
     Tcl_DecrRefCount(t);
     Tcl_AppendToObj(infoPtr->messages, "-", -1);
-    t = Tcl_NewIntObj(location->last_column);
+    TclNewIntObj(t, location->last_column);
     Tcl_IncrRefCount(t);
     Tcl_AppendObjToObj(infoPtr->messages, t);
     Tcl_DecrRefCount(t);
@@ -765,9 +764,9 @@ LookupWord(
     YYSTYPE* yylvalPtr,
     char *buff)
 {
-    register char *p;
-    register char *q;
-    register const TABLE *tp;
+    char *p;
+    char *q;
+    const TABLE *tp;
     int i, abbrev;
 
     /*
@@ -890,14 +889,14 @@ TclDatelex(
     YYLTYPE* location,
     DateInfo *info)
 {
-    register char c;
-    register char *p;
+    char c;
+    char *p;
     char buff[20];
     int Count;
 
     location->first_column = yyInput - info->dateStart;
     for ( ; ; ) {
-       while (TclIsSpaceProc(*yyInput)) {
+       while (TclIsSpaceProcM(*yyInput)) {
            yyInput++;
        }
 
@@ -960,7 +959,7 @@ TclDatelex(
 
 int
 TclClockOldscanObjCmd(
-    ClientData clientData,     /* Unused */
+    void *dummy,               /* Unused */
     Tcl_Interp *interp,                /* Tcl interpreter */
     int objc,                  /* Count of paraneters */
     Tcl_Obj *const *objv)      /* Parameters */
@@ -970,6 +969,7 @@ TclClockOldscanObjCmd(
     DateInfo dateInfo;
     DateInfo* info = &dateInfo;
     int status;
+    (void)dummy;
 
     if (objc != 5) {
        Tcl_WrongNumArgs(interp, 1, objv,
@@ -1003,7 +1003,7 @@ TclClockOldscanObjCmd(
     yyHaveRel = 0;
     yyRelMonth = 0; yyRelDay = 0; yyRelSeconds = 0; yyRelPointer = NULL;
 
-    dateInfo.messages = Tcl_NewObj();
+    TclNewObj(dateInfo.messages);
     dateInfo.separatrix = "";
     Tcl_IncrRefCount(dateInfo.messages);
 
@@ -1060,8 +1060,8 @@ TclClockOldscanObjCmd(
        return TCL_ERROR;
     }
 
-    result = Tcl_NewObj();
-    resultElement = Tcl_NewObj();
+    TclNewObj(result);
+    TclNewObj(resultElement);
     if (yyHaveDate) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyYear));
@@ -1074,12 +1074,12 @@ TclClockOldscanObjCmd(
 
     if (yyHaveTime) {
        Tcl_ListObjAppendElement(interp, result, Tcl_NewIntObj((int)
-               ToSeconds(yyHour, yyMinutes, yySeconds, yyMeridian)));
+               ToSeconds(yyHour, yyMinutes, yySeconds, (MERIDIAN)yyMeridian)));
     } else {
        Tcl_ListObjAppendElement(interp, result, Tcl_NewObj());
     }
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveZone) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) -yyTimezone));
@@ -1088,7 +1088,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveRel) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyRelMonth));
@@ -1099,7 +1099,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TcNewObj(resultElement);
     if (yyHaveDay && !yyHaveDate) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyDayOrdinal));
@@ -1108,7 +1108,7 @@ TclClockOldscanObjCmd(
     }
     Tcl_ListObjAppendElement(interp, result, resultElement);
 
-    resultElement = Tcl_NewObj();
+    TclNewObj(resultElement);
     if (yyHaveOrdinalMonth) {
        Tcl_ListObjAppendElement(interp, resultElement,
                Tcl_NewIntObj((int) yyMonthOrdinal));
index 193664d..bcf6eee 100644 (file)
@@ -126,7 +126,7 @@ const Tcl_HashKeyType tclStringHashKeyType = {
 
 void
 Tcl_InitHashTable(
-    register Tcl_HashTable *tablePtr,
+    Tcl_HashTable *tablePtr,
                                /* Pointer to table record, which is supplied
                                 * by the caller. */
     int keyType)               /* Type of keys to use in table:
@@ -164,7 +164,7 @@ Tcl_InitHashTable(
 
 void
 Tcl_InitCustomHashTable(
-    register Tcl_HashTable *tablePtr,
+    Tcl_HashTable *tablePtr,
                                /* Pointer to table record, which is supplied
                                 * by the caller. */
     int keyType,               /* Type of keys to use in table:
@@ -284,7 +284,7 @@ CreateHashEntry(
     int *newPtr)               /* Store info here telling whether a new entry
                                 * was created. */
 {
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     const Tcl_HashKeyType *typePtr;
     unsigned int hash;
     int index;
@@ -415,7 +415,7 @@ void
 Tcl_DeleteHashEntry(
     Tcl_HashEntry *entryPtr)
 {
-    register Tcl_HashEntry *prevPtr;
+    Tcl_HashEntry *prevPtr;
     const Tcl_HashKeyType *typePtr;
     Tcl_HashTable *tablePtr;
     Tcl_HashEntry **bucketPtr;
@@ -490,9 +490,9 @@ Tcl_DeleteHashEntry(
 
 void
 Tcl_DeleteHashTable(
-    register Tcl_HashTable *tablePtr)  /* Table to delete. */
+    Tcl_HashTable *tablePtr)   /* Table to delete. */
 {
-    register Tcl_HashEntry *hPtr, *nextPtr;
+    Tcl_HashEntry *hPtr, *nextPtr;
     const Tcl_HashKeyType *typePtr;
     int i;
 
@@ -598,7 +598,7 @@ Tcl_FirstHashEntry(
 
 Tcl_HashEntry *
 Tcl_NextHashEntry(
-    register Tcl_HashSearch *searchPtr)
+    Tcl_HashSearch *searchPtr)
                                /* Place to store information about progress
                                 * through the table. Must have been
                                 * initialized by calling
@@ -645,7 +645,7 @@ Tcl_HashStats(
 #define NUM_COUNTERS 10
     int count[NUM_COUNTERS], overflow, i, j;
     double average, tmp;
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     char *result, *p;
 
     /*
@@ -715,7 +715,7 @@ AllocArrayEntry(
     void *keyPtr)              /* Key to store in the hash table entry. */
 {
     int *array = (int *) keyPtr;
-    register int *iPtr1, *iPtr2;
+    int *iPtr1, *iPtr2;
     Tcl_HashEntry *hPtr;
     int count;
     unsigned int size;
@@ -759,8 +759,8 @@ CompareArrayKeys(
     void *keyPtr,              /* New key to compare. */
     Tcl_HashEntry *hPtr)       /* Existing key to compare. */
 {
-    register const int *iPtr1 = (const int *) keyPtr;
-    register const int *iPtr2 = (const int *) hPtr->key.words;
+    const int *iPtr1 = (const int *) keyPtr;
+    const int *iPtr2 = (const int *) hPtr->key.words;
     Tcl_HashTable *tablePtr = hPtr->tablePtr;
     int count;
 
@@ -798,8 +798,8 @@ HashArrayKey(
     Tcl_HashTable *tablePtr,   /* Hash table. */
     void *keyPtr)              /* Key from which to compute hash value. */
 {
-    register const int *array = (const int *) keyPtr;
-    register unsigned int result;
+    const int *array = (const int *) keyPtr;
+    unsigned int result;
     int count;
 
     for (result = 0, count = tablePtr->keyType; count > 0;
@@ -867,8 +867,8 @@ CompareStringKeys(
     void *keyPtr,              /* New key to compare. */
     Tcl_HashEntry *hPtr)       /* Existing key to compare. */
 {
-    register const char *p1 = (const char *) keyPtr;
-    register const char *p2 = (const char *) hPtr->key.string;
+    const char *p1 = (const char *) keyPtr;
+    const char *p2 = (const char *) hPtr->key.string;
 
     return !strcmp(p1, p2);
 }
@@ -895,9 +895,9 @@ HashStringKey(
     Tcl_HashTable *tablePtr,   /* Hash table. */
     void *keyPtr)              /* Key from which to compute hash value. */
 {
-    register const char *string = keyPtr;
-    register unsigned int result;
-    register char c;
+    const char *string = keyPtr;
+    unsigned int result;
+    char c;
 
     /*
      * I tried a zillion different hash functions and asked many other people
@@ -1016,12 +1016,12 @@ BogusCreate(
 
 static void
 RebuildTable(
-    register Tcl_HashTable *tablePtr)  /* Table to enlarge. */
+    Tcl_HashTable *tablePtr)   /* Table to enlarge. */
 {
     int count, index, oldSize = tablePtr->numBuckets;
     Tcl_HashEntry **oldBuckets = tablePtr->buckets;
-    register Tcl_HashEntry **oldChainPtr, **newChainPtr;
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry **oldChainPtr, **newChainPtr;
+    Tcl_HashEntry *hPtr;
     const Tcl_HashKeyType *typePtr;
 
     /* Avoid outgrowing capability of the memory allocators */
index b08e352..24f6d65 100644 (file)
@@ -61,7 +61,7 @@ Tcl_RecordAndEval(
                                 * TCL_EVAL_GLOBAL means use Tcl_GlobalEval
                                 * instead of Tcl_Eval. */
 {
-    register Tcl_Obj *cmdPtr;
+    Tcl_Obj *cmdPtr;
     int length = strlen(cmd);
     int result;
 
@@ -214,7 +214,7 @@ DeleteHistoryObjs(
     ClientData clientData,
     Tcl_Interp *interp)
 {
-    register HistoryObjs *histObjsPtr = clientData;
+    HistoryObjs *histObjsPtr = clientData;
 
     TclDecrRefCount(histObjsPtr->historyObj);
     TclDecrRefCount(histObjsPtr->addObj);
index ff04636..349e717 100644 (file)
@@ -200,12 +200,10 @@ static int                FilterInputBytes(Channel *chanPtr,
 static int             FlushChannel(Tcl_Interp *interp, Channel *chanPtr,
                            int calledFromAsyncFlush);
 static int             TclGetsObjBinary(Tcl_Channel chan, Tcl_Obj *objPtr);
-static Tcl_Encoding    GetBinaryEncoding();
+static Tcl_Encoding    GetBinaryEncoding(void);
 static void            FreeBinaryEncoding(ClientData clientData);
 static Tcl_HashTable * GetChannelTable(Tcl_Interp *interp);
 static int             GetInput(Channel *chanPtr);
-static int             HaveVersion(const Tcl_ChannelType *typePtr,
-                           Tcl_ChannelTypeVersion minimumVersion);
 static void            PeekAhead(Channel *chanPtr, char **dstEndPtr,
                            GetsState *gsPtr);
 static int             ReadBytes(ChannelState *statePtr, Tcl_Obj *objPtr,
@@ -289,9 +287,9 @@ static int              WillRead(Channel *chanPtr);
 
 #define IsBufferOverflowing(bufPtr) ((bufPtr)->nextAdded>(bufPtr)->bufLength)
 
-#define InsertPoint(bufPtr)    ((bufPtr)->buf + (bufPtr)->nextAdded)
+#define InsertPoint(bufPtr)    (&(bufPtr)->buf[(bufPtr)->nextAdded])
 
-#define RemovePoint(bufPtr)    ((bufPtr)->buf + (bufPtr)->nextRemoved)
+#define RemovePoint(bufPtr)    (&(bufPtr)->buf[(bufPtr)->nextRemoved])
 
 /*
  * For working with channel state flag bits.
@@ -367,34 +365,25 @@ ChanClose(
     }
 }
 
-static inline int
-ChanCloseHalf(
-    Channel *chanPtr,
-    Tcl_Interp *interp,
-    int flags)
-{
-    return chanPtr->typePtr->close2Proc(chanPtr->instanceData, interp, flags);
-}
-
 /*
  *---------------------------------------------------------------------------
  *
  * ChanRead --
  *
- *     Read up to dstSize bytes using the inputProc of chanPtr, store
- *     them at dst, and return the number of bytes stored.
+ *     Read up to dstSize bytes using the inputProc of chanPtr, store them at
+ *     dst, and return the number of bytes stored.
  *
  * Results:
  *     The return value of the driver inputProc,
  *       - number of bytes stored at dst, ot
- *       - -1 on error, with a Posix error code available to the
- *         caller by calling Tcl_GetErrno().
+ *       - -1 on error, with a Posix error code available to the caller by
+ *         calling Tcl_GetErrno().
  *
  * Side effects:
- *     The CHANNEL_BLOCKED and CHANNEL_EOF flags of the channel state are
- *     set as appropriate.
- *     On EOF, the inputEncodingFlags are set to perform ending operations
- *     on decoding.
+ *     The CHANNEL_BLOCKED and CHANNEL_EOF flags of the channel state are set
+ *     as appropriate.  On EOF, the inputEncodingFlags are set to perform
+ *     ending operations on decoding.
+ *
  *     TODO - Is this really the right place for that?
  *
  *---------------------------------------------------------------------------
@@ -408,15 +397,17 @@ ChanRead(
     int bytesRead, result;
 
     /*
-     * If the caller asked for zero bytes, we'd force the inputProc
-     * to return zero bytes, and then misinterpret that as EOF.
+     * If the caller asked for zero bytes, we'd force the inputProc to return
+     * zero bytes, and then misinterpret that as EOF.
      */
+
     assert(dstSize > 0);
 
     /*
      * Each read op must set the blocked and eof states anew, not let
      * the effect of prior reads leak through.
      */
+
     if (GotFlag(chanPtr->state, CHANNEL_EOF)) {
         chanPtr->state->inputEncodingFlags |= TCL_ENCODING_START;
     }
@@ -429,7 +420,10 @@ ChanRead(
     bytesRead = chanPtr->typePtr->inputProc(chanPtr->instanceData,
            dst, dstSize, &result);
 
-    /* Stop any flag leakage through stacked channel levels */
+    /*
+     * Stop any flag leakage through stacked channel levels.
+     */
+
     if (GotFlag(chanPtr->state, CHANNEL_EOF)) {
         chanPtr->state->inputEncodingFlags |= TCL_ENCODING_START;
     }
@@ -437,10 +431,10 @@ ChanRead(
     chanPtr->state->inputEncodingFlags &= ~TCL_ENCODING_END;
     if (bytesRead > 0) {
        /*
-        * If we get a short read, signal up that we may be BLOCKED.
-        * We should avoid calling the driver because on some
-        * platforms we will block in the low level reading code even
-        * though the channel is set into nonblocking mode.
+        * If we get a short read, signal up that we may be BLOCKED. We should
+        * avoid calling the driver because on some platforms we will block in
+        * the low level reading code even though the channel is set into
+        * nonblocking mode.
         */
 
        if (bytesRead < dstSize) {
@@ -471,9 +465,8 @@ ChanSeek(
      * type and non-NULL.
      */
 
-    if (HaveVersion(chanPtr->typePtr, TCL_CHANNEL_VERSION_3) &&
-           chanPtr->typePtr->wideSeekProc != NULL) {
-       return chanPtr->typePtr->wideSeekProc(chanPtr->instanceData,
+    if (Tcl_ChannelWideSeekProc(chanPtr->typePtr) != NULL) {
+       return Tcl_ChannelWideSeekProc(chanPtr->typePtr)(chanPtr->instanceData,
                offset, mode, errnoPtr);
     }
 
@@ -482,7 +475,7 @@ ChanSeek(
        return Tcl_LongAsWide(-1);
     }
 
-    return Tcl_LongAsWide(chanPtr->typePtr->seekProc(chanPtr->instanceData,
+    return Tcl_LongAsWide(Tcl_ChannelSeekProc(chanPtr->typePtr)(chanPtr->instanceData,
            Tcl_WideAsLong(offset), mode, errnoPtr));
 }
 
@@ -574,7 +567,10 @@ TclFinalizeIOSubsystem(void)
     int active = 1;            /* Flag == 1 while there's still work to do */
     int doflushnb;
 
-    /* Fetch the pre-TIP#398 compatibility flag */
+    /*
+     * Fetch the pre-TIP#398 compatibility flag.
+     */
+
     {
         const char *s;
         Tcl_DString ds;
@@ -619,18 +615,20 @@ TclFinalizeIOSubsystem(void)
         */
 
        if (active) {
-
            TclChannelPreserve((Tcl_Channel)chanPtr);
+
            /*
-            * TIP #398:  by default, we no  longer set the  channel back into
-             * blocking  mode.  To  restore  the old  blocking  behavior,  the
-             * environment variable  TCL_FLUSH_NONBLOCKING_ON_EXIT must be set
+            * TIP #398: by default, we no longer set the channel back into
+             * blocking mode.  To restore the old blocking behavior, the
+             * environment variable TCL_FLUSH_NONBLOCKING_ON_EXIT must be set
              * and not be "0".
             */
+
             if (doflushnb) {
-                    /* Set the channel back into blocking mode to ensure that we wait
-                     * for all data to flush out.
-                     */
+                /*
+                 * Set the channel back into blocking mode to ensure that we
+                 * wait for all data to flush out.
+                 */
 
                 (void) Tcl_SetChannelOption(NULL, (Tcl_Channel) chanPtr,
                                             "-blocking", "on");
@@ -834,7 +832,7 @@ Tcl_CreateCloseHandler(
     ChannelState *statePtr = ((Channel *) chan)->state;
     CloseCallback *cbPtr;
 
-    cbPtr = ckalloc(sizeof(CloseCallback));
+    cbPtr = (CloseCallback *)ckalloc(sizeof(CloseCallback));
     cbPtr->proc = proc;
     cbPtr->clientData = clientData;
 
@@ -913,9 +911,9 @@ GetChannelTable(
     Tcl_HashTable *hTblPtr;    /* Hash table of channels. */
     Tcl_Channel stdinChan, stdoutChan, stderrChan;
 
-    hTblPtr = Tcl_GetAssocData(interp, "tclIO", NULL);
+    hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclIO", NULL);
     if (hTblPtr == NULL) {
-       hTblPtr = ckalloc(sizeof(Tcl_HashTable));
+       hTblPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
        Tcl_InitHashTable(hTblPtr, TCL_STRING_KEYS);
        Tcl_SetAssocData(interp, "tclIO",
                (Tcl_InterpDeleteProc *) DeleteChannelTable, hTblPtr);
@@ -983,10 +981,10 @@ DeleteChannelTable(
      * refcount reaches zero.
      */
 
-    hTblPtr = clientData;
+    hTblPtr = (Tcl_HashTable *)clientData;
     for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch); hPtr != NULL;
            hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch)) {
-       chanPtr = Tcl_GetHashValue(hPtr);
+       chanPtr = (Channel *)Tcl_GetHashValue(hPtr);
        statePtr = chanPtr->state;
 
        /*
@@ -1353,7 +1351,7 @@ DetachChannel(
     statePtr = chanPtr->state;
 
     if (interp != NULL) {
-       hTblPtr = Tcl_GetAssocData(interp, "tclIO", NULL);
+       hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclIO", NULL);
        if (hTblPtr == NULL) {
            return TCL_ERROR;
        }
@@ -1456,7 +1454,7 @@ Tcl_GetChannel(
      * compensate where necessary to retrieve the topmost channel again.
      */
 
-    chanPtr = Tcl_GetHashValue(hPtr);
+    chanPtr = (Channel *)Tcl_GetHashValue(hPtr);
     chanPtr = chanPtr->state->bottomChanPtr;
     if (modePtr != NULL) {
        *modePtr = chanPtr->state->flags & (TCL_READABLE|TCL_WRITABLE);
@@ -1500,6 +1498,7 @@ TclGetChannelFromObj(
     ChannelState *statePtr;
     ResolvedChanName *resPtr = NULL;
     Tcl_Channel chan;
+    (void)flags;
 
     if (interp == NULL) {
        return TCL_ERROR;
@@ -1515,8 +1514,10 @@ TclGetChannelFromObj(
        if ((resPtr->interp == interp)          /* Same interp context */
                        /* No epoch change in channel since lookup */
                && (resPtr->epoch == statePtr->epoch)) {
+           /*
+            * Have a valid saved lookup. Jump to end to return it.
+            */
 
-           /* Have a valid saved lookup. Jump to end to return it. */
            goto valid;
        }
     }
@@ -1622,8 +1623,8 @@ Tcl_CreateChannel(
      * assignments to 0/NULL below.
      */
 
-    chanPtr = ckalloc(sizeof(Channel));
-    statePtr = ckalloc(sizeof(ChannelState));
+    chanPtr = (Channel *)ckalloc(sizeof(Channel));
+    statePtr = (ChannelState *)ckalloc(sizeof(ChannelState));
     chanPtr->state = statePtr;
 
     chanPtr->instanceData = instanceData;
@@ -1642,10 +1643,10 @@ Tcl_CreateChannel(
          * later.
          */
 
-       tmp = ckalloc((len < 7) ? 7 : len);
+       tmp = (char *)ckalloc((len < 7) ? 7 : len);
        strcpy(tmp, chanName);
     } else {
-       tmp = ckalloc(7);
+       tmp = (char *)ckalloc(7);
        tmp[0] = '\0';
     }
     statePtr->channelName = tmp;
@@ -1675,7 +1676,7 @@ Tcl_CreateChannel(
      * Set the channel up initially in AUTO input translation mode to accept
      * "\n", "\r" and "\r\n". Output translation mode is set to a platform
      * specific default value. The eofChar is set to 0 for both input and
-     * output, so that Tcl does not look for an in-file EOF indicator (e.g.
+     * output, so that Tcl does not look for an in-file EOF indicator (e.g.,
      * ^Z) and does not append an EOF indicator to files.
      */
 
@@ -1903,7 +1904,6 @@ Tcl_StackChannel(
      */
 
     if (((mask & TCL_READABLE) != 0) && (statePtr->inQueueHead != NULL)) {
-
        /*
         * When statePtr->inQueueHead is not NULL, we know
         * prevChanPtr->inQueueHead must be NULL.
@@ -1919,7 +1919,7 @@ Tcl_StackChannel(
        statePtr->inQueueTail = NULL;
     }
 
-    chanPtr = ckalloc(sizeof(Channel));
+    chanPtr = (Channel *)ckalloc(sizeof(Channel));
 
     /*
      * Save some of the current state into the new structure, reinitialize the
@@ -2035,9 +2035,7 @@ Tcl_UnstackChannel(
         * of registered channels we wind down the state of the
         * transformation, and then restore the state of underlying channel
         * into the old structure.
-        */
-
-       /*
+        *
         * TODO: Figure out how to handle the situation where the chan
         * operations called below by this unstacking operation cause
         * another unstacking recursively.  In that case the downChanPtr
@@ -2450,7 +2448,7 @@ AllocChannelBuffer(
     int n;
 
     n = length + CHANNELBUFFER_HEADER_SIZE + BUFFER_PADDING + BUFFER_PADDING;
-    bufPtr = ckalloc(n);
+    bufPtr = (ChannelBuffer *)ckalloc(n);
     bufPtr->nextAdded  = BUFFER_PADDING;
     bufPtr->nextRemoved        = BUFFER_PADDING;
     bufPtr->bufLength  = length + BUFFER_PADDING;
@@ -2515,6 +2513,7 @@ RecycleBuffer(
     /*
      * Do we have to free the buffer to the OS?
      */
+
     if (IsShared(bufPtr)) {
        mustDiscard = 1;
     }
@@ -2525,9 +2524,8 @@ RecycleBuffer(
     }
 
     /*
-     * Only save buffers which have the requested buffersize for the
-     * channel. This is to honor dynamic changes of the buffersize
-     * made by the user.
+     * Only save buffers which have the requested buffersize for the channel.
+     * This is to honor dynamic changes of the buffersize made by the user.
      */
 
     if ((bufPtr->bufLength - BUFFER_PADDING) != statePtr->bufSize) {
@@ -2697,14 +2695,18 @@ FlushChannel(
     /*
      * Should we shift the current output buffer over to the output queue?
      * First check that there are bytes in it.  If so then...
-     * If the output queue is empty, then yes, trusting the caller called
-     * us only when written bytes ought to be flushed.
-     * If the current output buffer is full, then yes, so we can meet
-     * the post-condition that on a successful return to caller we've
-     * left space in the current output buffer for more writing (the flush
-     * call was to make new room).
-     * If the channel is blocking, then yes, so we guarantee that
-     * blocking flushes actually flush all pending data.
+     *
+     * If the output queue is empty, then yes, trusting the caller called us
+     * only when written bytes ought to be flushed.
+     *
+     * If the current output buffer is full, then yes, so we can meet the
+     * post-condition that on a successful return to caller we've left space
+     * in the current output buffer for more writing (the flush call was to
+     * make new room).
+     *
+     * If the channel is blocking, then yes, so we guarantee that blocking
+     * flushes actually flush all pending data.
+     *
      * Otherwise, no.  Keep the current output buffer where it is so more
      * can be written to it, possibly filling it, to promote more efficient
      * buffer usage.
@@ -2798,8 +2800,8 @@ FlushChannel(
                /*
                 * TIP #219, Tcl Channel Reflection API.
                 * When defering the error copy a message from the bypass into
-                * the unreported area. Or discard it if the new error is to be
-                * ignored in favor of an earlier defered error.
+                * the unreported area. Or discard it if the new error is to
+                * be ignored in favor of an earlier defered error.
                 */
 
                Tcl_Obj *msg = statePtr->chanMsg;
@@ -2851,8 +2853,11 @@ FlushChannel(
            ReleaseChannelBuffer(bufPtr);
            break;
        } else {
-           /* TODO: Consider detecting and reacting to short writes
-            * on blocking channels.  Ought not happen.  See iocmd-24.2. */
+           /*
+            * TODO: Consider detecting and reacting to short writes on
+            * blocking channels.  Ought not happen.  See iocmd-24.2.
+            */
+
            wroteSome = 1;
        }
 
@@ -2886,7 +2891,6 @@ FlushChannel(
            ResetFlag(statePtr, BG_FLUSH_SCHEDULED);
            ChanWatch(chanPtr, statePtr->interestMask);
        } else {
-
            /*
             * When we are calledFromAsyncFlush, that means a writable
             * state on the channel triggered the call, so we should be
@@ -2931,7 +2935,8 @@ FlushChannel(
            (statePtr->outQueueHead == NULL) &&
            ((statePtr->curOutPtr == NULL) ||
            IsBufferEmpty(statePtr->curOutPtr))) {
-       errorCode = CloseChannelPart(interp, chanPtr, errorCode, TCL_CLOSE_WRITE);
+       errorCode = CloseChannelPart(interp, chanPtr, errorCode,
+                TCL_CLOSE_WRITE);
        goto done;
     }
 
@@ -3184,6 +3189,9 @@ CutChannel(
      */
 
     ChanThreadAction((Channel *) chan, TCL_CHANNEL_THREAD_REMOVE);
+
+    /* Channel is not managed by any thread */
+    statePtr->managingThread = NULL;
 }
 
 void
@@ -3228,6 +3236,9 @@ Tcl_CutChannel(
     for (; chanPtr != NULL ; chanPtr = chanPtr->upChanPtr) {
        ChanThreadAction(chanPtr, TCL_CHANNEL_THREAD_REMOVE);
     }
+
+    /* Channel is not managed by any thread */
+    statePtr->managingThread = NULL;
 }
 \f
 /*
@@ -3353,7 +3364,7 @@ Tcl_Close(
                                 * channel. */
     Channel *chanPtr;          /* The real IO channel. */
     ChannelState *statePtr;    /* State of real IO channel. */
-    int result;                        /* Of calling FlushChannel. */
+    int result = 0;                    /* Of calling FlushChannel. */
     int flushcode;
     int stickyError;
 
@@ -3402,7 +3413,6 @@ Tcl_Close(
 
     if (GotFlag(statePtr, TCL_WRITABLE) && (statePtr->encoding != NULL)
            && !(statePtr->outputEncodingFlags & TCL_ENCODING_START)) {
-
        int code = CheckChannelErrors(statePtr, TCL_WRITABLE);
 
        if (code == 0) {
@@ -3453,8 +3463,9 @@ Tcl_Close(
     if (chanPtr->typePtr->closeProc == TCL_CLOSE2PROC) {
        result = chanPtr->typePtr->close2Proc(chanPtr->instanceData, interp,
                TCL_CLOSE_READ);
-    } else {
-       result = 0;
+       if ((result == EINVAL) || result == ENOTCONN) {
+           result = 0;
+       }
     }
 
     /*
@@ -3492,17 +3503,23 @@ Tcl_Close(
        }
        return TCL_ERROR;
     }
+
     /*
      * Bug 97069ea11a: set error message if a flush code is set and no error
      * message set up to now.
      */
-    if (flushcode != 0 && interp != NULL
-           && 0 == Tcl_GetCharLength(Tcl_GetObjResult(interp)) ) {
-       Tcl_SetErrno(flushcode);
+
+    if (flushcode != 0) {
+       /* flushcode has precedence, if available */
+       result = flushcode;
+    }
+    if ((result != 0) && (result != TCL_ERROR) && (interp != NULL)
+           && 0 == Tcl_GetCharLength(Tcl_GetObjResult(interp))) {
+       Tcl_SetErrno(result);
        Tcl_SetObjResult(interp,
                Tcl_NewStringObj(Tcl_PosixError(interp), -1));
     }
-    if ((flushcode != 0) || (result != 0)) {
+    if (result != 0) {
        return TCL_ERROR;
     }
     return TCL_OK;
@@ -3524,7 +3541,7 @@ Tcl_Close(
  * NOTE:
  *     Tcl_CloseEx closes the specified direction of the channel as far as
  *     the user is concerned. The channel keeps existing however. You cannot
- *     calls this function to close the last possible direction of the
+ *     call this function to close the last possible direction of the
  *     channel. Use Tcl_Close for that.
  *
  *----------------------------------------------------------------------
@@ -3545,18 +3562,26 @@ Tcl_CloseEx(
        return TCL_OK;
     }
 
-    /* TODO: assert flags validity ? */
-
     chanPtr = (Channel *) chan;
     statePtr = chanPtr->state;
 
+    if ((flags & (TCL_READABLE | TCL_WRITABLE)) == 0) {
+       return Tcl_Close(interp, chan);
+    }
+    if ((flags & (TCL_READABLE | TCL_WRITABLE)) == (TCL_READABLE | TCL_WRITABLE)) {
+       Tcl_SetObjResult(interp, Tcl_ObjPrintf(
+               "double-close of channels not supported by %ss",
+               chanPtr->typePtr->typeName));
+       return TCL_ERROR;
+    }
+
     /*
      * Does the channel support half-close anyway? Error if not.
      */
 
     if (!chanPtr->typePtr->close2Proc) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
-                "half-close of channels not supported by %ss",
+               "half-close of channels not supported by %ss",
                chanPtr->typePtr->typeName));
        return TCL_ERROR;
     }
@@ -3592,8 +3617,8 @@ Tcl_CloseEx(
     }
 
     /*
-     * A user may try to call half-close from within a channel close
-     * handler. That won't do.
+     * A user may try to call half-close from within a channel close handler.
+     * That won't do.
      */
 
     if (statePtr->flags & CHANNEL_INCLOSE) {
@@ -3664,9 +3689,12 @@ CloseWrite(
                                  * closed. May still be used by some
                                  * interpreter */
 {
-    /* Notes: clear-channel-handlers - write side only ? or keep around, just
-     * not called. */
-    /* No close cllbacks are run - channel is still open (read side) */
+    /*
+     * Notes: clear-channel-handlers - write side only ? or keep around, just
+     * not called.
+     *
+     * No close callbacks are run - channel is still open (read side)
+     */
 
     ChannelState *statePtr = chanPtr->state;
                                 /* State of real IO channel. */
@@ -3691,9 +3719,9 @@ CloseWrite(
      * Notes: Due to the assertion of CHANNEL_CLOSEDWRITE in the flags
      * FlushChannel() has called CloseChannelPart(). While we can still access
      * "chan" (no structures were freed), the only place which may still
-     * contain a message is the interpreter itself, and "CloseChannelPart" made
-     * sure to lift any channel message it generated into it. Hence the NULL
-     * argument in the call below.
+     * contain a message is the interpreter itself, and "CloseChannelPart"
+     * made sure to lift any channel message it generated into it. Hence the
+     * NULL argument in the call below.
      */
 
     if (TclChanCaughtErrorBypass(interp, NULL)) {
@@ -3789,7 +3817,7 @@ CloseChannelPart(
      * message in the interp.
      */
 
-    result = ChanCloseHalf(chanPtr, interp, flags);
+    result = chanPtr->typePtr->close2Proc(chanPtr->instanceData, NULL, flags);
 
     /*
      * If we are being called synchronously, report either any latent error on
@@ -3917,10 +3945,10 @@ Tcl_ClearChannelHandlers(
     StopCopy(statePtr->csPtrW);
 
     /*
-     * Must set the interest mask now to 0, otherwise infinite loops
-     * will occur if Tcl_DoOneEvent is called before the channel is
-     * finally deleted in FlushChannel. This can happen if the channel
-     * has a background flush active.
+     * Must set the interest mask now to 0, otherwise infinite loops will
+     * occur if Tcl_DoOneEvent is called before the channel is finally deleted
+     * in FlushChannel. This can happen if the channel has a background flush
+     * active.
      */
 
     statePtr->interestMask = 0;
@@ -4175,12 +4203,12 @@ WillWrite(
 {
     int inputBuffered;
 
-    if ((chanPtr->typePtr->seekProc != NULL) &&
-            ((inputBuffered = Tcl_InputBuffered((Tcl_Channel) chanPtr)) > 0)){
-        int ignore;
+    if ((Tcl_ChannelSeekProc(chanPtr->typePtr) != NULL) &&
+           ((inputBuffered = Tcl_InputBuffered((Tcl_Channel) chanPtr)) > 0)){
+       int ignore;
 
-        DiscardInputQueued(chanPtr->state, 0);
-        ChanSeek(chanPtr, -inputBuffered, SEEK_CUR, &ignore);
+       DiscardInputQueued(chanPtr->state, 0);
+       ChanSeek(chanPtr, -inputBuffered, SEEK_CUR, &ignore);
     }
 }
 \f
@@ -4189,27 +4217,30 @@ WillRead(
     Channel *chanPtr)
 {
     if (chanPtr->typePtr == NULL) {
-       /* Prevent read attempts on a closed channel */
-        DiscardInputQueued(chanPtr->state, 0);
+       /*
+        * Prevent read attempts on a closed channel.
+        */
+
+       DiscardInputQueued(chanPtr->state, 0);
        Tcl_SetErrno(EINVAL);
        return -1;
     }
-    if ((chanPtr->typePtr->seekProc != NULL)
-            && (Tcl_OutputBuffered((Tcl_Channel) chanPtr) > 0)) {
+    if ((Tcl_ChannelSeekProc(chanPtr->typePtr) != NULL)
+           && (Tcl_OutputBuffered((Tcl_Channel) chanPtr) > 0)) {
 
        /*
-        * CAVEAT - The assumption here is that FlushChannel() will
-        * push out the bytes of any writes that are in progress.
-        * Since this is a seekable channel, we assume it is not one
-        * that can block and force bg flushing.  Channels we know that
-        * can do that -- sockets, pipes -- are not seekable.  If the
-        * assumption is wrong, more drastic measures may be required here
-        * like temporarily setting the channel into blocking mode.
+        * CAVEAT - The assumption here is that FlushChannel() will push out
+        * the bytes of any writes that are in progress.  Since this is a
+        * seekable channel, we assume it is not one that can block and force
+        * bg flushing.  Channels we know that can do that - sockets, pipes -
+        * are not seekable. If the assumption is wrong, more drastic measures
+        * may be required here like temporarily setting the channel into
+        * blocking mode.
         */
 
-        if (FlushChannel(NULL, chanPtr, 0) != 0) {
-            return -1;
-        }
+       if (FlushChannel(NULL, chanPtr, 0) != 0) {
+       return -1;
+       }
     }
     return 0;
 }
@@ -4259,7 +4290,7 @@ Write(
 
     if (GotFlag(statePtr, CHANNEL_LINEBUFFERED)
            || (statePtr->outputTranslation != TCL_TRANSLATE_LF)) {
-       nextNewLine = memchr(src, '\n', srcLen);
+       nextNewLine = (char *)memchr(src, '\n', srcLen);
     }
 
     while (srcLen + saved + endEncoding > 0) {
@@ -4283,7 +4314,7 @@ Write(
             * that we need to stick at the beginning of this buffer.
             */
 
-           memcpy(InsertPoint(bufPtr), safe, (size_t) saved);
+           memcpy(InsertPoint(bufPtr), safe, saved);
            bufPtr->nextAdded += saved;
            saved = 0;
        }
@@ -4296,11 +4327,17 @@ Write(
                &statePtr->outputEncodingState, dst,
                dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
 
-       /* See chan-io-1.[89]. Tcl Bug 506297. */
+       /*
+        * See chan-io-1.[89]. Tcl Bug 506297.
+        */
+
        statePtr->outputEncodingFlags &= ~TCL_ENCODING_START;
 
        if ((result != TCL_OK) && (srcRead + dstWrote == 0)) {
-           /* We're reading from invalid/incomplete UTF-8 */
+           /*
+            * We're reading from invalid/incomplete UTF-8.
+            */
+
            ReleaseChannelBuffer(bufPtr);
            if (total == 0) {
                Tcl_SetErrno(EINVAL);
@@ -4340,11 +4377,10 @@ Write(
            }
 
            result |= Tcl_UtfToExternal(NULL, encoding, nl, nlLen,
-               statePtr->outputEncodingFlags,
-               &statePtr->outputEncodingState, dst,
-               dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
-
-           assert (srcRead == nlLen);
+                   statePtr->outputEncodingFlags,
+                   &statePtr->outputEncodingState, dst,
+                   dstLen + BUFFER_PADDING, &srcRead, &dstWrote, NULL);
+           assert(srcRead == nlLen);
 
            bufPtr->nextAdded += dstWrote;
            src++;
@@ -4352,21 +4388,21 @@ Write(
            total += dstWrote;
            dst += dstWrote;
            dstLen -= dstWrote;
-           nextNewLine = memchr(src, '\n', srcLen);
+           nextNewLine = (char *)memchr(src, '\n', srcLen);
            needNlFlush = 1;
        }
 
        if (IsBufferOverflowing(bufPtr)) {
            /*
-            * When translating from UTF-8 to external encoding, we
-            * allowed the translation to produce a character that crossed
-            * the end of the output buffer, so that we would get a
-            * completely full buffer before flushing it. The extra bytes
-            * will be moved to the beginning of the next buffer.
+            * When translating from UTF-8 to external encoding, we allowed
+            * the translation to produce a character that crossed the end of
+            * the output buffer, so that we would get a completely full
+            * buffer before flushing it. The extra bytes will be moved to the
+            * beginning of the next buffer.
             */
 
            saved = -SpaceLeft(bufPtr);
-           memcpy(safe, dst + dstLen, (size_t) saved);
+           memcpy(safe, dst + dstLen, saved);
            bufPtr->nextAdded = bufPtr->bufLength;
        }
 
@@ -4382,15 +4418,16 @@ Write(
            flushed += statePtr->bufSize;
 
            /*
-            * We just flushed.  So if we have needNlFlush set to record
-            * that we need to flush because theres a (translated) newline
-            * in the buffer, that's likely not true any more.  But there
-            * is a tricky exception.  If we have saved bytes that did not
-            * really get flushed and those bytes came from a translation
-            * of a newline as the last thing taken from the src array,
-            * then needNlFlush needs to remain set to flag that the
-            * next buffer still needs a newline flush.
+            * We just flushed.  So if we have needNlFlush set to record that
+            * we need to flush because theres a (translated) newline in the
+            * buffer, that's likely not true any more.  But there is a tricky
+            * exception.  If we have saved bytes that did not really get
+            * flushed and those bytes came from a translation of a newline as
+            * the last thing taken from the src array, then needNlFlush needs
+            * to remain set to flag that the next buffer still needs a
+            * newline flush.
             */
+
            if (needNlFlush && (saved == 0 || src[-1] != '\n')) {
                needNlFlush = 0;
            }
@@ -4496,8 +4533,8 @@ Tcl_GetsObj(
 
     if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
        SetFlag(statePtr, CHANNEL_EOF);
-       assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
-       assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+       assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+       assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
 
        /* TODO: Do we need this? */
        UpdateInterest(chanPtr);
@@ -4662,19 +4699,19 @@ Tcl_GetsObj(
                     * Skip the raw bytes that make up the '\n'.
                     */
 
-                   char tmp[TCL_UTF_MAX];
                    int rawRead;
+                   char tmp[TCL_UTF_MAX];
 
                    bufPtr = gs.bufPtr;
                    Tcl_ExternalToUtf(NULL, gs.encoding, RemovePoint(bufPtr),
                            gs.rawRead, statePtr->inputEncodingFlags
                                | TCL_ENCODING_NO_TERMINATE, &gs.state, tmp,
-                           TCL_UTF_MAX, &rawRead, NULL, NULL);
+                           sizeof(tmp), &rawRead, NULL, NULL);
                    bufPtr->nextRemoved += rawRead;
                    gs.rawRead -= rawRead;
                    gs.bytesWrote--;
                    gs.charsWrote--;
-                   memmove(dst, dst + 1, (size_t) (dstEnd - dst));
+                   memmove(dst, dst + 1, dstEnd - dst);
                    dstEnd--;
                }
            }
@@ -4837,17 +4874,17 @@ Tcl_GetsObj(
      */
 
   done:
-       assert(!GotFlag(statePtr, CHANNEL_EOF)
-               || GotFlag(statePtr, CHANNEL_STICKY_EOF)
-               || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
-
-       assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
-               == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+    assert(!GotFlag(statePtr, CHANNEL_EOF)
+           || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+           || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+    assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+           == (CHANNEL_EOF|CHANNEL_BLOCKED)));
 
     /*
      * Regenerate the top channel, in case it was changed due to
      * self-modifying reflected transforms.
      */
+
     if (chanPtr != statePtr->topChanPtr) {
        TclChannelRelease((Tcl_Channel)chanPtr);
        chanPtr = statePtr->topChanPtr;
@@ -4867,10 +4904,9 @@ Tcl_GetsObj(
  *     end-of-line or end-of-file has been seen. Bytes read from the input
  *     channel return as a ByteArray obj.
  *
- *     WARNING!  The notion of "binary" used here is different from
- *     notions of "binary" used in other places.  In particular, this
- *     "binary" routine may be called when an -eofchar is set on the
- *     channel.
+ *     WARNING!  The notion of "binary" used here is different from notions
+ *     of "binary" used in other places. In particular, this "binary" routine
+ *     may be called when an -eofchar is set on the channel.
  *
  * Results:
  *     Number of characters accumulated in the object or -1 if error,
@@ -4936,8 +4972,8 @@ TclGetsObjBinary(
     ResetFlag(statePtr, CHANNEL_BLOCKED);
     while (1) {
        /*
-        * Subtract the number of bytes that were removed from channel
-        * buffer during last call.
+        * Subtract the number of bytes that were removed from channel buffer
+        * during last call.
         */
 
        if (bufPtr != NULL) {
@@ -4949,10 +4985,11 @@ TclGetsObjBinary(
 
        if ((bufPtr == NULL) || (bufPtr->nextAdded == BUFFER_PADDING)) {
            /*
-            * All channel buffers were exhausted and the caller still
-            * hasn't seen EOL. Need to read more bytes from the channel
-            * device. Side effect is to allocate another channel buffer.
+            * All channel buffers were exhausted and the caller still hasn't
+            * seen EOL. Need to read more bytes from the channel device. Side
+            * effect is to allocate another channel buffer.
             */
+
            if (GetInput(chanPtr) != 0) {
                goto restore;
            }
@@ -4962,15 +4999,15 @@ TclGetsObjBinary(
            }
        } else {
            /*
-            * Incoming CHANNEL_STICKY_EOF is filtered out on entry.
-            * A new CHANNEL_STICKY_EOF set in this routine leads to
-            * return before coming back here.  When we are not dealing
-            * with CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an
-            * empty buffer.  Here the buffer is non-empty so we know
-            * we're a non-EOF */
+            * Incoming CHANNEL_STICKY_EOF is filtered out on entry.  A new
+            * CHANNEL_STICKY_EOF set in this routine leads to return before
+            * coming back here.  When we are not dealing with
+            * CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an empty buffer.
+            * Here the buffer is non-empty so we know we're a non-EOF.
+             */
 
-           assert ( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
-           assert ( !GotFlag(statePtr, CHANNEL_EOF) );
+           assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
+           assert(!GotFlag(statePtr, CHANNEL_EOF));
        }
 
        dst = (unsigned char *) RemovePoint(bufPtr);
@@ -5037,13 +5074,13 @@ TclGetsObjBinary(
        }
 
        /*
-        * Copy bytes from the channel buffer to the ByteArray.
-        * This may realloc space, so keep track of result.
+        * Copy bytes from the channel buffer to the ByteArray. This may
+        * realloc space, so keep track of result.
         */
 
        rawLen = dstEnd - dst;
        byteArray = Tcl_SetByteArrayLength(objPtr, byteLen + rawLen);
-       memcpy(byteArray + byteLen, dst, (size_t) rawLen);
+       memcpy(byteArray + byteLen, dst, rawLen);
        byteLen += rawLen;
     }
 
@@ -5060,7 +5097,7 @@ TclGetsObjBinary(
 
     rawLen = eol - dst;
     byteArray = Tcl_SetByteArrayLength(objPtr, byteLen + rawLen);
-    memcpy(byteArray + byteLen, dst, (size_t) rawLen);
+    memcpy(byteArray + byteLen, dst, rawLen);
     byteLen += rawLen;
     bufPtr->nextRemoved += rawLen + skip;
 
@@ -5122,11 +5159,11 @@ TclGetsObjBinary(
      */
 
   done:
-       assert(!GotFlag(statePtr, CHANNEL_EOF)
-               || GotFlag(statePtr, CHANNEL_STICKY_EOF)
-               || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
-       assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
-               == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+    assert(!GotFlag(statePtr, CHANNEL_EOF)
+           || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+           || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+    assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+           == (CHANNEL_EOF|CHANNEL_BLOCKED)));
     UpdateInterest(chanPtr);
     TclChannelRelease((Tcl_Channel)chanPtr);
     return copiedTotal;
@@ -5151,6 +5188,7 @@ FreeBinaryEncoding(
     ClientData dummy)  /* Not used */
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
 
     if (tsdPtr->binaryEncoding != NULL) {
        Tcl_FreeEncoding(tsdPtr->binaryEncoding);
@@ -5259,15 +5297,15 @@ FilterInputBytes(
        }
     } else {
        /*
-        * Incoming CHANNEL_STICKY_EOF is filtered out on entry.
-        * A new CHANNEL_STICKY_EOF set in this routine leads to
-        * return before coming back here.  When we are not dealing
-        * with CHANNEL_STICKY_EOF, a CHANNEL_EOF implies an
-        * empty buffer.  Here the buffer is non-empty so we know
-        * we're a non-EOF */
+        * Incoming CHANNEL_STICKY_EOF is filtered out on entry.  A new
+        * CHANNEL_STICKY_EOF set in this routine leads to return before
+        * coming back here.  When we are not dealing with CHANNEL_STICKY_EOF,
+        * a CHANNEL_EOF implies an empty buffer.  Here the buffer is
+        * non-empty so we know we're a non-EOF.
+         */
 
-       assert ( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
-       assert ( !GotFlag(statePtr, CHANNEL_EOF) );
+       assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
+       assert(!GotFlag(statePtr, CHANNEL_EOF));
     }
 
     /*
@@ -5597,7 +5635,9 @@ Tcl_ReadRaw(
        return -1;
     }
 
-    /* First read bytes from the push-back buffers. */
+    /*
+     * First read bytes from the push-back buffers.
+     */
 
     while (chanPtr->inQueueHead && bytesToRead > 0) {
        ChannelBuffer *bufPtr = chanPtr->inQueueHead;
@@ -5605,15 +5645,19 @@ Tcl_ReadRaw(
        int toCopy = (bytesInBuffer < bytesToRead) ? bytesInBuffer
                : bytesToRead;
 
-       /* Copy the current chunk into the read buffer. */
+       /*
+        * Copy the current chunk into the read buffer.
+        */
 
-       memcpy(readBuf, RemovePoint(bufPtr), (size_t) toCopy);
+       memcpy(readBuf, RemovePoint(bufPtr), toCopy);
        bufPtr->nextRemoved += toCopy;
        copied += toCopy;
        readBuf += toCopy;
        bytesToRead -= toCopy;
 
-       /* If the current buffer is empty recycle it. */
+       /*
+         * If the current buffer is empty recycle it.
+         */
 
        if (IsBufferEmpty(bufPtr)) {
            chanPtr->inQueueHead = bufPtr->nextPtr;
@@ -5625,37 +5669,40 @@ Tcl_ReadRaw(
     }
 
     /*
-     * Go to the driver only if we got nothing from pushback.
-     * Have to do it this way to avoid EOF mis-timings when we
-     * consider the ability that EOF may not be a permanent
-     * condition in the driver, and in that case we have to
-     * synchronize.
+     * Go to the driver only if we got nothing from pushback.  Have to do it
+     * this way to avoid EOF mis-timings when we consider the ability that EOF
+     * may not be a permanent condition in the driver, and in that case we
+     * have to synchronize.
      */
 
     if (copied) {
        return copied;
     }
 
-    /* This test not needed. */
-    if (bytesToRead > 0) {
+    /*
+     * This test not needed.
+     */
 
+    if (bytesToRead > 0) {
        int nread = ChanRead(chanPtr, readBuf, bytesToRead);
 
        if (nread > 0) {
-           /* Successful read (short is OK) - add to bytes copied */
+           /*
+            * Successful read (short is OK) - add to bytes copied.
+            */
+
            copied += nread;
        } else if (nread < 0) {
            /*
-            * An error signaled.  If CHANNEL_BLOCKED, then the error
-            * is not real, but an indication of blocked state.  In
-            * that case, retain the flag and let caller receive the
-            * short read of copied bytes from the pushback.
-            * HOWEVER, if copied==0 bytes from pushback then repeat
-            * signalling the blocked state as an error to caller so
-            * there is no false report of an EOF.
-            * When !CHANNEL_BLOCKED, the error is real and passes on
-            * to caller.
+            * An error signaled.  If CHANNEL_BLOCKED, then the error is not
+            * real, but an indication of blocked state.  In that case, retain
+            * the flag and let caller receive the short read of copied bytes
+            * from the pushback.  HOWEVER, if copied==0 bytes from pushback
+            * then repeat signalling the blocked state as an error to caller
+            * so there is no false report of an EOF.  When !CHANNEL_BLOCKED,
+            * the error is real and passes on to caller.
             */
+
            if (!GotFlag(statePtr, CHANNEL_BLOCKED) || copied == 0) {
                copied = -1;
            }
@@ -5792,21 +5839,23 @@ DoReadChars(
     /*
      * Early out when next read will see eofchar.
      *
-     * NOTE: See DoRead for argument that it's a bug (one we're keeping)
-     * to have this escape before the one for zero-char read request.
+     * NOTE: See DoRead for argument that it's a bug (one we're keeping) to
+     * have this escape before the one for zero-char read request.
      */
 
     if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
        SetFlag(statePtr, CHANNEL_EOF);
-       assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
-       assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+       assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+       assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
 
        /* TODO: We don't need this call? */
        UpdateInterest(chanPtr);
        return 0;
     }
 
-    /* Special handling for zero-char read request. */
+    /*
+     * Special handling for zero-char read request.
+     */
     if (toRead == 0) {
        if (GotFlag(statePtr, CHANNEL_EOF)) {
            statePtr->inputEncodingFlags |= TCL_ENCODING_START;
@@ -5825,7 +5874,10 @@ DoReadChars(
     chanPtr = statePtr->topChanPtr;
     TclChannelPreserve((Tcl_Channel)chanPtr);
 
-    /* Must clear the BLOCKED|EOF flags here since we check before reading */
+    /*
+     * Must clear the BLOCKED|EOF flags here since we check before reading.
+     */
+
     if (GotFlag(statePtr, CHANNEL_EOF)) {
        statePtr->inputEncodingFlags |= TCL_ENCODING_START;
     }
@@ -5883,10 +5935,11 @@ DoReadChars(
     }
 
     /*
-     * Failure to fill a channel buffer may have left channel reporting
-     * a "blocked" state, but so long as we fulfilled the request here,
-     * the caller does not consider us blocked.
+     * Failure to fill a channel buffer may have left channel reporting a
+     * "blocked" state, but so long as we fulfilled the request here, the
+     * caller does not consider us blocked.
      */
+
     if (toRead == 0) {
        ResetFlag(statePtr, CHANNEL_BLOCKED);
     }
@@ -5895,6 +5948,7 @@ DoReadChars(
      * Regenerate the top channel, in case it was changed due to
      * self-modifying reflected transforms.
      */
+
     if (chanPtr != statePtr->topChanPtr) {
        TclChannelRelease((Tcl_Channel)chanPtr);
        chanPtr = statePtr->topChanPtr;
@@ -5905,11 +5959,12 @@ DoReadChars(
      * Update the notifier state so we don't block while there is still data
      * in the buffers.
      */
-       assert(!GotFlag(statePtr, CHANNEL_EOF)
-               || GotFlag(statePtr, CHANNEL_STICKY_EOF)
-               || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
-       assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
-               == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+
+    assert(!GotFlag(statePtr, CHANNEL_EOF)
+           || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+           || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+    assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+            == (CHANNEL_EOF|CHANNEL_BLOCKED)));
     UpdateInterest(chanPtr);
     TclChannelRelease((Tcl_Channel)chanPtr);
     return copied;
@@ -6026,11 +6081,10 @@ ReadChars(
     int numBytes, srcLen = BytesLeft(bufPtr);
 
     /*
-     * One src byte can yield at most one character.  So when the
-     * number of src bytes we plan to read is less than the limit on
-     * character count to be read, clearly we will remain within that
-     * limit, and we can use the value of "srcLen" as a tighter limit
-     * for sizing receiving buffers.
+     * One src byte can yield at most one character.  So when the number of
+     * src bytes we plan to read is less than the limit on character count to
+     * be read, clearly we will remain within that limit, and we can use the
+     * value of "srcLen" as a tighter limit for sizing receiving buffers.
      */
 
     int toRead = ((charsToRead<0)||(charsToRead > srcLen)) ? srcLen : charsToRead;
@@ -6048,6 +6102,7 @@ ReadChars(
     Tcl_AppendToObj(objPtr, NULL, dstLimit);
     if (toRead == srcLen) {
        unsigned int size;
+
        dst = TclGetStringStorage(objPtr, &size) + numBytes;
        dstLimit = size - numBytes;
     } else {
@@ -6055,19 +6110,18 @@ ReadChars(
     }
 
     /*
-     * This routine is burdened with satisfying several constraints.
-     * It cannot append more than 'charsToRead` chars onto objPtr.
-     * This is measured after encoding and translation transformations
-     * are completed.  There is no precise number of src bytes that can
-     * be associated with the limit.  Yet, when we are done, we must know
-     * precisely the number of src bytes that were consumed to produce
-     * the appended chars, so that all subsequent bytes are left in
-     * the buffers for future read operations.
+     * This routine is burdened with satisfying several constraints. It cannot
+     * append more than 'charsToRead` chars onto objPtr. This is measured
+     * after encoding and translation transformations are completed. There is
+     * no precise number of src bytes that can be associated with the limit.
+     * Yet, when we are done, we must know precisely the number of src bytes
+     * that were consumed to produce the appended chars, so that all
+     * subsequent bytes are left in the buffers for future read operations.
      *
-     * The consequence is that we have no choice but to implement a
-     * "trial and error" approach, where in general we may need to
-     * perform transformations and copies multiple times to achieve
-     * a consistent set of results.  This takes the shape of a loop.
+     * The consequence is that we have no choice but to implement a "trial and
+     * error" approach, where in general we may need to perform
+     * transformations and copies multiple times to achieve a consistent set
+     * of results.  This takes the shape of a loop.
      */
 
     while (1) {
@@ -6080,18 +6134,17 @@ ReadChars(
        }
 
        /*
-        * Perform the encoding transformation.  Read no more than
-        * srcLen bytes, write no more than dstLimit bytes.
+        * Perform the encoding transformation.  Read no more than srcLen
+        * bytes, write no more than dstLimit bytes.
         *
-        * Some trickiness with encoding flags here.  We do not want
-        * the end of a buffer to be treated as the end of all input
-        * when the presence of bytes in a next buffer are already
-        * known to exist.  This is checked with an assert() because
-        * so far no test case causing the assertion to be false has
-        * been created.  The normal operations of channel reading
-        * appear to cause EOF and TCL_ENCODING_END setting to appear
-        * only in situations where there are no further bytes in
-        * any buffers.
+        * Some trickiness with encoding flags here.  We do not want the end
+        * of a buffer to be treated as the end of all input when the presence
+        * of bytes in a next buffer are already known to exist.  This is
+        * checked with an assert() because so far no test case causing the
+        * assertion to be false has been created.  The normal operations of
+        * channel reading appear to cause EOF and TCL_ENCODING_END setting to
+        * appear only in situations where there are no further bytes in any
+        * buffers.
         */
 
        assert(bufPtr->nextPtr == NULL || BytesLeft(bufPtr->nextPtr) == 0
@@ -6102,10 +6155,10 @@ ReadChars(
                dst, dstLimit, &srcRead, &dstDecoded, &numChars);
 
        /*
-        * Perform the translation transformation in place.  Read no more
-        * than the dstDecoded bytes the encoding transformation actually
-        * produced.  Capture the number of bytes written in dstWrote.
-        * Capture the number of bytes actually consumed in dstRead.
+        * Perform the translation transformation in place.  Read no more than
+        * the dstDecoded bytes the encoding transformation actually produced.
+        * Capture the number of bytes written in dstWrote. Capture the number
+        * of bytes actually consumed in dstRead.
         */
 
        dstWrote = dstLimit;
@@ -6113,11 +6166,9 @@ ReadChars(
        TranslateInputEOL(statePtr, dst, dst, &dstWrote, &dstRead);
 
        if (dstRead < dstDecoded) {
-
            /*
-            * The encoding transformation produced bytes that the
-            * translation transformation did not consume.  Why did
-            * this happen?
+            * The encoding transformation produced bytes that the translation
+            * transformation did not consume.  Why did this happen?
             */
 
            if (statePtr->inEofChar && dst[dstRead] == statePtr->inEofChar) {
@@ -6126,43 +6177,41 @@ ReadChars(
                 *    we saw it and stopped translating at that point.
                 *
                 * NOTE the bizarre spec of TranslateInputEOL in this case.
-                * Clearly the eof char had to be read in order to account
-                * for the stopping, but the value of dstRead does not
-                * include it.
+                * Clearly the eof char had to be read in order to account for
+                * the stopping, but the value of dstRead does not include it.
                 *
-                * Also rather bizarre, our caller can only notice an
-                * EOF condition if we return the value -1 as the number
-                * of chars read.  This forces us to perform a 2-call
-                * dance where the first call can read all the chars
-                * up to the eof char, and the second call is solely
-                * for consuming the encoded eof char then pointed at
-                * by src so that we can return that magic -1 value.
-                * This seems really wasteful, especially since
-                * the first decoding pass of each call is likely to
-                * decode many bytes beyond that eof char that's all we
-                * care about.
+                * Also rather bizarre, our caller can only notice an EOF
+                * condition if we return the value -1 as the number of chars
+                * read.  This forces us to perform a 2-call dance where the
+                * first call can read all the chars up to the eof char, and
+                * the second call is solely for consuming the encoded eof
+                * char then pointed at by src so that we can return that
+                * magic -1 value.  This seems really wasteful, especially
+                * since the first decoding pass of each call is likely to
+                * decode many bytes beyond that eof char that's all we care
+                * about.
                 */
 
                if (dstRead == 0) {
                    /*
-                    * Curious choice in the eof char handling.  We leave
-                    * the eof char in the buffer.  So, no need to compute
-                    * a proper srcRead value.  At this point, there
-                    * are no chars before the eof char in the buffer.
+                    * Curious choice in the eof char handling.  We leave the
+                    * eof char in the buffer. So, no need to compute a proper
+                    * srcRead value. At this point, there are no chars before
+                    * the eof char in the buffer.
                     */
+
                    Tcl_SetObjLength(objPtr, numBytes);
                    return -1;
                }
 
                {
                    /*
-                    * There are chars leading the buffer before the eof
-                    * char.  Adjust the dstLimit so we go back and read
-                    * only those and do not encounter the eof char this
-                    * time.
+                    * There are chars leading the buffer before the eof char.
+                    * Adjust the dstLimit so we go back and read only those
+                    * and do not encounter the eof char this time.
                     */
 
-                   dstLimit = dstRead - 1 + TCL_UTF_MAX;
+                   dstLimit = dstRead + (TCL_UTF_MAX - 1);
                    statePtr->flags = savedFlags;
                    statePtr->inputEncodingFlags = savedIEFlags;
                    statePtr->inputEncodingState = savedState;
@@ -6171,10 +6220,9 @@ ReadChars(
            }
 
            /*
-            * 2) The other way to read fewer bytes than are decoded
-            *    is when the final byte is \r and we're in a CRLF
-            *    translation mode so we cannot decide whether to
-            *    record \r or \n yet.
+            * 2) The other way to read fewer bytes than are decoded is when
+            *    the final byte is \r and we're in a CRLF translation mode so
+            *    we cannot decide whether to record \r or \n yet.
             */
 
            assert(dst[dstRead] == '\r');
@@ -6182,13 +6230,13 @@ ReadChars(
 
            if (dstWrote > 0) {
                /*
-                * There are chars we can read before we hit the bare cr.
-                * Go back with a smaller dstLimit so we get them in the
-                * next pass, compute a matching srcRead, and don't end
-                * up back here in this call.
+                * There are chars we can read before we hit the bare CR.  Go
+                * back with a smaller dstLimit so we get them in the next
+                * pass, compute a matching srcRead, and don't end up back
+                * here in this call.
                 */
 
-               dstLimit = dstRead - 1 + TCL_UTF_MAX;
+               dstLimit = dstRead + (TCL_UTF_MAX - 1);
                statePtr->flags = savedFlags;
                statePtr->inputEncodingFlags = savedIEFlags;
                statePtr->inputEncodingState = savedState;
@@ -6199,14 +6247,14 @@ ReadChars(
            assert(dstRead == 0);
 
            /*
-            * We decoded only the bare cr, and we cannot read a
-            * translated char from that alone.  We have to know what's
-            * next.  So why do we only have the one decoded char?
+            * We decoded only the bare CR, and we cannot read a translated
+            * char from that alone. We have to know what's next.  So why do
+            * we only have the one decoded char?
             */
 
            if (code != TCL_OK) {
-               char buffer[TCL_UTF_MAX + 1];
                int read, decoded, count;
+               char buffer[TCL_UTF_MAX + 1];
 
                /*
                 * Didn't get everything the buffer could offer
@@ -6222,7 +6270,7 @@ ReadChars(
 
                Tcl_ExternalToUtf(NULL, encoding, src, srcLen,
                (statePtr->inputEncodingFlags | TCL_ENCODING_NO_TERMINATE),
-               &statePtr->inputEncodingState, buffer, TCL_UTF_MAX + 1,
+               &statePtr->inputEncodingState, buffer, sizeof(buffer),
                &read, &decoded, &count);
 
                if (count == 2) {
@@ -6242,10 +6290,9 @@ ReadChars(
                }
 
            } else if (statePtr->flags & CHANNEL_EOF) {
-
                /*
-                * The bare \r is the only char and we will never read
-                * subsequent char to make the determination.
+                * The bare \r is the only char and we will never read a
+                * subsequent char to make the determination.
                 */
 
                dst[0] = '\r';
@@ -6255,8 +6302,8 @@ ReadChars(
            }
 
            /*
-            * Revise the dstRead value so that the numChars calc
-            * below correctly computes zero characters read.
+            * Revise the dstRead value so that the numChars calc below
+            * correctly computes zero characters read.
             */
 
            dstRead = numChars;
@@ -6265,9 +6312,9 @@ ReadChars(
        }
 
        /*
-        * The translation transformation can only reduce the number
-        * of chars when it converts \r\n into \n.  The reduction in
-        * the number of chars is the difference in bytes read and written.
+        * The translation transformation can only reduce the number of chars
+        * when it converts \r\n into \n. The reduction in the number of chars
+        * is the difference in bytes read and written.
         */
 
        numChars -= (dstRead - dstWrote);
@@ -6277,13 +6324,12 @@ ReadChars(
            /*
             * TODO: This cannot happen anymore.
             *
-            * We read more chars than allowed.  Reset limits to
-            * prevent that and try again.  Don't forget the extra
-            * padding of TCL_UTF_MAX bytes demanded by the
-            * Tcl_ExternalToUtf() call!
+            * We read more chars than allowed.  Reset limits to prevent that
+            * and try again.  Don't forget the extra padding of TCL_UTF_MAX
+            * bytes demanded by the Tcl_ExternalToUtf() call!
             */
 
-           dstLimit = Tcl_UtfAtIndex(dst, charsToRead) - 1 + TCL_UTF_MAX - dst;
+           dstLimit = Tcl_UtfAtIndex(dst, charsToRead) - dst + (TCL_UTF_MAX - 1);
            statePtr->flags = savedFlags;
            statePtr->inputEncodingFlags = savedIEFlags;
            statePtr->inputEncodingState = savedState;
@@ -6293,18 +6339,19 @@ ReadChars(
        if (dstWrote == 0) {
            ChannelBuffer *nextPtr;
 
-           /* We were not able to read any chars. */
+           /*
+            * We were not able to read any chars.
+            */
 
-           assert (numChars == 0);
+           assert(numChars == 0);
 
            /*
-            * There is one situation where this is the correct final
-            * result.  If the src buffer contains only a single \n
-            * byte, and we are in TCL_TRANSLATE_AUTO mode, and
-            * when the translation pass was made the INPUT_SAW_CR
-            * flag was set on the channel.  In that case, the
-            * correct behavior is to consume that \n and produce the
-            * empty string.
+            * There is one situation where this is the correct final result.
+            * If the src buffer contains only a single \n byte, and we are in
+            * TCL_TRANSLATE_AUTO mode, and when the translation pass was made
+            * the INPUT_SAW_CR flag was set on the channel. In that case, the
+            * correct behavior is to consume that \n and produce the empty
+            * string.
             */
 
            if (dstRead == 1 && dst[0] == '\n') {
@@ -6313,12 +6360,13 @@ ReadChars(
                goto consume;
            }
 
-           /* Otherwise, reading zero characters indicates there's
-            * something incomplete at the end of the src buffer.
-            * Maybe there were not enough src bytes to decode into
-            * a char.  Maybe a lone \r could not be translated (crlf
-            * mode).  Need to combine any unused src bytes we have
-            * in the first buffer with subsequent bytes to try again.
+           /*
+            * Otherwise, reading zero characters indicates there's something
+            * incomplete at the end of the src buffer.  Maybe there were not
+            * enough src bytes to decode into a char.  Maybe a lone \r could
+            * not be translated (crlf mode).  Need to combine any unused src
+            * bytes we have in the first buffer with subsequent bytes to try
+            * again.
             */
 
            nextPtr = bufPtr->nextPtr;
@@ -6333,15 +6381,15 @@ ReadChars(
 
            /*
             * Space is made at the beginning of the buffer to copy the
-            * previous unused bytes there. Check first if the buffer we
-            * are using actually has enough space at its beginning for
-            * the data we are copying.  Because if not we will write over
-            * the buffer management information, especially the 'nextPtr'.
+            * previous unused bytes there. Check first if the buffer we are
+            * using actually has enough space at its beginning for the data
+            * we are copying.  Because if not we will write over the buffer
+            * management information, especially the 'nextPtr'.
             *
-            * Note that the BUFFER_PADDING (See AllocChannelBuffer) is
-            * used to prevent exactly this situation. I.e. it should never
-            * happen.  Therefore it is ok to panic should it happen despite
-            * the precautions.
+            * Note that the BUFFER_PADDING (See AllocChannelBuffer) is used
+            * to prevent exactly this situation. I.e. it should never happen.
+            * Therefore it is ok to panic should it happen despite the
+            * precautions.
             */
 
            if (nextPtr->nextRemoved - srcLen < 0) {
@@ -6349,7 +6397,7 @@ ReadChars(
            }
 
            nextPtr->nextRemoved -= srcLen;
-           memcpy(RemovePoint(nextPtr), src, (size_t) srcLen);
+           memcpy(RemovePoint(nextPtr), src, srcLen);
            RecycleBuffer(statePtr, bufPtr, 0);
            statePtr->inQueueHead = nextPtr;
            Tcl_SetObjLength(objPtr, numBytes);
@@ -6360,10 +6408,12 @@ ReadChars(
 
     consume:
        bufPtr->nextRemoved += srcRead;
+
        /*
-        * If this read contained multibyte characters, revise factorPtr
-        * so the next read will allocate bigger buffers.
+        * If this read contained multibyte characters, revise factorPtr so
+        * the next read will allocate bigger buffers.
         */
+
        if (numChars && numChars < srcRead) {
            *factorPtr = srcRead * UTF_EXPANSION_FACTOR / numChars;
        }
@@ -6411,22 +6461,27 @@ TranslateInputEOL(
     int inEofChar = statePtr->inEofChar;
 
     /*
-     * Depending on the translation mode in use, there's no need
-     * to scan more srcLen bytes at srcStart than can possibly transform
-     * to dstLen bytes.  This keeps the scan for eof char below from
-     * being pointlessly long.
+     * Depending on the translation mode in use, there's no need to scan more
+     * srcLen bytes at srcStart than can possibly transform to dstLen bytes.
+     * This keeps the scan for eof char below from being pointlessly long.
      */
 
     switch (statePtr->inputTranslation) {
     case TCL_TRANSLATE_LF:
     case TCL_TRANSLATE_CR:
        if (srcLen > dstLen) {
-       /* In these modes, each src byte become a dst byte. */
+           /*
+            * In these modes, each src byte become a dst byte.
+            */
+
            srcLen = dstLen;
        }
        break;
     default:
-       /* In other modes, at most 2 src bytes become a dst byte. */
+       /*
+        * In other modes, at most 2 src bytes become a dst byte.
+        */
+
        if (srcLen/2 > dstLen) {
            srcLen = 2 * dstLen;
        }
@@ -6439,7 +6494,7 @@ TranslateInputEOL(
         * created by the presence of the input eof char.
         */
 
-       if ((eof = memchr(srcStart, inEofChar, srcLen))) {
+       if ((eof = (const char *)memchr(srcStart, inEofChar, srcLen))) {
            srcLen = eof - srcStart;
        }
     }
@@ -6448,13 +6503,13 @@ TranslateInputEOL(
     case TCL_TRANSLATE_LF:
     case TCL_TRANSLATE_CR:
        if (dstStart != srcStart) {
-           memcpy(dstStart, srcStart, (size_t) srcLen);
+           memcpy(dstStart, srcStart, srcLen);
        }
        if (statePtr->inputTranslation == TCL_TRANSLATE_CR) {
            char *dst = dstStart;
            char *dstEnd = dstStart + srcLen;
 
-           while ((dst = memchr(dst, '\r', dstEnd - dst))) {
+           while ((dst = (char *)memchr(dst, '\r', dstEnd - dst))) {
                *dst++ = '\n';
            }
        }
@@ -6465,7 +6520,7 @@ TranslateInputEOL(
        char *dst = dstStart;
        int lesser = (dstLen < srcLen) ? dstLen : srcLen;
 
-       while ((crFound = memchr(src, '\r', lesser))) {
+       while ((crFound = (const char *)memchr(src, '\r', lesser))) {
            int numBytes = crFound - src;
            memmove(dst, src, numBytes);
 
@@ -6505,7 +6560,7 @@ TranslateInputEOL(
            ResetFlag(statePtr, INPUT_SAW_CR);
        }
        lesser = (dstLen < srcLen) ? dstLen : srcLen;
-       while ((crFound = memchr(src, '\r', lesser))) {
+       while ((crFound = (const char *)memchr(src, '\r', lesser))) {
            int numBytes = crFound - src;
            memmove(dst, src, numBytes);
 
@@ -6605,7 +6660,7 @@ Tcl_Ungets(
     statePtr->inputEncodingFlags &= ~TCL_ENCODING_END;
 
     bufPtr = AllocChannelBuffer(len);
-    memcpy(InsertPoint(bufPtr), str, (size_t) len);
+    memcpy(InsertPoint(bufPtr), str, len);
     bufPtr->nextAdded += len;
 
     if (statePtr->inQueueHead == NULL) {
@@ -6759,7 +6814,7 @@ GetInput(
      * eofchar.
      */
 
-    assert( !GotFlag(statePtr, CHANNEL_STICKY_EOF) );
+    assert(!GotFlag(statePtr, CHANNEL_STICKY_EOF));
 
     /*
      * Prevent reading from a dead channel -- a channel that has been closed
@@ -6798,7 +6853,6 @@ GetInput(
      */
 
     if (chanPtr->inQueueHead != NULL) {
-
        /* TODO: Tests to cover this. */
        assert(statePtr->inQueueHead == NULL);
 
@@ -6828,8 +6882,9 @@ GetInput(
 
        /*
         * Check the actual buffersize against the requested buffersize.
-        * Saved buffers of the wrong size are squashed. This is done
-        * to honor dynamic changes of the buffersize made by the user.
+        * Saved buffers of the wrong size are squashed. This is done to honor
+        * dynamic changes of the buffersize made by the user.
+         *
         * TODO: Tests to cover this.
         */
 
@@ -6908,7 +6963,7 @@ Tcl_Seek(
                                 * non-blocking mode after the seek. */
 
     if (CheckChannelErrors(statePtr, TCL_WRITABLE | TCL_READABLE) != 0) {
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -6919,7 +6974,7 @@ Tcl_Seek(
      */
 
     if (CheckForDeadChannel(NULL, statePtr)) {
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -6933,9 +6988,9 @@ Tcl_Seek(
      * defined. This means that the channel does not support seeking.
      */
 
-    if (chanPtr->typePtr->seekProc == NULL) {
+    if (Tcl_ChannelSeekProc(chanPtr->typePtr) == NULL) {
        Tcl_SetErrno(EINVAL);
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -6948,7 +7003,7 @@ Tcl_Seek(
 
     if ((inputBuffered != 0) && (outputBuffered != 0)) {
        Tcl_SetErrno(EFAULT);
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -6991,7 +7046,7 @@ Tcl_Seek(
        wasAsync = 1;
        result = StackSetBlockMode(chanPtr, TCL_MODE_BLOCKING);
        if (result != 0) {
-           return Tcl_LongAsWide(-1);
+           return -1;
        }
        ResetFlag(statePtr, CHANNEL_NONBLOCKING);
        if (GotFlag(statePtr, BG_FLUSH_SCHEDULED)) {
@@ -7016,7 +7071,7 @@ Tcl_Seek(
         */
 
        curPos = ChanSeek(chanPtr, offset, mode, &result);
-       if (curPos == Tcl_LongAsWide(-1)) {
+       if (curPos == -1) {
            Tcl_SetErrno(result);
        }
     }
@@ -7032,7 +7087,7 @@ Tcl_Seek(
        SetFlag(statePtr, CHANNEL_NONBLOCKING);
        result = StackSetBlockMode(chanPtr, TCL_MODE_NONBLOCKING);
        if (result != 0) {
-           return Tcl_LongAsWide(-1);
+           return -1;
        }
     }
 
@@ -7072,7 +7127,7 @@ Tcl_Tell(
     Tcl_WideInt curPos;                /* Position on device. */
 
     if (CheckChannelErrors(statePtr, TCL_WRITABLE | TCL_READABLE) != 0) {
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -7083,7 +7138,7 @@ Tcl_Tell(
      */
 
     if (CheckForDeadChannel(NULL, statePtr)) {
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -7097,9 +7152,9 @@ Tcl_Tell(
      * defined. This means that the channel does not support seeking.
      */
 
-    if (chanPtr->typePtr->seekProc == NULL) {
+    if (Tcl_ChannelSeekProc(chanPtr->typePtr) == NULL) {
        Tcl_SetErrno(EINVAL);
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     /*
@@ -7116,10 +7171,10 @@ Tcl_Tell(
      * wideSeekProc if that is available and non-NULL...
      */
 
-    curPos = ChanSeek(chanPtr, Tcl_LongAsWide(0), SEEK_CUR, &result);
-    if (curPos == Tcl_LongAsWide(-1)) {
+    curPos = ChanSeek(chanPtr, 0, SEEK_CUR, &result);
+    if (curPos == -1) {
        Tcl_SetErrno(result);
-       return Tcl_LongAsWide(-1);
+       return -1;
     }
 
     if (inputBuffered != 0) {
@@ -7177,7 +7232,7 @@ Tcl_TellOld(
  *     Truncate a channel to the given length.
  *
  * Results:
- *     TCL_OK on success, TCL_ERROR if the operation failed (e.g. is not
+ *     TCL_OK on success, TCL_ERROR if the operation failed (e.g., is not
  *     supported by the type of channel, or the underlying OS operation
  *     failed in some way).
  *
@@ -7457,7 +7512,7 @@ Tcl_OutputBuffered(
        bytesBuffered += BytesLeft(bufPtr);
     }
     if (statePtr->curOutPtr != NULL) {
-       register ChannelBuffer *curOutPtr = statePtr->curOutPtr;
+       ChannelBuffer *curOutPtr = statePtr->curOutPtr;
 
        if (IsBufferReady(curOutPtr)) {
            bytesBuffered += BytesLeft(curOutPtr);
@@ -7644,7 +7699,7 @@ Tcl_BadChannelOption(
        }
        Tcl_ResetResult(interp);
        errObj = Tcl_ObjPrintf("bad option \"%s\": should be one of ",
-                optionName);
+                optionName ? optionName : "");
        argc--;
        for (i = 0; i < argc; i++) {
            Tcl_AppendPrintfToObj(errObj, "-%s, ", argv[i]);
@@ -8333,6 +8388,13 @@ Tcl_NotifyChannel(
     Tcl_Preserve(statePtr);
 
     /*
+     * Avoid processing if the channel owner has been changed.
+     */
+    if (statePtr->managingThread != Tcl_GetCurrentThread()) {
+       goto done;
+    }
+
+    /*
      * If we are flushing in the background, be sure to call FlushChannel for
      * writable events. Note that we have to discard the writable event so we
      * don't call any write handlers before the flush is complete.
@@ -8366,6 +8428,13 @@ Tcl_NotifyChannel(
        } else {
            chPtr = chPtr->nextPtr;
        }
+
+       /*
+        * Stop if the channel owner has been changed in-between.
+        */
+       if (chanPtr->state->managingThread != Tcl_GetCurrentThread()) {
+           goto done;
+       }
     }
 
     /*
@@ -8383,6 +8452,7 @@ Tcl_NotifyChannel(
        UpdateInterest(chanPtr);
     }
 
+done:
     Tcl_Release(statePtr);
     TclChannelRelease(channel);
 
@@ -8459,9 +8529,9 @@ UpdateInterest(
             *
             * - Tcl drops READABLE here, because it has data in its own
             *   buffers waiting to be read by the extension.
-            * - A READABLE event is syntesized via timer.
+            * - A READABLE event is synthesized via timer.
             * - The OS still reports the EXCEPTION condition on the file.
-            * - And the extension gets the EXCPTION event first, and handles
+            * - And the extension gets the EXCEPTION event first, and handles
             *   this as EOF.
             *
             * End result ==> Premature end of reading from a file.
@@ -8511,7 +8581,7 @@ static void
 ChannelTimerProc(
     ClientData clientData)
 {
-    Channel *chanPtr = clientData;
+    Channel *chanPtr = (Channel *)clientData;
     ChannelState *statePtr = chanPtr->state;
                                /* State info for channel */
 
@@ -8586,7 +8656,7 @@ Tcl_CreateChannelHandler(
        }
     }
     if (chPtr == NULL) {
-       chPtr = ckalloc(sizeof(ChannelHandler));
+       chPtr = (ChannelHandler *)ckalloc(sizeof(ChannelHandler));
        chPtr->mask = 0;
        chPtr->proc = proc;
        chPtr->clientData = clientData;
@@ -8798,7 +8868,7 @@ CreateScriptRecord(
     makeCH = (esPtr == NULL);
 
     if (makeCH) {
-       esPtr = ckalloc(sizeof(EventScriptRecord));
+       esPtr = (EventScriptRecord *)ckalloc(sizeof(EventScriptRecord));
     }
 
     /*
@@ -8854,12 +8924,17 @@ TclChannelEventScriptInvoker(
                                 * in. */
     int result;                        /* Result of call to eval script. */
 
-    esPtr = clientData;
+    esPtr = (EventScriptRecord *)clientData;
     chanPtr = esPtr->chanPtr;
     mask = esPtr->mask;
     interp = esPtr->interp;
 
     /*
+     * Be sure event executed in managed channel (covering bugs similar [f583715154]).
+     */
+    assert(chanPtr->state->managingThread == Tcl_GetCurrentThread());
+
+    /*
      * We must preserve the interpreter so we can report errors on it later.
      * Note that we do not need to preserve the channel because that is done
      * by Tcl_NotifyChannel before calling channel handlers.
@@ -8909,7 +8984,7 @@ TclChannelEventScriptInvoker(
        /* ARGSUSED */
 int
 Tcl_FileEventObjCmd(
-    ClientData clientData,     /* Not used. */
+    ClientData dummy,  /* Not used. */
     Tcl_Interp *interp,                /* Interpreter in which the channel for which
                                 * to create the handler is found. */
     int objc,                  /* Number of arguments. */
@@ -8923,6 +8998,7 @@ Tcl_FileEventObjCmd(
     int mask;
     static const char *const modeOptions[] = {"readable", "writable", NULL};
     static const int maskArray[] = {TCL_READABLE, TCL_WRITABLE};
+    (void)dummy;
 
     if ((objc != 3) && (objc != 4)) {
        Tcl_WrongNumArgs(interp, 1, objv, "channelId event ?script?");
@@ -9008,7 +9084,7 @@ ZeroTransferTimerProc(
     /* calling CopyData with mask==0 still implies immediate invocation of the
      *  -command callback, and completion of the fcopy.
      */
-    CopyData(clientData, 0);
+    CopyData((CopyState *)clientData, 0);
 }
 \f
 /*
@@ -9126,7 +9202,7 @@ TclCopyChannel(
      * completed.
      */
 
-    csPtr = ckalloc(sizeof(CopyState) + !moveBytes * inStatePtr->bufSize);
+    csPtr = (CopyState *)ckalloc(sizeof(CopyState) + !moveBytes * inStatePtr->bufSize);
     csPtr->bufSize = !moveBytes * inStatePtr->bufSize;
     csPtr->readPtr = inPtr;
     csPtr->writePtr = outPtr;
@@ -9537,7 +9613,10 @@ CopyData(
            }
            if (size == 0) {
                if (!GotFlag(inStatePtr, CHANNEL_NONBLOCKING)) {
-                   /* We allowed a short read.  Keep trying. */
+                   /*
+                    * We allowed a short read.  Keep trying.
+                    */
+
                    continue;
                }
                if (bufObj != NULL) {
@@ -9751,7 +9830,7 @@ DoRead(
     ChannelState *statePtr = chanPtr->state;
     char *p = dst;
 
-    assert (bytesToRead >= 0);
+    assert(bytesToRead >= 0);
 
     /*
      * Early out when we know a read will get the eofchar.
@@ -9767,15 +9846,18 @@ DoRead(
 
     if (GotFlag(statePtr, CHANNEL_STICKY_EOF)) {
        SetFlag(statePtr, CHANNEL_EOF);
-       assert( statePtr->inputEncodingFlags & TCL_ENCODING_END );
-       assert( !GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR) );
+       assert(statePtr->inputEncodingFlags & TCL_ENCODING_END);
+       assert(!GotFlag(statePtr, CHANNEL_BLOCKED|INPUT_SAW_CR));
 
        /* TODO: Don't need this call */
        UpdateInterest(chanPtr);
        return 0;
     }
 
-    /* Special handling for zero-char read request. */
+    /*
+     * Special handling for zero-char read request.
+     */
+
     if (bytesToRead == 0) {
        if (GotFlag(statePtr, CHANNEL_EOF)) {
            statePtr->inputEncodingFlags |= TCL_ENCODING_START;
@@ -9790,8 +9872,8 @@ DoRead(
     TclChannelPreserve((Tcl_Channel)chanPtr);
     while (bytesToRead) {
        /*
-        * Each pass through the loop is intended to process up to
-        * one channel buffer.
+        * Each pass through the loop is intended to process up to one channel
+        * buffer.
         */
 
        int bytesRead, bytesWritten;
@@ -9803,33 +9885,39 @@ DoRead(
 
        while (!bufPtr ||                       /* We got no buffer!   OR */
                (!IsBufferFull(bufPtr) &&       /* Our buffer has room AND */
-               (BytesLeft(bufPtr) < bytesToRead) ) ) {
-                                               /* Not enough bytes in it
-                                                * yet to fill the dst */
+               (BytesLeft(bufPtr) < bytesToRead))) {
+                                               /* Not enough bytes in it yet
+                                                * to fill the dst */
            int code;
 
        moreData:
            code = GetInput(chanPtr);
            bufPtr = statePtr->inQueueHead;
 
-           assert (bufPtr != NULL);
+           assert(bufPtr != NULL);
 
            if (GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)) {
-               /* Further reads cannot do any more */
+               /*
+                * Further reads cannot do any more.
+                */
+
                break;
            }
 
            if (code) {
-               /* Read error */
+               /*
+            * Read error
+            */
+
                UpdateInterest(chanPtr);
                TclChannelRelease((Tcl_Channel)chanPtr);
                return -1;
            }
 
-           assert (IsBufferFull(bufPtr));
+           assert(IsBufferFull(bufPtr));
        }
 
-       assert (bufPtr != NULL);
+       assert(bufPtr != NULL);
 
        bytesRead = BytesLeft(bufPtr);
        bytesWritten = bytesToRead;
@@ -9844,8 +9932,8 @@ DoRead(
            /*
             * Buffer is not empty.  How can that be?
             *
-            * 0) We stopped early because we got all the bytes
-            *    we were seeking.  That's fine.
+            * 0) We stopped early because we got all the bytes we were
+            *    seeking. That's fine.
             */
 
            if (bytesToRead == 0) {
@@ -9861,8 +9949,8 @@ DoRead(
            }
 
            /*
-            * 2) The buffer holds a \r while in CRLF translation,
-            *    followed by the end of the buffer.
+            * 2) The buffer holds a \r while in CRLF translation, followed by
+            *    the end of the buffer.
             */
 
            assert(statePtr->inputTranslation == TCL_TRANSLATE_CRLF);
@@ -9870,26 +9958,38 @@ DoRead(
            assert(BytesLeft(bufPtr) == 1);
 
            if (bufPtr->nextPtr == NULL) {
-               /* There's no more buffered data.... */
+               /*
+                * There's no more buffered data...
+                */
 
                if (statePtr->flags & CHANNEL_EOF) {
-                   /* ...and there never will be. */
+                   /*
+                    * ...and there never will be.
+                    */
 
                    *p++ = '\r';
                    bytesToRead--;
                    bufPtr->nextRemoved++;
                } else if (statePtr->flags & CHANNEL_BLOCKED) {
-                   /* ...and we cannot get more now. */
+                   /*
+                    * ...and we cannot get more now.
+                    */
+
                    SetFlag(statePtr, CHANNEL_NEED_MORE_DATA);
                    break;
                } else {
-                   /* ... so we need to get some. */
+                   /*
+                    * ...so we need to get some.
+                    */
+
                    goto moreData;
                }
            }
 
            if (bufPtr->nextPtr) {
-               /* There's a next buffer.  Shift orphan \r to it. */
+               /*
+                * There's a next buffer.  Shift orphan \r to it.
+                */
 
                ChannelBuffer *nextPtr = bufPtr->nextPtr;
 
@@ -9914,8 +10014,8 @@ DoRead(
        }
 
        /*
-        * When there's no buffered data to read, and we're at EOF,
-        * escape to the caller.
+        * When there's no buffered data to read, and we're at EOF, escape to
+        * the caller.
         */
 
        if (GotFlag(statePtr, CHANNEL_EOF)
@@ -9927,11 +10027,11 @@ DoRead(
        ResetFlag(statePtr, CHANNEL_BLOCKED);
     }
 
-       assert(!GotFlag(statePtr, CHANNEL_EOF)
-               || GotFlag(statePtr, CHANNEL_STICKY_EOF)
-               || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
-       assert( !(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
-               == (CHANNEL_EOF|CHANNEL_BLOCKED)) );
+    assert(!GotFlag(statePtr, CHANNEL_EOF)
+           || GotFlag(statePtr, CHANNEL_STICKY_EOF)
+           || Tcl_InputBuffered((Tcl_Channel)chanPtr) == 0);
+    assert(!(GotFlag(statePtr, CHANNEL_EOF|CHANNEL_BLOCKED)
+           == (CHANNEL_EOF|CHANNEL_BLOCKED)));
     UpdateInterest(chanPtr);
     TclChannelRelease((Tcl_Channel)chanPtr);
     return (int)(p - dst);
@@ -9960,7 +10060,7 @@ CopyEventProc(
     ClientData clientData,
     int mask)
 {
-    (void) CopyData(clientData, mask);
+    (void) CopyData((CopyState *)clientData, mask);
 }
 \f
 /*
@@ -10293,7 +10393,7 @@ Tcl_IsChannelRegistered(
     chanPtr = ((Channel *) chan)->state->bottomChanPtr;
     statePtr = chanPtr->state;
 
-    hTblPtr = Tcl_GetAssocData(interp, "tclIO", NULL);
+    hTblPtr = (Tcl_HashTable *)Tcl_GetAssocData(interp, "tclIO", NULL);
     if (hTblPtr == NULL) {
        return 0;
     }
@@ -10375,7 +10475,7 @@ Tcl_IsChannelExisting(
        }
 
        if ((*chanName == *name) &&
-               (memcmp(name, chanName, (size_t) chanNameLen + 1) == 0)) {
+               (memcmp(name, chanName, chanNameLen + 1) == 0)) {
            return 1;
        }
     }
@@ -10427,49 +10527,15 @@ Tcl_ChannelVersion(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (chanTypePtr->version == TCL_CHANNEL_VERSION_2) {
-       return TCL_CHANNEL_VERSION_2;
-    } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_3) {
-       return TCL_CHANNEL_VERSION_3;
-    } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_4) {
-       return TCL_CHANNEL_VERSION_4;
-    } else if (chanTypePtr->version == TCL_CHANNEL_VERSION_5) {
-       return TCL_CHANNEL_VERSION_5;
-    } else {
+    if ((chanTypePtr->version < TCL_CHANNEL_VERSION_2)
+           || (chanTypePtr->version > TCL_CHANNEL_VERSION_5)) {
        /*
         * In <v2 channel versions, the version field is occupied by the
         * Tcl_DriverBlockModeProc
         */
-
        return TCL_CHANNEL_VERSION_1;
     }
-}
-\f
-/*
- *----------------------------------------------------------------------
- *
- * HaveVersion --
- *
- *     Return whether a channel type is (at least) of a given version.
- *
- * Results:
- *     True if the minimum version is exceeded by the version actually
- *     present.
- *
- * Side effects:
- *     None.
- *
- *----------------------------------------------------------------------
- */
-
-static int
-HaveVersion(
-    const Tcl_ChannelType *chanTypePtr,
-    Tcl_ChannelTypeVersion minimumVersion)
-{
-    Tcl_ChannelTypeVersion actualVersion = Tcl_ChannelVersion(chanTypePtr);
-
-    return (PTR2INT(actualVersion)) >= (PTR2INT(minimumVersion));
+    return chanTypePtr->version;
 }
 \f
 /*
@@ -10492,15 +10558,14 @@ Tcl_ChannelBlockModeProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
-       return chanTypePtr->blockModeProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_2) {
+       /*
+        * The v1 structure had the blockModeProc in a different place.
+        */
+       return (Tcl_DriverBlockModeProc *) chanTypePtr->version;
     }
 
-    /*
-     * The v1 structure had the blockModeProc in a different place.
-     */
-
-    return (Tcl_DriverBlockModeProc *) chanTypePtr->version;
+    return chanTypePtr->blockModeProc;
 }
 \f
 /*
@@ -10740,10 +10805,10 @@ Tcl_ChannelFlushProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
-       return chanTypePtr->flushProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_2) {
+       return NULL;
     }
-    return NULL;
+    return chanTypePtr->flushProc;
 }
 \f
 /*
@@ -10767,10 +10832,10 @@ Tcl_ChannelHandlerProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_2)) {
-       return chanTypePtr->handlerProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_2) {
+       return NULL;
     }
-    return NULL;
+    return chanTypePtr->handlerProc;
 }
 \f
 /*
@@ -10794,10 +10859,10 @@ Tcl_ChannelWideSeekProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_3)) {
-       return chanTypePtr->wideSeekProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_3) {
+       return NULL;
     }
-    return NULL;
+    return chanTypePtr->wideSeekProc;
 }
 \f
 /*
@@ -10822,10 +10887,10 @@ Tcl_ChannelThreadActionProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_4)) {
-       return chanTypePtr->threadActionProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_4) {
+       return NULL;
     }
-    return NULL;
+    return chanTypePtr->threadActionProc;
 }
 \f
 /*
@@ -11002,7 +11067,7 @@ FixLevelCode(
        lcn += 2;
     }
 
-    lvn = ckalloc(lcn * sizeof(Tcl_Obj *));
+    lvn = (Tcl_Obj **)ckalloc(lcn * sizeof(Tcl_Obj *));
 
     /*
      * New level/code information is spliced into the first occurence of
@@ -11137,10 +11202,10 @@ Tcl_ChannelTruncateProc(
     const Tcl_ChannelType *chanTypePtr)
                                /* Pointer to channel type. */
 {
-    if (HaveVersion(chanTypePtr, TCL_CHANNEL_VERSION_5)) {
-       return chanTypePtr->truncateProc;
+    if (Tcl_ChannelVersion(chanTypePtr) < TCL_CHANNEL_VERSION_5) {
+       return NULL;
     }
-    return NULL;
+    return chanTypePtr->truncateProc;
 }
 \f
 /*
@@ -11163,9 +11228,9 @@ Tcl_ChannelTruncateProc(
 
 static void
 DupChannelIntRep(
-    register Tcl_Obj *srcPtr,  /* Object with internal rep to copy. Must have
+    Tcl_Obj *srcPtr,   /* Object with internal rep to copy. Must have
                                 * an internal rep of type "Channel". */
-    register Tcl_Obj *copyPtr) /* Object with internal rep to set. Must not
+    Tcl_Obj *copyPtr)  /* Object with internal rep to set. Must not
                                 * currently have an internal rep.*/
 {
     ResolvedChanName *resPtr = srcPtr->internalRep.twoPtrValue.ptr1;
index ffbfa31..eccc7a9 100644 (file)
@@ -44,7 +44,7 @@ typedef struct ChannelBuffer {
     int bufLength;             /* How big is the buffer? */
     struct ChannelBuffer *nextPtr;
                                /* Next buffer in chain. */
-    char buf[1];               /* Placeholder for real buffer. The real
+    char buf[TCLFLEXARRAY];            /* Placeholder for real buffer. The real
                                 * buffer occuppies this space + bufSize-1
                                 * bytes. This must be the last field in the
                                 * structure. */
index 834f225..af1295f 100644 (file)
@@ -713,7 +713,7 @@ Tcl_CloseObjCmd(
        /*
         * Special handling is needed if and only if the channel mode supports
         * more than the direction to close. Because if the close the last
-        * direction suppported we can and will go through the regular
+        * direction supported we can and will go through the regular
         * process.
         */
 
index 7f61def..dadcb53 100644 (file)
@@ -23,6 +23,8 @@ static int            TransformBlockModeProc(ClientData instanceData,
                            int mode);
 static int             TransformCloseProc(ClientData instanceData,
                            Tcl_Interp *interp);
+static int             TransformClose2Proc(ClientData instanceData,
+                           Tcl_Interp *interp, int flags);
 static int             TransformInputProc(ClientData instanceData, char *buf,
                            int toRead, int *errorCodePtr);
 static int             TransformOutputProc(ClientData instanceData,
@@ -127,7 +129,7 @@ static const Tcl_ChannelType transformChannelType = {
     TransformGetOptionProc,    /* Get option proc. */
     TransformWatchProc,                /* Initialize notifier. */
     TransformGetFileHandleProc,        /* Get OS handles out of channel. */
-    NULL,                      /* close2proc */
+    TransformClose2Proc,       /* close2proc */
     TransformBlockModeProc,    /* Set blocking/nonblocking mode.*/
     NULL,                      /* Flush proc. */
     TransformNotifyProc,       /* Handling of events bubbling up. */
@@ -287,7 +289,7 @@ TclChannelTransform(
      * regime of the underlying channel and to use the same for us too.
      */
 
-    dataPtr = ckalloc(sizeof(TransformChannelData));
+    dataPtr = (TransformChannelData *)ckalloc(sizeof(TransformChannelData));
 
     dataPtr->refCount = 1;
     Tcl_DStringInit(&ds);
@@ -503,7 +505,7 @@ TransformBlockModeProc(
     ClientData instanceData,   /* State of transformation. */
     int mode)                  /* New blocking mode. */
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
 
     if (mode == TCL_MODE_NONBLOCKING) {
        dataPtr->flags |= CHANNEL_ASYNC;
@@ -516,7 +518,7 @@ TransformBlockModeProc(
 /*
  *----------------------------------------------------------------------
  *
- * TransformCloseProc --
+ * TransformCloseProc/TransformClose2Proc --
  *
  *     Trap handler. Called by the generic IO system during destruction of
  *     the transformation channel.
@@ -592,6 +594,18 @@ TransformCloseProc(
     ReleaseData(dataPtr);
     return TCL_OK;
 }
+
+static int
+TransformClose2Proc(
+    ClientData instanceData,
+    Tcl_Interp *interp,
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return TransformCloseProc(instanceData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -616,7 +630,7 @@ TransformInputProc(
     int toRead,
     int *errorCodePtr)
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     int gotBytes, read, copied;
     Tcl_Channel downChan;
 
@@ -783,7 +797,7 @@ TransformOutputProc(
     int toWrite,
     int *errorCodePtr)
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
 
     /*
      * Should assert(dataPtr->mode & TCL_WRITABLE);
@@ -835,7 +849,7 @@ TransformSeekProc(
     int mode,                  /* How to move. */
     int *errorCodePtr)         /* Location of error flag. */
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     Tcl_Channel parent = Tcl_GetStackedChannel(dataPtr->self);
     const Tcl_ChannelType *parentType = Tcl_GetChannelType(parent);
     Tcl_DriverSeekProc *parentSeekProc = Tcl_ChannelSeekProc(parentType);
@@ -902,7 +916,7 @@ TransformWideSeekProc(
     int mode,                  /* How to move. */
     int *errorCodePtr)         /* Location of error flag. */
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     Tcl_Channel parent = Tcl_GetStackedChannel(dataPtr->self);
     const Tcl_ChannelType *parentType  = Tcl_GetChannelType(parent);
     Tcl_DriverSeekProc *parentSeekProc = Tcl_ChannelSeekProc(parentType);
@@ -910,7 +924,7 @@ TransformWideSeekProc(
            Tcl_ChannelWideSeekProc(parentType);
     ClientData parentData = Tcl_GetChannelInstanceData(parent);
 
-    if ((offset == Tcl_LongAsWide(0)) && (mode == SEEK_CUR)) {
+    if ((offset == 0) && (mode == SEEK_CUR)) {
        /*
         * This is no seek but a request to tell the caller the current
         * location. Simply pass the request down.
@@ -995,7 +1009,7 @@ TransformSetOptionProc(
     const char *optionName,
     const char *value)
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     Tcl_Channel downChan = Tcl_GetStackedChannel(dataPtr->self);
     Tcl_DriverSetOptionProc *setOptionProc;
 
@@ -1033,7 +1047,7 @@ TransformGetOptionProc(
     const char *optionName,
     Tcl_DString *dsPtr)
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     Tcl_Channel downChan = Tcl_GetStackedChannel(dataPtr->self);
     Tcl_DriverGetOptionProc *getOptionProc;
 
@@ -1079,7 +1093,7 @@ TransformWatchProc(
     ClientData instanceData,   /* Channel to watch. */
     int mask)                  /* Events of interest. */
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
     Tcl_Channel downChan;
 
     /*
@@ -1158,7 +1172,7 @@ TransformGetFileHandleProc(
     int direction,             /* Direction of interest. */
     ClientData *handlePtr)     /* Place to store the handle into. */
 {
-    TransformChannelData *dataPtr = instanceData;
+    TransformChannelData *dataPtr = (TransformChannelData *)instanceData;
 
     /*
      * Return the handle belonging to parent channel. IOW, pass the request
@@ -1192,7 +1206,7 @@ TransformNotifyProc(
                                 * transformation. */
     int mask)                  /* The mask of occuring events. */
 {
-    TransformChannelData *dataPtr = clientData;
+    TransformChannelData *dataPtr = (TransformChannelData *)clientData;
 
     /*
      * An event occured in the underlying channel. This transformation doesn't
@@ -1235,7 +1249,7 @@ static void
 TransformChannelHandlerTimer(
     ClientData clientData)     /* Transformation to query. */
 {
-    TransformChannelData *dataPtr = clientData;
+    TransformChannelData *dataPtr = (TransformChannelData *)clientData;
 
     dataPtr->timer = NULL;
     if (!(dataPtr->watchMask&TCL_READABLE) || ResultEmpty(&dataPtr->result)) {
@@ -1417,10 +1431,10 @@ ResultAdd(
 
        if (r->allocated == 0) {
            r->allocated = toWrite + INCREMENT;
-           r->buf = ckalloc(r->allocated);
+           r->buf = (unsigned char *)ckalloc(r->allocated);
        } else {
            r->allocated += toWrite + INCREMENT;
-           r->buf = ckrealloc(r->buf, r->allocated);
+           r->buf = (unsigned char *)ckrealloc(r->buf, r->allocated);
        }
     }
 
index e862761..dd24b0f 100644 (file)
@@ -33,6 +33,8 @@
 
 static int             ReflectClose(ClientData clientData,
                            Tcl_Interp *interp);
+static int             ReflectClose2(ClientData clientData,
+                           Tcl_Interp *interp, int flags);
 static int             ReflectInput(ClientData clientData, char *buf,
                            int toRead, int *errorCodePtr);
 static int             ReflectOutput(ClientData clientData, const char *buf,
@@ -71,7 +73,7 @@ static const Tcl_ChannelType tclRChannelType = {
     ReflectGetOption,     /* Get options.                      NULL'able */
     ReflectWatch,         /* Initialize notifier                         */
     NULL,                 /* Get OS handle from the channel.   NULL'able */
-    NULL,                 /* No close2 support.                NULL'able */
+    ReflectClose2,        /* No close2 support.                NULL'able */
     ReflectBlock,         /* Set blocking/nonblocking.         NULL'able */
     NULL,                 /* Flush channel. Not used by core.  NULL'able */
     NULL,                 /* Handle events.                    NULL'able */
@@ -481,7 +483,7 @@ static const char *msg_dstlost    = "-code 1 -level 0 -errorcode NONE -errorinfo
 
 int
 TclChanCreateObjCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const *objv)
@@ -507,6 +509,7 @@ TclChanCreateObjCmd(
                                 * this interp. */
     Tcl_HashEntry *hPtr;       /* Entry in the above map */
     int isNew;                 /* Placeholder. */
+    (void)dummy;
 
     /*
      * Syntax:   chan create MODE CMDPREFIX
@@ -670,7 +673,7 @@ TclChanCreateObjCmd(
         * as the actual channel type.
         */
 
-       Tcl_ChannelType *clonePtr = ckalloc(sizeof(Tcl_ChannelType));
+       Tcl_ChannelType *clonePtr = (Tcl_ChannelType *)ckalloc(sizeof(Tcl_ChannelType));
 
        memcpy(clonePtr, &tclRChannelType, sizeof(Tcl_ChannelType));
 
@@ -770,6 +773,7 @@ ReflectEventRun(
      */
 
     ReflectEvent *e = (ReflectEvent *) ev;
+    (void)flags;
 
     Tcl_NotifyChannel(e->rcPtr->chan, e->events);
     return 1;
@@ -798,7 +802,7 @@ ReflectEventDelete(
 
 int
 TclChanPostEventObjCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const *objv)
@@ -827,6 +831,7 @@ TclChanPostEventObjCmd(
     ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
                                 * this interp. */
     Tcl_HashEntry *hPtr;       /* Entry in the above map */
+    (void)dummy;
 
     /*
      * Number of arguments...
@@ -855,11 +860,12 @@ TclChanPostEventObjCmd(
     }
 
     /*
-     * Note that the search above subsumes several of the older checks, namely:
+     * Note that the search above subsumes several of the older checks,
+     * namely:
      *
-     * (1) Does the channel handle refer to a reflected channel ?
+     * (1) Does the channel handle refer to a reflected channel?
      * (2) Is the post event issued from the interpreter holding the handler
-     *     of the reflected channel ?
+     *     of the reflected channel?
      *
      * A successful search answers yes to both. Because the map holds only
      * handles of reflected channels, and only of such whose handler is
@@ -870,7 +876,7 @@ TclChanPostEventObjCmd(
      * have gone seriously haywire.
      */
 
-    chan = Tcl_GetHashValue(hPtr);
+    chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
     chanTypePtr = Tcl_GetChannelType(chan);
 
     /*
@@ -886,7 +892,7 @@ TclChanPostEventObjCmd(
        Tcl_Panic("TclChanPostEventObjCmd: channel is not a reflected channel");
     }
 
-    rcPtr = Tcl_GetChannelInstanceData(chan);
+    rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
 
     if (rcPtr->interp != interp) {
        Tcl_Panic("TclChanPostEventObjCmd: postevent accepted for call from outside interpreter");
@@ -922,7 +928,7 @@ TclChanPostEventObjCmd(
         Tcl_NotifyChannel(chan, events);
 #ifdef TCL_THREADS
     } else {
-        ReflectEvent *ev = ckalloc(sizeof(ReflectEvent));
+        ReflectEvent *ev = (ReflectEvent *)ckalloc(sizeof(ReflectEvent));
 
         ev->header.proc = ReflectEventRun;
         ev->events = events;
@@ -943,7 +949,8 @@ TclChanPostEventObjCmd(
 
         (void) GetThreadReflectedChannelMap();
 
-        /* XXX Race condition !!
+        /*
+         * XXX Race condition !!
          * XXX The destination thread may not exist anymore already.
          * XXX (Delayed postevent executed after channel got removed).
          * XXX Can we detect this ? (check the validity of the owner threadid ?)
@@ -1091,7 +1098,7 @@ TclChanCaughtErrorBypass(
 /*
  *----------------------------------------------------------------------
  *
- * ReflectClose --
+ * ReflectClose/ReflectClose2 --
  *
  *     This function is invoked when the channel is closed, to delete the
  *     driver specific instance data.
@@ -1110,7 +1117,7 @@ ReflectClose(
     ClientData clientData,
     Tcl_Interp *interp)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     int result;                        /* Result code for 'close' */
     Tcl_Obj *resObj;           /* Result data for 'close' */
     ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
@@ -1231,6 +1238,18 @@ ReflectClose(
     Tcl_EventuallyFree(rcPtr, (Tcl_FreeProc *) FreeReflectedChannel);
     return (result == TCL_OK) ? EOK : EINVAL;
 }
+
+static int
+ReflectClose2(
+    ClientData clientData,
+    Tcl_Interp *interp,
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return ReflectClose(clientData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -1255,7 +1274,7 @@ ReflectInput(
     int toRead,
     int *errorCodePtr)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *toReadObj;
     int bytec;                 /* Number of returned bytes */
     unsigned char *bytev;      /* Array of returned bytes */
@@ -1276,7 +1295,10 @@ ReflectInput(
 
        if (p.base.code != TCL_OK) {
            if (p.base.code < 0) {
-               /* No error message, this is an errno signal. */
+               /*
+                * No error message, this is an errno signal.
+                */
+
                *errorCodePtr = -p.base.code;
            } else {
                PassReceivedError(rcPtr->chan, &p);
@@ -1296,7 +1318,7 @@ ReflectInput(
 
     Tcl_Preserve(rcPtr);
 
-    toReadObj = Tcl_NewIntObj(toRead);
+    TclNewIntObj(toReadObj, toRead);
     Tcl_IncrRefCount(toReadObj);
 
     if (InvokeTclMethod(rcPtr, METH_READ, toReadObj, NULL, &resObj)!=TCL_OK) {
@@ -1321,7 +1343,7 @@ ReflectInput(
     *errorCodePtr = EOK;
 
     if (bytec > 0) {
-       memcpy(buf, bytev, (size_t) bytec);
+       memcpy(buf, bytev, bytec);
     }
 
  stop:
@@ -1359,7 +1381,7 @@ ReflectOutput(
     int toWrite,
     int *errorCodePtr)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *bufObj;
     Tcl_Obj *resObj;           /* Result data for 'write' */
     int written;
@@ -1379,7 +1401,10 @@ ReflectOutput(
 
        if (p.base.code != TCL_OK) {
            if (p.base.code < 0) {
-               /* No error message, this is an errno signal. */
+               /*
+                * No error message, this is an errno signal.
+                */
+
                *errorCodePtr = -p.base.code;
            } else {
                 PassReceivedError(rcPtr->chan, &p);
@@ -1430,8 +1455,8 @@ ReflectOutput(
 
     if ((written == 0) && (toWrite > 0)) {
        /*
-        * The handler claims to have written nothing of what it was
-        * given. That is bad.
+        * The handler claims to have written nothing of what it was given.
+        * That is bad.
         */
 
        SetChannelErrorStr(rcPtr->chan, msg_write_nothing);
@@ -1485,7 +1510,7 @@ ReflectSeekWide(
     int seekMode,
     int *errorCodePtr)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *offObj, *baseObj;
     Tcl_Obj *resObj;           /* Result for 'seek' */
     Tcl_WideInt newLoc;
@@ -1536,7 +1561,7 @@ ReflectSeekWide(
         goto invalid;
     }
 
-    if (newLoc < Tcl_LongAsWide(0)) {
+    if (newLoc < 0) {
        SetChannelErrorStr(rcPtr->chan, msg_seek_beforestart);
         goto invalid;
     }
@@ -1594,7 +1619,7 @@ ReflectWatch(
     ClientData clientData,
     int mask)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *maskObj;
 
     /*
@@ -1666,7 +1691,7 @@ ReflectBlock(
     ClientData clientData,
     int nonblocking)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *blockObj;
     int errorNum;              /* EINVAL or EOK (success). */
     Tcl_Obj *resObj;           /* Result data for 'blocking' */
@@ -1733,7 +1758,7 @@ ReflectThread(
     ClientData clientData,
     int action)
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
 
     switch (action) {
     case TCL_CHANNEL_THREAD_INSERT:
@@ -1772,7 +1797,7 @@ ReflectSetOption(
     const char *optionName,    /* Name of requested option */
     const char *newValue)      /* The new value */
 {
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *optionObj, *valueObj;
     int result;                        /* Result code for 'configure' */
     Tcl_Obj *resObj;           /* Result data for 'configure' */
@@ -1849,7 +1874,7 @@ ReflectGetOption(
      * The bypass functions are not required.
      */
 
-    ReflectedChannel *rcPtr = clientData;
+    ReflectedChannel *rcPtr = (ReflectedChannel *)clientData;
     Tcl_Obj *optionObj;
     Tcl_Obj *resObj;           /* Result data for 'configure' */
     int listc, result = TCL_OK;
@@ -2065,7 +2090,7 @@ static Tcl_Obj *
 DecodeEventMask(
     int mask)
 {
-    register const char *eventStr;
+    const char *eventStr;
     Tcl_Obj *evObj;
 
     switch (mask & RANDW) {
@@ -2116,7 +2141,7 @@ NewReflectedChannel(
     ReflectedChannel *rcPtr;
     MethodName mn = METH_BLOCKING;
 
-    rcPtr = ckalloc(sizeof(ReflectedChannel));
+    rcPtr = (ReflectedChannel *)ckalloc(sizeof(ReflectedChannel));
 
     /* rcPtr->chan: Assigned by caller. Dummy data here. */
 
@@ -2377,8 +2402,8 @@ InvokeTclMethod(
  *     None.
  *
  * Users:
- *     ReflectInput/Output(), to enable the signaling of EAGAIN
- *     on 0-sized short reads/writes.
+ *     ReflectInput/Output(), to enable the signaling of EAGAIN on 0-sized
+ *     short reads/writes.
  *
  *----------------------------------------------------------------------
  */
@@ -2434,10 +2459,10 @@ static ReflectedChannelMap *
 GetReflectedChannelMap(
     Tcl_Interp *interp)
 {
-    ReflectedChannelMap *rcmPtr = Tcl_GetAssocData(interp, RCMKEY, NULL);
+    ReflectedChannelMap *rcmPtr = (ReflectedChannelMap *)Tcl_GetAssocData(interp, RCMKEY, NULL);
 
     if (rcmPtr == NULL) {
-       rcmPtr = ckalloc(sizeof(ReflectedChannelMap));
+       rcmPtr = (ReflectedChannelMap *)ckalloc(sizeof(ReflectedChannelMap));
        Tcl_InitHashTable(&rcmPtr->map, TCL_STRING_KEYS);
        Tcl_SetAssocData(interp, RCMKEY,
                (Tcl_InterpDeleteProc *) DeleteReflectedChannelMap, rcmPtr);
@@ -2492,7 +2517,7 @@ DeleteReflectedChannelMap(
     ClientData clientData,     /* The per-interpreter data structure. */
     Tcl_Interp *interp)                /* The interpreter being deleted. */
 {
-    ReflectedChannelMap *rcmPtr = clientData;
+    ReflectedChannelMap *rcmPtr = (ReflectedChannelMap *)clientData;
                                /* The map */
     Tcl_HashSearch hSearch;     /* Search variable. */
     Tcl_HashEntry *hPtr;        /* Search variable. */
@@ -2519,8 +2544,8 @@ DeleteReflectedChannelMap(
     for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch)) {
-       chan = Tcl_GetHashValue(hPtr);
-       rcPtr = Tcl_GetChannelInstanceData(chan);
+       chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
+       rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
 
        MarkDead(rcPtr);
        Tcl_DeleteHashEntry(hPtr);
@@ -2564,7 +2589,10 @@ DeleteReflectedChannelMap(
 
        evPtr = resultPtr->evPtr;
 
-       /* Basic crash safety until this routine can get revised [3411310] */
+       /*
+        * Basic crash safety until this routine can get revised [3411310]
+        */
+
        if (evPtr == NULL) {
            continue;
        }
@@ -2594,8 +2622,8 @@ DeleteReflectedChannelMap(
     for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&hSearch)) {
-       chan = Tcl_GetHashValue(hPtr);
-       rcPtr = Tcl_GetChannelInstanceData(chan);
+       chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
+       rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
 
        if (rcPtr->interp != interp) {
            /*
@@ -2635,7 +2663,7 @@ GetThreadReflectedChannelMap(void)
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
     if (!tsdPtr->rcmPtr) {
-       tsdPtr->rcmPtr = ckalloc(sizeof(ReflectedChannelMap));
+       tsdPtr->rcmPtr = (ReflectedChannelMap *)ckalloc(sizeof(ReflectedChannelMap));
        Tcl_InitHashTable(&tsdPtr->rcmPtr->map, TCL_STRING_KEYS);
        Tcl_CreateThreadExitHandler(DeleteThreadReflectedChannelMap, NULL);
     }
@@ -2663,13 +2691,14 @@ GetThreadReflectedChannelMap(void)
 
 static void
 DeleteThreadReflectedChannelMap(
-    ClientData clientData)     /* The per-thread data structure. */
+    ClientData dummy)  /* The per-thread data structure. */
 {
     Tcl_HashSearch hSearch;     /* Search variable. */
     Tcl_HashEntry *hPtr;        /* Search variable. */
     Tcl_ThreadId self = Tcl_GetCurrentThread();
     ReflectedChannelMap *rcmPtr; /* The map */
     ForwardingResult *resultPtr;
+    (void)dummy;
 
     /*
      * The origin thread for one or more reflected channels is gone.
@@ -2679,8 +2708,8 @@ DeleteThreadReflectedChannelMap(
 
     /*
      * Go through the list of pending results and cancel all whose events were
-     * destined for this thread. While this is in progress we block any
-     * other access to the list of pending results.
+     * destined for this thread. While this is in progress we block any other
+     * access to the list of pending results.
      */
 
     Tcl_MutexLock(&rcForwardMutex);
@@ -2711,7 +2740,10 @@ DeleteThreadReflectedChannelMap(
 
        evPtr = resultPtr->evPtr;
 
-       /* Basic crash safety until this routine can get revised [3411310] */
+       /*
+        * Basic crash safety until this routine can get revised [3411310]
+        */
+
        if (evPtr == NULL ) {
            continue;
        }
@@ -2749,8 +2781,8 @@ DeleteThreadReflectedChannelMap(
     for (hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_FirstHashEntry(&rcmPtr->map, &hSearch)) {
-       Tcl_Channel chan = Tcl_GetHashValue(hPtr);
-       ReflectedChannel *rcPtr = Tcl_GetChannelInstanceData(chan);
+       Tcl_Channel chan = (Tcl_Channel)Tcl_GetHashValue(hPtr);
+       ReflectedChannel *rcPtr = (ReflectedChannel *)Tcl_GetChannelInstanceData(chan);
 
        MarkDead(rcPtr);
        Tcl_DeleteHashEntry(hPtr);
@@ -2765,8 +2797,8 @@ ForwardOpToHandlerThread(
     const void *param)         /* Arguments */
 {
     /*
-     * Core of the communication from OWNER to HANDLER thread.
-     * The receiver is ForwardProc() below.
+     * Core of the communication from OWNER to HANDLER thread. The receiver is
+     * ForwardProc() below.
      */
 
     Tcl_ThreadId dst = rcPtr->thread;
@@ -2795,8 +2827,8 @@ ForwardOpToHandlerThread(
      * Create and initialize the event and data structures.
      */
 
-    evPtr = ckalloc(sizeof(ForwardingEvent));
-    resultPtr = ckalloc(sizeof(ForwardingResult));
+    evPtr = (ForwardingEvent *)ckalloc(sizeof(ForwardingEvent));
+    resultPtr = (ForwardingResult *)ckalloc(sizeof(ForwardingResult));
 
     evPtr->event.proc = ForwardProc;
     evPtr->resultPtr = resultPtr;
@@ -2816,7 +2848,10 @@ ForwardOpToHandlerThread(
      */
 
     TclSpliceIn(resultPtr, forwardList);
-    /* Do not unlock here. That is done by the ConditionWait */
+
+    /*
+     * Do not unlock here. That is done by the ConditionWait.
+     */
 
     /*
      * Ensure cleanup of the event if the origin thread exits while this event
@@ -2892,7 +2927,7 @@ ForwardProc(
      * Notes regarding access to the referenced data.
      *
      * In principle the data belongs to the originating thread (see
-     * evPtr->src), however this thread is currently blocked at (*), i.e.
+     * evPtr->src), however this thread is currently blocked at (*), i.e.,
      * quiescent. Because of this we can treat the data as belonging to us,
      * without fear of race conditions. I.e. we can read and write as we like.
      *
@@ -2910,6 +2945,7 @@ ForwardProc(
     ReflectedChannelMap *rcmPtr;/* Map of reflected channels with handlers in
                                  * this interp. */
     Tcl_HashEntry *hPtr;       /* Entry in the above map */
+    (void)mask;
 
     /*
      * Ignore the event if no one is waiting for its result anymore.
@@ -2963,10 +2999,12 @@ ForwardProc(
     }
 
     case ForwardedInput: {
-       Tcl_Obj *toReadObj = Tcl_NewIntObj(paramPtr->input.toRead);
-        Tcl_IncrRefCount(toReadObj);
+       Tcl_Obj *toReadObj;
 
-        Tcl_Preserve(rcPtr);
+       TclNewIntObj(toReadObj, paramPtr->input.toRead);
+       Tcl_IncrRefCount(toReadObj);
+
+       Tcl_Preserve(rcPtr);
        if (InvokeTclMethod(rcPtr, METH_READ, toReadObj, NULL, &resObj)!=TCL_OK){
            int code = ErrnoReturn(rcPtr, resObj);
 
@@ -2991,7 +3029,7 @@ ForwardProc(
                paramPtr->input.toRead = -1;
            } else {
                if (bytec > 0) {
-                   memcpy(paramPtr->input.buf, bytev, (size_t) bytec);
+                   memcpy(paramPtr->input.buf, bytev, bytec);
                }
                paramPtr->input.toRead = bytec;
            }
@@ -3062,7 +3100,7 @@ ForwardProc(
            Tcl_WideInt newLoc;
 
            if (Tcl_GetWideIntFromObj(interp, resObj, &newLoc) == TCL_OK) {
-               if (newLoc < Tcl_LongAsWide(0)) {
+               if (newLoc < 0) {
                    ForwardSetStaticError(paramPtr, msg_seek_beforestart);
                    paramPtr->seek.offset = -1;
                } else {
@@ -3170,7 +3208,7 @@ ForwardProc(
                 * Odd number of elements is wrong. [x].
                 */
 
-               char *buf = ckalloc(200);
+               char *buf = (char *)ckalloc(200);
                sprintf(buf,
                        "{Expected list with even number of elements, got %d %s instead}",
                        listc, (listc == 1 ? "element" : "elements"));
@@ -3227,7 +3265,7 @@ static void
 SrcExitProc(
     ClientData clientData)
 {
-    ForwardingEvent *evPtr = clientData;
+    ForwardingEvent *evPtr = (ForwardingEvent *)clientData;
     ForwardingResult *resultPtr;
     ForwardParam *paramPtr;
 
@@ -3281,7 +3319,7 @@ ForwardSetObjError(
 
     len++;
     ForwardSetDynamicError(paramPtr, ckalloc(len));
-    memcpy(paramPtr->base.msgStr, msgStr, (unsigned) len);
+    memcpy(paramPtr->base.msgStr, msgStr, len);
 }
 #endif
 \f
index af86ba5..039b594 100644 (file)
 #define EOK    0
 #endif
 
-/* DUPLICATE of HaveVersion() in tclIO.c // TODO - MODULE_SCOPE */
-static int             HaveVersion(const Tcl_ChannelType *typePtr,
-                           Tcl_ChannelTypeVersion minimumVersion);
-
 /*
  * Signatures of all functions used in the C layer of the reflection.
  */
 
 static int             ReflectClose(ClientData clientData,
                            Tcl_Interp *interp);
+static int             ReflectClose2(ClientData clientData,
+                           Tcl_Interp *interp, int flags);
 static int             ReflectInput(ClientData clientData, char *buf,
                            int toRead, int *errorCodePtr);
 static int             ReflectOutput(ClientData clientData, const char *buf,
@@ -72,7 +70,7 @@ static const Tcl_ChannelType tclRTransformType = {
     ReflectGetOption,          /* Get options. */
     ReflectWatch,              /* Initialize notifier. */
     ReflectHandle,             /* Get OS handle from the channel. */
-    NULL,                      /* No close2 support. NULL'able. */
+    ReflectClose2,             /* No close2 support. NULL'able. */
     ReflectBlock,              /* Set blocking/nonblocking. */
     NULL,                      /* Flush channel. Not used by core.
                                 * NULL'able. */
@@ -501,7 +499,7 @@ static int          TransformLimit(ReflectedTransform *rtPtr,
 
 int
 TclChanPushObjCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const *objv)
@@ -528,6 +526,7 @@ TclChanPushObjCmd(
                                 * in this interp. */
     Tcl_HashEntry *hPtr;       /* Entry in the above map */
     int isNew;                 /* Placeholder. */
+    (void)dummy;
 
     /*
      * Syntax:   chan push CHANNEL CMDPREFIX
@@ -746,7 +745,7 @@ TclChanPushObjCmd(
 
 int
 TclChanPopObjCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const *objv)
@@ -764,6 +763,7 @@ TclChanPopObjCmd(
     const char *chanId;                /* Tcl level channel handle */
     Tcl_Channel chan;          /* Channel associated to the handle */
     int mode;                  /* Channel r/w mode */
+    (void)dummy;
 
     /*
      * Number of arguments...
@@ -885,7 +885,7 @@ ReflectClose(
     ClientData clientData,
     Tcl_Interp *interp)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
     int errorCode, errorCodeSet = 0;
     int result = TCL_OK;       /* Result code for 'close' */
     Tcl_Obj *resObj;           /* Result data for 'close' */
@@ -1037,6 +1037,18 @@ ReflectClose(
     Tcl_EventuallyFree (rtPtr, (Tcl_FreeProc *) FreeReflectedTransform);
     return errorCodeSet ? errorCode : ((result == TCL_OK) ? EOK : EINVAL);
 }
+
+static int
+ReflectClose2(
+    ClientData clientData,
+    Tcl_Interp *interp,
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return ReflectClose(clientData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -1061,7 +1073,7 @@ ReflectInput(
     int toRead,
     int *errorCodePtr)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
     int gotBytes, copied, readBytes;
     Tcl_Obj *bufObj;
 
@@ -1254,7 +1266,7 @@ ReflectOutput(
     int toWrite,
     int *errorCodePtr)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * The following check can be done before thread redirection, because we
@@ -1327,7 +1339,7 @@ ReflectSeekWide(
     int seekMode,
     int *errorCodePtr)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
     Channel *parent = (Channel *) rtPtr->parent;
     Tcl_WideInt curPos;                /* Position on the device. */
 
@@ -1386,20 +1398,19 @@ ReflectSeekWide(
      * non-NULL...
      */
 
-    if (HaveVersion(parent->typePtr, TCL_CHANNEL_VERSION_3) &&
-       parent->typePtr->wideSeekProc != NULL) {
-       curPos = parent->typePtr->wideSeekProc(parent->instanceData, offset,
+    if (Tcl_ChannelWideSeekProc(parent->typePtr) != NULL) {
+       curPos = Tcl_ChannelWideSeekProc(parent->typePtr)(parent->instanceData, offset,
                seekMode, errorCodePtr);
     } else if (offset < Tcl_LongAsWide(LONG_MIN) ||
            offset > Tcl_LongAsWide(LONG_MAX)) {
        *errorCodePtr = EOVERFLOW;
        curPos = Tcl_LongAsWide(-1);
     } else {
-       curPos = Tcl_LongAsWide(parent->typePtr->seekProc(
+       curPos = Tcl_LongAsWide(Tcl_ChannelSeekProc(parent->typePtr)(
                parent->instanceData, Tcl_WideAsLong(offset), seekMode,
                errorCodePtr));
     }
-    if (curPos == Tcl_LongAsWide(-1)) {
+    if (curPos == -1) {
        Tcl_SetErrno(*errorCodePtr);
     }
 
@@ -1448,7 +1459,7 @@ ReflectWatch(
     ClientData clientData,
     int mask)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
     Tcl_DriverWatchProc *watchProc;
 
     watchProc = Tcl_ChannelWatchProc(Tcl_GetChannelType(rtPtr->parent));
@@ -1499,7 +1510,7 @@ ReflectBlock(
     ClientData clientData,
     int nonblocking)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * Transformations simply record the blocking mode in their C level
@@ -1534,7 +1545,7 @@ ReflectSetOption(
     const char *optionName,    /* Name of requested option */
     const char *newValue)      /* The new value */
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * Transformations have no options. Thus the call is passed down unchanged
@@ -1576,7 +1587,7 @@ ReflectGetOption(
     const char *optionName,    /* Name of reuqested option */
     Tcl_DString *dsPtr)                /* String to place the result into */
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * Transformations have no options. Thus the call is passed down unchanged
@@ -1624,7 +1635,7 @@ ReflectHandle(
     int direction,
     ClientData *handlePtr)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * Transformations have no handle of their own. As such we simply query
@@ -1659,7 +1670,7 @@ ReflectNotify(
     ClientData clientData,
     int mask)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     /*
      * An event occured in the underlying channel.
@@ -1707,7 +1718,7 @@ static Tcl_Obj *
 DecodeEventMask(
     int mask)
 {
-    register const char *eventStr;
+    const char *eventStr;
     Tcl_Obj *evObj;
 
     switch (mask & RANDW) {
@@ -1759,8 +1770,9 @@ NewReflectedTransform(
     int listc;
     Tcl_Obj **listv;
     int i;
+    (void)mode;
 
-    rtPtr = ckalloc(sizeof(ReflectedTransform));
+    rtPtr = (ReflectedTransform *)ckalloc(sizeof(ReflectedTransform));
 
     /* rtPtr->chan: Assigned by caller. Dummy data here. */
     /* rtPtr->methods: Assigned by caller. Dummy data here. */
@@ -1807,7 +1819,7 @@ NewReflectedTransform(
      */
 
     rtPtr->argc = listc + 2;
-    rtPtr->argv = ckalloc(sizeof(Tcl_Obj *) * (listc+4));
+    rtPtr->argv = (Tcl_Obj **)ckalloc(sizeof(Tcl_Obj *) * (listc+4));
 
     /*
      * Duplicate object references.
@@ -2112,10 +2124,10 @@ static ReflectedTransformMap *
 GetReflectedTransformMap(
     Tcl_Interp *interp)
 {
-    ReflectedTransformMap *rtmPtr = Tcl_GetAssocData(interp, RTMKEY, NULL);
+    ReflectedTransformMap *rtmPtr = (ReflectedTransformMap *)Tcl_GetAssocData(interp, RTMKEY, NULL);
 
     if (rtmPtr == NULL) {
-       rtmPtr = ckalloc(sizeof(ReflectedTransformMap));
+       rtmPtr = (ReflectedTransformMap *)ckalloc(sizeof(ReflectedTransformMap));
        Tcl_InitHashTable(&rtmPtr->map, TCL_STRING_KEYS);
        Tcl_SetAssocData(interp, RTMKEY,
                (Tcl_InterpDeleteProc *) DeleteReflectedTransformMap, rtmPtr);
@@ -2170,11 +2182,11 @@ DeleteReflectedTransformMap(
      * this interp.
      */
 
-    rtmPtr = clientData;
+    rtmPtr = (ReflectedTransformMap *)clientData;
     for (hPtr = Tcl_FirstHashEntry(&rtmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_FirstHashEntry(&rtmPtr->map, &hSearch)) {
-       rtPtr = Tcl_GetHashValue(hPtr);
+       rtPtr = (ReflectedTransform *)Tcl_GetHashValue(hPtr);
 
        rtPtr->dead = 1;
        Tcl_DeleteHashEntry(hPtr);
@@ -2198,7 +2210,7 @@ DeleteReflectedTransformMap(
     for (hPtr = Tcl_FirstHashEntry(&rtmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&hSearch)) {
-       rtPtr = Tcl_GetHashValue(hPtr);
+       rtPtr = (ReflectedTransform *)Tcl_GetHashValue(hPtr);
 
        if (rtPtr->interp != interp) {
            /*
@@ -2278,7 +2290,7 @@ GetThreadReflectedTransformMap(void)
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
     if (!tsdPtr->rtmPtr) {
-       tsdPtr->rtmPtr = ckalloc(sizeof(ReflectedTransformMap));
+       tsdPtr->rtmPtr = (ReflectedTransformMap *)ckalloc(sizeof(ReflectedTransformMap));
        Tcl_InitHashTable(&tsdPtr->rtmPtr->map, TCL_STRING_KEYS);
        Tcl_CreateThreadExitHandler(DeleteThreadReflectedTransformMap, NULL);
     }
@@ -2306,13 +2318,14 @@ GetThreadReflectedTransformMap(void)
 
 static void
 DeleteThreadReflectedTransformMap(
-    ClientData clientData)     /* The per-thread data structure. */
+    ClientData dummy)  /* The per-thread data structure. */
 {
     Tcl_HashSearch hSearch;     /* Search variable. */
     Tcl_HashEntry *hPtr;        /* Search variable. */
     Tcl_ThreadId self = Tcl_GetCurrentThread();
     ReflectedTransformMap *rtmPtr; /* The map */
     ForwardingResult *resultPtr;
+    (void)dummy;
 
     /*
      * The origin thread for one or more reflected channels is gone.
@@ -2330,7 +2343,7 @@ DeleteThreadReflectedTransformMap(
     for (hPtr = Tcl_FirstHashEntry(&rtmPtr->map, &hSearch);
            hPtr != NULL;
            hPtr = Tcl_FirstHashEntry(&rtmPtr->map, &hSearch)) {
-       ReflectedTransform *rtPtr = Tcl_GetHashValue(hPtr);
+       ReflectedTransform *rtPtr = (ReflectedTransform *)Tcl_GetHashValue(hPtr);
 
        rtPtr->dead = 1;
        FreeReflectedTransformArgs(rtPtr);
@@ -2413,8 +2426,8 @@ ForwardOpToOwnerThread(
      * Create and initialize the event and data structures.
      */
 
-    evPtr = ckalloc(sizeof(ForwardingEvent));
-    resultPtr = ckalloc(sizeof(ForwardingResult));
+    evPtr = (ForwardingEvent *)ckalloc(sizeof(ForwardingEvent));
+    resultPtr = (ForwardingResult *)ckalloc(sizeof(ForwardingResult));
 
     evPtr->event.proc = ForwardProc;
     evPtr->resultPtr = resultPtr;
@@ -2525,6 +2538,7 @@ ForwardProc(
                                /* Map of reflected channels with handlers in
                                 * this interp. */
     Tcl_HashEntry *hPtr;       /* Entry in the above map */
+    (void)mask;
 
     /*
      * Ignore the event if no one is waiting for its result anymore.
@@ -2607,8 +2621,8 @@ ForwardProc(
            paramPtr->transform.size = bytec;
 
            if (bytec > 0) {
-               paramPtr->transform.buf = ckalloc(bytec);
-               memcpy(paramPtr->transform.buf, bytev, (size_t)bytec);
+               paramPtr->transform.buf = (char *)ckalloc(bytec);
+               memcpy(paramPtr->transform.buf, bytev, bytec);
            } else {
                paramPtr->transform.buf = NULL;
            }
@@ -2641,8 +2655,8 @@ ForwardProc(
            paramPtr->transform.size = bytec;
 
            if (bytec > 0) {
-               paramPtr->transform.buf = ckalloc(bytec);
-               memcpy(paramPtr->transform.buf, bytev, (size_t)bytec);
+               paramPtr->transform.buf = (char *)ckalloc(bytec);
+               memcpy(paramPtr->transform.buf, bytev, bytec);
            } else {
                paramPtr->transform.buf = NULL;
            }
@@ -2670,8 +2684,8 @@ ForwardProc(
            paramPtr->transform.size = bytec;
 
            if (bytec > 0) {
-               paramPtr->transform.buf = ckalloc(bytec);
-               memcpy(paramPtr->transform.buf, bytev, (size_t)bytec);
+               paramPtr->transform.buf = (char *)ckalloc(bytec);
+               memcpy(paramPtr->transform.buf, bytev, bytec);
            } else {
                paramPtr->transform.buf = NULL;
            }
@@ -2697,8 +2711,8 @@ ForwardProc(
            paramPtr->transform.size = bytec;
 
            if (bytec > 0) {
-               paramPtr->transform.buf = ckalloc(bytec);
-               memcpy(paramPtr->transform.buf, bytev, (size_t)bytec);
+               paramPtr->transform.buf = (char *)ckalloc(bytec);
+               memcpy(paramPtr->transform.buf, bytev, bytec);
            } else {
                paramPtr->transform.buf = NULL;
            }
@@ -2757,7 +2771,7 @@ static void
 SrcExitProc(
     ClientData clientData)
 {
-    ForwardingEvent *evPtr = clientData;
+    ForwardingEvent *evPtr = (ForwardingEvent *)clientData;
     ForwardingResult *resultPtr;
     ForwardParam *paramPtr;
 
@@ -2811,7 +2825,7 @@ ForwardSetObjError(
 
     len++;
     ForwardSetDynamicError(paramPtr, ckalloc(len));
-    memcpy(paramPtr->base.msgStr, msgStr, (unsigned) len);
+    memcpy(paramPtr->base.msgStr, msgStr, len);
 }
 #endif /* TCL_THREADS */
 \f
@@ -2897,7 +2911,7 @@ static void
 TimerRun(
     ClientData clientData)
 {
-    ReflectedTransform *rtPtr = clientData;
+    ReflectedTransform *rtPtr = (ReflectedTransform *)clientData;
 
     rtPtr->timer = NULL;
     Tcl_NotifyChannel(rtPtr->chan, TCL_READABLE);
@@ -3391,33 +3405,6 @@ TransformLimit(
     return 1;
 }
 \f
-/* DUPLICATE of HaveVersion() in tclIO.c
- *----------------------------------------------------------------------
- *
- * HaveVersion --
- *
- *     Return whether a channel type is (at least) of a given version.
- *
- * Results:
- *     True if the minimum version is exceeded by the version actually
- *     present.
- *
- * Side effects:
- *     None.
- *
- *----------------------------------------------------------------------
- */
-
-static int
-HaveVersion(
-    const Tcl_ChannelType *chanTypePtr,
-    Tcl_ChannelTypeVersion minimumVersion)
-{
-    Tcl_ChannelTypeVersion actualVersion = Tcl_ChannelVersion(chanTypePtr);
-
-    return PTR2INT(actualVersion) >= PTR2INT(minimumVersion);
-}
-\f
 /*
  * Local Variables:
  * mode: c
index 8a1e3e6..6413960 100644 (file)
@@ -11,7 +11,7 @@
 
 #include "tclInt.h"
 
-#if defined(_WIN32) && defined(UNICODE)
+#if defined(_WIN32)
 /* On Windows, we need to do proper Unicode->UTF-8 conversion. */
 
 typedef struct ThreadSpecificData {
index 4235c3e..5566f3e 100644 (file)
@@ -184,7 +184,7 @@ const Tcl_Filesystem tclNativeFilesystem = {
     TclpObjCopyDirectory,
     TclpObjLstat,
     /* Needs casts since we're using version_2. */
-    (Tcl_FSLoadFileProc *) TclpDlopen,
+    (Tcl_FSLoadFileProc *)(void *) TclpDlopen,
     (Tcl_FSGetCwdProc *) TclpGetNativeCwd,
     TclpObjChdir
 };
@@ -1798,7 +1798,7 @@ Tcl_FSEvalFileEx(
      */
 
     if (Tcl_ReadChars(chan, objPtr, -1,
-           memcmp(string, "\xef\xbb\xbf", 3)) < 0) {
+           memcmp(string, "\xEF\xBB\xBF", 3)) < 0) {
        Tcl_Close(interp, chan);
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "couldn't read file \"%s\": %s",
@@ -1933,7 +1933,7 @@ TclNREvalFile(
      */
 
     if (Tcl_ReadChars(chan, objPtr, -1,
-           memcmp(string, "\xef\xbb\xbf", 3)) < 0) {
+           memcmp(string, "\xEF\xBB\xBF", 3)) < 0) {
        Tcl_Close(interp, chan);
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "couldn't read file \"%s\": %s",
@@ -3244,7 +3244,7 @@ Tcl_LoadFile(
     }
 
     if (fsPtr->loadFileProc != NULL) {
-       int retVal = ((Tcl_FSLoadFileProc2 *)(fsPtr->loadFileProc))
+       retVal = ((Tcl_FSLoadFileProc2 *)(void *)(fsPtr->loadFileProc))
                (interp, pathPtr, handlePtr, &unloadProcPtr, flags);
 
        if (retVal == TCL_OK) {
@@ -4209,7 +4209,7 @@ TclFSNonnativePathType(
                    if (pathLen < len) {
                        continue;
                    }
-                   if (strncmp(strVol, path, (size_t) len) == 0) {
+                   if (strncmp(strVol, path, len) == 0) {
                        type = TCL_PATH_ABSOLUTE;
                        if (filesystemPtrPtr != NULL) {
                            *filesystemPtrPtr = fsRecPtr->fsPtr;
@@ -4619,7 +4619,7 @@ Tcl_FSGetFileSystemForPath(
     /*
      * Check if the filesystem has changed in some way since this object's
      * internal representation was calculated. Before doing that, assure we
-     * have the most up-to-date copy of the master filesystem. This is
+     * have the most up-to-date copy of the first filesystem. This is
      * accomplished by the FsGetFirstFilesystem() call.
      */
 
index 30c33f1..7e23931 100644 (file)
@@ -22,7 +22,6 @@
 static int             GetIndexFromObjList(Tcl_Interp *interp,
                            Tcl_Obj *objPtr, Tcl_Obj *tableObjPtr,
                            const char *msg, int flags, int *indexPtr);
-static int             SetIndexFromAny(Tcl_Interp *interp, Tcl_Obj *objPtr);
 static void            UpdateStringOfIndex(Tcl_Obj *objPtr);
 static void            DupIndex(Tcl_Obj *srcPtr, Tcl_Obj *dupPtr);
 static void            FreeIndex(Tcl_Obj *objPtr);
@@ -48,7 +47,7 @@ static const Tcl_ObjType indexType = {
     FreeIndex,                 /* freeIntRepProc */
     DupIndex,                  /* dupIntRepProc */
     UpdateStringOfIndex,       /* updateStringProc */
-    SetIndexFromAny            /* setFromAnyProc */
+    NULL                       /* setFromAnyProc */
 };
 
 /*
@@ -397,39 +396,6 @@ Tcl_GetIndexFromObjStruct(
 /*
  *----------------------------------------------------------------------
  *
- * SetIndexFromAny --
- *
- *     This function is called to convert a Tcl object to index internal
- *     form. However, this doesn't make sense (need to have a table of
- *     keywords in order to do the conversion) so the function always
- *     generates an error.
- *
- * Results:
- *     The return value is always TCL_ERROR, and an error message is left in
- *     interp's result if interp isn't NULL.
- *
- * Side effects:
- *     None.
- *
- *----------------------------------------------------------------------
- */
-
-static int
-SetIndexFromAny(
-    Tcl_Interp *interp,                /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
-{
-    if (interp) {
-       Tcl_SetObjResult(interp, Tcl_NewStringObj(
-           "can't convert value to index except via Tcl_GetIndexFromObj API",
-           -1));
-    }
-    return TCL_ERROR;
-}
-\f
-/*
- *----------------------------------------------------------------------
- *
  * UpdateStringOfIndex --
  *
  *     This function is called to convert a Tcl object from index internal
@@ -449,9 +415,9 @@ UpdateStringOfIndex(
     Tcl_Obj *objPtr)
 {
     IndexRep *indexRep = objPtr->internalRep.twoPtrValue.ptr1;
-    register char *buf;
-    register unsigned len;
-    register const char *indexStr = EXPAND_OF(indexRep);
+    char *buf;
+    unsigned len;
+    const char *indexStr = EXPAND_OF(indexRep);
 
     len = strlen(indexStr);
     buf = ckalloc(len + 1);
@@ -814,7 +780,7 @@ PrefixLongestObjCmd(
                     * Adjust in case we stopped in the middle of a UTF char.
                     */
 
-                   resultLength = Tcl_UtfPrev(&resultString[i+1],
+                   resultLength = TclUtfPrev(&resultString[i+1],
                            resultString) - resultString;
                    break;
                }
@@ -961,7 +927,7 @@ Tcl_WrongNumArgs(
             */
 
            if (origObjv[i]->typePtr == &indexType) {
-               register IndexRep *indexRep =
+               IndexRep *indexRep =
                        origObjv[i]->internalRep.twoPtrValue.ptr1;
 
                elementStr = EXPAND_OF(indexRep);
@@ -1011,7 +977,7 @@ Tcl_WrongNumArgs(
         */
 
        if (objv[i]->typePtr == &indexType) {
-           register IndexRep *indexRep = objv[i]->internalRep.twoPtrValue.ptr1;
+           IndexRep *indexRep = objv[i]->internalRep.twoPtrValue.ptr1;
 
            Tcl_AppendStringsToObj(objPtr, EXPAND_OF(indexRep), NULL);
        } else {
@@ -1103,14 +1069,14 @@ Tcl_ParseArgsObjv(
                                 * successful exit. Will include the name of
                                 * the command. */
     int nrem;                  /* Size of leftovers.*/
-    register const Tcl_ArgvInfo *infoPtr;
+    const Tcl_ArgvInfo *infoPtr;
                                /* Pointer to the current entry in the table
                                 * of argument descriptions. */
     const Tcl_ArgvInfo *matchPtr;
                                /* Descriptor that matches current argument */
     Tcl_Obj *curArg;           /* Current argument */
     const char *str = NULL;
-    register char c;           /* Second character of current arg (used for
+    char c;            /* Second character of current arg (used for
                                 * quick check for matching; use 2nd char.
                                 * because first char. will almost always be
                                 * '-'). */
@@ -1358,7 +1324,7 @@ PrintUsage(
                                /* Array of command-specific argument
                                 * descriptions. */
 {
-    register const Tcl_ArgvInfo *infoPtr;
+    const Tcl_ArgvInfo *infoPtr;
     int width, numSpaces;
 #define NUM_SPACES 20
     static const char spaces[] = "                    ";
index 2739122..b858dfa 100644 (file)
@@ -73,7 +73,7 @@ declare 11 {
 declare 12 {
     void TclDeleteVars(Interp *iPtr, TclVarHashTable *tablePtr)
 }
-# Removed in 8.5
+# Removed in 8.5:
 #declare 13 {
 #    int TclDoGlob(Tcl_Interp *interp, char *separators,
 #          Tcl_DString *headPtr, char *tail, Tcl_GlobTypeData *types)
@@ -88,7 +88,7 @@ declare 14 {
 declare 16 {
     void TclExprFloatError(Tcl_Interp *interp, double value)
 }
-# Removed in 8.4
+# Removed in 8.4:
 #declare 17 {
 #    int TclFileAttrsCmd(Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
 #}
@@ -123,7 +123,7 @@ declare 25 {
 #  declare 26 {
 #      char *TclGetCwd(Tcl_Interp *interp)
 #  }
-# Removed in 8.5
+# Removed in 8.5:
 #declare 27 {
 #    int TclGetDate(char *p, unsigned long now, long zone,
 #          unsigned long *timePtr)
@@ -147,7 +147,7 @@ declare 32 {
     int TclGetFrame(Tcl_Interp *interp, const char *str,
            CallFrame **framePtrPtr)
 }
-# Removed in Tcl 8.5
+# Removed in 8.5:
 #declare 33 {
 #    TclCmdProcType TclGetInterpProc(void)
 #}
@@ -185,9 +185,9 @@ declare 41 {
 declare 42 {
     CONST86 char *TclpGetUserHome(const char *name, Tcl_DString *bufferPtr)
 }
-# Removed in Tcl 8.5a2
+# Removed in 8.5a2:
 #declare 43 {
-#    int TclGlobalInvoke(Tcl_Interp *interp, int argc, CONST84 char **argv,
+#    int TclGlobalInvoke(Tcl_Interp *interp, int argc, const char **argv,
 #          int flags)
 #}
 declare 44 {
@@ -220,9 +220,9 @@ declare 50 {
 declare 51 {
     int TclInterpInit(Tcl_Interp *interp)
 }
-# Removed in Tcl 8.5a2
+# Removed in 8.5a2:
 #declare 52 {
-#    int TclInvoke(Tcl_Interp *interp, int argc, CONST84 char **argv,
+#    int TclInvoke(Tcl_Interp *interp, int argc, const char **argv,
 #          int flags)
 #}
 declare 53 {
@@ -273,7 +273,7 @@ declare 64 {
     int TclObjInvoke(Tcl_Interp *interp, int objc, Tcl_Obj *const objv[],
            int flags)
 }
-# Removed in Tcl 8.5a2
+# Removed in 8.5a2:
 #declare 65 {
 #    int TclObjInvokeGlobal(Tcl_Interp *interp, int objc,
 #          Tcl_Obj *const objv[], int flags)
@@ -380,9 +380,9 @@ declare 92 {
 declare 93 {
     void TclProcDeleteProc(ClientData clientData)
 }
-# Removed in Tcl 8.5:
+# Removed in 8.5:
 #declare 94 {
-#    int TclProcInterpProc(ClientData clientData, Tcl_Interp *interp,
+#    int TclProcInterpProc(void *clientData, Tcl_Interp *interp,
 #          int argc, const char **argv)
 #}
 # Replaced by Tcl_FSStat in 8.4:
@@ -555,7 +555,7 @@ declare 138 {
 #declare 139 {
 #    int TclpLoadFile(Tcl_Interp *interp, char *fileName, char *sym1,
 #          char *sym2, Tcl_PackageInitProc **proc1Ptr,
-#          Tcl_PackageInitProc **proc2Ptr, ClientData *clientDataPtr)
+#          Tcl_PackageInitProc **proc2Ptr, void **clientDataPtr)
 #}
 #declare 140 {
 #    int TclLooksLikeInt(const char *bytes, int length)
@@ -610,11 +610,11 @@ declare 153 {
 
 # moved to tclTest.c (static) in 8.3.2/8.4a2
 #declare 154 {
-#    int TclTestChannelCmd(ClientData clientData,
+#    int TclTestChannelCmd(void *clientData,
 #    Tcl_Interp *interp, int argc, char **argv)
 #}
 #declare 155 {
-#    int TclTestChannelEventCmd(ClientData clientData,
+#    int TclTestChannelEventCmd(void *clientData,
 #           Tcl_Interp *interp, int argc, char **argv)
 #}
 
@@ -903,7 +903,7 @@ declare 227 {
 #  Used to be needed for TclOO-extension; unneeded now that TclOO is in the
 #  core and NRE-enabled
 #  declare 228 {
-#      int TclObjInterpProcCore(register Tcl_Interp *interp, Tcl_Obj *procNameObj,
+#      int TclObjInterpProcCore(Tcl_Interp *interp, Tcl_Obj *procNameObj,
 #             int skip, ProcErrorProc *errorProc)
 #  }
 declare 229 {
@@ -1037,7 +1037,13 @@ declare 256 {
     int        TclPtrUnsetVar(Tcl_Interp *interp, Tcl_Var varPtr, Tcl_Var arrayPtr,
            Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, const int flags)
 }
-declare 258 {
+
+declare 257 {
+    void TclStaticPackage(Tcl_Interp *interp, const char *pkgName,
+           Tcl_PackageInitProc *initProc, Tcl_PackageInitProc *safeInitProc)
+}
+
+declare 260 {
     void TclUnusedStubEntry(void)
 }
 \f
@@ -1206,10 +1212,9 @@ declare 4 unix {
            const char **argv, TclFile inputFile, TclFile outputFile,
            TclFile errorFile, Tcl_Pid *pidPtr)
 }
-# Signature changed in 8.1:
-#  declare 5 unix {
-#      TclFile TclpCreateTempFile(char *contents, Tcl_DString *namePtr)
-#  }
+declare 5 unix {
+    int TclUnixWaitForFile_(int fd, int mask, int timeout)
+}
 declare 6 unix {
     TclFile TclpMakeFile(Tcl_Channel channel, int direction)
 }
@@ -1253,26 +1258,29 @@ declare 14 unix {
 ################################
 # Mac OS X specific functions
 
-declare 15 macosx {
+declare 15 {unix macosx} {
     int TclMacOSXGetFileAttribute(Tcl_Interp *interp, int objIndex,
            Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr)
 }
-declare 16 macosx {
+declare 16 {unix macosx} {
     int TclMacOSXSetFileAttribute(Tcl_Interp *interp, int objIndex,
            Tcl_Obj *fileName, Tcl_Obj *attributePtr)
 }
-declare 17 macosx {
+declare 17 {unix macosx} {
     int TclMacOSXCopyFileAttributes(const char *src, const char *dst,
            const Tcl_StatBuf *statBufPtr)
 }
-declare 18 macosx {
+declare 18 {unix macosx} {
     int TclMacOSXMatchType(Tcl_Interp *interp, const char *pathName,
            const char *fileName, Tcl_StatBuf *statBufPtr,
            Tcl_GlobTypeData *types)
 }
-declare 19 macosx {
+declare 19 {unix macosx} {
     void TclMacOSXNotifierAddRunLoopMode(const void *runLoopMode)
 }
+declare 22 {unix macosx} {
+    TclFile TclpCreateTempFile_(const char *contents)
+}
 
 declare 29 {win unix} {
     int TclWinCPUID(unsigned int index, unsigned int *regs)
@@ -1282,8 +1290,6 @@ declare 30 {win unix} {
     int TclUnixOpenTemporaryFile(Tcl_Obj *dirObj, Tcl_Obj *basenameObj,
            Tcl_Obj *extensionObj, Tcl_Obj *resultingNameObj)
 }
-
-
 \f
 # Local Variables:
 # mode: tcl
index 39fb740..f2f097c 100644 (file)
@@ -877,6 +877,12 @@ typedef struct VarInHash {
  *----------------------------------------------------------------
  */
 
+#if defined(__GNUC__) && (__GNUC__ > 2)
+#   define TCLFLEXARRAY 0
+#else
+#   define TCLFLEXARRAY 1
+#endif
+
 /*
  * Forward declaration to prevent an error when the forward reference to
  * Command is encountered in the Proc and ImportRef types declared below.
@@ -920,7 +926,7 @@ typedef struct CompiledLocal {
                                 * is marked by a unique ClientData tag during
                                 * compilation, and that same tag is used to
                                 * find the variable at runtime. */
-    char name[1];              /* Name of the local variable starts here. If
+    char name[TCLFLEXARRAY];           /* Name of the local variable starts here. If
                                 * the name is NULL, this will just be '\0'.
                                 * The actual size of this field will be large
                                 * enough to hold the name. MUST BE THE LAST
@@ -1254,7 +1260,7 @@ typedef struct CFWordBC {
 typedef struct ContLineLoc {
     int num;                   /* Number of entries in loc, not counting the
                                 * final -1 marker entry. */
-    int loc[1];                        /* Table of locations, as character offsets.
+    int loc[TCLFLEXARRAY];/* Table of locations, as character offsets.
                                 * The table is allocated as part of the
                                 * structure, extending behind the nominal end
                                 * of the structure. An entry containing the
@@ -1403,7 +1409,7 @@ typedef struct ExecStack {
     Tcl_Obj **markerPtr;
     Tcl_Obj **endPtr;
     Tcl_Obj **tosPtr;
-    Tcl_Obj *stackWords[1];
+    Tcl_Obj *stackWords[TCLFLEXARRAY];
 } ExecStack;
 
 /*
@@ -1682,6 +1688,7 @@ typedef struct Command {
 #define CMD_COMPILES_EXPANDED      0x08
 #define CMD_REDEF_IN_PROGRESS      0x10
 #define CMD_VIA_RESOLVER           0x20
+#define CMD_DEAD                    0x40
 
 
 /*
@@ -1804,7 +1811,7 @@ typedef struct Interp {
                                 * of hidden commands on a per-interp
                                 * basis. */
     ClientData interpInfo;     /* Information used by tclInterp.c to keep
-                                * track of master/slave interps on a
+                                * track of parent/child interps on a
                                 * per-interp basis. */
     union {
        void (*optimizer)(void *envPtr);
@@ -2082,7 +2089,7 @@ typedef struct Interp {
      *  (c) are accessed very often (e.g., at each command call)
      *
      * Note that these are the same for all interps in the same thread. They
-     * just have to be initialised for the thread's master interp, slaves
+     * just have to be initialised for the thread's parent interp, children
      * inherit the value.
      *
      * They are used by the macros defined below.
@@ -2600,20 +2607,20 @@ typedef void (TclInitProcessGlobalValueProc)(char **valuePtr, int *lengthPtr,
 /*
  * A ProcessGlobalValue struct exists for each internal value in Tcl that is
  * to be shared among several threads. Each thread sees a (Tcl_Obj) copy of
- * the value, and the master is kept as a counted string, with epoch and mutex
- * control. Each ProcessGlobalValue struct should be a static variable in some
- * file.
+ * the value, and the gobal value is kept as a counted string, with epoch and
+ * mutex control. Each ProcessGlobalValue struct should be a static variable in
+ * some file.
  */
 
 typedef struct ProcessGlobalValue {
     int epoch;                 /* Epoch counter to detect changes in the
-                                * master value. */
-    int numBytes;              /* Length of the master string. */
-    char *value;               /* The master string value. */
-    Tcl_Encoding encoding;     /* system encoding when master string was
+                                * global value. */
+    int numBytes;              /* Length of the global string. */
+    char *value;               /* The global string value. */
+    Tcl_Encoding encoding;     /* system encoding when global string was
                                 * initialized. */
     TclInitProcessGlobalValueProc *proc;
-                               /* A procedure to initialize the master string
+                               /* A procedure to initialize the global string
                                 * copy when a "get" request comes in before
                                 * any "set" request has been received. */
     Tcl_Mutex mutex;           /* Enforce orderly access from multiple
@@ -3025,7 +3032,6 @@ MODULE_SCOPE void TclInitNotifier(void);
 MODULE_SCOPE void      TclInitObjSubsystem(void);
 MODULE_SCOPE void      TclInitSubsystems(void);
 MODULE_SCOPE int       TclInterpReady(Tcl_Interp *interp);
-MODULE_SCOPE int       TclIsSpaceProc(int byte);
 MODULE_SCOPE int       TclIsBareword(int byte);
 MODULE_SCOPE Tcl_Obj * TclJoinPath(int elements, Tcl_Obj * const objv[],
                            int forceRelative);
@@ -3066,8 +3072,6 @@ MODULE_SCOPE int  TclObjUnsetVar2(Tcl_Interp *interp,
                            Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, int flags);
 MODULE_SCOPE int       TclParseBackslash(const char *src,
                            int numBytes, int *readPtr, char *dst);
-MODULE_SCOPE int       TclParseHex(const char *src, int numBytes,
-                           int *resultPtr);
 MODULE_SCOPE int       TclParseNumber(Tcl_Interp *interp, Tcl_Obj *objPtr,
                            const char *expected, const char *bytes,
                            int numBytes, const char **endPtrPtr, int flags);
@@ -3100,8 +3104,8 @@ MODULE_SCOPE void TclpInitLock(void);
 MODULE_SCOPE void      TclpInitPlatform(void);
 MODULE_SCOPE void      TclpInitUnlock(void);
 MODULE_SCOPE Tcl_Obj * TclpObjListVolumes(void);
-MODULE_SCOPE void      TclpMasterLock(void);
-MODULE_SCOPE void      TclpMasterUnlock(void);
+MODULE_SCOPE void      TclpGlobalLock(void);
+MODULE_SCOPE void      TclpGlobalUnlock(void);
 MODULE_SCOPE int       TclpMatchFiles(Tcl_Interp *interp, char *separators,
                            Tcl_DString *dirPtr, char *pattern, char *tail);
 MODULE_SCOPE int       TclpObjNormalizePath(Tcl_Interp *interp,
@@ -3127,7 +3131,6 @@ MODULE_SCOPE Tcl_Obj *    TclPathPart(Tcl_Interp *interp, Tcl_Obj *pathPtr,
                            Tcl_PathPart portion);
 MODULE_SCOPE char *    TclpReadlink(const char *fileName,
                            Tcl_DString *linkPtr);
-MODULE_SCOPE void      TclpSetInterfaces(void);
 MODULE_SCOPE void      TclpSetVariables(Tcl_Interp *interp);
 MODULE_SCOPE void *    TclThreadStorageKeyGet(Tcl_ThreadDataKey *keyPtr);
 MODULE_SCOPE void      TclThreadStorageKeySet(Tcl_ThreadDataKey *keyPtr,
@@ -3168,7 +3171,7 @@ MODULE_SCOPE int  TclStringMatch(const char *str, int strLen,
                            const char *pattern, int ptnLen, int flags);
 MODULE_SCOPE int       TclStringMatchObj(Tcl_Obj *stringObj,
                            Tcl_Obj *patternObj, int flags);
-MODULE_SCOPE Tcl_Obj * TclStringObjReverse(Tcl_Obj *objPtr);
+MODULE_SCOPE Tcl_Obj * TclStringReverse(Tcl_Obj *objPtr);
 MODULE_SCOPE void      TclSubstCompile(Tcl_Interp *interp, const char *bytes,
                            int numBytes, int flags, int line,
                            struct CompileEnv *envPtr);
@@ -3187,6 +3190,24 @@ MODULE_SCOPE int TclTrimLeft(const char *bytes, int numBytes,
 MODULE_SCOPE int       TclTrimRight(const char *bytes, int numBytes,
                            const char *trim, int numTrim);
 MODULE_SCOPE int       TclUtfCasecmp(const char *cs, const char *ct);
+MODULE_SCOPE int       TclUtfToUCS4(const char *, int *);
+MODULE_SCOPE int       TclUCS4ToUtf(int, char *);
+MODULE_SCOPE int       TclUCS4ToLower(int ch);
+#if TCL_UTF_MAX == 4
+    MODULE_SCOPE int   TclGetUCS4(Tcl_Obj *, int);
+    MODULE_SCOPE int   TclUniCharToUCS4(const Tcl_UniChar *, int *);
+#else
+#   define TclGetUCS4 Tcl_GetUniChar
+#   define TclUniCharToUCS4(src, ptr) (*ptr = *(src),1)
+#endif
+
+/*
+ * Bytes F0-F4 are start-bytes for 4-byte sequences.
+ * Byte 0xED can be the start-byte of an upper surrogate. In that case,
+ * TclUtfToUCS4() might read the lower surrogate following it too.
+ */
+#   define TclUCS4Complete(src, length) (((unsigned)(UCHAR(*(src)) - 0xF0) < 5) \
+           ? ((length) >= 4) : (UCHAR(*(src)) == 0xED) ? ((length) >= 6) : Tcl_UtfCharComplete((src), (length)))
 MODULE_SCOPE Tcl_Obj * TclpNativeToNormalized(ClientData clientData);
 MODULE_SCOPE Tcl_Obj * TclpFilesystemPathType(Tcl_Obj *pathPtr);
 MODULE_SCOPE int       TclpDlopen(Tcl_Interp *interp, Tcl_Obj *pathPtr,
@@ -3228,12 +3249,22 @@ MODULE_SCOPE Tcl_WideInt TclpGetMicroseconds(void);
 MODULE_SCOPE int       TclZlibInit(Tcl_Interp *interp);
 MODULE_SCOPE void *    TclpThreadCreateKey(void);
 MODULE_SCOPE void      TclpThreadDeleteKey(void *keyPtr);
-MODULE_SCOPE void      TclpThreadSetMasterTSD(void *tsdKeyPtr, void *ptr);
-MODULE_SCOPE void *    TclpThreadGetMasterTSD(void *tsdKeyPtr);
+MODULE_SCOPE void      TclpThreadSetGlobalTSD(void *tsdKeyPtr, void *ptr);
+MODULE_SCOPE void *    TclpThreadGetGlobalTSD(void *tsdKeyPtr);
 
 MODULE_SCOPE void      TclErrorStackResetIf(Tcl_Interp *interp, const char *msg, int length);
 
 /*
+ * Many parsing tasks need a common definition of whitespace.
+ * Use this routine and macro to achieve that and place
+ * optimization (fragile on changes) in one place.
+ */
+
+MODULE_SCOPE int       TclIsSpaceProc(int byte);
+#      define TclIsSpaceProcM(byte) \
+               (((byte) > 0x20) ? 0 : TclIsSpaceProc(byte))
+
+/*
  *----------------------------------------------------------------
  * Command procedures in the generic core:
  *----------------------------------------------------------------
@@ -4284,8 +4315,8 @@ MODULE_SCOPE void TclDbInitNewObj(Tcl_Obj *objPtr, const char *file,
        (objPtr)->bytes  = tclEmptyStringRep; \
        (objPtr)->length = 0; \
     } else { \
-       (objPtr)->bytes = (char *) ckalloc((unsigned) ((len) + 1)); \
-       memcpy((objPtr)->bytes, (bytePtr), (unsigned) (len)); \
+       (objPtr)->bytes = (char *) ckalloc((len) + 1); \
+       memcpy((objPtr)->bytes, (bytePtr), (len)); \
        (objPtr)->bytes[len] = '\0'; \
        (objPtr)->length = (len); \
     }
@@ -4338,12 +4369,18 @@ MODULE_SCOPE void       TclDbInitNewObj(Tcl_Obj *objPtr, const char *file,
  */
 
 #define TclInvalidateStringRep(objPtr) \
-    if (objPtr->bytes != NULL) { \
-       if (objPtr->bytes != tclEmptyStringRep) { \
-           ckfree((char *) objPtr->bytes); \
+    do { \
+       Tcl_Obj *_isobjPtr = (Tcl_Obj *)(objPtr); \
+       if (_isobjPtr->bytes != NULL) { \
+           if (_isobjPtr->bytes != tclEmptyStringRep) { \
+               ckfree((char *)_isobjPtr->bytes); \
+           } \
+           _isobjPtr->bytes = NULL; \
        } \
-       objPtr->bytes = NULL; \
-    }
+    } while (0)
+
+#define TclHasStringRep(objPtr) \
+    ((objPtr)->bytes != NULL)
 
 /*
  *----------------------------------------------------------------
@@ -4429,8 +4466,8 @@ MODULE_SCOPE void TclDbInitNewObj(Tcl_Obj *objPtr, const char *file,
  */
 
 #define TclUtfToUniChar(str, chPtr) \
-       ((((unsigned char) *(str)) < 0x80) ?            \
-           ((*(chPtr) = (unsigned char) *(str)), 1)    \
+       (((UCHAR(*(str))) < 0x80) ?             \
+           ((*(chPtr) = UCHAR(*(str))), 1)     \
            : Tcl_UtfToUniChar(str, chPtr))
 
 /*
@@ -4457,6 +4494,11 @@ MODULE_SCOPE void        TclDbInitNewObj(Tcl_Obj *objPtr, const char *file,
        (numChars) = _count; \
     } while (0);
 
+#define TclUtfPrev(src, start) \
+       (((src) < (start)+2) ? (start) : \
+       (UCHAR(*((src) - 1))) < 0x80 ? (src)-1 : \
+       Tcl_UtfPrev(src, start))
+
 /*
  *----------------------------------------------------------------
  * Macro that encapsulates the logic that determines when it is safe to
index 4039e9f..ffe0e17 100644 (file)
@@ -638,8 +638,14 @@ EXTERN int         TclPtrObjMakeUpvar(Tcl_Interp *interp,
 EXTERN int             TclPtrUnsetVar(Tcl_Interp *interp, Tcl_Var varPtr,
                                Tcl_Var arrayPtr, Tcl_Obj *part1Ptr,
                                Tcl_Obj *part2Ptr, const int flags);
-/* Slot 257 is reserved */
-/* 258 */
+/* 257 */
+EXTERN void            TclStaticPackage(Tcl_Interp *interp,
+                               const char *pkgName,
+                               Tcl_PackageInitProc *initProc,
+                               Tcl_PackageInitProc *safeInitProc);
+/* Slot 258 is reserved */
+/* Slot 259 is reserved */
+/* 260 */
 EXTERN void            TclUnusedStubEntry(void);
 
 typedef struct TclIntStubs {
@@ -903,8 +909,10 @@ typedef struct TclIntStubs {
     Tcl_Obj * (*tclPtrIncrObjVar) (Tcl_Interp *interp, Tcl_Var varPtr, Tcl_Var arrayPtr, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, Tcl_Obj *incrPtr, const int flags); /* 254 */
     int (*tclPtrObjMakeUpvar) (Tcl_Interp *interp, Tcl_Var otherPtr, Tcl_Obj *myNamePtr, int myFlags); /* 255 */
     int (*tclPtrUnsetVar) (Tcl_Interp *interp, Tcl_Var varPtr, Tcl_Var arrayPtr, Tcl_Obj *part1Ptr, Tcl_Obj *part2Ptr, const int flags); /* 256 */
-    void (*reserved257)(void);
-    void (*tclUnusedStubEntry) (void); /* 258 */
+    void (*tclStaticPackage) (Tcl_Interp *interp, const char *pkgName, Tcl_PackageInitProc *initProc, Tcl_PackageInitProc *safeInitProc); /* 257 */
+    void (*reserved258)(void);
+    void (*reserved259)(void);
+    void (*tclUnusedStubEntry) (void); /* 260 */
 } TclIntStubs;
 
 extern const TclIntStubs *tclIntStubsPtr;
@@ -1346,9 +1354,12 @@ extern const TclIntStubs *tclIntStubsPtr;
        (tclIntStubsPtr->tclPtrObjMakeUpvar) /* 255 */
 #define TclPtrUnsetVar \
        (tclIntStubsPtr->tclPtrUnsetVar) /* 256 */
-/* Slot 257 is reserved */
+#define TclStaticPackage \
+       (tclIntStubsPtr->tclStaticPackage) /* 257 */
+/* Slot 258 is reserved */
+/* Slot 259 is reserved */
 #define TclUnusedStubEntry \
-       (tclIntStubsPtr->tclUnusedStubEntry) /* 258 */
+       (tclIntStubsPtr->tclUnusedStubEntry) /* 260 */
 
 #endif /* defined(USE_TCL_STUBS) */
 
@@ -1411,4 +1422,6 @@ extern const TclIntStubs *tclIntStubsPtr;
 #undef TclCopyChannelOld
 #undef TclSockMinimumBuffersOld
 
+#define TclSetChildCancelFlags TclSetSlaveCancelFlags
+
 #endif /* _TCLINTDECLS */
index 903327f..7034fc3 100644 (file)
@@ -57,7 +57,8 @@ EXTERN int            TclpCreateProcess(Tcl_Interp *interp, int argc,
                                const char **argv, TclFile inputFile,
                                TclFile outputFile, TclFile errorFile,
                                Tcl_Pid *pidPtr);
-/* Slot 5 is reserved */
+/* 5 */
+EXTERN int             TclUnixWaitForFile_(int fd, int mask, int timeout);
 /* 6 */
 EXTERN TclFile         TclpMakeFile(Tcl_Channel channel, int direction);
 /* 7 */
@@ -78,14 +79,30 @@ EXTERN char *               TclpInetNtoa(struct in_addr addr);
 EXTERN int             TclUnixCopyFile(const char *src, const char *dst,
                                const Tcl_StatBuf *statBufPtr,
                                int dontCopyAtts);
-/* Slot 15 is reserved */
-/* Slot 16 is reserved */
-/* Slot 17 is reserved */
-/* Slot 18 is reserved */
-/* Slot 19 is reserved */
+/* 15 */
+EXTERN int             TclMacOSXGetFileAttribute(Tcl_Interp *interp,
+                               int objIndex, Tcl_Obj *fileName,
+                               Tcl_Obj **attributePtrPtr);
+/* 16 */
+EXTERN int             TclMacOSXSetFileAttribute(Tcl_Interp *interp,
+                               int objIndex, Tcl_Obj *fileName,
+                               Tcl_Obj *attributePtr);
+/* 17 */
+EXTERN int             TclMacOSXCopyFileAttributes(const char *src,
+                               const char *dst,
+                               const Tcl_StatBuf *statBufPtr);
+/* 18 */
+EXTERN int             TclMacOSXMatchType(Tcl_Interp *interp,
+                               const char *pathName, const char *fileName,
+                               Tcl_StatBuf *statBufPtr,
+                               Tcl_GlobTypeData *types);
+/* 19 */
+EXTERN void            TclMacOSXNotifierAddRunLoopMode(
+                               const void *runLoopMode);
 /* Slot 20 is reserved */
 /* Slot 21 is reserved */
-/* Slot 22 is reserved */
+/* 22 */
+EXTERN TclFile         TclpCreateTempFile_(const char *contents);
 /* Slot 23 is reserved */
 /* Slot 24 is reserved */
 /* Slot 25 is reserved */
@@ -191,7 +208,8 @@ EXTERN int          TclpCreateProcess(Tcl_Interp *interp, int argc,
                                const char **argv, TclFile inputFile,
                                TclFile outputFile, TclFile errorFile,
                                Tcl_Pid *pidPtr);
-/* Slot 5 is reserved */
+/* 5 */
+EXTERN int             TclUnixWaitForFile_(int fd, int mask, int timeout);
 /* 6 */
 EXTERN TclFile         TclpMakeFile(Tcl_Channel channel, int direction);
 /* 7 */
@@ -234,7 +252,8 @@ EXTERN void         TclMacOSXNotifierAddRunLoopMode(
                                const void *runLoopMode);
 /* Slot 20 is reserved */
 /* Slot 21 is reserved */
-/* Slot 22 is reserved */
+/* 22 */
+EXTERN TclFile         TclpCreateTempFile_(const char *contents);
 /* Slot 23 is reserved */
 /* Slot 24 is reserved */
 /* Slot 25 is reserved */
@@ -259,7 +278,7 @@ typedef struct TclIntPlatStubs {
     Tcl_Channel (*tclpCreateCommandChannel) (TclFile readFile, TclFile writeFile, TclFile errorFile, int numPids, Tcl_Pid *pidPtr); /* 2 */
     int (*tclpCreatePipe) (TclFile *readPipe, TclFile *writePipe); /* 3 */
     int (*tclpCreateProcess) (Tcl_Interp *interp, int argc, const char **argv, TclFile inputFile, TclFile outputFile, TclFile errorFile, Tcl_Pid *pidPtr); /* 4 */
-    void (*reserved5)(void);
+    int (*tclUnixWaitForFile_) (int fd, int mask, int timeout); /* 5 */
     TclFile (*tclpMakeFile) (Tcl_Channel channel, int direction); /* 6 */
     TclFile (*tclpOpenFile) (const char *fname, int mode); /* 7 */
     int (*tclUnixWaitForFile) (int fd, int mask, int timeout); /* 8 */
@@ -269,14 +288,14 @@ typedef struct TclIntPlatStubs {
     struct tm * (*tclpGmtime_unix) (const time_t *clock); /* 12 */
     char * (*tclpInetNtoa) (struct in_addr addr); /* 13 */
     int (*tclUnixCopyFile) (const char *src, const char *dst, const Tcl_StatBuf *statBufPtr, int dontCopyAtts); /* 14 */
-    void (*reserved15)(void);
-    void (*reserved16)(void);
-    void (*reserved17)(void);
-    void (*reserved18)(void);
-    void (*reserved19)(void);
+    int (*tclMacOSXGetFileAttribute) (Tcl_Interp *interp, int objIndex, Tcl_Obj *fileName, Tcl_Obj **attributePtrPtr); /* 15 */
+    int (*tclMacOSXSetFileAttribute) (Tcl_Interp *interp, int objIndex, Tcl_Obj *fileName, Tcl_Obj *attributePtr); /* 16 */
+    int (*tclMacOSXCopyFileAttributes) (const char *src, const char *dst, const Tcl_StatBuf *statBufPtr); /* 17 */
+    int (*tclMacOSXMatchType) (Tcl_Interp *interp, const char *pathName, const char *fileName, Tcl_StatBuf *statBufPtr, Tcl_GlobTypeData *types); /* 18 */
+    void (*tclMacOSXNotifierAddRunLoopMode) (const void *runLoopMode); /* 19 */
     void (*reserved20)(void);
     void (*reserved21)(void);
-    void (*reserved22)(void);
+    TclFile (*tclpCreateTempFile_) (const char *contents); /* 22 */
     void (*reserved23)(void);
     void (*reserved24)(void);
     void (*reserved25)(void);
@@ -325,7 +344,7 @@ typedef struct TclIntPlatStubs {
     Tcl_Channel (*tclpCreateCommandChannel) (TclFile readFile, TclFile writeFile, TclFile errorFile, int numPids, Tcl_Pid *pidPtr); /* 2 */
     int (*tclpCreatePipe) (TclFile *readPipe, TclFile *writePipe); /* 3 */
     int (*tclpCreateProcess) (Tcl_Interp *interp, int argc, const char **argv, TclFile inputFile, TclFile outputFile, TclFile errorFile, Tcl_Pid *pidPtr); /* 4 */
-    void (*reserved5)(void);
+    int (*tclUnixWaitForFile_) (int fd, int mask, int timeout); /* 5 */
     TclFile (*tclpMakeFile) (Tcl_Channel channel, int direction); /* 6 */
     TclFile (*tclpOpenFile) (const char *fname, int mode); /* 7 */
     int (*tclUnixWaitForFile) (int fd, int mask, int timeout); /* 8 */
@@ -342,7 +361,7 @@ typedef struct TclIntPlatStubs {
     void (*tclMacOSXNotifierAddRunLoopMode) (const void *runLoopMode); /* 19 */
     void (*reserved20)(void);
     void (*reserved21)(void);
-    void (*reserved22)(void);
+    TclFile (*tclpCreateTempFile_) (const char *contents); /* 22 */
     void (*reserved23)(void);
     void (*reserved24)(void);
     void (*reserved25)(void);
@@ -377,7 +396,8 @@ extern const TclIntPlatStubs *tclIntPlatStubsPtr;
        (tclIntPlatStubsPtr->tclpCreatePipe) /* 3 */
 #define TclpCreateProcess \
        (tclIntPlatStubsPtr->tclpCreateProcess) /* 4 */
-/* Slot 5 is reserved */
+#define TclUnixWaitForFile_ \
+       (tclIntPlatStubsPtr->tclUnixWaitForFile_) /* 5 */
 #define TclpMakeFile \
        (tclIntPlatStubsPtr->tclpMakeFile) /* 6 */
 #define TclpOpenFile \
@@ -396,14 +416,20 @@ extern const TclIntPlatStubs *tclIntPlatStubsPtr;
        (tclIntPlatStubsPtr->tclpInetNtoa) /* 13 */
 #define TclUnixCopyFile \
        (tclIntPlatStubsPtr->tclUnixCopyFile) /* 14 */
-/* Slot 15 is reserved */
-/* Slot 16 is reserved */
-/* Slot 17 is reserved */
-/* Slot 18 is reserved */
-/* Slot 19 is reserved */
+#define TclMacOSXGetFileAttribute \
+       (tclIntPlatStubsPtr->tclMacOSXGetFileAttribute) /* 15 */
+#define TclMacOSXSetFileAttribute \
+       (tclIntPlatStubsPtr->tclMacOSXSetFileAttribute) /* 16 */
+#define TclMacOSXCopyFileAttributes \
+       (tclIntPlatStubsPtr->tclMacOSXCopyFileAttributes) /* 17 */
+#define TclMacOSXMatchType \
+       (tclIntPlatStubsPtr->tclMacOSXMatchType) /* 18 */
+#define TclMacOSXNotifierAddRunLoopMode \
+       (tclIntPlatStubsPtr->tclMacOSXNotifierAddRunLoopMode) /* 19 */
 /* Slot 20 is reserved */
 /* Slot 21 is reserved */
-/* Slot 22 is reserved */
+#define TclpCreateTempFile_ \
+       (tclIntPlatStubsPtr->tclpCreateTempFile_) /* 22 */
 /* Slot 23 is reserved */
 /* Slot 24 is reserved */
 /* Slot 25 is reserved */
@@ -488,7 +514,8 @@ extern const TclIntPlatStubs *tclIntPlatStubsPtr;
        (tclIntPlatStubsPtr->tclpCreatePipe) /* 3 */
 #define TclpCreateProcess \
        (tclIntPlatStubsPtr->tclpCreateProcess) /* 4 */
-/* Slot 5 is reserved */
+#define TclUnixWaitForFile_ \
+       (tclIntPlatStubsPtr->tclUnixWaitForFile_) /* 5 */
 #define TclpMakeFile \
        (tclIntPlatStubsPtr->tclpMakeFile) /* 6 */
 #define TclpOpenFile \
@@ -519,7 +546,8 @@ extern const TclIntPlatStubs *tclIntPlatStubsPtr;
        (tclIntPlatStubsPtr->tclMacOSXNotifierAddRunLoopMode) /* 19 */
 /* Slot 20 is reserved */
 /* Slot 21 is reserved */
-/* Slot 22 is reserved */
+#define TclpCreateTempFile_ \
+       (tclIntPlatStubsPtr->tclpCreateTempFile_) /* 22 */
 /* Slot 23 is reserved */
 /* Slot 24 is reserved */
 /* Slot 25 is reserved */
@@ -545,6 +573,16 @@ extern const TclIntPlatStubs *tclIntPlatStubsPtr;
 #undef TclpInetNtoa
 #define TclpInetNtoa inet_ntoa
 
+#undef TclpCreateTempFile_
+#undef TclUnixWaitForFile_
+#ifndef MAC_OSX_TCL /* not accessable on Win32/UNIX */
+#undef TclMacOSXGetFileAttribute /* 15 */
+#undef TclMacOSXSetFileAttribute /* 16 */
+#undef TclMacOSXCopyFileAttributes /* 17 */
+#undef TclMacOSXMatchType /* 18 */
+#undef TclMacOSXNotifierAddRunLoopMode /* 19 */
+#endif
+
 #if defined(_WIN32)
 #   undef TclWinNToHS
 #   undef TclWinGetServByName
index 8a0d653..4f5b300 100644 (file)
@@ -27,34 +27,34 @@ struct Target;
 /*
  * struct Alias:
  *
- * Stores information about an alias. Is stored in the slave interpreter and
- * used by the source command to find the target command in the master when
+ * Stores information about an alias. Is stored in the child interpreter and
+ * used by the source command to find the target command in the parent when
  * the source command is invoked.
  */
 
 typedef struct Alias {
-    Tcl_Obj *token;            /* Token for the alias command in the slave
+    Tcl_Obj *token;            /* Token for the alias command in the child
                                 * interp. This used to be the command name in
-                                * the slave when the alias was first
+                                * the child when the alias was first
                                 * created. */
     Tcl_Interp *targetInterp;  /* Interp in which target command will be
                                 * invoked. */
-    Tcl_Command slaveCmd;      /* Source command in slave interpreter, bound
+    Tcl_Command childCmd;      /* Source command in child interpreter, bound
                                 * to command that invokes the target command
                                 * in the target interpreter. */
     Tcl_HashEntry *aliasEntryPtr;
-                               /* Entry for the alias hash table in slave.
+                               /* Entry for the alias hash table in child.
                                 * This is used by alias deletion to remove
-                                * the alias from the slave interpreter alias
+                                * the alias from the child interpreter alias
                                 * table. */
-    struct Target *targetPtr;  /* Entry for target command in master. This is
-                                * used in the master interpreter to map back
+    struct Target *targetPtr;  /* Entry for target command in parent. This is
+                                * used in the parent interpreter to map back
                                 * from the target command to aliases
                                 * redirecting to it. */
     int objc;                  /* Count of Tcl_Obj in the prefix of the
                                 * target command to be invoked in the target
                                 * interpreter. Additional arguments specified
-                                * when calling the alias in the slave interp
+                                * when calling the alias in the child interp
                                 * will be appended to the prefix before the
                                 * command is invoked. */
     Tcl_Obj *objPtr;           /* The first actual prefix object - the target
@@ -66,45 +66,45 @@ typedef struct Alias {
 
 /*
  *
- * struct Slave:
+ * struct Child:
  *
- * Used by the "interp" command to record and find information about slave
- * interpreters. Maps from a command name in the master to information about a
- * slave interpreter, e.g. what aliases are defined in it.
+ * Used by the "interp" command to record and find information about child
+ * interpreters. Maps from a command name in the parent to information about a
+ * child interpreter, e.g. what aliases are defined in it.
  */
 
-typedef struct Slave {
-    Tcl_Interp *masterInterp;  /* Master interpreter for this slave. */
-    Tcl_HashEntry *slaveEntryPtr;
-                               /* Hash entry in masters slave table for this
-                                * slave interpreter. Used to find this
-                                * record, and used when deleting the slave
-                                * interpreter to delete it from the master's
+typedef struct Child {
+    Tcl_Interp *parentInterp;  /* Parent interpreter for this child. */
+    Tcl_HashEntry *childEntryPtr;
+                               /* Hash entry in parents child table for this
+                                * child interpreter. Used to find this
+                                * record, and used when deleting the child
+                                * interpreter to delete it from the parent's
                                 * table. */
-    Tcl_Interp *slaveInterp;   /* The slave interpreter. */
+    Tcl_Interp *childInterp;   /* The child interpreter. */
     Tcl_Command interpCmd;     /* Interpreter object command. */
     Tcl_HashTable aliasTable;  /* Table which maps from names of commands in
-                                * slave interpreter to struct Alias defined
+                                * child interpreter to struct Alias defined
                                 * below. */
-} Slave;
+} Child;
 
 /*
  * struct Target:
  *
- * Maps from master interpreter commands back to the source commands in slave
+ * Maps from parent interpreter commands back to the source commands in child
  * interpreters. This is needed because aliases can be created between sibling
  * interpreters and must be deleted when the target interpreter is deleted. In
  * case they would not be deleted the source interpreter would be left with a
- * "dangling pointer". One such record is stored in the Master record of the
- * master interpreter with the master for each alias which directs to a
- * command in the master. These records are used to remove the source command
- * for an from a slave if/when the master is deleted. They are organized in a
- * doubly-linked list attached to the master interpreter.
+ * "dangling pointer". One such record is stored in the Parent record of the
+ * parent interpreter with the parent for each alias which directs to a
+ * command in the parent. These records are used to remove the source command
+ * for an from a child if/when the parent is deleted. They are organized in a
+ * doubly-linked list attached to the parent interpreter.
  */
 
 typedef struct Target {
-    Tcl_Command        slaveCmd;       /* Command for alias in slave interp. */
-    Tcl_Interp *slaveInterp;   /* Slave Interpreter. */
+    Tcl_Command        childCmd;       /* Command for alias in child interp. */
+    Tcl_Interp *childInterp;   /* Child Interpreter. */
     struct Target *nextPtr;    /* Next in list of target records, or NULL if
                                 * at the end of the list of targets. */
     struct Target *prevPtr;    /* Previous in list of target records, or NULL
@@ -112,43 +112,43 @@ typedef struct Target {
 } Target;
 
 /*
- * struct Master:
+ * struct Parent:
  *
- * This record is used for two purposes: First, slaveTable (a hashtable) maps
- * from names of commands to slave interpreters. This hashtable is used to
- * store information about slave interpreters of this interpreter, to map over
- * all slaves, etc. The second purpose is to store information about all
- * aliases in slaves (or siblings) which direct to target commands in this
+ * This record is used for two purposes: First, childTable (a hashtable) maps
+ * from names of commands to child interpreters. This hashtable is used to
+ * store information about child interpreters of this interpreter, to map over
+ * all children, etc. The second purpose is to store information about all
+ * aliases in children (or siblings) which direct to target commands in this
  * interpreter (using the targetsPtr doubly-linked list).
  *
  * NB: the flags field in the interp structure, used with SAFE_INTERP mask
  * denotes whether the interpreter is safe or not. Safe interpreters have
- * restricted functionality, can only create safe slave interpreters and can
+ * restricted functionality, can only create safe interpreters and can
  * only load safe extensions.
  */
 
-typedef struct Master {
-    Tcl_HashTable slaveTable;  /* Hash table for slave interpreters. Maps
-                                * from command names to Slave records. */
+typedef struct Parent {
+    Tcl_HashTable childTable;  /* Hash table for child interpreters. Maps
+                                * from command names to Child records. */
     Target *targetsPtr;                /* The head of a doubly-linked list of all the
                                 * target records which denote aliases from
-                                * slaves or sibling interpreters that direct
+                                * children or sibling interpreters that direct
                                 * to commands in this interpreter. This list
                                 * is used to remove dangling pointers from
-                                * the slave (or sibling) interpreters when
+                                * the child (or sibling) interpreters when
                                 * this interpreter is deleted. */
-} Master;
+} Parent;
 
 /*
- * The following structure keeps track of all the Master and Slave information
+ * The following structure keeps track of all the Parent and Child information
  * on a per-interp basis.
  */
 
 typedef struct InterpInfo {
-    Master master;             /* Keeps track of all interps for which this
-                                * interp is the Master. */
-    Slave slave;               /* Information necessary for this interp to
-                                * function as a slave. */
+    Parent parent;             /* Keeps track of all interps for which this
+                                * interp is the Parent. */
+    Child child;               /* Information necessary for this interp to
+                                * function as a child. */
 } InterpInfo;
 
 /*
@@ -214,14 +214,14 @@ struct LimitHandler {
  */
 
 static int             AliasCreate(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, Tcl_Interp *masterInterp,
+                           Tcl_Interp *childInterp, Tcl_Interp *parentInterp,
                            Tcl_Obj *namePtr, Tcl_Obj *targetPtr, int objc,
                            Tcl_Obj *const objv[]);
 static int             AliasDelete(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, Tcl_Obj *namePtr);
+                           Tcl_Interp *childInterp, Tcl_Obj *namePtr);
 static int             AliasDescribe(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, Tcl_Obj *objPtr);
-static int             AliasList(Tcl_Interp *interp, Tcl_Interp *slaveInterp);
+                           Tcl_Interp *childInterp, Tcl_Obj *objPtr);
+static int             AliasList(Tcl_Interp *interp, Tcl_Interp *childInterp);
 static int             AliasObjCmd(ClientData dummy,
                            Tcl_Interp *currentInterp, int objc,
                            Tcl_Obj *const objv[]);
@@ -234,43 +234,43 @@ static Tcl_Interp *       GetInterp2(Tcl_Interp *interp, int objc,
                            Tcl_Obj *const objv[]);
 static void            InterpInfoDeleteProc(ClientData clientData,
                            Tcl_Interp *interp);
-static int             SlaveBgerror(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, int objc,
+static int             ChildBgerror(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp, int objc,
                            Tcl_Obj *const objv[]);
-static Tcl_Interp *    SlaveCreate(Tcl_Interp *interp, Tcl_Obj *pathPtr,
+static Tcl_Interp *    ChildCreate(Tcl_Interp *interp, Tcl_Obj *pathPtr,
                            int safe);
-static int             SlaveDebugCmd(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp,
+static int             ChildDebugCmd(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp,
                            int objc, Tcl_Obj *const objv[]);
-static int             SlaveEval(Tcl_Interp *interp, Tcl_Interp *slaveInterp,
+static int             ChildEval(Tcl_Interp *interp, Tcl_Interp *childInterp,
                            int objc, Tcl_Obj *const objv[]);
-static int             SlaveExpose(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, int objc,
+static int             ChildExpose(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp, int objc,
                            Tcl_Obj *const objv[]);
-static int             SlaveHide(Tcl_Interp *interp, Tcl_Interp *slaveInterp,
+static int             ChildHide(Tcl_Interp *interp, Tcl_Interp *childInterp,
                            int objc, Tcl_Obj *const objv[]);
-static int             SlaveHidden(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp);
-static int             SlaveInvokeHidden(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp,
+static int             ChildHidden(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp);
+static int             ChildInvokeHidden(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp,
                            const char *namespaceName,
                            int objc, Tcl_Obj *const objv[]);
-static int             SlaveMarkTrusted(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp);
-static int             SlaveObjCmd(ClientData dummy, Tcl_Interp *interp,
+static int             ChildMarkTrusted(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp);
+static int             ChildObjCmd(ClientData dummy, Tcl_Interp *interp,
                            int objc, Tcl_Obj *const objv[]);
-static void            SlaveObjCmdDeleteProc(ClientData clientData);
-static int             SlaveRecursionLimit(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, int objc,
+static void            ChildObjCmdDeleteProc(ClientData clientData);
+static int             ChildRecursionLimit(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp, int objc,
                            Tcl_Obj *const objv[]);
-static int             SlaveCommandLimitCmd(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, int consumedObjc,
+static int             ChildCommandLimitCmd(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp, int consumedObjc,
                            int objc, Tcl_Obj *const objv[]);
-static int             SlaveTimeLimitCmd(Tcl_Interp *interp,
-                           Tcl_Interp *slaveInterp, int consumedObjc,
+static int             ChildTimeLimitCmd(Tcl_Interp *interp,
+                           Tcl_Interp *childInterp, int consumedObjc,
                            int objc, Tcl_Obj *const objv[]);
-static void            InheritLimitsFromMaster(Tcl_Interp *slaveInterp,
-                           Tcl_Interp *masterInterp);
+static void            InheritLimitsFromParent(Tcl_Interp *childInterp,
+                           Tcl_Interp *parentInterp);
 static void            SetScriptLimitCallback(Tcl_Interp *interp, int type,
                            Tcl_Interp *targetInterp, Tcl_Obj *scriptObj);
 static void            CallScriptLimitCallback(ClientData clientData,
@@ -283,7 +283,7 @@ static void         TimeLimitCallback(ClientData clientData);
 /* NRE enabling */
 static Tcl_NRPostProc  NRPostInvokeHidden;
 static Tcl_ObjCmdProc  NRInterpCmd;
-static Tcl_ObjCmdProc  NRSlaveCmd;
+static Tcl_ObjCmdProc  NRChildCmd;
 
 \f
 /*
@@ -452,7 +452,7 @@ Tcl_Init(
  *
  * TclInterpInit --
  *
- *     Initializes the invoking interpreter for using the master, slave and
+ *     Initializes the invoking interpreter for using the parent, child and
  *     safe interp facilities. This is called from inside Tcl_CreateInterp().
  *
  * Results:
@@ -470,22 +470,22 @@ TclInterpInit(
     Tcl_Interp *interp)                /* Interpreter to initialize. */
 {
     InterpInfo *interpInfoPtr;
-    Master *masterPtr;
-    Slave *slavePtr;
+    Parent *parentPtr;
+    Child *childPtr;
 
     interpInfoPtr = ckalloc(sizeof(InterpInfo));
     ((Interp *) interp)->interpInfo = interpInfoPtr;
 
-    masterPtr = &interpInfoPtr->master;
-    Tcl_InitHashTable(&masterPtr->slaveTable, TCL_STRING_KEYS);
-    masterPtr->targetsPtr = NULL;
+    parentPtr = &interpInfoPtr->parent;
+    Tcl_InitHashTable(&parentPtr->childTable, TCL_STRING_KEYS);
+    parentPtr->targetsPtr = NULL;
 
-    slavePtr = &interpInfoPtr->slave;
-    slavePtr->masterInterp     = NULL;
-    slavePtr->slaveEntryPtr    = NULL;
-    slavePtr->slaveInterp      = interp;
-    slavePtr->interpCmd                = NULL;
-    Tcl_InitHashTable(&slavePtr->aliasTable, TCL_STRING_KEYS);
+    childPtr = &interpInfoPtr->child;
+    childPtr->parentInterp     = NULL;
+    childPtr->childEntryPtr    = NULL;
+    childPtr->childInterp      = interp;
+    childPtr->interpCmd                = NULL;
+    Tcl_InitHashTable(&childPtr->aliasTable, TCL_STRING_KEYS);
 
     Tcl_NRCreateCommand(interp, "interp", Tcl_InterpObjCmd, NRInterpCmd,
            NULL, NULL);
@@ -500,7 +500,7 @@ TclInterpInit(
  * InterpInfoDeleteProc --
  *
  *     Invoked when an interpreter is being deleted. It releases all storage
- *     used by the master/slave/safe interpreter facilities.
+ *     used by the parent/child/safe interpreter facilities.
  *
  * Results:
  *     None.
@@ -515,11 +515,11 @@ static void
 InterpInfoDeleteProc(
     ClientData clientData,     /* Ignored. */
     Tcl_Interp *interp)                /* Interp being deleted. All commands for
-                                * slave interps should already be deleted. */
+                                * child interps should already be deleted. */
 {
     InterpInfo *interpInfoPtr;
-    Slave *slavePtr;
-    Master *masterPtr;
+    Child *childPtr;
+    Parent *parentPtr;
     Target *targetPtr;
 
     interpInfoPtr = (InterpInfo *) ((Interp *) interp)->interpInfo;
@@ -528,11 +528,11 @@ InterpInfoDeleteProc(
      * There shouldn't be any commands left.
      */
 
-    masterPtr = &interpInfoPtr->master;
-    if (masterPtr->slaveTable.numEntries != 0) {
+    parentPtr = &interpInfoPtr->parent;
+    if (parentPtr->childTable.numEntries != 0) {
        Tcl_Panic("InterpInfoDeleteProc: still exist commands");
     }
-    Tcl_DeleteHashTable(&masterPtr->slaveTable);
+    Tcl_DeleteHashTable(&parentPtr->childTable);
 
     /*
      * Tell any interps that have aliases to this interp that they should
@@ -540,35 +540,35 @@ InterpInfoDeleteProc(
      * have removed the target record already.
      */
 
-    for (targetPtr = masterPtr->targetsPtr; targetPtr != NULL; ) {
+    for (targetPtr = parentPtr->targetsPtr; targetPtr != NULL; ) {
        Target *tmpPtr = targetPtr->nextPtr;
-       Tcl_DeleteCommandFromToken(targetPtr->slaveInterp,
-               targetPtr->slaveCmd);
+       Tcl_DeleteCommandFromToken(targetPtr->childInterp,
+               targetPtr->childCmd);
        targetPtr = tmpPtr;
     }
 
-    slavePtr = &interpInfoPtr->slave;
-    if (slavePtr->interpCmd != NULL) {
+    childPtr = &interpInfoPtr->child;
+    if (childPtr->interpCmd != NULL) {
        /*
         * Tcl_DeleteInterp() was called on this interpreter, rather "interp
-        * delete" or the equivalent deletion of the command in the master.
+        * delete" or the equivalent deletion of the command in the parent.
         * First ensure that the cleanup callback doesn't try to delete the
         * interp again.
         */
 
-       slavePtr->slaveInterp = NULL;
-       Tcl_DeleteCommandFromToken(slavePtr->masterInterp,
-               slavePtr->interpCmd);
+       childPtr->childInterp = NULL;
+       Tcl_DeleteCommandFromToken(childPtr->parentInterp,
+               childPtr->interpCmd);
     }
 
     /*
      * There shouldn't be any aliases left.
      */
 
-    if (slavePtr->aliasTable.numEntries != 0) {
+    if (childPtr->aliasTable.numEntries != 0) {
        Tcl_Panic("InterpInfoDeleteProc: still exist aliases");
     }
-    Tcl_DeleteHashTable(&slavePtr->aliasTable);
+    Tcl_DeleteHashTable(&childPtr->aliasTable);
 
     ckfree(interpInfoPtr);
 }
@@ -607,11 +607,11 @@ NRInterpCmd(
     int objc,                          /* Number of arguments. */
     Tcl_Obj *const objv[])             /* Argument objects. */
 {
-    Tcl_Interp *slaveInterp;
+    Tcl_Interp *childInterp;
     int index;
     static const char *const options[] = {
        "alias",        "aliases",      "bgerror",      "cancel",
-       "create",       "debug",        "delete",
+       "children",     "create",       "debug",        "delete",
        "eval",         "exists",       "expose",
        "hide",         "hidden",       "issafe",
        "invokehidden", "limit",        "marktrusted",  "recursionlimit",
@@ -620,7 +620,7 @@ NRInterpCmd(
     };
     enum option {
        OPT_ALIAS,      OPT_ALIASES,    OPT_BGERROR,    OPT_CANCEL,
-       OPT_CREATE,     OPT_DEBUG,      OPT_DELETE,
+       OPT_CHILDREN,   OPT_CREATE,     OPT_DEBUG,      OPT_DELETE,
        OPT_EVAL,       OPT_EXISTS,     OPT_EXPOSE,
        OPT_HIDE,       OPT_HIDDEN,     OPT_ISSAFE,
        OPT_INVOKEHID,  OPT_LIMIT,      OPT_MARKTRUSTED,OPT_RECLIMIT,
@@ -637,7 +637,7 @@ NRInterpCmd(
     }
     switch ((enum option) index) {
     case OPT_ALIAS: {
-       Tcl_Interp *masterInterp;
+       Tcl_Interp *parentInterp;
 
        if (objc < 4) {
        aliasArgs:
@@ -645,43 +645,43 @@ NRInterpCmd(
                    "slavePath slaveCmd ?masterPath masterCmd? ?arg ...?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
        if (objc == 4) {
-           return AliasDescribe(interp, slaveInterp, objv[3]);
+           return AliasDescribe(interp, childInterp, objv[3]);
        }
        if ((objc == 5) && (TclGetString(objv[4])[0] == '\0')) {
-           return AliasDelete(interp, slaveInterp, objv[3]);
+           return AliasDelete(interp, childInterp, objv[3]);
        }
        if (objc > 5) {
-           masterInterp = GetInterp(interp, objv[4]);
-           if (masterInterp == NULL) {
+           parentInterp = GetInterp(interp, objv[4]);
+           if (parentInterp == NULL) {
                return TCL_ERROR;
            }
 
-           return AliasCreate(interp, slaveInterp, masterInterp, objv[3],
+           return AliasCreate(interp, childInterp, parentInterp, objv[3],
                    objv[5], objc - 6, objv + 6);
        }
        goto aliasArgs;
     }
     case OPT_ALIASES:
-       slaveInterp = GetInterp2(interp, objc, objv);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp2(interp, objc, objv);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return AliasList(interp, slaveInterp);
+       return AliasList(interp, childInterp);
     case OPT_BGERROR:
        if (objc != 3 && objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "path ?cmdPrefix?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveBgerror(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildBgerror(interp, childInterp, objc - 3, objv + 3);
     case OPT_CANCEL: {
        int i, flags;
        Tcl_Obj *resultObjPtr;
@@ -725,18 +725,18 @@ NRInterpCmd(
        }
 
        /*
-        * Did they specify a slave interp to cancel the script in progress
+        * Did they specify a child interp to cancel the script in progress
         * in?  If not, use the current interp.
         */
 
        if (i < objc) {
-           slaveInterp = GetInterp(interp, objv[i]);
-           if (slaveInterp == NULL) {
+           childInterp = GetInterp(interp, objv[i]);
+           if (childInterp == NULL) {
                return TCL_ERROR;
            }
            i++;
        } else {
-           slaveInterp = interp;
+           childInterp = interp;
        }
 
        if (i < objc) {
@@ -752,11 +752,11 @@ NRInterpCmd(
            resultObjPtr = NULL;
        }
 
-       return Tcl_CancelEval(slaveInterp, resultObjPtr, 0, flags);
+       return Tcl_CancelEval(childInterp, resultObjPtr, 0, flags);
     }
     case OPT_CREATE: {
        int i, last, safe;
-       Tcl_Obj *slavePtr;
+       Tcl_Obj *childPtr;
        char buf[16 + TCL_INTEGER_SPACE];
        static const char *const createOptions[] = {
            "-safe",    "--", NULL
@@ -771,7 +771,7 @@ NRInterpCmd(
         * Weird historical rules: "-safe" is accepted at the end, too.
         */
 
-       slavePtr = NULL;
+       childPtr = NULL;
        last = 0;
        for (i = 2; i < objc; i++) {
            if ((last == 0) && (Tcl_GetString(objv[i])[0] == '-')) {
@@ -786,21 +786,21 @@ NRInterpCmd(
                i++;
                last = 1;
            }
-           if (slavePtr != NULL) {
+           if (childPtr != NULL) {
                Tcl_WrongNumArgs(interp, 2, objv, "?-safe? ?--? ?path?");
                return TCL_ERROR;
            }
            if (i < objc) {
-               slavePtr = objv[i];
+               childPtr = objv[i];
            }
        }
        buf[0] = '\0';
-       if (slavePtr == NULL) {
+       if (childPtr == NULL) {
            /*
             * Create an anonymous interpreter -- we choose its name and the
             * name of the command. We check that the command name that we use
             * for the interpreter does not collide with an existing command
-            * in the master interpreter.
+            * in the parent interpreter.
             */
 
            for (i = 0; ; i++) {
@@ -811,15 +811,15 @@ NRInterpCmd(
                    break;
                }
            }
-           slavePtr = Tcl_NewStringObj(buf, -1);
+           childPtr = Tcl_NewStringObj(buf, -1);
        }
-       if (SlaveCreate(interp, slavePtr, safe) == NULL) {
+       if (ChildCreate(interp, childPtr, safe) == NULL) {
            if (buf[0] != '\0') {
-               Tcl_DecrRefCount(slavePtr);
+               Tcl_DecrRefCount(childPtr);
            }
            return TCL_ERROR;
        }
-       Tcl_SetObjResult(interp, slavePtr);
+       Tcl_SetObjResult(interp, childPtr);
        return TCL_OK;
     }
     case OPT_DEBUG:            /* TIP #378 */
@@ -831,29 +831,29 @@ NRInterpCmd(
            Tcl_WrongNumArgs(interp, 2, objv, "path ?-frame ?bool??");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveDebugCmd(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildDebugCmd(interp, childInterp, objc - 3, objv + 3);
     case OPT_DELETE: {
        int i;
        InterpInfo *iiPtr;
 
        for (i = 2; i < objc; i++) {
-           slaveInterp = GetInterp(interp, objv[i]);
-           if (slaveInterp == NULL) {
+           childInterp = GetInterp(interp, objv[i]);
+           if (childInterp == NULL) {
                return TCL_ERROR;
-           } else if (slaveInterp == interp) {
+           } else if (childInterp == interp) {
                Tcl_SetObjResult(interp, Tcl_NewStringObj(
                        "cannot delete the current interpreter", -1));
                Tcl_SetErrorCode(interp, "TCL", "OPERATION", "INTERP",
                        "DELETESELF", NULL);
                return TCL_ERROR;
            }
-           iiPtr = (InterpInfo *) ((Interp *) slaveInterp)->interpInfo;
-           Tcl_DeleteCommandFromToken(iiPtr->slave.masterInterp,
-                   iiPtr->slave.interpCmd);
+           iiPtr = (InterpInfo *) ((Interp *) childInterp)->interpInfo;
+           Tcl_DeleteCommandFromToken(iiPtr->child.parentInterp,
+                   iiPtr->child.interpCmd);
        }
        return TCL_OK;
     }
@@ -862,16 +862,16 @@ NRInterpCmd(
            Tcl_WrongNumArgs(interp, 2, objv, "path arg ?arg ...?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveEval(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildEval(interp, childInterp, objc - 3, objv + 3);
     case OPT_EXISTS: {
        int exists = 1;
 
-       slaveInterp = GetInterp2(interp, objc, objv);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp2(interp, objc, objv);
+       if (childInterp == NULL) {
            if (objc > 3) {
                return TCL_ERROR;
            }
@@ -886,33 +886,33 @@ NRInterpCmd(
            Tcl_WrongNumArgs(interp, 2, objv, "path hiddenCmdName ?cmdName?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveExpose(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildExpose(interp, childInterp, objc - 3, objv + 3);
     case OPT_HIDE:
        if ((objc < 4) || (objc > 5)) {
            Tcl_WrongNumArgs(interp, 2, objv, "path cmdName ?hiddenCmdName?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveHide(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildHide(interp, childInterp, objc - 3, objv + 3);
     case OPT_HIDDEN:
-       slaveInterp = GetInterp2(interp, objc, objv);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp2(interp, objc, objv);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveHidden(interp, slaveInterp);
+       return ChildHidden(interp, childInterp);
     case OPT_ISSAFE:
-       slaveInterp = GetInterp2(interp, objc, objv);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp2(interp, objc, objv);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_IsSafe(slaveInterp)));
+       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_IsSafe(childInterp)));
        return TCL_OK;
     case OPT_INVOKEHID: {
        int i;
@@ -951,11 +951,11 @@ NRInterpCmd(
                    "path ?-namespace ns? ?-global? ?--? cmd ?arg ..?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveInvokeHidden(interp, slaveInterp, namespaceName, objc - i,
+       return ChildInvokeHidden(interp, childInterp, namespaceName, objc - i,
                objv + i);
     }
     case OPT_LIMIT: {
@@ -972,8 +972,8 @@ NRInterpCmd(
                    "path limitType ?-option value ...?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
        if (Tcl_GetIndexFromObj(interp, objv[3], limitTypes, "limit type", 0,
@@ -982,31 +982,33 @@ NRInterpCmd(
        }
        switch ((enum LimitTypes) limitType) {
        case LIMIT_TYPE_COMMANDS:
-           return SlaveCommandLimitCmd(interp, slaveInterp, 4, objc,objv);
+           return ChildCommandLimitCmd(interp, childInterp, 4, objc,objv);
        case LIMIT_TYPE_TIME:
-           return SlaveTimeLimitCmd(interp, slaveInterp, 4, objc, objv);
+           return ChildTimeLimitCmd(interp, childInterp, 4, objc, objv);
        }
     }
+    break;
     case OPT_MARKTRUSTED:
        if (objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "path");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveMarkTrusted(interp, slaveInterp);
+       return ChildMarkTrusted(interp, childInterp);
     case OPT_RECLIMIT:
        if (objc != 3 && objc != 4) {
            Tcl_WrongNumArgs(interp, 2, objv, "path ?newlimit?");
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       return SlaveRecursionLimit(interp, slaveInterp, objc - 3, objv + 3);
+       return ChildRecursionLimit(interp, childInterp, objc - 3, objv + 3);
+    case OPT_CHILDREN:
     case OPT_SLAVES: {
        InterpInfo *iiPtr;
        Tcl_Obj *resultPtr;
@@ -1014,15 +1016,15 @@ NRInterpCmd(
        Tcl_HashSearch hashSearch;
        char *string;
 
-       slaveInterp = GetInterp2(interp, objc, objv);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp2(interp, objc, objv);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       iiPtr = (InterpInfo *) ((Interp *) slaveInterp)->interpInfo;
+       iiPtr = (InterpInfo *) ((Interp *) childInterp)->interpInfo;
        resultPtr = Tcl_NewObj();
-       hPtr = Tcl_FirstHashEntry(&iiPtr->master.slaveTable, &hashSearch);
+       hPtr = Tcl_FirstHashEntry(&iiPtr->parent.childTable, &hashSearch);
        for ( ; hPtr != NULL; hPtr = Tcl_NextHashEntry(&hashSearch)) {
-           string = Tcl_GetHashKey(&iiPtr->master.slaveTable, hPtr);
+           string = Tcl_GetHashKey(&iiPtr->parent.childTable, hPtr);
            Tcl_ListObjAppendElement(NULL, resultPtr,
                    Tcl_NewStringObj(string, -1));
        }
@@ -1031,35 +1033,35 @@ NRInterpCmd(
     }
     case OPT_TRANSFER:
     case OPT_SHARE: {
-       Tcl_Interp *masterInterp;       /* The master of the slave. */
+       Tcl_Interp *parentInterp;       /* The parent of the child. */
        Tcl_Channel chan;
 
        if (objc != 5) {
            Tcl_WrongNumArgs(interp, 2, objv, "srcPath channelId destPath");
            return TCL_ERROR;
        }
-       masterInterp = GetInterp(interp, objv[2]);
-       if (masterInterp == NULL) {
+       parentInterp = GetInterp(interp, objv[2]);
+       if (parentInterp == NULL) {
            return TCL_ERROR;
        }
-       chan = Tcl_GetChannel(masterInterp, TclGetString(objv[3]), NULL);
+       chan = Tcl_GetChannel(parentInterp, TclGetString(objv[3]), NULL);
        if (chan == NULL) {
-           Tcl_TransferResult(masterInterp, TCL_OK, interp);
+           Tcl_TransferResult(parentInterp, TCL_OK, interp);
            return TCL_ERROR;
        }
-       slaveInterp = GetInterp(interp, objv[4]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[4]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
-       Tcl_RegisterChannel(slaveInterp, chan);
+       Tcl_RegisterChannel(childInterp, chan);
        if (index == OPT_TRANSFER) {
            /*
             * When transferring, as opposed to sharing, we must unhitch the
             * channel from the interpreter where it started.
             */
 
-           if (Tcl_UnregisterChannel(masterInterp, chan) != TCL_OK) {
-               Tcl_TransferResult(masterInterp, TCL_OK, interp);
+           if (Tcl_UnregisterChannel(parentInterp, chan) != TCL_OK) {
+               Tcl_TransferResult(parentInterp, TCL_OK, interp);
                return TCL_ERROR;
            }
        }
@@ -1076,15 +1078,15 @@ NRInterpCmd(
            return TCL_ERROR;
        }
 
-       slaveInterp = GetInterp(interp, objv[2]);
-       if (slaveInterp == NULL) {
+       childInterp = GetInterp(interp, objv[2]);
+       if (childInterp == NULL) {
            return TCL_ERROR;
        }
 
        aliasName = TclGetString(objv[3]);
 
-       iiPtr = (InterpInfo *) ((Interp *) slaveInterp)->interpInfo;
-       hPtr = Tcl_FindHashEntry(&iiPtr->slave.aliasTable, aliasName);
+       iiPtr = (InterpInfo *) ((Interp *) childInterp)->interpInfo;
+       hPtr = Tcl_FindHashEntry(&iiPtr->child.aliasTable, aliasName);
        if (hPtr == NULL) {
            Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                    "alias \"%s\" in path \"%s\" not found",
@@ -1157,46 +1159,46 @@ GetInterp2(
  *     A standard Tcl result.
  *
  * Side effects:
- *     Creates a new alias, manipulates the result field of slaveInterp.
+ *     Creates a new alias, manipulates the result field of childInterp.
  *
  *----------------------------------------------------------------------
  */
 
 int
 Tcl_CreateAlias(
-    Tcl_Interp *slaveInterp,   /* Interpreter for source command. */
-    const char *slaveCmd,      /* Command to install in slave. */
+    Tcl_Interp *childInterp,   /* Interpreter for source command. */
+    const char *childCmd,      /* Command to install in child. */
     Tcl_Interp *targetInterp,  /* Interpreter for target command. */
     const char *targetCmd,     /* Name of target command. */
     int argc,                  /* How many additional arguments? */
     const char *const *argv)   /* These are the additional args. */
 {
-    Tcl_Obj *slaveObjPtr, *targetObjPtr;
+    Tcl_Obj *childObjPtr, *targetObjPtr;
     Tcl_Obj **objv;
     int i;
     int result;
 
-    objv = TclStackAlloc(slaveInterp, (unsigned) sizeof(Tcl_Obj *) * argc);
+    objv = TclStackAlloc(childInterp, (unsigned) sizeof(Tcl_Obj *) * argc);
     for (i = 0; i < argc; i++) {
        objv[i] = Tcl_NewStringObj(argv[i], -1);
        Tcl_IncrRefCount(objv[i]);
     }
 
-    slaveObjPtr = Tcl_NewStringObj(slaveCmd, -1);
-    Tcl_IncrRefCount(slaveObjPtr);
+    childObjPtr = Tcl_NewStringObj(childCmd, -1);
+    Tcl_IncrRefCount(childObjPtr);
 
     targetObjPtr = Tcl_NewStringObj(targetCmd, -1);
     Tcl_IncrRefCount(targetObjPtr);
 
-    result = AliasCreate(slaveInterp, slaveInterp, targetInterp, slaveObjPtr,
+    result = AliasCreate(childInterp, childInterp, targetInterp, childObjPtr,
            targetObjPtr, argc, objv);
 
     for (i = 0; i < argc; i++) {
        Tcl_DecrRefCount(objv[i]);
     }
-    TclStackFree(slaveInterp, objv);
+    TclStackFree(childInterp, objv);
     Tcl_DecrRefCount(targetObjPtr);
-    Tcl_DecrRefCount(slaveObjPtr);
+    Tcl_DecrRefCount(childObjPtr);
 
     return result;
 }
@@ -1219,26 +1221,26 @@ Tcl_CreateAlias(
 
 int
 Tcl_CreateAliasObj(
-    Tcl_Interp *slaveInterp,   /* Interpreter for source command. */
-    const char *slaveCmd,      /* Command to install in slave. */
+    Tcl_Interp *childInterp,   /* Interpreter for source command. */
+    const char *childCmd,      /* Command to install in child. */
     Tcl_Interp *targetInterp,  /* Interpreter for target command. */
     const char *targetCmd,     /* Name of target command. */
     int objc,                  /* How many additional arguments? */
     Tcl_Obj *const objv[])     /* Argument vector. */
 {
-    Tcl_Obj *slaveObjPtr, *targetObjPtr;
+    Tcl_Obj *childObjPtr, *targetObjPtr;
     int result;
 
-    slaveObjPtr = Tcl_NewStringObj(slaveCmd, -1);
-    Tcl_IncrRefCount(slaveObjPtr);
+    childObjPtr = Tcl_NewStringObj(childCmd, -1);
+    Tcl_IncrRefCount(childObjPtr);
 
     targetObjPtr = Tcl_NewStringObj(targetCmd, -1);
     Tcl_IncrRefCount(targetObjPtr);
 
-    result = AliasCreate(slaveInterp, slaveInterp, targetInterp, slaveObjPtr,
+    result = AliasCreate(childInterp, childInterp, targetInterp, childObjPtr,
            targetObjPtr, objc, objv);
 
-    Tcl_DecrRefCount(slaveObjPtr);
+    Tcl_DecrRefCount(childObjPtr);
     Tcl_DecrRefCount(targetObjPtr);
     return result;
 }
@@ -1275,7 +1277,7 @@ Tcl_GetAlias(
     int i, objc;
     Tcl_Obj **objv;
 
-    hPtr = Tcl_FindHashEntry(&iiPtr->slave.aliasTable, aliasName);
+    hPtr = Tcl_FindHashEntry(&iiPtr->child.aliasTable, aliasName);
     if (hPtr == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "alias \"%s\" not found", aliasName));
@@ -1337,7 +1339,7 @@ Tcl_GetAliasObj(
     int objc;
     Tcl_Obj **objv;
 
-    hPtr = Tcl_FindHashEntry(&iiPtr->slave.aliasTable, aliasName);
+    hPtr = Tcl_FindHashEntry(&iiPtr->child.aliasTable, aliasName);
     if (hPtr == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "alias \"%s\" not found", aliasName));
@@ -1424,7 +1426,7 @@ TclPreventAliasLoop(
 
        if (Tcl_InterpDeleted(nextAliasPtr->targetInterp)) {
            /*
-            * The slave interpreter can be deleted while creating the alias.
+            * The child interpreter can be deleted while creating the alias.
             * [Bug #641195]
             */
 
@@ -1478,7 +1480,7 @@ TclPreventAliasLoop(
  *
  * Side effects:
  *     An alias command is created and entered into the alias table for the
- *     slave interpreter.
+ *     child interpreter.
  *
  *----------------------------------------------------------------------
  */
@@ -1486,9 +1488,9 @@ TclPreventAliasLoop(
 static int
 AliasCreate(
     Tcl_Interp *interp,                /* Interp for error reporting. */
-    Tcl_Interp *slaveInterp,   /* Interp where alias cmd will live or from
+    Tcl_Interp *childInterp,   /* Interp where alias cmd will live or from
                                 * which alias will be deleted. */
-    Tcl_Interp *masterInterp,  /* Interp in which target command will be
+    Tcl_Interp *parentInterp,  /* Interp in which target command will be
                                 * invoked. */
     Tcl_Obj *namePtr,          /* Name of alias cmd. */
     Tcl_Obj *targetNamePtr,    /* Name of target cmd. */
@@ -1498,15 +1500,15 @@ AliasCreate(
     Alias *aliasPtr;
     Tcl_HashEntry *hPtr;
     Target *targetPtr;
-    Slave *slavePtr;
-    Master *masterPtr;
+    Child *childPtr;
+    Parent *parentPtr;
     Tcl_Obj **prefv;
     int isNew, i;
 
     aliasPtr = ckalloc(sizeof(Alias) + objc * sizeof(Tcl_Obj *));
     aliasPtr->token = namePtr;
     Tcl_IncrRefCount(aliasPtr->token);
-    aliasPtr->targetInterp = masterInterp;
+    aliasPtr->targetInterp = parentInterp;
 
     aliasPtr->objc = objc + 1;
     prefv = &aliasPtr->objPtr;
@@ -1518,21 +1520,21 @@ AliasCreate(
        Tcl_IncrRefCount(objv[i]);
     }
 
-    Tcl_Preserve(slaveInterp);
-    Tcl_Preserve(masterInterp);
+    Tcl_Preserve(childInterp);
+    Tcl_Preserve(parentInterp);
 
-    if (slaveInterp == masterInterp) {
-       aliasPtr->slaveCmd = Tcl_NRCreateCommand(slaveInterp,
+    if (childInterp == parentInterp) {
+       aliasPtr->childCmd = Tcl_NRCreateCommand(childInterp,
                TclGetString(namePtr), AliasObjCmd, AliasNRCmd, aliasPtr,
                AliasObjCmdDeleteProc);
     } else {
-    aliasPtr->slaveCmd = Tcl_CreateObjCommand(slaveInterp,
+    aliasPtr->childCmd = Tcl_CreateObjCommand(childInterp,
            TclGetString(namePtr), AliasObjCmd, aliasPtr,
            AliasObjCmdDeleteProc);
     }
 
-    if (TclPreventAliasLoop(interp, slaveInterp,
-           aliasPtr->slaveCmd) != TCL_OK) {
+    if (TclPreventAliasLoop(interp, childInterp,
+           aliasPtr->childCmd) != TCL_OK) {
        /*
         * Found an alias loop! The last call to Tcl_CreateObjCommand made the
         * alias point to itself. Delete the command and its alias record. Be
@@ -1548,11 +1550,11 @@ AliasCreate(
            Tcl_DecrRefCount(objv[i]);
        }
 
-       cmdPtr = (Command *) aliasPtr->slaveCmd;
+       cmdPtr = (Command *) aliasPtr->childCmd;
        cmdPtr->clientData = NULL;
        cmdPtr->deleteProc = NULL;
        cmdPtr->deleteData = NULL;
-       Tcl_DeleteCommandFromToken(slaveInterp, aliasPtr->slaveCmd);
+       Tcl_DeleteCommandFromToken(childInterp, aliasPtr->childCmd);
 
        ckfree(aliasPtr);
 
@@ -1560,8 +1562,8 @@ AliasCreate(
         * The result was already set by TclPreventAliasLoop.
         */
 
-       Tcl_Release(slaveInterp);
-       Tcl_Release(masterInterp);
+       Tcl_Release(childInterp);
+       Tcl_Release(parentInterp);
        return TCL_ERROR;
     }
 
@@ -1569,13 +1571,13 @@ AliasCreate(
      * Make an entry in the alias table. If it already exists, retry.
      */
 
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
     while (1) {
        Tcl_Obj *newToken;
        const char *string;
 
        string = TclGetString(aliasPtr->token);
-       hPtr = Tcl_CreateHashEntry(&slavePtr->aliasTable, string, &isNew);
+       hPtr = Tcl_CreateHashEntry(&childPtr->aliasTable, string, &isNew);
        if (isNew != 0) {
            break;
        }
@@ -1612,22 +1614,22 @@ AliasCreate(
      */
 
     targetPtr = ckalloc(sizeof(Target));
-    targetPtr->slaveCmd = aliasPtr->slaveCmd;
-    targetPtr->slaveInterp = slaveInterp;
+    targetPtr->childCmd = aliasPtr->childCmd;
+    targetPtr->childInterp = childInterp;
 
-    masterPtr = &((InterpInfo*) ((Interp*) masterInterp)->interpInfo)->master;
-    targetPtr->nextPtr = masterPtr->targetsPtr;
+    parentPtr = &((InterpInfo*) ((Interp*) parentInterp)->interpInfo)->parent;
+    targetPtr->nextPtr = parentPtr->targetsPtr;
     targetPtr->prevPtr = NULL;
-    if (masterPtr->targetsPtr != NULL) {
-       masterPtr->targetsPtr->prevPtr = targetPtr;
+    if (parentPtr->targetsPtr != NULL) {
+       parentPtr->targetsPtr->prevPtr = targetPtr;
     }
-    masterPtr->targetsPtr = targetPtr;
+    parentPtr->targetsPtr = targetPtr;
     aliasPtr->targetPtr = targetPtr;
 
     Tcl_SetObjResult(interp, aliasPtr->token);
 
-    Tcl_Release(slaveInterp);
-    Tcl_Release(masterInterp);
+    Tcl_Release(childInterp);
+    Tcl_Release(parentInterp);
     return TCL_OK;
 }
 \f
@@ -1636,13 +1638,13 @@ AliasCreate(
  *
  * AliasDelete --
  *
- *     Deletes the given alias from the slave interpreter given.
+ *     Deletes the given alias from the child interpreter given.
  *
  * Results:
  *     A standard Tcl result.
  *
  * Side effects:
- *     Deletes the alias from the slave interpreter.
+ *     Deletes the alias from the child interpreter.
  *
  *----------------------------------------------------------------------
  */
@@ -1650,21 +1652,21 @@ AliasCreate(
 static int
 AliasDelete(
     Tcl_Interp *interp,                /* Interpreter for result & errors. */
-    Tcl_Interp *slaveInterp,   /* Interpreter containing alias. */
+    Tcl_Interp *childInterp,   /* Interpreter containing alias. */
     Tcl_Obj *namePtr)          /* Name of alias to delete. */
 {
-    Slave *slavePtr;
+    Child *childPtr;
     Alias *aliasPtr;
     Tcl_HashEntry *hPtr;
 
     /*
-     * If the alias has been renamed in the slave, the master can still use
+     * If the alias has been renamed in the child, the parent can still use
      * the original name (with which it was created) to find the alias to
      * delete it.
      */
 
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
-    hPtr = Tcl_FindHashEntry(&slavePtr->aliasTable, TclGetString(namePtr));
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
+    hPtr = Tcl_FindHashEntry(&childPtr->aliasTable, TclGetString(namePtr));
     if (hPtr == NULL) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "alias \"%s\" not found", TclGetString(namePtr)));
@@ -1673,7 +1675,7 @@ AliasDelete(
        return TCL_ERROR;
     }
     aliasPtr = Tcl_GetHashValue(hPtr);
-    Tcl_DeleteCommandFromToken(slaveInterp, aliasPtr->slaveCmd);
+    Tcl_DeleteCommandFromToken(childInterp, aliasPtr->childCmd);
     return TCL_OK;
 }
 \f
@@ -1698,22 +1700,22 @@ AliasDelete(
 static int
 AliasDescribe(
     Tcl_Interp *interp,                /* Interpreter for result & errors. */
-    Tcl_Interp *slaveInterp,   /* Interpreter containing alias. */
+    Tcl_Interp *childInterp,   /* Interpreter containing alias. */
     Tcl_Obj *namePtr)          /* Name of alias to describe. */
 {
-    Slave *slavePtr;
+    Child *childPtr;
     Tcl_HashEntry *hPtr;
     Alias *aliasPtr;
     Tcl_Obj *prefixPtr;
 
     /*
-     * If the alias has been renamed in the slave, the master can still use
+     * If the alias has been renamed in the child, the parent can still use
      * the original name (with which it was created) to find the alias to
      * describe it.
      */
 
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
-    hPtr = Tcl_FindHashEntry(&slavePtr->aliasTable, Tcl_GetString(namePtr));
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
+    hPtr = Tcl_FindHashEntry(&childPtr->aliasTable, Tcl_GetString(namePtr));
     if (hPtr == NULL) {
        return TCL_OK;
     }
@@ -1728,7 +1730,7 @@ AliasDescribe(
  *
  * AliasList --
  *
- *     Computes a list of aliases defined in a slave interpreter.
+ *     Computes a list of aliases defined in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
@@ -1742,17 +1744,17 @@ AliasDescribe(
 static int
 AliasList(
     Tcl_Interp *interp,                /* Interp for data return. */
-    Tcl_Interp *slaveInterp)   /* Interp whose aliases to compute. */
+    Tcl_Interp *childInterp)   /* Interp whose aliases to compute. */
 {
     Tcl_HashEntry *entryPtr;
     Tcl_HashSearch hashSearch;
     Tcl_Obj *resultPtr = Tcl_NewObj();
     Alias *aliasPtr;
-    Slave *slavePtr;
+    Child *childPtr;
 
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
 
-    entryPtr = Tcl_FirstHashEntry(&slavePtr->aliasTable, &hashSearch);
+    entryPtr = Tcl_FirstHashEntry(&childPtr->aliasTable, &hashSearch);
     for ( ; entryPtr != NULL; entryPtr = Tcl_NextHashEntry(&hashSearch)) {
        aliasPtr = Tcl_GetHashValue(entryPtr);
        Tcl_ListObjAppendElement(NULL, resultPtr, aliasPtr->token);
@@ -1766,10 +1768,10 @@ AliasList(
  *
  * AliasObjCmd --
  *
- *     This is the function that services invocations of aliases in a slave
+ *     This is the function that services invocations of aliases in a child
  *     interpreter. One such command exists for each alias. When invoked,
  *     this function redirects the invocation to the target command in the
- *     master interpreter as designated by the Alias record associated with
+ *     parent interpreter as designated by the Alias record associated with
  *     this command.
  *
  * Results:
@@ -1812,8 +1814,8 @@ AliasNRCmd(
     cmdv = &listRep->elements;
 
     prefv = &aliasPtr->objPtr;
-    memcpy(cmdv, prefv, (size_t) (prefc * sizeof(Tcl_Obj *)));
-    memcpy(cmdv+prefc, objv+1, (size_t) ((objc-1) * sizeof(Tcl_Obj *)));
+    memcpy(cmdv, prefv, prefc * sizeof(Tcl_Obj *));
+    memcpy(cmdv+prefc, objv+1, (objc-1) * sizeof(Tcl_Obj *));
 
     for (i=0; i<cmdc; i++) {
        Tcl_IncrRefCount(cmdv[i]);
@@ -1861,8 +1863,8 @@ AliasObjCmd(
        cmdv = TclStackAlloc(interp, cmdc * sizeof(Tcl_Obj *));
     }
 
-    memcpy(cmdv, prefv, (size_t) (prefc * sizeof(Tcl_Obj *)));
-    memcpy(cmdv+prefc, objv+1, (size_t) ((objc-1) * sizeof(Tcl_Obj *)));
+    memcpy(cmdv, prefv, prefc * sizeof(Tcl_Obj *));
+    memcpy(cmdv+prefc, objv+1, (objc-1) * sizeof(Tcl_Obj *));
 
     Tcl_ResetResult(targetInterp);
 
@@ -1927,7 +1929,7 @@ AliasObjCmd(
  *
  * AliasObjCmdDeleteProc --
  *
- *     Is invoked when an alias command is deleted in a slave. Cleans up all
+ *     Is invoked when an alias command is deleted in a child. Cleans up all
  *     storage associated with this alias.
  *
  * Results:
@@ -1957,17 +1959,17 @@ AliasObjCmdDeleteProc(
     Tcl_DeleteHashEntry(aliasPtr->aliasEntryPtr);
 
     /*
-     * Splice the target record out of the target interpreter's master list.
+     * Splice the target record out of the target interpreter's parent list.
      */
 
     targetPtr = aliasPtr->targetPtr;
     if (targetPtr->prevPtr != NULL) {
        targetPtr->prevPtr->nextPtr = targetPtr->nextPtr;
     } else {
-       Master *masterPtr = &((InterpInfo *) ((Interp *)
-               aliasPtr->targetInterp)->interpInfo)->master;
+       Parent *parentPtr = &((InterpInfo *) ((Interp *)
+               aliasPtr->targetInterp)->interpInfo)->parent;
 
-       masterPtr->targetsPtr = targetPtr->nextPtr;
+       parentPtr->targetsPtr = targetPtr->nextPtr;
     }
     if (targetPtr->nextPtr != NULL) {
        targetPtr->nextPtr->prevPtr = targetPtr->prevPtr;
@@ -1980,13 +1982,13 @@ AliasObjCmdDeleteProc(
 /*
  *----------------------------------------------------------------------
  *
- * Tcl_CreateSlave --
+ * Tcl_CreateChild --
  *
- *     Creates a slave interpreter. The slavePath argument denotes the name
- *     of the new slave relative to the current interpreter; the slave is a
+ *     Creates a child interpreter. The childPath argument denotes the name
+ *     of the new child relative to the current interpreter; the child is a
  *     direct descendant of the one-before-last component of the path,
- *     e.g. it is a descendant of the current interpreter if the slavePath
- *     argument contains only one component. Optionally makes the slave
+ *     e.g. it is a descendant of the current interpreter if the childPath
+ *     argument contains only one component. Optionally makes the child
  *     interpreter safe.
  *
  * Results:
@@ -1995,33 +1997,33 @@ AliasObjCmdDeleteProc(
  *
  * Side effects:
  *     Creates a new interpreter and a new interpreter object command in the
- *     interpreter indicated by the slavePath argument.
+ *     interpreter indicated by the childPath argument.
  *
  *----------------------------------------------------------------------
  */
 
 Tcl_Interp *
-Tcl_CreateSlave(
+Tcl_CreateChild(
     Tcl_Interp *interp,                /* Interpreter to start search at. */
-    const char *slavePath,     /* Name of slave to create. */
-    int isSafe)                        /* Should new slave be "safe" ? */
+    const char *childPath,     /* Name of child to create. */
+    int isSafe)                        /* Should new child be "safe" ? */
 {
     Tcl_Obj *pathPtr;
-    Tcl_Interp *slaveInterp;
+    Tcl_Interp *childInterp;
 
-    pathPtr = Tcl_NewStringObj(slavePath, -1);
-    slaveInterp = SlaveCreate(interp, pathPtr, isSafe);
+    pathPtr = Tcl_NewStringObj(childPath, -1);
+    childInterp = ChildCreate(interp, pathPtr, isSafe);
     Tcl_DecrRefCount(pathPtr);
 
-    return slaveInterp;
+    return childInterp;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * Tcl_GetSlave --
+ * Tcl_GetChild --
  *
- *     Finds a slave interpreter by its path name.
+ *     Finds a child interpreter by its path name.
  *
  * Results:
  *     Returns a Tcl_Interp * for the named interpreter or NULL if not found.
@@ -2033,29 +2035,29 @@ Tcl_CreateSlave(
  */
 
 Tcl_Interp *
-Tcl_GetSlave(
+Tcl_GetChild(
     Tcl_Interp *interp,                /* Interpreter to start search from. */
-    const char *slavePath)     /* Path of slave to find. */
+    const char *childPath)     /* Path of child to find. */
 {
     Tcl_Obj *pathPtr;
-    Tcl_Interp *slaveInterp;
+    Tcl_Interp *childInterp;
 
-    pathPtr = Tcl_NewStringObj(slavePath, -1);
-    slaveInterp = GetInterp(interp, pathPtr);
+    pathPtr = Tcl_NewStringObj(childPath, -1);
+    childInterp = GetInterp(interp, pathPtr);
     Tcl_DecrRefCount(pathPtr);
 
-    return slaveInterp;
+    return childInterp;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * Tcl_GetMaster --
+ * Tcl_GetParent --
  *
- *     Finds the master interpreter of a slave interpreter.
+ *     Finds the parent interpreter of a child interpreter.
  *
  * Results:
- *     Returns a Tcl_Interp * for the master interpreter or NULL if none.
+ *     Returns a Tcl_Interp * for the parent interpreter or NULL if none.
  *
  * Side effects:
  *     None.
@@ -2064,24 +2066,24 @@ Tcl_GetSlave(
  */
 
 Tcl_Interp *
-Tcl_GetMaster(
-    Tcl_Interp *interp)                /* Get the master of this interpreter. */
+Tcl_GetParent(
+    Tcl_Interp *interp)                /* Get the parent of this interpreter. */
 {
-    Slave *slavePtr;           /* Slave record of this interpreter. */
+    Child *childPtr;           /* Child record of this interpreter. */
 
     if (interp == NULL) {
        return NULL;
     }
-    slavePtr = &((InterpInfo *) ((Interp *) interp)->interpInfo)->slave;
-    return slavePtr->masterInterp;
+    childPtr = &((InterpInfo *) ((Interp *) interp)->interpInfo)->child;
+    return childPtr->parentInterp;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * TclSetSlaveCancelFlags --
+ * TclSetChildCancelFlags --
  *
- *     This function marks all slave interpreters belonging to a given
+ *     This function marks all child interpreters belonging to a given
  *     interpreter as being canceled or not canceled, depending on the
  *     provided flags.
  *
@@ -2095,7 +2097,7 @@ Tcl_GetMaster(
  */
 
 void
-TclSetSlaveCancelFlags(
+TclSetChildCancelFlags(
     Tcl_Interp *interp,                /* Set cancel flags of this interpreter. */
     int flags,                 /* Collection of OR-ed bits that control
                                 * the cancellation of the script. Only
@@ -2104,10 +2106,10 @@ TclSetSlaveCancelFlags(
     int force)                 /* Non-zero to ignore numLevels for the purpose
                                 * of resetting the cancellation flags. */
 {
-    Master *masterPtr;         /* Master record of given interpreter. */
+    Parent *parentPtr;         /* Parent record of given interpreter. */
     Tcl_HashEntry *hPtr;       /* Search element. */
     Tcl_HashSearch hashSearch; /* Search variable. */
-    Slave *slavePtr;           /* Slave record of interpreter. */
+    Child *childPtr;           /* Child record of interpreter. */
     Interp *iPtr;
 
     if (interp == NULL) {
@@ -2116,12 +2118,12 @@ TclSetSlaveCancelFlags(
 
     flags &= (CANCELED | TCL_CANCEL_UNWIND);
 
-    masterPtr = &((InterpInfo *) ((Interp *) interp)->interpInfo)->master;
+    parentPtr = &((InterpInfo *) ((Interp *) interp)->interpInfo)->parent;
 
-    hPtr = Tcl_FirstHashEntry(&masterPtr->slaveTable, &hashSearch);
+    hPtr = Tcl_FirstHashEntry(&parentPtr->childTable, &hashSearch);
     for ( ; hPtr != NULL; hPtr = Tcl_NextHashEntry(&hashSearch)) {
-       slavePtr = Tcl_GetHashValue(hPtr);
-       iPtr = (Interp *) slavePtr->slaveInterp;
+       childPtr = Tcl_GetHashValue(hPtr);
+       iPtr = (Interp *) childPtr->childInterp;
 
        if (iPtr == NULL) {
            continue;
@@ -2134,11 +2136,11 @@ TclSetSlaveCancelFlags(
        }
 
        /*
-        * Now, recursively handle this for the slaves of this slave
+        * Now, recursively handle this for the children of this child
         * interpreter.
         */
 
-       TclSetSlaveCancelFlags((Tcl_Interp *) iPtr, flags, force);
+       TclSetChildCancelFlags((Tcl_Interp *) iPtr, flags, force);
     }
 }
 \f
@@ -2150,7 +2152,7 @@ TclSetSlaveCancelFlags(
  *     Sets the result of the asking interpreter to a proper Tcl list
  *     containing the names of interpreters between the asking and target
  *     interpreters. The target interpreter must be either the same as the
- *     asking interpreter or one of its slaves (including recursively).
+ *     asking interpreter or one of its children (including recursively).
  *
  * Results:
  *     TCL_OK if the target interpreter is the same as, or a descendant of,
@@ -2168,25 +2170,25 @@ TclSetSlaveCancelFlags(
 
 int
 Tcl_GetInterpPath(
-    Tcl_Interp *askingInterp,  /* Interpreter to start search from. */
+    Tcl_Interp *interp,        /* Interpreter to start search from. */
     Tcl_Interp *targetInterp)  /* Interpreter to find. */
 {
     InterpInfo *iiPtr;
 
-    if (targetInterp == askingInterp) {
-       Tcl_SetObjResult(askingInterp, Tcl_NewObj());
+    if (targetInterp == interp) {
+       Tcl_SetObjResult(interp, Tcl_NewObj());
        return TCL_OK;
     }
     if (targetInterp == NULL) {
        return TCL_ERROR;
     }
     iiPtr = (InterpInfo *) ((Interp *) targetInterp)->interpInfo;
-    if (Tcl_GetInterpPath(askingInterp, iiPtr->slave.masterInterp) != TCL_OK){
+    if (Tcl_GetInterpPath(interp, iiPtr->child.parentInterp) != TCL_OK){
        return TCL_ERROR;
     }
-    Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(askingInterp),
-           Tcl_NewStringObj(Tcl_GetHashKey(&iiPtr->master.slaveTable,
-                   iiPtr->slave.slaveEntryPtr), -1));
+    Tcl_ListObjAppendElement(NULL, Tcl_GetObjResult(interp),
+           Tcl_NewStringObj(Tcl_GetHashKey(&iiPtr->parent.childTable,
+                   iiPtr->child.childEntryPtr), -1));
     return TCL_OK;
 }
 \f
@@ -2195,10 +2197,10 @@ Tcl_GetInterpPath(
  *
  * GetInterp --
  *
- *     Helper function to find a slave interpreter given a pathname.
+ *     Helper function to find a child interpreter given a pathname.
  *
  * Results:
- *     Returns the slave interpreter known by that name in the calling
+ *     Returns the child interpreter known by that name in the calling
  *     interpreter, or NULL if no interpreter known by that name exists.
  *
  * Side effects:
@@ -2214,11 +2216,11 @@ GetInterp(
                                 * be found. */
 {
     Tcl_HashEntry *hPtr;       /* Search element. */
-    Slave *slavePtr;           /* Interim slave record. */
+    Child *childPtr;           /* Interim child record. */
     Tcl_Obj **objv;
     int objc, i;
     Tcl_Interp *searchInterp;  /* Interim storage for interp. to find. */
-    InterpInfo *masterInfoPtr;
+    InterpInfo *parentInfoPtr;
 
     if (TclListObjGetElements(interp, pathPtr, &objc, &objv) != TCL_OK) {
        return NULL;
@@ -2226,15 +2228,15 @@ GetInterp(
 
     searchInterp = interp;
     for (i = 0; i < objc; i++) {
-       masterInfoPtr = (InterpInfo *) ((Interp *) searchInterp)->interpInfo;
-       hPtr = Tcl_FindHashEntry(&masterInfoPtr->master.slaveTable,
+       parentInfoPtr = (InterpInfo *) ((Interp *) searchInterp)->interpInfo;
+       hPtr = Tcl_FindHashEntry(&parentInfoPtr->parent.childTable,
                TclGetString(objv[i]));
        if (hPtr == NULL) {
            searchInterp = NULL;
            break;
        }
-       slavePtr = Tcl_GetHashValue(hPtr);
-       searchInterp = slavePtr->slaveInterp;
+       childPtr = Tcl_GetHashValue(hPtr);
+       searchInterp = childPtr->childInterp;
        if (searchInterp == NULL) {
            break;
        }
@@ -2251,7 +2253,7 @@ GetInterp(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveBgerror --
+ * ChildBgerror --
  *
  *     Helper function to set/query the background error handling command
  *     prefix of an interp
@@ -2260,16 +2262,16 @@ GetInterp(
  *     A standard Tcl result.
  *
  * Side effects:
- *     When (objc == 1), slaveInterp will be set to a new background handler
+ *     When (objc == 1), childInterp will be set to a new background handler
  *     of objv[0].
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveBgerror(
+ChildBgerror(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* Interp in which limit is set/queried. */
+    Tcl_Interp *childInterp,   /* Interp in which limit is set/queried. */
     int objc,                  /* Set or Query. */
     Tcl_Obj *const objv[])     /* Argument strings. */
 {
@@ -2284,19 +2286,19 @@ SlaveBgerror(
                    "BGERRORFORMAT", NULL);
            return TCL_ERROR;
        }
-       TclSetBgErrorHandler(slaveInterp, objv[0]);
+       TclSetBgErrorHandler(childInterp, objv[0]);
     }
-    Tcl_SetObjResult(interp, TclGetBgErrorHandler(slaveInterp));
+    Tcl_SetObjResult(interp, TclGetBgErrorHandler(childInterp));
     return TCL_OK;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * SlaveCreate --
+ * ChildCreate --
  *
- *     Helper function to do the actual work of creating a slave interp and
- *     new object command. Also optionally makes the new slave interpreter
+ *     Helper function to do the actual work of creating a child interp and
+ *     new object command. Also optionally makes the new child interpreter
  *     "safe".
  *
  * Results:
@@ -2304,20 +2306,20 @@ SlaveBgerror(
  *     the result of the invoking interpreter contains an error message.
  *
  * Side effects:
- *     Creates a new slave interpreter and a new object command.
+ *     Creates a new child interpreter and a new object command.
  *
  *----------------------------------------------------------------------
  */
 
 static Tcl_Interp *
-SlaveCreate(
+ChildCreate(
     Tcl_Interp *interp,                /* Interp. to start search from. */
-    Tcl_Obj *pathPtr,          /* Path (name) of slave to create. */
+    Tcl_Obj *pathPtr,          /* Path (name) of child to create. */
     int safe)                  /* Should we make it "safe"? */
 {
-    Tcl_Interp *masterInterp, *slaveInterp;
-    Slave *slavePtr;
-    InterpInfo *masterInfoPtr;
+    Tcl_Interp *parentInterp, *childInterp;
+    Child *childPtr;
+    InterpInfo *parentInfoPtr;
     Tcl_HashEntry *hPtr;
     const char *path;
     int isNew, objc;
@@ -2327,25 +2329,25 @@ SlaveCreate(
        return NULL;
     }
     if (objc < 2) {
-       masterInterp = interp;
+       parentInterp = interp;
        path = TclGetString(pathPtr);
     } else {
        Tcl_Obj *objPtr;
 
        objPtr = Tcl_NewListObj(objc - 1, objv);
-       masterInterp = GetInterp(interp, objPtr);
+       parentInterp = GetInterp(interp, objPtr);
        Tcl_DecrRefCount(objPtr);
-       if (masterInterp == NULL) {
+       if (parentInterp == NULL) {
            return NULL;
        }
        path = TclGetString(objv[objc - 1]);
     }
     if (safe == 0) {
-       safe = Tcl_IsSafe(masterInterp);
+       safe = Tcl_IsSafe(parentInterp);
     }
 
-    masterInfoPtr = (InterpInfo *) ((Interp *) masterInterp)->interpInfo;
-    hPtr = Tcl_CreateHashEntry(&masterInfoPtr->master.slaveTable, path,
+    parentInfoPtr = (InterpInfo *) ((Interp *) parentInterp)->interpInfo;
+    hPtr = Tcl_CreateHashEntry(&parentInfoPtr->parent.childTable, path,
            &isNew);
     if (isNew == 0) {
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
@@ -2354,51 +2356,51 @@ SlaveCreate(
        return NULL;
     }
 
-    slaveInterp = Tcl_CreateInterp();
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
-    slavePtr->masterInterp = masterInterp;
-    slavePtr->slaveEntryPtr = hPtr;
-    slavePtr->slaveInterp = slaveInterp;
-    slavePtr->interpCmd = Tcl_NRCreateCommand(masterInterp, path,
-           SlaveObjCmd, NRSlaveCmd, slaveInterp, SlaveObjCmdDeleteProc);
-    Tcl_InitHashTable(&slavePtr->aliasTable, TCL_STRING_KEYS);
-    Tcl_SetHashValue(hPtr, slavePtr);
-    Tcl_SetVar(slaveInterp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
+    childInterp = Tcl_CreateInterp();
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
+    childPtr->parentInterp = parentInterp;
+    childPtr->childEntryPtr = hPtr;
+    childPtr->childInterp = childInterp;
+    childPtr->interpCmd = Tcl_NRCreateCommand(parentInterp, path,
+           ChildObjCmd, NRChildCmd, childInterp, ChildObjCmdDeleteProc);
+    Tcl_InitHashTable(&childPtr->aliasTable, TCL_STRING_KEYS);
+    Tcl_SetHashValue(hPtr, childPtr);
+    Tcl_SetVar(childInterp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
 
     /*
      * Inherit the recursion limit.
      */
 
-    ((Interp *) slaveInterp)->maxNestingDepth =
-           ((Interp *) masterInterp)->maxNestingDepth;
+    ((Interp *) childInterp)->maxNestingDepth =
+           ((Interp *) parentInterp)->maxNestingDepth;
 
     if (safe) {
-       if (Tcl_MakeSafe(slaveInterp) == TCL_ERROR) {
+       if (Tcl_MakeSafe(childInterp) == TCL_ERROR) {
            goto error;
        }
     } else {
-       if (Tcl_Init(slaveInterp) == TCL_ERROR) {
+       if (Tcl_Init(childInterp) == TCL_ERROR) {
            goto error;
        }
 
        /*
-        * This will create the "memory" command in slave interpreters if we
+        * This will create the "memory" command in child interpreters if we
         * compiled with TCL_MEM_DEBUG, otherwise it does nothing.
         */
 
-       Tcl_InitMemory(slaveInterp);
+       Tcl_InitMemory(childInterp);
     }
 
     /*
      * Inherit the TIP#143 limits.
      */
 
-    InheritLimitsFromMaster(slaveInterp, masterInterp);
+    InheritLimitsFromParent(childInterp, parentInterp);
 
     /*
      * The [clock] command presents a safe API, but uses unsafe features in
      * its implementation. This means it has to be implemented in safe interps
-     * as an alias to a version in the (trusted) master.
+     * as an alias to a version in the (trusted) parent.
      */
 
     if (safe) {
@@ -2407,7 +2409,7 @@ SlaveCreate(
 
        TclNewLiteralStringObj(clockObj, "clock");
        Tcl_IncrRefCount(clockObj);
-       status = AliasCreate(interp, slaveInterp, masterInterp, clockObj,
+       status = AliasCreate(interp, childInterp, parentInterp, clockObj,
                clockObj, 0, NULL);
        Tcl_DecrRefCount(clockObj);
        if (status != TCL_OK) {
@@ -2415,12 +2417,12 @@ SlaveCreate(
        }
     }
 
-    return slaveInterp;
+    return childInterp;
 
   error:
-    Tcl_TransferResult(slaveInterp, TCL_ERROR, interp);
+    Tcl_TransferResult(childInterp, TCL_ERROR, interp);
   error2:
-    Tcl_DeleteInterp(slaveInterp);
+    Tcl_DeleteInterp(childInterp);
 
     return NULL;
 }
@@ -2428,10 +2430,10 @@ SlaveCreate(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveObjCmd --
+ * ChildObjCmd --
  *
  *     Command to manipulate an interpreter, e.g. to send commands to it to
- *     be evaluated. One such command exists for each slave interpreter.
+ *     be evaluated. One such command exists for each child interpreter.
  *
  * Results:
  *     A standard Tcl result.
@@ -2443,23 +2445,23 @@ SlaveCreate(
  */
 
 static int
-SlaveObjCmd(
-    ClientData clientData,     /* Slave interpreter. */
+ChildObjCmd(
+    ClientData clientData,     /* Child interpreter. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    return Tcl_NRCallObjProc(interp, NRSlaveCmd, clientData, objc, objv);
+    return Tcl_NRCallObjProc(interp, NRChildCmd, clientData, objc, objv);
 }
 
 static int
-NRSlaveCmd(
-    ClientData clientData,     /* Slave interpreter. */
+NRChildCmd(
+    ClientData clientData,     /* Child interpreter. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    Tcl_Interp *slaveInterp = clientData;
+    Tcl_Interp *childInterp = clientData;
     int index;
     static const char *const options[] = {
        "alias",        "aliases",      "bgerror",      "debug",
@@ -2474,8 +2476,8 @@ NRSlaveCmd(
        OPT_RECLIMIT
     };
 
-    if (slaveInterp == NULL) {
-       Tcl_Panic("SlaveObjCmd: interpreter has been deleted");
+    if (childInterp == NULL) {
+       Tcl_Panic("ChildObjCmd: interpreter has been deleted");
     }
 
     if (objc < 2) {
@@ -2491,14 +2493,14 @@ NRSlaveCmd(
     case OPT_ALIAS:
        if (objc > 2) {
            if (objc == 3) {
-               return AliasDescribe(interp, slaveInterp, objv[2]);
+               return AliasDescribe(interp, childInterp, objv[2]);
            }
            if (TclGetString(objv[3])[0] == '\0') {
                if (objc == 4) {
-                   return AliasDelete(interp, slaveInterp, objv[2]);
+                   return AliasDelete(interp, childInterp, objv[2]);
                }
            } else {
-               return AliasCreate(interp, slaveInterp, interp, objv[2],
+               return AliasCreate(interp, childInterp, interp, objv[2],
                        objv[3], objc - 4, objv + 4);
            }
        }
@@ -2509,13 +2511,13 @@ NRSlaveCmd(
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
-       return AliasList(interp, slaveInterp);
+       return AliasList(interp, childInterp);
     case OPT_BGERROR:
        if (objc != 2 && objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "?cmdPrefix?");
            return TCL_ERROR;
        }
-       return SlaveBgerror(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildBgerror(interp, childInterp, objc - 2, objv + 2);
     case OPT_DEBUG:
        /*
         * TIP #378
@@ -2525,37 +2527,37 @@ NRSlaveCmd(
            Tcl_WrongNumArgs(interp, 2, objv, "?-frame ?bool??");
            return TCL_ERROR;
        }
-       return SlaveDebugCmd(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildDebugCmd(interp, childInterp, objc - 2, objv + 2);
     case OPT_EVAL:
        if (objc < 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "arg ?arg ...?");
            return TCL_ERROR;
        }
-       return SlaveEval(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildEval(interp, childInterp, objc - 2, objv + 2);
     case OPT_EXPOSE:
        if ((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "hiddenCmdName ?cmdName?");
            return TCL_ERROR;
        }
-       return SlaveExpose(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildExpose(interp, childInterp, objc - 2, objv + 2);
     case OPT_HIDE:
        if ((objc < 3) || (objc > 4)) {
            Tcl_WrongNumArgs(interp, 2, objv, "cmdName ?hiddenCmdName?");
            return TCL_ERROR;
        }
-       return SlaveHide(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildHide(interp, childInterp, objc - 2, objv + 2);
     case OPT_HIDDEN:
        if (objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
-       return SlaveHidden(interp, slaveInterp);
+       return ChildHidden(interp, childInterp);
     case OPT_ISSAFE:
        if (objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
-       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_IsSafe(slaveInterp)));
+       Tcl_SetObjResult(interp, Tcl_NewBooleanObj(Tcl_IsSafe(childInterp)));
        return TCL_OK;
     case OPT_INVOKEHIDDEN: {
        int i;
@@ -2594,7 +2596,7 @@ NRSlaveCmd(
                    "?-namespace ns? ?-global? ?--? cmd ?arg ..?");
            return TCL_ERROR;
        }
-       return SlaveInvokeHidden(interp, slaveInterp, namespaceName,
+       return ChildInvokeHidden(interp, childInterp, namespaceName,
                objc - i, objv + i);
     }
     case OPT_LIMIT: {
@@ -2616,23 +2618,24 @@ NRSlaveCmd(
        }
        switch ((enum LimitTypes) limitType) {
        case LIMIT_TYPE_COMMANDS:
-           return SlaveCommandLimitCmd(interp, slaveInterp, 3, objc,objv);
+           return ChildCommandLimitCmd(interp, childInterp, 3, objc,objv);
        case LIMIT_TYPE_TIME:
-           return SlaveTimeLimitCmd(interp, slaveInterp, 3, objc, objv);
+           return ChildTimeLimitCmd(interp, childInterp, 3, objc, objv);
        }
     }
+    break;
     case OPT_MARKTRUSTED:
        if (objc != 2) {
            Tcl_WrongNumArgs(interp, 2, objv, NULL);
            return TCL_ERROR;
        }
-       return SlaveMarkTrusted(interp, slaveInterp);
+       return ChildMarkTrusted(interp, childInterp);
     case OPT_RECLIMIT:
        if (objc != 2 && objc != 3) {
            Tcl_WrongNumArgs(interp, 2, objv, "?newlimit?");
            return TCL_ERROR;
        }
-       return SlaveRecursionLimit(interp, slaveInterp, objc - 2, objv + 2);
+       return ChildRecursionLimit(interp, childInterp, objc - 2, objv + 2);
     }
 
     return TCL_ERROR;
@@ -2641,71 +2644,71 @@ NRSlaveCmd(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveObjCmdDeleteProc --
+ * ChildObjCmdDeleteProc --
  *
- *     Invoked when an object command for a slave interpreter is deleted;
- *     cleans up all state associated with the slave interpreter and destroys
- *     the slave interpreter.
+ *     Invoked when an object command for a child interpreter is deleted;
+ *     cleans up all state associated with the child interpreter and destroys
+ *     the child interpreter.
  *
  * Results:
  *     None.
  *
  * Side effects:
- *     Cleans up all state associated with the slave interpreter and destroys
- *     the slave interpreter.
+ *     Cleans up all state associated with the child interpreter and destroys
+ *     the child interpreter.
  *
  *----------------------------------------------------------------------
  */
 
 static void
-SlaveObjCmdDeleteProc(
-    ClientData clientData)     /* The SlaveRecord for the command. */
+ChildObjCmdDeleteProc(
+    ClientData clientData)     /* The ChildRecord for the command. */
 {
-    Slave *slavePtr;           /* Interim storage for Slave record. */
-    Tcl_Interp *slaveInterp = clientData;
-                               /* And for a slave interp. */
+    Child *childPtr;           /* Interim storage for Child record. */
+    Tcl_Interp *childInterp = clientData;
+                               /* And for a child interp. */
 
-    slavePtr = &((InterpInfo *) ((Interp *) slaveInterp)->interpInfo)->slave;
+    childPtr = &((InterpInfo *) ((Interp *) childInterp)->interpInfo)->child;
 
     /*
-     * Unlink the slave from its master interpreter.
+     * Unlink the child from its parent interpreter.
      */
 
-    Tcl_DeleteHashEntry(slavePtr->slaveEntryPtr);
+    Tcl_DeleteHashEntry(childPtr->childEntryPtr);
 
     /*
-     * Set to NULL so that when the InterpInfo is cleaned up in the slave it
+     * Set to NULL so that when the InterpInfo is cleaned up in the child it
      * does not try to delete the command causing all sorts of grief. See
-     * SlaveRecordDeleteProc().
+     * ChildRecordDeleteProc().
      */
 
-    slavePtr->interpCmd = NULL;
+    childPtr->interpCmd = NULL;
 
-    if (slavePtr->slaveInterp != NULL) {
-       Tcl_DeleteInterp(slavePtr->slaveInterp);
+    if (childPtr->childInterp != NULL) {
+       Tcl_DeleteInterp(childPtr->childInterp);
     }
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * SlaveDebugCmd -- TIP #378
+ * ChildDebugCmd -- TIP #378
  *
- *     Helper function to handle 'debug' command in a slave interpreter.
+ *     Helper function to handle 'debug' command in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
  *
  * Side effects:
- *     May modify INTERP_DEBUG_FRAME flag in the slave.
+ *     May modify INTERP_DEBUG_FRAME flag in the child.
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveDebugCmd(
+ChildDebugCmd(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* The slave interpreter in which command
+    Tcl_Interp *childInterp,   /* The child interpreter in which command
                                 * will be evaluated. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
@@ -2720,7 +2723,7 @@ SlaveDebugCmd(
     Interp *iPtr;
     Tcl_Obj *resultPtr;
 
-    iPtr = (Interp *) slaveInterp;
+    iPtr = (Interp *) childInterp;
     if (objc == 0) {
        resultPtr = Tcl_NewObj();
        Tcl_ListObjAppendElement(NULL, resultPtr,
@@ -2760,9 +2763,9 @@ SlaveDebugCmd(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveEval --
+ * ChildEval --
  *
- *     Helper function to evaluate a command in a slave interpreter.
+ *     Helper function to evaluate a command in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
@@ -2774,9 +2777,9 @@ SlaveDebugCmd(
  */
 
 static int
-SlaveEval(
+ChildEval(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* The slave interpreter in which command
+    Tcl_Interp *childInterp,   /* The child interpreter in which command
                                 * will be evaluated. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
@@ -2784,17 +2787,17 @@ SlaveEval(
     int result;
 
     /*
-     * TIP #285: If necessary, reset the cancellation flags for the slave
-     * interpreter now; otherwise, canceling a script in a master interpreter
-     * can result in a situation where a slave interpreter can no longer
+     * TIP #285: If necessary, reset the cancellation flags for the child
+     * interpreter now; otherwise, canceling a script in a parent interpreter
+     * can result in a situation where a child interpreter can no longer
      * evaluate any scripts unless somebody calls the TclResetCancellation
      * function for that particular Tcl_Interp.
      */
 
-    TclSetSlaveCancelFlags(slaveInterp, 0, 0);
+    TclSetChildCancelFlags(childInterp, 0, 0);
 
-    Tcl_Preserve(slaveInterp);
-    Tcl_AllowExceptions(slaveInterp);
+    Tcl_Preserve(childInterp);
+    Tcl_AllowExceptions(childInterp);
 
     if (objc == 1) {
        /*
@@ -2807,40 +2810,40 @@ SlaveEval(
 
        TclArgumentGet(interp, objv[0], &invoker, &word);
 
-       result = TclEvalObjEx(slaveInterp, objv[0], 0, invoker, word);
+       result = TclEvalObjEx(childInterp, objv[0], 0, invoker, word);
     } else {
        Tcl_Obj *objPtr = Tcl_ConcatObj(objc, objv);
        Tcl_IncrRefCount(objPtr);
-       result = Tcl_EvalObjEx(slaveInterp, objPtr, 0);
+       result = Tcl_EvalObjEx(childInterp, objPtr, 0);
        Tcl_DecrRefCount(objPtr);
     }
-    Tcl_TransferResult(slaveInterp, result, interp);
+    Tcl_TransferResult(childInterp, result, interp);
 
-    Tcl_Release(slaveInterp);
+    Tcl_Release(childInterp);
     return result;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * SlaveExpose --
+ * ChildExpose --
  *
- *     Helper function to expose a command in a slave interpreter.
+ *     Helper function to expose a command in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
  *
  * Side effects:
- *     After this call scripts in the slave will be able to invoke the newly
+ *     After this call scripts in the child will be able to invoke the newly
  *     exposed command.
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveExpose(
+ChildExpose(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* Interp in which command will be exposed. */
+    Tcl_Interp *childInterp,   /* Interp in which command will be exposed. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument strings. */
 {
@@ -2856,9 +2859,9 @@ SlaveExpose(
     }
 
     name = TclGetString(objv[(objc == 1) ? 0 : 1]);
-    if (Tcl_ExposeCommand(slaveInterp, TclGetString(objv[0]),
+    if (Tcl_ExposeCommand(childInterp, TclGetString(objv[0]),
            name) != TCL_OK) {
-       Tcl_TransferResult(slaveInterp, TCL_ERROR, interp);
+       Tcl_TransferResult(childInterp, TCL_ERROR, interp);
        return TCL_ERROR;
     }
     return TCL_OK;
@@ -2867,7 +2870,7 @@ SlaveExpose(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveRecursionLimit --
+ * ChildRecursionLimit --
  *
  *     Helper function to set/query the Recursion limit of an interp
  *
@@ -2875,16 +2878,16 @@ SlaveExpose(
  *     A standard Tcl result.
  *
  * Side effects:
- *     When (objc == 1), slaveInterp will be set to a new recursion limit of
+ *     When (objc == 1), childInterp will be set to a new recursion limit of
  *     objv[0].
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveRecursionLimit(
+ChildRecursionLimit(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* Interp in which limit is set/queried. */
+    Tcl_Interp *childInterp,   /* Interp in which limit is set/queried. */
     int objc,                  /* Set or Query. */
     Tcl_Obj *const objv[])     /* Argument strings. */
 {
@@ -2909,9 +2912,9 @@ SlaveRecursionLimit(
                    NULL);
            return TCL_ERROR;
        }
-       Tcl_SetRecursionLimit(slaveInterp, limit);
-       iPtr = (Interp *) slaveInterp;
-       if (interp == slaveInterp && iPtr->numLevels > limit) {
+       Tcl_SetRecursionLimit(childInterp, limit);
+       iPtr = (Interp *) childInterp;
+       if (interp == childInterp && iPtr->numLevels > limit) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
                    "falling back due to new recursion limit", -1));
            Tcl_SetErrorCode(interp, "TCL", "RECURSION", NULL);
@@ -2920,7 +2923,7 @@ SlaveRecursionLimit(
        Tcl_SetObjResult(interp, objv[0]);
        return TCL_OK;
     } else {
-       limit = Tcl_SetRecursionLimit(slaveInterp, 0);
+       limit = Tcl_SetRecursionLimit(childInterp, 0);
        Tcl_SetObjResult(interp, Tcl_NewIntObj(limit));
        return TCL_OK;
     }
@@ -2929,24 +2932,24 @@ SlaveRecursionLimit(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveHide --
+ * ChildHide --
  *
- *     Helper function to hide a command in a slave interpreter.
+ *     Helper function to hide a command in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
  *
  * Side effects:
- *     After this call scripts in the slave will no longer be able to invoke
+ *     After this call scripts in the child will no longer be able to invoke
  *     the named command.
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveHide(
+ChildHide(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* Interp in which command will be exposed. */
+    Tcl_Interp *childInterp,   /* Interp in which command will be exposed. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument strings. */
 {
@@ -2962,8 +2965,8 @@ SlaveHide(
     }
 
     name = TclGetString(objv[(objc == 1) ? 0 : 1]);
-    if (Tcl_HideCommand(slaveInterp, TclGetString(objv[0]), name) != TCL_OK) {
-       Tcl_TransferResult(slaveInterp, TCL_ERROR, interp);
+    if (Tcl_HideCommand(childInterp, TclGetString(objv[0]), name) != TCL_OK) {
+       Tcl_TransferResult(childInterp, TCL_ERROR, interp);
        return TCL_ERROR;
     }
     return TCL_OK;
@@ -2972,9 +2975,9 @@ SlaveHide(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveHidden --
+ * ChildHidden --
  *
- *     Helper function to compute list of hidden commands in a slave
+ *     Helper function to compute list of hidden commands in a child
  *     interpreter.
  *
  * Results:
@@ -2987,16 +2990,16 @@ SlaveHide(
  */
 
 static int
-SlaveHidden(
+ChildHidden(
     Tcl_Interp *interp,                /* Interp for data return. */
-    Tcl_Interp *slaveInterp)   /* Interp whose hidden commands to query. */
+    Tcl_Interp *childInterp)   /* Interp whose hidden commands to query. */
 {
     Tcl_Obj *listObjPtr = Tcl_NewObj();        /* Local object pointer. */
     Tcl_HashTable *hTblPtr;            /* For local searches. */
     Tcl_HashEntry *hPtr;               /* For local searches. */
     Tcl_HashSearch hSearch;            /* For local searches. */
 
-    hTblPtr = ((Interp *) slaveInterp)->hiddenCmdTablePtr;
+    hTblPtr = ((Interp *) childInterp)->hiddenCmdTablePtr;
     if (hTblPtr != NULL) {
        for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
                hPtr != NULL;
@@ -3012,9 +3015,9 @@ SlaveHidden(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveInvokeHidden --
+ * ChildInvokeHidden --
  *
- *     Helper function to invoke a hidden command in a slave interpreter.
+ *     Helper function to invoke a hidden command in a child interpreter.
  *
  * Results:
  *     A standard Tcl result.
@@ -3026,9 +3029,9 @@ SlaveHidden(
  */
 
 static int
-SlaveInvokeHidden(
+ChildInvokeHidden(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp,   /* The slave interpreter in which command will
+    Tcl_Interp *childInterp,   /* The child interpreter in which command will
                                 * be invoked. */
     const char *namespaceName, /* The namespace to use, if any. */
     int objc,                  /* Number of arguments. */
@@ -3045,31 +3048,31 @@ SlaveInvokeHidden(
        return TCL_ERROR;
     }
 
-    Tcl_Preserve(slaveInterp);
-    Tcl_AllowExceptions(slaveInterp);
+    Tcl_Preserve(childInterp);
+    Tcl_AllowExceptions(childInterp);
 
     if (namespaceName == NULL) {
-       NRE_callback *rootPtr = TOP_CB(slaveInterp);
+       NRE_callback *rootPtr = TOP_CB(childInterp);
 
-       Tcl_NRAddCallback(interp, NRPostInvokeHidden, slaveInterp,
+       Tcl_NRAddCallback(interp, NRPostInvokeHidden, childInterp,
                rootPtr, NULL, NULL);
-       return TclNRInvoke(NULL, slaveInterp, objc, objv);
+       return TclNRInvoke(NULL, childInterp, objc, objv);
     } else {
        Namespace *nsPtr, *dummy1, *dummy2;
        const char *tail;
 
-       result = TclGetNamespaceForQualName(slaveInterp, namespaceName, NULL,
+       result = TclGetNamespaceForQualName(childInterp, namespaceName, NULL,
                TCL_FIND_ONLY_NS | TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG
                | TCL_CREATE_NS_IF_UNKNOWN, &nsPtr, &dummy1, &dummy2, &tail);
        if (result == TCL_OK) {
-           result = TclObjInvokeNamespace(slaveInterp, objc, objv,
+           result = TclObjInvokeNamespace(childInterp, objc, objv,
                    (Tcl_Namespace *) nsPtr, TCL_INVOKE_HIDDEN);
        }
     }
 
-    Tcl_TransferResult(slaveInterp, result, interp);
+    Tcl_TransferResult(childInterp, result, interp);
 
-    Tcl_Release(slaveInterp);
+    Tcl_Release(childInterp);
     return result;
 }
 
@@ -3079,38 +3082,38 @@ NRPostInvokeHidden(
     Tcl_Interp *interp,
     int result)
 {
-    Tcl_Interp *slaveInterp = (Tcl_Interp *)data[0];
+    Tcl_Interp *childInterp = (Tcl_Interp *)data[0];
     NRE_callback *rootPtr = (NRE_callback *)data[1];
 
-    if (interp != slaveInterp) {
-       result = TclNRRunCallbacks(slaveInterp, result, rootPtr);
-       Tcl_TransferResult(slaveInterp, result, interp);
+    if (interp != childInterp) {
+       result = TclNRRunCallbacks(childInterp, result, rootPtr);
+       Tcl_TransferResult(childInterp, result, interp);
     }
-    Tcl_Release(slaveInterp);
+    Tcl_Release(childInterp);
     return result;
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * SlaveMarkTrusted --
+ * ChildMarkTrusted --
  *
- *     Helper function to mark a slave interpreter as trusted (unsafe).
+ *     Helper function to mark a child interpreter as trusted (unsafe).
  *
  * Results:
  *     A standard Tcl result.
  *
  * Side effects:
  *     After this call the hard-wired security checks in the core no longer
- *     prevent the slave from performing certain operations.
+ *     prevent the child from performing certain operations.
  *
  *----------------------------------------------------------------------
  */
 
 static int
-SlaveMarkTrusted(
+ChildMarkTrusted(
     Tcl_Interp *interp,                /* Interp for error return. */
-    Tcl_Interp *slaveInterp)   /* The slave interpreter which will be marked
+    Tcl_Interp *childInterp)   /* The child interpreter which will be marked
                                 * trusted. */
 {
     if (Tcl_IsSafe(interp)) {
@@ -3121,7 +3124,7 @@ SlaveMarkTrusted(
                NULL);
        return TCL_ERROR;
     }
-    ((Interp *) slaveInterp)->flags &= ~SAFE_INTERP;
+    ((Interp *) childInterp)->flags &= ~SAFE_INTERP;
     return TCL_OK;
 }
 \f
@@ -3178,23 +3181,23 @@ Tcl_MakeSafe(
 {
     Tcl_Channel chan;          /* Channel to remove from safe interpreter. */
     Interp *iPtr = (Interp *) interp;
-    Tcl_Interp *master = ((InterpInfo*) iPtr->interpInfo)->slave.masterInterp;
+    Tcl_Interp *parent = ((InterpInfo*) iPtr->interpInfo)->child.parentInterp;
 
     TclHideUnsafeCommands(interp);
 
-    if (master != NULL) {
+    if (parent != NULL) {
        /*
-        * Alias these function implementations in the slave to those in the
-        * master; the overall implementations are safe, but they're normally
+        * Alias these function implementations in the child to those in the
+        * parent; the overall implementations are safe, but they're normally
         * defined by init.tcl which is not sourced by safe interpreters.
         * Assume these functions all work. [Bug 2895741]
         */
 
        (void) Tcl_Eval(interp,
                "namespace eval ::tcl {namespace eval mathfunc {}}");
-       (void) Tcl_CreateAlias(interp, "::tcl::mathfunc::min", master,
+       (void) Tcl_CreateAlias(interp, "::tcl::mathfunc::min", parent,
                "::tcl::mathfunc::min", 0, NULL);
-       (void) Tcl_CreateAlias(interp, "::tcl::mathfunc::max", master,
+       (void) Tcl_CreateAlias(interp, "::tcl::mathfunc::max", parent,
                "::tcl::mathfunc::max", 0, NULL);
     }
 
@@ -3206,7 +3209,7 @@ Tcl_MakeSafe(
      */
 
     /*
-     * No env array in a safe slave.
+     * No env array in a safe interpreter.
      */
 
     Tcl_UnsetVar(interp, "env", TCL_GLOBAL_ONLY);
@@ -3280,7 +3283,7 @@ int
 Tcl_LimitExceeded(
     Tcl_Interp *interp)
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     return iPtr->limit.exceeded != 0;
 }
@@ -3311,10 +3314,10 @@ int
 Tcl_LimitReady(
     Tcl_Interp *interp)
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     if (iPtr->limit.active != 0) {
-       register int ticker = ++iPtr->limit.granularityTicker;
+       int ticker = ++iPtr->limit.granularityTicker;
 
        if ((iPtr->limit.active & TCL_LIMIT_COMMANDS) &&
                ((iPtr->limit.cmdGranularity == 1) ||
@@ -3358,7 +3361,7 @@ Tcl_LimitCheck(
     Tcl_Interp *interp)
 {
     Interp *iPtr = (Interp *) interp;
-    register int ticker = iPtr->limit.granularityTicker;
+    int ticker = iPtr->limit.granularityTicker;
 
     if (Tcl_InterpDeleted(interp)) {
        return TCL_OK;
@@ -4110,7 +4113,7 @@ Tcl_LimitGetGranularity(
  * DeleteScriptLimitCallback --
  *
  *     Callback for when a script limit (a limit callback implemented as a
- *     Tcl script in a master interpreter, as set up from Tcl) is deleted.
+ *     Tcl script in a parent interpreter, as set up from Tcl) is deleted.
  *
  * Results:
  *     None.
@@ -4323,48 +4326,48 @@ TclInitLimitSupport(
 /*
  *----------------------------------------------------------------------
  *
- * InheritLimitsFromMaster --
+ * InheritLimitsFromParent --
  *
- *     Derive the interpreter limit configuration for a slave interpreter
- *     from the limit config for the master.
+ *     Derive the interpreter limit configuration for a child interpreter
+ *     from the limit config for the parent.
  *
  * Results:
  *     None.
  *
  * Side effects:
- *     The slave interpreter limits are set so that if the master has a
- *     limit, it may not exceed it by handing off work to slave interpreters.
- *     Note that this does not transfer limit callbacks from the master to
- *     the slave.
+ *     The child interpreter limits are set so that if the parent has a
+ *     limit, it may not exceed it by handing off work to child interpreters.
+ *     Note that this does not transfer limit callbacks from the parent to
+ *     the child.
  *
  *----------------------------------------------------------------------
  */
 
 static void
-InheritLimitsFromMaster(
-    Tcl_Interp *slaveInterp,
-    Tcl_Interp *masterInterp)
+InheritLimitsFromParent(
+    Tcl_Interp *childInterp,
+    Tcl_Interp *parentInterp)
 {
-    Interp *slavePtr = (Interp *) slaveInterp;
-    Interp *masterPtr = (Interp *) masterInterp;
+    Interp *childPtr = (Interp *) childInterp;
+    Interp *parentPtr = (Interp *) parentInterp;
 
-    if (masterPtr->limit.active & TCL_LIMIT_COMMANDS) {
-       slavePtr->limit.active |= TCL_LIMIT_COMMANDS;
-       slavePtr->limit.cmdCount = 0;
-       slavePtr->limit.cmdGranularity = masterPtr->limit.cmdGranularity;
+    if (parentPtr->limit.active & TCL_LIMIT_COMMANDS) {
+       childPtr->limit.active |= TCL_LIMIT_COMMANDS;
+       childPtr->limit.cmdCount = 0;
+       childPtr->limit.cmdGranularity = parentPtr->limit.cmdGranularity;
     }
-    if (masterPtr->limit.active & TCL_LIMIT_TIME) {
-       slavePtr->limit.active |= TCL_LIMIT_TIME;
-       memcpy(&slavePtr->limit.time, &masterPtr->limit.time,
+    if (parentPtr->limit.active & TCL_LIMIT_TIME) {
+       childPtr->limit.active |= TCL_LIMIT_TIME;
+       memcpy(&childPtr->limit.time, &parentPtr->limit.time,
                sizeof(Tcl_Time));
-       slavePtr->limit.timeGranularity = masterPtr->limit.timeGranularity;
+       childPtr->limit.timeGranularity = parentPtr->limit.timeGranularity;
     }
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * SlaveCommandLimitCmd --
+ * ChildCommandLimitCmd --
  *
  *     Implementation of the [interp limit $i commands] and [$i limit
  *     commands] subcommands. See the interp manual page for a full
@@ -4380,9 +4383,9 @@ InheritLimitsFromMaster(
  */
 
 static int
-SlaveCommandLimitCmd(
+ChildCommandLimitCmd(
     Tcl_Interp *interp,                /* Current interpreter. */
-    Tcl_Interp *slaveInterp,   /* Interpreter being adjusted. */
+    Tcl_Interp *childInterp,   /* Interpreter being adjusted. */
     int consumedObjc,          /* Number of args already parsed. */
     int objc,                  /* Total number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
@@ -4406,7 +4409,7 @@ SlaveCommandLimitCmd(
      * avoid. [Bug 3398794]
      */
 
-    if (interp == slaveInterp) {
+    if (interp == childInterp) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(
                "limits on current interpreter inaccessible", -1));
        Tcl_SetErrorCode(interp, "TCL", "OPERATION", "INTERP", "SELF", NULL);
@@ -4417,7 +4420,7 @@ SlaveCommandLimitCmd(
        Tcl_Obj *dictPtr;
 
        TclNewObj(dictPtr);
-       key.interp = slaveInterp;
+       key.interp = childInterp;
        key.type = TCL_LIMIT_COMMANDS;
        hPtr = Tcl_FindHashEntry(&iPtr->limit.callbacks, (char *) &key);
        if (hPtr != NULL) {
@@ -4437,12 +4440,12 @@ SlaveCommandLimitCmd(
                    Tcl_NewStringObj(options[0], -1), empty);
        }
        Tcl_DictObjPut(NULL, dictPtr, Tcl_NewStringObj(options[1], -1),
-               Tcl_NewIntObj(Tcl_LimitGetGranularity(slaveInterp,
+               Tcl_NewIntObj(Tcl_LimitGetGranularity(childInterp,
                TCL_LIMIT_COMMANDS)));
 
-       if (Tcl_LimitTypeEnabled(slaveInterp, TCL_LIMIT_COMMANDS)) {
+       if (Tcl_LimitTypeEnabled(childInterp, TCL_LIMIT_COMMANDS)) {
            Tcl_DictObjPut(NULL, dictPtr, Tcl_NewStringObj(options[2], -1),
-                   Tcl_NewIntObj(Tcl_LimitGetCommands(slaveInterp)));
+                   Tcl_NewIntObj(Tcl_LimitGetCommands(childInterp)));
        } else {
            Tcl_Obj *empty;
 
@@ -4459,7 +4462,7 @@ SlaveCommandLimitCmd(
        }
        switch ((enum Options) index) {
        case OPT_CMD:
-           key.interp = slaveInterp;
+           key.interp = childInterp;
            key.type = TCL_LIMIT_COMMANDS;
            hPtr = Tcl_FindHashEntry(&iPtr->limit.callbacks, (char *) &key);
            if (hPtr != NULL) {
@@ -4471,12 +4474,12 @@ SlaveCommandLimitCmd(
            break;
        case OPT_GRAN:
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
-                   Tcl_LimitGetGranularity(slaveInterp, TCL_LIMIT_COMMANDS)));
+                   Tcl_LimitGetGranularity(childInterp, TCL_LIMIT_COMMANDS)));
            break;
        case OPT_VAL:
-           if (Tcl_LimitTypeEnabled(slaveInterp, TCL_LIMIT_COMMANDS)) {
+           if (Tcl_LimitTypeEnabled(childInterp, TCL_LIMIT_COMMANDS)) {
                Tcl_SetObjResult(interp,
-                       Tcl_NewIntObj(Tcl_LimitGetCommands(slaveInterp)));
+                       Tcl_NewIntObj(Tcl_LimitGetCommands(childInterp)));
            }
            break;
        }
@@ -4532,18 +4535,18 @@ SlaveCommandLimitCmd(
            }
        }
        if (scriptObj != NULL) {
-           SetScriptLimitCallback(interp, TCL_LIMIT_COMMANDS, slaveInterp,
+           SetScriptLimitCallback(interp, TCL_LIMIT_COMMANDS, childInterp,
                    (scriptLen > 0 ? scriptObj : NULL));
        }
        if (granObj != NULL) {
-           Tcl_LimitSetGranularity(slaveInterp, TCL_LIMIT_COMMANDS, gran);
+           Tcl_LimitSetGranularity(childInterp, TCL_LIMIT_COMMANDS, gran);
        }
        if (limitObj != NULL) {
            if (limitLen > 0) {
-               Tcl_LimitSetCommands(slaveInterp, limit);
-               Tcl_LimitTypeSet(slaveInterp, TCL_LIMIT_COMMANDS);
+               Tcl_LimitSetCommands(childInterp, limit);
+               Tcl_LimitTypeSet(childInterp, TCL_LIMIT_COMMANDS);
            } else {
-               Tcl_LimitTypeReset(slaveInterp, TCL_LIMIT_COMMANDS);
+               Tcl_LimitTypeReset(childInterp, TCL_LIMIT_COMMANDS);
            }
        }
        return TCL_OK;
@@ -4553,7 +4556,7 @@ SlaveCommandLimitCmd(
 /*
  *----------------------------------------------------------------------
  *
- * SlaveTimeLimitCmd --
+ * ChildTimeLimitCmd --
  *
  *     Implementation of the [interp limit $i time] and [$i limit time]
  *     subcommands. See the interp manual page for a full description.
@@ -4568,9 +4571,9 @@ SlaveCommandLimitCmd(
  */
 
 static int
-SlaveTimeLimitCmd(
+ChildTimeLimitCmd(
     Tcl_Interp *interp,                        /* Current interpreter. */
-    Tcl_Interp *slaveInterp,           /* Interpreter being adjusted. */
+    Tcl_Interp *childInterp,           /* Interpreter being adjusted. */
     int consumedObjc,                  /* Number of args already parsed. */
     int objc,                          /* Total number of arguments. */
     Tcl_Obj *const objv[])             /* Argument objects. */
@@ -4594,7 +4597,7 @@ SlaveTimeLimitCmd(
      * avoid. [Bug 3398794]
      */
 
-    if (interp == slaveInterp) {
+    if (interp == childInterp) {
        Tcl_SetObjResult(interp, Tcl_NewStringObj(
                "limits on current interpreter inaccessible", -1));
        Tcl_SetErrorCode(interp, "TCL", "OPERATION", "INTERP", "SELF", NULL);
@@ -4605,7 +4608,7 @@ SlaveTimeLimitCmd(
        Tcl_Obj *dictPtr;
 
        TclNewObj(dictPtr);
-       key.interp = slaveInterp;
+       key.interp = childInterp;
        key.type = TCL_LIMIT_TIME;
        hPtr = Tcl_FindHashEntry(&iPtr->limit.callbacks, (char *) &key);
        if (hPtr != NULL) {
@@ -4624,13 +4627,13 @@ SlaveTimeLimitCmd(
                    Tcl_NewStringObj(options[0], -1), empty);
        }
        Tcl_DictObjPut(NULL, dictPtr, Tcl_NewStringObj(options[1], -1),
-               Tcl_NewIntObj(Tcl_LimitGetGranularity(slaveInterp,
+               Tcl_NewIntObj(Tcl_LimitGetGranularity(childInterp,
                TCL_LIMIT_TIME)));
 
-       if (Tcl_LimitTypeEnabled(slaveInterp, TCL_LIMIT_TIME)) {
+       if (Tcl_LimitTypeEnabled(childInterp, TCL_LIMIT_TIME)) {
            Tcl_Time limitMoment;
 
-           Tcl_LimitGetTime(slaveInterp, &limitMoment);
+           Tcl_LimitGetTime(childInterp, &limitMoment);
            Tcl_DictObjPut(NULL, dictPtr, Tcl_NewStringObj(options[2], -1),
                    Tcl_NewLongObj(limitMoment.usec/1000));
            Tcl_DictObjPut(NULL, dictPtr, Tcl_NewStringObj(options[3], -1),
@@ -4653,7 +4656,7 @@ SlaveTimeLimitCmd(
        }
        switch ((enum Options) index) {
        case OPT_CMD:
-           key.interp = slaveInterp;
+           key.interp = childInterp;
            key.type = TCL_LIMIT_TIME;
            hPtr = Tcl_FindHashEntry(&iPtr->limit.callbacks, (char *) &key);
            if (hPtr != NULL) {
@@ -4665,22 +4668,22 @@ SlaveTimeLimitCmd(
            break;
        case OPT_GRAN:
            Tcl_SetObjResult(interp, Tcl_NewIntObj(
-                   Tcl_LimitGetGranularity(slaveInterp, TCL_LIMIT_TIME)));
+                   Tcl_LimitGetGranularity(childInterp, TCL_LIMIT_TIME)));
            break;
        case OPT_MILLI:
-           if (Tcl_LimitTypeEnabled(slaveInterp, TCL_LIMIT_TIME)) {
+           if (Tcl_LimitTypeEnabled(childInterp, TCL_LIMIT_TIME)) {
                Tcl_Time limitMoment;
 
-               Tcl_LimitGetTime(slaveInterp, &limitMoment);
+               Tcl_LimitGetTime(childInterp, &limitMoment);
                Tcl_SetObjResult(interp,
                        Tcl_NewLongObj(limitMoment.usec/1000));
            }
            break;
        case OPT_SEC:
-           if (Tcl_LimitTypeEnabled(slaveInterp, TCL_LIMIT_TIME)) {
+           if (Tcl_LimitTypeEnabled(childInterp, TCL_LIMIT_TIME)) {
                Tcl_Time limitMoment;
 
-               Tcl_LimitGetTime(slaveInterp, &limitMoment);
+               Tcl_LimitGetTime(childInterp, &limitMoment);
                Tcl_SetObjResult(interp, Tcl_NewLongObj(limitMoment.sec));
            }
            break;
@@ -4697,7 +4700,7 @@ SlaveTimeLimitCmd(
        Tcl_Time limitMoment;
        int tmp;
 
-       Tcl_LimitGetTime(slaveInterp, &limitMoment);
+       Tcl_LimitGetTime(childInterp, &limitMoment);
        for (i=consumedObjc ; i<objc ; i+=2) {
            if (Tcl_GetIndexFromObj(interp, objv[i], options, "option", 0,
                    &index) != TCL_OK) {
@@ -4794,18 +4797,18 @@ SlaveTimeLimitCmd(
                limitMoment.sec += limitMoment.usec / 1000000;
                limitMoment.usec %= 1000000;
 
-               Tcl_LimitSetTime(slaveInterp, &limitMoment);
-               Tcl_LimitTypeSet(slaveInterp, TCL_LIMIT_TIME);
+               Tcl_LimitSetTime(childInterp, &limitMoment);
+               Tcl_LimitTypeSet(childInterp, TCL_LIMIT_TIME);
            } else {
-               Tcl_LimitTypeReset(slaveInterp, TCL_LIMIT_TIME);
+               Tcl_LimitTypeReset(childInterp, TCL_LIMIT_TIME);
            }
        }
        if (scriptObj != NULL) {
-           SetScriptLimitCallback(interp, TCL_LIMIT_TIME, slaveInterp,
+           SetScriptLimitCallback(interp, TCL_LIMIT_TIME, childInterp,
                    (scriptLen > 0 ? scriptObj : NULL));
        }
        if (granObj != NULL) {
-           Tcl_LimitSetGranularity(slaveInterp, TCL_LIMIT_TIME, gran);
+           Tcl_LimitSetGranularity(childInterp, TCL_LIMIT_TIME, gran);
        }
        return TCL_OK;
     }
index 6eb6780..11726d5 100644 (file)
@@ -420,14 +420,14 @@ TclListObjCopy(
 int
 Tcl_ListObjGetElements(
     Tcl_Interp *interp,                /* Used to report errors if not NULL. */
-    register Tcl_Obj *listPtr, /* List object for which an element array is
+    Tcl_Obj *listPtr,  /* List object for which an element array is
                                 * to be returned. */
     int *objcPtr,              /* Where to store the count of objects
                                 * referenced by objv. */
     Tcl_Obj ***objvPtr)                /* Where to store the pointer to an array of
                                 * pointers to the list's objects. */
 {
-    register List *listRepPtr;
+    List *listRepPtr;
 
     if (listPtr->typePtr != &tclListType) {
        int result;
@@ -481,7 +481,7 @@ Tcl_ListObjGetElements(
 int
 Tcl_ListObjAppendList(
     Tcl_Interp *interp,                /* Used to report errors if not NULL. */
-    register Tcl_Obj *listPtr, /* List object to append elements to. */
+    Tcl_Obj *listPtr,  /* List object to append elements to. */
     Tcl_Obj *elemListPtr)      /* List obj with elements to append. */
 {
     int objc;
@@ -543,7 +543,7 @@ Tcl_ListObjAppendElement(
     Tcl_Obj *listPtr,          /* List object to append objPtr to. */
     Tcl_Obj *objPtr)           /* Object to append to listPtr's list. */
 {
-    register List *listRepPtr, *newPtr = NULL;
+    List *listRepPtr, *newPtr = NULL;
     int numElems, numRequired, needGrow, isShared, attempt;
 
     if (Tcl_IsShared(listPtr)) {
@@ -653,7 +653,7 @@ Tcl_ListObjAppendElement(
             * Old intrep to be freed, re-use refCounts.
             */
 
-           memcpy(dst, src, (size_t) numElems * sizeof(Tcl_Obj *));
+           memcpy(dst, src, numElems * sizeof(Tcl_Obj *));
            ckfree(listRepPtr);
        }
        listRepPtr = newPtr;
@@ -711,11 +711,11 @@ Tcl_ListObjAppendElement(
 int
 Tcl_ListObjIndex(
     Tcl_Interp *interp,                /* Used to report errors if not NULL. */
-    register Tcl_Obj *listPtr, /* List object to index into. */
-    register int index,                /* Index of element to return. */
+    Tcl_Obj *listPtr,  /* List object to index into. */
+    int index,         /* Index of element to return. */
     Tcl_Obj **objPtrPtr)       /* The resulting Tcl_Obj* is stored here. */
 {
-    register List *listRepPtr;
+    List *listRepPtr;
 
     if (listPtr->typePtr != &tclListType) {
        int result;
@@ -766,10 +766,10 @@ Tcl_ListObjIndex(
 int
 Tcl_ListObjLength(
     Tcl_Interp *interp,                /* Used to report errors if not NULL. */
-    register Tcl_Obj *listPtr, /* List object whose #elements to return. */
-    register int *intPtr)      /* The resulting int is stored here. */
+    Tcl_Obj *listPtr,  /* List object whose #elements to return. */
+    int *intPtr)       /* The resulting int is stored here. */
 {
-    register List *listRepPtr;
+    List *listRepPtr;
 
     if (listPtr->typePtr != &tclListType) {
        int result;
@@ -839,7 +839,7 @@ Tcl_ListObjReplace(
                                 * insert. */
 {
     List *listRepPtr;
-    register Tcl_Obj **elemPtrs;
+    Tcl_Obj **elemPtrs;
     int needGrow, numElems, numRequired, numAfterLast, start, i, j, isShared;
 
     if (Tcl_IsShared(listPtr)) {
@@ -953,7 +953,7 @@ Tcl_ListObjReplace(
        if ((numAfterLast > 0) && (shift != 0)) {
            Tcl_Obj **src = elemPtrs + start;
 
-           memmove(src+shift, src, (size_t) numAfterLast * sizeof(Tcl_Obj*));
+           memmove(src+shift, src, numAfterLast * sizeof(Tcl_Obj*));
        }
     } else {
        /*
@@ -1024,7 +1024,7 @@ Tcl_ListObjReplace(
             */
 
            if (first > 0) {
-               memcpy(elemPtrs, oldPtrs, (size_t) first * sizeof(Tcl_Obj *));
+               memcpy(elemPtrs, oldPtrs, first * sizeof(Tcl_Obj *));
            }
 
            /*
@@ -1227,7 +1227,7 @@ TclLindexFlat(
                        return NULL;
                    }
                }
-               listPtr = Tcl_NewObj();
+               TclNewObj(listPtr);
            } else {
                /*
                 * Extract the pointer to the appropriate element.
@@ -1458,7 +1458,7 @@ TclLsetFlat(
        if (--indexCount) {
            parentList = subListPtr;
            if (index == elemCount) {
-               subListPtr = Tcl_NewObj();
+               TclNewObj(subListPtr);
            } else {
                subListPtr = elemPtrs[index];
            }
index 16185e6..35c54be 100644 (file)
@@ -58,7 +58,7 @@ static void           RebuildLiteralTable(LiteralTable *tablePtr);
 
 void
 TclInitLiteralTable(
-    register LiteralTable *tablePtr)
+    LiteralTable *tablePtr)
                                /* Pointer to table structure, which is
                                 * supplied by the caller. */
 {
@@ -213,7 +213,7 @@ TclCreateLiteral(
 
            if ((objLength == length) && ((length == 0)
                    || ((objBytes[0] == bytes[0])
-                   && (memcmp(objBytes, bytes, (unsigned) length) == 0)))) {
+                   && (memcmp(objBytes, bytes, length) == 0)))) {
                /*
                 * A literal was found: return it
                 */
@@ -269,7 +269,7 @@ TclCreateLiteral(
     }
 #endif
 
-    globalPtr = ckalloc(sizeof(LiteralEntry));
+    globalPtr = (LiteralEntry *)ckalloc(sizeof(LiteralEntry));
     globalPtr->objPtr = objPtr;
     Tcl_IncrRefCount(objPtr);
     globalPtr->refCount = 1;
@@ -381,7 +381,7 @@ int
 TclRegisterLiteral(
     void *ePtr,                /* Points to the CompileEnv in whose object
                                 * array an object is found or created. */
-    register char *bytes,      /* Points to string for which to find or
+    char *bytes,       /* Points to string for which to find or
                                 * create an object in CompileEnv's object
                                 * array. */
     int length,                        /* Number of bytes in the string. If < 0, the
@@ -418,7 +418,7 @@ TclRegisterLiteral(
        objPtr = localPtr->objPtr;
        if ((objPtr->length == length) && ((length == 0)
                || ((objPtr->bytes[0] == bytes[0])
-               && (memcmp(objPtr->bytes, bytes, (unsigned) length) == 0)))) {
+               && (memcmp(objPtr->bytes, bytes, length) == 0)))) {
            if ((flags & LITERAL_ON_HEAP)) {
                ckfree(bytes);
            }
@@ -490,13 +490,13 @@ static LiteralEntry *
 LookupLiteralEntry(
     Tcl_Interp *interp,                /* Interpreter for which objPtr was created to
                                 * hold a literal. */
-    register Tcl_Obj *objPtr)  /* Points to a Tcl object holding a literal
+    Tcl_Obj *objPtr)   /* Points to a Tcl object holding a literal
                                 * that was previously created by a call to
                                 * TclRegisterLiteral. */
 {
     Interp *iPtr = (Interp *) interp;
     LiteralTable *globalTablePtr = &iPtr->literalTable;
-    register LiteralEntry *entryPtr;
+    LiteralEntry *entryPtr;
     const char *bytes;
     int length, globalHash;
 
@@ -536,7 +536,7 @@ void
 TclHideLiteral(
     Tcl_Interp *interp,                /* Interpreter for which objPtr was created to
                                 * hold a literal. */
-    register CompileEnv *envPtr,/* Points to CompileEnv whose literal array
+    CompileEnv *envPtr,/* Points to CompileEnv whose literal array
                                 * contains the entry being hidden. */
     int index)                 /* The index of the entry in the literal
                                 * array. */
@@ -599,14 +599,14 @@ TclHideLiteral(
 
 int
 TclAddLiteralObj(
-    register CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
+    CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
                                 * the object is to be inserted. */
     Tcl_Obj *objPtr,           /* The object to insert into the array. */
     LiteralEntry **litPtrPtr)  /* The location where the pointer to the new
                                 * literal entry should be stored. May be
                                 * NULL. */
 {
-    register LiteralEntry *lPtr;
+    LiteralEntry *lPtr;
     int objIndex;
 
     if (envPtr->literalArrayNext >= envPtr->literalArrayEnd) {
@@ -648,12 +648,12 @@ TclAddLiteralObj(
 
 static int
 AddLocalLiteralEntry(
-    register CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
+    CompileEnv *envPtr,/* Points to CompileEnv in whose literal array
                                 * the object is to be inserted. */
     Tcl_Obj *objPtr,           /* The literal to add to the CompileEnv. */
     int localHash)             /* Hash value for the literal's string. */
 {
-    register LiteralTable *localTablePtr = &envPtr->localLitTable;
+    LiteralTable *localTablePtr = &envPtr->localLitTable;
     LiteralEntry *localPtr;
     int objIndex;
 
@@ -725,7 +725,7 @@ AddLocalLiteralEntry(
 
 static void
 ExpandLocalLiteralArray(
-    register CompileEnv *envPtr)/* Points to the CompileEnv whose object array
+    CompileEnv *envPtr)/* Points to the CompileEnv whose object array
                                 * must be enlarged. */
 {
     /*
@@ -747,14 +747,14 @@ ExpandLocalLiteralArray(
     }
 
     if (envPtr->mallocedLiteralArray) {
-       newArrayPtr = ckrealloc(currArrayPtr, newSize);
+       newArrayPtr = (LiteralEntry *)ckrealloc(currArrayPtr, newSize);
     } else {
        /*
         * envPtr->literalArrayPtr isn't a ckalloc'd pointer, so we must
         * code a ckrealloc equivalent for ourselves.
         */
 
-       newArrayPtr = ckalloc(newSize);
+       newArrayPtr = (LiteralEntry *)ckalloc(newSize);
        memcpy(newArrayPtr, currArrayPtr, currBytes);
        envPtr->mallocedLiteralArray = 1;
     }
@@ -807,13 +807,13 @@ void
 TclReleaseLiteral(
     Tcl_Interp *interp,                /* Interpreter for which objPtr was created to
                                 * hold a literal. */
-    register Tcl_Obj *objPtr)  /* Points to a literal object that was
+    Tcl_Obj *objPtr)   /* Points to a literal object that was
                                 * previously created by a call to
                                 * TclRegisterLiteral. */
 {
     Interp *iPtr = (Interp *) interp;
     LiteralTable *globalTablePtr;
-    register LiteralEntry *entryPtr, *prevPtr;
+    LiteralEntry *entryPtr, *prevPtr;
     const char *bytes;
     int length, index;
 
@@ -888,10 +888,10 @@ TclReleaseLiteral(
 
 static unsigned
 HashString(
-    register const char *string,       /* String for which to compute hash value. */
+    const char *string,        /* String for which to compute hash value. */
     int length)                        /* Number of bytes in the string. */
 {
-    register unsigned int result = 0;
+    unsigned int result = 0;
 
     /*
      * I tried a zillion different hash functions and asked many other people
@@ -952,12 +952,12 @@ HashString(
 
 static void
 RebuildLiteralTable(
-    register LiteralTable *tablePtr)
+    LiteralTable *tablePtr)
                                /* Local or global table to enlarge. */
 {
     LiteralEntry **oldBuckets;
-    register LiteralEntry **oldChainPtr, **newChainPtr;
-    register LiteralEntry *entryPtr;
+    LiteralEntry **oldChainPtr, **newChainPtr;
+    LiteralEntry *entryPtr;
     LiteralEntry **bucketPtr;
     const char *bytes;
     unsigned int oldSize;
@@ -982,7 +982,8 @@ RebuildLiteralTable(
     }
 
     tablePtr->numBuckets *= 4;
-    tablePtr->buckets = ckalloc(tablePtr->numBuckets * sizeof(LiteralEntry*));
+    tablePtr->buckets = (LiteralEntry **)ckalloc(
+           tablePtr->numBuckets * sizeof(LiteralEntry *));
     for (count=tablePtr->numBuckets, newChainPtr=tablePtr->buckets;
            count>0 ; count--, newChainPtr++) {
        *newChainPtr = NULL;
@@ -1086,7 +1087,7 @@ TclLiteralStats(
 #define NUM_COUNTERS 10
     int count[NUM_COUNTERS], overflow, i, j;
     double average, tmp;
-    register LiteralEntry *entryPtr;
+    LiteralEntry *entryPtr;
     char *result, *p;
 
     /*
@@ -1118,7 +1119,7 @@ TclLiteralStats(
      * Print out the histogram and a few other pieces of information.
      */
 
-    result = ckalloc(NUM_COUNTERS*60 + 300);
+    result = (char *)ckalloc(NUM_COUNTERS*60 + 300);
     sprintf(result, "%d entries in table, %d buckets\n",
            tablePtr->numEntries, tablePtr->numBuckets);
     p = result + strlen(result);
@@ -1157,10 +1158,10 @@ TclVerifyLocalLiteralTable(
     CompileEnv *envPtr)                /* Points to CompileEnv whose literal table is
                                 * to be validated. */
 {
-    register LiteralTable *localTablePtr = &envPtr->localLitTable;
-    register LiteralEntry *localPtr;
+    LiteralTable *localTablePtr = &envPtr->localLitTable;
+    LiteralEntry *localPtr;
     char *bytes;
-    register int i;
+    int i;
     int length, count;
 
     count = 0;
@@ -1208,10 +1209,10 @@ TclVerifyGlobalLiteralTable(
     Interp *iPtr)              /* Points to interpreter whose global literal
                                 * table is to be validated. */
 {
-    register LiteralTable *globalTablePtr = &iPtr->literalTable;
-    register LiteralEntry *globalPtr;
+    LiteralTable *globalTablePtr = &iPtr->literalTable;
+    LiteralEntry *globalPtr;
     char *bytes;
-    register int i;
+    int i;
     int length, count;
 
     count = 0;
index f1bd248..9ca2e7a 100644 (file)
@@ -196,9 +196,9 @@ Tcl_LoadObjCmd(
 
     target = interp;
     if (objc == 4) {
-       const char *slaveIntName = Tcl_GetString(objv[3]);
+       const char *childIntName = Tcl_GetString(objv[3]);
 
-       target = Tcl_GetSlave(interp, slaveIntName);
+       target = Tcl_GetChild(interp, childIntName);
        if (target == NULL) {
            code = TCL_ERROR;
            goto done;
@@ -619,9 +619,9 @@ Tcl_UnloadObjCmd(
 
     target = interp;
     if (objc - i == 3) {
-       const char *slaveIntName = Tcl_GetString(objv[i + 2]);
+       const char *childIntName = Tcl_GetString(objv[i + 2]);
 
-       target = Tcl_GetSlave(interp, slaveIntName);
+       target = Tcl_GetChild(interp, childIntName);
        if (target == NULL) {
            return TCL_ERROR;
        }
@@ -871,7 +871,7 @@ Tcl_UnloadObjCmd(
 
                    for (ipPrevPtr = ipPtr; ipPtr != NULL;
                            ipPrevPtr = ipPtr, ipPtr = ipPtr->nextPtr) {
-                       if (ipPtr->pkgPtr == pkgPtr) {
+                       if (ipPtr->pkgPtr == defaultPtr) {
                            ipPrevPtr->nextPtr = ipPtr->nextPtr;
                            break;
                        }
@@ -1049,7 +1049,7 @@ TclGetLoadedPackages(
         * Return information about all of the available packages.
         */
 
-       resultObj = Tcl_NewObj();
+       TclNewObj(resultObj);
        Tcl_MutexLock(&packageMutex);
        for (pkgPtr = firstPackagePtr; pkgPtr != NULL;
                pkgPtr = pkgPtr->nextPtr) {
@@ -1068,12 +1068,12 @@ TclGetLoadedPackages(
      * interpreter.
      */
 
-    target = Tcl_GetSlave(interp, targetName);
+    target = Tcl_GetChild(interp, targetName);
     if (target == NULL) {
        return TCL_ERROR;
     }
     ipPtr = Tcl_GetAssocData(target, "tclLoad", NULL);
-    resultObj = Tcl_NewObj();
+    TclNewObj(resultObj);
     for (; ipPtr != NULL; ipPtr = ipPtr->nextPtr) {
        pkgPtr = ipPtr->pkgPtr;
        pkgDesc[0] = Tcl_NewStringObj(pkgPtr->fileName, -1);
index 08c1fe0..f0b2682 100644 (file)
@@ -117,7 +117,7 @@ static void         Prompt(Tcl_Interp *interp, InteractiveState *isPtr);
 static void            StdinProc(ClientData clientData, int mask);
 static void            FreeMainInterp(ClientData clientData);
 \f
-#if !defined(_WIN32) || defined(UNICODE)
+#if !defined(_WIN32) || defined(UNICODE) && !defined(TCL_ASCII_MAIN)
 static Tcl_ThreadDataKey dataKey;
 
 /*
@@ -306,7 +306,7 @@ Tcl_MainEx(
 
     is.interp = interp;
     is.prompt = PROMPT_START;
-    is.commandPtr = Tcl_NewObj();
+    TclNewObj(is.commandPtr);
 
     /*
      * If the application has not already set a startup script, parse the
@@ -521,7 +521,7 @@ Tcl_MainEx(
                    TCL_EVAL_GLOBAL);
            is.input = Tcl_GetStdChannel(TCL_STDIN);
            Tcl_DecrRefCount(is.commandPtr);
-           is.commandPtr = Tcl_NewObj();
+           TclNewObj(is.commandPtr);
            Tcl_IncrRefCount(is.commandPtr);
            if (code != TCL_OK) {
                chan = Tcl_GetStdChannel(TCL_STDERR);
@@ -805,7 +805,8 @@ StdinProc(
     code = Tcl_RecordAndEvalObj(interp, commandPtr, TCL_EVAL_GLOBAL);
     isPtr->input = chan = Tcl_GetStdChannel(TCL_STDIN);
     Tcl_DecrRefCount(commandPtr);
-    isPtr->commandPtr = commandPtr = Tcl_NewObj();
+    TclNewObj(commandPtr);
+    isPtr->commandPtr = commandPtr;
     Tcl_IncrRefCount(commandPtr);
     if (chan != NULL) {
        Tcl_CreateChannelHandler(chan, TCL_READABLE, StdinProc, isPtr);
index cf4ecc4..9541828 100644 (file)
@@ -225,7 +225,7 @@ TclInitNamespaceSubsystem(void)
 
 Tcl_Namespace *
 Tcl_GetCurrentNamespace(
-    register Tcl_Interp *interp)/* Interpreter whose current namespace is
+    Tcl_Interp *interp)/* Interpreter whose current namespace is
                                 * being queried. */
 {
     return TclGetCurrentNamespace(interp);
@@ -249,7 +249,7 @@ Tcl_GetCurrentNamespace(
 
 Tcl_Namespace *
 Tcl_GetGlobalNamespace(
-    register Tcl_Interp *interp)/* Interpreter whose global namespace should
+    Tcl_Interp *interp)/* Interpreter whose global namespace should
                                 * be returned. */
 {
     return TclGetGlobalNamespace(interp);
@@ -301,8 +301,8 @@ Tcl_PushCallFrame(
                                 * variables. */
 {
     Interp *iPtr = (Interp *) interp;
-    register CallFrame *framePtr = (CallFrame *) callFramePtr;
-    register Namespace *nsPtr;
+    CallFrame *framePtr = (CallFrame *) callFramePtr;
+    Namespace *nsPtr;
 
     if (namespacePtr == NULL) {
        nsPtr = (Namespace *) TclGetCurrentNamespace(interp);
@@ -378,8 +378,8 @@ void
 Tcl_PopCallFrame(
     Tcl_Interp *interp)                /* Interpreter with call frame to pop. */
 {
-    register Interp *iPtr = (Interp *) interp;
-    register CallFrame *framePtr = iPtr->framePtr;
+    Interp *iPtr = (Interp *) interp;
+    CallFrame *framePtr = iPtr->framePtr;
     Namespace *nsPtr;
 
     /*
@@ -664,7 +664,7 @@ Tcl_CreateNamespace(
                                 * function should be called. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Namespace *nsPtr, *ancestorPtr;
+    Namespace *nsPtr, *ancestorPtr;
     Namespace *parentPtr, *dummy1Ptr, *dummy2Ptr;
     Namespace *globalNsPtr = iPtr->globalNsPtr;
     const char *simpleName;
@@ -833,7 +833,7 @@ Tcl_CreateNamespace(
     for (ancestorPtr = nsPtr; ancestorPtr != NULL;
            ancestorPtr = ancestorPtr->parentPtr) {
        if (ancestorPtr != globalNsPtr) {
-           register Tcl_DString *tempPtr = namePtr;
+           Tcl_DString *tempPtr = namePtr;
 
            TclDStringAppendLiteral(buffPtr, "::");
            Tcl_DStringAppend(buffPtr, ancestorPtr->name, -1);
@@ -861,7 +861,7 @@ Tcl_CreateNamespace(
     name = Tcl_DStringValue(namePtr);
     nameLen = Tcl_DStringLength(namePtr);
     nsPtr->fullName = ckalloc(nameLen + 1);
-    memcpy(nsPtr->fullName, name, (unsigned) nameLen + 1);
+    memcpy(nsPtr->fullName, name, nameLen + 1);
 
     Tcl_DStringFree(&buffer1);
     Tcl_DStringFree(&buffer2);
@@ -907,7 +907,7 @@ void
 Tcl_DeleteNamespace(
     Tcl_Namespace *namespacePtr)/* Points to the namespace to delete. */
 {
-    register Namespace *nsPtr = (Namespace *) namespacePtr;
+    Namespace *nsPtr = (Namespace *) namespacePtr;
     Interp *iPtr = (Interp *) nsPtr->interp;
     Namespace *globalNsPtr = (Namespace *)
            TclGetGlobalNamespace((Tcl_Interp *) iPtr);
@@ -1103,11 +1103,11 @@ TclNamespaceDeleted(
 
 void
 TclTeardownNamespace(
-    register Namespace *nsPtr) /* Points to the namespace to be dismantled
+    Namespace *nsPtr)  /* Points to the namespace to be dismantled
                                 * and unlinked from its parent. */
 {
     Interp *iPtr = (Interp *) nsPtr->interp;
-    register Tcl_HashEntry *entryPtr;
+    Tcl_HashEntry *entryPtr;
     Tcl_HashSearch search;
     int i;
 
@@ -1296,7 +1296,7 @@ TclTeardownNamespace(
 
 static void
 NamespaceFree(
-    register Namespace *nsPtr) /* Points to the namespace to free. */
+    Namespace *nsPtr)  /* Points to the namespace to free. */
 {
     /*
      * Most of the namespace's contents are freed when the namespace is
@@ -1455,7 +1455,7 @@ Tcl_Export(
 
     len = strlen(pattern);
     patternCpy = ckalloc(len + 1);
-    memcpy(patternCpy, pattern, (unsigned) len + 1);
+    memcpy(patternCpy, pattern, len + 1);
 
     nsPtr->exportArrayPtr[nsPtr->numExportPatterns] = patternCpy;
     nsPtr->numExportPatterns++;
@@ -1572,7 +1572,7 @@ Tcl_Import(
 {
     Namespace *nsPtr, *importNsPtr, *dummyPtr;
     const char *simplePattern;
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     Tcl_HashSearch search;
 
     /*
@@ -1851,7 +1851,7 @@ Tcl_ForgetImport(
     Namespace *nsPtr, *sourceNsPtr, *dummyPtr;
     const char *simplePattern;
     char *cmdName;
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     Tcl_HashSearch search;
 
     /*
@@ -1978,7 +1978,7 @@ TclGetOriginalCommand(
     Tcl_Command command)       /* The imported command for which the original
                                 * command should be returned. */
 {
-    register Command *cmdPtr = (Command *) command;
+    Command *cmdPtr = (Command *) command;
     ImportedCmdData *dataPtr;
 
     if (cmdPtr->deleteProc != DeleteImportedCmd) {
@@ -2067,7 +2067,7 @@ DeleteImportedCmd(
     ImportedCmdData *dataPtr = clientData;
     Command *realCmdPtr = dataPtr->realCmdPtr;
     Command *selfPtr = dataPtr->selfPtr;
-    register ImportRef *refPtr, *prevPtr;
+    ImportRef *refPtr, *prevPtr;
 
     prevPtr = NULL;
     for (refPtr = realCmdPtr->importRefPtr; refPtr != NULL;
@@ -2487,7 +2487,7 @@ Tcl_FindNamespace(
                                 * points to namespace in which to resolve
                                 * name; if NULL, look up name in the current
                                 * namespace. */
-    register int flags)                /* Flags controlling namespace lookup: an OR'd
+    int flags)         /* Flags controlling namespace lookup: an OR'd
                                 * combination of TCL_GLOBAL_ONLY and
                                 * TCL_LEAVE_ERR_MSG flags. */
 {
@@ -2558,8 +2558,8 @@ Tcl_FindCommand(
 {
     Interp *iPtr = (Interp *) interp;
     Namespace *cxtNsPtr;
-    register Tcl_HashEntry *entryPtr;
-    register Command *cmdPtr;
+    Tcl_HashEntry *entryPtr;
+    Command *cmdPtr;
     const char *simpleName;
     int result;
 
@@ -2670,7 +2670,7 @@ Tcl_FindCommand(
        }
     } else {
        Namespace *nsPtr[2];
-       register int search;
+       int search;
 
        TclGetNamespaceForQualName(interp, name, cxtNsPtr,
                flags, &nsPtr[0], &nsPtr[1], &cxtNsPtr, &simpleName);
@@ -2744,7 +2744,7 @@ TclResetShadowedCmdRefs(
 {
     char *cmdName;
     Tcl_HashEntry *hPtr;
-    register Namespace *nsPtr;
+    Namespace *nsPtr;
     Namespace *trailNsPtr, *shadowNsPtr;
     Namespace *globalNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
     int found, i;
@@ -2991,7 +2991,7 @@ NamespaceChildrenCmd(
     Namespace *globalNsPtr = (Namespace *) TclGetGlobalNamespace(interp);
     const char *pattern = NULL;
     Tcl_DString buffer;
-    register Tcl_HashEntry *entryPtr;
+    Tcl_HashEntry *entryPtr;
     Tcl_HashSearch search;
     Tcl_Obj *listPtr, *elemPtr;
 
@@ -3117,7 +3117,7 @@ NamespaceCodeCmd(
 {
     Namespace *currNsPtr;
     Tcl_Obj *listPtr, *objPtr;
-    register const char *arg;
+    const char *arg;
     int length;
 
     if (objc != 2) {
@@ -3196,7 +3196,7 @@ NamespaceCurrentCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Namespace *currNsPtr;
+    Namespace *currNsPtr;
 
     if (objc != 1) {
        Tcl_WrongNumArgs(interp, 1, objv, NULL);
@@ -3261,7 +3261,7 @@ NamespaceDeleteCmd(
 {
     Tcl_Namespace *namespacePtr;
     const char *name;
-    register int i;
+    int i;
 
     if (objc < 1) {
        Tcl_WrongNumArgs(interp, 1, objv, "?name name...?");
@@ -3547,8 +3547,9 @@ NamespaceExportCmd(
      */
 
     if (objc == 1) {
-       Tcl_Obj *listPtr = Tcl_NewObj();
+       Tcl_Obj *listPtr;
 
+       TclNewObj(listPtr);
        (void) Tcl_AppendExportList(interp, NULL, listPtr);
        Tcl_SetObjResult(interp, listPtr);
        return TCL_OK;
@@ -3616,7 +3617,7 @@ NamespaceForgetCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     const char *pattern;
-    register int i, result;
+    int i, result;
 
     if (objc < 1) {
        Tcl_WrongNumArgs(interp, 1, objv, "?pattern pattern...?");
@@ -3682,7 +3683,7 @@ NamespaceImportCmd(
 {
     int allowOverwrite = 0;
     const char *string, *pattern;
-    register int i, result;
+    int i, result;
     int firstArg;
 
     if (objc < 1) {
@@ -3835,7 +3836,7 @@ NRNamespaceInscopeCmd(
        cmdObjPtr = objv[2];
     } else {
        Tcl_Obj *concatObjv[2];
-       register Tcl_Obj *listPtr;
+       Tcl_Obj *listPtr;
 
        listPtr = Tcl_NewListObj(0, NULL);
        for (i = 3;  i < objc;  i++) {
@@ -4026,8 +4027,9 @@ NamespacePathCmd(
      */
 
     if (objc == 1) {
-       Tcl_Obj *resultObj = Tcl_NewObj();
+       Tcl_Obj *resultObj;
 
+       TclNewObj(resultObj);
        for (i=0 ; i<nsPtr->commandPathLength ; i++) {
            if (nsPtr->commandPathArray[i].nsPtr != NULL) {
                Tcl_ListObjAppendElement(NULL, resultObj, Tcl_NewStringObj(
@@ -4236,7 +4238,7 @@ NamespaceQualifiersCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register const char *name, *p;
+    const char *name, *p;
     int length;
 
     if (objc != 2) {
@@ -4491,7 +4493,7 @@ NamespaceTailCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register const char *name, *p;
+    const char *name, *p;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "string");
@@ -4694,7 +4696,7 @@ NamespaceWhichCmd(
 
 static void
 FreeNsNameInternalRep(
-    register Tcl_Obj *objPtr)  /* nsName object with internal representation
+    Tcl_Obj *objPtr)   /* nsName object with internal representation
                                 * to free. */
 {
     ResolvedNsName *resNamePtr = objPtr->internalRep.twoPtrValue.ptr1;
@@ -4740,7 +4742,7 @@ FreeNsNameInternalRep(
 static void
 DupNsNameInternalRep(
     Tcl_Obj *srcPtr,           /* Object with internal rep to copy. */
-    register Tcl_Obj *copyPtr) /* Object with internal rep to set. */
+    Tcl_Obj *copyPtr)  /* Object with internal rep to set. */
 {
     ResolvedNsName *resNamePtr = srcPtr->internalRep.twoPtrValue.ptr1;
 
@@ -4776,11 +4778,11 @@ SetNsNameFromAny(
     Tcl_Interp *interp,                /* Points to the namespace in which to resolve
                                 * name. Also used for error reporting if not
                                 * NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
+    Tcl_Obj *objPtr)   /* The object to convert. */
 {
     const char *dummy;
     Namespace *nsPtr, *dummy1Ptr, *dummy2Ptr;
-    register ResolvedNsName *resNamePtr;
+    ResolvedNsName *resNamePtr;
     const char *name;
 
     if (interp == NULL) {
@@ -4914,7 +4916,7 @@ TclLogCommandInfo(
     Tcl_Obj **tosPtr)          /* Current stack of bytecode execution
                                 * context */
 {
-    register const char *p;
+    const char *p;
     Interp *iPtr = (Interp *) interp;
     int overflow, limit = 150;
     Var *varPtr, *arrayPtr;
index c1db80c..053abfe 100644 (file)
@@ -132,7 +132,7 @@ static const Tcl_MethodType classConstructor = {
 };
 
 /*
- * Scripted parts of TclOO. First, the master script (cannot be outside this
+ * Scripted parts of TclOO. First, the main script (cannot be outside this
  * file).
  */
 
@@ -797,7 +797,7 @@ MyDeleted(
     ClientData clientData)     /* Reference to the object whose [my] has been
                                 * squelched. */
 {
-    register Object *oPtr = clientData;
+    Object *oPtr = clientData;
 
     oPtr->myCommand = NULL;
 }
@@ -1632,7 +1632,7 @@ Tcl_NewObjectInstance(
     int skip)                  /* Number of arguments to _not_ pass to the
                                 * constructor. */
 {
-    register Class *classPtr = (Class *) cls;
+    Class *classPtr = (Class *) cls;
     Object *oPtr;
     ClientData clientData[4];
 
@@ -1700,7 +1700,7 @@ TclNRNewObjectInstance(
     Tcl_Object *objectPtr)     /* Place to write the object reference upon
                                 * successful allocation. */
 {
-    register Class *classPtr = (Class *) cls;
+    Class *classPtr = (Class *) cls;
     CallContext *contextPtr;
     Tcl_InterpState state;
     Object *oPtr;
@@ -2558,7 +2558,7 @@ TclOOObjectCmdCore(
 
     methodNamePtr = objv[1];
     if (oPtr->mapMethodNameProc != NULL) {
-       register Class **startClsPtr = &startCls;
+       Class **startClsPtr = &startCls;
        Tcl_Obj *mappedMethodName = Tcl_DuplicateObj(methodNamePtr);
 
        result = oPtr->mapMethodNameProc(interp, (Tcl_Object) oPtr,
@@ -2615,7 +2615,7 @@ TclOOObjectCmdCore(
     if (startCls != NULL) {
        for (; contextPtr->index < contextPtr->callPtr->numChain;
                contextPtr->index++) {
-           register struct MInvoke *miPtr =
+           struct MInvoke *miPtr =
                    &contextPtr->callPtr->chain[contextPtr->index];
 
            if (miPtr->isFilter) {
@@ -2753,7 +2753,7 @@ TclNRObjectContextInvokeNext(
     Tcl_Obj *const *objv,
     int skip)
 {
-    register CallContext *contextPtr = (CallContext *) context;
+    CallContext *contextPtr = (CallContext *) context;
 
     if (contextPtr->index + 1 >= contextPtr->callPtr->numChain) {
        /*
index d874cba..b7f70e7 100644 (file)
@@ -399,7 +399,7 @@ TclOO_Object_Eval(
 {
     CallContext *contextPtr = (CallContext *) context;
     Tcl_Object object = Tcl_ObjectContextObject(context);
-    register const int skip = Tcl_ObjectContextSkippedArgs(context);
+    const int skip = Tcl_ObjectContextSkippedArgs(context);
     CallFrame *framePtr, **framePtrPtr = &framePtr;
     Tcl_Obj *scriptPtr;
     CmdFrame *invoker;
@@ -1028,7 +1028,7 @@ TclOOSelfObjCmd(
            Tcl_SetErrorCode(interp, "TCL", "OO", "UNMATCHED_CONTEXT", NULL);
            return TCL_ERROR;
        } else {
-           register struct MInvoke *miPtr = &CurrentlyInvoked(contextPtr);
+           struct MInvoke *miPtr = &CurrentlyInvoked(contextPtr);
            Object *oPtr;
            const char *type;
 
@@ -1155,7 +1155,7 @@ TclOOSelfObjCmd(
        }
     case SELF_CALL:
        result[0] = TclOORenderCallChain(interp, contextPtr->callPtr);
-       result[1] = Tcl_NewIntObj(contextPtr->index);
+       TclNewIntObj(result[1], contextPtr->index);
        Tcl_SetObjResult(interp, Tcl_NewListObj(2, result));
        return TCL_OK;
     }
index cc02c68..65b1e38 100644 (file)
@@ -105,7 +105,7 @@ void
 TclOODeleteContext(
     CallContext *contextPtr)
 {
-    register Object *oPtr = contextPtr->oPtr;
+    Object *oPtr = contextPtr->oPtr;
 
     TclOODeleteChain(contextPtr->callPtr);
     if (oPtr != NULL) {
@@ -215,7 +215,7 @@ DupMethodNameRep(
     Tcl_Obj *srcPtr,
     Tcl_Obj *dstPtr)
 {
-    register CallChain *callPtr = srcPtr->internalRep.twoPtrValue.ptr1;
+    CallChain *callPtr = srcPtr->internalRep.twoPtrValue.ptr1;
 
     dstPtr->typePtr = &methodNameType;
     dstPtr->internalRep.twoPtrValue.ptr1 = callPtr;
@@ -226,7 +226,7 @@ static void
 FreeMethodNameRep(
     Tcl_Obj *objPtr)
 {
-    register CallChain *callPtr = objPtr->internalRep.twoPtrValue.ptr1;
+    CallChain *callPtr = objPtr->internalRep.twoPtrValue.ptr1;
 
     TclOODeleteChain(callPtr);
     objPtr->typePtr = NULL;
@@ -255,7 +255,7 @@ TclOOInvokeContext(
     int objc,                  /* The number of arguments. */
     Tcl_Obj *const objv[])     /* The arguments as actually seen. */
 {
-    register CallContext *const contextPtr = clientData;
+    CallContext *const contextPtr = clientData;
     Method *const mPtr = contextPtr->callPtr->chain[contextPtr->index].mPtr;
     const int isFilter =
            contextPtr->callPtr->chain[contextPtr->index].isFilter;
@@ -487,7 +487,7 @@ TclOOGetSortedMethodList(
 
        if (i > 0) {
            if (i > 1) {
-               qsort((void *) strings, (unsigned) i, sizeof(char *), CmpStr);
+               qsort((void *) strings, i, sizeof(char *), CmpStr);
            }
            *stringsPtr = strings;
        } else {
@@ -560,7 +560,7 @@ TclOOGetSortedClassMethodList(
 
        if (i > 0) {
            if (i > 1) {
-               qsort((void *) strings, (unsigned) i, sizeof(char *), CmpStr);
+               qsort((void *) strings, i, sizeof(char *), CmpStr);
            }
            *stringsPtr = strings;
        } else {
@@ -792,7 +792,7 @@ AddMethodToCallChain(
                                 * looking to add things from a mixin and have
                                 * not passed a mixin. */
 {
-    register CallChain *callPtr = cbPtr->callChainPtr;
+    CallChain *callPtr = cbPtr->callChainPtr;
     int i;
 
     /*
@@ -1463,7 +1463,7 @@ AddSimpleClassChainToCallContext(
                (char *) methodNameObj);
 
        if (hPtr != NULL) {
-           register Method *mPtr = Tcl_GetHashValue(hPtr);
+           Method *mPtr = Tcl_GetHashValue(hPtr);
 
            if (!(flags & KNOWN_STATE)) {
                if (flags & PUBLIC_METHOD) {
index f02e1d3..aeee165 100644 (file)
@@ -610,7 +610,7 @@ FindCommand(
 {
     int length;
     const char *nameStr, *string = Tcl_GetStringFromObj(stringObj, &length);
-    register Namespace *const nsPtr = (Namespace *) namespacePtr;
+    Namespace *const nsPtr = (Namespace *) namespacePtr;
     FOREACH_HASH_DECLS;
     Tcl_Command cmd, cmd2;
 
@@ -2132,7 +2132,6 @@ ClassSuperSet(
            superclasses[i] = GetClassInOuterContext(interp, superv[i],
                    "only a class can be a superclass");
            if (superclasses[i] == NULL) {
-               i--;
                goto failedAfterAlloc;
            }
            for (j = 0; j < i; j++) {
@@ -2149,7 +2148,7 @@ ClassSuperSet(
                        "attempt to form circular dependency graph", -1));
                Tcl_SetErrorCode(interp, "TCL", "OO", "CIRCULARITY", NULL);
            failedAfterAlloc:
-               for (; i > 0; i--) {
+               for (; i-- > 0 ;) {
                    TclOODecrRefCount(superclasses[i]->thisPtr);
                }
                ckfree(superclasses);
index c9263b5..4b25c1a 100644 (file)
@@ -110,7 +110,7 @@ TclOOInitInfo(
     TclMakeEnsemble(interp, "::oo::InfoClass", infoClassCmds);
 
     /*
-     * Install into the master [info] ensemble.
+     * Install into the [info] ensemble.
      */
 
     infoCmd = Tcl_FindCommand(interp, "info", NULL, TCL_GLOBAL_ONLY);
index 0e4503a..44316ac 100644 (file)
@@ -277,7 +277,7 @@ typedef struct Class {
  */
 
 typedef struct ThreadLocalData {
-    int nsCount;               /* Master epoch counter is used for keeping
+    int nsCount;               /* Epoch counter is used for keeping
                                 * the values used in Tcl_Obj internal
                                 * representations sane. Must be thread-local
                                 * because Tcl_Objs can cross interpreter
@@ -289,7 +289,7 @@ typedef struct Foundation {
     Tcl_Interp *interp;
     Class *objectCls;          /* The root of the object system. */
     Class *classCls;           /* The class of all classes. */
-    Tcl_Namespace *ooNs;       /* Master ::oo namespace. */
+    Tcl_Namespace *ooNs;       /* ::oo namespace. */
     Tcl_Namespace *defineNs;   /* Namespace containing special commands for
                                 * manipulating objects and classes. The
                                 * "oo::define" command acts as a special kind
index 493c936..cd3c2c2 100644 (file)
@@ -149,8 +149,8 @@ Tcl_NewInstanceMethod(
     ClientData clientData)     /* Some data associated with the particular
                                 * method to be created. */
 {
-    register Object *oPtr = (Object *) object;
-    register Method *mPtr;
+    Object *oPtr = (Object *) object;
+    Method *mPtr;
     Tcl_HashEntry *hPtr;
     int isNew;
 
@@ -217,8 +217,8 @@ Tcl_NewMethod(
     ClientData clientData)     /* Some data associated with the particular
                                 * method to be created. */
 {
-    register Class *clsPtr = (Class *) cls;
-    register Method *mPtr;
+    Class *clsPtr = (Class *) cls;
+    Method *mPtr;
     Tcl_HashEntry *hPtr;
     int isNew;
 
@@ -336,7 +336,7 @@ TclOONewProcInstanceMethod(
                                 * interested. */
 {
     int argsLen;
-    register ProcedureMethod *pmPtr;
+    ProcedureMethod *pmPtr;
     Tcl_Method method;
 
     if (Tcl_ListObjLength(interp, argsObj, &argsLen) != TCL_OK) {
@@ -388,7 +388,7 @@ TclOONewProcMethod(
                                 * interested. */
 {
     int argsLen;               /* -1 => delete argsObj before exit */
-    register ProcedureMethod *pmPtr;
+    ProcedureMethod *pmPtr;
     const char *procName;
     Tcl_Method method;
 
@@ -790,7 +790,7 @@ PushMethodCallFrame(
                                 * frame. */
 {
     Namespace *nsPtr = (Namespace *) contextPtr->oPtr->namespacePtr;
-    register int result;
+    int result;
     const char *namePtr;
     CallFrame **framePtrPtr = &fdPtr->framePtr;
 
@@ -822,7 +822,7 @@ PushMethodCallFrame(
      */
 
     if (pmPtr->flags & USE_DECLARER_NS) {
-       register Method *mPtr =
+       Method *mPtr =
                contextPtr->callPtr->chain[contextPtr->index].mPtr;
 
        if (mPtr->declaringClassPtr != NULL) {
@@ -895,7 +895,7 @@ PushMethodCallFrame(
        fdPtr->efi.fields[1].proc = pmPtr->gfivProc;
        fdPtr->efi.fields[1].clientData = pmPtr;
     } else {
-       register Tcl_Method method =
+       Tcl_Method method =
                Tcl_ObjectContextMethod((Tcl_ObjectContext) contextPtr);
 
        if (Tcl_MethodDeclarerObject(method) != NULL) {
@@ -1271,7 +1271,7 @@ static void
 DeleteProcedureMethod(
     ClientData clientData)
 {
-    register ProcedureMethod *pmPtr = clientData;
+    ProcedureMethod *pmPtr = clientData;
 
     if (pmPtr->refCount-- <= 1) {
        DeleteProcedureMethodRecord(pmPtr);
@@ -1364,7 +1364,7 @@ TclOONewForwardInstanceMethod(
                                 * prefix to forward to. */
 {
     int prefixLen;
-    register ForwardMethod *fmPtr;
+    ForwardMethod *fmPtr;
 
     if (Tcl_ListObjLength(interp, prefixObj, &prefixLen) != TCL_OK) {
        return NULL;
@@ -1403,7 +1403,7 @@ TclOONewForwardMethod(
                                 * prefix to forward to. */
 {
     int prefixLen;
-    register ForwardMethod *fmPtr;
+    ForwardMethod *fmPtr;
 
     if (Tcl_ListObjLength(interp, prefixObj, &prefixLen) != TCL_OK) {
        return NULL;
index eca456f..2ec5eb8 100644 (file)
@@ -145,12 +145,12 @@ typedef struct PendingObjData {
 #define ObjDeletionUnlock(contextPtr)  ((contextPtr)->deletionCount--)
 #define ObjDeletePending(contextPtr)   ((contextPtr)->deletionCount > 0)
 #define ObjOnStack(contextPtr)         ((contextPtr)->deletionStack != NULL)
-#define PushObjToDelete(contextPtr,objPtr) \
+#define PushObjToDelete(contextPtr,objPtr)                              \
     /* The string rep is already invalidated so we can use the bytes value \
      * for our pointer chain: push onto the head of the stack. */       \
     (objPtr)->bytes = (char *) ((contextPtr)->deletionStack);           \
     (contextPtr)->deletionStack = (objPtr)
-#define PopObjToDelete(contextPtr,objPtrVar) \
+#define PopObjToDelete(contextPtr,objPtrVar)                            \
     (objPtrVar) = (contextPtr)->deletionStack;                          \
     (contextPtr)->deletionStack = (Tcl_Obj *) (objPtrVar)->bytes
 
@@ -161,14 +161,14 @@ typedef struct PendingObjData {
 static PendingObjData pendingObjData;
 #define ObjInitDeletionContext(contextPtr) \
     PendingObjData *const contextPtr = &pendingObjData
-#elif HAVE_FAST_TSD
+#elif defined(HAVE_FAST_TSD)
 static __thread PendingObjData pendingObjData;
 #define ObjInitDeletionContext(contextPtr) \
     PendingObjData *const contextPtr = &pendingObjData
 #else
 static Tcl_ThreadDataKey pendingObjDataKey;
 #define ObjInitDeletionContext(contextPtr) \
-    PendingObjData *const contextPtr =                                  \
+    PendingObjData *const contextPtr =     \
            Tcl_GetThreadData(&pendingObjDataKey, sizeof(PendingObjData))
 #endif
 
@@ -177,29 +177,29 @@ static Tcl_ThreadDataKey pendingObjDataKey;
  */
 
 #define PACK_BIGNUM(bignum, objPtr) \
-    if ((bignum).used > 0x7fff) {                                       \
-       mp_int *temp = (void *) ckalloc((unsigned) sizeof(mp_int));     \
+    if ((bignum).used > 0x7FFF) {                                   \
+       mp_int *temp = (mp_int *)ckalloc(sizeof(mp_int));               \
        *temp = bignum;                                                 \
-       (objPtr)->internalRep.twoPtrValue.ptr1 = temp;                 \
-       (objPtr)->internalRep.twoPtrValue.ptr2 = INT2PTR(-1); \
-    } else {                                                            \
-       if ((bignum).alloc > 0x7fff) {                                  \
+       (objPtr)->internalRep.twoPtrValue.ptr1 = temp;                  \
+       (objPtr)->internalRep.twoPtrValue.ptr2 = INT2PTR(-1);           \
+    } else {                                                        \
+       if ((bignum).alloc > 0x7FFF) {                                  \
            mp_shrink(&(bignum));                                       \
        }                                                               \
-       (objPtr)->internalRep.twoPtrValue.ptr1 = (void *) (bignum).dp; \
-       (objPtr)->internalRep.twoPtrValue.ptr2 = INT2PTR( ((bignum).sign << 30) \
-               | ((bignum).alloc << 15) | ((bignum).used));            \
+       (objPtr)->internalRep.twoPtrValue.ptr1 = (void *)(bignum).dp;   \
+       (objPtr)->internalRep.twoPtrValue.ptr2 = INT2PTR(((bignum).sign << 30) \
+               | ((bignum).alloc << 15) | ((bignum).used));                \
     }
 
 #define UNPACK_BIGNUM(objPtr, bignum) \
-    if ((objPtr)->internalRep.twoPtrValue.ptr2 == INT2PTR(-1)) { \
-       (bignum) = *((mp_int *) ((objPtr)->internalRep.twoPtrValue.ptr1)); \
+    if ((objPtr)->internalRep.twoPtrValue.ptr2 == INT2PTR(-1)) {        \
+       (bignum) = *((mp_int *) ((objPtr)->internalRep.twoPtrValue.ptr1));  \
     } else {                                                            \
-       (bignum).dp = (objPtr)->internalRep.twoPtrValue.ptr1;          \
+       (bignum).dp = (objPtr)->internalRep.twoPtrValue.ptr1;               \
        (bignum).sign = PTR2INT((objPtr)->internalRep.twoPtrValue.ptr2) >> 30; \
-       (bignum).alloc =                                                \
-               (PTR2INT((objPtr)->internalRep.twoPtrValue.ptr2) >> 15) & 0x7fff; \
-       (bignum).used = PTR2INT((objPtr)->internalRep.twoPtrValue.ptr2) & 0x7fff; \
+       (bignum).alloc =                                                    \
+               (PTR2INT((objPtr)->internalRep.twoPtrValue.ptr2) >> 15) & 0x7FFF; \
+       (bignum).used = PTR2INT((objPtr)->internalRep.twoPtrValue.ptr2) & 0x7FFF; \
     }
 
 /*
@@ -541,7 +541,7 @@ TclGetContLineTable(void)
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
     if (!tsdPtr->lineCLPtr) {
-       tsdPtr->lineCLPtr = ckalloc(sizeof(Tcl_HashTable));
+       tsdPtr->lineCLPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
        Tcl_InitHashTable(tsdPtr->lineCLPtr, TCL_ONE_WORD_KEYS);
        Tcl_CreateThreadExitHandler(TclThreadFinalizeContLines,NULL);
     }
@@ -576,7 +576,7 @@ TclContinuationsEnter(
     ThreadSpecificData *tsdPtr = TclGetContLineTable();
     Tcl_HashEntry *hPtr =
            Tcl_CreateHashEntry(tsdPtr->lineCLPtr, objPtr, &newEntry);
-    ContLineLoc *clLocPtr = ckalloc(sizeof(ContLineLoc) + num*sizeof(int));
+    ContLineLoc *clLocPtr = (ContLineLoc *)ckalloc(TclOffset(ContLineLoc, loc) + (num + 1) *sizeof(int));
 
     if (!newEntry) {
        /*
@@ -876,7 +876,7 @@ Tcl_AppendAllObjTypes(
                                 * name of each registered type is appended as
                                 * a list element. */
 {
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     Tcl_HashSearch search;
     int numElems;
 
@@ -924,7 +924,7 @@ const Tcl_ObjType *
 Tcl_GetObjType(
     const char *typeName)      /* Name of Tcl object type to look up. */
 {
-    register Tcl_HashEntry *hPtr;
+    Tcl_HashEntry *hPtr;
     const Tcl_ObjType *typePtr = NULL;
 
     Tcl_MutexLock(&tableMutex);
@@ -1054,10 +1054,10 @@ TclDbDumpActiveObjects(
 #ifdef TCL_MEM_DEBUG
 void
 TclDbInitNewObj(
-    register Tcl_Obj *objPtr,
-    register const char *file, /* The name of the source file calling this
+    Tcl_Obj *objPtr,
+    const char *file,  /* The name of the source file calling this
                                 * function; used for debugging. */
-    register int line)         /* Line number in the source file; used for
+    int line)          /* Line number in the source file; used for
                                 * debugging. */
 {
     objPtr->refCount = 0;
@@ -1079,7 +1079,7 @@ TclDbInitNewObj(
        ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
        if (tsdPtr->objThreadMap == NULL) {
-           tsdPtr->objThreadMap = ckalloc(sizeof(Tcl_HashTable));
+           tsdPtr->objThreadMap = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
            Tcl_InitHashTable(tsdPtr->objThreadMap, TCL_ONE_WORD_KEYS);
        }
        tablePtr = tsdPtr->objThreadMap;
@@ -1092,7 +1092,7 @@ TclDbInitNewObj(
         * Record the debugging information.
         */
 
-       objData = ckalloc(sizeof(ObjData));
+       objData = (ObjData *)ckalloc(sizeof(ObjData));
        objData->objPtr = objPtr;
        objData->file = file;
        objData->line = line;
@@ -1142,7 +1142,7 @@ Tcl_NewObj(void)
 Tcl_Obj *
 Tcl_NewObj(void)
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     /*
      * Use the macro defined in tclInt.h - it will use the correct allocator.
@@ -1184,12 +1184,12 @@ Tcl_NewObj(void)
 
 Tcl_Obj *
 Tcl_DbNewObj(
-    register const char *file, /* The name of the source file calling this
+    const char *file,  /* The name of the source file calling this
                                 * function; used for debugging. */
-    register int line)         /* Line number in the source file; used for
+    int line)          /* Line number in the source file; used for
                                 * debugging. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     /*
      * Use the macro defined in tclInt.h - it will use the correct allocator.
@@ -1239,8 +1239,8 @@ TclAllocateFreeObjects(void)
 {
     size_t bytesToAlloc = (OBJS_TO_ALLOC_EACH_TIME * sizeof(Tcl_Obj));
     char *basePtr;
-    register Tcl_Obj *prevPtr, *objPtr;
-    register int i;
+    Tcl_Obj *prevPtr, *objPtr;
+    int i;
 
     /*
      * This has been noted by Purify to be a potential leak. The problem is
@@ -1251,7 +1251,7 @@ TclAllocateFreeObjects(void)
      * Purify apparently can't figure that out, and fires a false alarm.
      */
 
-    basePtr = ckalloc(bytesToAlloc);
+    basePtr = (char *)ckalloc(bytesToAlloc);
 
     prevPtr = NULL;
     objPtr = (Tcl_Obj *) basePtr;
@@ -1291,9 +1291,9 @@ TclAllocateFreeObjects(void)
 #ifdef TCL_MEM_DEBUG
 void
 TclFreeObj(
-    register Tcl_Obj *objPtr)  /* The object to be freed. */
+    Tcl_Obj *objPtr)   /* The object to be freed. */
 {
-    register const Tcl_ObjType *typePtr = objPtr->typePtr;
+    const Tcl_ObjType *typePtr = objPtr->typePtr;
 
     /*
      * This macro declares a variable, so must come here...
@@ -1416,7 +1416,7 @@ TclFreeObj(
 
 void
 TclFreeObj(
-    register Tcl_Obj *objPtr)  /* The object to be freed. */
+    Tcl_Obj *objPtr)   /* The object to be freed. */
 {
     /*
      * Invalidate the string rep first so we can use the bytes value for our
@@ -1625,7 +1625,7 @@ TclSetDuplicateObj(
 
 char *
 Tcl_GetString(
-    register Tcl_Obj *objPtr)  /* Object whose string rep byte pointer should
+    Tcl_Obj *objPtr)   /* Object whose string rep byte pointer should
                                 * be returned. */
 {
     if (objPtr->bytes != NULL) {
@@ -1683,9 +1683,9 @@ Tcl_GetString(
 
 char *
 Tcl_GetStringFromObj(
-    register Tcl_Obj *objPtr,  /* Object whose string rep byte pointer should
+    Tcl_Obj *objPtr,   /* Object whose string rep byte pointer should
                                 * be returned. */
-    register int *lengthPtr)   /* If non-NULL, the location where the string
+    int *lengthPtr)    /* If non-NULL, the location where the string
                                 * rep's byte array length should * be stored.
                                 * If NULL, no length is stored. */
 {
@@ -1717,7 +1717,7 @@ Tcl_GetStringFromObj(
 
 void
 Tcl_InvalidateStringRep(
-    register Tcl_Obj *objPtr)  /* Object whose string rep byte pointer should
+    Tcl_Obj *objPtr)   /* Object whose string rep byte pointer should
                                 * be freed. */
 {
     TclInvalidateStringRep(objPtr);
@@ -1751,7 +1751,7 @@ Tcl_InvalidateStringRep(
 
 Tcl_Obj *
 Tcl_NewBooleanObj(
-    register int boolValue)    /* Boolean used to initialize new object. */
+    int boolValue)     /* Boolean used to initialize new object. */
 {
     return Tcl_DbNewBooleanObj(boolValue, "unknown", 0);
 }
@@ -1760,9 +1760,9 @@ Tcl_NewBooleanObj(
 
 Tcl_Obj *
 Tcl_NewBooleanObj(
-    register int boolValue)    /* Boolean used to initialize new object. */
+    int boolValue)     /* Boolean used to initialize new object. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclNewBooleanObj(objPtr, boolValue);
     return objPtr;
@@ -1800,13 +1800,13 @@ Tcl_NewBooleanObj(
 
 Tcl_Obj *
 Tcl_DbNewBooleanObj(
-    register int boolValue,    /* Boolean used to initialize new object. */
+    int boolValue,     /* Boolean used to initialize new object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
                                 * debugging. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclDbNewObj(objPtr, file, line);
     objPtr->bytes = NULL;
@@ -1820,7 +1820,7 @@ Tcl_DbNewBooleanObj(
 
 Tcl_Obj *
 Tcl_DbNewBooleanObj(
-    register int boolValue,    /* Boolean used to initialize new object. */
+    int boolValue,     /* Boolean used to initialize new object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
@@ -1851,8 +1851,8 @@ Tcl_DbNewBooleanObj(
 #undef Tcl_SetBooleanObj
 void
 Tcl_SetBooleanObj(
-    register Tcl_Obj *objPtr,  /* Object whose internal rep to init. */
-    register int boolValue)    /* Boolean used to set object's value. */
+    Tcl_Obj *objPtr,   /* Object whose internal rep to init. */
+    int boolValue)     /* Boolean used to set object's value. */
 {
     if (Tcl_IsShared(objPtr)) {
        Tcl_Panic("%s called with shared object", "Tcl_SetBooleanObj");
@@ -1883,8 +1883,8 @@ Tcl_SetBooleanObj(
 int
 Tcl_GetBooleanFromObj(
     Tcl_Interp *interp,         /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr,  /* The object from which to get boolean. */
-    register int *boolPtr)     /* Place to store resulting boolean. */
+    Tcl_Obj *objPtr,   /* The object from which to get boolean. */
+    int *boolPtr)      /* Place to store resulting boolean. */
 {
     do {
        if (objPtr->typePtr == &tclIntType) {
@@ -1950,7 +1950,7 @@ Tcl_GetBooleanFromObj(
 int
 TclSetBooleanFromAny(
     Tcl_Interp *interp,                /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
+    Tcl_Obj *objPtr)   /* The object to convert. */
 {
     /*
      * For some "pure" numeric Tcl_ObjTypes (no string rep), we can determine
@@ -2003,7 +2003,7 @@ TclSetBooleanFromAny(
 \f
 static int
 ParseBoolean(
-    register Tcl_Obj *objPtr)  /* The object to parse/convert. */
+    Tcl_Obj *objPtr)   /* The object to parse/convert. */
 {
     int i, length, newBool;
     char lowerCase[6];
@@ -2059,25 +2059,25 @@ ParseBoolean(
        /*
         * Checking the 'y' is redundant, but makes the code clearer.
         */
-       if (strncmp(lowerCase, "yes", (size_t) length) == 0) {
+       if (strncmp(lowerCase, "yes", length) == 0) {
            newBool = 1;
            goto goodBoolean;
        }
        return TCL_ERROR;
     case 'n':
-       if (strncmp(lowerCase, "no", (size_t) length) == 0) {
+       if (strncmp(lowerCase, "no", length) == 0) {
            newBool = 0;
            goto goodBoolean;
        }
        return TCL_ERROR;
     case 't':
-       if (strncmp(lowerCase, "true", (size_t) length) == 0) {
+       if (strncmp(lowerCase, "true", length) == 0) {
            newBool = 1;
            goto goodBoolean;
        }
        return TCL_ERROR;
     case 'f':
-       if (strncmp(lowerCase, "false", (size_t) length) == 0) {
+       if (strncmp(lowerCase, "false", length) == 0) {
            newBool = 0;
            goto goodBoolean;
        }
@@ -2086,10 +2086,10 @@ ParseBoolean(
        if (length < 2) {
            return TCL_ERROR;
        }
-       if (strncmp(lowerCase, "on", (size_t) length) == 0) {
+       if (strncmp(lowerCase, "on", length) == 0) {
            newBool = 1;
            goto goodBoolean;
-       } else if (strncmp(lowerCase, "off", (size_t) length) == 0) {
+       } else if (strncmp(lowerCase, "off", length) == 0) {
            newBool = 0;
            goto goodBoolean;
        }
@@ -2144,7 +2144,7 @@ ParseBoolean(
 
 Tcl_Obj *
 Tcl_NewDoubleObj(
-    register double dblValue)  /* Double used to initialize the object. */
+    double dblValue)   /* Double used to initialize the object. */
 {
     return Tcl_DbNewDoubleObj(dblValue, "unknown", 0);
 }
@@ -2153,9 +2153,9 @@ Tcl_NewDoubleObj(
 
 Tcl_Obj *
 Tcl_NewDoubleObj(
-    register double dblValue)  /* Double used to initialize the object. */
+    double dblValue)   /* Double used to initialize the object. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclNewDoubleObj(objPtr, dblValue);
     return objPtr;
@@ -2192,13 +2192,13 @@ Tcl_NewDoubleObj(
 
 Tcl_Obj *
 Tcl_DbNewDoubleObj(
-    register double dblValue,  /* Double used to initialize the object. */
+    double dblValue,   /* Double used to initialize the object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
                                 * debugging. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclDbNewObj(objPtr, file, line);
     objPtr->bytes = NULL;
@@ -2212,7 +2212,7 @@ Tcl_DbNewDoubleObj(
 
 Tcl_Obj *
 Tcl_DbNewDoubleObj(
-    register double dblValue,  /* Double used to initialize the object. */
+    double dblValue,   /* Double used to initialize the object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
@@ -2242,8 +2242,8 @@ Tcl_DbNewDoubleObj(
 
 void
 Tcl_SetDoubleObj(
-    register Tcl_Obj *objPtr,  /* Object whose internal rep to init. */
-    register double dblValue)  /* Double used to set the object's value. */
+    Tcl_Obj *objPtr,   /* Object whose internal rep to init. */
+    double dblValue)   /* Double used to set the object's value. */
 {
     if (Tcl_IsShared(objPtr)) {
        Tcl_Panic("%s called with shared object", "Tcl_SetDoubleObj");
@@ -2275,8 +2275,8 @@ Tcl_SetDoubleObj(
 int
 Tcl_GetDoubleFromObj(
     Tcl_Interp *interp,         /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr,  /* The object from which to get a double. */
-    register double *dblPtr)   /* Place to store resulting double. */
+    Tcl_Obj *objPtr,   /* The object from which to get a double. */
+    double *dblPtr)    /* Place to store resulting double. */
 {
     do {
        if (objPtr->typePtr == &tclDoubleType) {
@@ -2336,7 +2336,7 @@ Tcl_GetDoubleFromObj(
 static int
 SetDoubleFromAny(
     Tcl_Interp *interp,                /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
+    Tcl_Obj *objPtr)   /* The object to convert. */
 {
     return TclParseNumber(interp, objPtr, "floating-point number", NULL, -1,
            NULL, 0);
@@ -2365,16 +2365,16 @@ SetDoubleFromAny(
 
 static void
 UpdateStringOfDouble(
-    register Tcl_Obj *objPtr)  /* Double obj with string rep to update. */
+    Tcl_Obj *objPtr)   /* Double obj with string rep to update. */
 {
     char buffer[TCL_DOUBLE_SPACE];
-    register int len;
+    int len;
 
     Tcl_PrintDouble(NULL, objPtr->internalRep.doubleValue, buffer);
     len = strlen(buffer);
 
-    objPtr->bytes = ckalloc(len + 1);
-    memcpy(objPtr->bytes, buffer, (unsigned) len + 1);
+    objPtr->bytes = (char *)ckalloc(len + 1);
+    memcpy(objPtr->bytes, buffer, len + 1);
     objPtr->length = len;
 }
 \f
@@ -2413,7 +2413,7 @@ UpdateStringOfDouble(
 
 Tcl_Obj *
 Tcl_NewIntObj(
-    register int intValue)     /* Int used to initialize the new object. */
+    int intValue)      /* Int used to initialize the new object. */
 {
     return Tcl_DbNewLongObj((long)intValue, "unknown", 0);
 }
@@ -2422,9 +2422,9 @@ Tcl_NewIntObj(
 
 Tcl_Obj *
 Tcl_NewIntObj(
-    register int intValue)     /* Int used to initialize the new object. */
+    int intValue)      /* Int used to initialize the new object. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclNewIntObj(objPtr, intValue);
     return objPtr;
@@ -2452,8 +2452,8 @@ Tcl_NewIntObj(
 #undef Tcl_SetIntObj
 void
 Tcl_SetIntObj(
-    register Tcl_Obj *objPtr,  /* Object whose internal rep to init. */
-    register int intValue)     /* Integer used to set object's value. */
+    Tcl_Obj *objPtr,   /* Object whose internal rep to init. */
+    int intValue)      /* Integer used to set object's value. */
 {
     if (Tcl_IsShared(objPtr)) {
        Tcl_Panic("%s called with shared object", "Tcl_SetIntObj");
@@ -2494,8 +2494,8 @@ Tcl_SetIntObj(
 int
 Tcl_GetIntFromObj(
     Tcl_Interp *interp,         /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr,  /* The object from which to get a int. */
-    register int *intPtr)      /* Place to store resulting int. */
+    Tcl_Obj *objPtr,   /* The object from which to get a int. */
+    int *intPtr)       /* Place to store resulting int. */
 {
 #if (LONG_MAX == INT_MAX)
     return TclGetLongFromObj(interp, objPtr, (long *) intPtr);
@@ -2566,15 +2566,15 @@ SetIntFromAny(
 
 static void
 UpdateStringOfInt(
-    register Tcl_Obj *objPtr)  /* Int object whose string rep to update. */
+    Tcl_Obj *objPtr)   /* Int object whose string rep to update. */
 {
     char buffer[TCL_INTEGER_SPACE];
-    register int len;
+    int len;
 
     len = TclFormatInt(buffer, objPtr->internalRep.longValue);
 
-    objPtr->bytes = ckalloc(len + 1);
-    memcpy(objPtr->bytes, buffer, (unsigned) len + 1);
+    objPtr->bytes = (char *)ckalloc(len + 1);
+    memcpy(objPtr->bytes, buffer, len + 1);
     objPtr->length = len;
 }
 \f
@@ -2613,7 +2613,7 @@ UpdateStringOfInt(
 
 Tcl_Obj *
 Tcl_NewLongObj(
-    register long longValue)   /* Long integer used to initialize the
+    long longValue)    /* Long integer used to initialize the
                                 * new object. */
 {
     return Tcl_DbNewLongObj(longValue, "unknown", 0);
@@ -2623,10 +2623,10 @@ Tcl_NewLongObj(
 
 Tcl_Obj *
 Tcl_NewLongObj(
-    register long longValue)   /* Long integer used to initialize the
+    long longValue)    /* Long integer used to initialize the
                                 * new object. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclNewLongObj(objPtr, longValue);
     return objPtr;
@@ -2669,14 +2669,14 @@ Tcl_NewLongObj(
 
 Tcl_Obj *
 Tcl_DbNewLongObj(
-    register long longValue,   /* Long integer used to initialize the new
+    long longValue,    /* Long integer used to initialize the new
                                 * object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
                                 * debugging. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclDbNewObj(objPtr, file, line);
     objPtr->bytes = NULL;
@@ -2690,7 +2690,7 @@ Tcl_DbNewLongObj(
 
 Tcl_Obj *
 Tcl_DbNewLongObj(
-    register long longValue,   /* Long integer used to initialize the new
+    long longValue,    /* Long integer used to initialize the new
                                 * object. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
@@ -2721,8 +2721,8 @@ Tcl_DbNewLongObj(
 
 void
 Tcl_SetLongObj(
-    register Tcl_Obj *objPtr,  /* Object whose internal rep to init. */
-    register long longValue)   /* Long integer used to initialize the
+    Tcl_Obj *objPtr,   /* Object whose internal rep to init. */
+    long longValue)    /* Long integer used to initialize the
                                 * object's value. */
 {
     if (Tcl_IsShared(objPtr)) {
@@ -2756,8 +2756,8 @@ Tcl_SetLongObj(
 int
 Tcl_GetLongFromObj(
     Tcl_Interp *interp,         /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr,  /* The object from which to get a long. */
-    register long *longPtr)    /* Place to store resulting long. */
+    Tcl_Obj *objPtr,   /* The object from which to get a long. */
+    long *longPtr)     /* Place to store resulting long. */
 {
     do {
        if (objPtr->typePtr == &tclIntType) {
@@ -2862,11 +2862,11 @@ Tcl_GetLongFromObj(
 
 static void
 UpdateStringOfWideInt(
-    register Tcl_Obj *objPtr)  /* Int object whose string rep to update. */
+    Tcl_Obj *objPtr)   /* Int object whose string rep to update. */
 {
     char buffer[TCL_INTEGER_SPACE+2];
-    register unsigned len;
-    register Tcl_WideInt wideVal = objPtr->internalRep.wideValue;
+    unsigned len;
+    Tcl_WideInt wideVal = objPtr->internalRep.wideValue;
 
     /*
      * Note that sprintf will generate a compiler warning under Mingw claiming
@@ -2877,7 +2877,7 @@ UpdateStringOfWideInt(
 
     sprintf(buffer, "%" TCL_LL_MODIFIER "d", wideVal);
     len = strlen(buffer);
-    objPtr->bytes = ckalloc(len + 1);
+    objPtr->bytes = (char *)ckalloc(len + 1);
     memcpy(objPtr->bytes, buffer, len + 1);
     objPtr->length = len;
 }
@@ -2913,7 +2913,7 @@ UpdateStringOfWideInt(
 
 Tcl_Obj *
 Tcl_NewWideIntObj(
-    register Tcl_WideInt wideValue)
+    Tcl_WideInt wideValue)
                                /* Wide integer used to initialize the new
                                 * object. */
 {
@@ -2924,11 +2924,11 @@ Tcl_NewWideIntObj(
 
 Tcl_Obj *
 Tcl_NewWideIntObj(
-    register Tcl_WideInt wideValue)
+    Tcl_WideInt wideValue)
                                /* Wide integer used to initialize the new
                                 * object. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclNewObj(objPtr);
     Tcl_SetWideIntObj(objPtr, wideValue);
@@ -2972,7 +2972,7 @@ Tcl_NewWideIntObj(
 
 Tcl_Obj *
 Tcl_DbNewWideIntObj(
-    register Tcl_WideInt wideValue,
+    Tcl_WideInt wideValue,
                                /* Wide integer used to initialize the new
                                 * object. */
     const char *file,          /* The name of the source file calling this
@@ -2980,7 +2980,7 @@ Tcl_DbNewWideIntObj(
     int line)                  /* Line number in the source file; used for
                                 * debugging. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclDbNewObj(objPtr, file, line);
     Tcl_SetWideIntObj(objPtr, wideValue);
@@ -2991,7 +2991,7 @@ Tcl_DbNewWideIntObj(
 
 Tcl_Obj *
 Tcl_DbNewWideIntObj(
-    register Tcl_WideInt wideValue,
+    Tcl_WideInt wideValue,
                                /* Long integer used to initialize the new
                                 * object. */
     const char *file,          /* The name of the source file calling this
@@ -3023,8 +3023,8 @@ Tcl_DbNewWideIntObj(
 
 void
 Tcl_SetWideIntObj(
-    register Tcl_Obj *objPtr,  /* Object w. internal rep to init. */
-    register Tcl_WideInt wideValue)
+    Tcl_Obj *objPtr,   /* Object w. internal rep to init. */
+    Tcl_WideInt wideValue)
                                /* Wide integer used to initialize the
                                 * object's value. */
 {
@@ -3071,8 +3071,8 @@ Tcl_SetWideIntObj(
 int
 Tcl_GetWideIntFromObj(
     Tcl_Interp *interp,         /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr,  /* Object from which to get a wide int. */
-    register Tcl_WideInt *wideIntPtr)
+    Tcl_Obj *objPtr,   /* Object from which to get a wide int. */
+    Tcl_WideInt *wideIntPtr)
                                /* Place to store resulting long. */
 {
     do {
@@ -3269,7 +3269,7 @@ UpdateStringOfBignum(
 
        Tcl_Panic("UpdateStringOfBignum: string length limit exceeded");
     }
-    stringVal = ckalloc(size);
+    stringVal = (char *)ckalloc(size);
     status = mp_to_radix(&bignumVal, stringVal, size, NULL, 10);
     if (status != MP_OKAY) {
        Tcl_Panic("conversion failure in UpdateStringOfBignum");
@@ -3392,7 +3392,14 @@ GetBignumFromObj(
                mp_int temp;
 
                UNPACK_BIGNUM(objPtr, temp);
-               mp_init_copy(bignumValue, &temp);
+               if (mp_init_copy(bignumValue, &temp) != MP_OKAY) {
+                   if (interp != NULL) {
+                       Tcl_SetObjResult(interp, Tcl_NewStringObj(
+                               "insufficient memory to unpack bignum", -1));
+                       Tcl_SetErrorCode(interp, "TCL", "MEMORY", NULL);
+                   }
+                   return TCL_ERROR;
+               }
            } else {
                UNPACK_BIGNUM(objPtr, *bignumValue);
                objPtr->internalRep.twoPtrValue.ptr1 = NULL;
@@ -3705,7 +3712,7 @@ TclGetNumberFromObj(
 
 void
 Tcl_DbIncrRefCount(
-    register Tcl_Obj *objPtr,  /* The object we are registering a reference
+    Tcl_Obj *objPtr,   /* The object we are registering a reference
                                 * to. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
@@ -3768,7 +3775,7 @@ Tcl_DbIncrRefCount(
 
 void
 Tcl_DbDecrRefCount(
-    register Tcl_Obj *objPtr,  /* The object we are releasing a reference
+    Tcl_Obj *objPtr,   /* The object we are releasing a reference
                                 * to. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
@@ -3834,7 +3841,7 @@ Tcl_DbDecrRefCount(
 
 int
 Tcl_DbIsShared(
-    register Tcl_Obj *objPtr,  /* The object to test for being shared. */
+    Tcl_Obj *objPtr,   /* The object to test for being shared. */
     const char *file,          /* The name of the source file calling this
                                 * function; used for debugging. */
     int line)                  /* Line number in the source file; used for
@@ -3906,7 +3913,7 @@ Tcl_DbIsShared(
 
 void
 Tcl_InitObjHashTable(
-    register Tcl_HashTable *tablePtr)
+    Tcl_HashTable *tablePtr)
                                /* Pointer to table record, which is supplied
                                 * by the caller. */
 {
@@ -3935,8 +3942,8 @@ AllocObjEntry(
     Tcl_HashTable *tablePtr,   /* Hash table. */
     void *keyPtr)              /* Key to store in the hash table entry. */
 {
-    Tcl_Obj *objPtr = keyPtr;
-    Tcl_HashEntry *hPtr = ckalloc(sizeof(Tcl_HashEntry));
+    Tcl_Obj *objPtr = (Tcl_Obj *)keyPtr;
+    Tcl_HashEntry *hPtr = (Tcl_HashEntry *)ckalloc(sizeof(Tcl_HashEntry));
 
     hPtr->key.objPtr = objPtr;
     Tcl_IncrRefCount(objPtr);
@@ -3969,8 +3976,8 @@ TclCompareObjKeys(
 {
     Tcl_Obj *objPtr1 = keyPtr;
     Tcl_Obj *objPtr2 = (Tcl_Obj *) hPtr->key.oneWordValue;
-    register const char *p1, *p2;
-    register size_t l1, l2;
+    const char *p1, *p2;
+    size_t l1, l2;
 
     /*
      * If the object pointers are the same then they match.
@@ -4127,13 +4134,13 @@ Tcl_Command
 Tcl_GetCommandFromObj(
     Tcl_Interp *interp,                /* The interpreter in which to resolve the
                                 * command and to report errors. */
-    register Tcl_Obj *objPtr)  /* The object containing the command's name.
+    Tcl_Obj *objPtr)   /* The object containing the command's name.
                                 * If the name starts with "::", will be
                                 * looked up in global namespace. Else, looked
                                 * up first in the current namespace, then in
                                 * global namespace. */
 {
-    register ResolvedCmdName *resPtr;
+    ResolvedCmdName *resPtr;
 
     /*
      * Get the internal representation, converting to a command type if
@@ -4156,13 +4163,13 @@ Tcl_GetCommandFromObj(
 
     resPtr = objPtr->internalRep.twoPtrValue.ptr1;
     if ((objPtr->typePtr == &tclCmdNameType) && (resPtr != NULL)) {
-        register Command *cmdPtr = resPtr->cmdPtr;
+        Command *cmdPtr = resPtr->cmdPtr;
 
         if ((cmdPtr->cmdEpoch == resPtr->cmdEpoch)
                 && !(cmdPtr->flags & CMD_IS_DELETED)
                 && (interp == cmdPtr->nsPtr->interp)
                 && !(cmdPtr->nsPtr->flags & NS_DYING)) {
-            register Namespace *refNsPtr = (Namespace *)
+            Namespace *refNsPtr = (Namespace *)
                     TclGetCurrentNamespace(interp);
 
             if ((resPtr->refNsPtr == NULL)
@@ -4211,14 +4218,14 @@ void
 TclSetCmdNameObj(
     Tcl_Interp *interp,                /* Points to interpreter containing command
                                 * that should be cached in objPtr. */
-    register Tcl_Obj *objPtr,  /* Points to Tcl object to be changed to a
+    Tcl_Obj *objPtr,   /* Points to Tcl object to be changed to a
                                 * CmdName object. */
     Command *cmdPtr)           /* Points to Command structure that the
                                 * CmdName object should refer to. */
 {
     Interp *iPtr = (Interp *) interp;
-    register ResolvedCmdName *resPtr;
-    register Namespace *currNsPtr;
+    ResolvedCmdName *resPtr;
+    Namespace *currNsPtr;
     const char *name;
 
     if (objPtr->typePtr == &tclCmdNameType) {
@@ -4229,7 +4236,7 @@ TclSetCmdNameObj(
     }
 
     cmdPtr->refCount++;
-    resPtr = ckalloc(sizeof(ResolvedCmdName));
+    resPtr = (ResolvedCmdName *)ckalloc(sizeof(ResolvedCmdName));
     resPtr->cmdPtr = cmdPtr;
     resPtr->cmdEpoch = cmdPtr->cmdEpoch;
     resPtr->refCount = 1;
@@ -4283,10 +4290,10 @@ TclSetCmdNameObj(
 
 static void
 FreeCmdNameInternalRep(
-    register Tcl_Obj *objPtr)  /* CmdName object with internal
+    Tcl_Obj *objPtr)   /* CmdName object with internal
                                 * representation to free. */
 {
-    register ResolvedCmdName *resPtr = objPtr->internalRep.twoPtrValue.ptr1;
+    ResolvedCmdName *resPtr = objPtr->internalRep.twoPtrValue.ptr1;
 
     if (resPtr != NULL) {
        /*
@@ -4333,9 +4340,9 @@ FreeCmdNameInternalRep(
 static void
 DupCmdNameInternalRep(
     Tcl_Obj *srcPtr,           /* Object with internal rep to copy. */
-    register Tcl_Obj *copyPtr) /* Object with internal rep to set. */
+    Tcl_Obj *copyPtr)  /* Object with internal rep to set. */
 {
-    register ResolvedCmdName *resPtr = srcPtr->internalRep.twoPtrValue.ptr1;
+    ResolvedCmdName *resPtr = srcPtr->internalRep.twoPtrValue.ptr1;
 
     copyPtr->internalRep.twoPtrValue.ptr1 = resPtr;
     copyPtr->internalRep.twoPtrValue.ptr2 = NULL;
@@ -4369,13 +4376,13 @@ DupCmdNameInternalRep(
 static int
 SetCmdNameFromAny(
     Tcl_Interp *interp,                /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
+    Tcl_Obj *objPtr)   /* The object to convert. */
 {
     Interp *iPtr = (Interp *) interp;
     const char *name;
-    register Command *cmdPtr;
+    Command *cmdPtr;
     Namespace *currNsPtr;
-    register ResolvedCmdName *resPtr;
+    ResolvedCmdName *resPtr;
 
     if (interp == NULL) {
        return TCL_ERROR;
@@ -4415,7 +4422,7 @@ SetCmdNameFromAny(
            }
        } else {
            TclFreeIntRep(objPtr);
-           resPtr = ckalloc(sizeof(ResolvedCmdName));
+           resPtr = (ResolvedCmdName *)ckalloc(sizeof(ResolvedCmdName));
            resPtr->refCount = 1;
            objPtr->internalRep.twoPtrValue.ptr1 = resPtr;
            objPtr->internalRep.twoPtrValue.ptr2 = NULL;
index 827d89d..03daa40 100644 (file)
@@ -34,7 +34,7 @@ static void           TrimUnreachable(CompileEnv *envPtr);
 #define AddrLength(address) \
     (tclInstructionTable[*(unsigned char *)(address)].numBytes)
 #define InstLength(instruction) \
-    (tclInstructionTable[(unsigned char)(instruction)].numBytes)
+    (tclInstructionTable[UCHAR(instruction)].numBytes)
 \f
 /*
  * ----------------------------------------------------------------------
index 1532c05..5bbaf93 100644 (file)
@@ -167,6 +167,8 @@ static int          ParseTokens(const char *src, int numBytes, int mask,
                            int flags, Tcl_Parse *parsePtr);
 static int             ParseWhiteSpace(const char *src, int numBytes,
                            int *incompletePtr, char *typePtr);
+static int             ParseHex(const char *src, int numBytes,
+                           int *resultPtr);
 \f
 /*
  *----------------------------------------------------------------------
@@ -234,19 +236,19 @@ Tcl_ParseCommand(
                                 * NULL, then no error message is provided. */
     const char *start,         /* First character of string containing one or
                                 * more Tcl commands. */
-    register int numBytes,     /* Total number of bytes in string. If < 0,
+    int numBytes,      /* Total number of bytes in string. If < 0,
                                 * the script consists of all bytes up to the
                                 * first null character. */
     int nested,                        /* Non-zero means this is a nested command:
                                 * close bracket should be considered a
                                 * command terminator. If zero, then close
                                 * bracket has no special meaning. */
-    register Tcl_Parse *parsePtr)
+    Tcl_Parse *parsePtr)
                                /* Structure to fill in with information about
                                 * the parsed command; any previous
                                 * information in the structure is ignored. */
 {
-    register const char *src;  /* Points to current character in the
+    const char *src;   /* Points to current character in the
                                 * command. */
     char type;                 /* Result returned by CHAR_TYPE(*src). */
     Tcl_Token *tokenPtr;       /* Pointer to token being filled in. */
@@ -257,6 +259,10 @@ Tcl_ParseCommand(
                                 * point to char after terminating one. */
     int scanned;
 
+    if (numBytes < 0 && start) {
+       numBytes = strlen(start);
+    }
+    TclParseInit(interp, start, numBytes, parsePtr);
     if ((start == NULL) && (numBytes != 0)) {
        if (interp != NULL) {
            Tcl_SetObjResult(interp, Tcl_NewStringObj(
@@ -264,10 +270,6 @@ Tcl_ParseCommand(
        }
        return TCL_ERROR;
     }
-    if (numBytes < 0) {
-       numBytes = strlen(start);
-    }
-    TclParseInit(interp, start, numBytes, parsePtr);
     parsePtr->commentStart = NULL;
     parsePtr->commentSize = 0;
     parsePtr->commandStart = NULL;
@@ -682,14 +684,14 @@ TclIsBareword(
 static int
 ParseWhiteSpace(
     const char *src,           /* First character to parse. */
-    register int numBytes,     /* Max number of bytes to scan. */
+    int numBytes,      /* Max number of bytes to scan. */
     int *incompletePtr,                /* Set this boolean memory to true if parsing
                                 * indicates an incomplete command. */
     char *typePtr)             /* Points to location to store character type
                                 * of character that ends run of whitespace */
 {
-    register char type = TYPE_NORMAL;
-    register const char *p = src;
+    char type = TYPE_NORMAL;
+    const char *p = src;
 
     while (1) {
        while (numBytes && ((type = CHAR_TYPE(*p)) & TYPE_SPACE)) {
@@ -754,7 +756,7 @@ TclParseAllWhiteSpace(
 /*
  *----------------------------------------------------------------------
  *
- * TclParseHex --
+ * ParseHex --
  *
  *     Scans a hexadecimal number as a Tcl_UniChar value (e.g., for parsing
  *     \x and \u escape sequences). At most numBytes bytes are scanned.
@@ -774,7 +776,7 @@ TclParseAllWhiteSpace(
  */
 
 int
-TclParseHex(
+ParseHex(
     const char *src,           /* First character to parse. */
     int numBytes,              /* Max number of byes to scan */
     int *resultPtr)    /* Points to storage provided by caller where
@@ -782,12 +784,12 @@ TclParseHex(
                                 * conversion is to be written. */
 {
     int result = 0;
-    register const char *p = src;
+    const char *p = src;
 
     while (numBytes--) {
        unsigned char digit = UCHAR(*p);
 
-       if (!isxdigit(digit) || (result > 0x10fff)) {
+       if (!isxdigit(digit) || (result > 0x10FFF)) {
            break;
        }
 
@@ -840,8 +842,7 @@ TclParseBackslash(
                                 * written. At most TCL_UTF_MAX bytes will be
                                 * written there. */
 {
-    register const char *p = src+1;
-    Tcl_UniChar unichar = 0;
+    const char *p = src+1;
     int result;
     int count;
     char buf[TCL_UTF_MAX] = "";
@@ -870,7 +871,7 @@ TclParseBackslash(
     count = 2;
     switch (*p) {
        /*
-        * Note: in the conversions below, use absolute values (e.g., 0xa)
+        * Note: in the conversions below, use absolute values (e.g., 0xA)
         * rather than symbolic values (e.g. \n) that get converted by the
         * compiler. It's possible that compilers on some platforms will do
         * the symbolic conversions differently, which could result in
@@ -884,25 +885,25 @@ TclParseBackslash(
        result = 0x8;
        break;
     case 'f':
-       result = 0xc;
+       result = 0xC;
        break;
     case 'n':
-       result = 0xa;
+       result = 0xA;
        break;
     case 'r':
-       result = 0xd;
+       result = 0xD;
        break;
     case 't':
        result = 0x9;
        break;
     case 'v':
-       result = 0xb;
+       result = 0xB;
        break;
     case 'x':
-       count += TclParseHex(p+1, (numBytes > 3) ? 2 : numBytes-2, &result);
+       count += ParseHex(p+1, (numBytes > 3) ? 2 : numBytes-2, &result);
        if (count == 2) {
            /*
-            * No hexadigits -> This is just "x".
+            * No hexdigits -> This is just "x".
             */
 
            result = 'x';
@@ -910,25 +911,42 @@ TclParseBackslash(
            /*
             * Keep only the last byte (2 hex digits).
             */
-           result = (unsigned char) result;
+           result = UCHAR(result);
        }
        break;
     case 'u':
-       count += TclParseHex(p+1, (numBytes > 5) ? 4 : numBytes-2, &result);
+       count += ParseHex(p+1, (numBytes > 5) ? 4 : numBytes-2, &result);
        if (count == 2) {
            /*
-            * No hexadigits -> This is just "u".
+            * No hexdigits -> This is just "u".
             */
            result = 'u';
+#if TCL_UTF_MAX > 3
+       } else if (((result & 0xFC00) == 0xD800) && (count == 6)
+                   && (p[5] == '\\') && (p[6] == 'u') && (numBytes >= 10)) {
+           /* If high surrogate is immediately followed by a low surrogate
+            * escape, combine them into one character. */
+           int low;
+           int count2 = ParseHex(p+7, 4, &low);
+           if ((count2 == 4) && ((low & 0xFC00) == 0xDC00)) {
+               result = ((result & 0x3FF)<<10 | (low & 0x3FF)) + 0x10000;
+               count += count2 + 2;
+           }
+#endif
        }
        break;
     case 'U':
-       count += TclParseHex(p+1, (numBytes > 9) ? 8 : numBytes-2, &result);
+       count += ParseHex(p+1, (numBytes > 9) ? 8 : numBytes-2, &result);
        if (count == 2) {
            /*
-            * No hexadigits -> This is just "U".
+            * No hexdigits -> This is just "U".
             */
            result = 'U';
+#if TCL_UTF_MAX > 3
+       } else if ((result & ~0x7FF) == 0xD800) {
+           /* Upper or lower surrogate, not allowed in this syntax. */
+           result = 0xFFFD;
+#endif
        }
        break;
     case '\n':
@@ -974,16 +992,15 @@ TclParseBackslash(
         * #217987] test subst-3.2
         */
 
-       if (Tcl_UtfCharComplete(p, numBytes - 1)) {
-           count = TclUtfToUniChar(p, &unichar) + 1;   /* +1 for '\' */
+       if (TclUCS4Complete(p, numBytes - 1)) {
+           count = TclUtfToUCS4(p, &result) + 1;       /* +1 for '\' */
        } else {
-           char utfBytes[TCL_UTF_MAX];
+           char utfBytes[8];
 
-           memcpy(utfBytes, p, (size_t) (numBytes - 1));
+           memcpy(utfBytes, p, numBytes - 1);
            utfBytes[numBytes - 1] = '\0';
-           count = TclUtfToUniChar(utfBytes, &unichar) + 1;
+           count = TclUtfToUCS4(utfBytes, &result) + 1;
        }
-       result = unichar;
        break;
     }
 
@@ -991,13 +1008,12 @@ TclParseBackslash(
     if (readPtr != NULL) {
        *readPtr = count;
     }
-    count = Tcl_UniCharToUtf(result, dst);
-#if TCL_UTF_MAX > 3
-     if ((result >= 0xD800) && (count < 3)) {
-       count += Tcl_UniCharToUtf(-1, dst + count);
+#if TCL_UTF_MAX < 4
+    if (result > 0xFFFF) {
+       result = 0xFFFD;
     }
 #endif
-    return count;
+    return TclUCS4ToUtf(result, dst);
 }
 \f
 /*
@@ -1021,12 +1037,12 @@ TclParseBackslash(
 static int
 ParseComment(
     const char *src,           /* First character to parse. */
-    register int numBytes,     /* Max number of bytes to scan. */
+    int numBytes,      /* Max number of bytes to scan. */
     Tcl_Parse *parsePtr)       /* Information about parse in progress.
                                 * Updated if parsing indicates an incomplete
                                 * command. */
 {
-    register const char *p = src;
+    const char *p = src;
 
     while (numBytes) {
        char type;
@@ -1105,8 +1121,8 @@ ParseComment(
 
 static int
 ParseTokens(
-    register const char *src,  /* First character to parse. */
-    register int numBytes,     /* Max number of bytes to scan. */
+    const char *src,   /* First character to parse. */
+    int numBytes,      /* Max number of bytes to scan. */
     int mask,                  /* Specifies when to stop parsing. The parse
                                 * stops at the first unquoted character whose
                                 * CHAR_TYPE contains any of the bits in
@@ -1384,7 +1400,7 @@ Tcl_ParseVarName(
                                 * NULL, then no error message is provided. */
     const char *start,         /* Start of variable substitution string.
                                 * First character must be "$". */
-    register int numBytes,     /* Total number of bytes in string. If < 0,
+    int numBytes,      /* Total number of bytes in string. If < 0,
                                 * the string consists of all bytes up to the
                                 * first null character. */
     Tcl_Parse *parsePtr,       /* Structure to fill in with information about
@@ -1395,20 +1411,19 @@ Tcl_ParseVarName(
                                 * reinitialize it. */
 {
     Tcl_Token *tokenPtr;
-    register const char *src;
+    const char *src;
     int varIndex;
     unsigned array;
 
-    if ((numBytes == 0) || (start == NULL)) {
-       return TCL_ERROR;
-    }
-    if (numBytes < 0) {
+    if (numBytes < 0 && start) {
        numBytes = strlen(start);
     }
-
     if (!append) {
        TclParseInit(interp, start, numBytes, parsePtr);
     }
+    if ((numBytes == 0) || (start == NULL)) {
+       return TCL_ERROR;
+    }
 
     /*
      * Generate one token for the variable, an additional token for the name,
@@ -1577,13 +1592,13 @@ Tcl_ParseVarName(
 const char *
 Tcl_ParseVar(
     Tcl_Interp *interp,                /* Context for looking up variable. */
-    register const char *start,        /* Start of variable substitution. First
+    const char *start, /* Start of variable substitution. First
                                 * character must be "$". */
     const char **termPtr)      /* If non-NULL, points to word to fill in with
                                 * character just after last one in the
                                 * variable specifier. */
 {
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
     int code;
     Tcl_Parse *parsePtr = TclStackAlloc(interp, sizeof(Tcl_Parse));
 
@@ -1662,10 +1677,10 @@ Tcl_ParseBraces(
                                 * NULL, then no error message is provided. */
     const char *start,         /* Start of string enclosed in braces. The
                                 * first character must be {'. */
-    register int numBytes,     /* Total number of bytes in string. If < 0,
+    int numBytes,      /* Total number of bytes in string. If < 0,
                                 * the string consists of all bytes up to the
                                 * first null character. */
-    register Tcl_Parse *parsePtr,
+    Tcl_Parse *parsePtr,
                                /* Structure to fill in with information about
                                 * the string. */
     int append,                        /* Non-zero means append tokens to existing
@@ -1678,19 +1693,18 @@ Tcl_ParseBraces(
                                 * successful. */
 {
     Tcl_Token *tokenPtr;
-    register const char *src;
+    const char *src;
     int startIndex, level, length;
 
-    if ((numBytes == 0) || (start == NULL)) {
-       return TCL_ERROR;
-    }
-    if (numBytes < 0) {
+    if (numBytes < 0 && start) {
        numBytes = strlen(start);
     }
-
     if (!append) {
        TclParseInit(interp, start, numBytes, parsePtr);
     }
+    if ((numBytes == 0) || (start == NULL)) {
+       return TCL_ERROR;
+    }
 
     src = start;
     startIndex = parsePtr->numTokens;
@@ -1804,7 +1818,7 @@ Tcl_ParseBraces(
      */
 
     {
-       register int openBrace = 0;
+       int openBrace = 0;
 
        while (--src > start) {
            switch (*src) {
@@ -1815,7 +1829,7 @@ Tcl_ParseBraces(
                openBrace = 0;
                break;
            case '#' :
-               if (openBrace && TclIsSpaceProc(src[-1])) {
+               if (openBrace && TclIsSpaceProcM(src[-1])) {
                    Tcl_AppendToObj(Tcl_GetObjResult(parsePtr->interp),
                            ": possible unbalanced brace in comment", -1);
                    goto error;
@@ -1864,10 +1878,10 @@ Tcl_ParseQuotedString(
                                 * NULL, then no error message is provided. */
     const char *start,         /* Start of the quoted string. The first
                                 * character must be '"'. */
-    register int numBytes,     /* Total number of bytes in string. If < 0,
+    int numBytes,      /* Total number of bytes in string. If < 0,
                                 * the string consists of all bytes up to the
                                 * first null character. */
-    register Tcl_Parse *parsePtr,
+    Tcl_Parse *parsePtr,
                                /* Structure to fill in with information about
                                 * the string. */
     int append,                        /* Non-zero means append tokens to existing
@@ -1879,16 +1893,15 @@ Tcl_ParseQuotedString(
                                 * the quoted string's terminating close-quote
                                 * if the parse succeeds. */
 {
-    if ((numBytes == 0) || (start == NULL)) {
-       return TCL_ERROR;
-    }
-    if (numBytes < 0) {
+    if (numBytes < 0 && start) {
        numBytes = strlen(start);
     }
-
     if (!append) {
        TclParseInit(interp, start, numBytes, parsePtr);
     }
+    if ((numBytes == 0) || (start == NULL)) {
+       return TCL_ERROR;
+    }
 
     if (TCL_OK != ParseTokens(start+1, numBytes-1, TYPE_QUOTE, TCL_SUBST_ALL,
            parsePtr)) {
@@ -2159,7 +2172,7 @@ TclSubstTokens(
                                 * command, which is refered to by 'script'.
                                 * The 'clNextOuter' refers to the current
                                 * entry in the table of continuation lines in
-                                * this "master script", and the character
+                                * this "main script", and the character
                                 * offsets are relative to the 'outerScript'
                                 * as well.
                                 *
index c5b1ef6..a41d9fd 100644 (file)
@@ -1745,7 +1745,7 @@ Tcl_FSGetTranslatedStringPath(
        const char *orig = Tcl_GetStringFromObj(transPtr, &len);
        char *result = ckalloc(len+1);
 
-       memcpy(result, orig, (size_t) len+1);
+       memcpy(result, orig, len+1);
        TclDecrRefCount(transPtr);
        return result;
     }
@@ -2617,7 +2617,7 @@ DupFsPathInternalRep(
 
 static void
 UpdateStringOfFsPath(
-    register Tcl_Obj *pathPtr) /* path obj with string rep to update. */
+    Tcl_Obj *pathPtr)  /* path obj with string rep to update. */
 {
     FsPath *fsPathPtr = PATHOBJ(pathPtr);
     int cwdLen;
index bd49bec..7d5fab0 100644 (file)
@@ -183,7 +183,7 @@ Tcl_DetachPids(
                                 * array pointed to by pidPtr. */
     Tcl_Pid *pidPtr)           /* Array of pids to detach. */
 {
-    register Detached *detPtr;
+    Detached *detPtr;
     int i;
 
     Tcl_MutexLock(&pipeMutex);
@@ -219,7 +219,7 @@ Tcl_DetachPids(
 void
 Tcl_ReapDetachedProcs(void)
 {
-    register Detached *detPtr;
+    Detached *detPtr;
     Detached *nextPtr, *prevPtr;
     int status;
     Tcl_Pid pid;
index 06d6ade..2150c31 100644 (file)
@@ -718,8 +718,9 @@ SelectPackageFinal(ClientData data[], Tcl_Interp *interp, int result) {
            }
        }
     } else if (result != TCL_ERROR) {
-       Tcl_Obj *codePtr = Tcl_NewIntObj(result);
+       Tcl_Obj *codePtr;
 
+       TclNewIntObj(codePtr, result);
        Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                "attempt to provide package %s %s failed:"
                " bad return code: %s",
@@ -1137,9 +1138,10 @@ TclNRPackageObjCmd(
            Tcl_NRAddCallback(interp, PkgRequireCore, (void *)argv3, INT2PTR(newobjc), newObjvPtr, NULL);
            return TCL_OK;
        } else {
-           int i, newobjc = objc-3;
            Tcl_Obj *const *newobjv = objv + 3;
-           if (CheckAllRequirements(interp, objc-3, objv+3) != TCL_OK) {
+           newobjc = objc - 3;
+
+           if (CheckAllRequirements(interp, objc - 3, objv + 3) != TCL_OK) {
                return TCL_ERROR;
            }
            objvListPtr = Tcl_NewListObj(0, NULL);
index 466d535..727e872 100644 (file)
 
 #include "tclInt.h"
 \f
+#ifndef TCL_CFGVAL_ENCODING
+#   ifdef _WIN32
+#      define TCL_CFGVAL_ENCODING "cp1252"
+#   else
+#      define TCL_CFGVAL_ENCODING "iso8859-1"
+#   endif
+#endif
+
 /*
  * Use C preprocessor statements to define the various values for the embedded
  * configuration information.
index abc8ee8..974bafa 100644 (file)
@@ -114,6 +114,11 @@ extern const TclPlatStubs *tclPlatStubsPtr;
 
 /* !END!: Do not edit above this line. */
 
+#ifdef MAC_OSX_TCL /* MACOSX */
+#undef Tcl_MacOSXOpenBundleResources
+#define Tcl_MacOSXOpenBundleResources(a,b,c,d,e) Tcl_MacOSXOpenVersionedBundleResources(a,b,NULL,c,d,e)
+#endif
+
 #undef TCL_STORAGE_CLASS
 #define TCL_STORAGE_CLASS DLLIMPORT
 
index f050d54..769074b 100644 (file)
@@ -122,7 +122,7 @@ Tcl_ProcObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     Proc *procPtr;
     const char *procName;
     const char *simpleName, *procArgs, *procBody;
@@ -197,9 +197,10 @@ Tcl_ProcObjCmd(
      */
 
     if (iPtr->cmdFramePtr) {
-       CmdFrame *contextPtr = TclStackAlloc(interp, sizeof(CmdFrame));
+       CmdFrame *contextPtr = (CmdFrame *)TclStackAlloc(interp, sizeof(CmdFrame));
 
        *contextPtr = *iPtr->cmdFramePtr;
+
        if (contextPtr->type == TCL_LOCATION_BC) {
            /*
             * Retrieve source information from the bytecode, if possible. If
@@ -228,11 +229,11 @@ Tcl_ProcObjCmd(
                    && (contextPtr->nline >= 4) && (contextPtr->line[3] >= 0)) {
                int isNew;
                Tcl_HashEntry *hePtr;
-               CmdFrame *cfPtr = ckalloc(sizeof(CmdFrame));
+               CmdFrame *cfPtr = (CmdFrame *)ckalloc(sizeof(CmdFrame));
 
                cfPtr->level = -1;
                cfPtr->type = contextPtr->type;
-               cfPtr->line = ckalloc(sizeof(int));
+               cfPtr->line = (int *)ckalloc(sizeof(int));
                cfPtr->line[0] = contextPtr->line[3];
                cfPtr->nline = 1;
                cfPtr->framePtr = NULL;
@@ -245,7 +246,7 @@ Tcl_ProcObjCmd(
                cfPtr->len = 0;
 
                hePtr = Tcl_CreateHashEntry(iPtr->linePBodyPtr,
-                       procPtr, &isNew);
+                       (char *)procPtr, &isNew);
                if (!isNew) {
                    /*
                     * Get the old command frame and release it. See also
@@ -370,9 +371,9 @@ TclCreateProc(
 {
     Interp *iPtr = (Interp *) interp;
 
-    register Proc *procPtr;
+    Proc *procPtr;
     int i, result, numArgs;
-    register CompiledLocal *localPtr = NULL;
+    CompiledLocal *localPtr = NULL;
     Tcl_Obj **argArray;
     int precompiled = 0;
 
@@ -434,7 +435,7 @@ TclCreateProc(
 
        Tcl_IncrRefCount(bodyPtr);
 
-       procPtr = ckalloc(sizeof(Proc));
+       procPtr = (Proc *)ckalloc(sizeof(Proc));
        procPtr->iPtr = iPtr;
        procPtr->refCount = 1;
        procPtr->bodyPtr = bodyPtr;
@@ -451,7 +452,7 @@ TclCreateProc(
      * in the Proc.
      */
 
-    result = Tcl_ListObjGetElements(interp , argsPtr ,&numArgs ,&argArray);
+    result = Tcl_ListObjGetElements(interp, argsPtr, &numArgs, &argArray);
     if (result != TCL_OK) {
        goto procError;
     }
@@ -473,7 +474,7 @@ TclCreateProc(
     }
 
     for (i = 0; i < numArgs; i++) {
-       const char *argname, *argnamei, *argnamelast;
+       const char *argname, *p, *last;
        int fieldCount, nameLength;
        Tcl_Obj **fieldValues;
 
@@ -504,17 +505,15 @@ TclCreateProc(
            goto procError;
        }
 
-       argname = Tcl_GetStringFromObj(fieldValues[0], &nameLength);
-
        /*
         * Check that the formal parameter name is a scalar.
         */
 
-       argnamei = argname;
-       argnamelast = Tcl_UtfPrev(argname + nameLength, argname);
-       while (argnamei < argnamelast) {
-           if (*argnamei == '(') {
-               if (*argnamelast == ')') { /* We have an array element. */
+       p = argname = Tcl_GetStringFromObj(fieldValues[0], &nameLength);
+       last = argname + nameLength;
+       while (p < last) {
+           if (*p == '(') {
+               if (last[-1] == ')') { /* We have an array element. */
                    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
                            "formal parameter \"%s\" is an array element",
                            Tcl_GetString(fieldValues[0])));
@@ -522,7 +521,7 @@ TclCreateProc(
                            "FORMALARGUMENTFORMAT", NULL);
                    goto procError;
                }
-           } else if (*argnamei == ':' && *(argnamei+1) == ':') {
+           } else if (p[0] == ':' && p[1] == ':') {
                Tcl_Obj *errorObj = Tcl_NewStringObj(
                    "formal parameter \"", -1);
                Tcl_AppendObjToObj(errorObj, fieldValues[0]);
@@ -532,7 +531,7 @@ TclCreateProc(
                        "FORMALARGUMENTFORMAT", NULL);
                goto procError;
            }
-           argnamei = Tcl_UtfNext(argnamei);
+           p++;
        }
 
        if (precompiled) {
@@ -600,7 +599,8 @@ TclCreateProc(
             * local variables for the argument.
             */
 
-           localPtr = ckalloc(TclOffset(CompiledLocal, name) + fieldValues[0]->length +1);
+           localPtr = (CompiledLocal *)ckalloc(
+                   TclOffset(CompiledLocal, name) + fieldValues[0]->length + 1);
            if (procPtr->firstLocalPtr == NULL) {
                procPtr->firstLocalPtr = procPtr->lastLocalPtr = localPtr;
            } else {
@@ -684,7 +684,7 @@ TclGetFrame(
     CallFrame **framePtrPtr)   /* Store pointer to frame here (or NULL if
                                 * global frame indicated). */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     int curLevel, level, result;
     CallFrame *framePtr;
 
@@ -768,7 +768,7 @@ TclObjGetFrame(
     CallFrame **framePtrPtr)   /* Store pointer to frame here (or NULL if
                                 * global frame indicated). */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     int curLevel, level, result;
     const char *name = NULL;
 
@@ -895,7 +895,7 @@ TclNRUplevelObjCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
 
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     CmdFrame *invoker = NULL;
     int word = 0;
     int result;
@@ -903,9 +903,28 @@ TclNRUplevelObjCmd(
     Tcl_Obj *objPtr;
 
     if (objc < 2) {
+    /* to do
+    *    simplify things by interpreting the argument as a command when there
+    *    is only one argument.  This requires a TIP since currently a single
+    *    argument is interpreted as a level indicator if possible.
+    */
     uplevelSyntax:
        Tcl_WrongNumArgs(interp, 1, objv, "?level? command ?arg ...?");
        return TCL_ERROR;
+    } else if (!TclHasStringRep(objv[1]) && objc == 2) {
+       int status ,llength;
+       status = Tcl_ListObjLength(interp, objv[1], &llength);
+       if (status == TCL_OK && llength > 1) {
+           /* the first argument can't interpreted as a level. Avoid
+            * generating a string representation of the script. */
+           result = TclGetFrame(interp, "1", &framePtr);
+           if (result == -1) {
+               return TCL_ERROR;
+           }
+           objc -= 1;
+           objv += 1;
+           goto havelevel;
+       }
     }
 
     /*
@@ -922,6 +941,8 @@ TclNRUplevelObjCmd(
     }
     objv += result + 1;
 
+    havelevel:
+
     /*
      * Modify the interpreter state to execute in the given frame.
      */
@@ -1035,7 +1056,7 @@ ProcWrongNumArgs(
     int skip)
 {
     CallFrame *framePtr = ((Interp *)interp)->varFramePtr;
-    register Proc *procPtr = framePtr->procPtr;
+    Proc *procPtr = framePtr->procPtr;
     int localCt = procPtr->numCompiledLocals, numArgs, i;
     Tcl_Obj **desiredObjs;
     const char *final = NULL;
@@ -1045,7 +1066,7 @@ ProcWrongNumArgs(
      */
 
     numArgs = framePtr->procPtr->numArgs;
-    desiredObjs = TclStackAlloc(interp,
+    desiredObjs = (Tcl_Obj **)TclStackAlloc(interp,
            (int) sizeof(Tcl_Obj *) * (numArgs+1));
 
     if (framePtr->isProcCallFrame & FRAME_IS_LAMBDA) {
@@ -1060,7 +1081,7 @@ ProcWrongNumArgs(
     Tcl_IncrRefCount(desiredObjs[0]);
 
     if (localCt > 0) {
-       register Var *defPtr = (Var *) (&framePtr->localCachePtr->varName0 + localCt);
+       Var *defPtr = (Var *)(&framePtr->localCachePtr->varName0 + localCt);
 
        for (i=1 ; i<=numArgs ; i++, defPtr++) {
            Tcl_Obj *argObj;
@@ -1251,7 +1272,7 @@ InitResolvedLocals(
 
        resVarInfo = localPtr->resolveInfo;
        if (resVarInfo && resVarInfo->fetchProc) {
-           register Var *resolvedVarPtr = (Var *)
+           Var *resolvedVarPtr = (Var *)
                    resVarInfo->fetchProc(interp, resVarInfo);
 
            if (resolvedVarPtr) {
@@ -1274,7 +1295,7 @@ TclFreeLocalCache(
     Tcl_Obj **namePtrPtr = &localCachePtr->varName0;
 
     for (i = 0; i < localCachePtr->numVars; i++, namePtrPtr++) {
-       register Tcl_Obj *objPtr = *namePtrPtr;
+       Tcl_Obj *objPtr = *namePtrPtr;
 
        if (objPtr) {
            /* TclReleaseLiteral calls Tcl_DecrRefCount for us */
@@ -1305,8 +1326,8 @@ InitLocalCache(
      * for future calls.
      */
 
-    localCachePtr = ckalloc(sizeof(LocalCache)
-           + (localCt - 1) * sizeof(Tcl_Obj *)
+    localCachePtr = (LocalCache *)ckalloc(TclOffset(LocalCache, varName0)
+           + localCt * sizeof(Tcl_Obj *)
            + numArgs * sizeof(Var));
 
     namePtr = &localCachePtr->varName0;
@@ -1358,16 +1379,16 @@ InitLocalCache(
 
 static int
 InitArgsAndLocals(
-    register Tcl_Interp *interp,/* Interpreter in which procedure was
+    Tcl_Interp *interp,/* Interpreter in which procedure was
                                 * invoked. */
     Tcl_Obj *procNameObj,      /* Procedure name for error reporting. */
     int skip)                  /* Number of initial arguments to be skipped,
                                 * i.e., words in the "command name". */
 {
     CallFrame *framePtr = ((Interp *)interp)->varFramePtr;
-    register Proc *procPtr = framePtr->procPtr;
+    Proc *procPtr = framePtr->procPtr;
     ByteCode *codePtr = procPtr->bodyPtr->internalRep.twoPtrValue.ptr1;
-    register Var *varPtr, *defPtr;
+    Var *varPtr, *defPtr;
     int localCt = procPtr->numCompiledLocals, numArgs, argCt, i, imax;
     Tcl_Obj *const *argObjs;
 
@@ -1393,7 +1414,7 @@ InitArgsAndLocals(
      * parameters.
      */
 
-    varPtr = TclStackAlloc(interp, (int)(localCt * sizeof(Var)));
+    varPtr = TclStackAlloc(interp, localCt * sizeof(Var));
     framePtr->compiledLocals = varPtr;
     framePtr->numCompiledLocals = localCt;
 
@@ -1523,7 +1544,7 @@ int
 TclPushProcCallFrame(
     ClientData clientData,     /* Record describing procedure to be
                                 * interpreted. */
-    register Tcl_Interp *interp,/* Interpreter in which procedure was
+    Tcl_Interp *interp,/* Interpreter in which procedure was
                                 * invoked. */
     int objc,                  /* Count of number of arguments to this
                                 * procedure. */
@@ -1615,7 +1636,7 @@ int
 TclObjInterpProc(
     ClientData clientData,     /* Record describing procedure to be
                                 * interpreted. */
-    register Tcl_Interp *interp,/* Interpreter in which procedure was
+    Tcl_Interp *interp,/* Interpreter in which procedure was
                                 * invoked. */
     int objc,                  /* Count of number of arguments to this
                                 * procedure. */
@@ -1632,7 +1653,7 @@ int
 TclNRInterpProc(
     ClientData clientData,     /* Record describing procedure to be
                                 * interpreted. */
-    register Tcl_Interp *interp,/* Interpreter in which procedure was
+    Tcl_Interp *interp,/* Interpreter in which procedure was
                                 * invoked. */
     int objc,                  /* Count of number of arguments to this
                                 * procedure. */
@@ -1667,7 +1688,7 @@ TclNRInterpProc(
 
 int
 TclNRInterpProcCore(
-    register Tcl_Interp *interp,/* Interpreter in which procedure was
+    Tcl_Interp *interp,/* Interpreter in which procedure was
                                 * invoked. */
     Tcl_Obj *procNameObj,      /* Procedure name for error reporting. */
     int skip,                  /* Number of initial arguments to be skipped,
@@ -1676,7 +1697,7 @@ TclNRInterpProcCore(
                                 * results of the overall procedure. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Proc *procPtr = iPtr->varFramePtr->procPtr;
+    Proc *procPtr = iPtr->varFramePtr->procPtr;
     int result;
     CallFrame *freePtr;
     ByteCode *codePtr;
@@ -1693,8 +1714,8 @@ TclNRInterpProcCore(
 
 #if defined(TCL_COMPILE_DEBUG)
     if (tclTraceExec >= 1) {
-       register CallFrame *framePtr = iPtr->varFramePtr;
-       register int i;
+       CallFrame *framePtr = iPtr->varFramePtr;
+       int i;
 
        if (framePtr->isProcCallFrame & FRAME_IS_LAMBDA) {
            fprintf(stdout, "Calling lambda ");
@@ -2107,9 +2128,9 @@ TclProcDeleteProc(
 
 void
 TclProcCleanupProc(
-    register Proc *procPtr)    /* Procedure to be deleted. */
+    Proc *procPtr)     /* Procedure to be deleted. */
 {
-    register CompiledLocal *localPtr;
+    CompiledLocal *localPtr;
     Tcl_Obj *bodyPtr = procPtr->bodyPtr;
     Tcl_Obj *defPtr;
     Tcl_ResolvedVarInfo *resVarInfo;
@@ -2156,7 +2177,7 @@ TclProcCleanupProc(
        return;
     }
 
-    cfPtr = Tcl_GetHashValue(hePtr);
+    cfPtr = (CmdFrame *) Tcl_GetHashValue(hePtr);
 
     if (cfPtr) {
        if (cfPtr->type == TCL_LOCATION_SOURCE) {
@@ -2360,7 +2381,7 @@ ProcBodyFree(
 static void
 DupLambdaInternalRep(
     Tcl_Obj *srcPtr,           /* Object with internal rep to copy. */
-    register Tcl_Obj *copyPtr) /* Object with internal rep to set. */
+    Tcl_Obj *copyPtr)  /* Object with internal rep to set. */
 {
     Proc *procPtr = srcPtr->internalRep.twoPtrValue.ptr1;
     Tcl_Obj *nsObjPtr = srcPtr->internalRep.twoPtrValue.ptr2;
@@ -2375,7 +2396,7 @@ DupLambdaInternalRep(
 
 static void
 FreeLambdaInternalRep(
-    register Tcl_Obj *objPtr)  /* CmdName object with internal representation
+    Tcl_Obj *objPtr)   /* CmdName object with internal representation
                                 * to free. */
 {
     Proc *procPtr = objPtr->internalRep.twoPtrValue.ptr1;
@@ -2391,7 +2412,7 @@ FreeLambdaInternalRep(
 static int
 SetLambdaFromAny(
     Tcl_Interp *interp,                /* Used for error reporting if not NULL. */
-    register Tcl_Obj *objPtr)  /* The object to convert. */
+    Tcl_Obj *objPtr)   /* The object to convert. */
 {
     Interp *iPtr = (Interp *) interp;
     const char *name;
@@ -2499,12 +2520,12 @@ SetLambdaFromAny(
                 * location (line of 2nd list element).
                 */
 
-               cfPtr = ckalloc(sizeof(CmdFrame));
+               cfPtr = (CmdFrame *)ckalloc(sizeof(CmdFrame));
                TclListLines(objPtr, contextPtr->line[1], 2, buf, NULL);
 
                cfPtr->level = -1;
                cfPtr->type = contextPtr->type;
-               cfPtr->line = ckalloc(sizeof(int));
+               cfPtr->line = (int *)ckalloc(sizeof(int));
                cfPtr->line[0] = buf[1];
                cfPtr->nline = 1;
                cfPtr->framePtr = NULL;
index 19ff8fd..2070956 100644 (file)
@@ -64,7 +64,7 @@
 
 #define NUM_REGEXPS 30
 
-typedef struct ThreadSpecificData {
+typedef struct {
     int initialized;           /* Set to 1 when the module is initialized. */
     char *patterns[NUM_REGEXPS];/* Strings corresponding to compiled regular
                                 * expression patterns. NULL means that this
@@ -245,7 +245,7 @@ Tcl_RegExpRange(
 
     if ((size_t) index > regexpPtr->re.re_nsub) {
        *startPtr = *endPtr = NULL;
-    } else if (regexpPtr->matches[index].rm_so < 0) {
+    } else if (regexpPtr->matches[index].rm_so == -1) {
        *startPtr = *endPtr = NULL;
     } else {
        if (regexpPtr->objPtr) {
@@ -355,7 +355,7 @@ TclRegExpRangeUniChar(
 {
     TclRegexp *regexpPtr = (TclRegexp *) re;
 
-    if ((regexpPtr->flags&REG_EXPECT) && index == -1) {
+    if ((regexpPtr->flags&REG_EXPECT) && (index == -1)) {
        *startPtr = regexpPtr->details.rm_extend.rm_so;
        *endPtr = regexpPtr->details.rm_extend.rm_eo;
     } else if ((size_t) index > regexpPtr->re.re_nsub) {
@@ -510,9 +510,9 @@ Tcl_RegExpMatchObj(
      */
 
     if (!(re = Tcl_GetRegExpFromObj(interp, patternObj,
-            TCL_REG_ADVANCED | TCL_REG_NOSUB))
+           TCL_REG_ADVANCED | TCL_REG_NOSUB))
      && !(re = Tcl_GetRegExpFromObj(interp, patternObj, TCL_REG_ADVANCED))) {
-        return -1;
+       return -1;
     }
     return Tcl_RegExpExecObj(interp, re, textObj, 0 /* offset */,
            0 /* nmatches */, 0 /* flags */);
@@ -912,7 +912,7 @@ CompileRegexp(
      * This is a new expression, so compile it and add it to the cache.
      */
 
-    regexpPtr = ckalloc(sizeof(TclRegexp));
+    regexpPtr = (TclRegexp*)ckalloc(sizeof(TclRegexp));
     regexpPtr->objPtr = NULL;
     regexpPtr->string = NULL;
     regexpPtr->details.rm_extend.rm_so = -1;
@@ -967,7 +967,7 @@ CompileRegexp(
      */
 
     regexpPtr->matches =
-           ckalloc(sizeof(regmatch_t) * (regexpPtr->re.re_nsub + 1));
+           (regmatch_t*)ckalloc(sizeof(regmatch_t) * (regexpPtr->re.re_nsub + 1));
 
     /*
      * Initialize the refcount to one initially, since it is in the cache.
@@ -993,8 +993,8 @@ CompileRegexp(
        tsdPtr->patLengths[i+1] = tsdPtr->patLengths[i];
        tsdPtr->regexps[i+1] = tsdPtr->regexps[i];
     }
-    tsdPtr->patterns[0] = ckalloc(length + 1);
-    memcpy(tsdPtr->patterns[0], string, (unsigned) length + 1);
+    tsdPtr->patterns[0] = (char *)ckalloc(length + 1);
+    memcpy(tsdPtr->patterns[0], string, length + 1);
     tsdPtr->patLengths[0] = length;
     tsdPtr->regexps[0] = regexpPtr;
 
index 9d0714c..07d0e83 100644 (file)
@@ -411,14 +411,14 @@ void
 Tcl_SetResult(
     Tcl_Interp *interp,                /* Interpreter with which to associate the
                                 * return value. */
-    register char *result,     /* Value to be returned. If NULL, the result
+    char *result,      /* Value to be returned. If NULL, the result
                                 * is set to an empty string. */
     Tcl_FreeProc *freeProc)    /* Gives information about the string:
                                 * TCL_STATIC, TCL_VOLATILE, or the address of
                                 * a Tcl_FreeProc such as free. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Tcl_FreeProc *oldFreeProc = iPtr->freeProc;
+    Tcl_FreeProc *oldFreeProc = iPtr->freeProc;
     char *oldResult = iPtr->result;
 
     if (result == NULL) {
@@ -435,7 +435,7 @@ Tcl_SetResult(
            iPtr->result = iPtr->resultSpace;
            iPtr->freeProc = 0;
        }
-       memcpy(iPtr->result, result, (unsigned) length+1);
+       memcpy(iPtr->result, result, length+1);
     } else {
        iPtr->result = (char *) result;
        iPtr->freeProc = freeProc;
@@ -481,7 +481,7 @@ Tcl_SetResult(
 
 const char *
 Tcl_GetStringResult(
-    register Tcl_Interp *interp)/* Interpreter whose result to return. */
+    Tcl_Interp *interp)/* Interpreter whose result to return. */
 {
     /*
      * If the string result is empty, move the object result to the string
@@ -520,11 +520,11 @@ void
 Tcl_SetObjResult(
     Tcl_Interp *interp,                /* Interpreter with which to associate the
                                 * return object value. */
-    register Tcl_Obj *objPtr)  /* Tcl object to be returned. If NULL, the obj
+    Tcl_Obj *objPtr)   /* Tcl object to be returned. If NULL, the obj
                                 * result is made an empty string object. */
 {
-    register Interp *iPtr = (Interp *) interp;
-    register Tcl_Obj *oldObjResult = iPtr->objResultPtr;
+    Interp *iPtr = (Interp *) interp;
+    Tcl_Obj *oldObjResult = iPtr->objResultPtr;
 
     iPtr->objResultPtr = objPtr;
     Tcl_IncrRefCount(objPtr);  /* since interp result is a reference */
@@ -577,7 +577,7 @@ Tcl_Obj *
 Tcl_GetObjResult(
     Tcl_Interp *interp)                /* Interpreter whose result to return. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
     Tcl_Obj *objResultPtr;
     int length;
 
@@ -725,6 +725,7 @@ Tcl_AppendElement(
     char *dst;
     int size;
     int flags;
+    int quoteHash = 1;
 
     /*
      * If the string result is empty, move the object result to the string
@@ -761,9 +762,17 @@ Tcl_AppendElement(
         * then this element will not lead a list, and need not have it's
         * leading '#' quoted.
         */
-
+       quoteHash = 0;
+    } else {
+       while ((--dst >= iPtr->appendResult) && TclIsSpaceProcM(*dst)) {
+       }
+       quoteHash = !TclNeedSpace(iPtr->appendResult, dst+1);
+    }
+    dst = iPtr->appendResult + iPtr->appendUsed;
+    if (!quoteHash) {
        flags |= TCL_DONT_QUOTE_HASH;
     }
+
     iPtr->appendUsed += Tcl_ConvertElement(element, dst, flags);
 }
 \f
@@ -871,9 +880,9 @@ SetupAppendBuffer(
 
 void
 Tcl_FreeResult(
-    register Tcl_Interp *interp)/* Interpreter for which to free result. */
+    Tcl_Interp *interp)/* Interpreter for which to free result. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     if (iPtr->freeProc != NULL) {
        if (iPtr->freeProc == TCL_DYNAMIC) {
@@ -908,9 +917,9 @@ Tcl_FreeResult(
 
 void
 Tcl_ResetResult(
-    register Tcl_Interp *interp)/* Interpreter for which to clear result. */
+    Tcl_Interp *interp)/* Interpreter for which to clear result. */
 {
-    register Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *) interp;
 
     ResetObjResult(iPtr);
     if (iPtr->freeProc != NULL) {
@@ -971,10 +980,10 @@ Tcl_ResetResult(
 
 static void
 ResetObjResult(
-    register Interp *iPtr)     /* Points to the interpreter whose result
+    Interp *iPtr)      /* Points to the interpreter whose result
                                 * object should be reset. */
 {
-    register Tcl_Obj *objResultPtr = iPtr->objResultPtr;
+    Tcl_Obj *objResultPtr = iPtr->objResultPtr;
 
     if (Tcl_IsShared(objResultPtr)) {
        TclDecrRefCount(objResultPtr);
@@ -1682,22 +1691,14 @@ Tcl_SetReturnOptions(
  *
  * Tcl_TransferResult --
  *
- *     Copy the result (and error information) from one interp to another.
+ *     Transfer the result (and error information) from one interp to another.
  *     Used when one interp has caused another interp to evaluate a script
  *     and then wants to transfer the results back to itself.
  *
- *     This routine copies the string reps of the result and error
- *     information. It does not simply increment the refcounts of the result
- *     and error information objects themselves. It is not legal to exchange
- *     objects between interps, because an object may be kept alive by one
- *     interp, but have an internal rep that is only valid while some other
- *     interp is alive.
- *
  * Results:
- *     The target interp's result is set to a copy of the source interp's
- *     result. The source's errorInfo field may be transferred to the
- *     target's errorInfo field, and the source's errorCode field may be
- *     transferred to the target's errorCode field.
+ *     The result of targetInterp is set to the result read from sourceInterp.
+ *     The return options dictionary of sourceInterp is transferred to
+ *     targetInterp as appropriate for the return code value code.
  *
  * Side effects:
  *     None.
@@ -1707,14 +1708,16 @@ Tcl_SetReturnOptions(
 
 void
 Tcl_TransferResult(
-    Tcl_Interp *sourceInterp,  /* Interp whose result and error information
+    Tcl_Interp *sourceInterp,  /* Interp whose result and return options
                                 * should be moved to the target interp.
                                 * After moving result, this interp's result
                                 * is reset. */
-    int result,                        /* TCL_OK if just the result should be copied,
-                                * TCL_ERROR if both the result and error
-                                * information should be copied. */
-    Tcl_Interp *targetInterp)  /* Interp where result and error information
+    int code,                  /* The return code value active in
+                                * sourceInterp. Controls how the return options
+                                * dictionary is retrieved from sourceInterp,
+                                * same as in Tcl_GetReturnOptions, to then be
+                                * transferred to targetInterp. */
+    Tcl_Interp *targetInterp)  /* Interp where result and return options
                                 * should be stored. If source and target are
                                 * the same, nothing is done. */
 {
@@ -1725,7 +1728,7 @@ Tcl_TransferResult(
        return;
     }
 
-    if (result == TCL_OK && siPtr->returnOpts == NULL) {
+    if (code == TCL_OK && siPtr->returnOpts == NULL) {
        /*
         * Special optimization for the common case of normal command return
         * code and no explicit return options.
@@ -1737,7 +1740,7 @@ Tcl_TransferResult(
        }
     } else {
        Tcl_SetReturnOptions(targetInterp,
-               Tcl_GetReturnOptions(sourceInterp, result));
+               Tcl_GetReturnOptions(sourceInterp, code));
        tiPtr->flags &= ~(ERR_ALREADY_LOGGED);
     }
     Tcl_SetObjResult(targetInterp, Tcl_GetObjResult(sourceInterp));
index 4b9298d..6ab17bd 100644 (file)
@@ -721,7 +721,7 @@ Tcl_ScanObjCmd(
        switch (ch) {
        case 'n':
            if (!(flags & SCAN_SUPPRESS)) {
-               objPtr = Tcl_NewIntObj(string - baseString);
+               TclNewIntObj(objPtr, string - baseString);
                Tcl_IncrRefCount(objPtr);
                CLANG_ASSERT(objs);
                objs[objIndex++] = objPtr;
@@ -881,17 +881,10 @@ Tcl_ScanObjCmd(
             * Scan a single Unicode character.
             */
 
-           offset = TclUtfToUniChar(string, &sch);
-           i = (int)sch;
-#if TCL_UTF_MAX == 4
-           if ((sch >= 0xD800) && (offset < 3)) {
-               offset += TclUtfToUniChar(string+offset, &sch);
-               i = (((i<<10) & 0x0FFC00) + 0x10000) + (sch & 0x3FF);
-           }
-#endif
+           offset = TclUtfToUCS4(string, &i);
            string += offset;
            if (!(flags & SCAN_SUPPRESS)) {
-               objPtr = Tcl_NewIntObj(i);
+               TclNewIntObj(objPtr, i);
                Tcl_IncrRefCount(objPtr);
                CLANG_ASSERT(objs);
                objs[objIndex++] = objPtr;
@@ -1042,7 +1035,7 @@ Tcl_ScanObjCmd(
         * Here no vars were specified, we want a list returned (inline scan)
         */
 
-       objPtr = Tcl_NewObj();
+       TclNewObj(objPtr);
        for (i = 0; i < totalVars; i++) {
            if (objs[i] != NULL) {
                Tcl_ListObjAppendElement(NULL, objPtr, objs[i]);
@@ -1063,16 +1056,16 @@ Tcl_ScanObjCmd(
     if (code == TCL_OK) {
        if (underflow && (nconversions == 0)) {
            if (numVars) {
-               objPtr = Tcl_NewIntObj(-1);
+               TclNewIntObj(objPtr, -1);
            } else {
                if (objPtr) {
                    Tcl_SetListObj(objPtr, 0, NULL);
                } else {
-                   objPtr = Tcl_NewObj();
+                   TclNewObj(objPtr);
                }
            }
        } else if (numVars) {
-           objPtr = Tcl_NewIntObj(result);
+           TclNewIntObj(objPtr, result);
        }
        Tcl_SetObjResult(interp, objPtr);
     }
index 1862290..2e66864 100644 (file)
 
 #include "tclInt.h"
 #include "tommath.h"
+#include <float.h>
 #include <math.h>
 
+#ifdef _WIN32
+#define copysign _copysign
+#endif
+
 /*
  * Define KILL_OCTAL to suppress interpretation of numbers with leading zero
  * as octal. (Ceterum censeo: numeros octonarios delendos esse.)
@@ -52,7 +57,7 @@ typedef unsigned int  fpu_control_t __attribute__ ((__mode__ (__HI__)));
 
 #define _FPU_GETCW(cw) __asm__ __volatile__ ("fnstcw %0" : "=m" (*&cw))
 #define _FPU_SETCW(cw) __asm__ __volatile__ ("fldcw %0" : : "m" (*&cw))
-#   define FPU_IEEE_ROUNDING   0x027f
+#   define FPU_IEEE_ROUNDING   0x027F
 #   define ADJUST_FPU_CONTROL_WORD
 #define TCL_IEEE_DOUBLE_ROUNDING \
     fpu_control_t roundTo53Bits = FPU_IEEE_ROUNDING;   \
@@ -101,10 +106,10 @@ typedef unsigned int      fpu_control_t __attribute__ ((__mode__ (__HI__)));
  */
 
 #ifdef __hppa
-#   define NAN_START   0x7ff4
+#   define NAN_START   0x7FF4
 #   define NAN_MASK    (((Tcl_WideUInt) 1) << 50)
 #else
-#   define NAN_START   0x7ff8
+#   define NAN_START   0x7FF8
 #   define NAN_MASK    (((Tcl_WideUInt) 1) << 51)
 #endif
 
@@ -126,23 +131,23 @@ typedef unsigned int      fpu_control_t __attribute__ ((__mode__ (__HI__)));
 #define SIGN_BIT       0x80000000
                                /* Mask for the sign bit in the first word of
                                 * a double. */
-#define EXP_MASK       0x7ff00000
+#define EXP_MASK       0x7FF00000
                                /* Mask for the exponent field in the first
                                 * word of a double. */
 #define EXP_SHIFT      20      /* Shift count to make the exponent an
                                 * integer. */
 #define HIDDEN_BIT     (((Tcl_WideUInt) 0x00100000) << 32)
                                /* Hidden 1 bit for the significand. */
-#define HI_ORDER_SIG_MASK 0x000fffff
+#define HI_ORDER_SIG_MASK 0x000FFFFF
                                /* Mask for the high-order part of the
                                 * significand in the first word of a
                                 * double. */
 #define SIG_MASK       (((Tcl_WideUInt) HI_ORDER_SIG_MASK << 32) \
-                       | 0xffffffff)
+                       | 0xFFFFFFFF)
                                /* Mask for the 52-bit significand. */
 #define FP_PRECISION   53      /* Number of bits of significand plus the
                                 * hidden bit. */
-#define EXPONENT_BIAS  0x3ff   /* Bias of the exponent 0. */
+#define EXPONENT_BIAS  0x3FF   /* Bias of the exponent 0. */
 
 /*
  * Derived quantities.
@@ -296,10 +301,10 @@ static const Tcl_WideUInt wuipow5[27] = {
 static int             AccumulateDecimalDigit(unsigned, int,
                            Tcl_WideUInt *, mp_int *, int);
 static double          MakeHighPrecisionDouble(int signum,
-                           mp_int *significand, int nSigDigs, int exponent);
+                           mp_int *significand, int nSigDigs, long exponent);
 static double          MakeLowPrecisionDouble(int signum,
                            Tcl_WideUInt significand, int nSigDigs,
-                           int exponent);
+                           long exponent);
 #ifdef IEEE_FLOATING_POINT
 static double          MakeNaN(int signum, Tcl_WideUInt tag);
 #endif
@@ -563,7 +568,7 @@ TclParseNumber(
             * I, N, and whitespace.
             */
 
-           if (TclIsSpaceProc(c)) {
+           if (TclIsSpaceProcM(c)) {
                if (flags & TCL_PARSE_NO_WHITESPACE) {
                    goto endgame;
                }
@@ -836,6 +841,7 @@ TclParseNumber(
            acceptState = state;
            acceptPoint = p;
            acceptLen = len;
+           /* FALLTHRU */
        case ZERO_B:
        zerob:
            if (c == '0') {
@@ -1089,7 +1095,7 @@ TclParseNumber(
            }
            /* FALLTHROUGH */
        case sNANPAREN:
-           if (TclIsSpaceProc(c)) {
+           if (TclIsSpaceProcM(c)) {
                break;
            }
            if (numSigDigs < 13) {
@@ -1143,7 +1149,7 @@ TclParseNumber(
             * Accept trailing whitespace.
             */
 
-           while (len != 0 && TclIsSpaceProc(*p)) {
+           while (len != 0 && TclIsSpaceProcM(*p)) {
                p++;
                len--;
            }
@@ -1277,7 +1283,7 @@ TclParseNumber(
            }
            if (octalSignificandOverflow) {
                if (signum) {
-                   mp_neg(&octalSignificandBig, &octalSignificandBig);
+                   (void)mp_neg(&octalSignificandBig, &octalSignificandBig);
                }
                TclSetBignumIntRep(objPtr, &octalSignificandBig);
            }
@@ -1287,7 +1293,7 @@ TclParseNumber(
        case DECIMAL:
            significandOverflow = AccumulateDecimalDigit(0, numTrailZeros-1,
                    &significandWide, &significandBig, significandOverflow);
-           if (!significandOverflow && (significandWide > MOST_BITS+signum)){
+           if (!significandOverflow && (significandWide > MOST_BITS+signum)) {
                significandOverflow = 1;
                TclBNInitBignumFromWideUInt(&significandBig, significandWide);
            }
@@ -1324,7 +1330,7 @@ TclParseNumber(
            }
            if (significandOverflow) {
                if (signum) {
-                   mp_neg(&significandBig, &significandBig);
+                   (void)mp_neg(&significandBig, &significandBig);
                }
                TclSetBignumIntRep(objPtr, &significandBig);
            }
@@ -1343,16 +1349,45 @@ TclParseNumber(
 
            objPtr->typePtr = &tclDoubleType;
            if (exponentSignum) {
+               /*
+                * At this point exponent>=0, so the following calculation
+                * cannot underflow.
+                */
                exponent = -exponent;
            }
+
+           /*
+            * Adjust the exponent for the number of trailing zeros that
+            * have not been accumulated, and the number of digits after
+            * the decimal point. Pin any overflow to LONG_MAX/LONG_MIN
+            * respectively.
+            */
+
+           if (exponent >= 0) {
+               if (exponent - numDigitsAfterDp > LONG_MAX - numTrailZeros) {
+                   exponent = LONG_MAX;
+               } else {
+                   exponent = exponent - numDigitsAfterDp + numTrailZeros;
+               }
+           } else {
+               if (exponent + numTrailZeros < LONG_MIN + numDigitsAfterDp) {
+                   exponent = LONG_MIN;
+               } else {
+                   exponent = exponent + numTrailZeros - numDigitsAfterDp;
+               }
+           }
+
+           /*
+            * The desired number is now significandWide * 10**exponent
+            * or significandBig * 10**exponent, depending on whether
+            * the significand has overflowed a wide int.
+            */
            if (!significandOverflow) {
                objPtr->internalRep.doubleValue = MakeLowPrecisionDouble(
-                       signum, significandWide, numSigDigs,
-                       numTrailZeros + exponent - numDigitsAfterDp);
+                       signum, significandWide, numSigDigs, exponent);
            } else {
                objPtr->internalRep.doubleValue = MakeHighPrecisionDouble(
-                       signum, &significandBig, numSigDigs,
-                       numTrailZeros + exponent - numDigitsAfterDp);
+                       signum, &significandBig, numSigDigs, exponent);
            }
            break;
 
@@ -1369,7 +1404,7 @@ TclParseNumber(
 #ifdef IEEE_FLOATING_POINT
        case sNAN:
        case sNANFINISH:
-           objPtr->internalRep.doubleValue = MakeNaN(signum,significandWide);
+           objPtr->internalRep.doubleValue = MakeNaN(signum, significandWide);
            objPtr->typePtr = &tclDoubleType;
            break;
 #endif
@@ -1536,9 +1571,9 @@ AccumulateDecimalDigit(
 static double
 MakeLowPrecisionDouble(
     int signum,                        /* 1 if the number is negative, 0 otherwise */
-    Tcl_WideUInt significand,  /* Significand of the number. */
-    int numSigDigs,            /* Number of digits in the significand. */
-    int exponent)              /* Power of ten. */
+    Tcl_WideUInt significand,  /* Significand of the number */
+    int numSigDigs,            /* Number of digits in the significand */
+    long exponent)             /* Power of ten */
 {
     double retval;             /* Value of the number. */
     mp_int significandBig;     /* Significand expressed as a bignum. */
@@ -1557,6 +1592,9 @@ MakeLowPrecisionDouble(
      * Test for the easy cases.
      */
 
+    if (significand == 0) {
+       return copysign(0.0, -signum);
+    }
     if (numSigDigs <= QUICK_MAX) {
        if (exponent >= 0) {
            if (exponent <= mmaxpow) {
@@ -1649,10 +1687,10 @@ MakeLowPrecisionDouble(
 
 static double
 MakeHighPrecisionDouble(
-    int signum,                        /* 1=negative, 0=nonnegative. */
-    mp_int *significand,       /* Exact significand of the number. */
-    int numSigDigs,            /* Number of significant digits. */
-    int exponent)              /* Power of 10 by which to multiply. */
+    int signum,                        /* 1=negative, 0=nonnegative */
+    mp_int *significand,       /* Exact significand of the number */
+    int numSigDigs,            /* Number of significant digits */
+    long exponent)             /* Power of 10 by which to multiply */
 {
     double retval;
     int machexp;               /* Machine exponent of a power of 10. */
@@ -1668,15 +1706,18 @@ MakeHighPrecisionDouble(
     TCL_IEEE_DOUBLE_ROUNDING;
 
     /*
-     * Quick checks for over/underflow.
+     * Quick checks for zero, and over/underflow. Be careful to avoid
+     * integer overflow when calculating with 'exponent'.
      */
 
-    if (numSigDigs+exponent-1 > maxDigits) {
+    if (mp_iszero(significand)) {
+       return copysign(0.0, -signum);
+    }
+    if (exponent >= 0 && exponent-1 > maxDigits-numSigDigs) {
        retval = HUGE_VAL;
        goto returnValue;
-    }
-    if (numSigDigs+exponent-1 < minDigits) {
-       retval = 0;
+    } else if (exponent < 0 && numSigDigs+exponent < minDigits+1) {
+       retval = 0.0;
        goto returnValue;
     }
 
@@ -1811,6 +1852,9 @@ RefineApproximation(
                                 * "round to even" functionality */
     double rteSignificand;     /* Significand of the round-to-even result */
     int rteExponent;           /* Exponent of the round-to-even result */
+    int shift;                 /* Shift count for converting numerator
+                                * and denominator of corrector to floating
+                                * point */
     Tcl_WideInt rteSigWide;    /* Wide integer version of the significand
                                 * for testing evenness */
     int i;
@@ -1823,13 +1867,22 @@ RefineApproximation(
     if (approxResult == HUGE_VAL) {
        return approxResult;
     }
+    significand = frexp(approxResult, &binExponent);
 
     /*
-     * Find a common denominator for the decimal and binary fractions. The
-     * common denominator will be 2**M2 + 5**M5.
+     * We are trying to compute a corrector term that, when added to the
+     * approximate result, will yield close to the exact result.
+     * The exact result is exactSignificand * 10**exponent.
+     * The approximate result is significand * 2**binExponent
+     * If exponent<0, we need to multiply the exact value by 10**-exponent
+     * to make it an integer, plus another factor of 2 to decide on rounding.
+     *  Similarly if binExponent<FP_PRECISION, we need
+     * to multiply by 2**FP_PRECISION to make the approximate value an integer.
+     *
+     * Let M = 2**M2 * 5**M5 be the least common multiple of these two
+     * multipliers.
      */
 
-    significand = frexp(approxResult, &binExponent);
     i = mantBits - binExponent;
     if (i < 0) {
        M2 = 0;
@@ -1846,12 +1899,9 @@ RefineApproximation(
     }
 
     /*
-     * The floating point number is significand*2**binExponent. Compute the
-     * large integer significand*2**(binExponent+M2+1). The 2**-1 bit of the
-     * significand (the most significant) corresponds to the
-     * 2**(binExponent+M2 + 1) bit of 2*M2*v. Allocate enough digits to hold
-     * that quantity, then convert the significand to a large integer, scaled
-     * appropriately. Then multiply by the appropriate power of 5.
+     * Compute twoMv as 2*M*v, where v is the approximate value.
+     * This is done by bit-whacking to calculate 2**(M2+1)*significand,
+     * and then multiplying by 5**M5.
      */
 
     msb = binExponent + M2;    /* 1008 */
@@ -1872,10 +1922,9 @@ RefineApproximation(
     }
 
     /*
-     * Collect the decimal significand as a high precision integer. The least
-     * significant bit corresponds to bit M2+exponent+1 so it will need to be
-     * shifted left by that many bits after being multiplied by
-     * 5**(M5+exponent).
+     * Compute twoMd as 2*M*d, where d is the exact value.
+     * This is done by multiplying by 5**(M5+exponent) and then multiplying
+     * by 2**(M5+exponent+1), which is, of couse, a left shift.
      */
 
     mp_init_copy(&twoMd, exactSignificand);
@@ -1885,16 +1934,22 @@ RefineApproximation(
        }
     }
     mp_mul_2d(&twoMd, M2+exponent+1, &twoMd);
+
+    /*
+     * Now let twoMd = twoMd - twoMv, the difference between the exact and
+     * approximate values.
+     */
+
     mp_sub(&twoMd, &twoMv, &twoMd);
 
     /*
      * The result, 2Mv-2Md, needs to be divided by 2M to yield a correction
      * term. Because 2M may well overflow a double, we need to scale the
-     * denominator by a factor of 2**binExponent-mantBits.
+     * denominator by a factor of 2**binExponent-mantBits. Place that factor
+     * times 1/2 ULP into twoMd.
      */
 
     scale = binExponent - mantBits - 1;
-
     mp_set(&twoMv, 1);
     for (i=0; i<=8; ++i) {
        if (M5 & (1 << i)) {
@@ -1908,25 +1963,36 @@ RefineApproximation(
        mp_div_2d(&twoMv, -multiplier, &twoMv, NULL);
     }
 
+    /*
+     * Will the eventual correction term be less than, equal to, or
+     * greater than 1/2 ULP?
+     */
+
     switch (mp_cmp_mag(&twoMd, &twoMv)) {
     case MP_LT:
        /*
-        * If the result is less than unity, the error is less than 1/2 unit in
-        * the last place, so there's no correction to make.
+        * If the error is less than 1/2 ULP, there's no correction to make.
         */
        mp_clear(&twoMd);
        mp_clear(&twoMv);
        return approxResult;
     case MP_EQ:
        /*
-        * If the result is exactly unity, we need to round to even.
+        * If the error is exactly 1/2 ULP, we need to round to even.
         */
        roundToEven = 1;
        break;
     case MP_GT:
+       /*
+        * We need to correct the result if the error exceeds 1/2 ULP.
+        */
        break;
     }
 
+    /*
+     * If we're in the 'round to even' case, and the significand is already
+     * even, we're done. Return the approximate result.
+     */
     if (roundToEven) {
        rteSignificand = frexp(approxResult, &rteExponent);
        rteSigWide = (Tcl_WideInt) ldexp(rteSignificand, FP_PRECISION);
@@ -1938,6 +2004,16 @@ RefineApproximation(
     }
 
     /*
+     * Reduce the numerator and denominator of the corrector term so that
+     * they will fit in the floating point precision.
+     */
+    shift = mp_count_bits(&twoMv) - FP_PRECISION - 1;
+    if (shift > 0) {
+       mp_div_2d(&twoMv, shift, &twoMv, NULL);
+       mp_div_2d(&twoMd, shift, &twoMd, NULL);
+    }
+
+    /*
      * Convert the numerator and denominator of the corrector term accurately
      * to floating point numbers.
      */
@@ -2025,16 +2101,16 @@ NormalizeRightward(
     int rv = 0;
     Tcl_WideUInt w = *wPtr;
 
-    if (!(w & (Tcl_WideUInt) 0xffffffff)) {
+    if (!(w & (Tcl_WideUInt) 0xFFFFFFFF)) {
        w >>= 32; rv += 32;
     }
-    if (!(w & (Tcl_WideUInt) 0xffff)) {
+    if (!(w & (Tcl_WideUInt) 0xFFFF)) {
        w >>= 16; rv += 16;
     }
-    if (!(w & (Tcl_WideUInt) 0xff)) {
+    if (!(w & (Tcl_WideUInt) 0xFF)) {
        w >>= 8; rv += 8;
     }
-    if (!(w & (Tcl_WideUInt) 0xf)) {
+    if (!(w & (Tcl_WideUInt) 0xF)) {
        w >>= 4; rv += 4;
     }
     if (!(w & 0x3)) {
@@ -2068,21 +2144,21 @@ RequiredPrecision(
     int rv;
     unsigned long wi;
 
-    if (w & ((Tcl_WideUInt) 0xffffffff << 32)) {
+    if (w & ((Tcl_WideUInt) 0xFFFFFFFF << 32)) {
        wi = (unsigned long) (w >> 32); rv = 32;
     } else {
        wi = (unsigned long) w; rv = 0;
     }
-    if (wi & 0xffff0000) {
+    if (wi & 0xFFFF0000) {
        wi >>= 16; rv += 16;
     }
-    if (wi & 0xff00) {
+    if (wi & 0xFF00) {
        wi >>= 8; rv += 8;
     }
-    if (wi & 0xf0) {
+    if (wi & 0xF0) {
        wi >>= 4; rv += 4;
     }
-    if (wi & 0xc) {
+    if (wi & 0xC) {
        wi >>= 2; rv += 2;
     }
     if (wi & 0x2) {
@@ -2527,7 +2603,7 @@ AdjustRange(
         * The number must be reduced to bring it into range.
         */
 
-       ds = tens[k & 0xf];
+       ds = tens[k & 0xF];
        j = k >> 4;
        if (j & BLETCH) {
            j &= (BLETCH-1);
@@ -2548,7 +2624,7 @@ AdjustRange(
         * The number must be increased to bring it into range.
         */
 
-       d *= tens[j1 & 0xf];
+       d *= tens[j1 & 0xF];
        i = 0;
        for (j = j1>>4; j; j>>=1) {
            if (j & 1) {
@@ -2773,7 +2849,7 @@ QuickConversion(
        }
        ilim = ilim1;
        --k;
-       d *= 10.0;
+       d = d * 10.0;
        ++ieps;
     }
 
@@ -2790,7 +2866,7 @@ QuickConversion(
 
     retval = ckalloc(len + 1);
     if (ilim == 0) {
-       d -= 5.;
+       d = d - 5.;
        if (d > eps.d) {
            *retval = '1';
            *decpt = k;
@@ -4392,7 +4468,8 @@ TclInitDoubleConversion(void)
 
     maxpow10_wide = (int)
            floor(sizeof(Tcl_WideUInt) * CHAR_BIT * log(2.) / log(10.));
-    pow10_wide = ckalloc((maxpow10_wide + 1) * sizeof(Tcl_WideUInt));
+    pow10_wide = (Tcl_WideUInt *)
+           ckalloc((maxpow10_wide + 1) * sizeof(Tcl_WideUInt));
     u = 1;
     for (i = 0; i < maxpow10_wide; ++i) {
        pow10_wide[i] = u;
@@ -4468,9 +4545,9 @@ TclInitDoubleConversion(void)
 #ifdef IEEE_FLOATING_POINT
     bitwhack.dv = 1.000000238418579;
                                /* 3ff0 0000 4000 0000 */
-    if ((bitwhack.iv >> 32) == 0x3ff00000) {
+    if ((bitwhack.iv >> 32) == 0x3FF00000) {
        n770_fp = 0;
-    } else if ((bitwhack.iv & 0xffffffff) == 0x3ff00000) {
+    } else if ((bitwhack.iv & 0xFFFFFFFF) == 0x3FF00000) {
        n770_fp = 1;
     } else {
        Tcl_Panic("unknown floating point word order on this machine");
@@ -4720,7 +4797,7 @@ TclCeil(
                mp_int d;
                mp_init(&d);
                mp_div_2d(a, -shift, &b, &d);
-               exact = d.used == 0;
+               exact = mp_iszero(&d);
                mp_clear(&d);
            } else {
                mp_copy(a, &b);
@@ -4889,7 +4966,7 @@ Pow10TimesFrExp(
         * Multiply by 10**exponent.
         */
 
-       retval = frexp(retval * pow10vals[exponent&0xf], &j);
+       retval = frexp(retval * pow10vals[exponent&0xF], &j);
        expt += j;
        for (i=4; i<9; ++i) {
            if (exponent & (1<<i)) {
@@ -4902,7 +4979,7 @@ Pow10TimesFrExp(
         * Divide by 10**-exponent.
         */
 
-       retval = frexp(retval / pow10vals[(-exponent) & 0xf], &j);
+       retval = frexp(retval / pow10vals[(-exponent) & 0xF], &j);
        expt += j;
        for (i=4; i<9; ++i) {
            if ((-exponent) & (1<<i)) {
@@ -5018,7 +5095,7 @@ static Tcl_WideUInt
 Nokia770Twiddle(
     Tcl_WideUInt w)            /* Number to transpose. */
 {
-    return (((w >> 32) & 0xffffffff) | (w << 32));
+    return (((w >> 32) & 0xFFFFFFFF) | (w << 32));
 }
 #endif
 \f
index e4db140..33b2139 100644 (file)
@@ -149,9 +149,9 @@ GrowStringBuffer(
        objPtr->bytes = NULL;
     }
     if (flag == 0 || stringPtr->allocated > 0) {
-       attempt = 2 * needed;
-       if (attempt >= 0) {
-           ptr = attemptckrealloc(objPtr->bytes, attempt + 1);
+       if (needed <= INT_MAX / 2) {
+           attempt = 2 * needed;
+           ptr = (char *)attemptckrealloc(objPtr->bytes, attempt + 1);
        }
        if (ptr == NULL) {
            /*
@@ -164,7 +164,7 @@ GrowStringBuffer(
            int growth = (int) ((extra > limit) ? limit : extra);
 
            attempt = needed + growth;
-           ptr = attemptckrealloc(objPtr->bytes, attempt + 1);
+           ptr = (char *)attemptckrealloc(objPtr->bytes, attempt + 1);
        }
     }
     if (ptr == NULL) {
@@ -173,7 +173,7 @@ GrowStringBuffer(
         */
 
        attempt = needed;
-       ptr = ckrealloc(objPtr->bytes, attempt + 1);
+       ptr = (char *)ckrealloc(objPtr->bytes, attempt + 1);
     }
     objPtr->bytes = ptr;
     stringPtr->allocated = attempt;
@@ -199,8 +199,8 @@ GrowUnicodeBuffer(
         * Subsequent appends - apply the growth algorithm.
         */
 
-       attempt = 2 * needed;
-       if (attempt >= 0 && attempt <= STRING_MAXCHARS) {
+       if (needed <= STRING_MAXCHARS / 2) {
+           attempt = 2 * needed;
            ptr = stringAttemptRealloc(stringPtr, attempt);
        }
        if (ptr == NULL) {
@@ -418,6 +418,15 @@ Tcl_GetCharLength(
     int numChars;
 
     /*
+     * Quick, no-shimmer return for short string reps.
+     */
+
+    if ((objPtr->bytes) && (objPtr->length < 2)) {
+       /* 0 bytes -> 0 chars; 1 byte -> 1 char */
+       return objPtr->length;
+    }
+
+    /*
      * Optimize the case where we're really dealing with a bytearray object;
      * we don't need to convert to a string to perform the get-length operation.
      *
@@ -434,7 +443,6 @@ Tcl_GetCharLength(
        return length;
     }
 
-
     /*
      * OK, need to work with the object as a string.
      */
@@ -465,8 +473,6 @@ Tcl_GetCharLength(
     }
     return numChars;
 }
-
-
 \f
 /*
  *----------------------------------------------------------------------
@@ -486,8 +492,8 @@ Tcl_GetCharLength(
  */
 int
 TclCheckEmptyString (
-    Tcl_Obj *objPtr
-{
+    Tcl_Obj *objPtr)
+{
     int length = -1;
 
     if (objPtr->bytes == tclEmptyStringRep) {
@@ -513,10 +519,10 @@ TclCheckEmptyString (
 /*
  *----------------------------------------------------------------------
  *
- * Tcl_GetUniChar --
+ * Tcl_GetUniChar/TclGetUCS4 --
  *
- *     Get the index'th Unicode character from the String object. The index
- *     is assumed to be in the appropriate range.
+ *     Get the index'th Unicode character from the String object. If index
+ *     is out of range, the result = 0xFFFD (Tcl_GetUniChar) resp. -1 (TclGetUCS4)
  *
  * Results:
  *     Returns the index'th Unicode character in the Object.
@@ -534,15 +540,22 @@ Tcl_GetUniChar(
     int index)                 /* Get the index'th Unicode character. */
 {
     String *stringPtr;
+    int length;
+
+    if (index < 0) {
+       return 0xFFFD;
+    }
 
     /*
      * Optimize the case where we're really dealing with a bytearray object
-     * without string representation; we don't need to convert to a string to
-     * perform the indexing operation.
+     * we don't need to convert to a string to perform the indexing operation.
      */
 
     if (TclIsPureByteArray(objPtr)) {
-       unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, NULL);
+       unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
+       if (index >= length) {
+               return 0xFFFD;
+       }
 
        return (Tcl_UniChar) bytes[index];
     }
@@ -568,8 +581,86 @@ Tcl_GetUniChar(
        FillUnicodeRep(objPtr);
        stringPtr = GET_STRING(objPtr);
     }
+
+    if (index >= stringPtr->numChars) {
+       return 0xFFFD;
+    }
     return stringPtr->unicode[index];
 }
+
+#if TCL_UTF_MAX == 4
+int
+TclGetUCS4(
+    Tcl_Obj *objPtr,           /* The object to get the Unicode charater
+                                * from. */
+    int index)                 /* Get the index'th Unicode character. */
+{
+    String *stringPtr;
+    int ch, length;
+
+    if (index < 0) {
+       return -1;
+    }
+
+    /*
+     * Optimize the case where we're really dealing with a bytearray object
+     * we don't need to convert to a string to perform the indexing operation.
+     */
+
+    if (TclIsPureByteArray(objPtr)) {
+       unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
+       if (index >= length) {
+               return -1;
+       }
+
+       return (int) bytes[index];
+    }
+
+    /*
+     * OK, need to work with the object as a string.
+     */
+
+    SetStringFromAny(NULL, objPtr);
+    stringPtr = GET_STRING(objPtr);
+
+    if (stringPtr->hasUnicode == 0) {
+       /*
+        * If numChars is unknown, compute it.
+        */
+
+       if (stringPtr->numChars == -1) {
+           TclNumUtfChars(stringPtr->numChars, objPtr->bytes, objPtr->length);
+       }
+       if (stringPtr->numChars == objPtr->length) {
+           return (Tcl_UniChar) objPtr->bytes[index];
+       }
+       FillUnicodeRep(objPtr);
+       stringPtr = GET_STRING(objPtr);
+    }
+
+    if (index >= stringPtr->numChars) {
+       return -1;
+    }
+    ch = stringPtr->unicode[index];
+#if TCL_UTF_MAX <= 4
+    /* See: bug [11ae2be95dac9417] */
+    if ((ch & 0xF800) == 0xD800) {
+       if (ch & 0x400) {
+           if ((index > 0)
+                   && ((stringPtr->unicode[index-1] & 0xFC00) == 0xD800)) {
+               ch = -1; /* low surrogate preceded by high surrogate */
+           }
+       } else if ((++index < stringPtr->numChars)
+               && ((stringPtr->unicode[index] & 0xFC00) == 0xDC00)) {
+           /* high surrogate followed by low surrogate */
+           ch = (((ch & 0x3FF) << 10) |
+                       (stringPtr->unicode[index] & 0x3FF)) + 0x10000;
+       }
+    }
+#endif
+    return ch;
+}
+#endif
 \f
 /*
  *----------------------------------------------------------------------
@@ -668,17 +759,27 @@ Tcl_GetRange(
 {
     Tcl_Obj *newObjPtr;                /* The Tcl object to find the range of. */
     String *stringPtr;
+    int length;
+
+    if (first < 0) {
+       first = 0;
+    }
 
     /*
      * Optimize the case where we're really dealing with a bytearray object
-     * without string representation; we don't need to convert to a string to
-     * perform the substring operation.
+     * we don't need to convert to a string to perform the substring operation.
      */
 
     if (TclIsPureByteArray(objPtr)) {
-       unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, NULL);
+       unsigned char *bytes = Tcl_GetByteArrayFromObj(objPtr, &length);
 
-       return Tcl_NewByteArrayObj(bytes+first, last-first+1);
+       if (last >= length) {
+           last = length - 1;
+       }
+       if (last < first) {
+           return Tcl_NewObj();
+       }
+       return Tcl_NewByteArrayObj(bytes + first, last - first + 1);
     }
 
     /*
@@ -697,6 +798,12 @@ Tcl_GetRange(
            TclNumUtfChars(stringPtr->numChars, objPtr->bytes, objPtr->length);
        }
        if (stringPtr->numChars == objPtr->length) {
+           if (last >= stringPtr->numChars) {
+               last = stringPtr->numChars - 1;
+           }
+           if (last < first) {
+               return Tcl_NewObj();
+           }
            newObjPtr = Tcl_NewStringObj(objPtr->bytes + first, last-first+1);
 
            /*
@@ -711,19 +818,25 @@ Tcl_GetRange(
        FillUnicodeRep(objPtr);
        stringPtr = GET_STRING(objPtr);
     }
-
+    if (last > stringPtr->numChars) {
+       last = stringPtr->numChars;
+    }
+    if (last < first) {
+       return Tcl_NewObj();
+    }
 #if TCL_UTF_MAX == 4
-       /* See: bug [11ae2be95dac9417] */
-       if ((first>0) && ((stringPtr->unicode[first]&0xFC00) == 0xDC00)
-               && ((stringPtr->unicode[first-1]&0xFC00) == 0xD800)) {
-           ++first;
-       }
-       if ((last+1<stringPtr->numChars) && ((stringPtr->unicode[last+1]&0xFC00) == 0xDC00)
-               && ((stringPtr->unicode[last]&0xFC00) == 0xD800)) {
-           ++last;
-       }
+    /* See: bug [11ae2be95dac9417] */
+    if ((first > 0) && ((stringPtr->unicode[first] & 0xFC00) == 0xDC00)
+               && ((stringPtr->unicode[first-1] & 0xFC00) == 0xD800)) {
+       ++first;
+    }
+    if ((last + 1 < stringPtr->numChars)
+               && ((stringPtr->unicode[last+1] & 0xFC00) == 0xDC00)
+               && ((stringPtr->unicode[last] & 0xFC00) == 0xD800)) {
+       ++last;
+    }
 #endif
-    return Tcl_NewUnicodeObj(stringPtr->unicode + first, last-first+1);
+    return Tcl_NewUnicodeObj(stringPtr->unicode + first, last - first + 1);
 }
 \f
 /*
@@ -840,9 +953,9 @@ Tcl_SetObjLength(
             * Need to enlarge the buffer.
             */
            if (objPtr->bytes == tclEmptyStringRep) {
-               objPtr->bytes = ckalloc(length + 1);
+               objPtr->bytes = (char *)ckalloc(length + 1);
            } else {
-               objPtr->bytes = ckrealloc(objPtr->bytes, length + 1);
+               objPtr->bytes = (char *)ckrealloc(objPtr->bytes, length + 1);
            }
            stringPtr->allocated = length;
        }
@@ -946,9 +1059,9 @@ Tcl_AttemptSetObjLength(
            char *newBytes;
 
            if (objPtr->bytes == tclEmptyStringRep) {
-               newBytes = attemptckalloc(length + 1);
+               newBytes = (char *)attemptckalloc(length + 1);
            } else {
-               newBytes = attemptckrealloc(objPtr->bytes, length + 1);
+               newBytes = (char *)attemptckrealloc(objPtr->bytes, length + 1);
            }
            if (newBytes == NULL) {
                return 0;
@@ -1112,10 +1225,7 @@ Tcl_AppendLimitedToObj(
 {
     String *stringPtr;
     int toCopy = 0;
-
-    if (Tcl_IsShared(objPtr)) {
-       Tcl_Panic("%s called with shared object", "Tcl_AppendLimitedToObj");
-    }
+    int eLen = 0;
 
     if (length < 0) {
        length = (bytes ? strlen(bytes) : 0);
@@ -1123,6 +1233,9 @@ Tcl_AppendLimitedToObj(
     if (length == 0) {
        return;
     }
+    if (limit <= 0) {
+       return;
+    }
 
     if (length <= limit) {
        toCopy = length;
@@ -1130,8 +1243,12 @@ Tcl_AppendLimitedToObj(
        if (ellipsis == NULL) {
            ellipsis = "...";
        }
-       toCopy = (bytes == NULL) ? limit
-               : Tcl_UtfPrev(bytes+limit+1-strlen(ellipsis), bytes) - bytes;
+       eLen = strlen(ellipsis);
+       while (eLen > limit) {
+           eLen = TclUtfPrev(ellipsis+eLen, ellipsis) - ellipsis;
+       }
+
+       toCopy = TclUtfPrev(bytes+limit+1-eLen, bytes) - bytes;
     }
 
     /*
@@ -1140,6 +1257,10 @@ Tcl_AppendLimitedToObj(
      * objPtr's string rep.
      */
 
+    if (Tcl_IsShared(objPtr)) {
+       Tcl_Panic("%s called with shared object", "Tcl_AppendLimitedToObj");
+    }
+
     SetStringFromAny(NULL, objPtr);
     stringPtr = GET_STRING(objPtr);
 
@@ -1155,9 +1276,9 @@ Tcl_AppendLimitedToObj(
 
     stringPtr = GET_STRING(objPtr);
     if (stringPtr->hasUnicode && stringPtr->numChars > 0) {
-       AppendUtfToUnicodeRep(objPtr, ellipsis, strlen(ellipsis));
+       AppendUtfToUnicodeRep(objPtr, ellipsis, eLen);
     } else {
-       AppendUtfToUtfRep(objPtr, ellipsis, strlen(ellipsis));
+       AppendUtfToUtfRep(objPtr, ellipsis, eLen);
     }
 }
 \f
@@ -1291,39 +1412,45 @@ Tcl_AppendObjToObj(
 
     if ((TclIsPureByteArray(objPtr) || objPtr->bytes == tclEmptyStringRep)
            && TclIsPureByteArray(appendObjPtr)) {
-
        /*
         * You might expect the code here to be
         *
         *  bytes = Tcl_GetByteArrayFromObj(appendObjPtr, &length);
         *  TclAppendBytesToByteArray(objPtr, bytes, length);
         *
-        * and essentially all of the time that would be fine.  However,
-        * it would run into trouble in the case where objPtr and
-        * appendObjPtr point to the same thing.  That may never be a
-        * good idea.  It seems to violate Copy On Write, and we don't
-        * have any tests for the situation, since making any Tcl commands
-        * that call Tcl_AppendObjToObj() do that appears impossible
-        * (They honor Copy On Write!).  For the sake of extensions that
-        * go off into that realm, though, here's a more complex approach
-        * that can handle all the cases.
+        * and essentially all of the time that would be fine. However, it
+        * would run into trouble in the case where objPtr and appendObjPtr
+        * point to the same thing. That may never be a good idea. It seems to
+        * violate Copy On Write, and we don't have any tests for the
+        * situation, since making any Tcl commands that call
+        * Tcl_AppendObjToObj() do that appears impossible (They honor Copy On
+        * Write!). For the sake of extensions that go off into that realm,
+        * though, here's a more complex approach that can handle all the
+        * cases.
+        *
+        * First, get the lengths.
         */
 
-       /* Get lengths */
        int lengthSrc;
 
        (void) Tcl_GetByteArrayFromObj(objPtr, &length);
        (void) Tcl_GetByteArrayFromObj(appendObjPtr, &lengthSrc);
 
-       /* Grow buffer enough for the append */
+       /*
+        * Grow buffer enough for the append.
+        */
+
        TclAppendBytesToByteArray(objPtr, NULL, lengthSrc);
 
-       /* Reset objPtr back to the original value */
+       /*
+        * Reset objPtr back to the original value.
+        */
+
        Tcl_SetByteArrayLength(objPtr, length);
 
        /*
-        * Now do the append knowing that buffer growth cannot cause
-        * any trouble.
+        * Now do the append knowing that buffer growth cannot cause any
+        * trouble.
         */
 
        TclAppendBytesToByteArray(objPtr,
@@ -1375,6 +1502,7 @@ Tcl_AppendObjToObj(
     numChars = stringPtr->numChars;
     if ((numChars >= 0) && (appendObjPtr->typePtr == &tclStringType)) {
        String *appendStringPtr = GET_STRING(appendObjPtr);
+
        appendNumChars = appendStringPtr->numChars;
     }
 
@@ -1994,7 +2122,7 @@ Tcl_AppendFormatToObj(
            }
            break;
        case 'c': {
-           char buf[TCL_UTF_MAX];
+           char buf[4] = "";
            int code, length;
 
            if (TclGetIntFromObj(interp, segment, &code) != TCL_OK) {
@@ -2081,7 +2209,7 @@ Tcl_AppendFormatToObj(
                isNegative = (l < (long) 0);
            }
 
-           segment = Tcl_NewObj();
+           TclNewObj(segment);
            allocSegment = 1;
            segmentLimit = INT_MAX;
            Tcl_IncrRefCount(segment);
@@ -2121,7 +2249,7 @@ Tcl_AppendFormatToObj(
                const char *bytes;
 
                if (useShort) {
-                   pure = Tcl_NewIntObj((int) s);
+                   TclNewIntObj(pure, (int) s);
 #ifndef TCL_WIDE_INT_IS_LONG
                } else if (useWide) {
                    pure = Tcl_NewWideIntObj(w);
@@ -2250,7 +2378,7 @@ Tcl_AppendFormatToObj(
                if ((numDigits == 0) && !((ch == 'o') && gotHash)) {
                    numDigits = 1;
                }
-               pure = Tcl_NewObj();
+               TclNewObj(pure);
                Tcl_SetObjLength(pure, (int) numDigits);
                bytes = TclGetString(pure);
                toAppend = length = (int) numDigits;
@@ -2369,7 +2497,7 @@ Tcl_AppendFormatToObj(
            *p++ = (char) ch;
            *p = '\0';
 
-           segment = Tcl_NewObj();
+           TclNewObj(segment);
            allocSegment = 1;
            if (!Tcl_AttemptSetObjLength(segment, length)) {
                msg = overflow;
@@ -2458,7 +2586,7 @@ Tcl_AppendFormatToObj(
 /*
  *---------------------------------------------------------------------------
  *
- * Tcl_Format--
+ * Tcl_Format --
  *
  * Results:
  *     A refcount zero Tcl_Obj.
@@ -2477,8 +2605,9 @@ Tcl_Format(
     Tcl_Obj *const objv[])
 {
     int result;
-    Tcl_Obj *objPtr = Tcl_NewObj();
+    Tcl_Obj *objPtr;
 
+    TclNewObj(objPtr);
     result = Tcl_AppendFormatToObj(interp, objPtr, format, objc, objv);
     if (result != TCL_OK) {
        Tcl_DecrRefCount(objPtr);
@@ -2506,9 +2635,10 @@ AppendPrintfToObjVA(
     va_list argList)
 {
     int code, objc;
-    Tcl_Obj **objv, *list = Tcl_NewObj();
+    Tcl_Obj **objv, *list;
     const char *p;
 
+    TclNewObj(list);
     p = format;
     Tcl_IncrRefCount(list);
     while (*p != '\0') {
@@ -2548,7 +2678,7 @@ AppendPrintfToObjVA(
                 * multi-byte characters.
                 */
 
-               q = Tcl_UtfPrev(end, bytes);
+               q = TclUtfPrev(end, bytes);
                if (!Tcl_UtfCharComplete(q, (int)(end - q))) {
                    end = q;
                }
@@ -2680,8 +2810,9 @@ Tcl_ObjPrintf(
     ...)
 {
     va_list argList;
-    Tcl_Obj *objPtr = Tcl_NewObj();
+    Tcl_Obj *objPtr;
 
+    TclNewObj(objPtr);
     va_start(argList, format);
     AppendPrintfToObjVA(objPtr, format, argList);
     va_end(argList);
@@ -2723,7 +2854,7 @@ TclGetStringStorage(
 /*
  *---------------------------------------------------------------------------
  *
- * TclStringObjReverse --
+ * TclStringReverse --
  *
  *     Implements the [string reverse] operation.
  *
@@ -2742,18 +2873,20 @@ static void
 ReverseBytes(
     unsigned char *to,         /* Copy bytes into here... */
     unsigned char *from,       /* ...from here... */
-    int count)         /* Until this many are copied, */
+    int count)                 /* Until this many are copied, */
                                /* reversing as you go. */
 {
     unsigned char *src = from + count;
+
     if (to == from) {
        /* Reversing in place */
        while (--src > to) {
            unsigned char c = *src;
+
            *src = *to;
            *to++ = c;
        }
-    }  else {
+    } else {
        while (--src >= from) {
            *to++ = *src;
        }
@@ -2761,7 +2894,7 @@ ReverseBytes(
 }
 
 Tcl_Obj *
-TclStringObjReverse(
+TclStringReverse(
     Tcl_Obj *objPtr)
 {
     String *stringPtr;
@@ -2800,7 +2933,10 @@ TclStringObjReverse(
                *to++ = *src;
            }
        } else {
-           /* Reversing in place */
+           /*
+            * Reversing in place.
+            */
+
            while (--src > from) {
                ch = *src;
                *src = *from;
@@ -2815,7 +2951,7 @@ TclStringObjReverse(
        char *to, *from = objPtr->bytes;
 
        if (Tcl_IsShared(objPtr)) {
-           objPtr = Tcl_NewObj();
+           TclNewObj(objPtr);
            Tcl_SetObjLength(objPtr, numBytes);
        }
        to = objPtr->bytes;
@@ -2824,20 +2960,22 @@ TclStringObjReverse(
            /*
             * Either numChars == -1 and we don't know how many chars are
             * represented by objPtr->bytes and we need Pass 1 just in case,
-            * or numChars >= 0 and we know we have fewer chars than bytes,
-            * so we know there's a multibyte character needing Pass 1.
+            * or numChars >= 0 and we know we have fewer chars than bytes, so
+            * we know there's a multibyte character needing Pass 1.
             *
             * Pass 1. Reverse the bytes of each multi-byte character.
             */
+
            int charCount = 0;
            int bytesLeft = numBytes;
 
            while (bytesLeft) {
                /*
-                * NOTE: We know that the from buffer is NUL-terminated.
-                * It's part of the contract for objPtr->bytes values.
-                * Thus, we can skip calling Tcl_UtfCharComplete() here.
+                * NOTE: We know that the from buffer is NUL-terminated. It's
+                * part of the contract for objPtr->bytes values. Thus, we can
+                * skip calling Tcl_UtfCharComplete() here.
                 */
+
                int bytesInChar = TclUtfToUniChar(from, &ch);
 
                ReverseBytes((unsigned char *)to, (unsigned char *)from,
@@ -3135,7 +3273,7 @@ ExtendStringRepWithUnicode(
      */
 
     int i, origLength, size = 0;
-    char *dst, buf[TCL_UTF_MAX];
+    char *dst, buf[4] = "";
     String *stringPtr = GET_STRING(objPtr);
 
     if (numChars < 0) {
index 227e6bc..25b854e 100644 (file)
@@ -59,15 +59,15 @@ typedef struct String {
                                 * space allocated for the unicode array. */
     int hasUnicode;            /* Boolean determining whether the string has
                                 * a Unicode representation. */
-    Tcl_UniChar unicode[1];    /* The array of Unicode chars. The actual size
+    Tcl_UniChar unicode[TCLFLEXARRAY]; /* The array of Unicode chars. The actual size
                                 * of this field depends on the 'maxChars'
                                 * field above. */
 } String;
 
 #define STRING_MAXCHARS \
-    (int)(((size_t)UINT_MAX - sizeof(String))/sizeof(Tcl_UniChar))
+    (int)(((size_t)UINT_MAX - 1 - TclOffset(String, unicode))/sizeof(Tcl_UniChar))
 #define STRING_SIZE(numChars) \
-    (sizeof(String) + ((numChars) * sizeof(Tcl_UniChar)))
+    (TclOffset(String, unicode) + ((numChars + 1) * sizeof(Tcl_UniChar)))
 #define stringCheckLimits(numChars) \
     do {                                                               \
        if ((numChars) < 0 || (numChars) > STRING_MAXCHARS) {           \
index 030e4ec..7067428 100644 (file)
@@ -28,6 +28,8 @@ MODULE_SCOPE const char tclDefaultTrimSet[];
 /*
  * The whitespace trimming set used when [concat]enating. This is a subset of
  * the above, and deliberately so.
+ *
+ * TODO: Find a reasonable way to guarantee in sync with TclIsSpaceProc()
  */
 
 #define CONCAT_TRIM_SET " \f\v\r\t\n"
index 631a417..f05db0a 100644 (file)
@@ -57,6 +57,7 @@
 #define TclBN_mp_tc_and TclBN_mp_and
 #define TclBN_mp_tc_or TclBN_mp_or
 #define TclBN_mp_tc_xor TclBN_mp_xor
+#define TclStaticPackage Tcl_StaticPackage
 #define TclUnusedStubEntry NULL
 
 /* See bug 510001: TclSockMinimumBuffers needs plat imp */
@@ -71,6 +72,8 @@ static int TclSockMinimumBuffersOld(int sock, int size)
 #endif
 
 MP_SET_UNSIGNED(mp_set_ull, Tcl_WideUInt)
+MP_GET_MAG(mp_get_mag_ull, Tcl_WideUInt)
+MP_SET_SIGNED(mp_set_ll, mp_set_ull, Tcl_WideInt, Tcl_WideUInt)
 
 
 mp_err TclBN_mp_set_int(mp_int *a, unsigned long i)
@@ -93,6 +96,21 @@ int TclBN_mp_expt_d_ex(const mp_int *a, mp_digit b, mp_int *c, int fast)
        return mp_expt_u32(a, b, c);
 }
 
+#define TclBN_mp_div_ld TclBNMpDivLd
+static mp_err TclBN_mp_div_ld(const mp_int *a, Tcl_WideUInt b, mp_int *c, Tcl_WideUInt *d) {
+   mp_err result;
+   mp_digit d2;
+
+   if ((b | (mp_digit)-1) != (mp_digit)-1) {
+      return MP_VAL;
+   }
+   result = mp_div_d(a, (mp_digit)b, c, (d ? &d2 : NULL));
+   if (d) {
+      *d = d2;
+   }
+   return result;
+}
+
 #define TclSetStartupScriptPath setStartupScriptPath
 static void TclSetStartupScriptPath(Tcl_Obj *path)
 {
@@ -127,6 +145,16 @@ static unsigned short TclWinNToHS(unsigned short ns) {
 }
 #endif
 
+#define TclpCreateTempFile_ TclpCreateTempFile
+#define TclUnixWaitForFile_ TclUnixWaitForFile
+#ifndef MAC_OSX_TCL /* On UNIX, fill with other stub entries */
+#define TclMacOSXGetFileAttribute (int (*)(Tcl_Interp *, int, Tcl_Obj *, Tcl_Obj **))(void *)TclpCreateProcess
+#define TclMacOSXSetFileAttribute (int (*)(Tcl_Interp *, int, Tcl_Obj *, Tcl_Obj *))(void *)isatty
+#define TclMacOSXCopyFileAttributes (int (*)(const char *, const char *, const Tcl_StatBuf *))(void *)TclUnixCopyFile
+#define TclMacOSXMatchType (int (*)(Tcl_Interp *, const char *, const char *, Tcl_StatBuf *, Tcl_GlobTypeData *))(void *)TclpMakeFile
+#define TclMacOSXNotifierAddRunLoopMode (void (*)(const void *))(void *)TclpOpenFile
+#endif
+
 #ifdef _WIN32
 #   define TclUnixWaitForFile 0
 #   define TclUnixCopyFile 0
@@ -134,18 +162,12 @@ static unsigned short TclWinNToHS(unsigned short ns) {
 #   define TclpReaddir 0
 #   define TclpIsAtty 0
 #elif defined(__CYGWIN__)
-#   define TclpIsAtty TclPlatIsAtty
-#   define TclWinSetInterfaces (void (*) (int)) doNothing
-#   define TclWinAddProcess (void (*) (void *, unsigned int)) doNothing
+#   define TclpIsAtty isatty
+#   define TclWinSetInterfaces (void (*) (int))(void *)doNothing
+#   define TclWinAddProcess (void (*) (void *, unsigned int))(void *)doNothing
 #   define TclWinFlushDirtyChannels doNothing
 #   define TclWinResetInterfaces doNothing
 
-static int
-TclpIsAtty(int fd)
-{
-    return isatty(fd);
-}
-
 #define TclWinGetPlatformId winGetPlatformId
 static int
 TclWinGetPlatformId()
@@ -155,14 +177,6 @@ TclWinGetPlatformId()
     return 2; /* VER_PLATFORM_WIN32_NT */;
 }
 
-void *TclWinGetTclInstance()
-{
-    void *hInstance = NULL;
-    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
-           (const char *)&TclpIsAtty, &hInstance);
-    return hInstance;
-}
-
 #define TclWinSetSockOpt winSetSockOpt
 static int
 TclWinSetSockOpt(SOCKET s, int level, int optname,
@@ -200,6 +214,14 @@ TclWinNoBackslash(char *path)
     return path;
 }
 
+void *TclWinGetTclInstance()
+{
+    void *hInstance = NULL;
+    GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
+           (const char *)&TclWinNoBackslash, &hInstance);
+    return hInstance;
+}
+
 int
 TclpGetPid(Tcl_Pid pid)
 {
@@ -341,14 +363,14 @@ Tcl_WinTCharToUtf(
  * signature. Tcl 9 must find a better solution, but that cannot be done
  * without introducing a binary incompatibility.
  */
-#define Tcl_DbNewLongObj ((Tcl_Obj*(*)(long,const char*,int))dbNewLongObj)
+#define Tcl_DbNewLongObj ((Tcl_Obj*(*)(long,const char*,int))(void *)dbNewLongObj)
 static Tcl_Obj *dbNewLongObj(
     int intValue,
     const char *file,
     int line
 ) {
 #ifdef TCL_MEM_DEBUG
-    register Tcl_Obj *objPtr;
+    Tcl_Obj *objPtr;
 
     TclDbNewObj(objPtr, file, line);
     objPtr->bytes = NULL;
@@ -360,9 +382,9 @@ static Tcl_Obj *dbNewLongObj(
     return Tcl_NewIntObj(intValue);
 #endif
 }
-#define Tcl_GetLongFromObj (int(*)(Tcl_Interp*,Tcl_Obj*,long*))Tcl_GetIntFromObj
-#define Tcl_NewLongObj (Tcl_Obj*(*)(long))Tcl_NewIntObj
-#define Tcl_SetLongObj (void(*)(Tcl_Obj*,long))Tcl_SetIntObj
+#define Tcl_GetLongFromObj (int(*)(Tcl_Interp*,Tcl_Obj*,long*))(void *)Tcl_GetIntFromObj
+#define Tcl_NewLongObj (Tcl_Obj*(*)(long))(void *)Tcl_NewIntObj
+#define Tcl_SetLongObj (void(*)(Tcl_Obj*,long))(void *)Tcl_SetIntObj
 static int exprInt(Tcl_Interp *interp, const char *expr, int *ptr){
     long longValue;
     int result = Tcl_ExprLong(interp, expr, &longValue);
@@ -398,23 +420,23 @@ static int exprIntObj(Tcl_Interp *interp, Tcl_Obj*expr, int *ptr){
 static int uniCharNcmp(const Tcl_UniChar *ucs, const Tcl_UniChar *uct, unsigned int n){
    return Tcl_UniCharNcmp(ucs, uct, (unsigned long)n);
 }
-#define Tcl_UniCharNcmp (int(*)(const Tcl_UniChar*,const Tcl_UniChar*,unsigned long))uniCharNcmp
+#define Tcl_UniCharNcmp (int(*)(const Tcl_UniChar*,const Tcl_UniChar*,unsigned long))(void *)uniCharNcmp
 static int utfNcmp(const char *s1, const char *s2, unsigned int n){
    return Tcl_UtfNcmp(s1, s2, (unsigned long)n);
 }
-#define Tcl_UtfNcmp (int(*)(const char*,const char*,unsigned long))utfNcmp
+#define Tcl_UtfNcmp (int(*)(const char*,const char*,unsigned long))(void *)utfNcmp
 static int utfNcasecmp(const char *s1, const char *s2, unsigned int n){
    return Tcl_UtfNcasecmp(s1, s2, (unsigned long)n);
 }
-#define Tcl_UtfNcasecmp (int(*)(const char*,const char*,unsigned long))utfNcasecmp
+#define Tcl_UtfNcasecmp (int(*)(const char*,const char*,unsigned long))(void *)utfNcasecmp
 static int uniCharNcasecmp(const Tcl_UniChar *ucs, const Tcl_UniChar *uct, unsigned int n){
    return Tcl_UniCharNcasecmp(ucs, uct, (unsigned long)n);
 }
-#define Tcl_UniCharNcasecmp (int(*)(const Tcl_UniChar*,const Tcl_UniChar*,unsigned long))uniCharNcasecmp
+#define Tcl_UniCharNcasecmp (int(*)(const Tcl_UniChar*,const Tcl_UniChar*,unsigned long))(void *)uniCharNcasecmp
 static int formatInt(char *buffer, int n){
    return TclFormatInt(buffer, (long)n);
 }
-#define TclFormatInt (int(*)(char *, long))formatInt
+#define TclFormatInt (int(*)(char *, long))(void *)formatInt
 
 #endif
 
@@ -443,7 +465,7 @@ mp_err mp_toradix_n(const mp_int *a, char *str, int radix, int maxlen)
    if (maxlen < 0) {
       return MP_VAL;
    }
-   return mp_to_radix(a, str, (size_t)maxlen, NULL, radix);
+   return mp_to_radix(a, str, maxlen, NULL, radix);
 }
 
 void bn_reverse(unsigned char *s, int len)
@@ -724,8 +746,10 @@ static const TclIntStubs tclIntStubs = {
     TclPtrIncrObjVar, /* 254 */
     TclPtrObjMakeUpvar, /* 255 */
     TclPtrUnsetVar, /* 256 */
-    0, /* 257 */
-    TclUnusedStubEntry, /* 258 */
+    TclStaticPackage, /* 257 */
+    0, /* 258 */
+    0, /* 259 */
+    TclUnusedStubEntry, /* 260 */
 };
 
 static const TclIntPlatStubs tclIntPlatStubs = {
@@ -737,7 +761,7 @@ static const TclIntPlatStubs tclIntPlatStubs = {
     TclpCreateCommandChannel, /* 2 */
     TclpCreatePipe, /* 3 */
     TclpCreateProcess, /* 4 */
-    0, /* 5 */
+    TclUnixWaitForFile_, /* 5 */
     TclpMakeFile, /* 6 */
     TclpOpenFile, /* 7 */
     TclUnixWaitForFile, /* 8 */
@@ -747,14 +771,14 @@ static const TclIntPlatStubs tclIntPlatStubs = {
     TclpGmtime_unix, /* 12 */
     TclpInetNtoa, /* 13 */
     TclUnixCopyFile, /* 14 */
-    0, /* 15 */
-    0, /* 16 */
-    0, /* 17 */
-    0, /* 18 */
-    0, /* 19 */
+    TclMacOSXGetFileAttribute, /* 15 */
+    TclMacOSXSetFileAttribute, /* 16 */
+    TclMacOSXCopyFileAttributes, /* 17 */
+    TclMacOSXMatchType, /* 18 */
+    TclMacOSXNotifierAddRunLoopMode, /* 19 */
     0, /* 20 */
     0, /* 21 */
-    0, /* 22 */
+    TclpCreateTempFile_, /* 22 */
     0, /* 23 */
     0, /* 24 */
     0, /* 25 */
@@ -803,7 +827,7 @@ static const TclIntPlatStubs tclIntPlatStubs = {
     TclpCreateCommandChannel, /* 2 */
     TclpCreatePipe, /* 3 */
     TclpCreateProcess, /* 4 */
-    0, /* 5 */
+    TclUnixWaitForFile_, /* 5 */
     TclpMakeFile, /* 6 */
     TclpOpenFile, /* 7 */
     TclUnixWaitForFile, /* 8 */
@@ -820,7 +844,7 @@ static const TclIntPlatStubs tclIntPlatStubs = {
     TclMacOSXNotifierAddRunLoopMode, /* 19 */
     0, /* 20 */
     0, /* 21 */
-    0, /* 22 */
+    TclpCreateTempFile_, /* 22 */
     0, /* 23 */
     0, /* 24 */
     0, /* 25 */
@@ -917,8 +941,8 @@ const TclTomMathStubs tclTomMathStubs = {
     TclBNInitBignumFromWideUInt, /* 66 */
     TclBN_mp_expt_d_ex, /* 67 */
     TclBN_mp_set_ull, /* 68 */
-    0, /* 69 */
-    0, /* 70 */
+    TclBN_mp_get_mag_ull, /* 69 */
+    TclBN_mp_set_ll, /* 70 */
     0, /* 71 */
     0, /* 72 */
     TclBN_mp_tc_and, /* 73 */
@@ -927,7 +951,7 @@ const TclTomMathStubs tclTomMathStubs = {
     TclBN_mp_signed_rsh, /* 76 */
     0, /* 77 */
     TclBN_mp_to_ubin, /* 78 */
-    0, /* 79 */
+    TclBN_mp_div_ld, /* 79 */
     TclBN_mp_to_radix, /* 80 */
 };
 
@@ -1612,7 +1636,8 @@ const TclStubs tclStubs = {
     0, /* 645 */
     0, /* 646 */
     0, /* 647 */
-    TclUnusedStubEntry, /* 648 */
+    0, /* 648 */
+    TclUnusedStubEntry, /* 649 */
 };
 
 /* !END!: Do not edit above this line. */
index 5e807d4..2c29cda 100644 (file)
@@ -98,7 +98,7 @@ static Tcl_Trace cmdTrace;
  * TestdelCmd:
  */
 
-typedef struct DelCmd {
+typedef struct {
     Tcl_Interp *interp;                /* Interpreter in which command exists. */
     char *deleteCmd;           /* Script to execute when command is deleted.
                                 * Malloc'ed. */
@@ -109,7 +109,7 @@ typedef struct DelCmd {
  * command.
  */
 
-typedef struct TclEncoding {
+typedef struct {
     Tcl_Interp *interp;
     char *toUtfCmd;
     char *fromUtfCmd;
@@ -132,7 +132,7 @@ static int exitMainLoop = 0;
  * Event structure used in testing the event queue management procedures.
  */
 
-typedef struct TestEvent {
+typedef struct {
     Tcl_Event header;          /* Header common to all events */
     Tcl_Interp *interp;                /* Interpreter that will handle the event */
     Tcl_Obj *command;          /* Command to evaluate when the event occurs */
@@ -164,10 +164,8 @@ static void                CleanupTestSetassocdataTests(
                            ClientData clientData, Tcl_Interp *interp);
 static void            CmdDelProc1(ClientData clientData);
 static void            CmdDelProc2(ClientData clientData);
-static int             CmdProc1(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             CmdProc2(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
+static Tcl_CmdProc     CmdProc1;
+static Tcl_CmdProc     CmdProc2;
 static void            CmdTraceDeleteProc(
                            ClientData clientData, Tcl_Interp *interp,
                            int level, char *command, Tcl_CmdProc *cmdProc,
@@ -177,16 +175,11 @@ static void               CmdTraceProc(ClientData clientData,
                            Tcl_Interp *interp, int level, char *command,
                            Tcl_CmdProc *cmdProc, ClientData cmdClientData,
                            int argc, const char *argv[]);
-static int             CreatedCommandProc(
-                           ClientData clientData, Tcl_Interp *interp,
-                           int argc, const char **argv);
-static int             CreatedCommandProc2(
-                           ClientData clientData, Tcl_Interp *interp,
-                           int argc, const char **argv);
+static Tcl_CmdProc     CreatedCommandProc;
+static Tcl_CmdProc     CreatedCommandProc2;
 static void            DelCallbackProc(ClientData clientData,
                            Tcl_Interp *interp);
-static int             DelCmdProc(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
+static Tcl_CmdProc     DelCmdProc;
 static void            DelDeleteProc(ClientData clientData);
 static void            EncodingFreeProc(ClientData clientData);
 static int             EncodingToUtfProc(ClientData clientData,
@@ -201,15 +194,10 @@ static int                EncodingFromUtfProc(ClientData clientData,
                            int *dstCharsPtr);
 static void            ExitProcEven(ClientData clientData);
 static void            ExitProcOdd(ClientData clientData);
-static int             GetTimesObjCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_ObjCmdProc  GetTimesObjCmd;
 static void            MainLoop(void);
-static int             NoopCmd(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             NoopObjCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_CmdProc     NoopCmd;
+static Tcl_ObjCmdProc  NoopObjCmd;
 static int             ObjTraceProc(ClientData clientData,
                            Tcl_Interp *interp, int level, const char *command,
                            Tcl_Command commandToken, int objc,
@@ -218,164 +206,81 @@ static void              ObjTraceDeleteProc(ClientData clientData);
 static void            PrintParse(Tcl_Interp *interp, Tcl_Parse *parsePtr);
 static void            SpecialFree(char *blockPtr);
 static int             StaticInitProc(Tcl_Interp *interp);
-static int             TestasyncCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestbumpinterpepochObjCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestpurebytesobjObjCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestbytestringObjCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestcmdinfoCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestcmdtokenCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestcmdtraceCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestconcatobjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestcreatecommandCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestdcallCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestdelCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestdelassocdataCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestdoubledigitsObjCmd(ClientData dummy,
-                                              Tcl_Interp* interp,
-                                              int objc, Tcl_Obj* const objv[]);
-static int             TestdstringCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestencodingObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestevalexObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestevalobjvObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TesteventObjCmd(ClientData unused,
-                           Tcl_Interp *interp, int argc,
-                           Tcl_Obj *const objv[]);
+static Tcl_CmdProc     TestasyncCmd;
+static Tcl_ObjCmdProc  TestbumpinterpepochObjCmd;
+static Tcl_ObjCmdProc  TestsetbytearraylengthObjCmd;
+static Tcl_ObjCmdProc  TestpurebytesobjObjCmd;
+static Tcl_ObjCmdProc  TestbytestringObjCmd;
+static Tcl_ObjCmdProc  TeststringbytesObjCmd;
+static Tcl_CmdProc     TestcmdinfoCmd;
+static Tcl_CmdProc     TestcmdtokenCmd;
+static Tcl_CmdProc     TestcmdtraceCmd;
+static Tcl_CmdProc     TestconcatobjCmd;
+static Tcl_CmdProc     TestcreatecommandCmd;
+static Tcl_CmdProc     TestdcallCmd;
+static Tcl_CmdProc     TestdelCmd;
+static Tcl_CmdProc     TestdelassocdataCmd;
+static Tcl_ObjCmdProc  TestdoubledigitsObjCmd;
+static Tcl_CmdProc     TestdstringCmd;
+static Tcl_ObjCmdProc  TestencodingObjCmd;
+static Tcl_ObjCmdProc  TestevalexObjCmd;
+static Tcl_ObjCmdProc  TestevalobjvObjCmd;
+static Tcl_ObjCmdProc  TesteventObjCmd;
 static int             TesteventProc(Tcl_Event *event, int flags);
 static int             TesteventDeleteProc(Tcl_Event *event,
                            ClientData clientData);
-static int             TestexithandlerCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestexprlongCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestexprlongobjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestexprdoubleCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestexprdoubleobjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestexprparserObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestexprstringCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestfileCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
-static int             TestfilelinkCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
-static int             TestfeventCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestgetassocdataCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestgetintCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestgetplatformCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestgetvarfullnameCmd(
-                           ClientData dummy, Tcl_Interp *interp,
-                           int objc, Tcl_Obj *const objv[]);
-static int             TestinterpdeleteCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestlinkCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestlocaleCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_CmdProc     TestexithandlerCmd;
+static Tcl_CmdProc     TestexprlongCmd;
+static Tcl_ObjCmdProc  TestexprlongobjCmd;
+static Tcl_CmdProc     TestexprdoubleCmd;
+static Tcl_ObjCmdProc  TestexprdoubleobjCmd;
+static Tcl_ObjCmdProc  TestexprparserObjCmd;
+static Tcl_CmdProc     TestexprstringCmd;
+static Tcl_ObjCmdProc  TestfileCmd;
+static Tcl_ObjCmdProc  TestfilelinkCmd;
+static Tcl_CmdProc     TestfeventCmd;
+static Tcl_CmdProc     TestgetassocdataCmd;
+static Tcl_CmdProc     TestgetintCmd;
+static Tcl_CmdProc     TestgetplatformCmd;
+static Tcl_ObjCmdProc  TestgetvarfullnameCmd;
+static Tcl_CmdProc     TestinterpdeleteCmd;
+static Tcl_CmdProc     TestlinkCmd;
+static Tcl_ObjCmdProc  TestlocaleCmd;
 static int             TestMathFunc(ClientData clientData,
                            Tcl_Interp *interp, Tcl_Value *args,
                            Tcl_Value *resultPtr);
 static int             TestMathFunc2(ClientData clientData,
                            Tcl_Interp *interp, Tcl_Value *args,
                            Tcl_Value *resultPtr);
-static int             TestmainthreadCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestsetmainloopCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestexitmainloopCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestpanicCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestparseargsCmd(ClientData dummy, Tcl_Interp *interp,
-                           int objc, Tcl_Obj *const objv[]);
-static int             TestparserObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestparsevarObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestparsevarnameObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestregexpObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestreturnObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_CmdProc     TestmainthreadCmd;
+static Tcl_CmdProc     TestsetmainloopCmd;
+static Tcl_CmdProc     TestexitmainloopCmd;
+static Tcl_CmdProc     TestpanicCmd;
+static Tcl_ObjCmdProc  TestparseargsCmd;
+static Tcl_ObjCmdProc  TestparserObjCmd;
+static Tcl_ObjCmdProc  TestparsevarObjCmd;
+static Tcl_ObjCmdProc  TestparsevarnameObjCmd;
+static Tcl_ObjCmdProc  TestregexpObjCmd;
+static Tcl_ObjCmdProc  TestreturnObjCmd;
 static void            TestregexpXflags(const char *string,
                            int length, int *cflagsPtr, int *eflagsPtr);
-static int             TestsaveresultCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_ObjCmdProc  TestsaveresultCmd;
 static void            TestsaveresultFree(char *blockPtr);
-static int             TestsetassocdataCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestsetCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             Testset2Cmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestseterrorcodeCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestsetobjerrorcodeCmd(
-                           ClientData dummy, Tcl_Interp *interp,
-                           int objc, Tcl_Obj *const objv[]);
-static int             TestsetplatformCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TeststaticpkgCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TesttranslatefilenameCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestupvarCmd(ClientData dummy,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestWrongNumArgsObjCmd(
-                           ClientData clientData, Tcl_Interp *interp,
-                           int objc, Tcl_Obj *const objv[]);
-static int             TestGetIndexFromObjStructObjCmd(
-                           ClientData clientData, Tcl_Interp *interp,
-                           int objc, Tcl_Obj *const objv[]);
-static int             TestChannelCmd(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestChannelEventCmd(ClientData clientData,
-                           Tcl_Interp *interp, int argc, const char **argv);
-static int             TestFilesystemObjCmd(ClientData dummy,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestSimpleFilesystemObjCmd(
-                           ClientData dummy, Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_CmdProc     TestsetassocdataCmd;
+static Tcl_CmdProc     TestsetCmd;
+static Tcl_CmdProc     Testset2Cmd;
+static Tcl_CmdProc     TestseterrorcodeCmd;
+static Tcl_ObjCmdProc  TestsetobjerrorcodeCmd;
+static Tcl_CmdProc     TestsetplatformCmd;
+static Tcl_CmdProc     TeststaticpkgCmd;
+static Tcl_CmdProc     TesttranslatefilenameCmd;
+static Tcl_CmdProc     TestupvarCmd;
+static Tcl_ObjCmdProc  TestWrongNumArgsObjCmd;
+static Tcl_ObjCmdProc  TestGetIndexFromObjStructObjCmd;
+static Tcl_CmdProc     TestChannelCmd;
+static Tcl_CmdProc     TestChannelEventCmd;
+static Tcl_ObjCmdProc  TestFilesystemObjCmd;
+static Tcl_ObjCmdProc  TestSimpleFilesystemObjCmd;
 static void            TestReport(const char *cmd, Tcl_Obj *arg1,
                            Tcl_Obj *arg2);
 static Tcl_Obj *       TestReportGetNativePath(Tcl_Obj *pathPtr);
@@ -402,7 +307,7 @@ static Tcl_FSNormalizePathProc TestReportNormalizePath;
 static Tcl_FSPathInFilesystemProc TestReportInFilesystem;
 static Tcl_FSFreeInternalRepProc TestReportFreeInternalRep;
 static Tcl_FSDupInternalRepProc TestReportDupInternalRep;
-
+static Tcl_CmdProc TestServiceModeCmd;
 static Tcl_FSStatProc SimpleStat;
 static Tcl_FSAccessProc SimpleAccess;
 static Tcl_FSOpenFileChannelProc SimpleOpenFileChannel;
@@ -410,33 +315,19 @@ static Tcl_FSListVolumesProc SimpleListVolumes;
 static Tcl_FSPathInFilesystemProc SimplePathInFilesystem;
 static Tcl_Obj *       SimpleRedirect(Tcl_Obj *pathPtr);
 static Tcl_FSMatchInDirectoryProc SimpleMatchInDirectory;
-static int             TestNumUtfCharsCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestFindFirstCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestFindLastCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestHashSystemHashCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_ObjCmdProc  TestUtfNextCmd;
+static Tcl_ObjCmdProc  TestUtfPrevCmd;
+static Tcl_ObjCmdProc  TestNumUtfCharsCmd;
+static Tcl_ObjCmdProc  TestFindFirstCmd;
+static Tcl_ObjCmdProc  TestFindLastCmd;
+static Tcl_ObjCmdProc  TestHashSystemHashCmd;
 
 static Tcl_NRPostProc  NREUnwind_callback;
-static int             TestNREUnwind(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestNRELevels(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
-static int             TestInterpResolverCmd(ClientData clientData,
-                           Tcl_Interp *interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_ObjCmdProc  TestNREUnwind;
+static Tcl_ObjCmdProc  TestNRELevels;
+static Tcl_ObjCmdProc  TestInterpResolverCmd;
 #if defined(HAVE_CPUID) || defined(_WIN32)
-static int             TestcpuidCmd(ClientData dummy,
-                           Tcl_Interp* interp, int objc,
-                           Tcl_Obj *const objv[]);
+static Tcl_ObjCmdProc  TestcpuidCmd;
 #endif
 
 static const Tcl_Filesystem testReportingFilesystem = {
@@ -546,8 +437,7 @@ Tcltest_Init(
 {
     Tcl_ValueType t3ArgTypes[2];
 
-    Tcl_Obj *listPtr;
-    Tcl_Obj **objv;
+    Tcl_Obj **objv, *objPtr;
     int objc, index;
     static const char *const specialOptions[] = {
        "-appinitprocerror", "-appinitprocdeleteinterp",
@@ -577,7 +467,9 @@ Tcltest_Init(
     Tcl_CreateCommand(interp, "noop", NoopCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "noop", NoopObjCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "testpurebytesobj", TestpurebytesobjObjCmd, NULL, NULL);
+    Tcl_CreateObjCommand(interp, "testsetbytearraylength", TestsetbytearraylengthObjCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "testbytestring", TestbytestringObjCmd, NULL, NULL);
+    Tcl_CreateObjCommand(interp, "teststringbytes", TeststringbytesObjCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "testwrongnumargs", TestWrongNumArgsObjCmd,
            NULL, NULL);
     Tcl_CreateObjCommand(interp, "testfilesystem", TestFilesystemObjCmd,
@@ -669,6 +561,8 @@ Tcltest_Init(
            NULL, NULL);
     Tcl_CreateObjCommand(interp, "testsaveresult", TestsaveresultCmd,
            NULL, NULL);
+    Tcl_CreateCommand(interp, "testservicemode", TestServiceModeCmd,
+           NULL, NULL);
     Tcl_CreateCommand(interp, "testsetassocdata", TestsetassocdataCmd,
            NULL, NULL);
     Tcl_CreateCommand(interp, "testsetnoerr", TestsetCmd,
@@ -681,6 +575,10 @@ Tcltest_Init(
            NULL, NULL);
     Tcl_CreateObjCommand(interp, "testsetobjerrorcode",
            TestsetobjerrorcodeCmd, NULL, NULL);
+    Tcl_CreateObjCommand(interp, "testutfnext",
+           TestUtfNextCmd, NULL, NULL);
+    Tcl_CreateObjCommand(interp, "testutfprev",
+           TestUtfPrevCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "testnumutfchars",
            TestNumUtfCharsCmd, NULL, NULL);
     Tcl_CreateObjCommand(interp, "testfindfirst",
@@ -704,7 +602,7 @@ Tcltest_Init(
            NULL, NULL);
 #if defined(HAVE_CPUID) || defined(_WIN32)
     Tcl_CreateObjCommand(interp, "testcpuid", TestcpuidCmd,
-           (ClientData) 0, NULL);
+           NULL, NULL);
 #endif
     t3ArgTypes[0] = TCL_EITHER;
     t3ArgTypes[1] = TCL_EITHER;
@@ -734,9 +632,9 @@ Tcltest_Init(
      * Check for special options used in ../tests/main.test
      */
 
-    listPtr = Tcl_GetVar2Ex(interp, "argv", NULL, TCL_GLOBAL_ONLY);
-    if (listPtr != NULL) {
-       if (Tcl_ListObjGetElements(interp, listPtr, &objc, &objv) != TCL_OK) {
+    objPtr = Tcl_GetVar2Ex(interp, "argv", NULL, TCL_GLOBAL_ONLY);
+    if (objPtr != NULL) {
+       if (Tcl_ListObjGetElements(interp, objPtr, &objc, &objv) != TCL_OK) {
            return TCL_ERROR;
        }
        if (objc && (Tcl_GetIndexFromObj(NULL, objv[0], specialOptions, NULL,
@@ -816,7 +714,6 @@ Tcltest_SafeInit(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestasyncCmd(
     ClientData dummy,                  /* Not used. */
@@ -827,18 +724,19 @@ TestasyncCmd(
     TestAsyncHandler *asyncPtr, *prevPtr;
     int id, code;
     static int nextId = 1;
+    (void)dummy;
 
     if (argc < 2) {
        wrongNumArgs:
-       Tcl_SetResult(interp, "wrong # args", TCL_STATIC);
+       Tcl_AppendResult(interp, "wrong # args", NULL);
        return TCL_ERROR;
     }
     if (strcmp(argv[1], "create") == 0) {
        if (argc != 3) {
            goto wrongNumArgs;
        }
-       asyncPtr = ckalloc(sizeof(TestAsyncHandler));
-       asyncPtr->command = ckalloc(strlen(argv[2]) + 1);
+       asyncPtr = (TestAsyncHandler *)ckalloc(sizeof(TestAsyncHandler));
+       asyncPtr->command = (char *)ckalloc(strlen(argv[2]) + 1);
        strcpy(asyncPtr->command, argv[2]);
         Tcl_MutexLock(&asyncTestMutex);
        asyncPtr->id = nextId;
@@ -920,7 +818,7 @@ TestasyncCmd(
                if (Tcl_CreateThread(&threadID, AsyncThreadProc,
                        INT2PTR(id), TCL_THREAD_STACK_DEFAULT,
                        TCL_THREAD_NOFLAGS) != TCL_OK) {
-                   Tcl_SetResult(interp, "can't create thread", TCL_STATIC);
+                   Tcl_AppendResult(interp, "can't create thread", NULL);
                    Tcl_MutexUnlock(&asyncTestMutex);
                    return TCL_ERROR;
                }
@@ -1035,6 +933,7 @@ TestbumpinterpepochObjCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     Interp *iPtr = (Interp *)interp;
+
     if (objc != 1) {
        Tcl_WrongNumArgs(interp, 1, objv, "");
        return TCL_ERROR;
@@ -1061,7 +960,6 @@ TestbumpinterpepochObjCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestcmdinfoCmd(
     ClientData dummy,          /* Not used. */
@@ -1070,6 +968,7 @@ TestcmdinfoCmd(
     const char **argv)         /* Argument strings. */
 {
     Tcl_CmdInfo info;
+    (void)dummy;
 
     if (argc != 3) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
@@ -1085,7 +984,7 @@ TestcmdinfoCmd(
        Tcl_DStringResult(interp, &delString);
     } else if (strcmp(argv[1], "get") == 0) {
        if (Tcl_GetCommandInfo(interp, argv[2], &info) ==0) {
-           Tcl_SetResult(interp, "??", TCL_STATIC);
+           Tcl_AppendResult(interp, "??", NULL);
            return TCL_OK;
        }
        if (info.proc == CmdProc1) {
@@ -1132,7 +1031,6 @@ TestcmdinfoCmd(
     return TCL_OK;
 }
 
-       /*ARGSUSED*/
 static int
 CmdProc1(
     ClientData clientData,     /* String to return. */
@@ -1144,7 +1042,6 @@ CmdProc1(
     return TCL_OK;
 }
 
-       /*ARGSUSED*/
 static int
 CmdProc2(
     ClientData clientData,     /* String to return. */
@@ -1191,7 +1088,6 @@ CmdDelProc2(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestcmdtokenCmd(
     ClientData dummy,          /* Not used. */
@@ -1255,7 +1151,6 @@ TestcmdtokenCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestcmdtraceCmd(
     ClientData dummy,          /* Not used. */
@@ -1541,7 +1436,6 @@ CreatedCommandProc2(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestdcallCmd(
     ClientData dummy,          /* Not used. */
@@ -1606,7 +1500,6 @@ DelCallbackProc(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestdelCmd(
     ClientData dummy,          /* Not used. */
@@ -1615,24 +1508,24 @@ TestdelCmd(
     const char **argv)         /* Argument strings. */
 {
     DelCmd *dPtr;
-    Tcl_Interp *slave;
+    Tcl_Interp *child;
 
     if (argc != 4) {
        Tcl_SetResult(interp, "wrong # args", TCL_STATIC);
        return TCL_ERROR;
     }
 
-    slave = Tcl_GetSlave(interp, argv[1]);
-    if (slave == NULL) {
+    child = Tcl_GetChild(interp, argv[1]);
+    if (child == NULL) {
        return TCL_ERROR;
     }
 
-    dPtr = ckalloc(sizeof(DelCmd));
+    dPtr = (DelCmd *)ckalloc(sizeof(DelCmd));
     dPtr->interp = interp;
-    dPtr->deleteCmd = ckalloc(strlen(argv[3]) + 1);
+    dPtr->deleteCmd = (char *)ckalloc(strlen(argv[3]) + 1);
     strcpy(dPtr->deleteCmd, argv[3]);
 
-    Tcl_CreateCommand(slave, argv[2], DelCmdProc, (ClientData) dPtr,
+    Tcl_CreateCommand(child, argv[2], DelCmdProc, (ClientData) dPtr,
            DelDeleteProc);
     return TCL_OK;
 }
@@ -1656,7 +1549,7 @@ static void
 DelDeleteProc(
     ClientData clientData)     /* String command to evaluate. */
 {
-    DelCmd *dPtr = clientData;
+    DelCmd *dPtr = (DelCmd *)clientData;
 
     Tcl_Eval(dPtr->interp, dPtr->deleteCmd);
     Tcl_ResetResult(dPtr->interp);
@@ -1811,7 +1704,6 @@ TestdoubledigitsObjCmd(ClientData unused,
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestdstringCmd(
     ClientData dummy,          /* Not used. */
@@ -1938,7 +1830,6 @@ static void SpecialFree(blockPtr)
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestencodingObjCmd(
     ClientData dummy,          /* Not used. */
@@ -1969,16 +1860,16 @@ TestencodingObjCmd(
        if (objc != 5) {
            return TCL_ERROR;
        }
-       encodingPtr = ckalloc(sizeof(TclEncoding));
+       encodingPtr = (TclEncoding *)ckalloc(sizeof(TclEncoding));
        encodingPtr->interp = interp;
 
        string = Tcl_GetStringFromObj(objv[3], &length);
-       encodingPtr->toUtfCmd = ckalloc(length + 1);
-       memcpy(encodingPtr->toUtfCmd, string, (unsigned) length + 1);
+       encodingPtr->toUtfCmd = (char *)ckalloc(length + 1);
+       memcpy(encodingPtr->toUtfCmd, string, length + 1);
 
        string = Tcl_GetStringFromObj(objv[4], &length);
-       encodingPtr->fromUtfCmd = ckalloc(length + 1);
-       memcpy(encodingPtr->fromUtfCmd, string, (unsigned) (length + 1));
+       encodingPtr->fromUtfCmd = (char *)ckalloc(length + 1);
+       memcpy(encodingPtr->fromUtfCmd, string, length + 1);
 
        string = Tcl_GetStringFromObj(objv[2], &length);
 
@@ -2027,7 +1918,7 @@ EncodingToUtfProc(
     if (len > dstLen) {
        len = dstLen;
     }
-    memcpy(dst, Tcl_GetStringResult(encodingPtr->interp), (unsigned) len);
+    memcpy(dst, Tcl_GetStringResult(encodingPtr->interp), len);
     Tcl_ResetResult(encodingPtr->interp);
 
     *srcReadPtr = srcLen;
@@ -2059,7 +1950,7 @@ EncodingFromUtfProc(
     if (len > dstLen) {
        len = dstLen;
     }
-    memcpy(dst, Tcl_GetStringResult(encodingPtr->interp), (unsigned) len);
+    memcpy(dst, Tcl_GetStringResult(encodingPtr->interp), len);
     Tcl_ResetResult(encodingPtr->interp);
 
     *srcReadPtr = srcLen;
@@ -2072,7 +1963,7 @@ static void
 EncodingFreeProc(
     ClientData clientData)     /* ClientData associated with type. */
 {
-    TclEncoding *encodingPtr = clientData;
+    TclEncoding *encodingPtr = (TclEncoding *)clientData;
 
     ckfree(encodingPtr->toUtfCmd);
     ckfree(encodingPtr->fromUtfCmd);
@@ -2231,7 +2122,7 @@ TesteventObjCmd(
                "position specifier", TCL_EXACT, &posIndex) != TCL_OK) {
            return TCL_ERROR;
        }
-       ev = ckalloc(sizeof(TestEvent));
+       ev = (TestEvent *)ckalloc(sizeof(TestEvent));
        ev->header.proc = TesteventProc;
        ev->header.nextPtr = NULL;
        ev->interp = interp;
@@ -2793,7 +2684,6 @@ TestgetplatformCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestinterpdeleteCmd(
     ClientData dummy,          /* Not used. */
@@ -2801,18 +2691,18 @@ TestinterpdeleteCmd(
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
-    Tcl_Interp *slaveToDelete;
+    Tcl_Interp *childToDelete;
 
     if (argc != 2) {
        Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                " path\"", NULL);
        return TCL_ERROR;
     }
-    slaveToDelete = Tcl_GetSlave(interp, argv[1]);
-    if (slaveToDelete == NULL) {
+    childToDelete = Tcl_GetChild(interp, argv[1]);
+    if (childToDelete == NULL) {
        return TCL_ERROR;
     }
-    Tcl_DeleteInterp(slaveToDelete);
+    Tcl_DeleteInterp(childToDelete);
     return TCL_OK;
 }
 \f
@@ -2834,7 +2724,6 @@ TestinterpdeleteCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestlinkCmd(
     ClientData dummy,          /* Not used. */
@@ -2851,7 +2740,7 @@ TestlinkCmd(
     static unsigned char ucharVar = 130;
     static short shortVar = 3000;
     static unsigned short ushortVar = 60000;
-    static unsigned int uintVar = 0xbeeffeed;
+    static unsigned int uintVar = 0xBEEFFEED;
     static long longVar = 123456789L;
     static unsigned long ulongVar = 3456789012UL;
     static float floatVar = 4.5;
@@ -3089,7 +2978,7 @@ TestlinkCmd(
            if (strcmp(argv[5], "-") == 0) {
                stringVar = NULL;
            } else {
-               stringVar = ckalloc(strlen(argv[5]) + 1);
+               stringVar = (char *)ckalloc(strlen(argv[5]) + 1);
                strcpy(stringVar, argv[5]);
            }
        }
@@ -3196,7 +3085,7 @@ TestlinkCmd(
            if (strcmp(argv[5], "-") == 0) {
                stringVar = NULL;
            } else {
-               stringVar = ckalloc(strlen(argv[5]) + 1);
+               stringVar = (char *)ckalloc(strlen(argv[5]) + 1);
                strcpy(stringVar, argv[5]);
            }
            Tcl_UpdateLinkedVar(interp, "string");
@@ -3365,7 +3254,6 @@ TestlocaleCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestMathFunc(
     ClientData clientData,     /* Integer value to return. */
@@ -3395,7 +3283,6 @@ TestMathFunc(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestMathFunc2(
     ClientData clientData,     /* Integer value to return. */
@@ -3502,7 +3389,6 @@ TestMathFunc2(
  *
  *----------------------------------------------------------------------
  */
-       /* ARGSUSED */
 static void
 CleanupTestSetassocdataTests(
     ClientData clientData,     /* Data to be released. */
@@ -3836,7 +3722,6 @@ TestparsevarnameObjCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestregexpObjCmd(
     ClientData dummy,          /* Not used. */
@@ -4160,7 +4045,6 @@ TestregexpXflags(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestreturnObjCmd(
     ClientData dummy,          /* Not used. */
@@ -4382,7 +4266,6 @@ TesttranslatefilenameCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestupvarCmd(
     ClientData dummy,          /* Not used. */
@@ -4435,7 +4318,6 @@ TestupvarCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestseterrorcodeCmd(
     ClientData dummy,          /* Not used. */
@@ -4488,7 +4370,6 @@ TestseterrorcodeCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestsetobjerrorcodeCmd(
     ClientData dummy,          /* Not used. */
@@ -4517,7 +4398,6 @@ TestsetobjerrorcodeCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestfeventCmd(
     ClientData clientData,     /* Not used. */
@@ -4771,8 +4651,8 @@ static int
 GetTimesObjCmd(
     ClientData unused,         /* Unused. */
     Tcl_Interp *interp,                /* The current interpreter. */
-    int notused1,                      /* Number of arguments. */
-    Tcl_Obj *const notused2[]) /* The argument objects. */
+    int objc,                  /* Number of arguments. (not used)*/
+    Tcl_Obj *const dummy[])    /* The argument objects (not used). */
 {
     Interp *iPtr = (Interp *) interp;
     int i, n;
@@ -4781,12 +4661,14 @@ GetTimesObjCmd(
     Tcl_Obj *objPtr, **objv;
     const char *s;
     char newString[TCL_INTEGER_SPACE];
+    (void)objc;
+    (void)dummy;
 
     /* alloc & free 100000 times */
     fprintf(stderr, "alloc & free 100000 6 word items\n");
     Tcl_GetTime(&start);
     for (i = 0;  i < 100000;  i++) {
-       objPtr = ckalloc(sizeof(Tcl_Obj));
+       objPtr = (Tcl_Obj *)ckalloc(sizeof(Tcl_Obj));
        ckfree(objPtr);
     }
     Tcl_GetTime(&stop);
@@ -4795,10 +4677,10 @@ GetTimesObjCmd(
 
     /* alloc 5000 times */
     fprintf(stderr, "alloc 5000 6 word items\n");
-    objv = ckalloc(5000 * sizeof(Tcl_Obj *));
+    objv = (Tcl_Obj **) ckalloc(5000 * sizeof(Tcl_Obj *));
     Tcl_GetTime(&start);
     for (i = 0;  i < 5000;  i++) {
-       objv[i] = ckalloc(sizeof(Tcl_Obj));
+       objv[i] = (Tcl_Obj *) ckalloc(sizeof(Tcl_Obj));
     }
     Tcl_GetTime(&stop);
     timePer = (stop.sec - start.sec)*1000000 + (stop.usec - start.usec);
@@ -4986,6 +4868,41 @@ NoopObjCmd(
 /*
  *----------------------------------------------------------------------
  *
+ * TeststringbytesObjCmd --
+ *     Returns bytearray value of the bytes in argument string rep
+ *
+ * Results:
+ *     Returns the TCL_OK result code.
+ *
+ * Side effects:
+ *     None.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int
+TeststringbytesObjCmd(
+    ClientData dummy,
+    Tcl_Interp *interp,                /* Current interpreter. */
+    int objc,                  /* Number of arguments. */
+    Tcl_Obj *const objv[])     /* The argument objects. */
+{
+    int n;
+    const unsigned char *p;
+    (void)dummy;
+
+    if (objc != 2) {
+       Tcl_WrongNumArgs(interp, 1, objv, "value");
+       return TCL_ERROR;
+    }
+    p = (const unsigned char *)Tcl_GetStringFromObj(objv[1], &n);
+    Tcl_SetObjResult(interp, Tcl_NewByteArrayObj(p, n));
+    return TCL_OK;
+}
+\f
+/*
+ *----------------------------------------------------------------------
+ *
  * TestpurebytesobjObjCmd --
  *
  *     This object-based procedure constructs a pure bytes object
@@ -5006,12 +4923,13 @@ NoopObjCmd(
 
 static int
 TestpurebytesobjObjCmd(
-    ClientData unused,         /* Not used. */
+    ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* The argument objects. */
 {
     Tcl_Obj *objPtr;
+    (void)dummy;
 
     if (objc > 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "?string?");
@@ -5026,7 +4944,7 @@ TestpurebytesobjObjCmd(
     if (objc == 2) {
        const char *s = Tcl_GetString(objv[1]);
        objPtr->length = objv[1]->length;
-       objPtr->bytes = ckalloc(objPtr->length + 1);
+       objPtr->bytes = (char *)ckalloc(objPtr->length + 1);
        memcpy(objPtr->bytes, s, objPtr->length);
        objPtr->bytes[objPtr->length] = 0;
     }
@@ -5037,6 +4955,51 @@ TestpurebytesobjObjCmd(
 /*
  *----------------------------------------------------------------------
  *
+ * TestsetbytearraylengthObjCmd --
+ *
+ *     Testing command 'testsetbytearraylength` used to test the public
+ *     interface routine Tcl_SetByteArrayLength().
+ *
+ * Results:
+ *     Returns the TCL_OK result code.
+ *
+ * Side effects:
+ *     None.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int
+TestsetbytearraylengthObjCmd(
+    ClientData dummy,          /* Not used. */
+    Tcl_Interp *interp,                /* Current interpreter. */
+    int objc,                  /* Number of arguments. */
+    Tcl_Obj *const objv[])     /* The argument objects. */
+{
+    int n;
+    Tcl_Obj *obj = NULL;
+    (void)dummy;
+
+    if (objc != 3) {
+       Tcl_WrongNumArgs(interp, 1, objv, "value length");
+       return TCL_ERROR;
+    }
+    if (TCL_OK != Tcl_GetIntFromObj(interp, objv[2], &n)) {
+       return TCL_ERROR;
+    }
+    if (Tcl_IsShared(objv[1])) {
+       obj = Tcl_DuplicateObj(objv[1]);
+    } else {
+       obj = objv[1];
+    }
+    Tcl_SetByteArrayLength(obj, n);
+    Tcl_SetObjResult(interp, obj);
+    return TCL_OK;
+}
+\f
+/*
+ *----------------------------------------------------------------------
+ *
  * TestbytestringObjCmd --
  *
  *     This object-based procedure constructs a string which can
@@ -5053,18 +5016,20 @@ TestpurebytesobjObjCmd(
 
 static int
 TestbytestringObjCmd(
-    ClientData unused,         /* Not used. */
+    ClientData dummy,          /* Not used. */
     Tcl_Interp *interp,                /* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* The argument objects. */
 {
-    int n;
+    int n = 0;
     const char *p;
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "bytearray");
        return TCL_ERROR;
     }
+
     p = (const char *)Tcl_GetByteArrayFromObj(objv[1], &n);
     Tcl_SetObjResult(interp, Tcl_NewStringObj(p, n));
     return TCL_OK;
@@ -5087,11 +5052,10 @@ TestbytestringObjCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestsetCmd(
     ClientData data,           /* Additional flags for Get/SetVar2. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
@@ -5123,7 +5087,7 @@ TestsetCmd(
 static int
 Testset2Cmd(
     ClientData data,           /* Additional flags for Get/SetVar2. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
@@ -5170,11 +5134,10 @@ Testset2Cmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestsaveresultCmd(
     ClientData dummy,          /* Not used. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* The argument objects. */
 {
@@ -5307,7 +5270,7 @@ TestsaveresultFree(
 static int
 TestmainthreadCmd(
     ClientData dummy,          /* Not used. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
@@ -5368,7 +5331,7 @@ MainLoop(void)
 static int
 TestsetmainloopCmd(
     ClientData dummy,          /* Not used. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
@@ -5397,7 +5360,7 @@ TestsetmainloopCmd(
 static int
 TestexitmainloopCmd(
     ClientData dummy,          /* Not used. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int argc,                  /* Number of arguments. */
     const char **argv)         /* Argument strings. */
 {
@@ -5422,7 +5385,6 @@ TestexitmainloopCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestChannelCmd(
     ClientData clientData,     /* Not used. */
@@ -5484,7 +5446,6 @@ TestChannelCmd(
        chanPtr         = statePtr->topChanPtr;
        chan            = (Tcl_Channel) chanPtr;
     } else {
-       /* lint */
        statePtr        = NULL;
        chan            = NULL;
     }
@@ -5539,7 +5500,7 @@ TestChannelCmd(
 
        /* Remember the channel in the pool of detached channels */
 
-       det = ckalloc(sizeof(TestChannel));
+       det = (TestChannel *)ckalloc(sizeof(TestChannel));
        det->chan     = chan;
        det->nextPtr  = firstDetached;
        firstDetached = det;
@@ -5731,7 +5692,7 @@ TestChannelCmd(
        for (hPtr = Tcl_FirstHashEntry(hTblPtr, &hSearch);
             hPtr != NULL;
             hPtr = Tcl_NextHashEntry(&hSearch)) {
-           Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
+           Tcl_AppendElement(interp, (char *)Tcl_GetHashKey(hTblPtr, hPtr));
        }
        return TCL_OK;
     }
@@ -5772,7 +5733,7 @@ TestChannelCmd(
            chanPtr  = (Channel *) Tcl_GetHashValue(hPtr);
            statePtr = chanPtr->state;
            if (statePtr->flags & TCL_READABLE) {
-               Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
+               Tcl_AppendElement(interp, (char *)Tcl_GetHashKey(hTblPtr, hPtr));
            }
        }
        return TCL_OK;
@@ -5829,7 +5790,7 @@ TestChannelCmd(
            chanPtr = (Channel *) Tcl_GetHashValue(hPtr);
            statePtr = chanPtr->state;
            if (statePtr->flags & TCL_WRITABLE) {
-               Tcl_AppendElement(interp, Tcl_GetHashKey(hTblPtr, hPtr));
+               Tcl_AppendElement(interp, (char *)Tcl_GetHashKey(hTblPtr, hPtr));
            }
        }
        return TCL_OK;
@@ -5891,7 +5852,6 @@ TestChannelCmd(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TestChannelEventCmd(
     ClientData dummy,          /* Not used. */
@@ -5919,7 +5879,7 @@ TestChannelEventCmd(
 
     cmd = argv[2];
     len = strlen(cmd);
-    if ((cmd[0] == 'a') && (strncmp(cmd, "add", (unsigned) len) == 0)) {
+    if ((cmd[0] == 'a') && (strncmp(cmd, "add", len) == 0)) {
        if (argc != 5) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName add eventSpec script\"", NULL);
@@ -5937,7 +5897,8 @@ TestChannelEventCmd(
            return TCL_ERROR;
        }
 
-       esPtr = ckalloc(sizeof(EventScriptRecord));
+       esPtr = (EventScriptRecord *) ckalloc((unsigned)
+               sizeof(EventScriptRecord));
        esPtr->nextPtr = statePtr->scriptRecordPtr;
        statePtr->scriptRecordPtr = esPtr;
 
@@ -5953,7 +5914,7 @@ TestChannelEventCmd(
        return TCL_OK;
     }
 
-    if ((cmd[0] == 'd') && (strncmp(cmd, "delete", (unsigned) len) == 0)) {
+    if ((cmd[0] == 'd') && (strncmp(cmd, "delete", len) == 0)) {
        if (argc != 4) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName delete index\"", NULL);
@@ -5999,7 +5960,7 @@ TestChannelEventCmd(
        return TCL_OK;
     }
 
-    if ((cmd[0] == 'l') && (strncmp(cmd, "list", (unsigned) len) == 0)) {
+    if ((cmd[0] == 'l') && (strncmp(cmd, "list", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName list\"", NULL);
@@ -6022,7 +5983,7 @@ TestChannelEventCmd(
        return TCL_OK;
     }
 
-    if ((cmd[0] == 'r') && (strncmp(cmd, "removeall", (unsigned) len) == 0)) {
+    if ((cmd[0] == 'r') && (strncmp(cmd, "removeall", len) == 0)) {
        if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName removeall\"", NULL);
@@ -6041,7 +6002,7 @@ TestChannelEventCmd(
        return TCL_OK;
     }
 
-    if ((cmd[0] == 's') && (strncmp(cmd, "set", (unsigned) len) == 0)) {
+    if ((cmd[0] == 's') && (strncmp(cmd, "set", len) == 0)) {
        if (argc != 5) {
            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
                    " channelName delete index event\"", NULL);
@@ -6090,6 +6051,54 @@ TestChannelEventCmd(
 /*
  *----------------------------------------------------------------------
  *
+ * TestServiceModeCmd --
+ *
+ *     This procedure implements the "testservicemode" command which gets or
+ *      sets the current Tcl ServiceMode.  There are several tests which open
+ *      a file and assign various handlers to it.  For these tests to be
+ *      deterministic it is important that file events not be processed until
+ *      all of the handlers are in place.
+ *
+ * Results:
+ *     A standard Tcl result.
+ *
+ * Side effects:
+ *     May change the ServiceMode setting.
+ *
+ *----------------------------------------------------------------------
+ */
+
+static int
+TestServiceModeCmd(
+    ClientData dummy,          /* Not used. */
+    Tcl_Interp *interp,                /* Current interpreter. */
+    int argc,                  /* Number of arguments. */
+    const char **argv)         /* Argument strings. */
+{
+    int newmode, oldmode;
+    if (argc > 2) {
+        Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
+                         " ?newmode?\"", NULL);
+        return TCL_ERROR;
+    }
+    oldmode = (Tcl_GetServiceMode() != TCL_SERVICE_NONE);
+    if (argc == 2) {
+        if (Tcl_GetInt(interp, argv[1], &newmode) == TCL_ERROR) {
+            return TCL_ERROR;
+        }
+        if (newmode == 0) {
+            Tcl_SetServiceMode(TCL_SERVICE_NONE);
+        } else {
+            Tcl_SetServiceMode(TCL_SERVICE_ALL);
+        }
+    }
+    Tcl_SetObjResult(interp, Tcl_NewIntObj(oldmode));
+    return TCL_OK;
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
  * TestWrongNumArgsObjCmd --
  *
  *     Test the Tcl_WrongNumArgs function.
@@ -6315,11 +6324,6 @@ TestReport(
     if (interp == NULL) {
        /* This is bad, but not much we can do about it */
     } else {
-       /*
-        * No idea why I decided to program this up using the old string-based
-        * API, but there you go. We should convert it to objects.
-        */
-
        Tcl_Obj *savedResult;
        Tcl_DString ds;
 
@@ -6746,6 +6750,135 @@ SimpleListVolumes(void)
 }
 \f
 /*
+ * Used to check operations of Tcl_UtfNext.
+ *
+ * Usage: testutfnext $bytes $offset
+ */
+
+static int
+TestUtfNextCmd(
+    ClientData dummy,
+    Tcl_Interp *interp,
+    int objc,
+    Tcl_Obj *const objv[])
+{
+    int numBytes;      /* Number of bytes supplied in the test string */
+    int offset;                /* Number of bytes we are permitted to read */
+    char *bytes;
+    const char *result, *first;
+    char buffer[32];
+    static const char tobetested[] = "A\xA0\xC0\xC1\xC2\xD0\xE0\xE8\xF2\xF7\xF8\xFE\xFF";
+    const char *p = tobetested;
+    (void)dummy;
+
+    if (objc < 2 || objc > 3) {
+       Tcl_WrongNumArgs(interp, 1, objv, "string ?numBytes?");
+       return TCL_ERROR;
+    }
+
+    bytes = Tcl_GetStringFromObj(objv[1], &numBytes);
+
+    offset = numBytes +TCL_UTF_MAX -1; /* If no constraint is given, allow
+                                        * the terminating NUL to limit
+                                        * operations. */
+
+    if (objc == 3) {
+       if (TCL_OK != TclGetIntForIndex(interp, objv[2], numBytes, &offset)) {
+           return TCL_ERROR;
+       }
+       if (offset < 0) {
+           offset = 0;
+       }
+       if (offset > numBytes +TCL_UTF_MAX -1) {
+           offset = numBytes +TCL_UTF_MAX -1;
+       }
+    }
+
+    if (numBytes > (int)sizeof(buffer) - 3) {
+       Tcl_SetObjResult(interp, Tcl_ObjPrintf(
+               "\"testutfnext\" can only handle %d bytes",
+               (int)sizeof(buffer) - 4));
+       return TCL_ERROR;
+    }
+
+    memcpy(buffer + 1, bytes, numBytes);
+    buffer[0] = buffer[numBytes + 1] = buffer[numBytes + 2] = buffer[numBytes + 3] = '\xA0';
+
+    if (!Tcl_UtfCharComplete(buffer + 1, offset)) {
+       /* Cannot scan a complete sequence from the data */
+
+       Tcl_SetObjResult(interp, Tcl_NewIntObj(0));
+       return TCL_OK;
+    }
+
+    first = result = Tcl_UtfNext(buffer + 1);
+    while ((buffer[0] = *p++) != '\0') {
+       /* Run Tcl_UtfNext with many more possible bytes at src[-1], all should give the same result */
+       result = Tcl_UtfNext(buffer + 1);
+       if (first != result) {
+           Tcl_AppendResult(interp, "Tcl_UtfNext is not supposed to read src[-1]", NULL);
+           return TCL_ERROR;
+       }
+    }
+    p = tobetested;
+    while ((buffer[numBytes + 1] = *p++) != '\0') {
+       /* Run Tcl_UtfNext with many more possible bytes at src[end], all should give the same result */
+       result = Tcl_UtfNext(buffer + 1);
+       if (first != result) {
+           Tcl_SetObjResult(interp, Tcl_ObjPrintf(
+                   "Tcl_UtfNext is not supposed to read src[end]\n"
+                   "Different result when src[end] is %#x", UCHAR(p[-1])));
+           return TCL_ERROR;
+       }
+    }
+
+    Tcl_SetObjResult(interp, Tcl_NewIntObj(first - buffer - 1));
+
+    return TCL_OK;
+}
+/*
+ * Used to check operations of Tcl_UtfPrev.
+ *
+ * Usage: testutfprev $bytes $offset
+ */
+
+static int
+TestUtfPrevCmd(
+    ClientData clientData,
+    Tcl_Interp *interp,
+    int objc,
+    Tcl_Obj *const objv[])
+{
+    int numBytes, offset;
+    char *bytes;
+    const char *result;
+
+    if (objc < 2 || objc > 3) {
+       Tcl_WrongNumArgs(interp, 1, objv, "bytes ?offset?");
+       return TCL_ERROR;
+    }
+
+    bytes = Tcl_GetStringFromObj(objv[1], &numBytes);
+
+    if (objc == 3) {
+       if (TCL_OK != TclGetIntForIndex(interp, objv[2], numBytes, &offset)) {
+           return TCL_ERROR;
+       }
+       if (offset < 0) {
+           offset = 0;
+       }
+       if (offset > numBytes) {
+           offset = numBytes;
+       }
+    } else {
+       offset = numBytes;
+    }
+    result = TclUtfPrev(bytes + offset, bytes);
+    Tcl_SetObjResult(interp, Tcl_NewIntObj(result - bytes));
+    return TCL_OK;
+}
+\f
+/*
  * Used to check correct string-length determining in Tcl_NumUtfChars
  */
 
@@ -6757,12 +6890,18 @@ TestNumUtfCharsCmd(
     Tcl_Obj *const objv[])
 {
     if (objc > 1) {
-       int len = -1;
+       int numBytes, len, limit = -1;
+       const char *bytes = Tcl_GetStringFromObj(objv[1], &numBytes);
 
        if (objc > 2) {
-           (void) Tcl_GetIntFromObj(interp, objv[2], &len);
+           if (TclGetIntForIndex(interp, objv[2], numBytes, &limit) != TCL_OK) {
+               return TCL_ERROR;
+           }
+           if (limit > numBytes + 1) {
+               limit = numBytes + 1;
+           }
        }
-       len = Tcl_NumUtfChars(Tcl_GetString(objv[1]), len);
+       len = Tcl_NumUtfChars(bytes, limit);
        Tcl_SetObjResult(interp, Tcl_NewIntObj(len));
     }
     return TCL_OK;
@@ -6874,7 +7013,7 @@ TestcpuidCmd(
 
 static int
 TestHashSystemHashCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const objv[])
@@ -6886,6 +7025,7 @@ TestHashSystemHashCmd(
     Tcl_HashTable hash;
     Tcl_HashEntry *hPtr;
     int i, isNew, limit = 100;
+    (void)dummy;
 
     if (objc>1 && Tcl_GetIntFromObj(interp, objv[1], &limit)!=TCL_OK) {
        return TCL_ERROR;
@@ -6955,6 +7095,8 @@ TestgetintCmd(
     int argc,
     const char **argv)
 {
+    (void)dummy;
+
     if (argc < 2) {
        Tcl_SetResult(interp, "wrong # args", TCL_STATIC);
        return TCL_ERROR;
@@ -6979,6 +7121,7 @@ NREUnwind_callback(
     int result)
 {
     int none;
+    (void)result;
 
     if (data[0] == INT2PTR(-1)) {
         Tcl_NRAddCallback(interp, NREUnwind_callback, &none, INT2PTR(-1),
@@ -7001,11 +7144,15 @@ NREUnwind_callback(
 
 static int
 TestNREUnwind(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const objv[])
 {
+    (void)dummy;
+    (void)objc;
+    (void)objv;
+
     /*
      * Insure that callbacks effectively run at the proper level during the
      * unwinding of the NRE stack.
@@ -7019,7 +7166,7 @@ TestNREUnwind(
 
 static int
 TestNRELevels(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const objv[])
@@ -7030,6 +7177,9 @@ TestNRELevels(
     Tcl_Obj *levels[6];
     int i = 0;
     NRE_callback *cbPtr = iPtr->execEnvPtr->callbackPtr;
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     if (refDepth == NULL) {
        refDepth = &depth;
@@ -7250,8 +7400,6 @@ TestconcatobjCmd(
                "\n\t* (e) concatObj does not have refCount 0", NULL);
     }
     if (concatPtr == tmpPtr) {
-       int len;
-
        result = TCL_ERROR;
        Tcl_AppendResult(interp, "\n\t* (e) concatObj is not a new obj ",
                NULL);
@@ -7282,8 +7430,6 @@ TestconcatobjCmd(
                "\n\t* (f) concatObj does not have refCount 0", NULL);
     }
     if (concatPtr == tmpPtr) {
-       int len;
-
        result = TCL_ERROR;
        Tcl_AppendResult(interp, "\n\t* (f) concatObj is not a new obj ",
                NULL);
@@ -7315,8 +7461,6 @@ TestconcatobjCmd(
                "\n\t* (g) concatObj does not have refCount 0", NULL);
     }
     if (concatPtr == tmpPtr) {
-       int len;
-
        result = TCL_ERROR;
        Tcl_AppendResult(interp, "\n\t* (g) concatObj is not a new obj ",
                NULL);
@@ -7411,7 +7555,7 @@ static int
 InterpCmdResolver(
     Tcl_Interp *interp,
     const char *name,
-    Tcl_Namespace *context,
+    Tcl_Namespace *dummy,
     int flags,
     Tcl_Command *rPtr)
 {
@@ -7421,6 +7565,7 @@ InterpCmdResolver(
             varFramePtr->procPtr : NULL;
     Namespace *callerNsPtr = varFramePtr->nsPtr;
     Tcl_Command resolvedCmdPtr = NULL;
+    (void)dummy;
 
     /*
      * Just do something special on a cmd literal "z" in two cases:
@@ -7633,7 +7778,7 @@ TestInterpResolverCmd(
        return TCL_ERROR;
     }
     if (objc == 3) {
-       interp = Tcl_GetSlave(interp, Tcl_GetString(objv[2]));
+       interp = Tcl_GetChild(interp, Tcl_GetString(objv[2]));
        if (interp == NULL) {
            Tcl_AppendResult(interp, "provided interpreter not found", NULL);
            return TCL_ERROR;
index f741714..3fe9d02 100644 (file)
@@ -53,7 +53,7 @@ static int            TeststringobjCmd(ClientData dummy, Tcl_Interp *interp,
 
 static void VarPtrDeleteProc(ClientData clientData, Tcl_Interp *interp)
 {
-    register int i;
+    int i;
     Tcl_Obj **varPtr = (Tcl_Obj **) clientData;
     for (i = 0;  i < NUMBER_OF_OBJECT_VARS;  i++) {
        if (varPtr[i]) Tcl_DecrRefCount(varPtr[i]);
@@ -91,7 +91,7 @@ int
 TclObjTest_Init(
     Tcl_Interp *interp)
 {
-    register int i;
+    int i;
     /*
      * An array of Tcl_Obj pointers used in the commands that operate on or get
      * the values of Tcl object-valued variables. varPtr[i] is the i-th variable's
@@ -160,7 +160,7 @@ TestbignumobjCmd(
     };
     int index, varIndex;
     const char *string;
-    mp_int bignumValue, newValue;
+    mp_int bignumValue;
     Tcl_Obj **varPtr;
 
     if (objc < 3) {
@@ -233,19 +233,16 @@ TestbignumobjCmd(
                &bignumValue) != TCL_OK) {
            return TCL_ERROR;
        }
-       if (mp_init(&newValue) != MP_OKAY
-               || (mp_mul_d(&bignumValue, 10, &newValue) != MP_OKAY)) {
+       if (mp_mul_d(&bignumValue, 10, &bignumValue) != MP_OKAY) {
            mp_clear(&bignumValue);
-           mp_clear(&newValue);
            Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("error in mp_mul_d", -1));
            return TCL_ERROR;
        }
-       mp_clear(&bignumValue);
        if (!Tcl_IsShared(varPtr[varIndex])) {
-           Tcl_SetBignumObj(varPtr[varIndex], &newValue);
+           Tcl_SetBignumObj(varPtr[varIndex], &bignumValue);
        } else {
-           SetVarToObj(varPtr, varIndex, Tcl_NewBignumObj(&newValue));
+           SetVarToObj(varPtr, varIndex, Tcl_NewBignumObj(&bignumValue));
        }
        break;
 
@@ -261,19 +258,16 @@ TestbignumobjCmd(
                &bignumValue) != TCL_OK) {
            return TCL_ERROR;
        }
-       if (mp_init(&newValue) != MP_OKAY
-               || (mp_div_d(&bignumValue, 10, &newValue, NULL) != MP_OKAY)) {
+       if (mp_div_d(&bignumValue, 10, &bignumValue, NULL) != MP_OKAY) {
            mp_clear(&bignumValue);
-           mp_clear(&newValue);
            Tcl_SetObjResult(interp,
                    Tcl_NewStringObj("error in mp_div_d", -1));
            return TCL_ERROR;
        }
-       mp_clear(&bignumValue);
        if (!Tcl_IsShared(varPtr[varIndex])) {
-           Tcl_SetBignumObj(varPtr[varIndex], &newValue);
+           Tcl_SetBignumObj(varPtr[varIndex], &bignumValue);
        } else {
-           SetVarToObj(varPtr, varIndex, Tcl_NewBignumObj(&newValue));
+           SetVarToObj(varPtr, varIndex, Tcl_NewBignumObj(&bignumValue));
        }
        break;
 
@@ -289,10 +283,16 @@ TestbignumobjCmd(
                &bignumValue) != TCL_OK) {
            return TCL_ERROR;
        }
+       if (mp_mod_2d(&bignumValue, 1, &bignumValue) != MP_OKAY) {
+           mp_clear(&bignumValue);
+           Tcl_SetObjResult(interp,
+                   Tcl_NewStringObj("error in mp_mod_2d", -1));
+           return TCL_ERROR;
+       }
        if (!Tcl_IsShared(varPtr[varIndex])) {
-           Tcl_SetIntObj(varPtr[varIndex], !mp_isodd(&bignumValue));
+           Tcl_SetIntObj(varPtr[varIndex], mp_iszero(&bignumValue));
        } else {
-           SetVarToObj(varPtr, varIndex, Tcl_NewIntObj(!mp_isodd(&bignumValue)));
+           SetVarToObj(varPtr, varIndex, Tcl_NewIntObj(mp_iszero(&bignumValue)));
        }
        mp_clear(&bignumValue);
        break;
index 198fa6a..03937de 100644 (file)
@@ -88,13 +88,13 @@ Tcl_GetThreadData(
 
     if (result == NULL) {
        result = ckalloc(size);
-       memset(result, 0, (size_t) size);
+       memset(result, 0, size);
        TclThreadStorageKeySet(keyPtr, result);
     }
 #else /* TCL_THREADS */
     if (*keyPtr == NULL) {
        result = ckalloc(size);
-       memset(result, 0, (size_t)size);
+       memset(result, 0, size);
        *keyPtr = result;
        RememberSyncObject(keyPtr, &keyRecord);
     } else {
@@ -141,7 +141,7 @@ TclThreadDataKeyGet(
  *     Keep a list of (mutexes/condition variable/data key) used during
  *     finalization.
  *
- *     Assume master lock is held.
+ *     Assume global lock is held.
  *
  * Results:
  *     None.
@@ -202,7 +202,7 @@ RememberSyncObject(
  * ForgetSyncObject
  *
  *     Remove a single object from the list.
- *     Assume master lock is held.
+ *     Assume global lock is held.
  *
  * Results:
  *     None.
@@ -234,7 +234,7 @@ ForgetSyncObject(
  * TclRememberMutex
  *
  *     Keep a list of mutexes used during finalization.
- *     Assume master lock is held.
+ *     Assume global lock is held.
  *
  * Results:
  *     None.
@@ -276,9 +276,9 @@ Tcl_MutexFinalize(
 #ifdef TCL_THREADS
     TclpFinalizeMutex(mutexPtr);
 #endif
-    TclpMasterLock();
+    TclpGlobalLock();
     ForgetSyncObject(mutexPtr, &mutexRecord);
-    TclpMasterUnlock();
+    TclpGlobalUnlock();
 }
 \f
 /*
@@ -287,7 +287,7 @@ Tcl_MutexFinalize(
  * TclRememberCondition
  *
  *     Keep a list of condition variables used during finalization.
- *     Assume master lock is held.
+ *     Assume global lock is held.
  *
  * Results:
  *     None.
@@ -329,9 +329,9 @@ Tcl_ConditionFinalize(
 #ifdef TCL_THREADS
     TclpFinalizeCondition(condPtr);
 #endif
-    TclpMasterLock();
+    TclpGlobalLock();
     ForgetSyncObject(condPtr, &condRecord);
-    TclpMasterUnlock();
+    TclpGlobalUnlock();
 }
 \f
 /*
@@ -393,7 +393,7 @@ TclFinalizeSynchronization(void)
     Tcl_Mutex *mutexPtr;
     Tcl_Condition *condPtr;
 
-    TclpMasterLock();
+    TclpGlobalLock();
 #endif
 
     /*
@@ -415,7 +415,7 @@ TclFinalizeSynchronization(void)
 
 #ifdef TCL_THREADS
     /*
-     * Call thread storage master cleanup.
+     * Call thread storage global cleanup.
      */
 
     TclFinalizeThreadStorage();
@@ -446,7 +446,7 @@ TclFinalizeSynchronization(void)
     condRecord.max = 0;
     condRecord.num = 0;
 
-    TclpMasterUnlock();
+    TclpGlobalUnlock();
 #endif /* TCL_THREADS */
 }
 \f
index 2ee758e..5a1e8ca 100644 (file)
@@ -257,7 +257,7 @@ TclFreeAllocCache(
 {
     Cache *cachePtr = arg;
     Cache **nextPtrPtr;
-    register unsigned int bucket;
+    unsigned int bucket;
 
     /*
      * Flush blocks.
@@ -314,7 +314,7 @@ TclpAlloc(
 {
     Cache *cachePtr;
     Block *blockPtr;
-    register int bucket;
+    int bucket;
     size_t size;
 
 #ifndef __LP64__
@@ -546,8 +546,8 @@ TclpRealloc(
 Tcl_Obj *
 TclThreadAllocObj(void)
 {
-    register Cache *cachePtr;
-    register Tcl_Obj *objPtr;
+    Cache *cachePtr;
+    Tcl_Obj *objPtr;
 
     GETCACHE(cachePtr);
 
@@ -557,7 +557,7 @@ TclThreadAllocObj(void)
      */
 
     if (cachePtr->numObjects == 0) {
-       register int numMove;
+       int numMove;
 
        Tcl_MutexLock(objLockPtr);
        numMove = sharedPtr->numObjects;
@@ -718,7 +718,7 @@ MoveObjs(
     Cache *toPtr,
     int numMove)
 {
-    register Tcl_Obj *objPtr = fromPtr->firstObjPtr;
+    Tcl_Obj *objPtr = fromPtr->firstObjPtr;
     Tcl_Obj *fromFirstObjPtr = objPtr;
 
     toPtr->numObjects += numMove;
@@ -819,7 +819,7 @@ Block2Ptr(
     int bucket,
     unsigned int reqSize)
 {
-    register void *ptr;
+    void *ptr;
 
     blockPtr->magicNum1 = blockPtr->magicNum2 = MAGIC;
     blockPtr->sourceBucket = bucket;
@@ -835,7 +835,7 @@ static Block *
 Ptr2Block(
     char *ptr)
 {
-    register Block *blockPtr;
+    Block *blockPtr;
 
     blockPtr = (((Block *) ptr) - 1);
     if (blockPtr->magicNum1 != MAGIC || blockPtr->magicNum2 != MAGIC) {
@@ -969,8 +969,8 @@ GetBlocks(
     Cache *cachePtr,
     int bucket)
 {
-    register Block *blockPtr;
-    register int n;
+    Block *blockPtr;
+    int n;
 
     /*
      * First, atttempt to move blocks from the shared cache. Note the
@@ -1015,7 +1015,7 @@ GetBlocks(
     }
 
     if (cachePtr->buckets[bucket].numFree == 0) {
-       register size_t size;
+       size_t size;
 
        /*
         * If no blocks could be moved from shared, first look for a larger
index 755a461..ad8c50f 100644 (file)
  */
 
 /*
- * The master collection of information about TSDs. This is shared across the
+ * The global collection of information about TSDs. This is shared across the
  * whole process, and includes the mutex used to protect it.
  */
 
-static struct TSDMaster {
+static struct {
     void *key;                 /* Key into the system TSD structure. The
                                 * collection of Tcl TSD values for a
                                 * particular thread will hang off the
@@ -41,13 +41,13 @@ static struct TSDMaster {
                                 * increasing value. */
     Tcl_Mutex mutex;           /* Protection for the rest of this structure,
                                 * which holds per-process data. */
-} tsdMaster = { NULL, 0, NULL };
+} tsdGlobal = { NULL, 0, NULL };
 
 /*
  * The type of the data held per thread in a system TSD.
  */
 
-typedef struct TSDTable {
+typedef struct {
     ClientData *tablePtr;      /* The table of Tcl TSDs. */
     sig_atomic_t allocated;    /* The size of the table in the current
                                 * thread. */
@@ -57,7 +57,7 @@ typedef struct TSDTable {
  * The actual type of Tcl_ThreadDataKey.
  */
 
-typedef union TSDUnion {
+typedef union {
     volatile sig_atomic_t offset;
                                /* The type is really an offset into the
                                 * thread-local table of TSDs, which is this
@@ -189,7 +189,7 @@ void *
 TclThreadStorageKeyGet(
     Tcl_ThreadDataKey *dataKeyPtr)
 {
-    TSDTable *tsdTablePtr = TclpThreadGetMasterTSD(tsdMaster.key);
+    TSDTable *tsdTablePtr = TclpThreadGetGlobalTSD(tsdGlobal.key);
     ClientData resultPtr = NULL;
     TSDUnion *keyPtr = (TSDUnion *) dataKeyPtr;
     sig_atomic_t offset = keyPtr->offset;
@@ -223,12 +223,12 @@ TclThreadStorageKeySet(
     Tcl_ThreadDataKey *dataKeyPtr,
     void *value)
 {
-    TSDTable *tsdTablePtr = TclpThreadGetMasterTSD(tsdMaster.key);
+    TSDTable *tsdTablePtr = TclpThreadGetGlobalTSD(tsdGlobal.key);
     TSDUnion *keyPtr = (TSDUnion *) dataKeyPtr;
 
     if (tsdTablePtr == NULL) {
        tsdTablePtr = TSDTableCreate();
-       TclpThreadSetMasterTSD(tsdMaster.key, tsdTablePtr);
+       TclpThreadSetGlobalTSD(tsdGlobal.key, tsdTablePtr);
     }
 
     /*
@@ -240,15 +240,15 @@ TclThreadStorageKeySet(
      */
 
     if (keyPtr->offset == 0) {
-       Tcl_MutexLock(&tsdMaster.mutex);
+       Tcl_MutexLock(&tsdGlobal.mutex);
        if (keyPtr->offset == 0) {
            /*
             * The Tcl_ThreadDataKey hasn't been used yet. Make a new one.
             */
 
-           keyPtr->offset = ++tsdMaster.counter;
+           keyPtr->offset = ++tsdGlobal.counter;
        }
-       Tcl_MutexUnlock(&tsdMaster.mutex);
+       Tcl_MutexUnlock(&tsdGlobal.mutex);
     }
 
     /*
@@ -288,11 +288,11 @@ TclThreadStorageKeySet(
 void
 TclFinalizeThreadDataThread(void)
 {
-    TSDTable *tsdTablePtr = TclpThreadGetMasterTSD(tsdMaster.key);
+    TSDTable *tsdTablePtr = TclpThreadGetGlobalTSD(tsdGlobal.key);
 
     if (tsdTablePtr != NULL) {
        TSDTableDelete(tsdTablePtr);
-       TclpThreadSetMasterTSD(tsdMaster.key, NULL);
+       TclpThreadSetGlobalTSD(tsdGlobal.key, NULL);
     }
 }
 \f
@@ -316,7 +316,7 @@ TclFinalizeThreadDataThread(void)
 void
 TclInitThreadStorage(void)
 {
-    tsdMaster.key = TclpThreadCreateKey();
+    tsdGlobal.key = TclpThreadCreateKey();
 }
 \f
 /*
@@ -339,8 +339,8 @@ TclInitThreadStorage(void)
 void
 TclFinalizeThreadStorage(void)
 {
-    TclpThreadDeleteKey(tsdMaster.key);
-    tsdMaster.key = NULL;
+    TclpThreadDeleteKey(tsdGlobal.key);
+    tsdGlobal.key = NULL;
 }
 \f
 #else /* !TCL_THREADS */
index 35b3fc3..ff18077 100644 (file)
@@ -294,7 +294,7 @@ ThreadObjCmd(
            script = Tcl_GetStringFromObj(objv[2], &len);
 
            if ((len > 1) && (script[0] == '-') && (script[1] == 'j') &&
-                   (0 == strncmp(script, "-joinable", (size_t) len))) {
+                   (0 == strncmp(script, "-joinable", len))) {
                joinable = 1;
                script = "testthread wait";     /* Just enter event loop */
            } else {
@@ -311,7 +311,7 @@ ThreadObjCmd(
 
            script = Tcl_GetStringFromObj(objv[2], &len);
            joinable = ((len > 1) && (script[0] == '-') && (script[1] == 'j')
-                   && (0 == strncmp(script, "-joinable", (size_t) len)));
+                   && (0 == strncmp(script, "-joinable", len)));
            script = Tcl_GetString(objv[3]);
        } else {
            Tcl_WrongNumArgs(interp, 2, objv, "?-joinable? ?script?");
index 5755edc..d30879f 100644 (file)
@@ -217,7 +217,7 @@ TimerExitProc(
 
     Tcl_DeleteEventSource(TimerSetupProc, TimerCheckProc, NULL);
     if (tsdPtr != NULL) {
-       register TimerHandler *timerHandlerPtr;
+       TimerHandler *timerHandlerPtr;
 
        timerHandlerPtr = tsdPtr->firstTimerHandlerPtr;
        while (timerHandlerPtr != NULL) {
@@ -294,7 +294,7 @@ TclCreateAbsoluteTimerHandler(
     Tcl_TimerProc *proc,
     ClientData clientData)
 {
-    register TimerHandler *timerHandlerPtr, *tPtr2, *prevPtr;
+    TimerHandler *timerHandlerPtr, *tPtr2, *prevPtr;
     ThreadSpecificData *tsdPtr = InitTimer();
 
     timerHandlerPtr = ckalloc(sizeof(TimerHandler));
@@ -355,7 +355,7 @@ Tcl_DeleteTimerHandler(
     Tcl_TimerToken token)      /* Result previously returned by
                                 * Tcl_DeleteTimerHandler. */
 {
-    register TimerHandler *timerHandlerPtr, *prevPtr;
+    TimerHandler *timerHandlerPtr, *prevPtr;
     ThreadSpecificData *tsdPtr = InitTimer();
 
     if (token == NULL) {
@@ -621,7 +621,7 @@ Tcl_DoWhenIdle(
     Tcl_IdleProc *proc,                /* Function to invoke. */
     ClientData clientData)     /* Arbitrary value to pass to proc. */
 {
-    register IdleHandler *idlePtr;
+    IdleHandler *idlePtr;
     Tcl_Time blockTime;
     ThreadSpecificData *tsdPtr = InitTimer();
 
@@ -665,7 +665,7 @@ Tcl_CancelIdleCall(
     Tcl_IdleProc *proc,                /* Function that was previously registered. */
     ClientData clientData)     /* Arbitrary value to pass to proc. */
 {
-    register IdleHandler *idlePtr, *prevPtr;
+    IdleHandler *idlePtr, *prevPtr;
     IdleHandler *nextPtr;
     ThreadSpecificData *tsdPtr = InitTimer();
 
@@ -898,7 +898,7 @@ Tcl_AfterObjCmd(
        if (objc == 3) {
            commandPtr = objv[2];
        } else {
-           commandPtr = Tcl_ConcatObj(objc-2, objv+2);;
+           commandPtr = Tcl_ConcatObj(objc-2, objv+2);
        }
        command = Tcl_GetStringFromObj(commandPtr, &length);
        for (afterPtr = assocPtr->firstAfterPtr;  afterPtr != NULL;
@@ -906,7 +906,7 @@ Tcl_AfterObjCmd(
            tempCommand = Tcl_GetStringFromObj(afterPtr->commandPtr,
                    &tempLength);
            if ((length == tempLength)
-                   && !memcmp(command, tempCommand, (unsigned) length)) {
+                   && !memcmp(command, tempCommand, length)) {
                break;
            }
        }
index 40b182f..2511e3a 100644 (file)
@@ -220,9 +220,6 @@ declare 62 {
 declare 63 {
     int TclBN_mp_cnt_lsb(const mp_int *a)
 }
-
-# Formerly internal API to allow initialisation of bignums without knowing the
-# typedefs of how a bignum works internally.
 declare 64 {
     int TclBNInitBignumFromLong(mp_int *bignum, long initVal)
 }
@@ -241,6 +238,13 @@ declare 67 {
 declare 68 {
     void TclBN_mp_set_ull(mp_int *a, Tcl_WideUInt i)
 }
+declare 69 {
+    Tcl_WideUInt TclBN_mp_get_mag_ull(const mp_int *a)
+}
+declare 70 {
+    void TclBN_mp_set_ll(mp_int *a, Tcl_WideInt i)
+}
+
 # Added in libtommath 1.1.0
 declare 73 {
     mp_err TclBN_mp_tc_and(const mp_int *a, const mp_int *b, mp_int *c)
@@ -259,6 +263,9 @@ declare 76 {
 declare 78 {
     int TclBN_mp_to_ubin(const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written)
 }
+declare 79 {
+    mp_err TclBN_mp_div_ld(const mp_int *a, Tcl_WideUInt b, mp_int *q, Tcl_WideUInt *r)
+}
 declare 80 {
     int TclBN_mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
 }
index 3436798..6991643 100644 (file)
@@ -72,6 +72,7 @@
 #define mp_expt_d TclBN_mp_expt_d
 #define mp_expt_d_ex TclBN_mp_expt_d_ex
 #define mp_expt_u32 TclBN_mp_expt_d
+#define mp_get_mag_ull TclBN_mp_get_mag_ull
 #define mp_grow TclBN_mp_grow
 #define mp_init TclBN_mp_init
 #define mp_init_copy TclBN_mp_init_copy
@@ -93,6 +94,7 @@
 #define mp_rshd TclBN_mp_rshd
 #define mp_set TclBN_mp_set
 #define mp_set_int(a,b) (TclBN_mp_set_int(a,(unsigned int)(b)),MP_OKAY)
+#define mp_set_ll TclBN_mp_set_ll
 #define mp_set_long(a,b) (TclBN_mp_set_int(a,b),MP_OKAY)
 #define mp_set_ul(a,b) (void)TclBN_mp_set_int(a,b)
 #define mp_set_ull TclBN_mp_set_ull
@@ -323,8 +325,10 @@ EXTERN mp_err              TclBN_mp_expt_d_ex(const mp_int *a, mp_digit b,
                                mp_int *c, int fast);
 /* 68 */
 EXTERN void            TclBN_mp_set_ull(mp_int *a, Tcl_WideUInt i);
-/* Slot 69 is reserved */
-/* Slot 70 is reserved */
+/* 69 */
+EXTERN Tcl_WideUInt    TclBN_mp_get_mag_ull(const mp_int *a);
+/* 70 */
+EXTERN void            TclBN_mp_set_ll(mp_int *a, Tcl_WideInt i);
 /* Slot 71 is reserved */
 /* Slot 72 is reserved */
 /* 73 */
@@ -343,7 +347,9 @@ EXTERN mp_err               TclBN_mp_signed_rsh(const mp_int *a, int b,
 /* 78 */
 EXTERN int             TclBN_mp_to_ubin(const mp_int *a, unsigned char *buf,
                                size_t maxlen, size_t *written);
-/* Slot 79 is reserved */
+/* 79 */
+EXTERN mp_err          TclBN_mp_div_ld(const mp_int *a, Tcl_WideUInt b,
+                               mp_int *q, Tcl_WideUInt *r);
 /* 80 */
 EXTERN int             TclBN_mp_to_radix(const mp_int *a, char *str,
                                size_t maxlen, size_t *written, int radix);
@@ -421,8 +427,8 @@ typedef struct TclTomMathStubs {
     int (*tclBNInitBignumFromWideUInt) (mp_int *bignum, Tcl_WideUInt initVal); /* 66 */
     mp_err (*tclBN_mp_expt_d_ex) (const mp_int *a, mp_digit b, mp_int *c, int fast); /* 67 */
     void (*tclBN_mp_set_ull) (mp_int *a, Tcl_WideUInt i); /* 68 */
-    void (*reserved69)(void);
-    void (*reserved70)(void);
+    Tcl_WideUInt (*tclBN_mp_get_mag_ull) (const mp_int *a); /* 69 */
+    void (*tclBN_mp_set_ll) (mp_int *a, Tcl_WideInt i); /* 70 */
     void (*reserved71)(void);
     void (*reserved72)(void);
     mp_err (*tclBN_mp_tc_and) (const mp_int *a, const mp_int *b, mp_int *c); /* 73 */
@@ -431,7 +437,7 @@ typedef struct TclTomMathStubs {
     mp_err (*tclBN_mp_signed_rsh) (const mp_int *a, int b, mp_int *c); /* 76 */
     void (*reserved77)(void);
     int (*tclBN_mp_to_ubin) (const mp_int *a, unsigned char *buf, size_t maxlen, size_t *written); /* 78 */
-    void (*reserved79)(void);
+    mp_err (*tclBN_mp_div_ld) (const mp_int *a, Tcl_WideUInt b, mp_int *q, Tcl_WideUInt *r); /* 79 */
     int (*tclBN_mp_to_radix) (const mp_int *a, char *str, size_t maxlen, size_t *written, int radix); /* 80 */
 } TclTomMathStubs;
 
@@ -585,8 +591,10 @@ extern const TclTomMathStubs *tclTomMathStubsPtr;
        (tclTomMathStubsPtr->tclBN_mp_expt_d_ex) /* 67 */
 #define TclBN_mp_set_ull \
        (tclTomMathStubsPtr->tclBN_mp_set_ull) /* 68 */
-/* Slot 69 is reserved */
-/* Slot 70 is reserved */
+#define TclBN_mp_get_mag_ull \
+       (tclTomMathStubsPtr->tclBN_mp_get_mag_ull) /* 69 */
+#define TclBN_mp_set_ll \
+       (tclTomMathStubsPtr->tclBN_mp_set_ll) /* 70 */
 /* Slot 71 is reserved */
 /* Slot 72 is reserved */
 #define TclBN_mp_tc_and \
@@ -600,7 +608,8 @@ extern const TclTomMathStubs *tclTomMathStubsPtr;
 /* Slot 77 is reserved */
 #define TclBN_mp_to_ubin \
        (tclTomMathStubsPtr->tclBN_mp_to_ubin) /* 78 */
-/* Slot 79 is reserved */
+#define TclBN_mp_div_ld \
+       (tclTomMathStubsPtr->tclBN_mp_div_ld) /* 79 */
 #define TclBN_mp_to_radix \
        (tclTomMathStubsPtr->tclBN_mp_to_radix) /* 80 */
 
index 2dc8c2d..21fd238 100644 (file)
@@ -111,7 +111,6 @@ TclBNInitBignumFromLong(
     mp_int *a,
     long initVal)
 {
-    int status;
     unsigned long v;
     mp_digit *p;
 
@@ -119,8 +118,7 @@ TclBNInitBignumFromLong(
      * Allocate enough memory to hold the largest possible long
      */
 
-    status = mp_init(a);
-    if (status != MP_OKAY) {
+    if (mp_init(a) != MP_OKAY) {
        Tcl_Panic("initialization failure in TclBNInitBignumFromLong");
     }
 
@@ -130,7 +128,7 @@ TclBNInitBignumFromLong(
 
     if (initVal < 0) {
        a->sign = MP_NEG;
-       v = -initVal;
+       v = -(unsigned long)initVal;
     } else {
        a->sign = MP_ZPOS;
        v = initVal;
@@ -170,12 +168,11 @@ TclBNInitBignumFromWideInt(
     mp_int *a,                 /* Bignum to initialize */
     Tcl_WideInt v)             /* Initial value */
 {
-    if (v < (Tcl_WideInt)0) {
-       TclBNInitBignumFromWideUInt(a, (Tcl_WideUInt)(-v));
-       mp_neg(a, a);
-    } else {
-       TclBNInitBignumFromWideUInt(a, (Tcl_WideUInt)v);
+    if (v < 0) {
+       (void)TclBNInitBignumFromWideUInt(a, -(Tcl_WideUInt)v);
+       return mp_neg(a, a);
     }
+    (void)TclBNInitBignumFromWideUInt(a, (Tcl_WideUInt)v);
     return MP_OKAY;
 }
 \f
@@ -200,15 +197,13 @@ TclBNInitBignumFromWideUInt(
     mp_int *a,                 /* Bignum to initialize */
     Tcl_WideUInt v)            /* Initial value */
 {
-    int status;
     mp_digit *p;
 
     /*
      * Allocate enough memory to hold the largest possible Tcl_WideUInt.
      */
 
-    status = mp_init(a);
-    if (status != MP_OKAY) {
+    if (mp_init(a) != MP_OKAY) {
        Tcl_Panic("initialization failure in TclBNInitBignumFromWideUInt");
     }
 
index 882dc39..c82fc14 100644 (file)
@@ -136,7 +136,7 @@ static int          StringTraceProc(ClientData clientData,
 static void            StringTraceDeleteProc(ClientData clientData);
 static void            DisposeTraceResult(int flags, char *result);
 static int             TraceVarEx(Tcl_Interp *interp, const char *part1,
-                           const char *part2, register VarTrace *tracePtr);
+                           const char *part2, VarTrace *tracePtr);
 
 /*
  * The following structure holds the client data for string-based
@@ -278,7 +278,7 @@ Tcl_TraceObjCmd(
            return TCL_ERROR;
        }
 
-       opsList = Tcl_NewObj();
+       TclNewObj(opsList);
        Tcl_IncrRefCount(opsList);
        flagOps = Tcl_GetStringFromObj(objv[3], &numFlags);
        if (numFlags == 0) {
@@ -322,7 +322,7 @@ Tcl_TraceObjCmd(
            Tcl_WrongNumArgs(interp, 2, objv, "name");
            return TCL_ERROR;
        }
-       resultListPtr = Tcl_NewObj();
+       TclNewObj(resultListPtr);
        name = Tcl_GetString(objv[2]);
        FOREACH_VAR_TRACE(interp, name, clientData) {
            TraceVarInfo *tvarPtr = clientData;
@@ -967,7 +967,7 @@ TraceVariableObjCmd(
            return TCL_ERROR;
        }
 
-       resultListPtr = Tcl_NewObj();
+       TclNewObj(resultListPtr);
        name = Tcl_GetString(objv[3]);
        FOREACH_VAR_TRACE(interp, name, clientData) {
            Tcl_Obj *opObjPtr, *eachTraceObjPtr, *elemObjPtr;
@@ -1049,7 +1049,7 @@ Tcl_CommandTraceInfo(
                                 * call will return the first trace. */
 {
     Command *cmdPtr;
-    register CommandTrace *tracePtr;
+    CommandTrace *tracePtr;
 
     cmdPtr = (Command *) Tcl_FindCommand(interp, cmdName, NULL,
            TCL_LEAVE_ERR_MSG);
@@ -1114,7 +1114,7 @@ Tcl_TraceCommand(
     ClientData clientData)     /* Arbitrary argument to pass to proc. */
 {
     Command *cmdPtr;
-    register CommandTrace *tracePtr;
+    CommandTrace *tracePtr;
 
     cmdPtr = (Command *) Tcl_FindCommand(interp, cmdName, NULL,
            TCL_LEAVE_ERR_MSG);
@@ -1177,10 +1177,10 @@ Tcl_UntraceCommand(
     Tcl_CommandTraceProc *proc,        /* Function assocated with trace. */
     ClientData clientData)     /* Arbitrary argument to pass to proc. */
 {
-    register CommandTrace *tracePtr;
+    CommandTrace *tracePtr;
     CommandTrace *prevPtr;
     Command *cmdPtr;
-    Interp *iPtr = (Interp *) interp;
+    Interp *iPtr = (Interp *)interp;
     ActiveCommandTrace *activePtr;
     int hasExecTraces = 0;
 
@@ -1255,7 +1255,6 @@ Tcl_UntraceCommand(
         */
 
        if (cmdPtr->compileProc != NULL) {
-           Interp *iPtr = (Interp *) interp;
            iPtr->compileEpoch++;
        }
     }
@@ -1672,13 +1671,13 @@ TclCheckInterpTraces(
 static int
 CallTraceFunction(
     Tcl_Interp *interp,                /* The current interpreter. */
-    register Trace *tracePtr,  /* Describes the trace function to call. */
+    Trace *tracePtr,   /* Describes the trace function to call. */
     Command *cmdPtr,           /* Points to command's Command struct. */
     const char *command,       /* Points to the first character of the
                                 * command's source before substitutions. */
     int numChars,              /* The number of characters in the command's
                                 * source. */
-    register int objc,         /* Number of arguments for the command. */
+    int objc,          /* Number of arguments for the command. */
     Tcl_Obj *const objv[])     /* Pointers to Tcl_Obj of each argument. */
 {
     Interp *iPtr = (Interp *) interp;
@@ -1689,8 +1688,8 @@ CallTraceFunction(
      * Copy the command characters into a new string.
      */
 
-    commandCopy = TclStackAlloc(interp, (unsigned) numChars + 1);
-    memcpy(commandCopy, command, (size_t) numChars);
+    commandCopy = TclStackAlloc(interp, numChars + 1);
+    memcpy(commandCopy, command, numChars);
     commandCopy[numChars] = '\0';
 
     /*
@@ -1853,7 +1852,7 @@ TraceExecutionProc(
                 * Append result code.
                 */
 
-               resultCode = Tcl_NewIntObj(code);
+               TclNewIntObj(resultCode, code);
                resultCodeStr = Tcl_GetString(resultCode);
                Tcl_DStringAppendElement(&cmd, resultCodeStr);
                Tcl_DecrRefCount(resultCode);
@@ -1920,7 +1919,7 @@ TraceExecutionProc(
        if ((flags & TCL_TRACE_ENTER_EXEC) && (tcmdPtr->stepTrace == NULL)
                && (tcmdPtr->flags & (TCL_TRACE_ENTER_DURING_EXEC |
                        TCL_TRACE_LEAVE_DURING_EXEC))) {
-           register unsigned len = strlen(command) + 1;
+           unsigned len = strlen(command) + 1;
 
            tcmdPtr->startLevel = level;
            tcmdPtr->startCmd = ckalloc(len);
@@ -2065,7 +2064,7 @@ TraceVarProc(
        }
     }
     if (destroy && result != NULL) {
-       register Tcl_Obj *errMsgObj = (Tcl_Obj *) result;
+       Tcl_Obj *errMsgObj = (Tcl_Obj *) result;
 
        Tcl_DecrRefCount(errMsgObj);
        result = NULL;
@@ -2142,8 +2141,8 @@ Tcl_CreateObjTrace(
     Tcl_CmdObjTraceDeleteProc *delProc)
                                /* Function to call when trace is deleted */
 {
-    register Trace *tracePtr;
-    register Interp *iPtr = (Interp *) interp;
+    Trace *tracePtr;
+    Interp *iPtr = (Interp *) interp;
 
     /*
      * Test if this trace allows inline compilation of commands.
@@ -2342,7 +2341,7 @@ Tcl_DeleteTrace(
 {
     Interp *iPtr = (Interp *) interp;
     Trace *prevPtr, *tracePtr = (Trace *) trace;
-    register Trace **tracePtr2 = &iPtr->tracePtr;
+    Trace **tracePtr2 = &iPtr->tracePtr;
     ActiveInterpTrace *activePtr;
 
     /*
@@ -2534,7 +2533,7 @@ TclCheckArrayTraces(
 int
 TclObjCallVarTraces(
     Interp *iPtr,              /* Interpreter containing variable. */
-    register Var *arrayPtr,    /* Pointer to array variable that contains the
+    Var *arrayPtr,     /* Pointer to array variable that contains the
                                 * variable, or NULL if the variable isn't an
                                 * element of an array. */
     Var *varPtr,               /* Variable whose traces are to be invoked. */
@@ -2568,7 +2567,7 @@ TclObjCallVarTraces(
 int
 TclCallVarTraces(
     Interp *iPtr,              /* Interpreter containing variable. */
-    register Var *arrayPtr,    /* Pointer to array variable that contains the
+    Var *arrayPtr,     /* Pointer to array variable that contains the
                                 * variable, or NULL if the variable isn't an
                                 * element of an array. */
     Var *varPtr,               /* Variable whose traces are to be invoked. */
@@ -2581,7 +2580,7 @@ TclCallVarTraces(
                                 * error, then leave an error message and
                                 * stack trace information in *iPTr. */
 {
-    register VarTrace *tracePtr;
+    VarTrace *tracePtr;
     ActiveVarTrace active;
     char *result;
     const char *openParen, *p;
@@ -2909,7 +2908,7 @@ Tcl_UntraceVar2(
     Tcl_VarTraceProc *proc,    /* Function assocated with trace. */
     ClientData clientData)     /* Arbitrary argument to pass to proc. */
 {
-    register VarTrace *tracePtr;
+    VarTrace *tracePtr;
     VarTrace *prevPtr, *nextPtr;
     Var *varPtr, *arrayPtr;
     Interp *iPtr = (Interp *) interp;
@@ -3099,7 +3098,7 @@ Tcl_VarTraceInfo2(
     hPtr = Tcl_FindHashEntry(&iPtr->varTraces, (char *) varPtr);
 
     if (hPtr) {
-       register VarTrace *tracePtr = Tcl_GetHashValue(hPtr);
+       VarTrace *tracePtr = Tcl_GetHashValue(hPtr);
 
        if (prevClientData != NULL) {
            for (; tracePtr != NULL; tracePtr = tracePtr->nextPtr) {
@@ -3195,7 +3194,7 @@ Tcl_TraceVar2(
                                 * invoked upon varName. */
     ClientData clientData)     /* Arbitrary argument to pass to proc. */
 {
-    register VarTrace *tracePtr;
+    VarTrace *tracePtr;
     int result;
 
     tracePtr = ckalloc(sizeof(VarTrace));
@@ -3240,7 +3239,7 @@ TraceVarEx(
     const char *part2,         /* Name of element within array; NULL means
                                 * trace applies to scalar variable or array
                                 * as-a-whole. */
-    register VarTrace *tracePtr)/* Structure containing flags, traceProc and
+    VarTrace *tracePtr)/* Structure containing flags, traceProc and
                                 * clientData fields. Others should be left
                                 * blank. Will be ckfree()d (eventually) if
                                 * this function returns TCL_OK, and up to
index 94f5718..ad47dda 100644 (file)
@@ -41,22 +41,22 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 4224, 4256, 1344, 1344, 4288, 4320, 4352,
     4384, 4416, 1344, 4448, 4480, 4512, 4544, 1344, 4576, 4608, 4640, 4672,
     1344, 4704, 4736, 4768, 4800, 4832, 1344, 4864, 4896, 4928, 4960, 1344,
-    4992, 5024, 5056, 5088, 1824, 1824, 5120, 5152, 5184, 5216, 5248, 5280,
-    1344, 5312, 1344, 5344, 5376, 5408, 5440, 5472, 5504, 5536, 5568, 5600,
-    5632, 5664, 5696, 5632, 704, 5728, 224, 224, 224, 224, 5760, 224, 224,
-    224, 5792, 5824, 5856, 5888, 5920, 5952, 5984, 6016, 6048, 6080, 6112,
-    6144, 6176, 6208, 6240, 6272, 6304, 6336, 6368, 6400, 6432, 6464, 6496,
-    6528, 6560, 6560, 6560, 6560, 6560, 6560, 6560, 6560, 6592, 6624, 4928,
-    6656, 6688, 6720, 6752, 6784, 4928, 6816, 6848, 6880, 6912, 6944, 6976,
-    7008, 4928, 4928, 4928, 4928, 4928, 7040, 7072, 7104, 4928, 4928, 4928,
-    7136, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 7168, 7200, 4928, 7232,
-    7264, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 6560, 6560, 6560,
-    6560, 7296, 6560, 7328, 7360, 6560, 6560, 6560, 6560, 6560, 6560, 6560,
-    6560, 4928, 7392, 7424, 7456, 7488, 4928, 4928, 4928, 7520, 7552, 7584,
-    7616, 224, 224, 224, 7648, 7680, 7712, 1344, 7744, 7776, 7808, 7808,
-    704, 7840, 7872, 7904, 1824, 7936, 4928, 4928, 7968, 4928, 4928, 4928,
-    4928, 4928, 4928, 8000, 8032, 8064, 8096, 3232, 1344, 8128, 4192, 1344,
-    8160, 8192, 8224, 1344, 1344, 8256, 8288, 4928, 8320, 8352, 8384, 8416,
+    4992, 5024, 5056, 5088, 5120, 1824, 5152, 5184, 5216, 5248, 5280, 5312,
+    1344, 5344, 1344, 5376, 5408, 5440, 5472, 5504, 5536, 5568, 5600, 5632,
+    5664, 5696, 5728, 5664, 704, 5760, 224, 224, 224, 224, 5792, 224, 224,
+    224, 5824, 5856, 5888, 5920, 5952, 5984, 6016, 6048, 6080, 6112, 6144,
+    6176, 6208, 6240, 6272, 6304, 6336, 6368, 6400, 6432, 6464, 6496, 6528,
+    6560, 6592, 6592, 6592, 6592, 6592, 6592, 6592, 6592, 6624, 6656, 4928,
+    6688, 6720, 6752, 6784, 6816, 4928, 6848, 6880, 6912, 6944, 6976, 7008,
+    7040, 4928, 4928, 4928, 4928, 4928, 7072, 7104, 7136, 4928, 4928, 4928,
+    7168, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 7200, 7232, 4928, 7264,
+    7296, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 6592, 6592, 6592,
+    6592, 7328, 6592, 7360, 7392, 6592, 6592, 6592, 6592, 6592, 6592, 6592,
+    6592, 4928, 7424, 7456, 7488, 7520, 4928, 4928, 4928, 7552, 7584, 7616,
+    7648, 224, 224, 224, 7680, 7712, 7744, 1344, 7776, 7808, 7840, 7840,
+    704, 7872, 7904, 7936, 1824, 7968, 4928, 4928, 8000, 4928, 4928, 4928,
+    4928, 4928, 4928, 8032, 8064, 8096, 8128, 3232, 1344, 8160, 4192, 1344,
+    8192, 8224, 8256, 1344, 1344, 8288, 1344, 4928, 8320, 8352, 8384, 8416,
     4928, 8384, 8448, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928,
     4928, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -75,7 +75,7 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 4704, 4928, 4928, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 4928, 4928, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -133,12 +133,12 @@ static const unsigned short pageMap[] = {
     8480, 8512, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 8544, 4928, 8576, 5408, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 8544, 4928, 8576, 5440, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 8608, 8640, 224, 8672, 8704, 1344, 1344, 8736, 8768, 8800, 224,
     8832, 8864, 8896, 8928, 8960, 8992, 9024, 1344, 9056, 9088, 9120, 9152,
-    9184, 1632, 9216, 9248, 9280, 1952, 9312, 9344, 9376, 1344, 9408, 9440,
-    9472, 1344, 9504, 9536, 9568, 9600, 9632, 9664, 9696, 9728, 9728, 1344,
-    9760, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    9184, 1632, 9216, 9248, 8480, 1952, 9280, 9312, 9344, 1344, 9376, 9408,
+    9440, 1344, 9472, 9504, 9536, 9568, 9600, 9632, 9664, 9696, 9696, 1344,
+    9728, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -167,73 +167,73 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 9792, 9824, 9856, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    1344, 1344, 9760, 9792, 9824, 9856, 9856, 9856, 9856, 9856, 9856, 9856,
+    9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856,
+    9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856,
+    9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856,
+    9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856,
+    9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9856, 9888, 9888, 9888,
     9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
     9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
     9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
     9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
-    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920, 9920,
-    9920, 9920, 9920, 9920, 9920, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 9952, 1344, 1344, 9984, 1824, 10016, 10048,
-    10080, 1344, 1344, 10112, 10144, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 10176, 10208, 1344, 10240, 1344, 10272, 10304,
-    10336, 10368, 10400, 10432, 1344, 1344, 1344, 10464, 10496, 64, 10528,
-    10560, 10592, 4736, 10624, 10656
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888, 9888,
+    9888, 9888, 9888, 9888, 9888, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 9920, 1344, 1344, 9952, 1824, 9984, 10016,
+    10048, 1344, 1344, 10080, 10112, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 10144, 10176, 1344, 10208, 1344, 10240, 10272,
+    10304, 10336, 10368, 10400, 1344, 1344, 1344, 10432, 10464, 64, 10496,
+    10528, 10560, 4736, 10592, 10624
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
-    ,10688, 10720, 10752, 1824, 1344, 1344, 1344, 8288, 10784, 10816, 10848,
-    10880, 10912, 10944, 10976, 11008, 1824, 1824, 1824, 1824, 9280, 1344,
-    11040, 11072, 1344, 11104, 11136, 11168, 11200, 1344, 11232, 1824,
-    11264, 11296, 11328, 1344, 11360, 11392, 11424, 11456, 1344, 11488,
-    1344, 11520, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 7776, 4704, 10272, 1824, 1824, 1824, 1824,
-    11552, 11584, 11616, 11648, 4736, 11680, 1824, 11712, 11744, 11776,
-    1824, 1824, 1344, 11808, 11840, 6880, 11872, 11904, 11936, 11968, 12000,
-    1824, 12032, 12064, 1344, 12096, 12128, 12160, 12192, 12224, 1824,
-    1824, 1344, 1344, 12256, 1824, 12288, 12320, 12352, 12384, 1344, 12416,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 12448, 1824,
-    1824, 1824, 1824, 12000, 12480, 12512, 1824, 1824, 1824, 1824, 7776,
-    12544, 12576, 12608, 12640, 5248, 12672, 12704, 12736, 12768, 12800,
-    12832, 12864, 5248, 12896, 12928, 12960, 12992, 13024, 1824, 1824,
-    13056, 13088, 13120, 13152, 13184, 13216, 13248, 13280, 1824, 1824,
-    1824, 1824, 1344, 13312, 13344, 1824, 1344, 13376, 13408, 1824, 1824,
-    1824, 1824, 1824, 1344, 13440, 13472, 1824, 1344, 13504, 13536, 13568,
-    1344, 13600, 13632, 1824, 4032, 13664, 1824, 1824, 1824, 1824, 1824,
-    1824, 1344, 13696, 1824, 1824, 1824, 13728, 13760, 13792, 1824, 1824,
-    1824, 1824, 1824, 13824, 13856, 13888, 13920, 13952, 13984, 1344, 14016,
-    14048, 1344, 4608, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    14080, 14112, 14144, 14176, 14208, 14240, 1824, 1824, 14272, 14304,
-    14336, 14368, 14400, 13632, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 14432, 1824, 1824, 1824, 1824, 1824, 1824, 14464, 14496,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    ,10656, 10688, 10720, 1824, 1344, 1344, 1344, 10752, 10784, 10816,
+    10848, 10880, 10912, 10944, 10976, 11008, 1824, 1824, 1824, 1824, 8480,
+    1344, 11040, 11072, 1344, 11104, 11136, 11168, 11200, 1344, 11232,
+    1824, 11264, 11296, 11328, 1344, 11360, 11392, 11424, 11456, 1344,
+    11488, 1344, 11520, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 7808, 4704, 10240, 1824, 1824, 1824,
+    1824, 11552, 11584, 11616, 11648, 4736, 11680, 1824, 11712, 11744,
+    11776, 1824, 1824, 1344, 11808, 11840, 6912, 11872, 11904, 11936, 11968,
+    12000, 1824, 12032, 12064, 1344, 12096, 12128, 12160, 12192, 12224,
+    1824, 1824, 1344, 1344, 12256, 1824, 12288, 12320, 12352, 12384, 1344,
+    12416, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 12448,
+    1344, 12480, 1824, 1824, 12000, 12512, 12544, 1824, 1824, 10176, 12576,
+    7808, 12608, 12640, 12672, 12704, 5280, 12736, 12768, 12800, 12832,
+    12864, 12896, 12928, 5280, 12960, 12992, 13024, 13056, 13088, 1824,
+    1824, 13120, 13152, 13184, 13216, 13248, 13280, 13312, 13344, 1824,
+    1824, 1824, 1824, 1344, 13376, 13408, 13440, 1344, 13472, 13504, 1824,
+    1824, 1824, 1824, 1824, 1344, 13536, 13568, 1824, 1344, 13600, 13632,
+    13664, 1344, 13696, 13728, 1824, 4032, 13760, 1824, 1824, 1824, 1824,
+    1824, 1824, 1344, 13792, 1824, 1824, 1824, 13824, 13856, 13888, 13920,
+    13952, 13984, 1824, 1824, 14016, 14048, 14080, 14112, 14144, 14176,
+    1344, 14208, 14240, 1344, 4608, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 14272, 14304, 14336, 14368, 14400, 14432, 1824, 1824, 14464,
+    14496, 14528, 14560, 14592, 13728, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 14624, 1824, 1824, 1824, 1824, 1824, 14656, 14688,
+    14720, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 9984, 1824, 1824, 1824, 10848, 10848, 10848,
-    14528, 1344, 1344, 1344, 1344, 1344, 1344, 14560, 1824, 1824, 1824,
+    1344, 1344, 1344, 1344, 1344, 1344, 9952, 1824, 1824, 1824, 10848,
+    10848, 10848, 14752, 1344, 1344, 1344, 1344, 1344, 1344, 14784, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 14592, 1824, 1824, 1824,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 14816, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
@@ -244,8 +244,8 @@ static const unsigned short pageMap[] = {
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 14624, 1824,
+    1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 14848,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
@@ -268,12 +268,13 @@ static const unsigned short pageMap[] = {
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 4608, 4736, 14656,
-    1824, 1824, 10208, 14688, 1344, 14720, 14752, 14784, 8480, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 4608, 4736,
+    14880, 1824, 1824, 10176, 14912, 1344, 14944, 14976, 15008, 15040,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 13728, 13760, 14816, 1824,
-    1824, 1824, 1344, 1344, 14848, 14880, 14912, 1824, 1824, 14944, 1344,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 13824, 13856,
+    15072, 1824, 1824, 1824, 1344, 1344, 15104, 15136, 15168, 1824, 1824,
+    15200, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -289,10 +290,10 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 14976,
+    1344, 15232, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 15008,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 4704, 1824, 12256, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
@@ -316,16 +317,15 @@ static const unsigned short pageMap[] = {
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 4736, 1824, 15040, 15072, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 9856, 1824, 1824, 1824,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 4736, 1824, 15264,
+    15296, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 9824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344,
-    15104, 15136, 15168, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1344, 1344, 1344, 15328, 15360, 15392, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
@@ -338,41 +338,41 @@ static const unsigned short pageMap[] = {
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 8000, 4928, 15200,
-    4928, 15232, 15264, 15296, 4928, 15328, 4928, 4928, 15360, 1824, 1824,
-    1824, 1824, 15392, 4928, 4928, 15424, 15456, 1824, 1824, 1824, 1824,
-    15488, 15520, 15552, 15584, 15616, 15648, 15680, 15712, 15744, 15776,
-    15808, 15840, 15872, 15488, 15520, 15904, 15584, 15936, 15968, 16000,
-    15712, 16032, 16064, 16096, 16128, 16160, 16192, 16224, 16256, 16288,
-    16320, 16352, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928,
-    4928, 4928, 4928, 4928, 4928, 4928, 4928, 704, 16384, 704, 16416, 16448,
-    16480, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 4928, 4928, 4928, 4928, 4928,
+    4928, 4928, 8032, 4928, 15424, 4928, 15456, 15488, 15520, 4928, 15552,
+    4928, 4928, 15584, 1824, 1824, 1824, 1824, 15616, 4928, 4928, 15648,
+    15680, 1824, 1824, 1824, 1824, 15712, 15744, 15776, 15808, 15840, 15872,
+    15904, 15936, 15968, 16000, 16032, 16064, 16096, 15712, 15744, 16128,
+    15808, 16160, 16192, 16224, 15936, 16256, 16288, 16320, 16352, 16384,
+    16416, 16448, 16480, 16512, 16544, 16576, 4928, 4928, 4928, 4928, 4928,
+    4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 704,
+    16608, 704, 16640, 16672, 16704, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 16512, 16544, 1824,
-    1824, 1824, 1824, 1824, 1824, 1344, 16576, 16608, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 16640, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    16736, 16768, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 16800, 16832,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344,
+    16864, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 16672, 1824,
-    16704, 16736, 16768, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344,
+    16896, 1824, 16928, 16960, 16992, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 16800, 6880, 16832, 1824, 1824, 16864, 16896,
-    1824, 1824, 1824, 1824, 1824, 1824, 16928, 16960, 16992, 17024, 17056,
-    17088, 1824, 17120, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    4928, 17152, 4928, 4928, 7968, 17184, 17216, 8000, 17248, 4928, 4928,
-    17280, 4928, 17312, 1824, 17344, 17376, 17408, 17440, 17472, 1824,
-    1824, 1824, 1824, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 17504,
+    1824, 1824, 1824, 1824, 1824, 1824, 17024, 6912, 17056, 1824, 1824,
+    17088, 17120, 1824, 1824, 1824, 1824, 1824, 1824, 17152, 17184, 17216,
+    17248, 17280, 17312, 1824, 17344, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 4928, 17376, 4928, 4928, 8000, 17408, 17440, 8032, 17472,
+    4928, 4928, 4928, 4928, 17504, 1824, 17536, 17568, 17600, 17632, 17664,
+    1824, 1824, 1824, 1824, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 17696,
     4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928,
-    4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 8000, 17536,
-    4928, 4928, 4928, 7968, 4928, 4928, 17568, 17600, 17152, 4928, 17632,
-    4928, 17664, 17696, 1824, 1824, 17728, 4928, 4928, 17760, 4928, 17792,
-    17824, 4928, 4928, 4928, 7968, 17856, 17888, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 4928, 17728,
+    17760, 4928, 4928, 4928, 8000, 4928, 4928, 17792, 17824, 17376, 4928,
+    17856, 4928, 17888, 17920, 1824, 1824, 4928, 4928, 4928, 17952, 4928,
+    4928, 17984, 4928, 4928, 4928, 8000, 18016, 18048, 18080, 18112, 1824,
+    4928, 4928, 4928, 4928, 18144, 4928, 6880, 18176, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -483,7 +483,7 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 7776, 1824, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 11360, 1824, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -494,8 +494,8 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 17920, 1344, 1344, 1344, 1344, 1344, 1344,
-    11360, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 18208, 1344, 1344, 1344,
+    1344, 1344, 1344, 11360, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -510,7 +510,7 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 17952, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 18240, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
@@ -529,7 +529,8 @@ static const unsigned short pageMap[] = {
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 17984, 1824,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    18272, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
@@ -537,9 +538,25 @@ static const unsigned short pageMap[] = {
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
     1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
-    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344,
+    1824, 1824, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 11360, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824, 1824,
+    1824, 1824, 1824, 1824, 1824, 1824, 1824, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
     1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
-    1344, 1344, 1344, 11360
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344, 1344,
+    1344, 1344, 1344, 1344, 1344, 1792
 #endif /* TCL_UTF_MAX > 3 */
 };
 
@@ -658,107 +675,107 @@ static const unsigned char groupMap[] = {
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15,
-    15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 17,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 17, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
     93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 93, 125, 93, 15, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93,
-    93, 125, 125, 125, 125, 93, 125, 125, 15, 93, 93, 93, 93, 93, 93, 93,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 3, 3, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 9, 3, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 93, 125, 125, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0,
-    15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15,
-    0, 0, 0, 15, 15, 15, 15, 0, 0, 93, 15, 125, 125, 125, 93, 93, 93, 93,
-    0, 0, 125, 125, 0, 0, 125, 125, 93, 15, 0, 0, 0, 0, 0, 0, 0, 0, 125,
-    0, 0, 0, 0, 15, 15, 0, 15, 15, 15, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 15, 15, 4, 4, 18, 18, 18, 18, 18, 18, 14, 4, 15, 3, 93,
-    0, 0, 93, 93, 125, 0, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 15, 15, 0,
-    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0,
-    15, 15, 0, 15, 15, 0, 0, 93, 0, 125, 125, 125, 93, 93, 0, 0, 0, 0,
-    93, 93, 0, 0, 93, 93, 93, 0, 0, 0, 93, 0, 0, 0, 0, 0, 0, 0, 15, 15,
-    15, 15, 0, 15, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 93,
-    93, 15, 15, 15, 93, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 93, 125, 0,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15, 15,
-    0, 0, 93, 15, 125, 125, 125, 93, 93, 93, 93, 93, 0, 93, 93, 125, 0,
-    125, 125, 93, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    15, 15, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 4, 0, 0, 0,
-    0, 0, 0, 0, 15, 93, 93, 93, 93, 93, 93, 0, 93, 125, 125, 0, 15, 15,
-    15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15,
+    93, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 93, 125, 93, 15, 125, 125, 125, 93, 93, 93, 93,
+    93, 93, 93, 93, 125, 125, 125, 125, 93, 125, 125, 15, 93, 93, 93, 93,
+    93, 93, 93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 3, 3, 9,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 93, 125, 125, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15,
+    15, 15, 0, 15, 0, 0, 0, 15, 15, 15, 15, 0, 0, 93, 15, 125, 125, 125,
+    93, 93, 93, 93, 0, 0, 125, 125, 0, 0, 125, 125, 93, 15, 0, 0, 0, 0,
+    0, 0, 0, 0, 125, 0, 0, 0, 0, 15, 15, 0, 15, 15, 15, 93, 93, 0, 0, 9,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 4, 4, 18, 18, 18, 18, 18, 18, 14,
+    4, 15, 3, 93, 0, 0, 93, 93, 125, 0, 15, 15, 15, 15, 15, 15, 0, 0, 0,
+    0, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15,
+    0, 15, 15, 0, 15, 15, 0, 15, 15, 0, 0, 93, 0, 125, 125, 125, 93, 93,
+    0, 0, 0, 0, 93, 93, 0, 0, 93, 93, 93, 0, 0, 0, 93, 0, 0, 0, 0, 0, 0,
+    0, 15, 15, 15, 15, 0, 15, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 93, 93, 15, 15, 15, 93, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93,
+    93, 125, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 0, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15,
+    15, 15, 15, 0, 0, 93, 15, 125, 125, 125, 93, 93, 93, 93, 93, 0, 93,
+    93, 125, 0, 125, 125, 93, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 15, 15, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3,
+    4, 0, 0, 0, 0, 0, 0, 0, 15, 93, 93, 93, 93, 93, 93, 0, 93, 125, 125,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15,
+    15, 0, 0, 93, 15, 125, 93, 125, 93, 93, 93, 93, 0, 0, 125, 125, 0,
+    0, 125, 125, 93, 0, 0, 0, 0, 0, 0, 0, 93, 93, 125, 0, 0, 0, 0, 15,
+    15, 0, 15, 15, 15, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 14,
+    15, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 15, 0,
+    15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 15, 15, 0, 15, 15, 15, 15, 0,
+    0, 0, 15, 15, 0, 15, 0, 15, 15, 0, 0, 0, 15, 15, 0, 0, 0, 15, 15, 15,
+    0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0,
+    125, 125, 93, 125, 125, 0, 0, 0, 125, 125, 125, 0, 125, 125, 125, 93,
+    0, 0, 15, 0, 0, 0, 0, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 14, 14, 14, 14, 14,
+    14, 4, 14, 0, 0, 0, 0, 0, 93, 125, 125, 125, 93, 15, 15, 15, 15, 15,
+    15, 15, 15, 0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 93,
+    93, 93, 125, 125, 125, 125, 0, 93, 93, 93, 0, 93, 93, 93, 93, 0, 0,
+    0, 0, 0, 0, 0, 93, 93, 0, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 93, 93,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 3, 18, 18,
+    18, 18, 18, 18, 18, 14, 15, 93, 125, 125, 3, 15, 15, 15, 15, 15, 15,
+    15, 15, 0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 0, 0, 93, 15, 125, 93,
+    125, 125, 125, 125, 125, 0, 93, 125, 125, 0, 125, 125, 93, 93, 0, 0,
+    0, 0, 0, 0, 0, 125, 125, 0, 0, 0, 0, 0, 0, 0, 15, 0, 15, 15, 93, 93,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 15, 15, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 93, 93, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 15, 125, 125,
+    125, 93, 93, 93, 93, 0, 125, 125, 125, 0, 125, 125, 125, 93, 15, 14,
+    0, 0, 0, 0, 15, 15, 15, 125, 18, 18, 18, 18, 18, 18, 18, 15, 15, 15,
+    93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 14, 15, 15, 15, 15, 15, 15, 0, 93, 125, 125, 0, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 0, 0,
-    93, 15, 125, 93, 125, 93, 93, 93, 93, 0, 0, 125, 125, 0, 0, 125, 125,
-    93, 0, 0, 0, 0, 0, 0, 0, 0, 93, 125, 0, 0, 0, 0, 15, 15, 0, 15, 15,
-    15, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 14, 15, 18, 18, 18,
-    18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 15, 0, 15, 15, 15, 15,
-    15, 15, 0, 0, 0, 15, 15, 15, 0, 15, 15, 15, 15, 0, 0, 0, 15, 15, 0,
-    15, 0, 15, 15, 0, 0, 0, 15, 15, 0, 0, 0, 15, 15, 15, 0, 0, 0, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 125, 125, 93, 125,
-    125, 0, 0, 0, 125, 125, 125, 0, 125, 125, 125, 93, 0, 0, 15, 0, 0,
-    0, 0, 0, 0, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 14, 14, 14, 14, 14, 14, 4, 14, 0,
-    0, 0, 0, 0, 93, 125, 125, 125, 93, 15, 15, 15, 15, 15, 15, 15, 15,
-    0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 93, 93, 93, 125,
-    125, 125, 125, 0, 93, 93, 93, 0, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0,
-    0, 93, 93, 0, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 93, 93, 0, 0, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 3, 18, 18, 18, 18, 18,
-    18, 18, 14, 15, 93, 125, 125, 3, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 0, 0, 93, 15, 125, 93, 125,
-    125, 125, 125, 125, 0, 93, 125, 125, 0, 125, 125, 93, 93, 0, 0, 0,
-    0, 0, 0, 0, 125, 125, 0, 0, 0, 0, 0, 0, 0, 15, 0, 15, 15, 93, 93, 0,
-    0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 93, 93, 125, 125, 0, 15, 15, 15, 15, 15, 15, 15, 15,
-    0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 15, 125, 125, 125,
-    93, 93, 93, 93, 0, 125, 125, 125, 0, 125, 125, 125, 93, 15, 14, 0,
-    0, 0, 0, 15, 15, 15, 125, 18, 18, 18, 18, 18, 18, 18, 15, 15, 15, 93,
-    93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 14, 15, 15, 15, 15, 15, 15, 0, 0, 125, 125, 0, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 93, 0, 0, 0,
+    0, 125, 125, 125, 93, 93, 93, 0, 93, 0, 125, 125, 125, 125, 125, 125,
+    125, 125, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 125,
+    125, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    0, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 93, 0, 0, 0, 0, 125,
-    125, 125, 93, 93, 93, 0, 93, 0, 125, 125, 125, 125, 125, 125, 125,
-    125, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 125, 125,
-    3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 93, 15, 15, 93, 93, 93, 93, 93, 93, 93,
-    0, 0, 0, 0, 4, 15, 15, 15, 15, 15, 15, 92, 93, 93, 93, 93, 93, 93,
-    93, 93, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 0, 0, 0, 0, 0, 15, 15,
-    0, 15, 0, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15,
-    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 15, 15, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 15, 0, 0, 15, 15, 15, 15, 15, 0, 92, 0, 93,
-    93, 93, 93, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 15, 15,
-    15, 15, 15, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
-    14, 3, 14, 14, 14, 93, 93, 14, 14, 14, 14, 14, 14, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 93, 14, 93,
-    14, 93, 5, 6, 5, 6, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 125, 93, 93, 93, 93, 93, 3, 93, 93, 15, 15, 15, 15, 15, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93, 93,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 93, 15, 15, 93, 93, 93, 93, 93, 93,
+    93, 0, 0, 0, 0, 4, 15, 15, 15, 15, 15, 15, 92, 93, 93, 93, 93, 93,
+    93, 93, 93, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 0, 0, 0, 0, 0, 15,
+    15, 0, 15, 0, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
+    15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 15, 15, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 15, 0, 0, 15, 15, 15, 15, 15, 0, 92, 0,
+    93, 93, 93, 93, 93, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 15,
+    15, 15, 15, 15, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+    3, 3, 14, 3, 14, 14, 14, 93, 93, 14, 14, 14, 14, 14, 14, 9, 9, 9, 9,
+    9, 9, 9, 9, 9, 9, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 93, 14,
+    93, 14, 93, 5, 6, 5, 6, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 0,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 125, 93, 93, 93, 93, 93, 3, 93, 93, 15, 15, 15, 15, 15, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93,
     93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 14, 14, 14, 14,
-    14, 14, 14, 14, 93, 14, 14, 14, 14, 14, 14, 0, 14, 14, 3, 3, 3, 3,
-    3, 14, 14, 14, 14, 3, 3, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 125, 125, 93, 93, 93, 93, 125, 93, 93, 93, 93, 93,
-    93, 125, 93, 93, 125, 125, 93, 93, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    3, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15, 125, 125, 93, 93, 15, 15,
-    15, 15, 93, 93, 93, 15, 125, 125, 125, 15, 15, 125, 125, 125, 125,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 14, 14, 14,
+    14, 14, 14, 14, 14, 93, 14, 14, 14, 14, 14, 14, 0, 14, 14, 3, 3, 3,
+    3, 3, 14, 14, 14, 14, 3, 3, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 125, 125, 93, 93, 93, 93, 125, 93, 93, 93, 93,
+    93, 93, 125, 93, 93, 125, 125, 93, 93, 15, 9, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 3, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15, 125, 125, 93, 93, 15,
+    15, 15, 15, 93, 93, 93, 15, 125, 125, 125, 15, 15, 125, 125, 125, 125,
     125, 125, 125, 15, 15, 15, 93, 93, 93, 93, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 93, 125, 125, 93, 93, 125, 125, 125, 125,
     125, 125, 93, 15, 125, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 125, 125, 125,
@@ -838,209 +855,209 @@ static const unsigned char groupMap[] = {
     125, 125, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 0, 93, 9, 9, 9,
     9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
     0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 92, 3, 3, 3, 3, 3, 3, 0, 0,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 120, 0, 93,
-    93, 93, 93, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    93, 125, 93, 93, 93, 93, 93, 125, 93, 125, 125, 125, 125, 125, 93,
-    125, 125, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 93, 93, 93, 93, 93, 93, 93, 93, 93, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 0, 0, 0, 93, 93, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 125, 93, 93, 93, 93, 125, 125, 93, 93, 125, 93, 93, 93,
-    15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 93, 125, 93, 93, 125, 125, 125, 93, 125, 93, 93, 93,
-    125, 125, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 15, 15, 15, 15, 125,
-    125, 125, 125, 125, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93,
-    125, 125, 93, 93, 0, 0, 0, 3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    9, 0, 0, 0, 15, 15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 3, 3, 130,
-    131, 132, 133, 133, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 138, 138,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 120, 93, 93,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 125, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 93, 125, 93, 93, 93, 93, 93, 125, 93, 125,
+    125, 125, 125, 125, 93, 125, 125, 15, 15, 15, 15, 15, 15, 15, 0, 0,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 93, 93, 93, 93, 93, 93, 93, 93, 93, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 93, 93, 125, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 93, 93, 93, 93, 125, 125,
+    93, 93, 125, 93, 93, 93, 15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 125, 93, 93, 125, 125,
+    125, 93, 125, 93, 93, 93, 125, 125, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3,
+    3, 15, 15, 15, 15, 125, 125, 125, 125, 125, 125, 125, 125, 93, 93,
+    93, 93, 93, 93, 93, 93, 125, 125, 93, 93, 0, 0, 0, 3, 3, 3, 3, 3, 9,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 15, 15, 15, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92,
+    92, 92, 92, 92, 3, 3, 130, 131, 132, 133, 133, 134, 135, 136, 137,
+    0, 0, 0, 0, 0, 0, 0, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138,
     138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138,
     138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138,
-    138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 0,
-    0, 138, 138, 138, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 93,
-    93, 93, 3, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125,
-    93, 93, 93, 93, 93, 93, 93, 15, 15, 15, 15, 93, 15, 15, 15, 15, 15,
-    15, 93, 15, 15, 125, 93, 93, 15, 0, 0, 0, 0, 0, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    138, 138, 138, 138, 138, 0, 0, 138, 138, 138, 3, 3, 3, 3, 3, 3, 3,
+    3, 0, 0, 0, 0, 0, 0, 0, 0, 93, 93, 93, 3, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 125, 93, 93, 93, 93, 93, 93, 93, 15, 15, 15,
+    15, 93, 15, 15, 15, 15, 15, 15, 93, 15, 15, 125, 93, 93, 15, 0, 0,
+    0, 0, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 92, 92, 92, 92, 92,
     92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
     92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
     92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 92, 139, 21, 21,
-    21, 140, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 141, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 92, 92, 92,
-    92, 92, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93,
-    23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23,
-    24, 23, 24, 23, 24, 21, 21, 21, 21, 21, 142, 21, 21, 143, 21, 144,
-    144, 144, 144, 144, 144, 144, 144, 145, 145, 145, 145, 145, 145, 145,
-    145, 144, 144, 144, 144, 144, 144, 0, 0, 145, 145, 145, 145, 145, 145,
-    0, 0, 144, 144, 144, 144, 144, 144, 144, 144, 145, 145, 145, 145, 145,
-    145, 145, 145, 144, 144, 144, 144, 144, 144, 144, 144, 145, 145, 145,
-    145, 145, 145, 145, 145, 144, 144, 144, 144, 144, 144, 0, 0, 145, 145,
-    145, 145, 145, 145, 0, 0, 21, 144, 21, 144, 21, 144, 21, 144, 0, 145,
-    0, 145, 0, 145, 0, 145, 144, 144, 144, 144, 144, 144, 144, 144, 145,
-    145, 145, 145, 145, 145, 145, 145, 146, 146, 147, 147, 147, 147, 148,
-    148, 149, 149, 150, 150, 151, 151, 0, 0, 144, 144, 144, 144, 144, 144,
-    144, 144, 152, 152, 152, 152, 152, 152, 152, 152, 144, 144, 144, 144,
-    144, 144, 144, 144, 152, 152, 152, 152, 152, 152, 152, 152, 144, 144,
-    144, 144, 144, 144, 144, 144, 152, 152, 152, 152, 152, 152, 152, 152,
-    144, 144, 21, 153, 21, 0, 21, 21, 145, 145, 154, 154, 155, 11, 156,
-    11, 11, 11, 21, 153, 21, 0, 21, 21, 157, 157, 157, 157, 155, 11, 11,
-    11, 144, 144, 21, 21, 0, 0, 21, 21, 145, 145, 158, 158, 0, 11, 11,
-    11, 144, 144, 21, 21, 21, 114, 21, 21, 145, 145, 159, 159, 118, 11,
-    11, 11, 0, 0, 21, 153, 21, 0, 21, 21, 160, 160, 161, 161, 155, 11,
-    11, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 17, 17, 17, 17, 17, 8, 8, 8,
-    8, 8, 8, 3, 3, 16, 20, 5, 16, 16, 20, 5, 16, 3, 3, 3, 3, 3, 3, 3, 3,
-    162, 163, 17, 17, 17, 17, 17, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 16, 20,
-    3, 3, 3, 3, 12, 12, 3, 3, 3, 7, 5, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
-    3, 7, 3, 12, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 17, 17, 17, 17, 17, 0,
-    17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 92, 0, 0, 18, 18, 18, 18,
-    18, 18, 7, 7, 7, 5, 6, 92, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    7, 7, 7, 5, 6, 0, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
-    0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
-    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    120, 120, 120, 120, 93, 120, 120, 120, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14,
-    14, 108, 14, 14, 14, 14, 108, 14, 14, 21, 108, 108, 108, 21, 21, 108,
-    108, 108, 21, 14, 108, 14, 14, 7, 108, 108, 108, 108, 108, 14, 14,
-    14, 14, 14, 14, 108, 14, 164, 14, 108, 14, 165, 166, 108, 108, 14,
-    21, 108, 108, 167, 108, 21, 15, 15, 15, 15, 21, 14, 14, 21, 21, 108,
-    108, 7, 7, 7, 7, 7, 108, 21, 21, 21, 21, 14, 7, 14, 14, 168, 14, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 169, 169,
-    169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169, 169,
-    170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170, 170,
-    170, 170, 129, 129, 129, 23, 24, 129, 129, 129, 129, 18, 14, 14, 0,
-    0, 0, 0, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 7, 7, 14, 14, 14, 14, 7,
-    14, 14, 7, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14,
+    92, 92, 92, 92, 92, 92, 92, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 92, 139, 21, 21, 21, 140, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 141, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 92, 92, 92, 92, 92, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 0, 93, 93, 93, 93, 93, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24,
+    23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 21, 21, 21, 21, 21,
+    142, 21, 21, 143, 21, 144, 144, 144, 144, 144, 144, 144, 144, 145,
+    145, 145, 145, 145, 145, 145, 145, 144, 144, 144, 144, 144, 144, 0,
+    0, 145, 145, 145, 145, 145, 145, 0, 0, 144, 144, 144, 144, 144, 144,
+    144, 144, 145, 145, 145, 145, 145, 145, 145, 145, 144, 144, 144, 144,
+    144, 144, 144, 144, 145, 145, 145, 145, 145, 145, 145, 145, 144, 144,
+    144, 144, 144, 144, 0, 0, 145, 145, 145, 145, 145, 145, 0, 0, 21, 144,
+    21, 144, 21, 144, 21, 144, 0, 145, 0, 145, 0, 145, 0, 145, 144, 144,
+    144, 144, 144, 144, 144, 144, 145, 145, 145, 145, 145, 145, 145, 145,
+    146, 146, 147, 147, 147, 147, 148, 148, 149, 149, 150, 150, 151, 151,
+    0, 0, 144, 144, 144, 144, 144, 144, 144, 144, 152, 152, 152, 152, 152,
+    152, 152, 152, 144, 144, 144, 144, 144, 144, 144, 144, 152, 152, 152,
+    152, 152, 152, 152, 152, 144, 144, 144, 144, 144, 144, 144, 144, 152,
+    152, 152, 152, 152, 152, 152, 152, 144, 144, 21, 153, 21, 0, 21, 21,
+    145, 145, 154, 154, 155, 11, 156, 11, 11, 11, 21, 153, 21, 0, 21, 21,
+    157, 157, 157, 157, 155, 11, 11, 11, 144, 144, 21, 21, 0, 0, 21, 21,
+    145, 145, 158, 158, 0, 11, 11, 11, 144, 144, 21, 21, 21, 114, 21, 21,
+    145, 145, 159, 159, 118, 11, 11, 11, 0, 0, 21, 153, 21, 0, 21, 21,
+    160, 160, 161, 161, 155, 11, 11, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+    17, 17, 17, 17, 17, 8, 8, 8, 8, 8, 8, 3, 3, 16, 20, 5, 16, 16, 20,
+    5, 16, 3, 3, 3, 3, 3, 3, 3, 3, 162, 163, 17, 17, 17, 17, 17, 2, 3,
+    3, 3, 3, 3, 3, 3, 3, 3, 16, 20, 3, 3, 3, 3, 12, 12, 3, 3, 3, 7, 5,
+    6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 12, 3, 3, 3, 3, 3, 3, 3,
+    3, 3, 3, 2, 17, 17, 17, 17, 17, 0, 17, 17, 17, 17, 17, 17, 17, 17,
+    17, 17, 18, 92, 0, 0, 18, 18, 18, 18, 18, 18, 7, 7, 7, 5, 6, 92, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 7, 7, 7, 5, 6, 0, 92, 92, 92, 92,
+    92, 92, 92, 92, 92, 92, 92, 92, 92, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4,
+    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
+    4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 120, 120, 120, 120, 93, 120, 120,
+    120, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 108, 14, 14, 14, 14, 108, 14,
+    14, 21, 108, 108, 108, 21, 21, 108, 108, 108, 21, 14, 108, 14, 14,
+    7, 108, 108, 108, 108, 108, 14, 14, 14, 14, 14, 14, 108, 14, 164, 14,
+    108, 14, 165, 166, 108, 108, 14, 21, 108, 108, 167, 108, 21, 15, 15,
+    15, 15, 21, 14, 14, 21, 21, 108, 108, 7, 7, 7, 7, 7, 108, 21, 21, 21,
+    21, 14, 7, 14, 14, 168, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 169, 169, 169, 169, 169, 169, 169, 169, 169,
+    169, 169, 169, 169, 169, 169, 169, 170, 170, 170, 170, 170, 170, 170,
+    170, 170, 170, 170, 170, 170, 170, 170, 170, 129, 129, 129, 23, 24,
+    129, 129, 129, 129, 18, 14, 14, 0, 0, 0, 0, 7, 7, 7, 7, 7, 14, 14,
+    14, 14, 14, 7, 7, 14, 14, 14, 14, 7, 14, 14, 7, 14, 14, 7, 14, 14,
+    14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 14, 14, 7, 14, 7, 14,
+    14, 14, 14, 7, 7, 14, 14, 7, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7,
+    14, 14, 14, 14, 14, 14, 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, 14, 14, 14, 14, 14,
-    14, 14, 14, 5, 6, 5, 6, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 14, 14, 14, 14, 14, 14, 14,
-    5, 6, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 5, 6, 5, 6, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7,
+    14, 7, 7, 14, 14, 14, 14, 14, 14, 14, 5, 6, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 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, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 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, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 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, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7,
+    7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 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, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 14,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 171, 171, 171, 171, 171, 171, 171, 171,
     171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171,
-    171, 171, 171, 171, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172,
+    171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 171, 172, 172,
     172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 172,
-    172, 172, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    172, 172, 172, 172, 172, 172, 172, 172, 172, 172, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 18, 18,
+    14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 5, 6, 5, 6,
+    5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7,
+    18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7,
+    7, 7, 5, 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, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 7,
+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 6, 5, 6, 5,
+    6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 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,
-    5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
-    7, 7, 7, 7, 7, 7, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
-    6, 5, 6, 5, 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, 5, 6, 5, 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, 5, 6, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
-    7, 7, 7, 7, 14, 14, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14,
+    7, 7, 5, 6, 5, 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, 5, 6, 7, 7, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7,
+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 14, 14, 7, 7, 7, 7,
+    7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14,
+    14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14,
-    14, 14, 14, 14, 14, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,
+    14, 14, 14, 14, 14, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 123, 123,
     123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,
     123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,
-    123, 123, 123, 123, 123, 123, 123, 123, 123, 0, 124, 124, 124, 124,
-    124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
+    123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123,
+    123, 123, 123, 0, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
     124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
     124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
-    124, 0, 23, 24, 173, 174, 175, 176, 177, 23, 24, 23, 24, 23, 24, 178,
-    179, 180, 181, 21, 23, 24, 21, 23, 24, 21, 21, 21, 21, 21, 92, 92,
-    182, 182, 23, 24, 23, 24, 21, 14, 14, 14, 14, 14, 14, 23, 24, 23, 24,
-    93, 93, 93, 23, 24, 0, 0, 0, 0, 0, 3, 3, 3, 3, 18, 3, 3, 183, 183,
+    124, 124, 124, 124, 124, 124, 124, 124, 124, 0, 23, 24, 173, 174, 175,
+    176, 177, 23, 24, 23, 24, 23, 24, 178, 179, 180, 181, 21, 23, 24, 21,
+    23, 24, 21, 21, 21, 21, 21, 92, 92, 182, 182, 23, 24, 23, 24, 21, 14,
+    14, 14, 14, 14, 14, 23, 24, 23, 24, 93, 93, 93, 23, 24, 0, 0, 0, 0,
+    0, 3, 3, 3, 3, 18, 3, 3, 183, 183, 183, 183, 183, 183, 183, 183, 183,
     183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183,
     183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183,
-    183, 183, 183, 183, 183, 183, 183, 183, 0, 183, 0, 0, 0, 0, 0, 183,
-    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 92, 3, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15,
-    15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15,
-    0, 3, 3, 16, 20, 16, 20, 3, 3, 3, 16, 20, 3, 16, 20, 3, 3, 3, 3, 3,
-    3, 3, 3, 3, 8, 3, 3, 8, 3, 16, 20, 3, 3, 16, 20, 5, 6, 5, 6, 5, 6,
-    5, 6, 3, 3, 3, 3, 3, 92, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 8, 3, 3,
-    3, 3, 8, 3, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    183, 0, 183, 0, 0, 0, 0, 0, 183, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    0, 0, 0, 0, 0, 0, 0, 92, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15,
+    15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15,
+    15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 3, 3, 16, 20, 16, 20,
+    3, 3, 3, 16, 20, 3, 16, 20, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 3, 3, 8,
+    3, 16, 20, 3, 3, 16, 20, 5, 6, 5, 6, 5, 6, 5, 6, 3, 3, 3, 3, 3, 92,
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 8, 3, 3, 3, 3, 8, 3, 5, 3, 3, 3, 3,
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 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, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 0, 0, 0, 0, 2, 3, 3, 3, 14, 92, 15, 129, 5, 6, 5, 6, 5,
-    6, 5, 6, 5, 6, 14, 14, 5, 6, 5, 6, 5, 6, 5, 6, 8, 5, 6, 6, 14, 129,
-    129, 129, 129, 129, 129, 129, 129, 129, 93, 93, 93, 93, 125, 125, 8,
-    92, 92, 92, 92, 92, 14, 14, 129, 129, 129, 92, 15, 3, 14, 14, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 0, 93, 93, 11, 11, 92, 92, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 3, 92, 92, 92, 15, 0, 0, 0, 0, 0, 15, 15, 15, 15,
+    14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    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, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0,
+    2, 3, 3, 3, 14, 92, 15, 129, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 14, 14,
+    5, 6, 5, 6, 5, 6, 5, 6, 8, 5, 6, 6, 14, 129, 129, 129, 129, 129, 129,
+    129, 129, 129, 93, 93, 93, 93, 125, 125, 8, 92, 92, 92, 92, 92, 14,
+    14, 129, 129, 129, 92, 15, 3, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 93,
+    93, 11, 11, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3,
+    92, 92, 92, 15, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 0, 14, 14, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 14,
-    14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 14, 14,
+    18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 0, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18,
-    18, 18, 18, 18, 18, 18, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    14, 14, 14, 14, 14, 14, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18, 18, 18,
+    18, 18, 18, 18, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    92, 3, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 24, 23, 24, 23, 24, 23,
+    15, 92, 3, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 24, 23, 24, 23, 24, 23,
     24, 23, 24, 23, 24, 23, 24, 15, 93, 120, 120, 120, 3, 93, 93, 93, 93,
     93, 93, 93, 93, 93, 93, 3, 92, 23, 24, 23, 24, 23, 24, 23, 24, 23,
     24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24,
@@ -1056,510 +1073,525 @@ static const unsigned char groupMap[] = {
     186, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23,
     24, 23, 24, 23, 24, 187, 188, 189, 190, 187, 21, 191, 192, 193, 194,
     23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 0, 0, 23, 24, 195,
-    196, 197, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    196, 197, 23, 24, 23, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 15, 92, 92, 21, 15, 15, 15, 15, 15, 15, 15, 93, 15,
-    15, 15, 93, 15, 15, 15, 15, 93, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 93,
-    93, 125, 14, 14, 14, 14, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 14, 14,
-    4, 14, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0,
-    0, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
-    125, 125, 125, 125, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 9, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 15, 15, 15, 15, 15, 15,
-    3, 3, 3, 15, 3, 15, 15, 93, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93,
-    93, 93, 93, 93, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 125, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 125,
-    125, 93, 93, 93, 93, 125, 125, 93, 93, 125, 125, 125, 3, 3, 3, 3, 3,
-    3, 3, 3, 3, 3, 3, 3, 3, 0, 92, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0,
-    0, 0, 3, 3, 15, 15, 15, 15, 15, 93, 92, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 15, 15, 15, 0, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93, 125, 125, 93, 93,
-    125, 125, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 93, 15, 15,
-    15, 15, 15, 15, 15, 15, 93, 125, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    0, 0, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 92, 15, 15, 15, 15, 15, 15, 14, 14, 14, 15, 125, 93, 125,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 93, 15, 93, 93, 93, 15, 15, 93, 93, 15, 15, 15, 15, 15, 93, 93,
-    15, 93, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 15, 15, 92, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 125, 93, 93, 125, 125, 3, 3, 15, 92, 92, 125, 93, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15,
-    15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
-    15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 21, 21, 21,
+    0, 0, 0, 0, 0, 23, 24, 15, 92, 92, 21, 15, 15, 15, 15, 15, 15, 15,
+    93, 15, 15, 15, 93, 15, 15, 15, 15, 93, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125,
+    125, 93, 93, 125, 14, 14, 14, 14, 93, 0, 0, 0, 18, 18, 18, 18, 18,
+    18, 14, 14, 4, 14, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 3, 3, 3, 0, 0, 0,
+    0, 0, 0, 0, 0, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
+    125, 125, 125, 125, 125, 125, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 15, 15, 15, 15,
+    15, 15, 3, 3, 3, 15, 3, 15, 15, 93, 15, 15, 15, 15, 15, 15, 93, 93,
+    93, 93, 93, 93, 93, 93, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 125, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 93, 125, 125, 93, 93, 93, 93, 125, 125, 93, 93, 125, 125,
+    125, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 92, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 9, 0, 0, 0, 0, 3, 3, 15, 15, 15, 15, 15, 93, 92, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 15, 15, 15, 15,
+    15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93,
+    125, 125, 93, 93, 125, 125, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
+    15, 15, 93, 15, 15, 15, 15, 15, 15, 15, 15, 93, 125, 0, 0, 9, 9, 9,
+    9, 9, 9, 9, 9, 9, 9, 0, 0, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 15, 15, 15, 15, 15, 15, 14,
+    14, 14, 15, 125, 93, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 93, 15, 93, 93, 93, 15, 15, 93, 93, 15,
+    15, 15, 15, 15, 93, 93, 15, 93, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 92, 3, 3, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 125, 93, 93, 125, 125, 3, 3, 15, 92,
+    92, 125, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15,
+    0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15,
+    15, 15, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 198, 21,
-    21, 21, 21, 21, 21, 21, 11, 92, 92, 92, 92, 21, 21, 21, 21, 21, 21,
-    21, 21, 0, 0, 0, 0, 0, 0, 0, 0, 199, 199, 199, 199, 199, 199, 199,
+    21, 21, 21, 21, 198, 21, 21, 21, 21, 21, 21, 21, 11, 92, 92, 92, 92,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 92, 11, 11, 0, 0, 0, 0, 199, 199,
     199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199,
     199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199,
-    199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 15,
-    15, 15, 125, 125, 93, 125, 125, 93, 125, 125, 3, 125, 93, 0, 0, 9,
-    9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 15,
+    199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199,
+    199, 199, 199, 199, 15, 15, 15, 125, 125, 93, 125, 125, 93, 125, 125,
+    3, 125, 93, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 15,
+    15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0,
-    200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 0, 0, 0, 0, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
     200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200,
-    200, 200, 200, 200, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201,
+    200, 200, 200, 200, 200, 200, 200, 200, 201, 201, 201, 201, 201, 201,
     201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201,
-    201, 201, 201, 201, 201, 201, 201, 201, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 201, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    0, 0, 0, 0, 0, 21, 21, 21, 21, 21, 21, 21, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 21, 21, 21, 21, 21, 0, 0, 0, 0, 0, 15, 93, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 7, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 0, 15, 0, 15, 15, 0, 15, 15,
-    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 11, 11, 11, 11, 11, 11,
-    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 21, 21, 21, 21, 21, 21, 21, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21, 21, 21, 21, 21, 0, 0, 0, 0, 0, 15,
+    93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 0, 15, 0, 15,
+    15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 6, 5, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 11, 11, 11,
+    11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 4, 14, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 3, 3, 3, 3, 3, 3, 3, 5, 6, 3, 0, 0, 0,
-    0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 3, 8, 8, 12, 12, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6,
-    3, 3, 5, 6, 3, 3, 3, 3, 12, 12, 12, 3, 3, 3, 0, 3, 3, 3, 3, 8, 5, 6,
-    5, 6, 5, 6, 3, 3, 3, 7, 8, 7, 7, 7, 0, 3, 4, 3, 3, 0, 0, 0, 0, 15,
-    15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 17, 0, 3, 3, 3, 4, 3,
-    3, 3, 5, 6, 3, 7, 3, 8, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 7,
-    7, 7, 3, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
-    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 5, 7, 6, 7, 5, 6, 3,
-    5, 6, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 0, 0, 15, 15, 15, 15, 15, 15,
-    0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15,
-    15, 15, 0, 0, 0, 4, 4, 7, 11, 14, 4, 4, 0, 14, 7, 7, 7, 7, 14, 14,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 14, 14, 0, 0
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 4, 14, 0, 0, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 3, 3, 3, 3, 3, 3, 3, 5,
+    6, 3, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 3, 8, 8, 12, 12, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6,
+    5, 6, 5, 6, 5, 6, 3, 3, 5, 6, 3, 3, 3, 3, 12, 12, 12, 3, 3, 3, 0, 3,
+    3, 3, 3, 8, 5, 6, 5, 6, 5, 6, 3, 3, 3, 7, 8, 7, 7, 7, 0, 3, 4, 3, 3,
+    0, 0, 0, 0, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 17, 0,
+    3, 3, 3, 4, 3, 3, 3, 5, 6, 3, 7, 3, 8, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 3, 3, 7, 7, 7, 3, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 5,
+    7, 6, 7, 5, 6, 3, 5, 6, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 0, 0, 15, 15,
+    15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15,
+    15, 15, 0, 0, 15, 15, 15, 0, 0, 0, 4, 4, 7, 11, 14, 4, 4, 0, 14, 7,
+    7, 7, 7, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 17, 17, 14, 14,
+    0, 0
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
     ,15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 0, 0, 3, 3, 3, 0, 0, 0, 0, 18, 18, 18,
+    15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
+    18, 18, 18, 18, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 129, 129,
     129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
     129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
-    129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 18,
-    18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 18, 18, 14, 14, 14, 0, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
+    129, 129, 129, 129, 129, 129, 129, 129, 129, 18, 18, 18, 18, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18,
+    14, 14, 14, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14,
+    0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 93, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 93, 0,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 18, 18, 18, 18,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 129, 15, 15, 15, 15, 15, 15,
-    15, 15, 129, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 0,
+    18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 18, 18, 18, 18, 0, 0, 0, 0, 0,
     0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    3, 15, 15, 15, 15, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 3, 129,
-    129, 129, 129, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 202, 202, 202, 202,
+    15, 15, 15, 15, 15, 15, 129, 15, 15, 15, 15, 15, 15, 15, 15, 129, 0,
+    0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 3, 15, 15, 15, 15,
+    0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 3, 129, 129, 129, 129,
+    129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 202, 202, 202, 202, 202, 202, 202,
     202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
     202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
-    202, 202, 202, 202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203,
+    202, 202, 202, 202, 202, 203, 203, 203, 203, 203, 203, 203, 203, 203,
     203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203,
     203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203,
-    203, 203, 203, 203, 203, 203, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    203, 203, 203, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 202,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
+    0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 202, 202, 202, 202,
     202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
     202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202,
-    202, 202, 202, 202, 202, 202, 202, 0, 0, 0, 0, 203, 203, 203, 203,
+    202, 202, 202, 202, 0, 0, 0, 0, 203, 203, 203, 203, 203, 203, 203,
     203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203,
     203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203,
-    203, 203, 203, 203, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15,
-    15, 0, 0, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15,
-    0, 0, 0, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 3, 18, 18, 18, 18, 18,
-    18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 14, 18, 18, 18, 18, 18, 18,
-    18, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 0, 0,
-    0, 0, 18, 18, 18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 18, 18, 18, 18, 18, 18,
-    0, 0, 0, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 3, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 18, 18, 15, 15, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 15, 93, 93, 93, 0, 93, 93,
-    0, 0, 0, 0, 0, 93, 93, 93, 93, 15, 15, 15, 15, 0, 15, 15, 15, 0, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 93, 93, 93, 0, 0,
-    0, 0, 93, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0,
-    3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 18, 18, 3, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 14,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 0, 0, 0, 0, 18,
-    18, 18, 18, 18, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    0, 18, 18, 18, 18, 18, 18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 18, 18,
-    18, 18, 18, 18, 18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
+    203, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 0, 0, 15,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 0, 0, 15,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 0, 3, 18, 18, 18, 18, 18, 18, 18, 18, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 14, 14, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0,
+    0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 0, 0, 0, 0, 18, 18, 18,
+    18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 18, 18, 18, 18, 18, 18, 0, 0, 0, 3, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 3, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 0, 0, 0, 0, 18, 18, 15, 15, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 15, 93, 93, 93, 0, 93, 93, 0, 0, 0, 0, 0, 93,
+    93, 93, 93, 15, 15, 15, 15, 0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 0, 0, 93, 93, 93, 0, 0, 0, 0, 93, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3,
+    3, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 18, 18, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 18,
+    18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 14, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 93, 93, 0, 0, 0, 0, 18, 18, 18, 18, 18, 3, 3, 3,
+    3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
+    3, 3, 3, 3, 3, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 18, 18, 18, 18, 18, 18,
+    18, 18, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 98, 98, 98, 98, 98, 98,
     98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
     98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
-    98, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 103, 103, 103, 103,
-    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
+    98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 98, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
     103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
     103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103,
-    103, 103, 103, 103, 103, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18,
-    15, 15, 15, 15, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9,
-    9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 0, 18, 18, 18, 18, 18, 18, 18, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 18, 18, 18, 18, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 125, 93,
-    125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 103, 0, 0, 0,
+    0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 15, 15, 15, 15, 93, 93, 93, 93,
+    0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0,
+    0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 93, 93, 8, 0, 0, 15, 15, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18,
+    15, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 18, 18, 18, 18, 3, 3, 3, 3, 3, 0, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 93, 125, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 9, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125,
-    93, 93, 93, 93, 125, 125, 93, 93, 3, 3, 17, 3, 3, 3, 3, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 93,
-    93, 93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 93, 93, 93, 93, 93, 125, 93, 93, 93, 93, 93, 93, 93,
-    93, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 3, 3, 15, 125, 125, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 3, 3, 3,
+    3, 3, 3, 3, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93,
+    93, 125, 125, 93, 93, 3, 3, 17, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 17, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 93, 93, 93, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 93, 3, 3, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125, 125, 15,
-    15, 15, 15, 3, 3, 3, 3, 93, 93, 93, 93, 3, 0, 0, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 15, 3, 15, 3, 3, 3, 0, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0,
+    15, 93, 93, 93, 93, 93, 125, 93, 93, 93, 93, 93, 93, 93, 93, 0, 9,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 3, 3, 15, 125, 125, 15, 0, 0, 0, 0,
     0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125,
-    93, 93, 93, 125, 125, 93, 125, 93, 93, 3, 3, 3, 3, 3, 3, 93, 0, 15,
-    15, 15, 15, 15, 15, 15, 0, 15, 0, 15, 15, 15, 15, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 3, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 93, 125, 125, 125, 93, 93, 93, 93, 93, 93,
-    93, 93, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0,
-    0, 93, 93, 125, 125, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15,
+    15, 15, 15, 15, 93, 3, 3, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125,
+    125, 125, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125, 125, 15, 15, 15,
+    15, 3, 3, 3, 3, 93, 93, 93, 93, 3, 125, 93, 9, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 15, 3, 15, 3, 3, 3, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0,
-    15, 15, 15, 15, 15, 0, 93, 93, 15, 125, 125, 93, 125, 125, 125, 125,
-    0, 0, 125, 125, 0, 0, 125, 125, 125, 0, 0, 15, 0, 0, 0, 0, 0, 0, 125,
+    15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93,
+    93, 125, 125, 93, 125, 93, 93, 3, 3, 3, 3, 3, 3, 93, 0, 15, 15, 15,
+    15, 15, 15, 15, 0, 15, 0, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 3, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 93, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93,
+    0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 93,
+    93, 125, 125, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 0, 0,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15,
+    15, 15, 15, 15, 0, 93, 93, 15, 125, 125, 93, 125, 125, 125, 125, 0,
+    0, 125, 125, 0, 0, 125, 125, 125, 0, 0, 15, 0, 0, 0, 0, 0, 0, 125,
     0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 125, 125, 0, 0, 93, 93, 93, 93,
     93, 93, 93, 0, 0, 0, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0,
     0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93,
     125, 125, 93, 93, 93, 125, 93, 15, 15, 15, 15, 3, 3, 3, 3, 3, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 9, 0, 3, 0, 3, 93, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93,
-    93, 93, 93, 125, 93, 125, 125, 125, 125, 93, 93, 125, 93, 93, 15, 15,
-    3, 15, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0,
-    0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 125, 125, 125, 93, 93, 93, 93, 0, 0, 125, 125, 125, 125, 93, 93,
-    125, 93, 93, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
-    3, 3, 3, 3, 3, 15, 15, 15, 15, 93, 93, 0, 0, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93,
-    93, 93, 93, 93, 93, 125, 125, 93, 125, 93, 93, 3, 3, 3, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0,
-    0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 93, 125, 93, 125, 125, 93, 93, 93, 93, 93, 93, 125, 93, 15, 0,
-    0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 125, 125, 93, 93, 93,
-    93, 125, 93, 93, 93, 93, 93, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    9, 18, 18, 3, 3, 3, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125, 93, 93,
-    3, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
+    9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 0, 3, 93, 15, 15, 15, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    125, 125, 125, 93, 93, 93, 93, 93, 93, 125, 93, 125, 125, 125, 125,
+    93, 93, 125, 93, 93, 15, 15, 3, 15, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9,
+    9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93, 93, 0, 0,
+    125, 125, 125, 125, 93, 93, 125, 93, 93, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 15, 15, 15, 15, 93, 93, 0,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    125, 125, 125, 93, 93, 93, 93, 93, 93, 93, 93, 125, 125, 93, 125, 93,
+    93, 3, 3, 3, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 93, 125, 93, 125, 125, 93, 93, 93,
+    93, 93, 93, 125, 93, 15, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 125, 125, 93, 93, 93, 93, 125, 93, 93, 93, 93, 93, 0, 0, 0, 0,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 3, 3, 3, 14, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 125, 93, 93, 3, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10,
     10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
-    10, 10, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+    10, 10, 10, 10, 10, 10, 10, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13,
     13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
-    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 125, 125, 125, 93, 93, 93, 93, 0, 0, 93, 93,
-    125, 125, 125, 125, 93, 15, 3, 15, 125, 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, 15, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93,
-    93, 93, 125, 15, 93, 93, 93, 93, 3, 3, 3, 3, 3, 3, 3, 3, 93, 0, 0,
-    0, 0, 0, 0, 0, 0, 15, 93, 93, 93, 93, 93, 93, 125, 125, 93, 93, 93,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 125, 93, 93, 3, 3, 3, 15, 3,
-    3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 125, 93, 93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93,
-    93, 125, 93, 15, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 3, 3, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 125, 93,
-    93, 93, 93, 93, 93, 93, 125, 93, 93, 125, 93, 93, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    13, 13, 13, 13, 13, 13, 13, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15,
+    15, 15, 15, 15, 15, 15, 0, 0, 15, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 125, 125,
+    125, 0, 125, 125, 0, 0, 93, 93, 125, 93, 15, 125, 15, 125, 93, 3, 3,
+    3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0,
+    0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    125, 125, 125, 93, 93, 93, 93, 0, 0, 93, 93, 125, 125, 125, 125, 93,
+    15, 3, 15, 125, 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, 15, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    93, 93, 93, 93, 93, 93, 0, 0, 0, 93, 0, 93, 93, 0, 93, 93, 93, 93,
-    93, 93, 93, 15, 93, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9,
-    9, 9, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 0, 15, 15, 0, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93, 125, 15, 93, 93,
+    93, 93, 3, 3, 3, 3, 3, 3, 3, 3, 93, 0, 0, 0, 0, 0, 0, 0, 0, 15, 93,
+    93, 93, 93, 93, 93, 125, 125, 93, 93, 93, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 125, 93, 93, 3, 3, 3, 15, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125,
-    125, 125, 0, 93, 93, 0, 125, 125, 93, 125, 93, 15, 0, 0, 0, 0, 0, 0,
-    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 93, 93, 125, 125, 3, 3, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 93, 93, 93,
+    93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93, 125, 93, 15, 3, 3, 3, 3,
+    3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 14, 14, 14, 14, 14, 14, 14, 14, 4, 4, 4, 4, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 3, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
-    129, 129, 129, 129, 129, 0, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 15, 15, 15, 15, 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, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 17, 17, 17, 17, 17, 17, 17, 17,
-    17, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9,
-    9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 0, 0, 93, 93, 93, 93, 93, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93,
-    93, 93, 93, 93, 93, 3, 3, 3, 3, 3, 14, 14, 14, 14, 92, 92, 92, 92,
-    3, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    0, 18, 18, 18, 18, 18, 18, 18, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 15,
-    15, 15, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 3, 3, 3, 3, 0, 0, 0, 0, 0, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 93, 15, 125, 125, 125,
+    18, 0, 0, 0, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 0, 125, 93, 93, 93, 93, 93, 93, 93, 125,
+    93, 93, 125, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15,
+    15, 15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93, 93, 0, 0, 0,
+    93, 0, 93, 93, 0, 93, 93, 93, 93, 93, 93, 93, 15, 93, 0, 0, 0, 0, 0,
+    0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 15, 15, 15,
+    15, 15, 15, 0, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 125, 125, 125, 125, 125, 0, 93, 93, 0, 125, 125, 93,
+    125, 93, 15, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 125, 125, 3, 3, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 14,
+    14, 14, 14, 14, 14, 14, 4, 4, 4, 4, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 3, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129,
+    129, 129, 129, 0, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15,
+    15, 15, 15, 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, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 0, 17, 17, 17, 17, 17, 17, 17, 17, 17, 0, 0, 0,
+    0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9,
+    9, 9, 9, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0,
+    93, 93, 93, 93, 93, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 93,
+    93, 93, 3, 3, 3, 3, 3, 14, 14, 14, 14, 92, 92, 92, 92, 3, 14, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 18, 18, 18,
+    18, 18, 18, 18, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 3,
+    3, 3, 3, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    0, 0, 0, 0, 93, 15, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
     125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
     125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
     125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125,
-    125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 0, 0, 0, 0, 0, 0,
-    0, 93, 93, 93, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92,
-    92, 92, 92, 3, 92, 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, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
-    0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 0, 0, 0,
-    0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0,
-    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 0, 0, 14, 93, 93, 3, 17, 17, 17, 17, 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, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 14, 14,
+    125, 125, 125, 0, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 92, 92, 92, 92,
+    92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 3, 92, 93, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 125, 125, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 0, 0, 14, 93, 93, 3, 17, 17, 17, 17, 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, 14,
+    14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 125, 125, 93, 93, 93, 14, 14, 14, 125, 125, 125,
-    125, 125, 125, 17, 17, 17, 17, 17, 17, 17, 17, 93, 93, 93, 93, 93,
-    93, 93, 93, 14, 14, 93, 93, 93, 93, 93, 93, 93, 14, 14, 14, 14, 14,
+    14, 125, 125, 93, 93, 93, 14, 14, 14, 125, 125, 125, 125, 125, 125,
+    17, 17, 17, 17, 17, 17, 17, 17, 93, 93, 93, 93, 93, 93, 93, 93, 14,
+    14, 93, 93, 93, 93, 93, 93, 93, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 93, 93, 93, 93, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 93, 93, 93, 93, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 14, 14, 93, 93, 93, 14, 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, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0,
+    14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 14, 14, 93, 93, 93, 14, 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, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 21, 21, 21, 21, 21, 21, 21, 0, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 108,
+    21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 108, 0, 108, 108, 0, 0, 108, 0, 0, 108, 108, 0, 0, 108,
-    108, 108, 108, 0, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21,
-    21, 0, 21, 0, 21, 21, 21, 21, 21, 21, 21, 0, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 21, 21, 21, 21, 21, 21, 21, 0, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 0, 108, 108,
-    108, 108, 0, 0, 108, 108, 108, 108, 108, 108, 108, 108, 0, 108, 108,
-    108, 108, 108, 108, 108, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108,
-    108, 0, 108, 108, 108, 108, 0, 108, 108, 108, 108, 108, 0, 108, 0,
-    0, 0, 108, 108, 108, 108, 108, 108, 108, 0, 21, 21, 21, 21, 21, 21,
+    0, 108, 108, 0, 0, 108, 0, 0, 108, 108, 0, 0, 108, 108, 108, 108, 0,
+    108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 0, 21, 0, 21,
+    21, 21, 21, 21, 21, 21, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 0, 108, 108, 108, 108, 0,
+    0, 108, 108, 108, 108, 108, 108, 108, 108, 0, 108, 108, 108, 108, 108,
+    108, 108, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 0, 108, 108,
+    108, 108, 0, 108, 108, 108, 108, 108, 0, 108, 0, 0, 0, 108, 108, 108,
+    108, 108, 108, 108, 0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 21, 21, 21, 21,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 108, 108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 108, 108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 21, 21, 21,
-    21, 21, 21, 0, 0, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 7, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 108, 108, 108, 108, 108, 108, 21, 21, 21, 21, 21, 21, 0, 0, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 7, 21, 21, 21,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 7, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108,
+    21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 108, 108, 108, 108, 108, 7, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7,
+    21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 7, 21, 21, 21, 21, 21, 21, 21, 21,
+    108, 108, 7, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21,
+    21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 7, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    7, 21, 21, 21, 21, 21, 21, 108, 108, 108, 108, 108, 108, 108, 108,
+    21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 108, 108, 108,
     108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 7, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21,
-    21, 21, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
-    108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 7,
+    108, 108, 108, 108, 108, 108, 108, 108, 7, 21, 21, 21, 21, 21, 21,
     21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
-    21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 108, 21,
-    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
+    21, 21, 7, 21, 21, 21, 21, 21, 21, 108, 21, 0, 0, 9, 9, 9, 9, 9, 9,
     9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 9, 9, 9, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 14, 14, 14, 14, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 14, 14,
-    14, 14, 14, 14, 14, 14, 93, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 93, 14, 14, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93,
-    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 0, 0, 93, 93, 93, 93, 93,
-    93, 93, 0, 93, 93, 0, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 14, 14, 14, 14, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 14, 14, 14, 14, 14, 14, 14,
+    14, 93, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 93,
+    14, 14, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93,
+    93, 93, 93, 93, 93, 93, 0, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93,
+    93, 93, 93, 93, 93, 93, 93, 0, 0, 93, 93, 93, 93, 93, 93, 93, 0, 93,
+    93, 0, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92, 92, 92, 92, 92,
+    0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 15, 14, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 0, 0, 0, 93, 93, 93, 93, 93, 93, 93, 92, 92, 92,
-    92, 92, 92, 92, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 15,
-    14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 93, 93, 93, 93, 9, 9, 9, 9, 9, 9, 9,
-    9, 9, 9, 0, 0, 0, 0, 0, 4, 15, 15, 15, 15, 15, 0, 0, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 93, 93, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
+    15, 15, 15, 15, 93, 93, 93, 93, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0,
+    0, 0, 0, 4, 15, 15, 15, 15, 15, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 93, 93, 93, 93, 93, 93, 93, 0, 0, 0, 0, 0, 0, 0, 0, 0, 204, 204,
+    204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
     204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204, 204,
-    204, 204, 204, 204, 204, 204, 204, 205, 205, 205, 205, 205, 205, 205,
+    204, 204, 204, 204, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
     205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205,
-    205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 93,
-    93, 93, 93, 93, 93, 93, 92, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9,
-    9, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 18, 18, 18, 4, 18,
-    18, 18, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18,
+    205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 93, 93, 93, 93, 93,
+    93, 93, 92, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 3,
+    3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 18, 14, 18, 18, 18, 4, 18, 18, 18, 18, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
     18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 0, 0, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 0, 15, 15, 0, 15, 0, 0, 15, 0, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 0, 15, 0, 15, 0, 0, 0, 0, 0,
-    0, 15, 0, 0, 0, 0, 15, 0, 15, 0, 15, 0, 15, 15, 15, 0, 15, 15, 0, 15,
-    0, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 15, 0, 15, 0, 0, 15, 15,
-    15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 0, 15, 15,
-    15, 15, 0, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0,
-    0, 0, 15, 15, 15, 0, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
-    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0,
-    0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18, 18, 18, 18,
-    18, 18, 18, 18, 18, 18, 18, 18, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14,
+    18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
+    0, 0, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0,
+    15, 15, 0, 15, 0, 0, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    0, 15, 15, 15, 15, 0, 15, 0, 15, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0,
+    15, 0, 15, 0, 15, 0, 15, 15, 15, 0, 15, 15, 0, 15, 0, 0, 15, 0, 15,
+    0, 15, 0, 15, 0, 15, 0, 15, 15, 0, 15, 0, 0, 15, 15, 15, 15, 0, 15,
+    15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 0, 15, 15, 15, 15, 0, 15,
+    0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 15, 15,
+    15, 0, 15, 15, 15, 15, 15, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+    15, 15, 15, 15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18, 18, 18, 18, 18, 18, 18,
+    18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 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, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0,
-    0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0,
+    0, 0, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14,
     14, 14, 14, 14, 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, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
     11, 11, 11, 11, 11, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0,
-    0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0,
-    0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0,
-    0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0,
+    0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 14, 14, 14,
+    14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 0, 14, 14, 14, 14, 0, 0, 0, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 14, 14, 0, 0, 0, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14,
+    14, 14, 14, 0, 0, 0, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14,
+    14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 14,
     14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 14, 14, 14, 14, 0, 0,
-    0, 0, 14, 14, 14, 0, 0, 0, 0, 0, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0,
-    0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14,
+    14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 14, 14, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 14, 14,
+    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0,
     15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
     15, 15, 15, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 0, 0, 0, 0,
     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
@@ -1614,9 +1646,9 @@ static const int groups[] = {
 };
 
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
-#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1fffff) >= 0x2fa20)
+#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1FFFFF) >= 0x31360)
 #else
-#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1f0000) != 0)
+#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1F0000) != 0)
 #endif
 
 /*
@@ -1663,8 +1695,8 @@ enum {
  * to do sign extension on right shifts.
  */
 
-#define GetCaseType(info) (((info) & 0xe0) >> 5)
-#define GetCategory(ch) (GetUniCharInfo(ch) & 0x1f)
+#define GetCaseType(info) (((info) & 0xE0) >> 5)
+#define GetCategory(ch) (GetUniCharInfo(ch) & 0x1F)
 #define GetDelta(info) ((info) >> 8)
 
 /*
@@ -1673,7 +1705,7 @@ enum {
  */
 
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
-#   define GetUniCharInfo(ch) (groups[groupMap[pageMap[((ch) & 0x1fffff) >> OFFSET_BITS] | ((ch) & ((1 << OFFSET_BITS)-1))]])
+#   define GetUniCharInfo(ch) (groups[groupMap[pageMap[((ch) & 0x1FFFFF) >> OFFSET_BITS] | ((ch) & ((1 << OFFSET_BITS)-1))]])
 #else
-#   define GetUniCharInfo(ch) (groups[groupMap[pageMap[((ch) & 0xffff) >> OFFSET_BITS] | ((ch) & ((1 << OFFSET_BITS)-1))]])
+#   define GetUniCharInfo(ch) (groups[groupMap[pageMap[((ch) & 0xFFFF) >> OFFSET_BITS] | ((ch) & ((1 << OFFSET_BITS)-1))]])
 #endif
index 9c2ef03..5ae977a 100644 (file)
@@ -66,12 +66,31 @@ static const unsigned char totalBytes[256] = {
     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
     1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
-    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+    2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
     3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
 #if TCL_UTF_MAX > 3
     4,4,4,4,4,
 #else
-    3,3,3,3,3, /* Tcl_UtfCharComplete() only checks TCL_UTF_MAX bytes */
+    1,1,1,1,1,
+#endif
+    1,1,1,1,1,1,1,1,1,1,1
+};
+
+static const unsigned char complete[256] = {
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+/* Tcl_UtfCharComplete() might point to 2nd byte of valid 4-byte sequence */
+    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+/* End of "continuation byte section" */
+    2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+    3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+#if TCL_UTF_MAX > 3
+    4,4,4,4,4,
+#else
+    3,3,3,3,3,
 #endif
     1,1,1,1,1,1,1,1,1,1,1
 };
@@ -81,6 +100,9 @@ static const unsigned char totalBytes[256] = {
  */
 
 static int             UtfCount(int ch);
+static int             Invalid(const char *src);
+static int             UCS4ToUpper(int ch);
+static int             UCS4ToTitle(int ch);
 \f
 /*
  *---------------------------------------------------------------------------
@@ -115,7 +137,68 @@ UtfCount(
 #endif
     return 3;
 }
+\f
+/*
+ *---------------------------------------------------------------------------
+ *
+ * Invalid --
+ *
+ *     Given a pointer to a two-byte prefix of a well-formed UTF-8 byte
+ *     sequence (a lead byte followed by a trail byte) this routine
+ *     examines those two bytes to determine whether the sequence is
+ *     invalid in UTF-8.  This might be because it is an overlong
+ *     encoding, or because it encodes something out of the proper range.
+ *
+ *     Given a pointer to the bytes \xF8 or \xFC , this routine will
+ *     try to read beyond the end of the "bounds" table.  Callers must
+ *     prevent this.
+ *
+ *     Given a pointer to something else (an ASCII byte, a trail byte,
+ *     or another byte that can never begin a valid byte sequence such
+ *     as \xF5) this routine returns false.  That makes the routine poorly
+ *     named, as it does not detect and report all invalid sequences.
+ *
+ *     Callers have to take care that this routine does something useful
+ *     for their needs.
+ *
+ * Results:
+ *     A boolean.
+ *---------------------------------------------------------------------------
+ */
+
+static const unsigned char bounds[28] = {
+    0x80, 0x80,                /* \xC0 accepts \x80 only */
+    0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF,
+    0x80, 0xBF,                /* (\xC4 - \xDC) -- all sequences valid */
+    0xA0, 0xBF,        /* \xE0\x80 through \xE0\x9F are invalid prefixes */
+    0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, /* (\xE4 - \xEC) -- all valid */
+#if TCL_UTF_MAX > 3
+    0x90, 0xBF,        /* \xF0\x80 through \xF0\x8F are invalid prefixes */
+    0x80, 0x8F  /* \xF4\x90 and higher are invalid prefixes */
+#else
+    0xC0, 0xBF,        /* Not used, but reject all again for safety. */
+    0xC0, 0xBF /* Not used, but reject all again for safety. */
+#endif
+};
 
+static int
+Invalid(
+    const char *src)   /* Points to lead byte of a UTF-8 byte sequence */
+{
+    unsigned char byte = UCHAR(*src);
+    int index;
+
+    if ((byte & 0xC3) == 0xC0) {
+       /* Only lead bytes 0xC0, 0xE0, 0xF0, 0xF4 need examination */
+       index = (byte - 0xC0) >> 1;
+       if (UCHAR(src[1]) < bounds[index] || UCHAR(src[1]) > bounds[index+1]) {
+           /* Out of bounds - report invalid. */
+           return 1;
+       }
+    }
+    return 0;
+}
+\f
 /*
  *---------------------------------------------------------------------------
  *
@@ -278,8 +361,8 @@ Tcl_UniCharToUtfDString(
  *     If TCL_UTF_MAX <= 4, special handling of Surrogate pairs is done:
  *     For any UTF-8 string containing a character outside of the BMP, the
  *     first call to this function will fill *chPtr with the high surrogate
- *     and generate a return value of 0. Calling Tcl_UtfToUniChar again
- *     will produce the low surrogate and a return value of 4. Because *chPtr
+ *     and generate a return value of 1. Calling Tcl_UtfToUniChar again
+ *     will produce the low surrogate and a return value of 3. Because *chPtr
  *     is used to remember whether the high surrogate is already produced, it
  *     is recommended to initialize the variable it points to as 0 before
  *     the first call to Tcl_UtfToUniChar is done.
@@ -296,8 +379,8 @@ Tcl_UniCharToUtfDString(
 
 int
 Tcl_UtfToUniChar(
-    register const char *src,  /* The UTF-8 string. */
-    register Tcl_UniChar *chPtr)/* Filled with the Tcl_UniChar represented by
+    const char *src,   /* The UTF-8 string. */
+    Tcl_UniChar *chPtr)/* Filled with the Tcl_UniChar represented by
                                 * the UTF-8 string. */
 {
     Tcl_UniChar byte;
@@ -306,7 +389,7 @@ Tcl_UtfToUniChar(
      * Unroll 1 to 3 (or 4) byte UTF-8 sequences.
      */
 
-    byte = *((unsigned char *) src);
+    byte = UCHAR(*src);
     if (byte < 0xC0) {
        /*
         * Handles properly formed UTF-8 characters between 0x01 and 0x7F.
@@ -320,10 +403,10 @@ Tcl_UtfToUniChar(
         * bytes, then we must produce a follow-up low surrogate. We only
         * do that if the high surrogate matches the bits we encounter.
         */
-       if ((byte >= 0x80)
+       if (((byte & 0xC0) == 0x80)
+               && ((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80)
                && (((((byte - 0x10) << 2) & 0xFC) | 0xD800) == (*chPtr & 0xFCFC))
-               && ((src[1] & 0xF0) == (((*chPtr << 4) & 0x30) | 0x80))
-               && ((src[2] & 0xC0) == 0x80)) {
+               && ((src[1] & 0xF0) == (((*chPtr << 4) & 0x30) | 0x80))) {
            *chPtr = ((src[1] & 0x0F) << 6) + (src[2] & 0x3F) + 0xDC00;
            return 3;
        }
@@ -364,26 +447,28 @@ Tcl_UtfToUniChar(
         * represents itself.
         */
     }
-    else if (byte < 0xF8) {
-       if (((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80) && ((src[3] & 0xC0) == 0x80)) {
+    else if (byte < 0xF5) {
+       if (((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80)) {
            /*
-            * Four-byte-character lead byte followed by three trail bytes.
+            * Four-byte-character lead byte followed by at least two trail bytes.
+            * We don't test the validity of 3th trail byte, see [ed29806ba]
             */
 #if TCL_UTF_MAX <= 4
            Tcl_UniChar high = (((byte & 0x07) << 8) | ((src[1] & 0x3F) << 2)
                    | ((src[2] & 0x3F) >> 4)) - 0x40;
-           if (high >= 0x400) {
-               /* out of range, < 0x10000 or > 0x10ffff */
-           } else {
+           if (high < 0x400) {
                /* produce high surrogate, advance source pointer */
                *chPtr = 0xD800 + high;
                return 1;
            }
+           /* out of range, < 0x10000 or > 0x10FFFF */
 #else
-           *chPtr = (((byte & 0x07) << 18) | ((src[1] & 0x3F) << 12)
-                   | ((src[2] & 0x3F) << 6) | (src[3] & 0x3F));
-           if ((unsigned)(*chPtr - 0x10000) <= 0xFFFFF) {
-               return 4;
+           if ((src[3] & 0xC0) == 0x80) {
+               *chPtr = (((byte & 0x07) << 18) | ((src[1] & 0x3F) << 12)
+                       | ((src[2] & 0x3F) << 6) | (src[3] & 0x3F));
+               if ((unsigned)(*chPtr - 0x10000) <= 0xFFFFF) {
+                   return 4;
+               }
            }
 #endif
        }
@@ -426,8 +511,12 @@ Tcl_UtfToUniCharDString(
                                 * DString. */
 {
     Tcl_UniChar ch = 0, *w, *wString;
-    const char *p, *end;
+    const char *p;
     int oldLength;
+    /* Pointer to the end of string. Never read endPtr[0] */
+    const char *endPtr = src + length;
+    /* Pointer to last byte where optimization still can be used */
+    const char *optPtr = endPtr - TCL_UTF_MAX;
 
     if (length < 0) {
        length = strlen(src);
@@ -441,28 +530,28 @@ Tcl_UtfToUniCharDString(
     oldLength = Tcl_DStringLength(dsPtr);
 
     Tcl_DStringSetLength(dsPtr,
-           oldLength + (int) ((length + 1) * sizeof(Tcl_UniChar)));
+           oldLength + ((length + 1) * sizeof(Tcl_UniChar)));
     wString = (Tcl_UniChar *) (Tcl_DStringValue(dsPtr) + oldLength);
 
     w = wString;
     p = src;
-    end = src + length - TCL_UTF_MAX;
-    while (p < end) {
+    endPtr = src + length;
+    optPtr = endPtr - TCL_UTF_MAX;
+    while (p <= optPtr) {
        p += TclUtfToUniChar(p, &ch);
        *w++ = ch;
     }
-    end += TCL_UTF_MAX;
-    while (p < end) {
-       if (Tcl_UtfCharComplete(p, end-p)) {
+    while (p < endPtr) {
+       if (Tcl_UtfCharComplete(p, endPtr-p)) {
            p += TclUtfToUniChar(p, &ch);
+           *w++ = ch;
        } else {
-           ch = UCHAR(*p++);
+           *w++ = UCHAR(*p++);
        }
-       *w++ = ch;
     }
     *w = '\0';
     Tcl_DStringSetLength(dsPtr,
-           (oldLength + ((char *) w - (char *) wString)));
+           oldLength + ((char *) w - (char *) wString));
 
     return wString;
 }
@@ -492,7 +581,7 @@ Tcl_UtfCharComplete(
                                 * a complete UTF-8 character. */
     int length)                        /* Length of above string in bytes. */
 {
-    return length >= totalBytes[(unsigned char)*src];
+    return length >= complete[UCHAR(*src)];
 }
 \f
 /*
@@ -515,41 +604,52 @@ Tcl_UtfCharComplete(
 
 int
 Tcl_NumUtfChars(
-    register const char *src,  /* The UTF-8 string to measure. */
-    int length)                        /* The length of the string in bytes, or -1
-                                * for strlen(string). */
+    const char *src,   /* The UTF-8 string to measure. */
+    int length)                /* The length of the string in bytes, or -1
+                        * for strlen(string). */
 {
     Tcl_UniChar ch = 0;
-    register int i = 0;
-
-    /*
-     * The separate implementations are faster.
-     *
-     * Since this is a time-sensitive function, we also do the check for the
-     * single-byte char case specially.
-     */
+    int i = 0;
 
     if (length < 0) {
-       while (*src != '\0') {
+       /* string is NUL-terminated, so TclUtfToUniChar calls are safe. */
+       while ((*src != '\0') && (i < INT_MAX)) {
            src += TclUtfToUniChar(src, &ch);
            i++;
        }
-       if (i < 0) i = INT_MAX; /* Bug [2738427] */
     } else {
-       register const char *endPtr = src + length - TCL_UTF_MAX;
+       /* Will return value between 0 and length. No overflow checks. */
 
-       while (src < endPtr) {
+       /* Pointer to the end of string. Never read endPtr[0] */
+       const char *endPtr = src + length;
+       /* Pointer to last byte where optimization still can be used */
+       const char *optPtr = endPtr - TCL_UTF_MAX;
+
+       /*
+        * Optimize away the call in this loop. Justified because...
+        * when (src <= optPtr), (endPtr - src) >= (endPtr - optPtr)
+        * By initialization above (endPtr - optPtr) = TCL_UTF_MAX
+        * So (endPtr - src) >= TCL_UTF_MAX, and passing that to
+        * Tcl_UtfCharComplete we know will cause return of 1.
+        */
+       while (src <= optPtr
+               /* && Tcl_UtfCharComplete(src, endPtr - src) */ ) {
            src += TclUtfToUniChar(src, &ch);
            i++;
        }
-       endPtr += TCL_UTF_MAX;
-       while ((src < endPtr) && Tcl_UtfCharComplete(src, endPtr - src)) {
-           src += TclUtfToUniChar(src, &ch);
+       /* Loop over the remaining string where call must happen */
+       while (src < endPtr) {
+           if (Tcl_UtfCharComplete(src, endPtr - src)) {
+               src += TclUtfToUniChar(src, &ch);
+           } else {
+               /*
+                * src points to incomplete UTF-8 sequence
+                * Treat first byte as character and count it
+                */
+               src++;
+           }
            i++;
        }
-       if (src < endPtr) {
-           i += endPtr - src;
-       }
     }
     return i;
 }
@@ -559,7 +659,7 @@ Tcl_NumUtfChars(
  *
  * Tcl_UtfFindFirst --
  *
- *     Returns a pointer to the first occurance of the given Unicode character
+ *     Returns a pointer to the first occurrence of the given Unicode character
  *     in the NULL-terminated UTF-8 string. The NULL terminator is considered
  *     part of the UTF-8 string. Equivalent to Plan 9 utfrune().
  *
@@ -578,19 +678,10 @@ Tcl_UtfFindFirst(
     const char *src,           /* The UTF-8 string to be searched. */
     int ch)                    /* The Unicode character to search for. */
 {
-    int len, fullchar;
-    Tcl_UniChar find = 0;
-
     while (1) {
-       len = TclUtfToUniChar(src, &find);
-       fullchar = find;
-#if TCL_UTF_MAX <= 4
-       if ((fullchar != ch) && (find >= 0xD800) && (len < 3)) {
-           len += TclUtfToUniChar(src + len, &find);
-           fullchar = (((fullchar & 0x3ff) << 10) | (find & 0x3ff)) + 0x10000;
-       }
-#endif
-       if (fullchar == ch) {
+       int find, len = TclUtfToUCS4(src, &find);
+
+       if (find == ch) {
            return src;
        }
        if (*src == '\0') {
@@ -605,7 +696,7 @@ Tcl_UtfFindFirst(
  *
  * Tcl_UtfFindLast --
  *
- *     Returns a pointer to the last occurance of the given Unicode character
+ *     Returns a pointer to the last occurrence of the given Unicode character
  *     in the NULL-terminated UTF-8 string. The NULL terminator is considered
  *     part of the UTF-8 string. Equivalent to Plan 9 utfrrune().
  *
@@ -624,21 +715,12 @@ Tcl_UtfFindLast(
     const char *src,           /* The UTF-8 string to be searched. */
     int ch)                    /* The Unicode character to search for. */
 {
-    int len, fullchar;
-    Tcl_UniChar find = 0;
-    const char *last;
+    const char *last = NULL;
 
-    last = NULL;
     while (1) {
-       len = TclUtfToUniChar(src, &find);
-       fullchar = find;
-#if TCL_UTF_MAX <= 4
-       if ((fullchar != ch) && (find >= 0xD800) && (len < 3)) {
-           len += TclUtfToUniChar(src + len, &find);
-           fullchar = (((fullchar & 0x3ff) << 10) | (find & 0x3ff)) + 0x10000;
-       }
-#endif
-       if (fullchar == ch) {
+       int find, len = TclUtfToUCS4(src, &find);
+
+       if (find == ch) {
            last = src;
        }
        if (*src == '\0') {
@@ -654,9 +736,11 @@ Tcl_UtfFindLast(
  *
  * Tcl_UtfNext --
  *
- *     Given a pointer to some current location in a UTF-8 string, move
- *     forward one character. The caller must ensure that they are not asking
- *     for the next character after the last character in the string.
+ *     Given a pointer to some location in a UTF-8 string, Tcl_UtfNext
+ *     returns a pointer to the next UTF-8 character in the string.
+ *     The caller must not ask for the next character after the last
+ *     character in the string if the string is not terminated by a null
+ *     character.
  *
  * Results:
  *     The return value is the pointer to the next character in the UTF-8
@@ -672,15 +756,33 @@ const char *
 Tcl_UtfNext(
     const char *src)           /* The current location in the string. */
 {
-    Tcl_UniChar ch = 0;
-    int len = TclUtfToUniChar(src, &ch);
+    int left;
+    const char *next;
 
-#if TCL_UTF_MAX <= 4
-    if ((ch >= 0xD800) && (len < 3)) {
-       len += TclUtfToUniChar(src + len, &ch);
+    left = totalBytes[UCHAR(*src)];
+    next = src + 1;
+    while (--left) {
+       if ((*next & 0xC0) != 0x80) {
+           /*
+            * src points to non-trail byte; We ran out of trail bytes
+            * before the needs of the lead byte were satisfied.
+            * Let the (malformed) lead byte alone be a character
+            */
+           return src + 1;
+       }
+       next++;
     }
-#endif
-    return src + len;
+    /*
+     * Call Invalid() here only if required conditions are met:
+     *    src[0] is known a lead byte.
+     *    src[1] is known a trail byte.
+     * Especially important to prevent calls when src[0] == '\xF8' or '\xFC'
+     * See tests utf-6.37 through utf-6.43 through valgrind or similar tool.
+     */
+    if ((next == src + 1) || Invalid(src)) {
+       return src + 1;
+    }
+    return next;
 }
 \f
 /*
@@ -706,31 +808,95 @@ Tcl_UtfNext(
 
 const char *
 Tcl_UtfPrev(
-    const char *src,           /* The current location in the string. */
-    const char *start)         /* Pointer to the beginning of the string, to
-                                * avoid going backwards too far. */
+    const char *src,           /* A location in a UTF-8 string. */
+    const char *start)         /* Pointer to the beginning of the string */
 {
-    const char *look;
-    int i, byte;
-
-    look = --src;
-    for (i = 0; i < 4; i++) {
-       if (look < start) {
-           if (src < start) {
-               src = start;
-           }
-           break;
-       }
-       byte = *((unsigned char *) look);
+    int trailBytesSeen = 0;    /* How many trail bytes have been verified? */
+    const char *fallback = src - 1;
+                               /* If we cannot find a lead byte that might
+                                * start a prefix of a valid UTF byte sequence,
+                                * we will fallback to a one-byte back step */
+    const char *look = fallback;
+                               /* Start search at the fallback position */
+
+    /* Quick boundary case exit. */
+    if (fallback <= start) {
+       return start;
+    }
+
+    do {
+       unsigned char byte = UCHAR(look[0]);
+
        if (byte < 0x80) {
-           break;
+           /*
+            * Single byte character. Either this is a correct previous
+            * character, or it is followed by at least one trail byte
+            * which indicates a malformed sequence. In either case the
+            * correct result is to return the fallback.
+            */
+           return fallback;
        }
        if (byte >= 0xC0) {
-           return look;
+           /* Non-trail byte; May be multibyte lead. */
+
+           if ((trailBytesSeen == 0)
+               /*
+                * We've seen no trailing context to use to check
+                * anything. From what we know, this non-trail byte
+                * is a prefix of a previous character, and accepting
+                * it (the fallback) is correct.
+                */
+
+                   || (trailBytesSeen >= totalBytes[byte])) {
+               /*
+                * That is, (1 + trailBytesSeen > needed).
+                * We've examined more bytes than needed to complete
+                * this lead byte. No matter about well-formedness or
+                * validity, the sequence starting with this lead byte
+                * will never include the fallback location, so we must
+                * return the fallback location. See test utf-7.17
+                */
+               return fallback;
+           }
+
+           /*
+            * trailBytesSeen > 0, so we can examine look[1] safely.
+            * Use that capability to screen out invalid sequences.
+            */
+
+           if (Invalid(look)) {
+               /* Reject */
+               return fallback;
+           }
+           return (const char *)look;
        }
+
+       /* We saw a trail byte. */
+       trailBytesSeen++;
+
+       if ((const char *)look == start) {
+           /*
+            * Do not read before the start of the string
+            *
+            * If we get here, we've examined bytes at every location
+            * >= start and < src and all of them are trail bytes,
+            * including (*start).  We need to return our fallback
+            * and exit this loop before we run past the start of the string.
+            */
+           return fallback;
+       }
+
+       /* Continue the search backwards... */
        look--;
-    }
-    return src;
+    } while (trailBytesSeen < 3);
+
+    /*
+     * We've seen 3 trail bytes, so we know there will not be a
+     * properly formed byte sequence to find, and we can stop looking,
+     * accepting the fallback.
+     */
+
+    return fallback;
 }
 \f
 /*
@@ -752,8 +918,8 @@ Tcl_UtfPrev(
 
 Tcl_UniChar
 Tcl_UniCharAtIndex(
-    register const char *src,  /* The UTF-8 string to dereference. */
-    register int index)                /* The position of the desired character. */
+    const char *src,   /* The UTF-8 string to dereference. */
+    int index)         /* The position of the desired character. */
 {
     Tcl_UniChar ch = 0;
 
@@ -782,8 +948,8 @@ Tcl_UniCharAtIndex(
 
 const char *
 Tcl_UtfAtIndex(
-    register const char *src,  /* The UTF-8 string. */
-    register int index)                /* The position of the desired character. */
+    const char *src,   /* The UTF-8 string. */
+    int index)         /* The position of the desired character. */
 {
     Tcl_UniChar ch = 0;
     int len = 0;
@@ -846,7 +1012,7 @@ Tcl_UtfBackslash(
         * We ate a whole line. Pay the price of a strlen()
         */
 
-       result = TclParseBackslash(src, (int)strlen(src), &numRead, dst);
+       result = TclParseBackslash(src, strlen(src), &numRead, dst);
     }
     if (readPtr != NULL) {
        *readPtr = numRead;
@@ -876,7 +1042,7 @@ int
 Tcl_UtfToUpper(
     char *str)                 /* String to convert in place. */
 {
-    Tcl_UniChar ch = 0, upChar;
+    int ch, upChar;
     char *src, *dst;
     int len;
 
@@ -886,8 +1052,8 @@ Tcl_UtfToUpper(
 
     src = dst = str;
     while (*src) {
-       len = TclUtfToUniChar(src, &ch);
-       upChar = Tcl_UniCharToUpper(ch);
+       len = TclUtfToUCS4(src, &ch);
+       upChar = UCS4ToUpper(ch);
 
        /*
         * To keep badly formed Utf strings from getting inflated by the
@@ -899,7 +1065,7 @@ Tcl_UtfToUpper(
            memmove(dst, src, len);
            dst += len;
        } else {
-           dst += Tcl_UniCharToUtf(upChar, dst);
+           dst += TclUCS4ToUtf(upChar, dst);
        }
        src += len;
     }
@@ -929,7 +1095,7 @@ int
 Tcl_UtfToLower(
     char *str)                 /* String to convert in place. */
 {
-    Tcl_UniChar ch = 0, lowChar;
+    int ch, lowChar;
     char *src, *dst;
     int len;
 
@@ -939,8 +1105,8 @@ Tcl_UtfToLower(
 
     src = dst = str;
     while (*src) {
-       len = TclUtfToUniChar(src, &ch);
-       lowChar = Tcl_UniCharToLower(ch);
+       len = TclUtfToUCS4(src, &ch);
+       lowChar = TclUCS4ToLower(ch);
 
        /*
         * To keep badly formed Utf strings from getting inflated by the
@@ -952,7 +1118,7 @@ Tcl_UtfToLower(
            memmove(dst, src, len);
            dst += len;
        } else {
-           dst += Tcl_UniCharToUtf(lowChar, dst);
+           dst += TclUCS4ToUtf(lowChar, dst);
        }
        src += len;
     }
@@ -983,7 +1149,7 @@ int
 Tcl_UtfToTitle(
     char *str)                 /* String to convert in place. */
 {
-    Tcl_UniChar ch = 0, titleChar, lowChar;
+    int ch, titleChar, lowChar;
     char *src, *dst;
     int len;
 
@@ -995,30 +1161,30 @@ Tcl_UtfToTitle(
     src = dst = str;
 
     if (*src) {
-       len = TclUtfToUniChar(src, &ch);
-       titleChar = Tcl_UniCharToTitle(ch);
+       len = TclUtfToUCS4(src, &ch);
+       titleChar = UCS4ToTitle(ch);
 
        if (len < UtfCount(titleChar)) {
            memmove(dst, src, len);
            dst += len;
        } else {
-           dst += Tcl_UniCharToUtf(titleChar, dst);
+           dst += TclUCS4ToUtf(titleChar, dst);
        }
        src += len;
     }
     while (*src) {
-       len = TclUtfToUniChar(src, &ch);
+       len = TclUtfToUCS4(src, &ch);
        lowChar = ch;
        /* Special exception for Georgian Asomtavruli chars, no titlecase. */
        if ((unsigned)(lowChar - 0x1C90) >= 0x30) {
-           lowChar = Tcl_UniCharToLower(lowChar);
+           lowChar = TclUCS4ToLower(lowChar);
        }
 
        if (len < UtfCount(lowChar)) {
            memmove(dst, src, len);
            dst += len;
        } else {
-           dst += Tcl_UniCharToUtf(lowChar, dst);
+           dst += TclUCS4ToUtf(lowChar, dst);
        }
        src += len;
     }
@@ -1055,7 +1221,7 @@ TclpUtfNcmp2(
      * fine in the strcmp manner.
      */
 
-    register int result = 0;
+    int result = 0;
 
     for ( ; numBytes != 0; numBytes--, cs++, ct++) {
        if (*cs != *ct) {
@@ -1116,11 +1282,11 @@ Tcl_UtfNcmp(
        if (ch1 != ch2) {
 #if TCL_UTF_MAX == 4
            /* Surrogates always report higher than non-surrogates */
-           if (((ch1 & 0xFC00) == 0xD800)) {
-           if ((ch2 & 0xFC00) != 0xD800) {
+           if (((ch1 & ~0x3FF) == 0xD800)) {
+           if ((ch2 & ~0x3FF) != 0xD800) {
                return ch1;
            }
-           } else if ((ch2 & 0xFC00) == 0xD800) {
+           } else if ((ch2 & ~0x3FF) == 0xD800) {
                return -ch2;
            }
 #endif
@@ -1251,16 +1417,26 @@ TclUtfCasecmp(
  *----------------------------------------------------------------------
  */
 
-Tcl_UniChar
-Tcl_UniCharToUpper(
+static int
+UCS4ToUpper(
     int ch)                    /* Unicode character to convert. */
 {
-    int info = GetUniCharInfo(ch);
+    if (!UNICODE_OUT_OF_RANGE(ch)) {
+       int info = GetUniCharInfo(ch);
 
-    if (GetCaseType(info) & 0x04) {
-       ch -= GetDelta(info);
+       if (GetCaseType(info) & 0x04) {
+           ch -= GetDelta(info);
+       }
     }
-    return (Tcl_UniChar) ch;
+    /* Clear away extension bits, if any */
+    return ch & 0x1FFFFF;
+}
+
+Tcl_UniChar
+Tcl_UniCharToUpper(
+    int ch)                    /* Unicode character to convert. */
+{
+    return (Tcl_UniChar) UCS4ToUpper(ch);
 }
 \f
 /*
@@ -1279,17 +1455,27 @@ Tcl_UniCharToUpper(
  *----------------------------------------------------------------------
  */
 
-Tcl_UniChar
-Tcl_UniCharToLower(
+int
+TclUCS4ToLower(
     int ch)                    /* Unicode character to convert. */
 {
-    int info = GetUniCharInfo(ch);
-    int mode = GetCaseType(info);
+    if (!UNICODE_OUT_OF_RANGE(ch)) {
+       int info = GetUniCharInfo(ch);
+       int mode = GetCaseType(info);
 
-    if ((mode & 0x02) && (mode != 0x7)) {
-       ch += GetDelta(info);
+       if ((mode & 0x02) && (mode != 0x7)) {
+           ch += GetDelta(info);
+       }
     }
-    return (Tcl_UniChar) ch;
+    /* Clear away extension bits, if any */
+    return ch & 0x1FFFFF;
+}
+
+Tcl_UniChar
+Tcl_UniCharToLower(
+    int ch)                    /* Unicode character to convert. */
+{
+    return (Tcl_UniChar) TclUCS4ToLower(ch);
 }
 \f
 /*
@@ -1308,25 +1494,35 @@ Tcl_UniCharToLower(
  *----------------------------------------------------------------------
  */
 
-Tcl_UniChar
-Tcl_UniCharToTitle(
+static int
+UCS4ToTitle(
     int ch)                    /* Unicode character to convert. */
 {
-    int info = GetUniCharInfo(ch);
-    int mode = GetCaseType(info);
+    if (!UNICODE_OUT_OF_RANGE(ch)) {
+       int info = GetUniCharInfo(ch);
+       int mode = GetCaseType(info);
 
-    if (mode & 0x1) {
-       /*
-        * Subtract or add one depending on the original case.
-        */
+       if (mode & 0x1) {
+           /*
+            * Subtract or add one depending on the original case.
+            */
 
-       if (mode != 0x7) {
-           ch += ((mode & 0x4) ? -1 : 1);
+           if (mode != 0x7) {
+               ch += ((mode & 0x4) ? -1 : 1);
+           }
+       } else if (mode == 0x4) {
+           ch -= GetDelta(info);
        }
-    } else if (mode == 0x4) {
-       ch -= GetDelta(info);
     }
-    return (Tcl_UniChar) ch;
+    /* Clear away extension bits, if any */
+    return ch & 0x1FFFFF;
+}
+
+Tcl_UniChar
+Tcl_UniCharToTitle(
+    int ch)                    /* Unicode character to convert. */
+{
+    return (Tcl_UniChar) UCS4ToTitle(ch);
 }
 \f
 /*
@@ -1518,8 +1714,9 @@ Tcl_UniCharIsControl(
 {
 #if TCL_UTF_MAX > 3
     if (UNICODE_OUT_OF_RANGE(ch)) {
+       /* Clear away extension bits, if any */
        ch &= 0x1FFFFF;
-       if ((ch == 0xE0001) || ((ch >= 0xE0020) && (ch <= 0xE007f))) {
+       if ((ch == 0xE0001) || ((ch >= 0xE0020) && (ch <= 0xE007F))) {
            return 1;
        }
        if ((ch >= 0xF0000) && ((ch & 0xFFFF) <= 0xFFFD)) {
@@ -1581,8 +1778,7 @@ Tcl_UniCharIsGraph(
 {
 #if TCL_UTF_MAX > 3
     if (UNICODE_OUT_OF_RANGE(ch)) {
-       ch &= 0x1FFFFF;
-       return (ch >= 0xE0100) && (ch <= 0xE01EF);
+       return ((unsigned)((ch & 0x1FFFFF) - 0xE0100) <= 0xEF);
     }
 #endif
     return ((GRAPH_BITS >> GetCategory(ch)) & 1);
@@ -1638,8 +1834,7 @@ Tcl_UniCharIsPrint(
 {
 #if TCL_UTF_MAX > 3
     if (UNICODE_OUT_OF_RANGE(ch)) {
-       ch &= 0x1FFFFF;
-       return (ch >= 0xE0100) && (ch <= 0xE01EF);
+       return ((unsigned)((ch & 0x1FFFFF) - 0xE0100) <= 0xEF);
     }
 #endif
     return (((GRAPH_BITS|SPACE_BITS) >> GetCategory(ch)) & 1);
@@ -1707,7 +1902,7 @@ Tcl_UniCharIsSpace(
      */
 
     if (ch < 0x80) {
-       return TclIsSpaceProc((char) ch);
+       return TclIsSpaceProcM((char) ch);
 #if TCL_UTF_MAX > 3
     } else if (UNICODE_OUT_OF_RANGE(ch)) {
        return 0;
@@ -2158,6 +2353,119 @@ TclUniCharMatch(
 }
 \f
 /*
+ *---------------------------------------------------------------------------
+ *
+ * TclUtfToUCS4 --
+ *
+ *     Extract the 4-byte codepoint from the leading bytes of the
+ *     Modified UTF-8 string "src".  This is a utility routine to
+ *     contain the surrogate gymnastics in one place.
+ *
+ *     The caller must ensure that the source buffer is long enough that this
+ *     routine does not run off the end and dereference non-existent memory
+ *     looking for trail bytes. If the source buffer is known to be '\0'
+ *     terminated, this cannot happen. Otherwise, the caller should call
+ *     TclUCS4Complete() before calling this routine to ensure that
+ *     enough bytes remain in the string.
+ *
+ * Results:
+ *     *usc4Ptr is filled with the UCS4 code point, and the return value is
+ *     the number of bytes from the UTF-8 string that were consumed.
+ *
+ * Side effects:
+ *     None.
+ *
+ *---------------------------------------------------------------------------
+ */
+
+int
+TclUtfToUCS4(
+    const char *src,   /* The UTF-8 string. */
+    int *ucs4Ptr)      /* Filled with the UCS4 codepoint represented
+                        * by the UTF-8 string. */
+{
+    Tcl_UniChar ch = 0;
+    int len = Tcl_UtfToUniChar(src, &ch);
+
+#if TCL_UTF_MAX <= 4
+    if ((ch & ~0x3FF) == 0xD800) {
+       Tcl_UniChar low = ch;
+       int len2 = Tcl_UtfToUniChar(src+len, &low);
+       if ((low & ~0x3FF) == 0xDC00) {
+           *ucs4Ptr = (((ch & 0x3FF) << 10) | (low & 0x3FF)) + 0x10000;
+           return len + len2;
+       }
+    }
+#endif
+    *ucs4Ptr = (int)ch;
+    return len;
+}
+
+#if TCL_UTF_MAX == 4
+int
+TclUniCharToUCS4(
+    const Tcl_UniChar *src,    /* The Tcl_UniChar string. */
+    int *ucs4Ptr)      /* Filled with the UCS4 codepoint represented
+                        * by the Tcl_UniChar string. */
+{
+    if (((src[0] & 0xFC00) == 0xD800) && ((src[1] & 0xFC00) == 0xDC00)) {
+       *ucs4Ptr = (((src[0] & 0x3FF) << 10) | (src[01] & 0x3FF)) + 0x10000;
+       return 2;
+    }
+    *ucs4Ptr = src[0];
+    return 1;
+}
+#endif
+\f
+/*
+ *---------------------------------------------------------------------------
+ *
+ * TclUCS4ToUtf --
+ *
+ *     Store the given Unicode character as a sequence of UTF-8 bytes in the
+ *     provided buffer. Might output 6 bytes, if the code point > 0xFFFF.
+ *
+ * Results:
+ *     The return values is the number of bytes in the buffer that were
+ *     consumed. If ch == -1, this function outputs 0 bytes (empty string),
+ *     since TclGetUCS4 returns -1 for out-of-range indices.
+ *
+ * Side effects:
+ *     None.
+ *
+ *---------------------------------------------------------------------------
+ */
+
+int
+TclUCS4ToUtf(
+    int ch,                    /* Unicode character to be stored in the
+                                * buffer. */
+    char *buf)                 /* Buffer in which the UTF-8 representation of
+                                * the Unicode character is stored. Buffer must be
+                                * large enough to hold the UTF-8 character(s)
+                                * (at most 6 bytes). */
+{
+#if TCL_UTF_MAX <= 4
+    if (((unsigned)(ch - 0x10000) <= 0xFFFFF)) {
+       /* Spit out a 4-byte UTF-8 character or 2 x 3-byte UTF-8 characters, depending on Tcl
+        * version and/or TCL_UTF_MAX build value */
+       int len = Tcl_UniCharToUtf(0xD800 | ((ch - 0x10000) >> 10), buf);
+       return len + Tcl_UniCharToUtf(0xDC00 | (ch & 0x7FF), buf + len);
+    }
+#endif
+    if ((ch & ~0x7FF) == 0xD800) {
+       buf[2] = (char) ((ch | 0x80) & 0xBF);
+       buf[1] = (char) (((ch >> 6) | 0x80) & 0xBF);
+       buf[0] = (char) ((ch >> 12) | 0xE0);
+       return 3;
+    }
+    if (ch == -1) {
+       return 0;
+    }
+    return Tcl_UniCharToUtf(ch, buf);
+}
+
+/*
  * Local Variables:
  * mode: c
  * c-basic-offset: 4
index 61c1973..d7baedd 100644 (file)
@@ -404,7 +404,7 @@ TclMaxListLength(
      * No list element before leading white space.
      */
 
-    count += 1 - TclIsSpaceProc(*bytes);
+    count += 1 - TclIsSpaceProcM(*bytes);
 
     /*
      * Count white space runs as potential element separators.
@@ -414,7 +414,7 @@ TclMaxListLength(
        if ((numBytes == -1) && (*bytes == '\0')) {
            break;
        }
-       if (TclIsSpaceProc(*bytes)) {
+       if (TclIsSpaceProcM(*bytes)) {
            /*
             * Space run started; bump count.
             */
@@ -423,7 +423,7 @@ TclMaxListLength(
            do {
                bytes++;
                numBytes -= (numBytes != -1);
-           } while (numBytes && TclIsSpaceProc(*bytes));
+           } while (numBytes && TclIsSpaceProcM(*bytes));
            if ((numBytes == 0) || ((numBytes == -1) && (*bytes == '\0'))) {
                break;
            }
@@ -440,7 +440,7 @@ TclMaxListLength(
      * No list element following trailing white space.
      */
 
-    count -= TclIsSpaceProc(bytes[-1]);
+    count -= TclIsSpaceProcM(bytes[-1]);
 
   done:
     if (endPtr) {
@@ -577,7 +577,7 @@ FindElement(
     const char *limit;         /* Points just after list/dict's last byte. */
     int openBraces = 0;                /* Brace nesting level during parse. */
     int inQuotes = 0;
-    int size = 0;              /* lint. */
+    int size = 0;
     int numChars;
     int literal = 1;
     const char *p2;
@@ -589,7 +589,7 @@ FindElement(
      */
 
     limit = (string + stringLength);
-    while ((p < limit) && (TclIsSpaceProc(*p))) {
+    while ((p < limit) && (TclIsSpaceProcM(*p))) {
        p++;
     }
     if (p == limit) {          /* no element found */
@@ -634,7 +634,7 @@ FindElement(
            } else if (openBraces == 1) {
                size = (p - elemStart);
                p++;
-               if ((p >= limit) || TclIsSpaceProc(*p)) {
+               if ((p >= limit) || TclIsSpaceProcM(*p)) {
                    goto done;
                }
 
@@ -644,7 +644,7 @@ FindElement(
 
                if (interp != NULL) {
                    p2 = p;
-                   while ((p2 < limit) && (!TclIsSpaceProc(*p2))
+                   while ((p2 < limit) && (!TclIsSpaceProcM(*p2))
                            && (p2 < p+20)) {
                        p2++;
                    }
@@ -679,23 +679,6 @@ FindElement(
            break;
 
            /*
-            * Space: ignore if element is in braces or quotes; otherwise
-            * terminate element.
-            */
-
-       case ' ':
-       case '\f':
-       case '\n':
-       case '\r':
-       case '\t':
-       case '\v':
-           if ((openBraces == 0) && !inQuotes) {
-               size = (p - elemStart);
-               goto done;
-           }
-           break;
-
-           /*
             * Double-quote: if element is in quotes then terminate it.
             */
 
@@ -703,7 +686,7 @@ FindElement(
            if (inQuotes) {
                size = (p - elemStart);
                p++;
-               if ((p >= limit) || TclIsSpaceProc(*p)) {
+               if ((p >= limit) || TclIsSpaceProcM(*p)) {
                    goto done;
                }
 
@@ -713,7 +696,7 @@ FindElement(
 
                if (interp != NULL) {
                    p2 = p;
-                   while ((p2 < limit) && (!TclIsSpaceProc(*p2))
+                   while ((p2 < limit) && (!TclIsSpaceProcM(*p2))
                            && (p2 < p+20)) {
                        p2++;
                    }
@@ -726,6 +709,20 @@ FindElement(
                return TCL_ERROR;
            }
            break;
+
+       default:
+           if (TclIsSpaceProcM(*p)) {
+               /*
+                * Space: ignore if element is in braces or quotes;
+                * otherwise terminate element.
+                */
+               if ((openBraces == 0) && !inQuotes) {
+                   size = (p - elemStart);
+                   goto done;
+               }
+           }
+           break;
+
        }
        p++;
     }
@@ -756,7 +753,7 @@ FindElement(
     }
 
   done:
-    while ((p < limit) && (TclIsSpaceProc(*p))) {
+    while ((p < limit) && (TclIsSpaceProcM(*p))) {
        p++;
     }
     *elementPtr = elemStart;
@@ -872,7 +869,7 @@ Tcl_SplitList(
 
     size = TclMaxListLength(list, -1, &end) + 1;
     length = end - list;
-    argv = ckalloc((size * sizeof(char *)) + length + 1);
+    argv = (const char **)ckalloc((size * sizeof(char *)) + length + 1);
 
     for (i = 0, p = ((char *) argv) + size*sizeof(char *);
            *list != 0;  i++) {
@@ -1112,12 +1109,6 @@ TclScanElement(
        case '[':       /* TYPE_SUBS */
        case '$':       /* TYPE_SUBS */
        case ';':       /* TYPE_COMMAND_END */
-       case ' ':       /* TYPE_SPACE */
-       case '\f':      /* TYPE_SPACE */
-       case '\n':      /* TYPE_COMMAND_END */
-       case '\r':      /* TYPE_SPACE */
-       case '\t':      /* TYPE_SPACE */
-       case '\v':      /* TYPE_SPACE */
            forbidNone = 1;
            extra++;            /* Escape sequences all one byte longer. */
 #if COMPAT
@@ -1162,6 +1153,15 @@ TclScanElement(
            }
            /* TODO: Panic on improper encoding? */
            break;
+       default:
+           if (TclIsSpaceProcM(*p)) {
+               forbidNone = 1;
+               extra++;        /* Escape sequences all one byte longer. */
+#if COMPAT
+               preferBrace = 1;
+#endif
+           }
+           break;
        }
       }
        length -= (length > 0);
@@ -1577,7 +1577,7 @@ Tcl_Merge(
      */
 
     if (argc == 0) {
-       result = ckalloc(1);
+       result = (char *)ckalloc(1);
        result[0] = '\0';
        return result;
     }
@@ -1589,7 +1589,7 @@ Tcl_Merge(
     if (argc <= LOCAL_SIZE) {
        flagPtr = localFlags;
     } else {
-       flagPtr = ckalloc(argc);
+       flagPtr = (char *)ckalloc(argc);
     }
     for (i = 0; i < argc; i++) {
        flagPtr[i] = ( i ? TCL_DONT_QUOTE_HASH : 0 );
@@ -1607,7 +1607,7 @@ Tcl_Merge(
      * Pass two: copy into the result area.
      */
 
-    result = ckalloc(bytesNeeded);
+    result = (char *)ckalloc(bytesNeeded);
     dst = result;
     for (i = 0; i < argc; i++) {
        flagPtr[i] |= ( i ? TCL_DONT_QUOTE_HASH : 0 );
@@ -1649,7 +1649,7 @@ Tcl_Backslash(
     int *readPtr)              /* Fill in with number of characters read from
                                 * src, unless NULL. */
 {
-    char buf[TCL_UTF_MAX] = "";
+    char buf[4] = "";
     Tcl_UniChar ch = 0;
 
     Tcl_UtfBackslash(src, readPtr, buf);
@@ -1660,42 +1660,6 @@ Tcl_Backslash(
 /*
  *----------------------------------------------------------------------
  *
- * UtfWellFormedEnd --
- *     Checks the end of utf string is malformed, if yes - wraps bytes
- *     to the given buffer (as well-formed NTS string).  The buffer
- *     argument should be initialized by the caller and ready to use.
- *
- * Results:
- *     The bytes with well-formed end of the string.
- *
- * Side effects:
- *     Buffer (DString) may be allocated, so must be released.
- *
- *----------------------------------------------------------------------
- */
-
-static inline const char*
-UtfWellFormedEnd(
-    Tcl_DString *buffer,       /* Buffer used to hold well-formed string. */
-    const char *bytes,         /* Pointer to the beginning of the string. */
-    int length)                        /* Length of the string. */
-{
-    const char *l = bytes + length;
-    const char *p = Tcl_UtfPrev(l, bytes);
-
-    if (Tcl_UtfCharComplete(p, l - p)) {
-       return bytes;
-    }
-    /*
-     * Malformed utf-8 end, be sure we've NTS to safe compare of end-character,
-     * avoid segfault by access violation out of range.
-     */
-    Tcl_DStringAppend(buffer, bytes, length);
-    return Tcl_DStringValue(buffer);
-}
-/*
- *----------------------------------------------------------------------
- *
  * TclTrimRight --
  *     Takes two counted strings in the Tcl encoding.  Conceptually
  *     finds the sub string (offset) to trim from the right side of the
@@ -1710,16 +1674,24 @@ UtfWellFormedEnd(
  *----------------------------------------------------------------------
  */
 
-static inline int
-TrimRight(
-    const char *bytes,         /* String to be trimmed... */
-    int numBytes,              /* ...and its length in bytes */
-    const char *trim,          /* String of trim characters... */
-    int numTrim)               /* ...and its length in bytes */
+int
+TclTrimRight(
+    const char *bytes, /* String to be trimmed... */
+    int numBytes,      /* ...and its length in bytes */
+                       /* Calls to TclUtfToUniChar() in this routine
+                        * rely on (bytes[numBytes] == '\0'). */
+    const char *trim,  /* String of trim characters... */
+    int numTrim)       /* ...and its length in bytes */
+                       /* Calls to TclUtfToUniChar() in this routine
+                        * rely on (trim[numTrim] == '\0'). */
 {
-    const char *p = bytes + numBytes;
-    int pInc;
-    Tcl_UniChar ch1 = 0, ch2 = 0;
+    const char *pp, *p = bytes + numBytes;
+    Tcl_UniChar ch1 = 0;
+
+    /* Empty strings -> nothing to do */
+    if ((numBytes == 0) || (numTrim == 0)) {
+       return 0;
+    }
 
     /*
      * Outer loop: iterate over string to be trimmed.
@@ -1727,10 +1699,14 @@ TrimRight(
 
     do {
        const char *q = trim;
-       int bytesLeft = numTrim;
+       int pInc = 0, bytesLeft = numTrim;
+       Tcl_UniChar ch2 = 0;
 
-       p = Tcl_UtfPrev(p, bytes);
-       pInc = TclUtfToUniChar(p, &ch1);
+       pp = TclUtfPrev(p, bytes);
+       do {
+           pp += pInc;
+           pInc = TclUtfToUniChar(pp, &ch1);
+       } while (pp + pInc < p);
 
        /*
         * Inner loop: scan trim string for match to current character.
@@ -1752,44 +1728,13 @@ TrimRight(
             * No match; trim task done; *p is last non-trimmed char.
             */
 
-           p += pInc;
            break;
        }
+       p = pp;
     } while (p > bytes);
 
     return numBytes - (p - bytes);
 }
-
-int
-TclTrimRight(
-    const char *bytes, /* String to be trimmed... */
-    int numBytes,      /* ...and its length in bytes */
-    const char *trim,  /* String of trim characters... */
-    int numTrim)       /* ...and its length in bytes */
-{
-    int res;
-    Tcl_DString bytesBuf, trimBuf;
-
-    /* Empty strings -> nothing to do */
-    if ((numBytes == 0) || (numTrim == 0)) {
-       return 0;
-    }
-
-    Tcl_DStringInit(&bytesBuf);
-    Tcl_DStringInit(&trimBuf);
-    bytes = UtfWellFormedEnd(&bytesBuf, bytes, numBytes);
-    trim = UtfWellFormedEnd(&trimBuf, trim, numTrim);
-
-    res = TrimRight(bytes, numBytes, trim, numTrim);
-    if (res > numBytes) {
-       res = numBytes;
-    }
-
-    Tcl_DStringFree(&bytesBuf);
-    Tcl_DStringFree(&trimBuf);
-
-    return res;
-}
 \f
 /*
  *----------------------------------------------------------------------
@@ -1809,21 +1754,31 @@ TclTrimRight(
  *----------------------------------------------------------------------
  */
 
-static inline int
-TrimLeft(
-    const char *bytes,         /* String to be trimmed... */
-    int numBytes,              /* ...and its length in bytes */
-    const char *trim,          /* String of trim characters... */
-    int numTrim)               /* ...and its length in bytes */
+int
+TclTrimLeft(
+    const char *bytes, /* String to be trimmed... */
+    int numBytes,      /* ...and its length in bytes */
+                       /* Calls to TclUtfToUniChar() in this routine
+                        * rely on (bytes[numBytes] == '\0'). */
+    const char *trim,  /* String of trim characters... */
+    int numTrim)       /* ...and its length in bytes */
+                       /* Calls to TclUtfToUniChar() in this routine
+                        * rely on (trim[numTrim] == '\0'). */
 {
     const char *p = bytes;
-       Tcl_UniChar ch1 = 0, ch2 = 0;
+    Tcl_UniChar ch1 = 0;
+
+    /* Empty strings -> nothing to do */
+    if ((numBytes == 0) || (numTrim == 0)) {
+       return 0;
+    }
 
     /*
      * Outer loop: iterate over string to be trimmed.
      */
 
     do {
+       Tcl_UniChar ch2 = 0;
        int pInc = TclUtfToUniChar(p, &ch1);
        const char *q = trim;
        int bytesLeft = numTrim;
@@ -1857,37 +1812,6 @@ TrimLeft(
 
     return p - bytes;
 }
-
-int
-TclTrimLeft(
-    const char *bytes, /* String to be trimmed... */
-    int numBytes,      /* ...and its length in bytes */
-    const char *trim,  /* String of trim characters... */
-    int numTrim)       /* ...and its length in bytes */
-{
-    int res;
-    Tcl_DString bytesBuf, trimBuf;
-
-    /* Empty strings -> nothing to do */
-    if ((numBytes == 0) || (numTrim == 0)) {
-       return 0;
-    }
-
-    Tcl_DStringInit(&bytesBuf);
-    Tcl_DStringInit(&trimBuf);
-    bytes = UtfWellFormedEnd(&bytesBuf, bytes, numBytes);
-    trim = UtfWellFormedEnd(&trimBuf, trim, numTrim);
-
-    res = TrimLeft(bytes, numBytes, trim, numTrim);
-    if (res > numBytes) {
-       res = numBytes;
-    }
-
-    Tcl_DStringFree(&bytesBuf);
-    Tcl_DStringFree(&trimBuf);
-
-    return res;
-}
 \f
 /*
  *----------------------------------------------------------------------
@@ -1909,41 +1833,39 @@ int
 TclTrim(
     const char *bytes, /* String to be trimmed... */
     int numBytes,      /* ...and its length in bytes */
+                       /* Calls in this routine
+                        * rely on (bytes[numBytes] == '\0'). */
     const char *trim,  /* String of trim characters... */
     int numTrim,       /* ...and its length in bytes */
-    int *trimRight)            /* Offset from the end of the string. */
+                       /* Calls in this routine
+                        * rely on (trim[numTrim] == '\0'). */
+    int *trimRightPtr) /* Offset from the end of the string. */
 {
-    int trimLeft;
-    Tcl_DString bytesBuf, trimBuf;
+    int trimLeft = 0, trimRight = 0;
 
-    *trimRight = 0;
     /* Empty strings -> nothing to do */
-    if ((numBytes == 0) || (numTrim == 0)) {
-       return 0;
-    }
-
-    Tcl_DStringInit(&bytesBuf);
-    Tcl_DStringInit(&trimBuf);
-    bytes = UtfWellFormedEnd(&bytesBuf, bytes, numBytes);
-    trim = UtfWellFormedEnd(&trimBuf, trim, numTrim);
-
-    trimLeft = TrimLeft(bytes, numBytes, trim, numTrim);
-    if (trimLeft > numBytes) {
-       trimLeft = numBytes;
-    }
-    numBytes -= trimLeft;
-    /* have to trim yet (first char was already verified within TrimLeft) */
-    if (numBytes > 1) {
-       bytes += trimLeft;
-       *trimRight = TrimRight(bytes, numBytes, trim, numTrim);
-       if (*trimRight > numBytes) {
-           *trimRight = numBytes;
+    if ((numBytes > 0) && (numTrim > 0)) {
+
+       /* When bytes is NUL-terminated, returns 0 <= trimLeft <= numBytes */
+       trimLeft = TclTrimLeft(bytes, numBytes, trim, numTrim);
+       numBytes -= trimLeft;
+
+       /* If we did not trim the whole string, it starts with a character
+        * that we will not trim. Skip over it. */
+       if (numBytes > 0) {
+           int ch;
+           const char *first = bytes + trimLeft;
+           bytes += TclUtfToUCS4(first, &ch);
+           numBytes -= (bytes - first);
+
+           if (numBytes > 0) {
+               /* When bytes is NUL-terminated, returns
+                * 0 <= trimRight <= numBytes */
+               trimRight = TclTrimRight(bytes, numBytes, trim, numTrim);
+           }
        }
     }
-
-    Tcl_DStringFree(&bytesBuf);
-    Tcl_DStringFree(&trimBuf);
-
+    *trimRightPtr = trimRight;
     return trimLeft;
 }
 \f
@@ -2010,7 +1932,7 @@ Tcl_Concat(
      * All element bytes + (argc - 1) spaces + 1 terminating NULL.
      */
 
-    result = ckalloc(bytesNeeded + argc);
+    result = (char *)ckalloc(bytesNeeded + argc);
 
     for (p = result, i = 0;  i < argc;  i++) {
        int triml, trimr, elemLength;
@@ -2114,7 +2036,7 @@ Tcl_ConcatObj(
            }
        }
        if (!resPtr) {
-           resPtr = Tcl_NewObj();
+           TclNewObj(resPtr);
        }
        return resPtr;
     }
@@ -2234,8 +2156,7 @@ Tcl_StringCaseMatch(
     int nocase)                        /* 0 for case sensitive, 1 for insensitive */
 {
     int p, charLen;
-    const char *pstart = pattern;
-    Tcl_UniChar ch1 = 0, ch2 = 0;
+    int ch1 = 0, ch2 = 0;
 
     while (1) {
        p = *pattern;
@@ -2276,12 +2197,12 @@ Tcl_StringCaseMatch(
             */
 
            if (UCHAR(*pattern) < 0x80) {
-               ch2 = (Tcl_UniChar)
+               ch2 = (int)
                        (nocase ? tolower(UCHAR(*pattern)) : UCHAR(*pattern));
            } else {
-               Tcl_UtfToUniChar(pattern, &ch2);
+               TclUtfToUCS4(pattern, &ch2);
                if (nocase) {
-                   ch2 = Tcl_UniCharToLower(ch2);
+                   ch2 = TclUCS4ToLower(ch2);
                }
            }
 
@@ -2295,8 +2216,8 @@ Tcl_StringCaseMatch(
                if ((p != '[') && (p != '?') && (p != '\\')) {
                    if (nocase) {
                        while (*str) {
-                           charLen = TclUtfToUniChar(str, &ch1);
-                           if (ch2==ch1 || ch2==Tcl_UniCharToLower(ch1)) {
+                           charLen = TclUtfToUCS4(str, &ch1);
+                           if (ch2==ch1 || ch2==TclUCS4ToLower(ch1)) {
                                break;
                            }
                            str += charLen;
@@ -2309,7 +2230,7 @@ Tcl_StringCaseMatch(
                         */
 
                        while (*str) {
-                           charLen = TclUtfToUniChar(str, &ch1);
+                           charLen = TclUtfToUCS4(str, &ch1);
                            if (ch2 == ch1) {
                                break;
                            }
@@ -2323,7 +2244,7 @@ Tcl_StringCaseMatch(
                if (*str == '\0') {
                    return 0;
                }
-               str += TclUtfToUniChar(str, &ch1);
+               str += TclUtfToUCS4(str, &ch1);
            }
        }
 
@@ -2334,7 +2255,7 @@ Tcl_StringCaseMatch(
 
        if (p == '?') {
            pattern++;
-           str += TclUtfToUniChar(str, &ch1);
+           str += TclUtfToUCS4(str, &ch1);
            continue;
        }
 
@@ -2345,17 +2266,17 @@ Tcl_StringCaseMatch(
         */
 
        if (p == '[') {
-           Tcl_UniChar startChar = 0, endChar = 0;
+           int startChar = 0, endChar = 0;
 
            pattern++;
            if (UCHAR(*str) < 0x80) {
-               ch1 = (Tcl_UniChar)
+               ch1 = (int)
                        (nocase ? tolower(UCHAR(*str)) : UCHAR(*str));
                str++;
            } else {
-               str += Tcl_UtfToUniChar(str, &ch1);
+               str += TclUtfToUCS4(str, &ch1);
                if (nocase) {
-                   ch1 = Tcl_UniCharToLower(ch1);
+                   ch1 = TclUCS4ToLower(ch1);
                }
            }
            while (1) {
@@ -2363,13 +2284,13 @@ Tcl_StringCaseMatch(
                    return 0;
                }
                if (UCHAR(*pattern) < 0x80) {
-                   startChar = (Tcl_UniChar) (nocase
+                   startChar = (int) (nocase
                            ? tolower(UCHAR(*pattern)) : UCHAR(*pattern));
                    pattern++;
                } else {
-                   pattern += Tcl_UtfToUniChar(pattern, &startChar);
+                   pattern += TclUtfToUCS4(pattern, &startChar);
                    if (nocase) {
-                       startChar = Tcl_UniCharToLower(startChar);
+                       startChar = TclUCS4ToLower(startChar);
                    }
                }
                if (*pattern == '-') {
@@ -2378,13 +2299,13 @@ Tcl_StringCaseMatch(
                        return 0;
                    }
                    if (UCHAR(*pattern) < 0x80) {
-                       endChar = (Tcl_UniChar) (nocase
+                       endChar = (int) (nocase
                                ? tolower(UCHAR(*pattern)) : UCHAR(*pattern));
                        pattern++;
                    } else {
-                       pattern += Tcl_UtfToUniChar(pattern, &endChar);
+                       pattern += TclUtfToUCS4(pattern, &endChar);
                        if (nocase) {
-                           endChar = Tcl_UniCharToLower(endChar);
+                           endChar = TclUCS4ToLower(endChar);
                        }
                    }
                    if (((startChar <= ch1) && (ch1 <= endChar))
@@ -2399,10 +2320,13 @@ Tcl_StringCaseMatch(
                    break;
                }
            }
+           /* If we reach here, we matched. Need to move past closing ] */
            while (*pattern != ']') {
                if (*pattern == '\0') {
-                   pattern = Tcl_UtfPrev(pattern, pstart);
-                   break;
+                   /* We ran out of pattern after matching something in
+                    * (unclosed!) brackets. So long as we ran out of string
+                    * at the same time, we have a match. Otherwise, not. */
+                   return (*str == '\0');
                }
                pattern++;
            }
@@ -2427,10 +2351,10 @@ Tcl_StringCaseMatch(
         * each string match.
         */
 
-       str += TclUtfToUniChar(str, &ch1);
-       pattern += TclUtfToUniChar(pattern, &ch2);
+       str += TclUtfToUCS4(str, &ch1);
+       pattern += TclUtfToUCS4(pattern, &ch2);
        if (nocase) {
-           if (Tcl_UniCharToLower(ch1) != Tcl_UniCharToLower(ch2)) {
+           if (TclUCS4ToLower(ch1) != TclUCS4ToLower(ch2)) {
                return 0;
            }
        } else if (ch1 != ch2) {
@@ -2743,7 +2667,7 @@ Tcl_DStringAppend(
     if (newSize >= dsPtr->spaceAvl) {
        dsPtr->spaceAvl = newSize * 2;
        if (dsPtr->string == dsPtr->staticSpace) {
-           char *newString = ckalloc(dsPtr->spaceAvl);
+           char *newString = (char *)ckalloc(dsPtr->spaceAvl);
 
            memcpy(newString, dsPtr->string, dsPtr->length);
            dsPtr->string = newString;
@@ -2756,7 +2680,7 @@ Tcl_DStringAppend(
                offset = bytes - dsPtr->string;
            }
 
-           dsPtr->string = ckrealloc(dsPtr->string, dsPtr->spaceAvl);
+           dsPtr->string = (char *)ckrealloc(dsPtr->string, dsPtr->spaceAvl);
 
            if (offset >= 0) {
                bytes = dsPtr->string + offset;
@@ -2831,9 +2755,37 @@ Tcl_DStringAppendElement(
 {
     char *dst = dsPtr->string + dsPtr->length;
     int needSpace = TclNeedSpace(dsPtr->string, dst);
-    char flags = needSpace ? TCL_DONT_QUOTE_HASH : 0;
-    int newSize = dsPtr->length + needSpace
-           + TclScanElement(element, -1, &flags);
+    char flags = 0;
+    int quoteHash = 1, newSize;
+
+    if (needSpace) {
+       /*
+        * If we need a space to separate the new element from something
+        * already ending the string, we're not appending the first element
+        * of any list, so we need not quote any leading hash character.
+        */
+       quoteHash = 0;
+    } else {
+       /*
+        * We don't need a space, maybe because there's some already there.
+        * Checking whether we might be appending a first element is a bit
+        * more involved.
+        *
+        * Backtrack over all whitespace.
+        */
+       while ((--dst >= dsPtr->string) && TclIsSpaceProcM(*dst)) {
+       }
+
+       /* Call again without whitespace to confound things. */
+       quoteHash = !TclNeedSpace(dsPtr->string, dst+1);
+    }
+    if (!quoteHash) {
+       flags |= TCL_DONT_QUOTE_HASH;
+    }
+    newSize = dsPtr->length + needSpace + TclScanElement(element, -1, &flags);
+    if (!quoteHash) {
+       flags |= TCL_DONT_QUOTE_HASH;
+    }
 
     /*
      * Allocate a larger buffer for the string if the current one isn't large
@@ -2846,7 +2798,7 @@ Tcl_DStringAppendElement(
     if (newSize >= dsPtr->spaceAvl) {
        dsPtr->spaceAvl = newSize * 2;
        if (dsPtr->string == dsPtr->staticSpace) {
-           char *newString = ckalloc(dsPtr->spaceAvl);
+           char *newString = (char *)ckalloc(dsPtr->spaceAvl);
 
            memcpy(newString, dsPtr->string, dsPtr->length);
            dsPtr->string = newString;
@@ -2859,14 +2811,14 @@ Tcl_DStringAppendElement(
                offset = element - dsPtr->string;
            }
 
-           dsPtr->string = ckrealloc(dsPtr->string, dsPtr->spaceAvl);
+           dsPtr->string = (char *)ckrealloc(dsPtr->string, dsPtr->spaceAvl);
 
            if (offset >= 0) {
                element = dsPtr->string + offset;
            }
        }
-       dst = dsPtr->string + dsPtr->length;
     }
+    dst = dsPtr->string + dsPtr->length;
 
     /*
      * Convert the new string to a list element and copy it into the buffer at
@@ -2877,15 +2829,8 @@ Tcl_DStringAppendElement(
        *dst = ' ';
        dst++;
        dsPtr->length++;
-
-       /*
-        * If we need a space to separate this element from preceding stuff,
-        * then this element will not lead a list, and need not have it's
-        * leading '#' quoted.
-        */
-
-       flags |= TCL_DONT_QUOTE_HASH;
     }
+
     dsPtr->length += TclConvertElement(element, -1, dst, flags);
     dsPtr->string[dsPtr->length] = '\0';
     return dsPtr->string;
@@ -2940,12 +2885,12 @@ Tcl_DStringSetLength(
            dsPtr->spaceAvl = length + 1;
        }
        if (dsPtr->string == dsPtr->staticSpace) {
-           char *newString = ckalloc(dsPtr->spaceAvl);
+           char *newString = (char *)ckalloc(dsPtr->spaceAvl);
 
            memcpy(newString, dsPtr->string, dsPtr->length);
            dsPtr->string = newString;
        } else {
-           dsPtr->string = ckrealloc(dsPtr->string, dsPtr->spaceAvl);
+           dsPtr->string = (char *)ckrealloc(dsPtr->string, dsPtr->spaceAvl);
        }
     }
     dsPtr->length = length;
@@ -3090,7 +3035,7 @@ Tcl_DStringGetResult(
            dsPtr->string = iPtr->result;
            dsPtr->spaceAvl = dsPtr->length+1;
        } else {
-           dsPtr->string = ckalloc(dsPtr->length+1);
+           dsPtr->string = (char *)ckalloc(dsPtr->length+1);
            memcpy(dsPtr->string, iPtr->result, dsPtr->length+1);
            iPtr->freeProc(iPtr->result);
        }
@@ -3101,7 +3046,7 @@ Tcl_DStringGetResult(
            dsPtr->string = dsPtr->staticSpace;
            dsPtr->spaceAvl = TCL_DSTRING_STATIC_SIZE;
        } else {
-           dsPtr->string = ckalloc(dsPtr->length+1);
+           dsPtr->string = (char *)ckalloc(dsPtr->length+1);
            dsPtr->spaceAvl = dsPtr->length + 1;
        }
        memcpy(dsPtr->string, iPtr->result, dsPtr->length+1);
@@ -3259,7 +3204,7 @@ Tcl_PrintDouble(
     int signum;
     char *digits;
     char *end;
-    int *precisionPtr = Tcl_GetThreadData(&precisionKey, sizeof(int));
+    int *precisionPtr = (int *)Tcl_GetThreadData(&precisionKey, sizeof(int));
 
     /*
      * Handle NaN.
@@ -3421,7 +3366,6 @@ Tcl_PrintDouble(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 char *
 TclPrecTraceProc(
     ClientData clientData,     /* Not used. */
@@ -3432,7 +3376,7 @@ TclPrecTraceProc(
 {
     Tcl_Obj *value;
     int prec;
-    int *precisionPtr = Tcl_GetThreadData(&precisionKey, (int) sizeof(int));
+    int *precisionPtr = (int *)Tcl_GetThreadData(&precisionKey, sizeof(int));
 
     /*
      * If the variable is unset, then recreate the trace.
@@ -3505,63 +3449,69 @@ TclNeedSpace(
     /*
      * A space is needed unless either:
      * (a) we're at the start of the string, or
-     */
+     *
+     * (NOTE: This check is now absorbed into the loop below.)
+     *
 
     if (end == start) {
        return 0;
     }
 
+     *
+     */
+
     /*
      * (b) we're at the start of a nested list-element, quoted with an open
      *    curly brace; we can be nested arbitrarily deep, so long as the
      *    first curly brace starts an element, so backtrack over open curly
      *    braces that are trailing characters of the string; and
-     */
+     *
+     *  (NOTE: Every character our parser is looking for is a proper
+     *  single-byte encoding of an ASCII value. It does not accept
+     *  overlong encodings.  Given that, there's no benefit using
+     *  Tcl_UtfPrev. If it would find what we seek, so would byte-by-byte
+     *  backward scan. Save routine call overhead and risk of wrong
+     *  results should the behavior of Tcl_UtfPrev change in unexpected ways.
+     * Reconsider this if we ever start treating non-ASCII Unicode
+     * characters as meaningful list syntax, expanded Unicode spaces as
+     * element separators, for example.)
+     *
 
     end = Tcl_UtfPrev(end, start);
     while (*end == '{') {
-       if (end == start) {
-           return 0;
-       }
-       end = Tcl_UtfPrev(end, start);
+        if (end == start) {
+            return 0;
+        }
+        end = Tcl_UtfPrev(end, start);
+    }
+
+     *
+     */
+
+    while ((--end >= start) && (*end == '{')) {
+    }
+    if (end < start) {
+        return 0;
     }
 
     /*
      * (c) the trailing character of the string is already a list-element
-     *    separator (according to TclFindElement); that is, one of these
-     *    characters:
-     *         \u0009  \t      TAB
-     *         \u000A  \n      NEWLINE
-     *         \u000B  \v      VERTICAL TAB
-     *         \u000C  \f      FORM FEED
-     *         \u000D  \r      CARRIAGE RETURN
-     *         \u0020          SPACE
-     *    with the condition that the penultimate character is not a
-     *    backslash.
+     *    separator, Use the same testing routine as TclFindElement to
+     *    enforce consistency.
      */
 
-    if (*end > 0x20) {
+    if (TclIsSpaceProcM(*end)) {
+       int result = 0;
+
        /*
-        * Performance tweak. All ASCII spaces are <= 0x20. So get a quick
-        * answer for most characters before comparing against all spaces in
-        * the switch below.
-        *
-        * NOTE: Remove this if other Unicode spaces ever get accepted as
-        * list-element separators.
+        * Trailing whitespace might be part of a backslash escape
+        * sequence. Handle that possibility.
         */
 
-       return 1;
-    }
-    switch (*end) {
-    case ' ':
-    case '\t':
-    case '\n':
-    case '\r':
-    case '\v':
-    case '\f':
-       if ((end == start) || (end[-1] != '\\')) {
-           return 0;
+       while ((--end >= start) && (*end == '\\')) {
+           result = !result;
        }
+       return result;
     }
     return 1;
 }
@@ -3597,49 +3547,25 @@ TclFormatInt(
                                 * formatted characters are written. */
     long n)                    /* The integer to format. */
 {
-    long intVal;
-    int i;
+    unsigned long intVal;
+    int i = 0;
     int numFormatted, j;
-    const char *digits = "0123456789";
-
-    /*
-     * Check first whether "n" is zero.
-     */
-
-    if (n == 0) {
-       buffer[0] = '0';
-       buffer[1] = 0;
-       return 1;
-    }
-
-    /*
-     * Check whether "n" is the maximum negative value. This is -2^(m-1) for
-     * an m-bit word, and has no positive equivalent; negating it produces the
-     * same value.
-     */
-
-    intVal = -n;                       /* [Bug 3390638] Workaround for*/
-    if (n == -n || intVal == n) {      /* broken compiler optimizers. */
-       return sprintf(buffer, "%ld", n);
-    }
+    static const char digits[] = "0123456789";
 
     /*
      * Generate the characters of the result backwards in the buffer.
      */
 
-    intVal = (n < 0? -n : n);
-    i = 0;
-    buffer[0] = '\0';
+    intVal = (n < 0 ? -(unsigned long)n : (unsigned long)n);
     do {
-       i++;
-       buffer[i] = digits[intVal % 10];
-       intVal = intVal/10;
+       buffer[i++] = digits[intVal % 10];
+       intVal = intVal / 10;
     } while (intVal > 0);
     if (n < 0) {
-       i++;
-       buffer[i] = '-';
+       buffer[i++] = '-';
     }
-    numFormatted = i;
+    buffer[i] = '\0';
+    numFormatted = i--;
 
     /*
      * Now reverse the characters.
@@ -3713,7 +3639,7 @@ TclGetIntForIndex(
      * Leading whitespace is acceptable in an index.
      */
 
-    while (length && TclIsSpaceProc(*bytes)) {
+    while (length && TclIsSpaceProcM(*bytes)) {
        bytes++;
        length--;
     }
@@ -3726,7 +3652,7 @@ TclGetIntForIndex(
        if ((savedOp != '+') && (savedOp != '-')) {
            goto parseError;
        }
-       if (TclIsSpaceProc(opPtr[1])) {
+       if (TclIsSpaceProcM(opPtr[1])) {
            goto parseError;
        }
        *opPtr = '\0';
@@ -3788,18 +3714,18 @@ TclGetIntForIndex(
 
 static void
 UpdateStringOfEndOffset(
-    register Tcl_Obj *objPtr)
+    Tcl_Obj *objPtr)
 {
     char buffer[TCL_INTEGER_SPACE + 5];
-    register int len = 3;
+    int len = 3;
 
     memcpy(buffer, "end", 4);
     if (objPtr->internalRep.longValue != 0) {
        buffer[len++] = '-';
        len += TclFormatInt(buffer+len, -(objPtr->internalRep.longValue));
     }
-    objPtr->bytes = ckalloc((unsigned) len+1);
-    memcpy(objPtr->bytes, buffer, (unsigned) len+1);
+    objPtr->bytes = (char *)ckalloc(len+1);
+    memcpy(objPtr->bytes, buffer, len+1);
     objPtr->length = len;
 }
 \f
@@ -3808,14 +3734,14 @@ UpdateStringOfEndOffset(
  *
  * GetEndOffsetFromObj --
  *
- *      Look for a string of the form "end[+-]offset" and convert it to an
- *      internal representation holding the offset.
+ *     Look for a string of the form "end[+-]offset" and convert it to an
+ *     internal representation holding the offset.
  *
  * Results:
- *      Tcl return code.
+ *     Tcl return code.
  *
  * Side effects:
- *      May store a Tcl_ObjType.
+ *     May store a Tcl_ObjType.
  *
  *----------------------------------------------------------------------
  */
@@ -3862,7 +3788,7 @@ SetEndOffsetFromAny(
     Tcl_Obj *objPtr)           /* Pointer to the object to parse */
 {
     int offset;                        /* Offset in the "end-offset" expression */
-    register const char *bytes;        /* String rep of the object */
+    const char *bytes; /* String rep of the object */
     int length;                        /* Length of the object's string rep */
 
     /*
@@ -3900,7 +3826,7 @@ SetEndOffsetFromAny(
         * after "end-" to Tcl_GetInt, then reverse for offset.
         */
 
-       if (TclIsSpaceProc(bytes[4])) {
+       if (TclIsSpaceProcM(bytes[4])) {
            goto badIndexFormat;
        }
        if (Tcl_GetInt(interp, bytes+4, &offset) != TCL_OK) {
@@ -3971,11 +3897,11 @@ SetEndOffsetFromAny(
  *      collection, and can be encoded as after.  The end-relative
  *      expressions that indicate an index less than or equal to end
  *      are encoded relative to the value TCL_INDEX_END (-2).  The
- *      index "end" is encoded as -2, down to the index "end-0x7ffffffe"
+ *      index "end" is encoded as -2, down to the index "end-0x7FFFFFFE"
  *      which is encoded as INT_MIN. Since the largest index into a
- *      string possible in Tcl 8 is 0x7ffffffe, the interpretation of
- *      "end-0x7ffffffe" for that largest string would be 0.  Thus,
- *      if the tokens "end-0x7fffffff" or "end+-0x80000000" are parsed,
+ *      string possible in Tcl 8 is 0x7FFFFFFE, the interpretation of
+ *      "end-0x7FFFFFFE" for that largest string would be 0.  Thus,
+ *      if the tokens "end-0x7FFFFFFF" or "end+-0x80000000" are parsed,
  *      they can be encoded with the before value.
  *
  *      These details will require re-examination whenever string and
@@ -4105,7 +4031,7 @@ TclCheckBadOctal(
      * zero. Try to generate a meaningful error message.
      */
 
-    while (TclIsSpaceProc(*p)) {
+    while (TclIsSpaceProcM(*p)) {
        p++;
     }
     if (*p == '+' || *p == '-') {
@@ -4118,7 +4044,7 @@ TclCheckBadOctal(
        while (isdigit(UCHAR(*p))) {    /* INTL: digit. */
            p++;
        }
-       while (TclIsSpaceProc(*p)) {
+       while (TclIsSpaceProcM(*p)) {
            p++;
        }
        if (*p == '\0') {
@@ -4160,7 +4086,7 @@ ClearHash(
 
     for (hPtr = Tcl_FirstHashEntry(tablePtr, &search); hPtr != NULL;
            hPtr = Tcl_NextHashEntry(&search)) {
-       Tcl_Obj *objPtr = Tcl_GetHashValue(hPtr);
+       Tcl_Obj *objPtr = (Tcl_Obj *)Tcl_GetHashValue(hPtr);
 
        Tcl_DecrRefCount(objPtr);
        Tcl_DeleteHashEntry(hPtr);
@@ -4190,10 +4116,10 @@ GetThreadHash(
     Tcl_ThreadDataKey *keyPtr)
 {
     Tcl_HashTable **tablePtrPtr =
-           Tcl_GetThreadData(keyPtr, sizeof(Tcl_HashTable *));
+           (Tcl_HashTable **)Tcl_GetThreadData(keyPtr, sizeof(Tcl_HashTable *));
 
     if (NULL == *tablePtrPtr) {
-       *tablePtrPtr = ckalloc(sizeof(Tcl_HashTable));
+       *tablePtrPtr = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
        Tcl_CreateThreadExitHandler(FreeThreadHash, *tablePtrPtr);
        Tcl_InitHashTable(*tablePtrPtr, TCL_ONE_WORD_KEYS);
     }
@@ -4218,7 +4144,7 @@ static void
 FreeThreadHash(
     ClientData clientData)
 {
-    Tcl_HashTable *tablePtr = clientData;
+    Tcl_HashTable *tablePtr = (Tcl_HashTable *)clientData;
 
     ClearHash(tablePtr);
     Tcl_DeleteHashTable(tablePtr);
@@ -4240,7 +4166,7 @@ static void
 FreeProcessGlobalValue(
     ClientData clientData)
 {
-    ProcessGlobalValue *pgvPtr = clientData;
+    ProcessGlobalValue *pgvPtr = (ProcessGlobalValue *)clientData;
 
     pgvPtr->epoch++;
     pgvPtr->numBytes = 0;
@@ -4288,7 +4214,7 @@ TclSetProcessGlobalValue(
        Tcl_CreateExitHandler(FreeProcessGlobalValue, pgvPtr);
     }
     bytes = Tcl_GetStringFromObj(newValue, &pgvPtr->numBytes);
-    pgvPtr->value = ckalloc(pgvPtr->numBytes + 1);
+    pgvPtr->value = (char *)ckalloc(pgvPtr->numBytes + 1);
     memcpy(pgvPtr->value, bytes, pgvPtr->numBytes + 1);
     if (pgvPtr->encoding) {
        Tcl_FreeEncoding(pgvPtr->encoding);
@@ -4337,8 +4263,8 @@ TclGetProcessGlobalValue(
 
        if (pgvPtr->encoding != current) {
            /*
-            * The system encoding has changed since the master string value
-            * was saved. Convert the master value to be based on the new
+            * The system encoding has changed since the global string value
+            * was saved. Convert the global value to be based on the new
             * system encoding.
             */
 
@@ -4352,7 +4278,7 @@ TclGetProcessGlobalValue(
            Tcl_DStringLength(&native), &newValue);
            Tcl_DStringFree(&native);
            ckfree(pgvPtr->value);
-           pgvPtr->value = ckalloc(Tcl_DStringLength(&newValue) + 1);
+           pgvPtr->value = (char *)ckalloc(Tcl_DStringLength(&newValue) + 1);
            memcpy(pgvPtr->value, Tcl_DStringValue(&newValue),
                    Tcl_DStringLength(&newValue) + 1);
            Tcl_DStringFree(&newValue);
@@ -4402,7 +4328,7 @@ TclGetProcessGlobalValue(
        Tcl_SetHashValue(hPtr, value);
        Tcl_IncrRefCount(value);
     }
-    return Tcl_GetHashValue(hPtr);
+    return (Tcl_Obj *)Tcl_GetHashValue(hPtr);
 }
 \f
 /*
index 7b3db7e..566e543 100644 (file)
@@ -123,17 +123,17 @@ VarHashNextVar(
  * access is denied.
  */
 
-static const char *noSuchVar =         "no such variable";
-static const char *isArray =           "variable is array";
-static const char *needArray =         "variable isn't array";
-static const char *noSuchElement =     "no such element in array";
-static const char *danglingElement =
+static const char NOSUCHVAR[] =                "no such variable";
+static const char ISARRAY[] =          "variable is array";
+static const char NEEDARRAY[] =                "variable isn't array";
+static const char NOSUCHELEMENT[] =    "no such element in array";
+static const char DANGLINGELEMENT[] =
        "upvar refers to element in deleted array";
-static const char *danglingVar =
+static const char DANGLINGVAR[] =
        "upvar refers to variable in deleted namespace";
-static const char *badNamespace =      "parent namespace doesn't exist";
-static const char *missingName =       "missing variable name";
-static const char *isArrayElement =
+static const char BADNAMESPACE[] =     "parent namespace doesn't exist";
+static const char MISSINGNAME[] =      "missing variable name";
+static const char ISARRAYELEMENT[] =
        "name refers to an element in an array";
 
 /*
@@ -489,7 +489,7 @@ TclLookupVar(
 Var *
 TclObjLookupVar(
     Tcl_Interp *interp,                /* Interpreter to use for lookup. */
-    register Tcl_Obj *part1Ptr,        /* If part2 isn't NULL, this is the name of an
+    Tcl_Obj *part1Ptr, /* If part2 isn't NULL, this is the name of an
                                 * array. Otherwise, this is a full variable
                                 * name that could include a parenthesized
                                 * array element. */
@@ -561,7 +561,7 @@ TclObjLookupVarEx(
                                 * is set to NULL. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Var *varPtr;      /* Points to the variable's in-frame Var
+    Var *varPtr;       /* Points to the variable's in-frame Var
                                 * structure. */
     const char *part1;
     int index, len1, len2;
@@ -613,7 +613,7 @@ TclObjLookupVarEx(
 
                if (flags & TCL_LEAVE_ERR_MSG) {
                    TclObjVarErrMsg(interp, part1Ptr, part2Ptr, msg,
-                           noSuchVar, -1);
+                           NOSUCHVAR, -1);
                    Tcl_SetErrorCode(interp, "TCL", "VALUE", "VARNAME", NULL);
                }
                return NULL;
@@ -640,7 +640,7 @@ TclObjLookupVarEx(
         * part1Ptr is possibly an unparsed array element.
         */
 
-       register int i;
+       int i;
 
        len2 = -1;
        for (i = 0; i < len1; i++) {
@@ -648,7 +648,7 @@ TclObjLookupVarEx(
                if (part2Ptr != NULL) {
                    if (flags & TCL_LEAVE_ERR_MSG) {
                        TclObjVarErrMsg(interp, part1Ptr, part2Ptr, msg,
-                               needArray, -1);
+                               NEEDARRAY, -1);
                        Tcl_SetErrorCode(interp, "TCL", "VALUE", "VARNAME",
                                NULL);
                    }
@@ -665,7 +665,7 @@ TclObjLookupVarEx(
                len1 = i;
 
                newPart2 = ckalloc(len2 + 1);
-               memcpy(newPart2, part2, (unsigned) len2);
+               memcpy(newPart2, part2, len2);
                *(newPart2+len2) = '\0';
                part2 = newPart2;
                part2Ptr = Tcl_NewStringObj(newPart2, -1);
@@ -942,10 +942,10 @@ TclLookupSimpleVar(
                TclGetNamespaceForQualName(interp, varName, cxtNsPtr,
                        flags, &varNsPtr, &dummy1Ptr, &dummy2Ptr, &tail);
                if (varNsPtr == NULL) {
-                   *errMsgPtr = badNamespace;
+                   *errMsgPtr = BADNAMESPACE;
                    return NULL;
                } else if (tail == NULL) {
-                   *errMsgPtr = missingName;
+                   *errMsgPtr = MISSINGNAME;
                    return NULL;
                }
                if (tail != varName) {
@@ -967,7 +967,7 @@ TclLookupSimpleVar(
                    *indexPtr = -2;
                }
            } else {            /* Var wasn't found and not to create it. */
-               *errMsgPtr = noSuchVar;
+               *errMsgPtr = NOSUCHVAR;
                return NULL;
            }
        }
@@ -980,7 +980,7 @@ TclLookupSimpleVar(
            int localLen;
 
            for (i=0 ; i<localCt ; i++, objPtrPtr++) {
-               register Tcl_Obj *objPtr = *objPtrPtr;
+               Tcl_Obj *objPtr = *objPtrPtr;
 
                if (objPtr) {
                    localNameStr = TclGetStringFromObj(objPtr, &localLen);
@@ -1007,7 +1007,7 @@ TclLookupSimpleVar(
                varPtr = VarHashFindVar(tablePtr, varNamePtr);
            }
            if (varPtr == NULL) {
-               *errMsgPtr = noSuchVar;
+               *errMsgPtr = NOSUCHVAR;
            }
        }
     }
@@ -1087,7 +1087,7 @@ TclLookupArrayElement(
        if (!createArray) {
            if (flags & TCL_LEAVE_ERR_MSG) {
                TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
-                       noSuchVar, index);
+                       NOSUCHVAR, index);
                Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
                        arrayNamePtr?TclGetString(arrayNamePtr):NULL, NULL);
            }
@@ -1102,7 +1102,7 @@ TclLookupArrayElement(
        if (TclIsVarDeadHash(arrayPtr)) {
            if (flags & TCL_LEAVE_ERR_MSG) {
                TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
-                       danglingVar, index);
+                       DANGLINGVAR, index);
                Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
                        arrayNamePtr?TclGetString(arrayNamePtr):NULL, NULL);
            }
@@ -1121,7 +1121,7 @@ TclLookupArrayElement(
        TclInitVarHashTable(arrayPtr->value.tablePtr, nsPtr);
     } else if (!TclIsVarArray(arrayPtr)) {
        if (flags & TCL_LEAVE_ERR_MSG) {
-           TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg, needArray,
+           TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg, NEEDARRAY,
                    index);
            Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
                    arrayNamePtr?TclGetString(arrayNamePtr):NULL, NULL);
@@ -1143,7 +1143,7 @@ TclLookupArrayElement(
        if (varPtr == NULL) {
            if (flags & TCL_LEAVE_ERR_MSG) {
                TclObjVarErrMsg(interp, arrayNamePtr, elNamePtr, msg,
-                       noSuchElement, index);
+                       NOSUCHELEMENT, index);
                Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ELEMENT",
                        TclGetString(elNamePtr), NULL);
            }
@@ -1330,10 +1330,10 @@ Tcl_Obj *
 Tcl_ObjGetVar2(
     Tcl_Interp *interp,                /* Command interpreter in which variable is to
                                 * be looked up. */
-    register Tcl_Obj *part1Ptr,        /* Points to an object holding the name of an
+    Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
                                 * array (if part2 is non-NULL) or the name of
                                 * a variable. */
-    register Tcl_Obj *part2Ptr,        /* If non-null, points to an object holding
+    Tcl_Obj *part2Ptr, /* If non-null, points to an object holding
                                 * the name of an element in the array
                                 * part1Ptr. */
     int flags)                 /* OR-ed combination of TCL_GLOBAL_ONLY and
@@ -1428,7 +1428,7 @@ Tcl_Obj *
 TclPtrGetVarIdx(
     Tcl_Interp *interp,                /* Command interpreter in which variable is to
                                 * be looked up. */
-    register Var *varPtr,      /* The variable to be read.*/
+    Var *varPtr,       /* The variable to be read.*/
     Var *arrayPtr,             /* NULL for scalar variables, pointer to the
                                 * containing array otherwise. */
     Tcl_Obj *part1Ptr,         /* Name of an array (if part2 is non-NULL) or
@@ -1469,11 +1469,11 @@ TclPtrGetVarIdx(
     if (flags & TCL_LEAVE_ERR_MSG) {
        if (TclIsVarUndefined(varPtr) && arrayPtr
                && !TclIsVarUndefined(arrayPtr)) {
-           msg = noSuchElement;
+           msg = NOSUCHELEMENT;
        } else if (TclIsVarArray(varPtr)) {
-           msg = isArray;
+           msg = ISARRAY;
        } else {
-           msg = noSuchVar;
+           msg = NOSUCHVAR;
        }
        TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "read", msg, index);
     }
@@ -1512,7 +1512,7 @@ TclPtrGetVarIdx(
 int
 Tcl_SetObjCmd(
     ClientData dummy,          /* Not used. */
-    register Tcl_Interp *interp,/* Current interpreter. */
+    Tcl_Interp *interp,/* Current interpreter. */
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
@@ -1738,10 +1738,10 @@ Tcl_Obj *
 Tcl_ObjSetVar2(
     Tcl_Interp *interp,                /* Command interpreter in which variable is to
                                 * be found. */
-    register Tcl_Obj *part1Ptr,        /* Points to an object holding the name of an
+    Tcl_Obj *part1Ptr, /* Points to an object holding the name of an
                                 * array (if part2 is non-NULL) or the name of
                                 * a variable. */
-    register Tcl_Obj *part2Ptr,        /* If non-NULL, points to an object holding
+    Tcl_Obj *part2Ptr, /* If non-NULL, points to an object holding
                                 * the name of an element in the array
                                 * part1Ptr. */
     Tcl_Obj *newValuePtr,      /* New value for variable. */
@@ -1854,7 +1854,7 @@ Tcl_Obj *
 TclPtrSetVarIdx(
     Tcl_Interp *interp,                /* Command interpreter in which variable is to
                                 * be looked up. */
-    register Var *varPtr,      /* Reference to the variable to set. */
+    Var *varPtr,       /* Reference to the variable to set. */
     Var *arrayPtr,             /* Reference to the array containing the
                                 * variable, or NULL if the variable is a
                                 * scalar. */
@@ -1887,11 +1887,11 @@ TclPtrSetVarIdx(
        if (flags & TCL_LEAVE_ERR_MSG) {
            if (TclIsVarArrayElement(varPtr)) {
                TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set",
-                       danglingElement, index);
+                       DANGLINGELEMENT, index);
                Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "ELEMENT", NULL);
            } else {
                TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set",
-                       danglingVar, index);
+                       DANGLINGVAR, index);
                Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME", NULL);
            }
        }
@@ -1904,7 +1904,7 @@ TclPtrSetVarIdx(
 
     if (TclIsVarArray(varPtr)) {
        if (flags & TCL_LEAVE_ERR_MSG) {
-           TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set", isArray,index);
+           TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "set", ISARRAY,index);
            Tcl_SetErrorCode(interp, "TCL", "WRITE", "ARRAY", NULL);
        }
        goto earlyError;
@@ -2205,7 +2205,7 @@ TclPtrIncrObjVarIdx(
                                 * variable, or -1. Only used when part1Ptr is
                                 * NULL. */
 {
-    register Tcl_Obj *varValuePtr;
+    Tcl_Obj *varValuePtr;
 
     if (TclIsVarInHash(varPtr)) {
        VarHashRefCount(varPtr)++;
@@ -2216,7 +2216,7 @@ TclPtrIncrObjVarIdx(
        VarHashRefCount(varPtr)--;
     }
     if (varValuePtr == NULL) {
-       varValuePtr = Tcl_NewIntObj(0);
+       TclNewIntObj(varValuePtr, 0);
     }
     if (Tcl_IsShared(varValuePtr)) {
        /* Copy on write */
@@ -2465,7 +2465,7 @@ int
 TclPtrUnsetVarIdx(
     Tcl_Interp *interp,                /* Command interpreter in which varName is to
                                 * be looked up. */
-    register Var *varPtr,      /* The variable to be unset. */
+    Var *varPtr,       /* The variable to be unset. */
     Var *arrayPtr,             /* NULL for scalar variables, pointer to the
                                 * containing array otherwise. */
     Tcl_Obj *part1Ptr,         /* Name of an array (if part2 is non-NULL) or
@@ -2502,7 +2502,7 @@ TclPtrUnsetVarIdx(
     if (result != TCL_OK) {
        if (flags & TCL_LEAVE_ERR_MSG) {
            TclObjVarErrMsg(interp, part1Ptr, part2Ptr, "unset",
-                   ((arrayPtr == NULL) ? noSuchVar : noSuchElement), index);
+                   ((arrayPtr == NULL) ? NOSUCHVAR : NOSUCHELEMENT), index);
            Tcl_SetErrorCode(interp, "TCL", "UNSET", "VARNAME", NULL);
        }
     }
@@ -2719,8 +2719,8 @@ Tcl_UnsetObjCmd(
     int objc,                  /* Number of arguments. */
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
-    register int i, flags = TCL_LEAVE_ERR_MSG;
-    register const char *name;
+    int i, flags = TCL_LEAVE_ERR_MSG;
+    const char *name;
 
     if (objc == 1) {
        /*
@@ -2788,7 +2788,7 @@ Tcl_AppendObjCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     Var *varPtr, *arrayPtr;
-    register Tcl_Obj *varValuePtr = NULL;
+    Tcl_Obj *varValuePtr = NULL;
                                /* Initialized to avoid compiler warning. */
     int i;
 
@@ -3697,7 +3697,7 @@ ArraySetCmd(
     }
     if (arrayPtr) {
        CleanupVar(varPtr, arrayPtr);
-       TclObjVarErrMsg(interp, arrayNameObj, NULL, "set", needArray, -1);
+       TclObjVarErrMsg(interp, arrayNameObj, NULL, "set", NEEDARRAY, -1);
        Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "VARNAME",
                TclGetString(arrayNameObj), NULL);
        return TCL_ERROR;
@@ -3815,7 +3815,7 @@ ArraySetCmd(
             */
 
            TclObjVarErrMsg(interp, arrayNameObj, NULL, "array set",
-                   needArray, -1);
+                   NEEDARRAY, -1);
            Tcl_SetErrorCode(interp, "TCL", "WRITE", "ARRAY", NULL);
            return TCL_ERROR;
        }
@@ -4529,7 +4529,7 @@ Tcl_GetVariableFullName(
                                 * variable's full name is appended. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Var *varPtr = (Var *) variable;
+    Var *varPtr = (Var *) variable;
     Tcl_Obj *namePtr;
     Namespace *nsPtr;
 
@@ -4589,9 +4589,9 @@ Tcl_GlobalObjCmd(
     Tcl_Obj *const objv[])     /* Argument objects. */
 {
     Interp *iPtr = (Interp *) interp;
-    register Tcl_Obj *objPtr, *tailPtr;
+    Tcl_Obj *objPtr, *tailPtr;
     const char *varName;
-    register const char *tail;
+    const char *tail;
     int result, i;
 
     /*
@@ -4718,7 +4718,7 @@ Tcl_VariableObjCmd(
             */
 
            TclObjVarErrMsg(interp, varNamePtr, NULL, "define",
-                   isArrayElement, -1);
+                   ISARRAYELEMENT, -1);
            Tcl_SetErrorCode(interp, "TCL", "UPVAR", "LOCAL_ELEMENT", NULL);
            return TCL_ERROR;
        }
@@ -4999,8 +4999,8 @@ ParseSearchId(
                                 * name. */
 {
     Interp *iPtr = (Interp *) interp;
-    register const char *string;
-    register size_t offset;
+    const char *string;
+    size_t offset;
     int id;
     ArraySearch *searchPtr;
     const char *varName = TclGetString(varNamePtr);
@@ -5081,7 +5081,7 @@ ParseSearchId(
 static void
 DeleteSearches(
     Interp *iPtr,
-    register Var *arrayVarPtr) /* Variable whose searches are to be
+    Var *arrayVarPtr)  /* Variable whose searches are to be
                                 * deleted. */
 {
     ArraySearch *searchPtr, *nextPtr;
@@ -5140,7 +5140,8 @@ TclDeleteNamespaceVars(
 
     for (varPtr = VarHashFirstVar(tablePtr, &search);  varPtr != NULL;
            varPtr = VarHashFirstVar(tablePtr, &search)) {
-       Tcl_Obj *objPtr = Tcl_NewObj();
+       Tcl_Obj *objPtr;
+       TclNewObj(objPtr);
        VarHashRefCount(varPtr)++;      /* Make sure we get to remove from
                                         * hash. */
        Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr, objPtr);
@@ -5222,7 +5223,7 @@ TclDeleteVars(
 {
     Tcl_Interp *interp = (Tcl_Interp *) iPtr;
     Tcl_HashSearch search;
-    register Var *varPtr;
+    Var *varPtr;
     int flags;
     Namespace *currNsPtr = (Namespace *) TclGetCurrentNamespace(interp);
 
@@ -5274,7 +5275,7 @@ TclDeleteCompiledLocalVars(
     CallFrame *framePtr)       /* Procedure call frame containing compiler-
                                 * assigned local variables to delete. */
 {
-    register Var *varPtr;
+    Var *varPtr;
     int numLocals, i;
     Tcl_Obj **namePtrPtr;
 
@@ -5323,7 +5324,7 @@ DeleteArray(
 {
     Tcl_HashSearch search;
     Tcl_HashEntry *tPtr;
-    register Var *elPtr;
+    Var *elPtr;
     ActiveVarTrace *activePtr;
     Tcl_Obj *objPtr;
     VarTrace *tracePtr;
@@ -5535,8 +5536,8 @@ static void
 FreeParsedVarName(
     Tcl_Obj *objPtr)
 {
-    register Tcl_Obj *arrayPtr = objPtr->internalRep.twoPtrValue.ptr1;
-    register char *elem = objPtr->internalRep.twoPtrValue.ptr2;
+    Tcl_Obj *arrayPtr = objPtr->internalRep.twoPtrValue.ptr1;
+    char *elem = objPtr->internalRep.twoPtrValue.ptr2;
 
     if (arrayPtr != NULL) {
        TclDecrRefCount(arrayPtr);
@@ -5550,8 +5551,8 @@ DupParsedVarName(
     Tcl_Obj *srcPtr,
     Tcl_Obj *dupPtr)
 {
-    register Tcl_Obj *arrayPtr = srcPtr->internalRep.twoPtrValue.ptr1;
-    register char *elem = srcPtr->internalRep.twoPtrValue.ptr2;
+    Tcl_Obj *arrayPtr = srcPtr->internalRep.twoPtrValue.ptr1;
+    char *elem = srcPtr->internalRep.twoPtrValue.ptr2;
     char *elemCopy;
     unsigned elemLen;
 
@@ -5595,10 +5596,10 @@ UpdateParsedVarName(
     objPtr->bytes = p;
     objPtr->length = totalLen;
 
-    memcpy(p, part1, (unsigned) len1);
+    memcpy(p, part1, len1);
     p += len1;
     *p++ = '(';
-    memcpy(p, part2, (unsigned) len2);
+    memcpy(p, part2, len2);
     p += len2;
     *p++ = ')';
     *p = '\0';
@@ -5684,7 +5685,7 @@ ObjFindNamespaceVar(
     Namespace *nsPtr[2], *cxtNsPtr;
     const char *simpleName;
     Var *varPtr;
-    register int search;
+    int search;
     int result;
     Tcl_Var var;
     Tcl_Obj *simpleNamePtr;
@@ -5875,7 +5876,7 @@ TclInfoVarsCmd(
                if (!TclIsVarUndefined(varPtr)
                        || TclIsVarNamespaceVar(varPtr)) {
                    if (specificNsInPattern) {
-                       elemObjPtr = Tcl_NewObj();
+                       TclNewObj(elemObjPtr);
                        Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr,
                                elemObjPtr);
                    } else {
@@ -5908,7 +5909,7 @@ TclInfoVarsCmd(
                    if ((simplePattern == NULL)
                            || Tcl_StringMatch(varName, simplePattern)) {
                        if (specificNsInPattern) {
-                           elemObjPtr = Tcl_NewObj();
+                           TclNewObj(elemObjPtr);
                            Tcl_GetVariableFullName(interp, (Tcl_Var) varPtr,
                                    elemObjPtr);
                        } else {
@@ -6311,8 +6312,8 @@ CompareVarKeys(
 {
     Tcl_Obj *objPtr1 = keyPtr;
     Tcl_Obj *objPtr2 = hPtr->key.objPtr;
-    register const char *p1, *p2;
-    register int l1, l2;
+    const char *p1, *p2;
+    int l1, l2;
 
     /*
      * If the object pointers are the same then they match.
index aed38c3..ac19449 100644 (file)
@@ -124,7 +124,6 @@ typedef struct {
     GzipHeader outHeader;      /* Header to write to an output stream, when
                                 * compressing a gzip stream. */
     Tcl_TimerToken timer;      /* Timer used for keeping events fresh. */
-    Tcl_DString decompressed;  /* Buffer for decompression results. */
     Tcl_Obj *compDictObj;      /* Byte-array object containing compression
                                 * dictionary (not dictObj!) to use if
                                 * necessary. */
@@ -137,11 +136,15 @@ typedef struct {
  *                     the input compressor.
  *     OUT_HEADER -    Whether the outputHeader field has been registered
  *                     with the output decompressor.
+ *     STREAM_DECOMPRESS - Signal decompress pending data.
+ *     STREAM_DONE -   Flag to signal stream end up to transform input.
  */
 
-#define ASYNC                  0x1
-#define IN_HEADER              0x2
-#define OUT_HEADER             0x4
+#define ASYNC                  0x01
+#define IN_HEADER              0x02
+#define OUT_HEADER             0x04
+#define STREAM_DECOMPRESS      0x08
+#define STREAM_DONE            0x10
 
 /*
  * Size of buffers allocated by default, and the range it can be set to.  The
@@ -184,10 +187,8 @@ static int         GenerateHeader(Tcl_Interp *interp, Tcl_Obj *dictObj,
                            GzipHeader *headerPtr, int *extraSizePtr);
 static int             ZlibPushSubcmd(Tcl_Interp *interp, int objc,
                            Tcl_Obj *const objv[]);
-static inline int      ResultCopy(ZlibChannelData *cd, char *buf,
-                           int toRead);
-static int             ResultGenerate(ZlibChannelData *cd, int n, int flush,
-                           int *errorCodePtr);
+static int             ResultDecompress(ZlibChannelData *cd, char *buf,
+                           int toRead, int flush, int *errorCodePtr);
 static Tcl_Channel     ZlibStackChannelTransform(Tcl_Interp *interp,
                            int mode, int format, int level, int limit,
                            Tcl_Channel channel, Tcl_Obj *gzipHeaderDictPtr,
@@ -204,7 +205,7 @@ static void         ZlibTransformTimerRun(ClientData clientData);
 
 static const Tcl_ChannelType zlibChannelType = {
     "zlib",
-    TCL_CHANNEL_VERSION_3,
+    TCL_CHANNEL_VERSION_5,
     ZlibTransformClose,
     ZlibTransformInput,
     ZlibTransformOutput,
@@ -593,7 +594,7 @@ SetInflateDictionary(
        int length;
        unsigned char *bytes = Tcl_GetByteArrayFromObj(compDictObj, &length);
 
-       return inflateSetDictionary(strm, bytes, (unsigned) length);
+       return inflateSetDictionary(strm, bytes, length);
     }
     return Z_OK;
 }
@@ -607,7 +608,7 @@ SetDeflateDictionary(
        int length;
        unsigned char *bytes = Tcl_GetByteArrayFromObj(compDictObj, &length);
 
-       return deflateSetDictionary(strm, bytes, (unsigned) length);
+       return deflateSetDictionary(strm, bytes, length);
     }
     return Z_OK;
 }
@@ -623,7 +624,7 @@ Deflate(
     int e;
 
     strm->next_out = (Bytef *) bufferPtr;
-    strm->avail_out = (unsigned) bufferSize;
+    strm->avail_out = bufferSize;
     e = deflate(strm, flush);
     if (writtenPtr != NULL) {
        *writtenPtr = bufferSize - strm->avail_out;
@@ -697,7 +698,7 @@ Tcl_ZlibStreamInit(
        case TCL_ZLIB_FORMAT_GZIP:
            wbits = WBITS_GZIP;
            if (dictObj) {
-               gzHeaderPtr = ckalloc(sizeof(GzipHeader));
+               gzHeaderPtr = (GzipHeader *)ckalloc(sizeof(GzipHeader));
                memset(gzHeaderPtr, 0, sizeof(GzipHeader));
                if (GenerateHeader(interp, dictObj, gzHeaderPtr,
                        NULL) != TCL_OK) {
@@ -731,7 +732,7 @@ Tcl_ZlibStreamInit(
            break;
        case TCL_ZLIB_FORMAT_GZIP:
            wbits = WBITS_GZIP;
-           gzHeaderPtr = ckalloc(sizeof(GzipHeader));
+           gzHeaderPtr = (GzipHeader *)ckalloc(sizeof(GzipHeader));
            memset(gzHeaderPtr, 0, sizeof(GzipHeader));
            gzHeaderPtr->header.name = (Bytef *)
                    gzHeaderPtr->nativeFilenameBuf;
@@ -757,7 +758,7 @@ Tcl_ZlibStreamInit(
                " TCL_ZLIB_STREAM_INFLATE");
     }
 
-    zshPtr = ckalloc(sizeof(ZlibStreamHandle));
+    zshPtr = (ZlibStreamHandle *)ckalloc(sizeof(ZlibStreamHandle));
     zshPtr->interp = interp;
     zshPtr->mode = mode;
     zshPtr->format = format;
@@ -884,7 +885,7 @@ static void
 ZlibStreamCmdDelete(
     ClientData cd)
 {
-    ZlibStreamHandle *zshPtr = cd;
+    ZlibStreamHandle *zshPtr = (ZlibStreamHandle *)cd;
 
     zshPtr->cmd = NULL;
     ZlibStreamCleanup(zshPtr);
@@ -1231,7 +1232,7 @@ Tcl_ZlibStreamPut(
        if (outSize > BUFFER_SIZE_LIMIT) {
            outSize = BUFFER_SIZE_LIMIT;
        }
-       dataTmp = ckalloc(outSize);
+       dataTmp = (char *)ckalloc(outSize);
 
        while (1) {
            e = Deflate(&zshPtr->stream, dataTmp, outSize, flush, &toStore);
@@ -1265,7 +1266,7 @@ Tcl_ZlibStreamPut(
            if (outSize < BUFFER_SIZE_LIMIT) {
                outSize = BUFFER_SIZE_LIMIT;
                /* There may be *lots* of data left to output... */
-               dataTmp = ckrealloc(dataTmp, outSize);
+               dataTmp = (char *)ckrealloc(dataTmp, outSize);
            }
        }
 
@@ -1750,10 +1751,10 @@ Tcl_ZlibInflate(
     if (gzipHeaderDictObj) {
        headerPtr = &header;
        memset(headerPtr, 0, sizeof(gz_header));
-       nameBuf = ckalloc(MAXPATHLEN);
+       nameBuf = (char *)ckalloc(MAXPATHLEN);
        header.name = (Bytef *) nameBuf;
        header.name_max = MAXPATHLEN - 1;
-       commentBuf = ckalloc(MAX_COMMENT_LEN);
+       commentBuf = (char *)ckalloc(MAX_COMMENT_LEN);
        header.comment = (Bytef *) commentBuf;
        header.comm_max = MAX_COMMENT_LEN - 1;
     }
@@ -1858,7 +1859,7 @@ Tcl_ZlibInflate(
     if (headerPtr != NULL) {
        ExtractHeader(&header, gzipHeaderDictObj);
        SetValue(gzipHeaderDictObj, "size",
-               Tcl_NewLongObj((long) stream.total_out));
+               Tcl_NewLongObj(stream.total_out));
        ckfree(nameBuf);
        ckfree(commentBuf);
     }
@@ -1894,7 +1895,7 @@ Tcl_ZlibCRC32(
     int len)
 {
     /* Nothing much to do, just wrap the crc32(). */
-    return crc32(crc, (Bytef *) buf, (unsigned) len);
+    return crc32(crc, (Bytef *) buf, len);
 }
 
 unsigned int
@@ -1903,7 +1904,7 @@ Tcl_ZlibAdler32(
     const unsigned char *buf,
     int len)
 {
-    return adler32(adler, (Bytef *) buf, (unsigned) len);
+    return adler32(adler, (Bytef *) buf, len);
 }
 \f
 /*
@@ -2132,7 +2133,7 @@ ZlibCmd(
                break;
            case 1:
                headerVarObj = objv[i+1];
-               headerDictObj = Tcl_NewObj();
+               TclNewObj(headerDictObj);
                break;
            }
        }
@@ -2364,7 +2365,7 @@ ZlibPushSubcmd(
     const char *const *pushOptions = pushDecompressOptions;
     enum pushOptions {poDictionary, poHeader, poLevel, poLimit};
     Tcl_Obj *headerObj = NULL, *compDictObj = NULL;
-    int limit = 1, dummy;
+    int limit = DEFAULT_BUFFER_SIZE, dummy;
 
     if (objc < 4) {
        Tcl_WrongNumArgs(interp, 2, objv, "mode channel ?options...?");
@@ -2519,7 +2520,7 @@ ZlibStreamCmd(
     int objc,
     Tcl_Obj *const objv[])
 {
-    Tcl_ZlibStream zstream = cd;
+    Tcl_ZlibStream zstream = (Tcl_ZlibStream)cd;
     int command, count, code;
     Tcl_Obj *obj;
     static const char *const cmds[] = {
@@ -2645,7 +2646,7 @@ ZlibStreamAddCmd(
     int objc,
     Tcl_Obj *const objv[])
 {
-    Tcl_ZlibStream zstream = cd;
+    Tcl_ZlibStream zstream = (Tcl_ZlibStream)cd;
     int index, code, buffersize = -1, flush = -1, i;
     Tcl_Obj *obj, *compDictObj = NULL;
     static const char *const add_options[] = {
@@ -2663,21 +2664,21 @@ ZlibStreamAddCmd(
 
        switch ((enum addOptions) index) {
        case ao_flush: /* -flush */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_SYNC_FLUSH;
            }
            break;
        case ao_fullflush: /* -fullflush */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_FULL_FLUSH;
            }
            break;
        case ao_finalize: /* -finalize */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_FINISH;
@@ -2769,7 +2770,7 @@ ZlibStreamPutCmd(
     int objc,
     Tcl_Obj *const objv[])
 {
-    Tcl_ZlibStream zstream = cd;
+    Tcl_ZlibStream zstream = (Tcl_ZlibStream)cd;
     int index, flush = -1, i;
     Tcl_Obj *compDictObj = NULL;
     static const char *const put_options[] = {
@@ -2787,21 +2788,21 @@ ZlibStreamPutCmd(
 
        switch ((enum putOptions) index) {
        case po_flush: /* -flush */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_SYNC_FLUSH;
            }
            break;
        case po_fullflush: /* -fullflush */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_FULL_FLUSH;
            }
            break;
        case po_finalize: /* -finalize */
-           if (flush > -1) {
+           if (flush >= 0) {
                flush = -2;
            } else {
                flush = Z_FINISH;
@@ -2858,7 +2859,7 @@ ZlibStreamHeaderCmd(
     int objc,
     Tcl_Obj *const objv[])
 {
-    ZlibStreamHandle *zshPtr = cd;
+    ZlibStreamHandle *zshPtr = (ZlibStreamHandle *)cd;
     Tcl_Obj *resultObj;
 
     if (objc != 2) {
@@ -2895,7 +2896,7 @@ ZlibTransformClose(
     ClientData instanceData,
     Tcl_Interp *interp)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     int e, written, result = TCL_OK;
 
     /*
@@ -2946,6 +2947,15 @@ ZlibTransformClose(
        } while (e != Z_STREAM_END);
        (void) deflateEnd(&cd->outStream);
     } else {
+       /*
+        * If we have unused bytes from the read input (overshot by
+        * Z_STREAM_END or on possible error), unget them back to the parent
+        * channel, so that they appear as not being read yet.
+        */
+       if (cd->inStream.avail_in) {
+           Tcl_Ungets (cd->parent, (char *)cd->inStream.next_in, cd->inStream.avail_in, 0);
+       }
+
        (void) inflateEnd(&cd->inStream);
     }
 
@@ -2957,7 +2967,6 @@ ZlibTransformClose(
        Tcl_DecrRefCount(cd->compDictObj);
        cd->compDictObj = NULL;
     }
-    Tcl_DStringFree(&cd->decompressed);
 
     if (cd->inBuffer) {
        ckfree(cd->inBuffer);
@@ -2988,10 +2997,10 @@ ZlibTransformInput(
     int toRead,
     int *errorCodePtr)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     Tcl_DriverInputProc *inProc =
            Tcl_ChannelInputProc(Tcl_GetChannelType(cd->parent));
-    int readBytes, gotBytes, copied;
+    int readBytes, gotBytes;
 
     if (cd->mode == TCL_ZLIB_STREAM_DEFLATE) {
        return inProc(Tcl_GetChannelInstanceData(cd->parent), buf, toRead,
@@ -2999,35 +3008,42 @@ ZlibTransformInput(
     }
 
     gotBytes = 0;
-    while (toRead > 0) {
+    readBytes = cd->inStream.avail_in; /* how many bytes in buffer now */
+    while (!(cd->flags & STREAM_DONE) && toRead > 0) {
+       int n, decBytes;
+
+       /* if starting from scratch or continuation after full decompression */
+       if (!cd->inStream.avail_in) {
+           /* buffer to start, we can read to whole available buffer */
+           cd->inStream.next_in = (Bytef *) cd->inBuffer;
+       }
        /*
-        * Loop until the request is satisfied (or no data available from
-        * below, possibly EOF).
+        * If done - no read needed anymore, check we have to copy rest of
+        * decompressed data, otherwise return with size (or 0 for Eof)
         */
-
-       copied = ResultCopy(cd, buf, toRead);
-       toRead -= copied;
-       buf += copied;
-       gotBytes += copied;
-
-       if (toRead == 0) {
-           return gotBytes;
+       if (cd->flags & STREAM_DECOMPRESS) {
+           goto copyDecompressed;
        }
-
        /*
         * The buffer is exhausted, but the caller wants even more. We now
         * have to go to the underlying channel, get more bytes and then
         * transform them for delivery. We may not get what we want (full EOF
         * or temporarily out of data).
-        *
-        * Length (cd->decompressed) == 0, toRead > 0 here.
-        *
-        * The zlib transform allows us to read at most one character from the
-        * underlying channel to properly identify Z_STREAM_END without
-        * reading over the border.
         */
 
-       readBytes = Tcl_ReadRaw(cd->parent, cd->inBuffer, cd->readAheadLimit);
+       /* Check free buffer size and adjust size of next chunk to read. */
+       n = cd->inAllocated - ((char *)cd->inStream.next_in - cd->inBuffer);
+       if (n <= 0) {
+           /* Normally unreachable: not enough input buffer to uncompress.
+            * Todo: firstly try to realloc inBuffer upto MAX_BUFFER_SIZE.
+            */
+           *errorCodePtr = ENOBUFS;
+           return -1;
+       }
+       if (n > cd->readAheadLimit) {
+           n = cd->readAheadLimit;
+       }
+       readBytes = Tcl_ReadRaw(cd->parent, (char *)cd->inStream.next_in, n);
 
        /*
         * Three cases here:
@@ -3043,45 +3059,59 @@ ZlibTransformInput(
 
            /* See ReflectInput() in tclIORTrans.c */
            if (Tcl_InputBlocked(cd->parent) && (gotBytes > 0)) {
-               return gotBytes;
+               break;
            }
 
            *errorCodePtr = Tcl_GetErrno();
            return -1;
        }
-       if (readBytes == 0) {
-           /*
-            * Eof in parent.
-            *
-            * Now this is a bit different. The partial data waiting is
-            * converted and returned.
-            */
 
-           if (ResultGenerate(cd, 0, Z_SYNC_FLUSH, errorCodePtr) != TCL_OK) {
-               return -1;
-           }
+       /* more bytes (or Eof if readBytes == 0) */
+       cd->inStream.avail_in += readBytes;
 
-           if (Tcl_DStringLength(&cd->decompressed) == 0) {
-               /*
-                * The drain delivered nothing. Time to deliver what we've
-                * got.
-                */
+copyDecompressed:
 
-               return gotBytes;
-           }
-       } else /* readBytes > 0 */ {
+       /*
+        * Transform the read chunk, if not empty. Anything we get
+        * back is a transformation result to be put into our buffers, and
+        * the next iteration will put it into the result.
+        * For the case readBytes is 0 which signaling Eof in parent, the
+        * partial data waiting is converted and returned.
+        */
+
+       decBytes = ResultDecompress(cd, buf, toRead,
+                   (readBytes != 0) ? Z_NO_FLUSH : Z_SYNC_FLUSH,
+                   errorCodePtr);
+       if (decBytes == -1) {
+           return -1;
+       }
+       gotBytes += decBytes;
+       buf += decBytes;
+       toRead -= decBytes;
+
+       if (((decBytes == 0) || (cd->flags & STREAM_DECOMPRESS))) {
            /*
-            * Transform the read chunk, which was not empty. Anything we get
-            * back is a transformation result to be put into our buffers, and
-            * the next iteration will put it into the result.
+            * The drain delivered nothing (or buffer too small to decompress).
+            * Time to deliver what we've got.
             */
-
-           if (ResultGenerate(cd, readBytes, Z_NO_FLUSH,
-                   errorCodePtr) != TCL_OK) {
+           if (!gotBytes && !(cd->flags & STREAM_DONE)) {
+               /* if no-data, but not ready - avoid signaling Eof,
+                * continue in blocking mode, otherwise EAGAIN */
+               if (Tcl_InputBlocked(cd->parent)) {
+                   continue;
+               }
+               *errorCodePtr = EAGAIN;
                return -1;
            }
+           break;
        }
+
+       /*
+        * Loop until the request is satisfied (or no data available from
+        * above, possibly EOF).
+        */
     }
+
     return gotBytes;
 }
 \f
@@ -3102,7 +3132,7 @@ ZlibTransformOutput(
     int toWrite,
     int *errorCodePtr)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     Tcl_DriverOutputProc *outProc =
            Tcl_ChannelOutputProc(Tcl_GetChannelType(cd->parent));
     int e, produced;
@@ -3223,7 +3253,7 @@ ZlibTransformSetOption(                   /* not used */
     const char *optionName,
     const char *value)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     Tcl_DriverSetOptionProc *setOptionProc =
            Tcl_ChannelSetOptionProc(Tcl_GetChannelType(cd->parent));
     static const char *compressChanOptions = "dictionary flush";
@@ -3336,7 +3366,7 @@ ZlibTransformGetOption(
     const char *optionName,
     Tcl_DString *dsPtr)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     Tcl_DriverGetOptionProc *getOptionProc =
            Tcl_ChannelGetOptionProc(Tcl_GetChannelType(cd->parent));
     static const char *compressChanOptions = "checksum dictionary";
@@ -3402,8 +3432,9 @@ ZlibTransformGetOption(
 
     if ((cd->flags & IN_HEADER) && ((optionName == NULL) ||
            (strcmp(optionName, "-header") == 0))) {
-       Tcl_Obj *tmpObj = Tcl_NewObj();
+       Tcl_Obj *tmpObj;
 
+       TclNewObj(tmpObj);
        ExtractHeader(&cd->inHeader.header, tmpObj);
        if (optionName == NULL) {
            Tcl_DStringAppendElement(dsPtr, "-header");
@@ -3454,7 +3485,7 @@ ZlibTransformWatch(
     ClientData instanceData,
     int mask)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
     Tcl_DriverWatchProc *watchProc;
 
     /*
@@ -3464,7 +3495,7 @@ ZlibTransformWatch(
     watchProc = Tcl_ChannelWatchProc(Tcl_GetChannelType(cd->parent));
     watchProc(Tcl_GetChannelInstanceData(cd->parent), mask);
 
-    if (!(mask & TCL_READABLE) || Tcl_DStringLength(&cd->decompressed) == 0) {
+    if (!(mask & TCL_READABLE) || !(cd->flags & STREAM_DECOMPRESS)) {
        ZlibTransformEventTimerKill(cd);
     } else if (cd->timer == NULL) {
        cd->timer = Tcl_CreateTimerHandler(SYNTHETIC_EVENT_TIME,
@@ -3477,7 +3508,7 @@ ZlibTransformEventHandler(
     ClientData instanceData,
     int interestMask)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
 
     ZlibTransformEventTimerKill(cd);
     return interestMask;
@@ -3497,7 +3528,7 @@ static void
 ZlibTransformTimerRun(
     ClientData clientData)
 {
-    ZlibChannelData *cd = clientData;
+    ZlibChannelData *cd = (ZlibChannelData *)clientData;
 
     cd->timer = NULL;
     Tcl_NotifyChannel(cd->chan, TCL_READABLE);
@@ -3520,7 +3551,7 @@ ZlibTransformGetHandle(
     int direction,
     ClientData *handlePtr)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
 
     return Tcl_GetChannelHandle(cd->parent, direction, handlePtr);
 }
@@ -3540,7 +3571,7 @@ ZlibTransformBlockMode(
     ClientData instanceData,
     int mode)
 {
-    ZlibChannelData *cd = instanceData;
+    ZlibChannelData *cd = (ZlibChannelData *)instanceData;
 
     if (mode == TCL_MODE_NONBLOCKING) {
        cd->flags |= ASYNC;
@@ -3590,7 +3621,7 @@ ZlibStackChannelTransform(
                                 * dictionary (not dictObj!) to use if
                                 * necessary. */
 {
-    ZlibChannelData *cd = ckalloc(sizeof(ZlibChannelData));
+    ZlibChannelData *cd = (ZlibChannelData *)ckalloc(sizeof(ZlibChannelData));
     Tcl_Channel chan;
     int wbits = 0;
 
@@ -3650,7 +3681,10 @@ ZlibStackChannelTransform(
            goto error;
        }
        cd->inAllocated = DEFAULT_BUFFER_SIZE;
-       cd->inBuffer = ckalloc(cd->inAllocated);
+       if (cd->inAllocated < cd->readAheadLimit) {
+           cd->inAllocated = cd->readAheadLimit;
+       }
+       cd->inBuffer = (char *)ckalloc(cd->inAllocated);
        if (cd->flags & IN_HEADER) {
            if (inflateGetHeader(&cd->inStream, &cd->inHeader.header) != Z_OK) {
                goto error;
@@ -3667,7 +3701,7 @@ ZlibStackChannelTransform(
            goto error;
        }
        cd->outAllocated = DEFAULT_BUFFER_SIZE;
-       cd->outBuffer = ckalloc(cd->outAllocated);
+       cd->outBuffer = (char *)ckalloc(cd->outAllocated);
        if (cd->flags & OUT_HEADER) {
            if (deflateSetHeader(&cd->outStream, &cd->outHeader.header) != Z_OK) {
                goto error;
@@ -3680,8 +3714,6 @@ ZlibStackChannelTransform(
        }
     }
 
-    Tcl_DStringInit(&cd->decompressed);
-
     chan = Tcl_StackChannel(interp, &zlibChannelType, cd,
            Tcl_GetChannelMode(channel), channel);
     if (chan == NULL) {
@@ -3711,96 +3743,37 @@ ZlibStackChannelTransform(
 /*
  *----------------------------------------------------------------------
  *
- * ResultCopy --
- *
- *     Copies the requested number of bytes from the buffer into the
- *     specified array and removes them from the buffer afterward. Copies
- *     less if there is not enough data in the buffer.
- *
- * Side effects:
- *     See above.
- *
- * Result:
- *     The number of actually copied bytes, possibly less than 'toRead'.
- *
- *----------------------------------------------------------------------
- */
-
-static inline int
-ResultCopy(
-    ZlibChannelData *cd,       /* The location of the buffer to read from. */
-    char *buf,                 /* The buffer to copy into */
-    int toRead)                        /* Number of requested bytes */
-{
-    int have = Tcl_DStringLength(&cd->decompressed);
-
-    if (have == 0) {
-       /*
-        * Nothing to copy in the case of an empty buffer.
-        */
-
-       return 0;
-    } else if (have > toRead) {
-       /*
-        * The internal buffer contains more than requested. Copy the
-        * requested subset to the caller, shift the remaining bytes down, and
-        * truncate.
-        */
-
-       char *src = Tcl_DStringValue(&cd->decompressed);
-
-       memcpy(buf, src, toRead);
-       memmove(src, src + toRead, have - toRead);
-
-       Tcl_DStringSetLength(&cd->decompressed, have - toRead);
-       return toRead;
-    } else /* have <= toRead */ {
-       /*
-        * There is just or not enough in the buffer to fully satisfy the
-        * caller, so take everything as best effort.
-        */
-
-       memcpy(buf, Tcl_DStringValue(&cd->decompressed), have);
-       TclDStringClear(&cd->decompressed);
-       return have;
-    }
-}
-\f
-/*
- *----------------------------------------------------------------------
- *
- * ResultGenerate --
+ * ResultDecompress --
  *
  *     Extract uncompressed bytes from the compression engine and store them
- *     in our working buffer.
+ *     in our buffer (buf) up to toRead bytes.
  *
  * Result:
- *     TCL_OK/TCL_ERROR (with *errorCodePtr updated with reason).
+ *     Number of bytes decompressed or -1 if error (with *errorCodePtr updated with reason).
  *
  * Side effects:
- *     See above.
+ *     After execution it updates cd->inStream (next_in, avail_in) to reflect
+ *     the data that has been decompressed.
  *
  *----------------------------------------------------------------------
  */
 
 static int
-ResultGenerate(
+ResultDecompress(
     ZlibChannelData *cd,
-    int n,
+    char *buf,
+    int toRead,
     int flush,
     int *errorCodePtr)
 {
-#define MAXBUF 1024
-    unsigned char buf[MAXBUF];
-    int e, written;
+    int e, written, resBytes = 0;
     Tcl_Obj *errObj;
 
-    cd->inStream.next_in = (Bytef *) cd->inBuffer;
-    cd->inStream.avail_in = n;
 
-    while (1) {
-       cd->inStream.next_out = (Bytef *) buf;
-       cd->inStream.avail_out = MAXBUF;
+    cd->flags &= ~STREAM_DECOMPRESS;
+    cd->inStream.next_out = (Bytef *) buf;
+    cd->inStream.avail_out = toRead;
+    while (cd->inStream.avail_out > 0) {
 
        e = inflate(&cd->inStream, flush);
        if (e == Z_NEED_DICT && cd->compDictObj) {
@@ -3809,31 +3782,35 @@ ResultGenerate(
                /*
                 * A repetition of Z_NEED_DICT is just an error.
                 */
-
-               cd->inStream.next_out = (Bytef *) buf;
-               cd->inStream.avail_out = MAXBUF;
                e = inflate(&cd->inStream, flush);
            }
        }
 
        /*
         * avail_out is now the left over space in the output.  Therefore
-        * "MAXBUF - avail_out" is the amount of bytes generated.
+        * "toRead - avail_out" is the amount of bytes generated.
         */
 
-       written = MAXBUF - cd->inStream.avail_out;
-       if (written) {
-           Tcl_DStringAppend(&cd->decompressed, (char *) buf, written);
-       }
+       written = toRead - cd->inStream.avail_out;
 
        /*
         * The cases where we're definitely done.
         */
 
-       if (((flush == Z_SYNC_FLUSH) && (e == Z_BUF_ERROR))
-               || (e == Z_STREAM_END)
-               || (e == Z_OK && cd->inStream.avail_out == 0)) {
-           return TCL_OK;
+       if (e == Z_STREAM_END) {
+           cd->flags |= STREAM_DONE;
+           resBytes += written;
+           break;
+       }
+       if (e == Z_OK) {
+           if (written == 0) {
+               break;
+           }
+           resBytes += written;
+       }
+
+       if ((flush == Z_SYNC_FLUSH) && (e == Z_BUF_ERROR)) {
+           break;
        }
 
        /*
@@ -3854,10 +3831,20 @@ ResultGenerate(
         */
 
        if (cd->inStream.avail_in <= 0 && flush != Z_SYNC_FLUSH) {
-           return TCL_OK;
+           break;
        }
     }
 
+    if (!(cd->flags & STREAM_DONE)) {
+       /* if we have pending input data, but no available output buffer */
+       if (cd->inStream.avail_in && !cd->inStream.avail_out) {
+           /* next time try to decompress it got readable (new output buffer) */
+           cd->flags |= STREAM_DECOMPRESS;
+       }
+    }
+
+    return resBytes;
+
   handleError:
     errObj = Tcl_NewListObj(0, NULL);
     Tcl_ListObjAppendElement(NULL, errObj, Tcl_NewStringObj("-errorcode",-1));
@@ -3867,7 +3854,7 @@ ResultGenerate(
            Tcl_NewStringObj(cd->inStream.msg, -1));
     Tcl_SetChannelError(cd->parent, errObj);
     *errorCodePtr = EINVAL;
-    return TCL_ERROR;
+    return -1;
 }
 \f
 /*
index a7a8979..64c5bc7 100644 (file)
@@ -240,6 +240,7 @@ proc auto_mkindex_old {dir args} {
        set f ""
        set error [catch {
            set f [open $file]
+           fconfigure $f -eofchar \032
            while {[gets $f line] >= 0} {
                if {[regexp {^proc[     ]+([^   ]*)} $line match procName]} {
                    set procName [lindex [auto_qualify $procName "::"] 0]
@@ -350,6 +351,7 @@ proc auto_mkindex_parser::mkindex {file} {
     set scriptFile $file
 
     set fid [open $file]
+    fconfigure $fid -eofchar \032
     set contents [read $fid]
     close $fid
 
@@ -376,10 +378,10 @@ proc auto_mkindex_parser::mkindex {file} {
 
 # auto_mkindex_parser::hook command
 #
-# Registers a Tcl command to evaluate when initializing the slave interpreter
-# used by the mkindex parser.  The command is evaluated in the master
+# Registers a Tcl command to evaluate when initializing the child interpreter
+# used by the mkindex parser.  The command is evaluated in the parent
 # interpreter, and can use the variable auto_mkindex_parser::parser to get to
-# the slave
+# the child
 
 proc auto_mkindex_parser::hook {cmd} {
     variable initCommands
@@ -389,14 +391,14 @@ proc auto_mkindex_parser::hook {cmd} {
 
 # auto_mkindex_parser::slavehook command
 #
-# Registers a Tcl command to evaluate when initializing the slave interpreter
-# used by the mkindex parser.  The command is evaluated in the slave
+# Registers a Tcl command to evaluate when initializing the child interpreter
+# used by the mkindex parser.  The command is evaluated in the child
 # interpreter.
 
 proc auto_mkindex_parser::slavehook {cmd} {
     variable initCommands
 
-    # The $parser variable is defined to be the name of the slave interpreter
+    # The $parser variable is defined to be the name of the child interpreter
     # when this command is used later.
 
     lappend initCommands "\$parser eval [list $cmd]"
@@ -550,7 +552,7 @@ auto_mkindex_parser::command proc {name args} {
 
 # Conditionally add support for Tcl byte code files.  There are some tricky
 # details here.  First, we need to get the tbcload library initialized in the
-# current interpreter.  We cannot load tbcload into the slave until we have
+# current interpreter.  We cannot load tbcload into the child until we have
 # done so because it needs access to the tcl_patchLevel variable.  Second,
 # because the package index file may defer loading the library until we invoke
 # a command, we need to explicitly invoke auto_load to force it to be loaded.
index 8e4b657..273b534 100644 (file)
@@ -9,7 +9,7 @@
 #
 #----------------------------------------------------------------------
 #
-# Copyright (c) 2004,2005,2006,2007 by Kevin B. Kenny
+# Copyright (c) 2004-2007 Kevin B. Kenny
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 #
@@ -3304,7 +3304,7 @@ proc ::tcl::clock::LoadTimeZoneFile { fileName } {
        return
     }
 
-    # Since an unsafe interp uses the [clock] command in the master, this code
+    # Since an unsafe interp uses the [clock] command in the parent, this code
     # is security sensitive.  Make sure that the path name cannot escape the
     # given directory.
 
@@ -3344,7 +3344,7 @@ proc ::tcl::clock::LoadTimeZoneFile { fileName } {
 proc ::tcl::clock::LoadZoneinfoFile { fileName } {
     variable ZoneinfoPaths
 
-    # Since an unsafe interp uses the [clock] command in the master, this code
+    # Since an unsafe interp uses the [clock] command in the parent, this code
     # is security sensitive.  Make sure that the path name cannot escape the
     # given directory.
 
@@ -3452,7 +3452,7 @@ proc ::tcl::clock::ReadZoneinfoFile {fileName fname} {
     set times [linsert $times 0 $MINWIDE]
     set codes {}
     foreach c $tempCodes {
-       lappend codes [expr { $c & 0xff }]
+       lappend codes [expr { $c & 0xFF }]
     }
     set codes [linsert $codes 0 0]
 
index f6a479d..1ca9c5a 100644 (file)
@@ -1,7 +1,7 @@
 if {![package vsatisfies [package provide Tcl] 8.5]} return
 if {[info sharedlibextension] != ".dll"} return
 if {[::tcl::pkgconfig get debug]} {
-    package ifneeded dde 1.4.2 [list load [file join $dir tcldde14g.dll] dde]
+    package ifneeded dde 1.4.3 [list load [file join $dir tcldde14g.dll] Dde]
 } else {
-    package ifneeded dde 1.4.2 [list load [file join $dir tcldde14.dll] dde]
+    package ifneeded dde 1.4.3 [list load [file join $dir tcldde14.dll] Dde]
 }
index c233be5..2e9142a 100644 (file)
@@ -17,4 +17,4 @@ S
 0E200E210E220E230E240E250E260E270E280E290E2A0E2B0E2C0E2D0E2E0E2F
 0E300E310E320E330E340E350E360E370E380E390E3A00000000000000000E3F
 0E400E410E420E430E440E450E460E470E480E490E4A0E4B0E4C0E4D0E4E0E4F
-0E500E510E520E530E540E550E560E570E580E590E5A0E5B0000000000000000
\ No newline at end of file
+0E500E510E520E530E540E550E560E570E580E590E5A0E5B0000000000000000
index 0aa283f..b0f87de 100644 (file)
@@ -11,7 +11,7 @@
 package require Tcl 8.6-
 # Keep this in sync with pkgIndex.tcl and with the install directories in
 # Makefiles
-package provide http 2.9.1
+package provide http 2.9.5
 
 namespace eval http {
     # Allow resourcing to not clobber existing data
@@ -531,7 +531,7 @@ proc http::CloseSocket {s {token {}}} {
     } else {
        set map [array get socketMapping]
        set ndx [lsearch -exact $map $s]
-       if {$ndx != -1} {
+       if {$ndx >= 0} {
            incr ndx -1
            set connId [lindex $map $ndx]
        }
@@ -721,7 +721,7 @@ proc http::geturl {url args} {
        body            {}
        status          ""
        http            ""
-       connection      close
+       connection      keep-alive
     }
     set state(-keepalive) $defaultKeepalive
     set state(-strict) $strict
@@ -733,6 +733,7 @@ proc http::geturl {url args} {
        -strict         boolean
        -timeout        integer
        -validate       boolean
+       -headers        dict
     }
     set state(charset) $defaultCharset
     set options {
@@ -746,9 +747,8 @@ proc http::geturl {url args} {
     foreach {flag value} $args {
        if {[regexp -- $pat $flag]} {
            # Validate numbers
-           if {
-               [info exists type($flag)] &&
-               ![string is $type($flag) -strict $value]
+           if {($flag eq "-headers") ? [catch {dict size $value}] :
+               ([info exists type($flag)] && ![string is $type($flag) -strict $value])
            } {
                unset $token
                return -code error \
@@ -966,6 +966,18 @@ proc http::geturl {url args} {
        set state(-pipeline) $http(-pipeline)
     }
 
+    # We cannot handle chunked encodings with -handler, so force HTTP/1.0
+    # until we can manage this.
+    if {[info exists state(-handler)]} {
+       set state(-protocol) 1.0
+    }
+
+    # RFC 7320 A.1 - HTTP/1.0 Keep-Alive is problematic. We do not support it.
+    if {$state(-protocol) eq "1.0"} {
+       set state(connection) close
+       set state(-keepalive) 0
+    }
+
     # See if we are supposed to use a previously opened channel.
     # - In principle, ANY call to http::geturl could use a previously opened
     #   channel if it is available - the "Connection: keep-alive" header is a
@@ -1037,7 +1049,7 @@ proc http::geturl {url args} {
 
            }
            # Do not automatically close the connection socket.
-           set state(connection) {}
+           set state(connection) keep-alive
        }
     }
 
@@ -1332,19 +1344,12 @@ proc http::Connected {token proto phost srvurl} {
        set how POST
        # The query channel must be blocking for the async Write to
        # work properly.
-       lassign [fconfigure $sock -translation] trRead trWrite
-       fconfigure $state(-querychannel) -blocking 1 \
-                                        -translation [list $trRead binary]
+       fconfigure $state(-querychannel) -blocking 1 -translation binary
        set contDone 0
     }
     if {[info exists state(-method)] && ($state(-method) ne "")} {
        set how $state(-method)
     }
-    # We cannot handle chunked encodings with -handler, so force HTTP/1.0
-    # until we can manage this.
-    if {[info exists state(-handler)]} {
-       set state(-protocol) 1.0
-    }
     set accept_types_seen 0
 
     Log ^B$tk begin sending request - token $token
@@ -1363,7 +1368,7 @@ proc http::Connected {token proto phost srvurl} {
            puts $sock "Host: $host:$port"
        }
        puts $sock "User-Agent: $http(-useragent)"
-       if {($state(-protocol) >= 1.0) && $state(-keepalive)} {
+       if {($state(-protocol) > 1.0) && $state(-keepalive)} {
            # Send this header, because a 1.1 server is not compelled to treat
            # this as the default.
            puts $sock "Connection: keep-alive"
@@ -1371,9 +1376,17 @@ proc http::Connected {token proto phost srvurl} {
        if {($state(-protocol) > 1.0) && !$state(-keepalive)} {
            puts $sock "Connection: close" ;# RFC2616 sec 8.1.2.1
        }
-       if {[info exists phost] && ($phost ne "") && $state(-keepalive)} {
-           puts $sock "Proxy-Connection: Keep-Alive"
-       }
+       if {($state(-protocol) < 1.1)} {
+           # RFC7230 A.1
+           # Some server implementations of HTTP/1.0 have a faulty
+           # implementation of RFC 2068 Keep-Alive.
+           # Don't leave this to chance.
+           # For HTTP/1.0 we have already "set state(connection) close"
+           # and "state(-keepalive) 0".
+           puts $sock "Connection: close"
+       }
+       # RFC7230 A.1 - "clients are encouraged not to send the
+       # Proxy-Connection header field in any requests"
        set accept_encoding_seen 0
        set content_type_seen 0
        dict for {key value} $state(-headers) {
@@ -1633,9 +1646,51 @@ proc http::ReceiveResponse {token} {
     Log ^D$tk begin receiving response - token $token
 
     coroutine ${token}EventCoroutine http::Event $sock $token
-    fileevent $sock readable ${token}EventCoroutine
+    if {[info exists state(-handler)] || [info exists state(-progress)]} {
+        fileevent $sock readable [list http::EventGateway $sock $token]
+    } else {
+        fileevent $sock readable ${token}EventCoroutine
+    }
+    return
+}
+
+
+# http::EventGateway
+#
+#      Bug [c2dc1da315].
+#      - Recursive launch of the coroutine can occur if a -handler or -progress
+#        callback is used, and the callback command enters the event loop.
+#      - To prevent this, the fileevent "binding" is disabled while the
+#        coroutine is in flight.
+#      - If a recursive call occurs despite these precautions, it is not
+#        trapped and discarded here, because it is better to report it as a
+#        bug.
+#      - Although this solution is believed to be sufficiently general, it is
+#        used only if -handler or -progress is specified.  In other cases,
+#        the coroutine is called directly.
+
+proc http::EventGateway {sock token} {
+    variable $token
+    upvar 0 $token state
+    fileevent $sock readable {}
+    catch {${token}EventCoroutine} res opts
+    if {[info commands ${token}EventCoroutine] ne {}} {
+        # The coroutine can be deleted by completion (a non-yield return), by
+        # http::Finish (when there is a premature end to the transaction), by
+        # http::reset or http::cleanup, or if the caller set option -channel
+        # but not option -handler: in the last case reading from the socket is
+        # now managed by commands ::http::Copy*, http::ReceiveChunked, and
+        # http::make-transformation-chunked.
+        #
+        # Catch in case the coroutine has closed the socket.
+        catch {fileevent $sock readable [list http::EventGateway $sock $token]}
+    }
+
+    # If there was an error, re-throw it.
+    return -options $opts $res
 }
 
+
 # http::NextPipelinedWrite
 #
 # - Connecting a socket to a token for writing is done by this command and by
@@ -2690,8 +2745,32 @@ proc http::Event {sock token} {
                        }
                        proxy-connection -
                        connection {
-                           set state(connection) \
-                                   [string trim [string tolower $value]]
+                           set tmpHeader [string trim [string tolower $value]]
+                           # RFC 7230 Section 6.1 states that a comma-separated
+                           # list is an acceptable value.  According to
+                           # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Connection
+                           # any comma-separated list implies keep-alive, but I
+                           # don't see this in the RFC so we'll play safe and
+                           # scan any list for "close".
+                           if {$tmpHeader in {close keep-alive}} {
+                               # The common cases, continue.
+                           } elseif {[string first , $tmpHeader] < 0} {
+                               # Not a comma-separated list, not "close",
+                               # therefore "keep-alive".
+                               set tmpHeader keep-alive
+                           } else {
+                               set tmpResult keep-alive
+                               set tmpCsl [split $tmpHeader ,]
+                               # Optional whitespace either side of separator.
+                               foreach el $tmpCsl {
+                                   if {[string trim $el] eq {close}} {
+                                       set tmpResult close
+                                       break
+                                   }
+                               }
+                               set tmpHeader $tmpResult
+                           }
+                           set state(connection) $tmpHeader
                        }
                    }
                    lappend state(meta) $key [string trim $value]
index f9f1176..74c4841 100644 (file)
@@ -1,2 +1,2 @@
 if {![package vsatisfies [package provide Tcl] 8.6-]} {return}
-package ifneeded http 2.9.1 [list tclPkgSetup $dir http 2.9.1 {{http.tcl source {::http::config ::http::formatQuery ::http::geturl ::http::reset ::http::wait ::http::register ::http::unregister ::http::mapReply}}}]
+package ifneeded http 2.9.5 [list tclPkgSetup $dir http 2.9.5 {{http.tcl source {::http::config ::http::formatQuery ::http::geturl ::http::reset ::http::wait ::http::register ::http::unregister ::http::mapReply}}}]
index 5cda0d9..1bfca4c 100644 (file)
@@ -6,7 +6,7 @@
 # Copyright (c) 1991-1993 The Regents of the University of California.
 # Copyright (c) 1994-1996 Sun Microsystems, Inc.
 # Copyright (c) 1998-1999 Scriptics Corporation.
-# Copyright (c) 2004 by Kevin B. Kenny.  All rights reserved.
+# Copyright (c) 2004 Kevin B. Kenny.  All rights reserved.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -16,7 +16,7 @@
 if {[info commands package] == ""} {
     error "version mismatch: library\nscripts expect Tcl version 7.5b1 or later but the loaded version is\nonly [info patchlevel]"
 }
-package require -exact Tcl 8.6.10
+package require -exact Tcl 8.6.11
 
 # Compute the auto path to use in this interpreter.
 # The values on the path come from several locations:
@@ -37,41 +37,46 @@ package require -exact Tcl 8.6.10
 # tcl_pkgPath, which is set by the platform-specific initialization routines
 #      On UNIX it is compiled in
 #       On Windows, it is not used
+#
+# (Ticket 41c9857bdd) In a safe interpreter, this file does not set
+# ::auto_path (other than to {} if it is undefined). The caller, typically
+# a Safe Base command, is responsible for setting ::auto_path.
 
 if {![info exists auto_path]} {
-    if {[info exists env(TCLLIBPATH)]} {
+    if {[info exists env(TCLLIBPATH)] && (![interp issafe])} {
        set auto_path $env(TCLLIBPATH)
     } else {
        set auto_path ""
     }
 }
 namespace eval tcl {
-    variable Dir
-    foreach Dir [list $::tcl_library [file dirname $::tcl_library]] {
-       if {$Dir ni $::auto_path} {
-           lappend ::auto_path $Dir
-       }
-    }
-    set Dir [file join [file dirname [file dirname \
-           [info nameofexecutable]]] lib]
-    if {$Dir ni $::auto_path} {
-       lappend ::auto_path $Dir
-    }
-    catch {
-       foreach Dir $::tcl_pkgPath {
+    if {![interp issafe]} {
+       variable Dir
+       foreach Dir [list $::tcl_library [file dirname $::tcl_library]] {
            if {$Dir ni $::auto_path} {
                lappend ::auto_path $Dir
            }
        }
-    }
+       set Dir [file join [file dirname [file dirname \
+               [info nameofexecutable]]] lib]
+       if {$Dir ni $::auto_path} {
+           lappend ::auto_path $Dir
+       }
+       if {[info exists ::tcl_pkgPath]} { catch {
+           foreach Dir $::tcl_pkgPath {
+               if {$Dir ni $::auto_path} {
+                   lappend ::auto_path $Dir
+               }
+           }
+       }}
 
-    if {![interp issafe]} {
-        variable Path [encoding dirs]
-        set Dir [file join $::tcl_library encoding]
-        if {$Dir ni $Path} {
+       variable Path [encoding dirs]
+       set Dir [file join $::tcl_library encoding]
+       if {$Dir ni $Path} {
            lappend Path $Dir
            encoding dirs $Path
-        }
+       }
+       unset Dir Path
     }
 
     # TIP #255 min and max functions
@@ -79,7 +84,7 @@ namespace eval tcl {
        proc min {args} {
            if {![llength $args]} {
                return -code error \
-                   "too few arguments to math function \"min\""
+                   "not enough arguments to math function \"min\""
            }
            set val Inf
            foreach arg $args {
@@ -95,7 +100,7 @@ namespace eval tcl {
        proc max {args} {
            if {![llength $args]} {
                return -code error \
-                   "too few arguments to math function \"max\""
+                   "not enough arguments to math function \"max\""
            }
            set val -Inf
            foreach arg $args {
@@ -308,7 +313,7 @@ proc unknown args {
                set errInfo [string range $errInfo 0 $last-1]
                set tail "\"$cinfo\""
                set last [string last $tail $errInfo]
-               if {$last + [string length $tail] != [string length $errInfo]} {
+               if {$last < 0 || $last + [string length $tail] != [string length $errInfo]} {
                    return -code error -errorcode $errCode \
                            -errorinfo $errInfo $msg
                }
@@ -489,6 +494,7 @@ proc auto_load_index {} {
            continue
        } else {
            set error [catch {
+               fconfigure $f -eofchar \032
                set id [gets $f]
                if {$id eq "# Tcl autoload index file, version 2.0"} {
                    eval [read $f]
@@ -792,7 +798,7 @@ proc tcl::CopyDirectory {action src dest} {
            }
        }
     } else {
-       if {[string first $nsrc $ndest] != -1} {
+       if {[string first $nsrc $ndest] >= 0} {
            set srclen [expr {[llength [file split $nsrc]] - 1}]
            set ndest [lindex [file split $ndest] $srclen]
            if {$ndest eq [file tail $nsrc]} {
index 646bc17..fa91a37 100644 (file)
@@ -4,9 +4,9 @@
 #      message catalog facility for Tcl programs.  It should be
 #      loaded with the command "package require msgcat".
 #
-# Copyright (c) 2010-2015 by Harald Oehlmann.
-# Copyright (c) 1998-2000 by Ajuba Solutions.
-# Copyright (c) 1998 by Mark Harrison.
+# Copyright (c) 2010-2015 Harald Oehlmann.
+# Copyright (c) 1998-2000 Ajuba Solutions.
+# Copyright (c) 1998 Mark Harrison.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 869a2b6..1639379 100644 (file)
@@ -8,10 +8,10 @@
 #      on it.  If your code does rely on this package you
 #      may directly incorporate this code into your application.
 
-package require Tcl 8.2
+package require Tcl 8.5-
 # When this version number changes, update the pkgIndex.tcl file
 # and the install directory in the Makefiles.
-package provide opt 0.4.6
+package provide opt 0.4.8
 
 namespace eval ::tcl {
 
@@ -44,8 +44,8 @@ namespace eval ::tcl {
             {-intflag      7}
             {-weirdflag                    "help string"}
             {-noStatics                    "Not ok to load static packages"}
-            {-nestedloading1 true           "OK to load into nested slaves"}
-            {-nestedloading2 -boolean true "OK to load into nested slaves"}
+            {-nestedloading1 true           "OK to load into nested children"}
+            {-nestedloading2 -boolean true "OK to load into nested children"}
             {-libsOK        -choice {Tk SybTcl}
                                      "List of packages that can be loaded"}
             {-precision     -int 12        "Number of digits of precision"}
index 107d4c6..23e118c 100644 (file)
@@ -8,5 +8,5 @@
 # script is sourced, the variable $dir must contain the
 # full path name of this file's directory.
 
-if {![package vsatisfies [package provide Tcl] 8.2]} {return}
-package ifneeded opt 0.4.6 [list source [file join $dir optparse.tcl]]
+if {![package vsatisfies [package provide Tcl] 8.5-]} {return}
+package ifneeded opt 0.4.8 [list source [file join $dir optparse.tcl]]
index 44e3b28..4a73346 100644 (file)
@@ -237,7 +237,7 @@ proc pkg_mkIndex {args} {
        $c eval [list set ::tcl::file $file]
        $c eval [list set ::tcl::direct $direct]
 
-       # Download needed procedures into the slave because we've just deleted
+       # Download needed procedures into the child because we've just deleted
        # the unknown procedure.  This doesn't handle procedures with default
        # arguments.
 
@@ -479,9 +479,12 @@ proc tclPkgUnknown {name args} {
        }
        set tclSeenPath($dir) 1
 
-       # we can't use glob in safe interps, so enclose the following in a
-       # catch statement, where we get the pkgIndex files out of the
-       # subdirectories
+       # Get the pkgIndex.tcl files in subdirectories of auto_path directories.
+       # - Safe Base interpreters have a restricted "glob" command that
+       #   works in this case.
+       # - The "catch" was essential when there was no safe glob and every
+       #   call in a safe interp failed; it is retained only for corner
+       #   cases in which the eventual call to glob returns an error.
        catch {
            foreach file [glob -directory $dir -join -nocomplain \
                    * pkgIndex.tcl] {
@@ -585,6 +588,7 @@ proc tcl::MacOSXPkgUnknown {original name args} {
        set tclSeenPath($dir) 1
 
        # get the pkgIndex files out of the subdirectories
+       # Safe interpreters do not use tcl::MacOSXPkgUnknown - see init.tcl.
        foreach file [glob -directory $dir -join -nocomplain \
                * Resources Scripts pkgIndex.tcl] {
            set dir [file dirname $file]
index 5970a3f..46a0ed4 100644 (file)
@@ -1,3 +1,3 @@
-package ifneeded platform        1.0.14 [list source [file join $dir platform.tcl]]
+package ifneeded platform        1.0.15 [list source [file join $dir platform.tcl]]
 package ifneeded platform::shell 1.1.4 [list source [file join $dir shell.tcl]]
 
index 35a22a3..6c01142 100644 (file)
@@ -94,9 +94,6 @@ proc ::platform::generic {} {
     }
 
     switch -glob -- $plat {
-       cygwin* {
-           set plat cygwin
-       }
        windows {
            if {$tcl_platform(platform) == "unix"} {
                set plat cygwin
@@ -149,6 +146,9 @@ proc ::platform::generic {} {
        osf1 {
            set plat tru64
        }
+       default {
+           set plat [lindex [split $plat _-] 0]
+       }
     }
 
     return "${plat}-${cpu}"
@@ -175,11 +175,15 @@ proc ::platform::identify {} {
        }
        macosx {
            set major [lindex [split $tcl_platform(osVersion) .] 0]
-           if {$major > 8} {
+           if {$major > 19} {
+               incr major -20
+               append plat 11.$major
+           } else {
                incr major -4
                append plat 10.$major
                return "${plat}-${cpu}"
            }
+           return "${plat}-${cpu}"
        }
        linux {
            # Look for the libc*.so and determine its version
@@ -330,7 +334,7 @@ proc ::platform::patterns {id} {
            lappend res macosx-universal macosx-i386-x86_64
        }
        macosx*-*    {
-           # 10.5+
+           # 10.5+,11.0+
            if {[regexp {macosx([^-]*)-(.*)} $id -> v cpu]} {
 
                switch -exact -- $cpu {
@@ -338,17 +342,39 @@ proc ::platform::patterns {id} {
                        lappend alt i386-x86_64
                        lappend alt universal
                    }
-                   x86_64  { lappend alt i386-x86_64 }
+                   x86_64  {
+                       if {[lindex [split $::tcl_platform(osVersion) .] 0] < 19} {
+                           set alt i386-x86_64
+                       } else {
+                           set alt {}
+                       }
+                   }
+                   arm  {
+                       lappend alt x86_64
+                   }
                    default { set alt {} }
                }
 
                if {$v ne ""} {
                    foreach {major minor} [split $v .] break
 
-                   # Add 10.5 to 10.minor to patterns.
                    set res {}
+                   if {$major eq 11} {
+                       # Add 11.0 to 11.minor to patterns.
+                       for {set j $minor} {$j >= 0} {incr j -1} {
+                           lappend res macosx${major}.${j}-${cpu}
+                           foreach a $alt {
+                               lappend res macosx${major}.${j}-$a
+                           }
+                       }
+                       set major 10
+                       set minor 15
+                   }
+                   # Add 10.5 to 10.minor to patterns.
                    for {set j $minor} {$j >= 5} {incr j -1} {
-                       lappend res macosx${major}.${j}-${cpu}
+                       if {$cpu ne "arm"} {
+                           lappend res macosx${major}.${j}-${cpu}
+                       }
                        foreach a $alt {
                            lappend res macosx${major}.${j}-$a
                        }
@@ -378,7 +404,7 @@ proc ::platform::patterns {id} {
 # ### ### ### ######### ######### #########
 ## Ready
 
-package provide platform 1.0.14
+package provide platform 1.0.15
 
 # ### ### ### ######### ######### #########
 ## Demo application
old mode 100755 (executable)
new mode 100644 (file)
index 219e41f..6603e3e
@@ -1,9 +1,9 @@
 if {![package vsatisfies [package provide Tcl] 8.5]} return
 if {[info sharedlibextension] != ".dll"} return
 if {[::tcl::pkgconfig get debug]} {
-    package ifneeded registry 1.3.4 \
-            [list load [file join $dir tclreg13g.dll] registry]
+    package ifneeded registry 1.3.5 \
+            [list load [file join $dir tclreg13g.dll] Registry]
 } else {
-    package ifneeded registry 1.3.4 \
-            [list load [file join $dir tclreg13.dll] registry]
+    package ifneeded registry 1.3.5 \
+            [list load [file join $dir tclreg13.dll] Registry]
 }
index ea6391d..b9dd18d 100644 (file)
@@ -1,9 +1,9 @@
 # safe.tcl --
 #
 # This file provide a safe loading/sourcing mechanism for safe interpreters.
-# It implements a virtual path mecanism to hide the real pathnames from the
-# slave. It runs in a master interpreter and sets up data structure and
-# aliases that will be invoked when used from a slave interpreter.
+# It implements a virtual path mechanism to hide the real pathnames from the
+# child. It runs in a parent interpreter and sets up data structure and
+# aliases that will be invoked when used from a child interpreter.
 #
 # See the safe.n man page for details.
 #
@@ -20,7 +20,7 @@
 #
 
 # Needed utilities package
-package require opt 0.4.1
+package require opt 0.4.8
 
 # Create the safe namespace
 namespace eval ::safe {
@@ -79,6 +79,7 @@ proc ::safe::InterpNested {} {
 # Interface/entry point function and front end for "Create"
 proc ::safe::interpCreate {args} {
     set Args [::tcl::OptKeyParse ::safe::interpCreate $args]
+    RejectExcessColons $slave
     InterpCreate $slave $accessPath \
        [InterpStatics] [InterpNested] $deleteHook
 }
@@ -88,16 +89,17 @@ proc ::safe::interpInit {args} {
     if {![::interp exists $slave]} {
        return -code error "\"$slave\" is not an interpreter"
     }
+    RejectExcessColons $slave
     InterpInit $slave $accessPath \
        [InterpStatics] [InterpNested] $deleteHook
 }
 
-# Check that the given slave is "one of us"
-proc ::safe::CheckInterp {slave} {
-    namespace upvar ::safe S$slave state
-    if {![info exists state] || ![::interp exists $slave]} {
+# Check that the given child is "one of us"
+proc ::safe::CheckInterp {child} {
+    namespace upvar ::safe [VarName $child] state
+    if {![info exists state] || ![::interp exists $child]} {
        return -code error \
-           "\"$slave\" is not an interpreter managed by ::safe::"
+           "\"$child\" is not an interpreter managed by ::safe::"
     }
 }
 
@@ -119,11 +121,11 @@ proc ::safe::interpConfigure {args} {
        1 {
            # If we have exactly 1 argument the semantic is to return all
            # the current configuration. We still call OptKeyParse though
-           # we know that "slave" is our given argument because it also
+           # we know that "child" is our given argument because it also
            # checks for the "-help" option.
            set Args [::tcl::OptKeyParse ::safe::interpIC $args]
            CheckInterp $slave
-           namespace upvar ::safe S$slave state
+           namespace upvar ::safe [VarName $slave] state
 
            return [join [list \
                [list -accessPath $state(access_path)] \
@@ -146,7 +148,7 @@ proc ::safe::interpConfigure {args} {
                return -code error [::tcl::OptFlagUsage $desc $arg]
            }
            CheckInterp $slave
-           namespace upvar ::safe S$slave state
+           namespace upvar ::safe [VarName $slave] state
 
            set item [::tcl::OptCurDesc $desc]
            set name [::tcl::OptName $item]
@@ -187,15 +189,15 @@ proc ::safe::interpConfigure {args} {
            # create did
            set Args [::tcl::OptKeyParse ::safe::interpIC $args]
            CheckInterp $slave
-           namespace upvar ::safe S$slave state
+           namespace upvar ::safe [VarName $slave] state
 
            # Get the current (and not the default) values of whatever has
            # not been given:
            if {![::tcl::OptProcArgGiven -accessPath]} {
-               set doreset 1
+               set doreset 0
                set accessPath $state(access_path)
            } else {
-               set doreset 0
+               set doreset 1
            }
            if {
                ![::tcl::OptProcArgGiven -statics]
@@ -218,14 +220,33 @@ proc ::safe::interpConfigure {args} {
            }
            # we can now reconfigure :
            InterpSetConfig $slave $accessPath $statics $nested $deleteHook
-           # auto_reset the slave (to completly synch the new access_path)
+           # auto_reset the child (to completly synch the new access_path)
            if {$doreset} {
                if {[catch {::interp eval $slave {auto_reset}} msg]} {
                    Log $slave "auto_reset failed: $msg"
                } else {
                    Log $slave "successful auto_reset" NOTICE
                }
+
+               # Sync the paths used to search for Tcl modules.
+               ::interp eval $slave {tcl::tm::path remove {*}[tcl::tm::list]}
+               if {[llength $state(tm_path_slave)] > 0} {
+                   ::interp eval $slave [list \
+                           ::tcl::tm::add {*}[lreverse $state(tm_path_slave)]]
+               }
+
+               # Remove stale "package ifneeded" data for non-loaded packages.
+               # - Not for loaded packages, because "package forget" erases
+               #   data from "package provide" as well as "package ifneeded".
+               # - This is OK because the script cannot reload any version of
+               #   the package unless it first does "package forget".
+               foreach pkg [::interp eval $slave {package names}] {
+                   if {[::interp eval $slave [list package provide $pkg]] eq ""} {
+                       ::interp eval $slave [list package forget $pkg]
+                   }
+               }
            }
+           return
        }
     }
 }
@@ -239,17 +260,17 @@ proc ::safe::interpConfigure {args} {
 #
 # safe::InterpCreate : doing the real job
 #
-# This procedure creates a safe slave and initializes it with the safe
+# This procedure creates a safe interpreter and initializes it with the safe
 # base aliases.
-# NB: slave name must be simple alphanumeric string, no spaces, no (), no
+# NB: child name must be simple alphanumeric string, no spaces, no (), no
 # {},...  {because the state array is stored as part of the name}
 #
-# Returns the slave name.
+# Returns the child name.
 #
 # Optional Arguments :
-# + slave name : if empty, generated name will be used
+# + child name : if empty, generated name will be used
 # + access_path: path list controlling where load/source can occur,
-#                if empty: the master auto_path will be used.
+#                if empty: the parent auto_path will be used.
 # + staticsok  : flag, if 0 :no static package can be loaded (load {} Xxx)
 #                      if 1 :static packages are ok.
 # + nestedok: flag, if 0 :no loading to sub-sub interps (load xx xx sub)
@@ -257,35 +278,37 @@ proc ::safe::interpConfigure {args} {
 
 # use the full name and no indent so auto_mkIndex can find us
 proc ::safe::InterpCreate {
-                          slave
+                          child
                           access_path
                           staticsok
                           nestedok
                           deletehook
                       } {
-    # Create the slave.
-    if {$slave ne ""} {
-       ::interp create -safe $slave
+    # Create the child.
+    # If evaluated in ::safe, the interpreter command for foo is ::foo;
+    # but for foo::bar is safe::foo::bar.  So evaluate in :: instead.
+    if {$child ne ""} {
+       namespace eval :: [list ::interp create -safe $child]
     } else {
-       # empty argument: generate slave name
-       set slave [::interp create -safe]
+       # empty argument: generate child name
+       set child [::interp create -safe]
     }
-    Log $slave "Created" NOTICE
+    Log $child "Created" NOTICE
 
-    # Initialize it. (returns slave name)
-    InterpInit $slave $access_path $staticsok $nestedok $deletehook
+    # Initialize it. (returns child name)
+    InterpInit $child $access_path $staticsok $nestedok $deletehook
 }
 
 #
 # InterpSetConfig (was setAccessPath) :
-#    Sets up slave virtual auto_path and corresponding structure within
-#    the master. Also sets the tcl_library in the slave to be the first
+#    Sets up child virtual auto_path and corresponding structure within
+#    the parent. Also sets the tcl_library in the child to be the first
 #    directory in the path.
-#    NB: If you change the path after the slave has been initialized you
-#    probably need to call "auto_reset" in the slave in order that it gets
+#    NB: If you change the path after the child has been initialized you
+#    probably need to call "auto_reset" in the child in order that it gets
 #    the right auto_index() array values.
 
-proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
+proc ::safe::InterpSetConfig {child access_path staticsok nestedok deletehook} {
     global auto_path
 
     # determine and store the access path if empty
@@ -295,36 +318,36 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
        # Make sure that tcl_library is in auto_path and at the first
        # position (needed by setAccessPath)
        set where [lsearch -exact $access_path [info library]]
-       if {$where == -1} {
+       if {$where < 0} {
            # not found, add it.
            set access_path [linsert $access_path 0 [info library]]
-           Log $slave "tcl_library was not in auto_path,\
+           Log $child "tcl_library was not in auto_path,\
                        added it to slave's access_path" NOTICE
        } elseif {$where != 0} {
            # not first, move it first
            set access_path [linsert \
                                 [lreplace $access_path $where $where] \
                                 0 [info library]]
-           Log $slave "tcl_libray was not in first in auto_path,\
+           Log $child "tcl_libray was not in first in auto_path,\
                        moved it to front of slave's access_path" NOTICE
        }
 
        # Add 1st level sub dirs (will searched by auto loading from tcl
-       # code in the slave using glob and thus fail, so we add them here
+       # code in the child using glob and thus fail, so we add them here
        # so by default it works the same).
        set access_path [AddSubDirs $access_path]
     }
 
-    Log $slave "Setting accessPath=($access_path) staticsok=$staticsok\
+    Log $child "Setting accessPath=($access_path) staticsok=$staticsok\
                nestedok=$nestedok deletehook=($deletehook)" NOTICE
 
-    namespace upvar ::safe S$slave state
+    namespace upvar ::safe [VarName $child] state
 
     # clear old autopath if it existed
     # build new one
     # Extend the access list with the paths used to look for Tcl Modules.
     # We save the virtual form separately as well, as syncing it with the
-    # slave has to be defered until the necessary commands are present for
+    # child has to be deferred until the necessary commands are present for
     # setup.
 
     set norm_access_path  {}
@@ -344,6 +367,7 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
     }
 
     set morepaths [::tcl::tm::list]
+    set firstpass 1
     while {[llength $morepaths]} {
        set addpaths $morepaths
        set morepaths {}
@@ -352,6 +376,12 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
            # Prevent the addition of dirs on the tm list to the
            # result if they are already known.
            if {[dict exists $remap_access_path $dir]} {
+               if {$firstpass} {
+                   # $dir is in [::tcl::tm::list] and belongs in the slave_tm_path.
+                   # Later passes handle subdirectories, which belong in the
+                   # access path but not in the module path.
+                   lappend slave_tm_path  [dict get $remap_access_path $dir]
+               }
                continue
            }
 
@@ -361,7 +391,12 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
            lappend map_access_path    $token $dir
            lappend remap_access_path  $dir $token
            lappend norm_access_path   [file normalize $dir]
-           lappend slave_tm_path $token
+           if {$firstpass} {
+               # $dir is in [::tcl::tm::list] and belongs in the slave_tm_path.
+               # Later passes handle subdirectories, which belong in the
+               # access path but not in the module path.
+               lappend slave_tm_path  $token
+           }
            incr i
 
            # [Bug 2854929]
@@ -372,6 +407,7 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
            # subdirectories.
            lappend morepaths {*}[glob -nocomplain -directory $dir -type d *]
        }
+       set firstpass 0
     }
 
     set state(access_path)       $access_path
@@ -384,7 +420,8 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
     set state(nestedok)          $nestedok
     set state(cleanupHook)       $deletehook
 
-    SyncAccessPath $slave
+    SyncAccessPath $child
+    return
 }
 
 #
@@ -392,11 +429,12 @@ proc ::safe::InterpSetConfig {slave access_path staticsok nestedok deletehook} {
 # FindInAccessPath:
 #    Search for a real directory and returns its virtual Id (including the
 #    "$")
-proc ::safe::interpFindInAccessPath {slave path} {
-    namespace upvar ::safe S$slave state
+proc ::safe::interpFindInAccessPath {child path} {
+    CheckInterp $child
+    namespace upvar ::safe [VarName $child] state
 
     if {![dict exists $state(access_path,remap) $path]} {
-       return -code error "$path not found in access path $access_path"
+       return -code error "$path not found in access path"
     }
 
     return [dict get $state(access_path,remap) $path]
@@ -406,10 +444,11 @@ proc ::safe::interpFindInAccessPath {slave path} {
 # addToAccessPath:
 #    add (if needed) a real directory to access path and return its
 #    virtual token (including the "$").
-proc ::safe::interpAddToAccessPath {slave path} {
+proc ::safe::interpAddToAccessPath {child path} {
     # first check if the directory is already in there
     # (inlined interpFindInAccessPath).
-    namespace upvar ::safe S$slave state
+    CheckInterp $child
+    namespace upvar ::safe [VarName $child] state
 
     if {[dict exists $state(access_path,remap) $path]} {
        return [dict get $state(access_path,remap) $path]
@@ -424,7 +463,7 @@ proc ::safe::interpAddToAccessPath {slave path} {
     lappend state(access_path,remap) $path $token
     lappend state(access_path,norm)  [file normalize $path]
 
-    SyncAccessPath $slave
+    SyncAccessPath $child
     return $token
 }
 
@@ -432,25 +471,25 @@ proc ::safe::interpAddToAccessPath {slave path} {
 # interpreter. It is useful when you want to install the safe base aliases
 # into a preexisting safe interpreter.
 proc ::safe::InterpInit {
-                        slave
+                        child
                         access_path
                         staticsok
                         nestedok
                         deletehook
                     } {
     # Configure will generate an access_path when access_path is empty.
-    InterpSetConfig $slave $access_path $staticsok $nestedok $deletehook
+    InterpSetConfig $child $access_path $staticsok $nestedok $deletehook
 
     # NB we need to add [namespace current], aliases are always absolute
     # paths.
 
-    # These aliases let the slave load files to define new commands
-    # This alias lets the slave use the encoding names, convertfrom,
+    # These aliases let the child load files to define new commands
+    # This alias lets the child use the encoding names, convertfrom,
     # convertto, and system, but not "encoding system <name>" to set the
     # system encoding.
     # Handling Tcl Modules, we need a restricted form of Glob.
     # This alias interposes on the 'exit' command and cleanly terminates
-    # the slave.
+    # the child.
 
     foreach {command alias} {
        source   AliasSource
@@ -459,61 +498,61 @@ proc ::safe::InterpInit {
        exit     interpDelete
        glob     AliasGlob
     } {
-       ::interp alias $slave $command {} [namespace current]::$alias $slave
+       ::interp alias $child $command {} [namespace current]::$alias $child
     }
 
-    # This alias lets the slave have access to a subset of the 'file'
+    # This alias lets the child have access to a subset of the 'file'
     # command functionality.
 
-    ::interp expose $slave file
+    ::interp expose $child file
     foreach subcommand {dirname extension rootname tail} {
-       ::interp alias $slave ::tcl::file::$subcommand {} \
-           ::safe::AliasFileSubcommand $slave $subcommand
+       ::interp alias $child ::tcl::file::$subcommand {} \
+           ::safe::AliasFileSubcommand $child $subcommand
     }
     foreach subcommand {
        atime attributes copy delete executable exists isdirectory isfile
        link lstat mtime mkdir nativename normalize owned readable readlink
        rename size stat tempfile type volumes writable
     } {
-       ::interp alias $slave ::tcl::file::$subcommand {} \
-           ::safe::BadSubcommand $slave file $subcommand
+       ::interp alias $child ::tcl::file::$subcommand {} \
+           ::safe::BadSubcommand $child file $subcommand
     }
 
     # Subcommands of info
     foreach {subcommand alias} {
        nameofexecutable   AliasExeName
     } {
-       ::interp alias $slave ::tcl::info::$subcommand \
-           {} [namespace current]::$alias $slave
+       ::interp alias $child ::tcl::info::$subcommand \
+           {} [namespace current]::$alias $child
     }
 
-    # The allowed slave variables already have been set by Tcl_MakeSafe(3)
+    # The allowed child variables already have been set by Tcl_MakeSafe(3)
 
-    # Source init.tcl and tm.tcl into the slave, to get auto_load and
+    # Source init.tcl and tm.tcl into the child, to get auto_load and
     # other procedures defined:
 
-    if {[catch {::interp eval $slave {
+    if {[catch {::interp eval $child {
        source [file join $tcl_library init.tcl]
     }} msg opt]} {
-       Log $slave "can't source init.tcl ($msg)"
-       return -options $opt "can't source init.tcl into slave $slave ($msg)"
+       Log $child "can't source init.tcl ($msg)"
+       return -options $opt "can't source init.tcl into slave $child ($msg)"
     }
 
-    if {[catch {::interp eval $slave {
+    if {[catch {::interp eval $child {
        source [file join $tcl_library tm.tcl]
     }} msg opt]} {
-       Log $slave "can't source tm.tcl ($msg)"
-       return -options $opt "can't source tm.tcl into slave $slave ($msg)"
+       Log $child "can't source tm.tcl ($msg)"
+       return -options $opt "can't source tm.tcl into slave $child ($msg)"
     }
 
     # Sync the paths used to search for Tcl modules. This can be done only
     # now, after tm.tcl was loaded.
-    namespace upvar ::safe S$slave state
+    namespace upvar ::safe [VarName $child] state
     if {[llength $state(tm_path_slave)] > 0} {
-       ::interp eval $slave [list \
+       ::interp eval $child [list \
                ::tcl::tm::add {*}[lreverse $state(tm_path_slave)]]
     }
-    return $slave
+    return $child
 }
 
 # Add (only if needed, avoid duplicates) 1 level of sub directories to an
@@ -539,15 +578,30 @@ proc ::safe::AddSubDirs {pathList} {
     return $res
 }
 
-# This procedure deletes a safe slave managed by Safe Tcl and cleans up
-# associated state:
-
-proc ::safe::interpDelete {slave} {
-    Log $slave "About to delete" NOTICE
-
-    namespace upvar ::safe S$slave state
+# This procedure deletes a safe interpreter managed by Safe Tcl and cleans up
+# associated state.
+# - The command will also delete non-Safe-Base interpreters.
+# - This is regrettable, but to avoid breaking existing code this should be
+#   amended at the next major revision by uncommenting "CheckInterp".
+
+proc ::safe::interpDelete {child} {
+    Log $child "About to delete" NOTICE
+
+    # CheckInterp $child
+    namespace upvar ::safe [VarName $child] state
+
+    # When an interpreter is deleted with [interp delete], any sub-interpreters
+    # are deleted automatically, but this leaves behind their data in the Safe
+    # Base. To clean up properly, we call safe::interpDelete recursively on each
+    # Safe Base sub-interpreter, so each one is deleted cleanly and not by
+    # the automatic mechanism built into [interp delete].
+    foreach sub [interp children $child] {
+        if {[info exists ::safe::[VarName [list $child $sub]]]} {
+            ::safe::interpDelete [list $child $sub]
+        }
+    }
 
-    # If the slave has a cleanup hook registered, call it.  Check the
+    # If the child has a cleanup hook registered, call it.  Check the
     # existance because we might be called to delete an interp which has
     # not been registered with us at all
 
@@ -558,14 +612,14 @@ proc ::safe::interpDelete {slave} {
            # we'll loop
            unset state(cleanupHook)
            try {
-               {*}$hook $slave
+               {*}$hook $child
            } on error err {
-               Log $slave "Delete hook error ($err)"
+               Log $child "Delete hook error ($err)"
            }
        }
     }
 
-    # Discard the global array of state associated with the slave, and
+    # Discard the global array of state associated with the child, and
     # delete the interpreter.
 
     if {[info exists state]} {
@@ -574,9 +628,9 @@ proc ::safe::interpDelete {slave} {
 
     # if we have been called twice, the interp might have been deleted
     # already
-    if {[::interp exists $slave]} {
-       ::interp delete $slave
-       Log $slave "Deleted" NOTICE
+    if {[::interp exists $child]} {
+       ::interp delete $child
+       Log $child "Deleted" NOTICE
     }
 
     return
@@ -602,9 +656,9 @@ proc ::safe::setLogCmd {args} {
     } else {
        # Activate logging, define proper command.
 
-       proc ::safe::Log {slave msg {type ERROR}} {
+       proc ::safe::Log {child msg {type ERROR}} {
            variable Log
-           {*}$Log "$type for slave $slave : $msg"
+           {*}$Log "$type for slave $child : $msg"
            return
        }
     }
@@ -613,23 +667,23 @@ proc ::safe::setLogCmd {args} {
 # ------------------- END OF PUBLIC METHODS ------------
 
 #
-# Sets the slave auto_path to the master recorded value.  Also sets
+# Sets the child auto_path to the parent recorded value.  Also sets
 # tcl_library to the first token of the virtual path.
 #
-proc ::safe::SyncAccessPath {slave} {
-    namespace upvar ::safe S$slave state
+proc ::safe::SyncAccessPath {child} {
+    namespace upvar ::safe [VarName $child] state
 
     set slave_access_path $state(access_path,slave)
-    ::interp eval $slave [list set auto_path $slave_access_path]
+    ::interp eval $child [list set auto_path $slave_access_path]
 
-    Log $slave "auto_path in $slave has been set to $slave_access_path"\
+    Log $child "auto_path in $child has been set to $slave_access_path"\
        NOTICE
 
     # This code assumes that info library is the first element in the
     # list of auto_path's. See -> InterpSetConfig for the code which
     # ensures this condition.
 
-    ::interp eval $slave [list \
+    ::interp eval $child [list \
              set tcl_library [lindex $slave_access_path 0]]
 }
 
@@ -643,8 +697,8 @@ proc ::safe::PathToken {n} {
 #
 # translate virtual path into real path
 #
-proc ::safe::TranslatePath {slave path} {
-    namespace upvar ::safe S$slave state
+proc ::safe::TranslatePath {child path} {
+    namespace upvar ::safe [VarName $child] state
 
     # somehow strip the namespaces 'functionality' out (the danger is that
     # we would strip valid macintosh "../" queries... :
@@ -659,7 +713,7 @@ proc ::safe::TranslatePath {slave path} {
 
 # file name control (limit access to files/resources that should be a
 # valid tcl source file)
-proc ::safe::CheckFileName {slave file} {
+proc ::safe::CheckFileName {child file} {
     # This used to limit what can be sourced to ".tcl" and forbid files
     # with more than 1 dot and longer than 14 chars, but I changed that
     # for 8.4 as a safe interp has enough internal protection already to
@@ -680,17 +734,17 @@ proc ::safe::CheckFileName {slave file} {
 # interpreters that are *almost* safe. In particular, it just acts to
 # prevent discovery of what home directories exist.
 
-proc ::safe::AliasFileSubcommand {slave subcommand name} {
+proc ::safe::AliasFileSubcommand {child subcommand name} {
     if {[string match ~* $name]} {
        set name ./$name
     }
-    tailcall ::interp invokehidden $slave tcl:file:$subcommand $name
+    tailcall ::interp invokehidden $child tcl:file:$subcommand $name
 }
 
 # AliasGlob is the target of the "glob" alias in safe interpreters.
 
-proc ::safe::AliasGlob {slave args} {
-    Log $slave "GLOB ! $args" NOTICE
+proc ::safe::AliasGlob {child args} {
+    Log $child "GLOB ! $args" NOTICE
     set cmd {}
     set at 0
     array set got {
@@ -712,11 +766,15 @@ proc ::safe::AliasGlob {slave args} {
 
     while {$at < [llength $args]} {
        switch -glob -- [set opt [lindex $args $at]] {
-           -nocomplain - -- - -join - -tails {
+           -nocomplain - -- - -tails {
                lappend cmd $opt
                set got($opt) 1
                incr at
            }
+           -join {
+               set got($opt) 1
+               incr at
+           }
            -types - -type {
                lappend cmd -types [lindex $args [incr at]]
                incr at
@@ -730,15 +788,8 @@ proc ::safe::AliasGlob {slave args} {
                set virtualdir [lindex $args [incr at]]
                incr at
            }
-           pkgIndex.tcl {
-               # Oops, this is globbing a subdirectory in regular package
-               # search. That is not wanted. Abort, handler does catch
-               # already (because glob was not defined before). See
-               # package.tcl, lines 484ff in tclPkgUnknown.
-               return -code error "unknown command glob"
-           }
            -* {
-               Log $slave "Safe base rejecting glob option '$opt'"
+               Log $child "Safe base rejecting glob option '$opt'"
                return -code error "Safe base rejecting glob option '$opt'"
            }
            default {
@@ -749,73 +800,116 @@ proc ::safe::AliasGlob {slave args} {
     }
 
     # Get the real path from the virtual one and check that the path is in the
-    # access path of that slave. Done after basic argument processing so that
+    # access path of that child. Done after basic argument processing so that
     # we know if -nocomplain is set.
     if {$got(-directory)} {
        try {
-           set dir [TranslatePath $slave $virtualdir]
-           DirInAccessPath $slave $dir
+           set dir [TranslatePath $child $virtualdir]
+           DirInAccessPath $child $dir
        } on error msg {
-           Log $slave $msg
+           Log $child $msg
            if {$got(-nocomplain)} return
            return -code error "permission denied"
        }
-       lappend cmd -directory $dir
+       if {$got(--)} {
+           set cmd [linsert $cmd end-1 -directory $dir]
+       } else {
+           lappend cmd -directory $dir
+       }
+    } else {
+       # The code after this "if ... else" block would conspire to return with
+       # no results in this case, if it were allowed to proceed.  Instead,
+       # return now and reduce the number of cases to be considered later.
+       Log $child {option -directory must be supplied}
+       if {$got(-nocomplain)} return
+       return -code error "permission denied"
     }
 
-    # Apply the -join semantics ourselves
+    # Apply the -join semantics ourselves.
     if {$got(-join)} {
        set args [lreplace $args $at end [join [lrange $args $at end] "/"]]
     }
 
-    # Process remaining pattern arguments
+    # Process the pattern arguments.  If we've done a join there is only one
+    # pattern argument.
+
     set firstPattern [llength $cmd]
     foreach opt [lrange $args $at end] {
        if {![regexp $dirPartRE $opt -> thedir thefile]} {
            set thedir .
-       } elseif {[string match ~* $thedir]} {
-           set thedir ./$thedir
+           # The *.tm search comes here.
        }
-       if {$thedir eq "*" &&
-               ($thefile eq "pkgIndex.tcl" || $thefile eq "*.tm")} {
+       # "Special" treatment for (joined) argument {*/pkgIndex.tcl}.
+       # Do the expansion of "*" here, and filter out any directories that are
+       # not in the access path.  The outcome is to lappend to cmd a path of
+       # the form $virtualdir/subdir/pkgIndex.tcl for each subdirectory subdir,
+       # after removing any subdir that are not in the access path.
+       if {($thedir eq "*") && ($thefile eq "pkgIndex.tcl")} {
            set mapped 0
-           foreach d [glob -directory [TranslatePath $slave $virtualdir] \
+           foreach d [glob -directory [TranslatePath $child $virtualdir] \
                           -types d -tails *] {
                catch {
-                   DirInAccessPath $slave \
-                       [TranslatePath $slave [file join $virtualdir $d]]
+                   DirInAccessPath $child \
+                       [TranslatePath $child [file join $virtualdir $d]]
                    lappend cmd [file join $d $thefile]
                    set mapped 1
                }
            }
            if {$mapped} continue
+           # Don't [continue] if */pkgIndex.tcl has no matches in the access
+           # path.  The pattern will now receive the same treatment as a
+           # "non-special" pattern (and will fail because it includes a "*" in
+           # the directory name).
        }
+       # Any directory pattern that is not an exact (i.e. non-glob) match to a
+       # directory in the access path will be rejected here.
+       # - Rejections include any directory pattern that has glob matching
+       #   patterns "*", "?", backslashes, braces or square brackets, (UNLESS
+       #   it corresponds to a genuine directory name AND that directory is in
+       #   the access path).
+       # - The only "special matching characters" that remain in patterns for
+       #   processing by glob are in the filename tail.
+       # - [file join $anything ~${foo}] is ~${foo}, which is not an exact
+       #   match to any directory in the access path.  Hence directory patterns
+       #   that begin with "~" are rejected here.  Tests safe-16.[5-8] check
+       #   that "file join" remains as required and does not expand ~${foo}.
+       # - Bug [3529949] relates to unwanted expansion of ~${foo} and this is
+       #   how the present code avoids the bug.  All tests safe-16.* relate.
        try {
-           DirInAccessPath $slave [TranslatePath $slave \
+           DirInAccessPath $child [TranslatePath $child \
                    [file join $virtualdir $thedir]]
        } on error msg {
-           Log $slave $msg
+           Log $child $msg
            if {$got(-nocomplain)} continue
            return -code error "permission denied"
        }
        lappend cmd $opt
     }
 
-    Log $slave "GLOB = $cmd" NOTICE
+    Log $child "GLOB = $cmd" NOTICE
 
     if {$got(-nocomplain) && [llength $cmd] eq $firstPattern} {
        return
     }
     try {
-       set entries [::interp invokehidden $slave glob {*}$cmd]
+       # >>>>>>>>>> HERE'S THE CALL TO SAFE INTERP GLOB <<<<<<<<<<
+       # - Pattern arguments added to cmd have NOT been translated from tokens.
+       #   Only the virtualdir is translated (to dir).
+       # - In the pkgIndex.tcl case, there is no "*" in the pattern arguments,
+       #   which are a list of names each with tail pkgIndex.tcl.  The purpose
+       #   of the call to glob is to remove the names for which the file does
+       #   not exist.
+       set entries [::interp invokehidden $child glob {*}$cmd]
     } on error msg {
-       Log $slave $msg
+       # This is the only place that a call with -nocomplain and no invalid
+       # "dash-options" can return an error.
+       Log $child $msg
        return -code error "script error"
     }
 
-    Log $slave "GLOB < $entries" NOTICE
+    Log $child "GLOB < $entries" NOTICE
 
-    # Translate path back to what the slave should see.
+    # Translate path back to what the child should see.
     set res {}
     set l [string length $dir]
     foreach p $entries {
@@ -825,13 +919,13 @@ proc ::safe::AliasGlob {slave args} {
        lappend res $p
     }
 
-    Log $slave "GLOB > $res" NOTICE
+    Log $child "GLOB > $res" NOTICE
     return $res
 }
 
 # AliasSource is the target of the "source" alias in safe interpreters.
 
-proc ::safe::AliasSource {slave args} {
+proc ::safe::AliasSource {child args} {
     set argc [llength $args]
     # Extended for handling of Tcl Modules to allow not only "source
     # filename", but "source -encoding E filename" as well.
@@ -840,7 +934,7 @@ proc ::safe::AliasSource {slave args} {
        set encoding [lindex $args 1]
        set at 2
        if {$encoding eq "identity"} {
-           Log $slave "attempt to use the identity encoding"
+           Log $child "attempt to use the identity encoding"
            return -code error "permission denied"
        }
     } else {
@@ -849,39 +943,42 @@ proc ::safe::AliasSource {slave args} {
     }
     if {$argc != 1} {
        set msg "wrong # args: should be \"source ?-encoding E? fileName\""
-       Log $slave "$msg ($args)"
+       Log $child "$msg ($args)"
        return -code error $msg
     }
     set file [lindex $args $at]
 
     # get the real path from the virtual one.
     if {[catch {
-       set realfile [TranslatePath $slave $file]
+       set realfile [TranslatePath $child $file]
     } msg]} {
-       Log $slave $msg
+       Log $child $msg
        return -code error "permission denied"
     }
 
-    # check that the path is in the access path of that slave
+    # check that the path is in the access path of that child
     if {[catch {
-       FileInAccessPath $slave $realfile
+       FileInAccessPath $child $realfile
     } msg]} {
-       Log $slave $msg
+       Log $child $msg
        return -code error "permission denied"
     }
 
-    # do the checks on the filename :
+    # Check that the filename exists and is readable.  If it is not, deliver
+    # this -errorcode so that caller in tclPkgUnknown does not write a message
+    # to tclLog.  Has no effect on other callers of ::source, which are in
+    # "package ifneeded" scripts.
     if {[catch {
-       CheckFileName $slave $realfile
+       CheckFileName $child $realfile
     } msg]} {
-       Log $slave "$realfile:$msg"
-       return -code error $msg
+       Log $child "$realfile:$msg"
+       return -code error -errorcode {POSIX EACCES} $msg
     }
 
     # Passed all the tests, lets source it. Note that we do this all manually
-    # because we want to control [info script] in the slave so information
+    # because we want to control [info script] in the child so information
     # doesn't leak so much. [Bug 2913625]
-    set old [::interp eval $slave {info script}]
+    set old [::interp eval $child {info script}]
     set replacementMsg "script error"
     set code [catch {
        set f [open $realfile]
@@ -891,17 +988,17 @@ proc ::safe::AliasSource {slave args} {
        }
        set contents [read $f]
        close $f
-       ::interp eval $slave [list info script $file]
+       ::interp eval $child [list info script $file]
     } msg opt]
     if {$code == 0} {
-       set code [catch {::interp eval $slave $contents} msg opt]
+       set code [catch {::interp eval $child $contents} msg opt]
        set replacementMsg $msg
     }
-    catch {interp eval $slave [list info script $old]}
+    catch {interp eval $child [list info script $old]}
     # Note that all non-errors are fine result codes from [source], so we must
     # take a little care to do it properly. [Bug 2923613]
     if {$code == 1} {
-       Log $slave $msg
+       Log $child $msg
        return -code error $replacementMsg
     }
     return -code $code -options $opt $msg
@@ -909,18 +1006,18 @@ proc ::safe::AliasSource {slave args} {
 
 # AliasLoad is the target of the "load" alias in safe interpreters.
 
-proc ::safe::AliasLoad {slave file args} {
+proc ::safe::AliasLoad {child file args} {
     set argc [llength $args]
     if {$argc > 2} {
        set msg "load error: too many arguments"
-       Log $slave "$msg ($argc) {$file $args}"
+       Log $child "$msg ($argc) {$file $args}"
        return -code error $msg
     }
 
     # package name (can be empty if file is not).
     set package [lindex $args 0]
 
-    namespace upvar ::safe S$slave state
+    namespace upvar ::safe [VarName $child] state
 
     # Determine where to load. load use a relative interp path and {}
     # means self, so we can directly and safely use passed arg.
@@ -929,7 +1026,7 @@ proc ::safe::AliasLoad {slave file args} {
        # we will try to load into a sub sub interp; check that we want to
        # authorize that.
        if {!$state(nestedok)} {
-           Log $slave "loading to a sub interp (nestedok)\
+           Log $child "loading to a sub interp (nestedok)\
                        disabled (trying to load $package to $target)"
            return -code error "permission denied (nested load)"
        }
@@ -940,11 +1037,11 @@ proc ::safe::AliasLoad {slave file args} {
        # static package loading
        if {$package eq ""} {
            set msg "load error: empty filename and no package name"
-           Log $slave $msg
+           Log $child $msg
            return -code error $msg
        }
        if {!$state(staticsok)} {
-           Log $slave "static packages loading disabled\
+           Log $child "static packages loading disabled\
                        (trying to load $package to $target)"
            return -code error "permission denied (static package)"
        }
@@ -953,36 +1050,43 @@ proc ::safe::AliasLoad {slave file args} {
 
        # get the real path from the virtual one.
        try {
-           set file [TranslatePath $slave $file]
+           set file [TranslatePath $child $file]
        } on error msg {
-           Log $slave $msg
+           Log $child $msg
            return -code error "permission denied"
        }
 
        # check the translated path
        try {
-           FileInAccessPath $slave $file
+           FileInAccessPath $child $file
        } on error msg {
-           Log $slave $msg
+           Log $child $msg
            return -code error "permission denied (path)"
        }
     }
 
     try {
-       return [::interp invokehidden $slave load $file $package $target]
+       return [::interp invokehidden $child load $file $package $target]
     } on error msg {
-       Log $slave $msg
+       # Some packages return no error message.
+       set msg0 "load of binary library for package $package failed"
+       if {$msg eq {}} {
+           set msg $msg0
+       } else {
+           set msg "$msg0: $msg"
+       }
+       Log $child $msg
        return -code error $msg
     }
 }
 
 # FileInAccessPath raises an error if the file is not found in the list of
-# directories contained in the (master side recorded) slave's access path.
+# directories contained in the (parent side recorded) child's access path.
 
 # the security here relies on "file dirname" answering the proper
 # result... needs checking ?
-proc ::safe::FileInAccessPath {slave file} {
-    namespace upvar ::safe S$slave state
+proc ::safe::FileInAccessPath {child file} {
+    namespace upvar ::safe [VarName $child] state
     set access_path $state(access_path)
 
     if {[file isdirectory $file]} {
@@ -994,14 +1098,14 @@ proc ::safe::FileInAccessPath {slave file} {
     # potential pathname anomalies.
     set norm_parent [file normalize $parent]
 
-    namespace upvar ::safe S$slave state
+    namespace upvar ::safe [VarName $child] state
     if {$norm_parent ni $state(access_path,norm)} {
        return -code error "\"$file\": not in access_path"
     }
 }
 
-proc ::safe::DirInAccessPath {slave dir} {
-    namespace upvar ::safe S$slave state
+proc ::safe::DirInAccessPath {child dir} {
+    namespace upvar ::safe [VarName $child] state
     set access_path $state(access_path)
 
     if {[file isfile $dir]} {
@@ -1012,7 +1116,7 @@ proc ::safe::DirInAccessPath {slave dir} {
     # potential pathname anomalies.
     set norm_dir [file normalize $dir]
 
-    namespace upvar ::safe S$slave state
+    namespace upvar ::safe [VarName $child] state
     if {$norm_dir ni $state(access_path,norm)} {
        return -code error "\"$dir\": not in access_path"
     }
@@ -1021,16 +1125,16 @@ proc ::safe::DirInAccessPath {slave dir} {
 # This procedure is used to report an attempt to use an unsafe member of an
 # ensemble command.
 
-proc ::safe::BadSubcommand {slave command subcommand args} {
+proc ::safe::BadSubcommand {child command subcommand args} {
     set msg "not allowed to invoke subcommand $subcommand of $command"
-    Log $slave $msg
+    Log $child $msg
     return -code error -errorcode {TCL SAFE SUBCOMMAND} $msg
 }
 
 # AliasEncoding is the target of the "encoding" alias in safe interpreters.
 
-proc ::safe::AliasEncoding {slave option args} {
-    # Note that [encoding dirs] is not supported in safe slaves at all
+proc ::safe::AliasEncoding {child option args} {
+    # Note that [encoding dirs] is not supported in safe children at all
     set subcommands {convertfrom convertto names system}
     try {
        set option [tcl::prefix match -error [list -level 1 -errorcode \
@@ -1041,18 +1145,70 @@ proc ::safe::AliasEncoding {slave option args} {
                "wrong # args: should be \"encoding system\""
        }
     } on error {msg options} {
-       Log $slave $msg
+       Log $child $msg
        return -options $options $msg
     }
-    tailcall ::interp invokehidden $slave encoding $option {*}$args
+    tailcall ::interp invokehidden $child encoding $option {*}$args
 }
 
 # Various minor hiding of platform features. [Bug 2913625]
 
-proc ::safe::AliasExeName {slave} {
+proc ::safe::AliasExeName {child} {
     return ""
 }
 
+# ------------------------------------------------------------------------------
+# Using Interpreter Names with Namespace Qualifiers
+# ------------------------------------------------------------------------------
+# (1) We wish to preserve compatibility with existing code, in which Safe Base
+#     interpreter names have no namespace qualifiers.
+# (2) safe::interpCreate and the rest of the Safe Base previously could not
+#     accept namespace qualifiers in an interpreter name.
+# (3) The interp command will accept namespace qualifiers in an interpreter
+#     name, but accepts distinct interpreters that will have the same command
+#     name (e.g. foo, ::foo, and :::foo) (bug 66c2e8c974).
+# (4) To satisfy these constraints, Safe Base interpreter names will be fully
+#     qualified namespace names with no excess colons and with the leading "::"
+#     omitted.
+# (5) Trailing "::" implies a namespace tail {}, which interp reads as {{}}.
+#     Reject such names.
+# (6) We could:
+#     (a) EITHER reject usable but non-compliant names (e.g. excess colons) in
+#         interpCreate, interpInit;
+#     (b) OR accept such names and then translate to a compliant name in every
+#         command.
+#     The problem with (b) is that the user will expect to use the name with the
+#     interp command and will find that it is not recognised.
+#     E.g "interpCreate ::foo" creates interpreter "foo", and the user's name
+#     "::foo" works with all the Safe Base commands, but "interp eval ::foo"
+#     fails.
+#     So we choose (a).
+# (7) The command
+#         namespace upvar ::safe S$child state
+#     becomes
+#         namespace upvar ::safe [VarName $child] state
+# ------------------------------------------------------------------------------
+
+proc ::safe::RejectExcessColons {child} {
+    set stripped [regsub -all -- {:::*} $child ::]
+    if {[string range $stripped end-1 end] eq {::}} {
+        return -code error {interpreter name must not end in "::"}
+    }
+    if {$stripped ne $child} {
+        set msg {interpreter name has excess colons in namespace separators}
+        return -code error $msg
+    }
+    if {[string range $stripped 0 1] eq {::}} {
+        return -code error {interpreter name must not begin "::"}
+    }
+    return
+}
+
+proc ::safe::VarName {child} {
+    # return S$child
+    return S[string map {:: @N @ @A} $child]
+}
+
 proc ::safe::Setup {} {
     ####
     #
@@ -1111,20 +1267,20 @@ namespace eval ::safe {
     # Log command, set via 'setLogCmd'. Logging is disabled when empty.
     variable Log {}
 
-    # The package maintains a state array per slave interp under its
+    # The package maintains a state array per child interp under its
     # control. The name of this array is S<interp-name>. This array is
     # brought into scope where needed, using 'namespace upvar'. The S
-    # prefix is used to avoid that a slave interp called "Log" smashes
+    # prefix is used to avoid that a child interp called "Log" smashes
     # the "Log" variable.
     #
     # The array's elements are:
     #
-    # access_path       : List of paths accessible to the slave.
+    # access_path       : List of paths accessible to the child.
     # access_path,norm  : Ditto, in normalized form.
-    # access_path,slave : Ditto, as the path tokens as seen by the slave.
+    # access_path,slave : Ditto, as the path tokens as seen by the child.
     # access_path,map   : dict ( token -> path )
     # access_path,remap : dict ( path -> token )
-    # tm_path_slave     : List of TM root directories, as tokens seen by the slave.
+    # tm_path_slave     : List of TM root directories, as tokens seen by the child.
     # staticsok         : Value of option -statics
     # nestedok          : Value of option -nested
     # cleanupHook       : Value of option -deleteHook
index ca93725..a56a0d6 100644 (file)
@@ -9,4 +9,4 @@
 # full path name of this file's directory.
 
 if {![package vsatisfies [package provide Tcl] 8.5-]} {return}
-package ifneeded tcltest 2.5.1 [list source [file join $dir tcltest.tcl]]
+package ifneeded tcltest 2.5.3 [list source [file join $dir tcltest.tcl]]
index a7a68c7..7dc75d7 100644 (file)
@@ -11,8 +11,8 @@
 #      Microsystems.
 #
 # Copyright (c) 1994-1997 Sun Microsystems, Inc.
-# Copyright (c) 1998-1999 by Scriptics Corporation.
-# Copyright (c) 2000 by Ajuba Solutions
+# Copyright (c) 1998-1999 Scriptics Corporation.
+# Copyright (c) 2000 Ajuba Solutions
 # Contributions from Don Porter, NIST, 2002.  (not subject to US copyright)
 # All rights reserved.
 
@@ -22,7 +22,7 @@ namespace eval tcltest {
     # When the version number changes, be sure to update the pkgIndex.tcl file,
     # and the install directory in the Makefiles.  When the minor version
     # changes (new feature) be sure to update the man page as well.
-    variable Version 2.5.1
+    variable Version 2.5.3
 
     # Compatibility support for dumb variables defined in tcltest 1
     # Do not use these.  Call [package provide Tcl] and [info patchlevel]
@@ -41,7 +41,9 @@ namespace eval tcltest {
            outputChannel testConstraint
 
     # Export commands that are duplication (candidates for deprecation)
-    namespace export bytestring                ;# dups [encoding convertfrom identity]
+    if {![package vsatisfies [package provide Tcl] 8.7-]} {
+       namespace export bytestring     ;# dups [encoding convertfrom identity]
+    }
     namespace export debug             ;#      [configure -debug]
     namespace export errorFile         ;#      [configure -errfile]
     namespace export limitConstraints  ;#      [configure -limitconstraints]
@@ -640,7 +642,7 @@ namespace eval tcltest {
 
     proc IsVerbose {level} {
        variable Option
-       return [expr {[lsearch -exact $Option(-verbose) $level] != -1}]
+       return [expr {[lsearch -exact $Option(-verbose) $level] >= 0}]
     }
 
     # Default verbosity is to show bodies of failed tests
@@ -811,14 +813,14 @@ namespace eval tcltest {
     trace add variable Option(-errfile) write \
            [namespace code {errorChannel $Option(-errfile) ;#}]
 
-    proc loadIntoSlaveInterpreter {slave args} {
+    proc loadIntoChildInterpreter {child args} {
        variable Version
-       interp eval $slave [package ifneeded tcltest $Version]
-       interp eval $slave "tcltest::configure {*}{$args}"
-       interp alias $slave ::tcltest::ReportToMaster \
-           {} ::tcltest::ReportedFromSlave
+       interp eval $child [package ifneeded tcltest $Version]
+       interp eval $child "tcltest::configure {*}{$args}"
+       interp alias $child ::tcltest::ReportToParent \
+           {} ::tcltest::ReportedFromChild
     }
-    proc ReportedFromSlave {total passed skipped failed because newfiles} {
+    proc ReportedFromChild {total passed skipped failed because newfiles} {
        variable numTests
        variable skippedBecause
        variable createdNewFiles
@@ -970,7 +972,7 @@ proc tcltest::testConstraint {constraint {value ""}} {
        return $testConstraints($constraint)
     }
     # Check for boolean values
-    if {[catch {expr {$value && $value}} msg]} {
+    if {[catch {expr {$value && 1}} msg]} {
        return -code error $msg
     }
     if {[limitConstraints] && ($constraint ni $Option(-constraints))} {
@@ -1269,7 +1271,7 @@ proc tcltest::DefineConstraintInitializers {} {
 
     ConstraintInitializer nonBlockFiles {
            set code [expr {[catch {set f [open defs r]}]
-                   || [catch {chan configure $f -blocking off}]}]
+                   || [catch {fconfigure $f -blocking off}]}]
            catch {close $f}
            set code
     }
@@ -1982,16 +1984,24 @@ proc tcltest::test {name description args} {
        }
     }
 
-    # First, run the setup script
+    # First, run the setup script (or a hook if it presents):
+    if {[set cmd [namespace which -command [namespace current]::SetupTest]] ne ""} {
+       set setup [list $cmd $setup]
+    }
+    set processTest 1
     set code [catch {uplevel 1 $setup} setupMsg]
     if {$code == 1} {
        set errorInfo(setup) $::errorInfo
        set errorCodeRes(setup) $::errorCode
+       if {$errorCodeRes(setup) eq "BYPASS-SKIPPED-TEST"} {
+           _noticeSkipped $name $setupMsg
+           set processTest [set code 0]
+       }
     }
     set setupFailure [expr {$code != 0}]
 
     # Only run the test body if the setup was successful
-    if {!$setupFailure} {
+    if {$processTest && !$setupFailure} {
 
        # Register startup time
        if {[IsVerbose msec] || [IsVerbose usec]} {
@@ -2014,16 +2024,20 @@ proc tcltest::test {name description args} {
        if {$returnCode == 1} {
            set errorInfo(body) $::errorInfo
            set errorCodeRes(body) $::errorCode
+           if {$errorCodeRes(body) eq "BYPASS-SKIPPED-TEST"} {
+               _noticeSkipped $name $actualAnswer
+               set processTest [set returnCode 0]
+           }
        }
     }
 
     # check if the return code matched the expected return code
     set codeFailure 0
-    if {!$setupFailure && ($returnCode ni $returnCodes)} {
+    if {$processTest && !$setupFailure && ($returnCode ni $returnCodes)} {
        set codeFailure 1
     }
     set errorCodeFailure 0
-    if {!$setupFailure && !$codeFailure && $returnCode == 1 && \
+    if {$processTest && !$setupFailure && !$codeFailure && $returnCode == 1 && \
                 ![string match $errorCode $errorCodeRes(body)]} {
        set errorCodeFailure 1
     }
@@ -2032,7 +2046,7 @@ proc tcltest::test {name description args} {
     # them.  If the comparison fails, then so did the test.
     set outputFailure 0
     variable outData
-    if {[info exists output] && !$codeFailure} {
+    if {$processTest && [info exists output] && !$codeFailure} {
        if {[set outputCompare [catch {
            CompareStrings $outData $output $match
        } outputMatch]] == 0} {
@@ -2044,7 +2058,7 @@ proc tcltest::test {name description args} {
 
     set errorFailure 0
     variable errData
-    if {[info exists errorOutput] && !$codeFailure} {
+    if {$processTest && [info exists errorOutput] && !$codeFailure} {
        if {[set errorCompare [catch {
            CompareStrings $errData $errorOutput $match
        } errorMatch]] == 0} {
@@ -2056,7 +2070,9 @@ proc tcltest::test {name description args} {
 
     # check if the answer matched the expected answer
     # Only check if we ran the body of the test (no setup failure)
-    if {$setupFailure || $codeFailure} {
+    if {!$processTest} {
+       set scriptFailure 0
+    } elseif {$setupFailure || $codeFailure} {
        set scriptFailure 0
     } elseif {[set scriptCompare [catch {
        CompareStrings $actualAnswer $result $match
@@ -2066,7 +2082,10 @@ proc tcltest::test {name description args} {
        set scriptFailure 1
     }
 
-    # Always run the cleanup script
+    # Always run the cleanup script (or a hook if it presents):
+    if {[set cmd [namespace which -command [namespace current]::CleanupTest]] ne ""} {
+       set cleanup [list $cmd $cleanup]
+    }
     set code [catch {uplevel 1 $cleanup} cleanupMsg]
     if {$code == 1} {
        set errorInfo(cleanup) $::errorInfo
@@ -2117,6 +2136,12 @@ proc tcltest::test {name description args} {
        }
     }
 
+    # if skipped, it is safe to return here
+    if {!$processTest} {
+       incr testLevel -1
+       return
+    }
+
     # if we didn't experience any failures, then we passed
     variable numTests
     if {!($setupFailure || $cleanupFailure || $coreFailure
@@ -2177,7 +2202,7 @@ proc tcltest::test {name description args} {
            puts [outputChannel] "---- errorCode(setup): $errorCodeRes(setup)"
        }
     }
-    if {$scriptFailure} {
+    if {$processTest && $scriptFailure} {
        if {$scriptCompare} {
            puts [outputChannel] "---- Error testing result: $scriptMatch"
        } else {
@@ -2244,6 +2269,32 @@ proc tcltest::test {name description args} {
     return
 }
 
+# Skip --
+#
+# Skips a running test and add a reason to skipped "constraints". Can be used
+# to conditional intended abort of the test.
+#
+# Side Effects:  Maintains tally of total tests seen and tests skipped.
+#
+proc tcltest::Skip {reason} {
+    return -code error -errorcode BYPASS-SKIPPED-TEST $reason
+}
+
+proc tcltest::_noticeSkipped {name reason} {
+    variable testLevel
+    variable numTests
+
+    if {[IsVerbose skip]} {
+       puts [outputChannel] "++++ $name SKIPPED: $reason"
+    }
+
+    if {$testLevel == 1} {
+       incr numTests(Skipped)
+       AddToSkippedBecause $reason
+    }
+}
+
+
 # Skipped --
 #
 # Given a test name and it constraints, returns a boolean indicating
@@ -2324,14 +2375,7 @@ proc tcltest::Skipped {name constraints} {
        }
 
        if {!$doTest} {
-           if {[IsVerbose skip]} {
-               puts [outputChannel] "++++ $name SKIPPED: $constraints"
-           }
-
-           if {$testLevel == 1} {
-               incr numTests(Skipped)
-               AddToSkippedBecause $constraints
-           }
+           _noticeSkipped $name $constraints
            return 1
        }
     }
@@ -2354,6 +2398,10 @@ proc tcltest::RunTest {name script} {
        memory tag $name
     }
 
+    # run the test script (or a hook if it presents):
+    if {[set cmd [namespace which -command [namespace current]::EvalTest]] ne ""} {
+       set script [list $cmd $script]
+    }
     set code [catch {uplevel 1 $script} actualAnswer]
 
     return [list $actualAnswer $code]
@@ -2416,8 +2464,8 @@ proc tcltest::cleanupTests {{calledFromAllFile 0}} {
     set testFileName [file tail [info script]]
 
     # Hook to handle reporting to a parent interpreter
-    if {[llength [info commands [namespace current]::ReportToMaster]]} {
-       ReportToMaster $numTests(Total) $numTests(Passed) $numTests(Skipped) \
+    if {[llength [info commands [namespace current]::ReportToParent]]} {
+       ReportToParent $numTests(Total) $numTests(Passed) $numTests(Skipped) \
            $numTests(Failed) [array get skippedBecause] \
            [array get createdNewFiles]
        set testSingleFile false
@@ -2752,7 +2800,6 @@ proc tcltest::runAllTests { {shell ""} } {
     variable numTests
     variable failFiles
     variable DefaultValue
-    set failFilesAccum {}
 
     FillFilesExisted
     if {[llength [info level 0]] == 1} {
@@ -2808,8 +2855,18 @@ proc tcltest::runAllTests { {shell ""} } {
        flush [outputChannel]
 
        if {[singleProcess]} {
-           incr numTestFiles
-           uplevel 1 [list ::source $file]
+           if {[catch {
+               incr numTestFiles
+               uplevel 1 [list ::source $file]
+           } msg]} {
+               puts [outputChannel] "Test file error: $msg"
+               # append the name of the test to a list to be reported
+               # later
+               lappend testFileFailures $file
+           }
+           if {$numTests(Failed) > 0} {
+               set failFilesSet 1
+           }
        } else {
            # Pass along our configuration to the child processes.
            # EXCEPT for the -outfile, because the parent process
@@ -2842,7 +2899,7 @@ proc tcltest::runAllTests { {shell ""} } {
                        }
                        if {$Failed > 0} {
                            lappend failFiles $testFile
-                           lappend failFilesAccum $testFile
+                           set failFilesSet 1
                        }
                    } elseif {[regexp [join {
                            {^Number of tests skipped }
@@ -2889,7 +2946,7 @@ proc tcltest::runAllTests { {shell ""} } {
        puts [outputChannel] ""
        puts [outputChannel] [string repeat ~ 44]
     }
-    return [expr {[info exists testFileFailures] || [llength $failFilesAccum]}]
+    return [expr {[info exists testFileFailures] || [info exists failFilesSet]}]
 }
 
 #####################################################################
@@ -3024,7 +3081,10 @@ proc tcltest::makeFile {contents name {directory ""}} {
             putting ``$contents'' into $fullName"
 
     set fd [open $fullName w]
-    chan configure $fd -translation lf
+    fconfigure $fd -translation lf
+    if {[package vsatisfies [package provide Tcl] 8.7-]} {
+       fconfigure $fd -encoding utf-8
+    }
     if {[string index $contents end] eq "\n"} {
        puts -nonewline $fd $contents
     } else {
@@ -3061,11 +3121,12 @@ proc tcltest::removeFile {name {directory ""}} {
     set fullName [file join $directory $name]
     DebugPuts 3 "[lindex [info level 0] 0]: removing $fullName"
     set idx [lsearch -exact $filesMade $fullName]
-    set filesMade [lreplace $filesMade $idx $idx]
-    if {$idx == -1} {
+    if {$idx < 0} {
        DebugDo 1 {
            Warn "removeFile removing \"$fullName\":\n  not created by makeFile"
        }
+    } else {
+       set filesMade [lreplace $filesMade $idx $idx]
     }
     if {![file isfile $fullName]} {
        DebugDo 1 {
@@ -3137,7 +3198,7 @@ proc tcltest::removeDirectory {name {directory ""}} {
     DebugPuts 3 "[lindex [info level 0] 0]: deleting $fullName"
     set idx [lsearch -exact $filesMade $fullName]
     set filesMade [lreplace $filesMade $idx $idx]
-    if {$idx == -1} {
+    if {$idx < 0} {
        DebugDo 1 {
            Warn "removeDirectory removing \"$fullName\":\n  not created\
                    by makeDirectory"
@@ -3172,6 +3233,9 @@ proc tcltest::viewFile {name {directory ""}} {
     }
     set fullName [file join $directory $name]
     set f [open $fullName]
+    if {[package vsatisfies [package provide Tcl] 8.7-]} {
+       fconfigure $f -encoding utf-8
+    }
     set data [read -nonewline $f]
     close $f
     return $data
@@ -3186,13 +3250,16 @@ proc tcltest::viewFile {name {directory ""}} {
 #    procedures that are supposed to accept strings with embedded NULL
 #    bytes.
 # 2. Confirm that a string result has a certain pattern of bytes, for
-#    instance to confirm that "\xe0\0" in a Tcl script is stored
-#    internally in UTF-8 as the sequence of bytes "\xc3\xa0\xc0\x80".
+#    instance to confirm that "\xE0\0" in a Tcl script is stored
+#    internally in UTF-8 as the sequence of bytes "\xC3\xA0\xC0\x80".
 #
 # Generally, it's a bad idea to examine the bytes in a Tcl string or to
 # construct improperly formed strings in this manner, because it involves
 # exposing that Tcl uses UTF-8 internally.
 #
+# This function doesn't work any more in Tcl 8.7, since the 'identity'
+# is gone (TIP #345)
+#
 # Arguments:
 #      string being converted
 #
@@ -3202,8 +3269,10 @@ proc tcltest::viewFile {name {directory ""}} {
 # Side effects:
 #      None
 
-proc tcltest::bytestring {string} {
-    return [encoding convertfrom identity $string]
+if {![package vsatisfies [package provide Tcl] 8.7-]} {
+    proc tcltest::bytestring {string} {
+       return [encoding convertfrom identity $string]
+    }
 }
 
 # tcltest::OpenFiles --
index 1802bb9..c60084c 100644 (file)
@@ -212,11 +212,12 @@ proc ::tcl::tm::UnknownHandler {original name args} {
            }
            set strip [llength [file split $path]]
 
-           # We can't use glob in safe interps, so enclose the following in a
-           # catch statement, where we get the module files out of the
-           # subdirectories. In other words, Tcl Modules are not-functional
-           # in such an interpreter. This is the same as for the command
-           # "tclPkgUnknown", i.e. the search for regular packages.
+           # Get the module files out of the subdirectories.
+           # - Safe Base interpreters have a restricted "glob" command that
+           #   works in this case.
+           # - The "catch" was essential when there was no safe glob and every
+           #   call in a safe interp failed; it is retained only for corner
+           #   cases in which the eventual call to glob returns an error.
 
            catch {
                # We always look for _all_ possible modules in the current
@@ -238,12 +239,16 @@ proc ::tcl::tm::UnknownHandler {original name args} {
                        continue
                    }
 
-                   if {[package ifneeded $pkgname $pkgversion] ne {}} {
+                   if {([package ifneeded $pkgname $pkgversion] ne {})
+                           && (![interp issafe])
+                   } {
                        # There's already a provide script registered for
                        # this version of this package.  Since all units of
                        # code claiming to be the same version of the same
                        # package ought to be identical, just stick with
                        # the one we already have.
+                       # This does not apply to Safe Base interpreters because
+                       # the token-to-directory mapping may have changed.
                        continue
                    }
 
index f43f751..3f755f6 100644 (file)
@@ -2,51 +2,65 @@
 
 set TZData(:Africa/Accra) {
     {-9223372036854775808 -52 0 LMT}
-    {-1640995148 0 0 GMT}
-    {-1556841600 1200 1 GMT}
-    {-1546388400 0 0 GMT}
-    {-1525305600 1200 1 GMT}
-    {-1514852400 0 0 GMT}
-    {-1493769600 1200 1 GMT}
-    {-1483316400 0 0 GMT}
-    {-1462233600 1200 1 GMT}
-    {-1451780400 0 0 GMT}
-    {-1430611200 1200 1 GMT}
-    {-1420158000 0 0 GMT}
-    {-1399075200 1200 1 GMT}
-    {-1388622000 0 0 GMT}
-    {-1367539200 1200 1 GMT}
-    {-1357086000 0 0 GMT}
-    {-1336003200 1200 1 GMT}
-    {-1325550000 0 0 GMT}
-    {-1304380800 1200 1 GMT}
-    {-1293927600 0 0 GMT}
-    {-1272844800 1200 1 GMT}
-    {-1262391600 0 0 GMT}
-    {-1241308800 1200 1 GMT}
-    {-1230855600 0 0 GMT}
-    {-1209772800 1200 1 GMT}
-    {-1199319600 0 0 GMT}
-    {-1178150400 1200 1 GMT}
-    {-1167697200 0 0 GMT}
-    {-1146614400 1200 1 GMT}
-    {-1136161200 0 0 GMT}
-    {-1115078400 1200 1 GMT}
-    {-1104625200 0 0 GMT}
-    {-1083542400 1200 1 GMT}
-    {-1073089200 0 0 GMT}
-    {-1051920000 1200 1 GMT}
-    {-1041466800 0 0 GMT}
-    {-1020384000 1200 1 GMT}
-    {-1009930800 0 0 GMT}
-    {-988848000 1200 1 GMT}
-    {-978394800 0 0 GMT}
-    {-957312000 1200 1 GMT}
-    {-946858800 0 0 GMT}
-    {-925689600 1200 1 GMT}
-    {-915236400 0 0 GMT}
-    {-894153600 1200 1 GMT}
-    {-883700400 0 0 GMT}
-    {-862617600 1200 1 GMT}
-    {-852164400 0 0 GMT}
+    {-1709337548 0 0 GMT}
+    {-1581206400 1200 1 +0020}
+    {-1577917200 0 0 GMT}
+    {-1556834400 1200 1 +0020}
+    {-1546294800 0 0 GMT}
+    {-1525298400 1200 1 +0020}
+    {-1514758800 0 0 GMT}
+    {-1493762400 1200 1 +0020}
+    {-1483222800 0 0 GMT}
+    {-1462226400 1200 1 +0020}
+    {-1451686800 0 0 GMT}
+    {-1430604000 1200 1 +0020}
+    {-1420064400 0 0 GMT}
+    {-1399068000 1200 1 +0020}
+    {-1388528400 0 0 GMT}
+    {-1367532000 1200 1 +0020}
+    {-1356992400 0 0 GMT}
+    {-1335996000 1200 1 +0020}
+    {-1325456400 0 0 GMT}
+    {-1304373600 1200 1 +0020}
+    {-1293834000 0 0 GMT}
+    {-1272837600 1200 1 +0020}
+    {-1262298000 0 0 GMT}
+    {-1241301600 1200 1 +0020}
+    {-1230762000 0 0 GMT}
+    {-1209765600 1200 1 +0020}
+    {-1199226000 0 0 GMT}
+    {-1178143200 1200 1 +0020}
+    {-1167603600 0 0 GMT}
+    {-1146607200 1200 1 +0020}
+    {-1136067600 0 0 GMT}
+    {-1115071200 1200 1 +0020}
+    {-1104531600 0 0 GMT}
+    {-1083535200 1200 1 +0020}
+    {-1072995600 0 0 GMT}
+    {-1051912800 1200 1 +0020}
+    {-1041373200 0 0 GMT}
+    {-1020376800 1200 1 +0020}
+    {-1009837200 0 0 GMT}
+    {-988840800 1200 1 +0020}
+    {-978301200 0 0 GMT}
+    {-957304800 1200 1 +0020}
+    {-946765200 0 0 GMT}
+    {-936309600 1200 1 +0020}
+    {-915142800 0 0 GMT}
+    {-904773600 1200 1 +0020}
+    {-883606800 0 0 GMT}
+    {-880329600 1800 0 +0030}
+    {-756952200 0 0 GMT}
+    {-610149600 1800 1 +0030}
+    {-599610600 0 0 GMT}
+    {-578613600 1800 1 +0030}
+    {-568074600 0 0 GMT}
+    {-546991200 1800 1 +0030}
+    {-536452200 0 0 GMT}
+    {-515455200 1800 1 +0030}
+    {-504916200 0 0 GMT}
+    {-483919200 1800 1 +0030}
+    {-473380200 0 0 GMT}
+    {-452383200 1800 1 +0030}
+    {-441844200 0 0 GMT}
 }
index fe4de22..b26d31c 100644 (file)
@@ -2,7 +2,7 @@
 
 set TZData(:Africa/Algiers) {
     {-9223372036854775808 732 0 LMT}
-    {-2486679072 561 0 PMT}
+    {-2486592732 561 0 PMT}
     {-1855958961 0 0 WET}
     {-1689814800 3600 1 WEST}
     {-1680397200 0 0 WET}
index 99027c9..cb60740 100644 (file)
@@ -60,13 +60,13 @@ set TZData(:Africa/Casablanca) {
     {1557021600 0 1 +01}
     {1560045600 3600 0 +01}
     {1587261600 0 1 +01}
-    {1590285600 3600 0 +01}
+    {1590890400 3600 0 +01}
     {1618106400 0 1 +01}
     {1621130400 3600 0 +01}
     {1648346400 0 1 +01}
     {1651975200 3600 0 +01}
     {1679191200 0 1 +01}
-    {1682215200 3600 0 +01}
+    {1682820000 3600 0 +01}
     {1710036000 0 1 +01}
     {1713060000 3600 0 +01}
     {1740276000 0 1 +01}
@@ -76,13 +76,13 @@ set TZData(:Africa/Casablanca) {
     {1801965600 0 1 +01}
     {1804989600 3600 0 +01}
     {1832205600 0 1 +01}
-    {1835229600 3600 0 +01}
+    {1835834400 3600 0 +01}
     {1863050400 0 1 +01}
     {1866074400 3600 0 +01}
     {1893290400 0 1 +01}
     {1896919200 3600 0 +01}
     {1924135200 0 1 +01}
-    {1927159200 3600 0 +01}
+    {1927764000 3600 0 +01}
     {1954980000 0 1 +01}
     {1958004000 3600 0 +01}
     {1985220000 0 1 +01}
@@ -92,13 +92,13 @@ set TZData(:Africa/Casablanca) {
     {2046304800 0 1 +01}
     {2049933600 3600 0 +01}
     {2077149600 0 1 +01}
-    {2080173600 3600 0 +01}
+    {2080778400 3600 0 +01}
     {2107994400 0 1 +01}
     {2111018400 3600 0 +01}
     {2138234400 0 1 +01}
     {2141863200 3600 0 +01}
     {2169079200 0 1 +01}
-    {2172103200 3600 0 +01}
+    {2172708000 3600 0 +01}
     {2199924000 0 1 +01}
     {2202948000 3600 0 +01}
     {2230164000 0 1 +01}
@@ -108,13 +108,13 @@ set TZData(:Africa/Casablanca) {
     {2291248800 0 1 +01}
     {2294877600 3600 0 +01}
     {2322093600 0 1 +01}
-    {2325117600 3600 0 +01}
+    {2325722400 3600 0 +01}
     {2352938400 0 1 +01}
     {2355962400 3600 0 +01}
     {2383178400 0 1 +01}
     {2386807200 3600 0 +01}
     {2414023200 0 1 +01}
-    {2417047200 3600 0 +01}
+    {2417652000 3600 0 +01}
     {2444868000 0 1 +01}
     {2447892000 3600 0 +01}
     {2475108000 0 1 +01}
@@ -124,13 +124,13 @@ set TZData(:Africa/Casablanca) {
     {2536192800 0 1 +01}
     {2539821600 3600 0 +01}
     {2567037600 0 1 +01}
-    {2570061600 3600 0 +01}
+    {2570666400 3600 0 +01}
     {2597882400 0 1 +01}
     {2600906400 3600 0 +01}
     {2628122400 0 1 +01}
     {2631751200 3600 0 +01}
     {2658967200 0 1 +01}
-    {2661991200 3600 0 +01}
+    {2662596000 3600 0 +01}
     {2689812000 0 1 +01}
     {2692836000 3600 0 +01}
     {2720052000 0 1 +01}
@@ -140,63 +140,63 @@ set TZData(:Africa/Casablanca) {
     {2781136800 0 1 +01}
     {2784765600 3600 0 +01}
     {2811981600 0 1 +01}
-    {2815005600 3600 0 +01}
+    {2815610400 3600 0 +01}
     {2842826400 0 1 +01}
     {2845850400 3600 0 +01}
     {2873066400 0 1 +01}
     {2876695200 3600 0 +01}
     {2903911200 0 1 +01}
-    {2906935200 3600 0 +01}
+    {2907540000 3600 0 +01}
     {2934756000 0 1 +01}
     {2937780000 3600 0 +01}
     {2964996000 0 1 +01}
-    {2968020000 3600 0 +01}
+    {2968624800 3600 0 +01}
     {2995840800 0 1 +01}
     {2998864800 3600 0 +01}
     {3026080800 0 1 +01}
     {3029709600 3600 0 +01}
     {3056925600 0 1 +01}
-    {3059949600 3600 0 +01}
+    {3060554400 3600 0 +01}
     {3087770400 0 1 +01}
     {3090794400 3600 0 +01}
     {3118010400 0 1 +01}
     {3121639200 3600 0 +01}
     {3148855200 0 1 +01}
-    {3151879200 3600 0 +01}
+    {3152484000 3600 0 +01}
     {3179700000 0 1 +01}
     {3182724000 3600 0 +01}
     {3209940000 0 1 +01}
-    {3212964000 3600 0 +01}
+    {3213568800 3600 0 +01}
     {3240784800 0 1 +01}
     {3243808800 3600 0 +01}
     {3271024800 0 1 +01}
     {3274653600 3600 0 +01}
     {3301869600 0 1 +01}
-    {3304893600 3600 0 +01}
+    {3305498400 3600 0 +01}
     {3332714400 0 1 +01}
     {3335738400 3600 0 +01}
     {3362954400 0 1 +01}
     {3366583200 3600 0 +01}
     {3393799200 0 1 +01}
-    {3396823200 3600 0 +01}
+    {3397428000 3600 0 +01}
     {3424644000 0 1 +01}
     {3427668000 3600 0 +01}
     {3454884000 0 1 +01}
-    {3457908000 3600 0 +01}
+    {3458512800 3600 0 +01}
     {3485728800 0 1 +01}
     {3488752800 3600 0 +01}
     {3515968800 0 1 +01}
     {3519597600 3600 0 +01}
     {3546813600 0 1 +01}
-    {3549837600 3600 0 +01}
+    {3550442400 3600 0 +01}
     {3577658400 0 1 +01}
     {3580682400 3600 0 +01}
     {3607898400 0 1 +01}
     {3611527200 3600 0 +01}
     {3638743200 0 1 +01}
-    {3641767200 3600 0 +01}
+    {3642372000 3600 0 +01}
     {3669588000 0 1 +01}
     {3672612000 3600 0 +01}
     {3699828000 0 1 +01}
-    {3702852000 3600 0 +01}
+    {3703456800 3600 0 +01}
 }
index 9f021a4..fd3e88f 100644 (file)
@@ -49,13 +49,13 @@ set TZData(:Africa/El_Aaiun) {
     {1557021600 0 1 +01}
     {1560045600 3600 0 +01}
     {1587261600 0 1 +01}
-    {1590285600 3600 0 +01}
+    {1590890400 3600 0 +01}
     {1618106400 0 1 +01}
     {1621130400 3600 0 +01}
     {1648346400 0 1 +01}
     {1651975200 3600 0 +01}
     {1679191200 0 1 +01}
-    {1682215200 3600 0 +01}
+    {1682820000 3600 0 +01}
     {1710036000 0 1 +01}
     {1713060000 3600 0 +01}
     {1740276000 0 1 +01}
@@ -65,13 +65,13 @@ set TZData(:Africa/El_Aaiun) {
     {1801965600 0 1 +01}
     {1804989600 3600 0 +01}
     {1832205600 0 1 +01}
-    {1835229600 3600 0 +01}
+    {1835834400 3600 0 +01}
     {1863050400 0 1 +01}
     {1866074400 3600 0 +01}
     {1893290400 0 1 +01}
     {1896919200 3600 0 +01}
     {1924135200 0 1 +01}
-    {1927159200 3600 0 +01}
+    {1927764000 3600 0 +01}
     {1954980000 0 1 +01}
     {1958004000 3600 0 +01}
     {1985220000 0 1 +01}
@@ -81,13 +81,13 @@ set TZData(:Africa/El_Aaiun) {
     {2046304800 0 1 +01}
     {2049933600 3600 0 +01}
     {2077149600 0 1 +01}
-    {2080173600 3600 0 +01}
+    {2080778400 3600 0 +01}
     {2107994400 0 1 +01}
     {2111018400 3600 0 +01}
     {2138234400 0 1 +01}
     {2141863200 3600 0 +01}
     {2169079200 0 1 +01}
-    {2172103200 3600 0 +01}
+    {2172708000 3600 0 +01}
     {2199924000 0 1 +01}
     {2202948000 3600 0 +01}
     {2230164000 0 1 +01}
@@ -97,13 +97,13 @@ set TZData(:Africa/El_Aaiun) {
     {2291248800 0 1 +01}
     {2294877600 3600 0 +01}
     {2322093600 0 1 +01}
-    {2325117600 3600 0 +01}
+    {2325722400 3600 0 +01}
     {2352938400 0 1 +01}
     {2355962400 3600 0 +01}
     {2383178400 0 1 +01}
     {2386807200 3600 0 +01}
     {2414023200 0 1 +01}
-    {2417047200 3600 0 +01}
+    {2417652000 3600 0 +01}
     {2444868000 0 1 +01}
     {2447892000 3600 0 +01}
     {2475108000 0 1 +01}
@@ -113,13 +113,13 @@ set TZData(:Africa/El_Aaiun) {
     {2536192800 0 1 +01}
     {2539821600 3600 0 +01}
     {2567037600 0 1 +01}
-    {2570061600 3600 0 +01}
+    {2570666400 3600 0 +01}
     {2597882400 0 1 +01}
     {2600906400 3600 0 +01}
     {2628122400 0 1 +01}
     {2631751200 3600 0 +01}
     {2658967200 0 1 +01}
-    {2661991200 3600 0 +01}
+    {2662596000 3600 0 +01}
     {2689812000 0 1 +01}
     {2692836000 3600 0 +01}
     {2720052000 0 1 +01}
@@ -129,63 +129,63 @@ set TZData(:Africa/El_Aaiun) {
     {2781136800 0 1 +01}
     {2784765600 3600 0 +01}
     {2811981600 0 1 +01}
-    {2815005600 3600 0 +01}
+    {2815610400 3600 0 +01}
     {2842826400 0 1 +01}
     {2845850400 3600 0 +01}
     {2873066400 0 1 +01}
     {2876695200 3600 0 +01}
     {2903911200 0 1 +01}
-    {2906935200 3600 0 +01}
+    {2907540000 3600 0 +01}
     {2934756000 0 1 +01}
     {2937780000 3600 0 +01}
     {2964996000 0 1 +01}
-    {2968020000 3600 0 +01}
+    {2968624800 3600 0 +01}
     {2995840800 0 1 +01}
     {2998864800 3600 0 +01}
     {3026080800 0 1 +01}
     {3029709600 3600 0 +01}
     {3056925600 0 1 +01}
-    {3059949600 3600 0 +01}
+    {3060554400 3600 0 +01}
     {3087770400 0 1 +01}
     {3090794400 3600 0 +01}
     {3118010400 0 1 +01}
     {3121639200 3600 0 +01}
     {3148855200 0 1 +01}
-    {3151879200 3600 0 +01}
+    {3152484000 3600 0 +01}
     {3179700000 0 1 +01}
     {3182724000 3600 0 +01}
     {3209940000 0 1 +01}
-    {3212964000 3600 0 +01}
+    {3213568800 3600 0 +01}
     {3240784800 0 1 +01}
     {3243808800 3600 0 +01}
     {3271024800 0 1 +01}
     {3274653600 3600 0 +01}
     {3301869600 0 1 +01}
-    {3304893600 3600 0 +01}
+    {3305498400 3600 0 +01}
     {3332714400 0 1 +01}
     {3335738400 3600 0 +01}
     {3362954400 0 1 +01}
     {3366583200 3600 0 +01}
     {3393799200 0 1 +01}
-    {3396823200 3600 0 +01}
+    {3397428000 3600 0 +01}
     {3424644000 0 1 +01}
     {3427668000 3600 0 +01}
     {3454884000 0 1 +01}
-    {3457908000 3600 0 +01}
+    {3458512800 3600 0 +01}
     {3485728800 0 1 +01}
     {3488752800 3600 0 +01}
     {3515968800 0 1 +01}
     {3519597600 3600 0 +01}
     {3546813600 0 1 +01}
-    {3549837600 3600 0 +01}
+    {3550442400 3600 0 +01}
     {3577658400 0 1 +01}
     {3580682400 3600 0 +01}
     {3607898400 0 1 +01}
     {3611527200 3600 0 +01}
     {3638743200 0 1 +01}
-    {3641767200 3600 0 +01}
+    {3642372000 3600 0 +01}
     {3669588000 0 1 +01}
     {3672612000 3600 0 +01}
     {3699828000 0 1 +01}
-    {3702852000 3600 0 +01}
+    {3703456800 3600 0 +01}
 }
index 079572f..8750661 100644 (file)
@@ -1,6 +1,9 @@
 # created by tools/tclZIC.tcl - do not edit
 
 set TZData(:Africa/Lagos) {
-    {-9223372036854775808 816 0 LMT}
-    {-1588464816 3600 0 WAT}
+    {-9223372036854775808 815 0 LMT}
+    {-2035584815 0 0 GMT}
+    {-1940889600 815 0 LMT}
+    {-1767226415 1800 0 +0030}
+    {-1588465800 3600 0 WAT}
 }
index 715dc45..b4c3b97 100644 (file)
@@ -2,8 +2,9 @@
 
 set TZData(:Africa/Nairobi) {
     {-9223372036854775808 8836 0 LMT}
-    {-1309746436 10800 0 EAT}
-    {-1262314800 9000 0 +0230}
-    {-946780200 9900 0 +0245}
-    {-315629100 10800 0 EAT}
+    {-1946168836 9000 0 +0230}
+    {-1309746600 10800 0 EAT}
+    {-1261969200 9000 0 +0230}
+    {-1041388200 9900 0 +0245}
+    {-865305900 10800 0 EAT}
 }
index 5b46388..3b3f9e4 100644 (file)
@@ -51,8 +51,51 @@ set TZData(:America/Belize) {
     {-911759400 -21600 0 CST}
     {-891194400 -19800 1 -0530}
     {-879705000 -21600 0 CST}
-    {-859744800 -19800 1 -0530}
-    {-848255400 -21600 0 CST}
+    {-868212000 -18000 1 CWT}
+    {-769395600 -18000 1 CPT}
+    {-758746800 -21600 0 CST}
+    {-701892000 -19800 1 -0530}
+    {-690402600 -21600 0 CST}
+    {-670442400 -19800 1 -0530}
+    {-658953000 -21600 0 CST}
+    {-638992800 -19800 1 -0530}
+    {-627503400 -21600 0 CST}
+    {-606938400 -19800 1 -0530}
+    {-596053800 -21600 0 CST}
+    {-575488800 -19800 1 -0530}
+    {-564604200 -21600 0 CST}
+    {-544039200 -19800 1 -0530}
+    {-532549800 -21600 0 CST}
+    {-512589600 -19800 1 -0530}
+    {-501100200 -21600 0 CST}
+    {-481140000 -19800 1 -0530}
+    {-469650600 -21600 0 CST}
+    {-449690400 -19800 1 -0530}
+    {-438201000 -21600 0 CST}
+    {-417636000 -19800 1 -0530}
+    {-406751400 -21600 0 CST}
+    {-386186400 -19800 1 -0530}
+    {-375301800 -21600 0 CST}
+    {-354736800 -19800 1 -0530}
+    {-343247400 -21600 0 CST}
+    {-323287200 -19800 1 -0530}
+    {-311797800 -21600 0 CST}
+    {-291837600 -19800 1 -0530}
+    {-280348200 -21600 0 CST}
+    {-259783200 -19800 1 -0530}
+    {-248898600 -21600 0 CST}
+    {-228333600 -19800 1 -0530}
+    {-217449000 -21600 0 CST}
+    {-196884000 -19800 1 -0530}
+    {-185999400 -21600 0 CST}
+    {-165434400 -19800 1 -0530}
+    {-153945000 -21600 0 CST}
+    {-133984800 -19800 1 -0530}
+    {-122495400 -21600 0 CST}
+    {-102535200 -19800 1 -0530}
+    {-91045800 -21600 0 CST}
+    {-70480800 -19800 1 -0530}
+    {-59596200 -21600 0 CST}
     {123919200 -18000 1 CDT}
     {129618000 -21600 0 CST}
     {409039200 -18000 1 CDT}
index 8d2b641..c8e3f26 100644 (file)
@@ -94,163 +94,5 @@ set TZData(:America/Dawson) {
     {1552212000 -25200 1 PDT}
     {1572771600 -28800 0 PST}
     {1583661600 -25200 1 PDT}
-    {1604221200 -28800 0 PST}
-    {1615716000 -25200 1 PDT}
-    {1636275600 -28800 0 PST}
-    {1647165600 -25200 1 PDT}
-    {1667725200 -28800 0 PST}
-    {1678615200 -25200 1 PDT}
-    {1699174800 -28800 0 PST}
-    {1710064800 -25200 1 PDT}
-    {1730624400 -28800 0 PST}
-    {1741514400 -25200 1 PDT}
-    {1762074000 -28800 0 PST}
-    {1772964000 -25200 1 PDT}
-    {1793523600 -28800 0 PST}
-    {1805018400 -25200 1 PDT}
-    {1825578000 -28800 0 PST}
-    {1836468000 -25200 1 PDT}
-    {1857027600 -28800 0 PST}
-    {1867917600 -25200 1 PDT}
-    {1888477200 -28800 0 PST}
-    {1899367200 -25200 1 PDT}
-    {1919926800 -28800 0 PST}
-    {1930816800 -25200 1 PDT}
-    {1951376400 -28800 0 PST}
-    {1962871200 -25200 1 PDT}
-    {1983430800 -28800 0 PST}
-    {1994320800 -25200 1 PDT}
-    {2014880400 -28800 0 PST}
-    {2025770400 -25200 1 PDT}
-    {2046330000 -28800 0 PST}
-    {2057220000 -25200 1 PDT}
-    {2077779600 -28800 0 PST}
-    {2088669600 -25200 1 PDT}
-    {2109229200 -28800 0 PST}
-    {2120119200 -25200 1 PDT}
-    {2140678800 -28800 0 PST}
-    {2152173600 -25200 1 PDT}
-    {2172733200 -28800 0 PST}
-    {2183623200 -25200 1 PDT}
-    {2204182800 -28800 0 PST}
-    {2215072800 -25200 1 PDT}
-    {2235632400 -28800 0 PST}
-    {2246522400 -25200 1 PDT}
-    {2267082000 -28800 0 PST}
-    {2277972000 -25200 1 PDT}
-    {2298531600 -28800 0 PST}
-    {2309421600 -25200 1 PDT}
-    {2329981200 -28800 0 PST}
-    {2341476000 -25200 1 PDT}
-    {2362035600 -28800 0 PST}
-    {2372925600 -25200 1 PDT}
-    {2393485200 -28800 0 PST}
-    {2404375200 -25200 1 PDT}
-    {2424934800 -28800 0 PST}
-    {2435824800 -25200 1 PDT}
-    {2456384400 -28800 0 PST}
-    {2467274400 -25200 1 PDT}
-    {2487834000 -28800 0 PST}
-    {2499328800 -25200 1 PDT}
-    {2519888400 -28800 0 PST}
-    {2530778400 -25200 1 PDT}
-    {2551338000 -28800 0 PST}
-    {2562228000 -25200 1 PDT}
-    {2582787600 -28800 0 PST}
-    {2593677600 -25200 1 PDT}
-    {2614237200 -28800 0 PST}
-    {2625127200 -25200 1 PDT}
-    {2645686800 -28800 0 PST}
-    {2656576800 -25200 1 PDT}
-    {2677136400 -28800 0 PST}
-    {2688631200 -25200 1 PDT}
-    {2709190800 -28800 0 PST}
-    {2720080800 -25200 1 PDT}
-    {2740640400 -28800 0 PST}
-    {2751530400 -25200 1 PDT}
-    {2772090000 -28800 0 PST}
-    {2782980000 -25200 1 PDT}
-    {2803539600 -28800 0 PST}
-    {2814429600 -25200 1 PDT}
-    {2834989200 -28800 0 PST}
-    {2846484000 -25200 1 PDT}
-    {2867043600 -28800 0 PST}
-    {2877933600 -25200 1 PDT}
-    {2898493200 -28800 0 PST}
-    {2909383200 -25200 1 PDT}
-    {2929942800 -28800 0 PST}
-    {2940832800 -25200 1 PDT}
-    {2961392400 -28800 0 PST}
-    {2972282400 -25200 1 PDT}
-    {2992842000 -28800 0 PST}
-    {3003732000 -25200 1 PDT}
-    {3024291600 -28800 0 PST}
-    {3035786400 -25200 1 PDT}
-    {3056346000 -28800 0 PST}
-    {3067236000 -25200 1 PDT}
-    {3087795600 -28800 0 PST}
-    {3098685600 -25200 1 PDT}
-    {3119245200 -28800 0 PST}
-    {3130135200 -25200 1 PDT}
-    {3150694800 -28800 0 PST}
-    {3161584800 -25200 1 PDT}
-    {3182144400 -28800 0 PST}
-    {3193034400 -25200 1 PDT}
-    {3213594000 -28800 0 PST}
-    {3225088800 -25200 1 PDT}
-    {3245648400 -28800 0 PST}
-    {3256538400 -25200 1 PDT}
-    {3277098000 -28800 0 PST}
-    {3287988000 -25200 1 PDT}
-    {3308547600 -28800 0 PST}
-    {3319437600 -25200 1 PDT}
-    {3339997200 -28800 0 PST}
-    {3350887200 -25200 1 PDT}
-    {3371446800 -28800 0 PST}
-    {3382941600 -25200 1 PDT}
-    {3403501200 -28800 0 PST}
-    {3414391200 -25200 1 PDT}
-    {3434950800 -28800 0 PST}
-    {3445840800 -25200 1 PDT}
-    {3466400400 -28800 0 PST}
-    {3477290400 -25200 1 PDT}
-    {3497850000 -28800 0 PST}
-    {3508740000 -25200 1 PDT}
-    {3529299600 -28800 0 PST}
-    {3540189600 -25200 1 PDT}
-    {3560749200 -28800 0 PST}
-    {3572244000 -25200 1 PDT}
-    {3592803600 -28800 0 PST}
-    {3603693600 -25200 1 PDT}
-    {3624253200 -28800 0 PST}
-    {3635143200 -25200 1 PDT}
-    {3655702800 -28800 0 PST}
-    {3666592800 -25200 1 PDT}
-    {3687152400 -28800 0 PST}
-    {3698042400 -25200 1 PDT}
-    {3718602000 -28800 0 PST}
-    {3730096800 -25200 1 PDT}
-    {3750656400 -28800 0 PST}
-    {3761546400 -25200 1 PDT}
-    {3782106000 -28800 0 PST}
-    {3792996000 -25200 1 PDT}
-    {3813555600 -28800 0 PST}
-    {3824445600 -25200 1 PDT}
-    {3845005200 -28800 0 PST}
-    {3855895200 -25200 1 PDT}
-    {3876454800 -28800 0 PST}
-    {3887344800 -25200 1 PDT}
-    {3907904400 -28800 0 PST}
-    {3919399200 -25200 1 PDT}
-    {3939958800 -28800 0 PST}
-    {3950848800 -25200 1 PDT}
-    {3971408400 -28800 0 PST}
-    {3982298400 -25200 1 PDT}
-    {4002858000 -28800 0 PST}
-    {4013748000 -25200 1 PDT}
-    {4034307600 -28800 0 PST}
-    {4045197600 -25200 1 PDT}
-    {4065757200 -28800 0 PST}
-    {4076647200 -25200 1 PDT}
-    {4097206800 -28800 0 PST}
+    {1604217600 -25200 0 MST}
 }
index 3e45f87..8bb7b73 100644 (file)
@@ -1,246 +1,5 @@
 # created by tools/tclZIC.tcl - do not edit
-
-set TZData(:America/Godthab) {
-    {-9223372036854775808 -12416 0 LMT}
-    {-1686083584 -10800 0 -03}
-    {323845200 -7200 0 -02}
-    {338950800 -10800 0 -03}
-    {354675600 -7200 1 -02}
-    {370400400 -10800 0 -03}
-    {386125200 -7200 1 -02}
-    {401850000 -10800 0 -03}
-    {417574800 -7200 1 -02}
-    {433299600 -10800 0 -03}
-    {449024400 -7200 1 -02}
-    {465354000 -10800 0 -03}
-    {481078800 -7200 1 -02}
-    {496803600 -10800 0 -03}
-    {512528400 -7200 1 -02}
-    {528253200 -10800 0 -03}
-    {543978000 -7200 1 -02}
-    {559702800 -10800 0 -03}
-    {575427600 -7200 1 -02}
-    {591152400 -10800 0 -03}
-    {606877200 -7200 1 -02}
-    {622602000 -10800 0 -03}
-    {638326800 -7200 1 -02}
-    {654656400 -10800 0 -03}
-    {670381200 -7200 1 -02}
-    {686106000 -10800 0 -03}
-    {701830800 -7200 1 -02}
-    {717555600 -10800 0 -03}
-    {733280400 -7200 1 -02}
-    {749005200 -10800 0 -03}
-    {764730000 -7200 1 -02}
-    {780454800 -10800 0 -03}
-    {796179600 -7200 1 -02}
-    {811904400 -10800 0 -03}
-    {828234000 -7200 1 -02}
-    {846378000 -10800 0 -03}
-    {859683600 -7200 1 -02}
-    {877827600 -10800 0 -03}
-    {891133200 -7200 1 -02}
-    {909277200 -10800 0 -03}
-    {922582800 -7200 1 -02}
-    {941331600 -10800 0 -03}
-    {954032400 -7200 1 -02}
-    {972781200 -10800 0 -03}
-    {985482000 -7200 1 -02}
-    {1004230800 -10800 0 -03}
-    {1017536400 -7200 1 -02}
-    {1035680400 -10800 0 -03}
-    {1048986000 -7200 1 -02}
-    {1067130000 -10800 0 -03}
-    {1080435600 -7200 1 -02}
-    {1099184400 -10800 0 -03}
-    {1111885200 -7200 1 -02}
-    {1130634000 -10800 0 -03}
-    {1143334800 -7200 1 -02}
-    {1162083600 -10800 0 -03}
-    {1174784400 -7200 1 -02}
-    {1193533200 -10800 0 -03}
-    {1206838800 -7200 1 -02}
-    {1224982800 -10800 0 -03}
-    {1238288400 -7200 1 -02}
-    {1256432400 -10800 0 -03}
-    {1269738000 -7200 1 -02}
-    {1288486800 -10800 0 -03}
-    {1301187600 -7200 1 -02}
-    {1319936400 -10800 0 -03}
-    {1332637200 -7200 1 -02}
-    {1351386000 -10800 0 -03}
-    {1364691600 -7200 1 -02}
-    {1382835600 -10800 0 -03}
-    {1396141200 -7200 1 -02}
-    {1414285200 -10800 0 -03}
-    {1427590800 -7200 1 -02}
-    {1445734800 -10800 0 -03}
-    {1459040400 -7200 1 -02}
-    {1477789200 -10800 0 -03}
-    {1490490000 -7200 1 -02}
-    {1509238800 -10800 0 -03}
-    {1521939600 -7200 1 -02}
-    {1540688400 -10800 0 -03}
-    {1553994000 -7200 1 -02}
-    {1572138000 -10800 0 -03}
-    {1585443600 -7200 1 -02}
-    {1603587600 -10800 0 -03}
-    {1616893200 -7200 1 -02}
-    {1635642000 -10800 0 -03}
-    {1648342800 -7200 1 -02}
-    {1667091600 -10800 0 -03}
-    {1679792400 -7200 1 -02}
-    {1698541200 -10800 0 -03}
-    {1711846800 -7200 1 -02}
-    {1729990800 -10800 0 -03}
-    {1743296400 -7200 1 -02}
-    {1761440400 -10800 0 -03}
-    {1774746000 -7200 1 -02}
-    {1792890000 -10800 0 -03}
-    {1806195600 -7200 1 -02}
-    {1824944400 -10800 0 -03}
-    {1837645200 -7200 1 -02}
-    {1856394000 -10800 0 -03}
-    {1869094800 -7200 1 -02}
-    {1887843600 -10800 0 -03}
-    {1901149200 -7200 1 -02}
-    {1919293200 -10800 0 -03}
-    {1932598800 -7200 1 -02}
-    {1950742800 -10800 0 -03}
-    {1964048400 -7200 1 -02}
-    {1982797200 -10800 0 -03}
-    {1995498000 -7200 1 -02}
-    {2014246800 -10800 0 -03}
-    {2026947600 -7200 1 -02}
-    {2045696400 -10800 0 -03}
-    {2058397200 -7200 1 -02}
-    {2077146000 -10800 0 -03}
-    {2090451600 -7200 1 -02}
-    {2108595600 -10800 0 -03}
-    {2121901200 -7200 1 -02}
-    {2140045200 -10800 0 -03}
-    {2153350800 -7200 1 -02}
-    {2172099600 -10800 0 -03}
-    {2184800400 -7200 1 -02}
-    {2203549200 -10800 0 -03}
-    {2216250000 -7200 1 -02}
-    {2234998800 -10800 0 -03}
-    {2248304400 -7200 1 -02}
-    {2266448400 -10800 0 -03}
-    {2279754000 -7200 1 -02}
-    {2297898000 -10800 0 -03}
-    {2311203600 -7200 1 -02}
-    {2329347600 -10800 0 -03}
-    {2342653200 -7200 1 -02}
-    {2361402000 -10800 0 -03}
-    {2374102800 -7200 1 -02}
-    {2392851600 -10800 0 -03}
-    {2405552400 -7200 1 -02}
-    {2424301200 -10800 0 -03}
-    {2437606800 -7200 1 -02}
-    {2455750800 -10800 0 -03}
-    {2469056400 -7200 1 -02}
-    {2487200400 -10800 0 -03}
-    {2500506000 -7200 1 -02}
-    {2519254800 -10800 0 -03}
-    {2531955600 -7200 1 -02}
-    {2550704400 -10800 0 -03}
-    {2563405200 -7200 1 -02}
-    {2582154000 -10800 0 -03}
-    {2595459600 -7200 1 -02}
-    {2613603600 -10800 0 -03}
-    {2626909200 -7200 1 -02}
-    {2645053200 -10800 0 -03}
-    {2658358800 -7200 1 -02}
-    {2676502800 -10800 0 -03}
-    {2689808400 -7200 1 -02}
-    {2708557200 -10800 0 -03}
-    {2721258000 -7200 1 -02}
-    {2740006800 -10800 0 -03}
-    {2752707600 -7200 1 -02}
-    {2771456400 -10800 0 -03}
-    {2784762000 -7200 1 -02}
-    {2802906000 -10800 0 -03}
-    {2816211600 -7200 1 -02}
-    {2834355600 -10800 0 -03}
-    {2847661200 -7200 1 -02}
-    {2866410000 -10800 0 -03}
-    {2879110800 -7200 1 -02}
-    {2897859600 -10800 0 -03}
-    {2910560400 -7200 1 -02}
-    {2929309200 -10800 0 -03}
-    {2942010000 -7200 1 -02}
-    {2960758800 -10800 0 -03}
-    {2974064400 -7200 1 -02}
-    {2992208400 -10800 0 -03}
-    {3005514000 -7200 1 -02}
-    {3023658000 -10800 0 -03}
-    {3036963600 -7200 1 -02}
-    {3055712400 -10800 0 -03}
-    {3068413200 -7200 1 -02}
-    {3087162000 -10800 0 -03}
-    {3099862800 -7200 1 -02}
-    {3118611600 -10800 0 -03}
-    {3131917200 -7200 1 -02}
-    {3150061200 -10800 0 -03}
-    {3163366800 -7200 1 -02}
-    {3181510800 -10800 0 -03}
-    {3194816400 -7200 1 -02}
-    {3212960400 -10800 0 -03}
-    {3226266000 -7200 1 -02}
-    {3245014800 -10800 0 -03}
-    {3257715600 -7200 1 -02}
-    {3276464400 -10800 0 -03}
-    {3289165200 -7200 1 -02}
-    {3307914000 -10800 0 -03}
-    {3321219600 -7200 1 -02}
-    {3339363600 -10800 0 -03}
-    {3352669200 -7200 1 -02}
-    {3370813200 -10800 0 -03}
-    {3384118800 -7200 1 -02}
-    {3402867600 -10800 0 -03}
-    {3415568400 -7200 1 -02}
-    {3434317200 -10800 0 -03}
-    {3447018000 -7200 1 -02}
-    {3465766800 -10800 0 -03}
-    {3479072400 -7200 1 -02}
-    {3497216400 -10800 0 -03}
-    {3510522000 -7200 1 -02}
-    {3528666000 -10800 0 -03}
-    {3541971600 -7200 1 -02}
-    {3560115600 -10800 0 -03}
-    {3573421200 -7200 1 -02}
-    {3592170000 -10800 0 -03}
-    {3604870800 -7200 1 -02}
-    {3623619600 -10800 0 -03}
-    {3636320400 -7200 1 -02}
-    {3655069200 -10800 0 -03}
-    {3668374800 -7200 1 -02}
-    {3686518800 -10800 0 -03}
-    {3699824400 -7200 1 -02}
-    {3717968400 -10800 0 -03}
-    {3731274000 -7200 1 -02}
-    {3750022800 -10800 0 -03}
-    {3762723600 -7200 1 -02}
-    {3781472400 -10800 0 -03}
-    {3794173200 -7200 1 -02}
-    {3812922000 -10800 0 -03}
-    {3825622800 -7200 1 -02}
-    {3844371600 -10800 0 -03}
-    {3857677200 -7200 1 -02}
-    {3875821200 -10800 0 -03}
-    {3889126800 -7200 1 -02}
-    {3907270800 -10800 0 -03}
-    {3920576400 -7200 1 -02}
-    {3939325200 -10800 0 -03}
-    {3952026000 -7200 1 -02}
-    {3970774800 -10800 0 -03}
-    {3983475600 -7200 1 -02}
-    {4002224400 -10800 0 -03}
-    {4015530000 -7200 1 -02}
-    {4033674000 -10800 0 -03}
-    {4046979600 -7200 1 -02}
-    {4065123600 -10800 0 -03}
-    {4078429200 -7200 1 -02}
-    {4096573200 -10800 0 -03}
+if {![info exists TZData(America/Nuuk)]} {
+    LoadTimeZoneFile America/Nuuk
 }
+set TZData(:America/Godthab) $TZData(:America/Nuuk)
index da5f09b..414b0f9 100644 (file)
@@ -77,8 +77,7 @@ set TZData(:America/Grand_Turk) {
     {1383458400 -18000 0 EST}
     {1394348400 -14400 1 EDT}
     {1414908000 -18000 0 EST}
-    {1425798000 -14400 1 EDT}
-    {1446361200 -14400 0 AST}
+    {1425798000 -14400 0 AST}
     {1520751600 -14400 0 EDT}
     {1541311200 -18000 0 EST}
     {1552201200 -14400 1 EDT}
index 1c35e93..292c56d 100644 (file)
@@ -3,6 +3,11 @@
 set TZData(:America/Nassau) {
     {-9223372036854775808 -18570 0 LMT}
     {-1825095030 -18000 0 EST}
+    {-873140400 -14400 1 EWT}
+    {-788904000 -18000 0 EST}
+    {-786222000 -14400 1 EWT}
+    {-769395600 -14400 1 EPT}
+    {-763848000 -18000 0 EST}
     {-179341200 -14400 1 EDT}
     {-163620000 -18000 0 EST}
     {-147891600 -14400 1 EDT}
diff --git a/library/tzdata/America/Nuuk b/library/tzdata/America/Nuuk
new file mode 100644 (file)
index 0000000..8d85a81
--- /dev/null
@@ -0,0 +1,246 @@
+# created by tools/tclZIC.tcl - do not edit
+
+set TZData(:America/Nuuk) {
+    {-9223372036854775808 -12416 0 LMT}
+    {-1686083584 -10800 0 -03}
+    {323845200 -7200 0 -02}
+    {338950800 -10800 0 -03}
+    {354675600 -7200 1 -02}
+    {370400400 -10800 0 -03}
+    {386125200 -7200 1 -02}
+    {401850000 -10800 0 -03}
+    {417574800 -7200 1 -02}
+    {433299600 -10800 0 -03}
+    {449024400 -7200 1 -02}
+    {465354000 -10800 0 -03}
+    {481078800 -7200 1 -02}
+    {496803600 -10800 0 -03}
+    {512528400 -7200 1 -02}
+    {528253200 -10800 0 -03}
+    {543978000 -7200 1 -02}
+    {559702800 -10800 0 -03}
+    {575427600 -7200 1 -02}
+    {591152400 -10800 0 -03}
+    {606877200 -7200 1 -02}
+    {622602000 -10800 0 -03}
+    {638326800 -7200 1 -02}
+    {654656400 -10800 0 -03}
+    {670381200 -7200 1 -02}
+    {686106000 -10800 0 -03}
+    {701830800 -7200 1 -02}
+    {717555600 -10800 0 -03}
+    {733280400 -7200 1 -02}
+    {749005200 -10800 0 -03}
+    {764730000 -7200 1 -02}
+    {780454800 -10800 0 -03}
+    {796179600 -7200 1 -02}
+    {811904400 -10800 0 -03}
+    {828234000 -7200 1 -02}
+    {846378000 -10800 0 -03}
+    {859683600 -7200 1 -02}
+    {877827600 -10800 0 -03}
+    {891133200 -7200 1 -02}
+    {909277200 -10800 0 -03}
+    {922582800 -7200 1 -02}
+    {941331600 -10800 0 -03}
+    {954032400 -7200 1 -02}
+    {972781200 -10800 0 -03}
+    {985482000 -7200 1 -02}
+    {1004230800 -10800 0 -03}
+    {1017536400 -7200 1 -02}
+    {1035680400 -10800 0 -03}
+    {1048986000 -7200 1 -02}
+    {1067130000 -10800 0 -03}
+    {1080435600 -7200 1 -02}
+    {1099184400 -10800 0 -03}
+    {1111885200 -7200 1 -02}
+    {1130634000 -10800 0 -03}
+    {1143334800 -7200 1 -02}
+    {1162083600 -10800 0 -03}
+    {1174784400 -7200 1 -02}
+    {1193533200 -10800 0 -03}
+    {1206838800 -7200 1 -02}
+    {1224982800 -10800 0 -03}
+    {1238288400 -7200 1 -02}
+    {1256432400 -10800 0 -03}
+    {1269738000 -7200 1 -02}
+    {1288486800 -10800 0 -03}
+    {1301187600 -7200 1 -02}
+    {1319936400 -10800 0 -03}
+    {1332637200 -7200 1 -02}
+    {1351386000 -10800 0 -03}
+    {1364691600 -7200 1 -02}
+    {1382835600 -10800 0 -03}
+    {1396141200 -7200 1 -02}
+    {1414285200 -10800 0 -03}
+    {1427590800 -7200 1 -02}
+    {1445734800 -10800 0 -03}
+    {1459040400 -7200 1 -02}
+    {1477789200 -10800 0 -03}
+    {1490490000 -7200 1 -02}
+    {1509238800 -10800 0 -03}
+    {1521939600 -7200 1 -02}
+    {1540688400 -10800 0 -03}
+    {1553994000 -7200 1 -02}
+    {1572138000 -10800 0 -03}
+    {1585443600 -7200 1 -02}
+    {1603587600 -10800 0 -03}
+    {1616893200 -7200 1 -02}
+    {1635642000 -10800 0 -03}
+    {1648342800 -7200 1 -02}
+    {1667091600 -10800 0 -03}
+    {1679792400 -7200 1 -02}
+    {1698541200 -10800 0 -03}
+    {1711846800 -7200 1 -02}
+    {1729990800 -10800 0 -03}
+    {1743296400 -7200 1 -02}
+    {1761440400 -10800 0 -03}
+    {1774746000 -7200 1 -02}
+    {1792890000 -10800 0 -03}
+    {1806195600 -7200 1 -02}
+    {1824944400 -10800 0 -03}
+    {1837645200 -7200 1 -02}
+    {1856394000 -10800 0 -03}
+    {1869094800 -7200 1 -02}
+    {1887843600 -10800 0 -03}
+    {1901149200 -7200 1 -02}
+    {1919293200 -10800 0 -03}
+    {1932598800 -7200 1 -02}
+    {1950742800 -10800 0 -03}
+    {1964048400 -7200 1 -02}
+    {1982797200 -10800 0 -03}
+    {1995498000 -7200 1 -02}
+    {2014246800 -10800 0 -03}
+    {2026947600 -7200 1 -02}
+    {2045696400 -10800 0 -03}
+    {2058397200 -7200 1 -02}
+    {2077146000 -10800 0 -03}
+    {2090451600 -7200 1 -02}
+    {2108595600 -10800 0 -03}
+    {2121901200 -7200 1 -02}
+    {2140045200 -10800 0 -03}
+    {2153350800 -7200 1 -02}
+    {2172099600 -10800 0 -03}
+    {2184800400 -7200 1 -02}
+    {2203549200 -10800 0 -03}
+    {2216250000 -7200 1 -02}
+    {2234998800 -10800 0 -03}
+    {2248304400 -7200 1 -02}
+    {2266448400 -10800 0 -03}
+    {2279754000 -7200 1 -02}
+    {2297898000 -10800 0 -03}
+    {2311203600 -7200 1 -02}
+    {2329347600 -10800 0 -03}
+    {2342653200 -7200 1 -02}
+    {2361402000 -10800 0 -03}
+    {2374102800 -7200 1 -02}
+    {2392851600 -10800 0 -03}
+    {2405552400 -7200 1 -02}
+    {2424301200 -10800 0 -03}
+    {2437606800 -7200 1 -02}
+    {2455750800 -10800 0 -03}
+    {2469056400 -7200 1 -02}
+    {2487200400 -10800 0 -03}
+    {2500506000 -7200 1 -02}
+    {2519254800 -10800 0 -03}
+    {2531955600 -7200 1 -02}
+    {2550704400 -10800 0 -03}
+    {2563405200 -7200 1 -02}
+    {2582154000 -10800 0 -03}
+    {2595459600 -7200 1 -02}
+    {2613603600 -10800 0 -03}
+    {2626909200 -7200 1 -02}
+    {2645053200 -10800 0 -03}
+    {2658358800 -7200 1 -02}
+    {2676502800 -10800 0 -03}
+    {2689808400 -7200 1 -02}
+    {2708557200 -10800 0 -03}
+    {2721258000 -7200 1 -02}
+    {2740006800 -10800 0 -03}
+    {2752707600 -7200 1 -02}
+    {2771456400 -10800 0 -03}
+    {2784762000 -7200 1 -02}
+    {2802906000 -10800 0 -03}
+    {2816211600 -7200 1 -02}
+    {2834355600 -10800 0 -03}
+    {2847661200 -7200 1 -02}
+    {2866410000 -10800 0 -03}
+    {2879110800 -7200 1 -02}
+    {2897859600 -10800 0 -03}
+    {2910560400 -7200 1 -02}
+    {2929309200 -10800 0 -03}
+    {2942010000 -7200 1 -02}
+    {2960758800 -10800 0 -03}
+    {2974064400 -7200 1 -02}
+    {2992208400 -10800 0 -03}
+    {3005514000 -7200 1 -02}
+    {3023658000 -10800 0 -03}
+    {3036963600 -7200 1 -02}
+    {3055712400 -10800 0 -03}
+    {3068413200 -7200 1 -02}
+    {3087162000 -10800 0 -03}
+    {3099862800 -7200 1 -02}
+    {3118611600 -10800 0 -03}
+    {3131917200 -7200 1 -02}
+    {3150061200 -10800 0 -03}
+    {3163366800 -7200 1 -02}
+    {3181510800 -10800 0 -03}
+    {3194816400 -7200 1 -02}
+    {3212960400 -10800 0 -03}
+    {3226266000 -7200 1 -02}
+    {3245014800 -10800 0 -03}
+    {3257715600 -7200 1 -02}
+    {3276464400 -10800 0 -03}
+    {3289165200 -7200 1 -02}
+    {3307914000 -10800 0 -03}
+    {3321219600 -7200 1 -02}
+    {3339363600 -10800 0 -03}
+    {3352669200 -7200 1 -02}
+    {3370813200 -10800 0 -03}
+    {3384118800 -7200 1 -02}
+    {3402867600 -10800 0 -03}
+    {3415568400 -7200 1 -02}
+    {3434317200 -10800 0 -03}
+    {3447018000 -7200 1 -02}
+    {3465766800 -10800 0 -03}
+    {3479072400 -7200 1 -02}
+    {3497216400 -10800 0 -03}
+    {3510522000 -7200 1 -02}
+    {3528666000 -10800 0 -03}
+    {3541971600 -7200 1 -02}
+    {3560115600 -10800 0 -03}
+    {3573421200 -7200 1 -02}
+    {3592170000 -10800 0 -03}
+    {3604870800 -7200 1 -02}
+    {3623619600 -10800 0 -03}
+    {3636320400 -7200 1 -02}
+    {3655069200 -10800 0 -03}
+    {3668374800 -7200 1 -02}
+    {3686518800 -10800 0 -03}
+    {3699824400 -7200 1 -02}
+    {3717968400 -10800 0 -03}
+    {3731274000 -7200 1 -02}
+    {3750022800 -10800 0 -03}
+    {3762723600 -7200 1 -02}
+    {3781472400 -10800 0 -03}
+    {3794173200 -7200 1 -02}
+    {3812922000 -10800 0 -03}
+    {3825622800 -7200 1 -02}
+    {3844371600 -10800 0 -03}
+    {3857677200 -7200 1 -02}
+    {3875821200 -10800 0 -03}
+    {3889126800 -7200 1 -02}
+    {3907270800 -10800 0 -03}
+    {3920576400 -7200 1 -02}
+    {3939325200 -10800 0 -03}
+    {3952026000 -7200 1 -02}
+    {3970774800 -10800 0 -03}
+    {3983475600 -7200 1 -02}
+    {4002224400 -10800 0 -03}
+    {4015530000 -7200 1 -02}
+    {4033674000 -10800 0 -03}
+    {4046979600 -7200 1 -02}
+    {4065123600 -10800 0 -03}
+    {4078429200 -7200 1 -02}
+    {4096573200 -10800 0 -03}
+}
index 1d61093..498a203 100644 (file)
@@ -94,163 +94,5 @@ set TZData(:America/Whitehorse) {
     {1552212000 -25200 1 PDT}
     {1572771600 -28800 0 PST}
     {1583661600 -25200 1 PDT}
-    {1604221200 -28800 0 PST}
-    {1615716000 -25200 1 PDT}
-    {1636275600 -28800 0 PST}
-    {1647165600 -25200 1 PDT}
-    {1667725200 -28800 0 PST}
-    {1678615200 -25200 1 PDT}
-    {1699174800 -28800 0 PST}
-    {1710064800 -25200 1 PDT}
-    {1730624400 -28800 0 PST}
-    {1741514400 -25200 1 PDT}
-    {1762074000 -28800 0 PST}
-    {1772964000 -25200 1 PDT}
-    {1793523600 -28800 0 PST}
-    {1805018400 -25200 1 PDT}
-    {1825578000 -28800 0 PST}
-    {1836468000 -25200 1 PDT}
-    {1857027600 -28800 0 PST}
-    {1867917600 -25200 1 PDT}
-    {1888477200 -28800 0 PST}
-    {1899367200 -25200 1 PDT}
-    {1919926800 -28800 0 PST}
-    {1930816800 -25200 1 PDT}
-    {1951376400 -28800 0 PST}
-    {1962871200 -25200 1 PDT}
-    {1983430800 -28800 0 PST}
-    {1994320800 -25200 1 PDT}
-    {2014880400 -28800 0 PST}
-    {2025770400 -25200 1 PDT}
-    {2046330000 -28800 0 PST}
-    {2057220000 -25200 1 PDT}
-    {2077779600 -28800 0 PST}
-    {2088669600 -25200 1 PDT}
-    {2109229200 -28800 0 PST}
-    {2120119200 -25200 1 PDT}
-    {2140678800 -28800 0 PST}
-    {2152173600 -25200 1 PDT}
-    {2172733200 -28800 0 PST}
-    {2183623200 -25200 1 PDT}
-    {2204182800 -28800 0 PST}
-    {2215072800 -25200 1 PDT}
-    {2235632400 -28800 0 PST}
-    {2246522400 -25200 1 PDT}
-    {2267082000 -28800 0 PST}
-    {2277972000 -25200 1 PDT}
-    {2298531600 -28800 0 PST}
-    {2309421600 -25200 1 PDT}
-    {2329981200 -28800 0 PST}
-    {2341476000 -25200 1 PDT}
-    {2362035600 -28800 0 PST}
-    {2372925600 -25200 1 PDT}
-    {2393485200 -28800 0 PST}
-    {2404375200 -25200 1 PDT}
-    {2424934800 -28800 0 PST}
-    {2435824800 -25200 1 PDT}
-    {2456384400 -28800 0 PST}
-    {2467274400 -25200 1 PDT}
-    {2487834000 -28800 0 PST}
-    {2499328800 -25200 1 PDT}
-    {2519888400 -28800 0 PST}
-    {2530778400 -25200 1 PDT}
-    {2551338000 -28800 0 PST}
-    {2562228000 -25200 1 PDT}
-    {2582787600 -28800 0 PST}
-    {2593677600 -25200 1 PDT}
-    {2614237200 -28800 0 PST}
-    {2625127200 -25200 1 PDT}
-    {2645686800 -28800 0 PST}
-    {2656576800 -25200 1 PDT}
-    {2677136400 -28800 0 PST}
-    {2688631200 -25200 1 PDT}
-    {2709190800 -28800 0 PST}
-    {2720080800 -25200 1 PDT}
-    {2740640400 -28800 0 PST}
-    {2751530400 -25200 1 PDT}
-    {2772090000 -28800 0 PST}
-    {2782980000 -25200 1 PDT}
-    {2803539600 -28800 0 PST}
-    {2814429600 -25200 1 PDT}
-    {2834989200 -28800 0 PST}
-    {2846484000 -25200 1 PDT}
-    {2867043600 -28800 0 PST}
-    {2877933600 -25200 1 PDT}
-    {2898493200 -28800 0 PST}
-    {2909383200 -25200 1 PDT}
-    {2929942800 -28800 0 PST}
-    {2940832800 -25200 1 PDT}
-    {2961392400 -28800 0 PST}
-    {2972282400 -25200 1 PDT}
-    {2992842000 -28800 0 PST}
-    {3003732000 -25200 1 PDT}
-    {3024291600 -28800 0 PST}
-    {3035786400 -25200 1 PDT}
-    {3056346000 -28800 0 PST}
-    {3067236000 -25200 1 PDT}
-    {3087795600 -28800 0 PST}
-    {3098685600 -25200 1 PDT}
-    {3119245200 -28800 0 PST}
-    {3130135200 -25200 1 PDT}
-    {3150694800 -28800 0 PST}
-    {3161584800 -25200 1 PDT}
-    {3182144400 -28800 0 PST}
-    {3193034400 -25200 1 PDT}
-    {3213594000 -28800 0 PST}
-    {3225088800 -25200 1 PDT}
-    {3245648400 -28800 0 PST}
-    {3256538400 -25200 1 PDT}
-    {3277098000 -28800 0 PST}
-    {3287988000 -25200 1 PDT}
-    {3308547600 -28800 0 PST}
-    {3319437600 -25200 1 PDT}
-    {3339997200 -28800 0 PST}
-    {3350887200 -25200 1 PDT}
-    {3371446800 -28800 0 PST}
-    {3382941600 -25200 1 PDT}
-    {3403501200 -28800 0 PST}
-    {3414391200 -25200 1 PDT}
-    {3434950800 -28800 0 PST}
-    {3445840800 -25200 1 PDT}
-    {3466400400 -28800 0 PST}
-    {3477290400 -25200 1 PDT}
-    {3497850000 -28800 0 PST}
-    {3508740000 -25200 1 PDT}
-    {3529299600 -28800 0 PST}
-    {3540189600 -25200 1 PDT}
-    {3560749200 -28800 0 PST}
-    {3572244000 -25200 1 PDT}
-    {3592803600 -28800 0 PST}
-    {3603693600 -25200 1 PDT}
-    {3624253200 -28800 0 PST}
-    {3635143200 -25200 1 PDT}
-    {3655702800 -28800 0 PST}
-    {3666592800 -25200 1 PDT}
-    {3687152400 -28800 0 PST}
-    {3698042400 -25200 1 PDT}
-    {3718602000 -28800 0 PST}
-    {3730096800 -25200 1 PDT}
-    {3750656400 -28800 0 PST}
-    {3761546400 -25200 1 PDT}
-    {3782106000 -28800 0 PST}
-    {3792996000 -25200 1 PDT}
-    {3813555600 -28800 0 PST}
-    {3824445600 -25200 1 PDT}
-    {3845005200 -28800 0 PST}
-    {3855895200 -25200 1 PDT}
-    {3876454800 -28800 0 PST}
-    {3887344800 -25200 1 PDT}
-    {3907904400 -28800 0 PST}
-    {3919399200 -25200 1 PDT}
-    {3939958800 -28800 0 PST}
-    {3950848800 -25200 1 PDT}
-    {3971408400 -28800 0 PST}
-    {3982298400 -25200 1 PDT}
-    {4002858000 -28800 0 PST}
-    {4013748000 -25200 1 PDT}
-    {4034307600 -28800 0 PST}
-    {4045197600 -25200 1 PDT}
-    {4065757200 -28800 0 PST}
-    {4076647200 -25200 1 PDT}
-    {4097206800 -28800 0 PST}
+    {1604217600 -25200 0 MST}
 }
index aa37480..56935e3 100644 (file)
@@ -9,4 +9,9 @@ set TZData(:Antarctica/Casey) {
     {1329843600 28800 0 +08}
     {1477065600 39600 0 +11}
     {1520701200 28800 0 +08}
+    {1538856000 39600 0 +11}
+    {1552752000 28800 0 +08}
+    {1570129200 39600 0 +11}
+    {1583596800 28800 0 +08}
+    {1601740860 39600 0 +11}
 }
index 60bf7a6..82b2b9f 100644 (file)
@@ -5,7 +5,7 @@ set TZData(:Antarctica/Macquarie) {
     {-2214259200 36000 0 AEST}
     {-1680508800 39600 1 AEDT}
     {-1669892400 39600 0 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1665388800 36000 0 AEST}
     {-1601719200 0 0 -00}
     {-94730400 36000 0 AEST}
     {-71136000 39600 1 AEDT}
@@ -93,5 +93,184 @@ set TZData(:Antarctica/Macquarie) {
     {1223136000 39600 1 AEDT}
     {1238860800 36000 0 AEST}
     {1254585600 39600 1 AEDT}
-    {1270310400 39600 0 +11}
+    {1262264400 39600 1 AEDT}
+    {1293800400 39600 0 AEST}
+    {1301760000 36000 0 AEST}
+    {1317484800 39600 1 AEDT}
+    {1333209600 36000 0 AEST}
+    {1349539200 39600 1 AEDT}
+    {1365264000 36000 0 AEST}
+    {1380988800 39600 1 AEDT}
+    {1396713600 36000 0 AEST}
+    {1412438400 39600 1 AEDT}
+    {1428163200 36000 0 AEST}
+    {1443888000 39600 1 AEDT}
+    {1459612800 36000 0 AEST}
+    {1475337600 39600 1 AEDT}
+    {1491062400 36000 0 AEST}
+    {1506787200 39600 1 AEDT}
+    {1522512000 36000 0 AEST}
+    {1538841600 39600 1 AEDT}
+    {1554566400 36000 0 AEST}
+    {1570291200 39600 1 AEDT}
+    {1586016000 36000 0 AEST}
+    {1601740800 39600 1 AEDT}
+    {1617465600 36000 0 AEST}
+    {1633190400 39600 1 AEDT}
+    {1648915200 36000 0 AEST}
+    {1664640000 39600 1 AEDT}
+    {1680364800 36000 0 AEST}
+    {1696089600 39600 1 AEDT}
+    {1712419200 36000 0 AEST}
+    {1728144000 39600 1 AEDT}
+    {1743868800 36000 0 AEST}
+    {1759593600 39600 1 AEDT}
+    {1775318400 36000 0 AEST}
+    {1791043200 39600 1 AEDT}
+    {1806768000 36000 0 AEST}
+    {1822492800 39600 1 AEDT}
+    {1838217600 36000 0 AEST}
+    {1853942400 39600 1 AEDT}
+    {1869667200 36000 0 AEST}
+    {1885996800 39600 1 AEDT}
+    {1901721600 36000 0 AEST}
+    {1917446400 39600 1 AEDT}
+    {1933171200 36000 0 AEST}
+    {1948896000 39600 1 AEDT}
+    {1964620800 36000 0 AEST}
+    {1980345600 39600 1 AEDT}
+    {1996070400 36000 0 AEST}
+    {2011795200 39600 1 AEDT}
+    {2027520000 36000 0 AEST}
+    {2043244800 39600 1 AEDT}
+    {2058969600 36000 0 AEST}
+    {2075299200 39600 1 AEDT}
+    {2091024000 36000 0 AEST}
+    {2106748800 39600 1 AEDT}
+    {2122473600 36000 0 AEST}
+    {2138198400 39600 1 AEDT}
+    {2153923200 36000 0 AEST}
+    {2169648000 39600 1 AEDT}
+    {2185372800 36000 0 AEST}
+    {2201097600 39600 1 AEDT}
+    {2216822400 36000 0 AEST}
+    {2233152000 39600 1 AEDT}
+    {2248876800 36000 0 AEST}
+    {2264601600 39600 1 AEDT}
+    {2280326400 36000 0 AEST}
+    {2296051200 39600 1 AEDT}
+    {2311776000 36000 0 AEST}
+    {2327500800 39600 1 AEDT}
+    {2343225600 36000 0 AEST}
+    {2358950400 39600 1 AEDT}
+    {2374675200 36000 0 AEST}
+    {2390400000 39600 1 AEDT}
+    {2406124800 36000 0 AEST}
+    {2422454400 39600 1 AEDT}
+    {2438179200 36000 0 AEST}
+    {2453904000 39600 1 AEDT}
+    {2469628800 36000 0 AEST}
+    {2485353600 39600 1 AEDT}
+    {2501078400 36000 0 AEST}
+    {2516803200 39600 1 AEDT}
+    {2532528000 36000 0 AEST}
+    {2548252800 39600 1 AEDT}
+    {2563977600 36000 0 AEST}
+    {2579702400 39600 1 AEDT}
+    {2596032000 36000 0 AEST}
+    {2611756800 39600 1 AEDT}
+    {2627481600 36000 0 AEST}
+    {2643206400 39600 1 AEDT}
+    {2658931200 36000 0 AEST}
+    {2674656000 39600 1 AEDT}
+    {2690380800 36000 0 AEST}
+    {2706105600 39600 1 AEDT}
+    {2721830400 36000 0 AEST}
+    {2737555200 39600 1 AEDT}
+    {2753280000 36000 0 AEST}
+    {2769609600 39600 1 AEDT}
+    {2785334400 36000 0 AEST}
+    {2801059200 39600 1 AEDT}
+    {2816784000 36000 0 AEST}
+    {2832508800 39600 1 AEDT}
+    {2848233600 36000 0 AEST}
+    {2863958400 39600 1 AEDT}
+    {2879683200 36000 0 AEST}
+    {2895408000 39600 1 AEDT}
+    {2911132800 36000 0 AEST}
+    {2926857600 39600 1 AEDT}
+    {2942582400 36000 0 AEST}
+    {2958912000 39600 1 AEDT}
+    {2974636800 36000 0 AEST}
+    {2990361600 39600 1 AEDT}
+    {3006086400 36000 0 AEST}
+    {3021811200 39600 1 AEDT}
+    {3037536000 36000 0 AEST}
+    {3053260800 39600 1 AEDT}
+    {3068985600 36000 0 AEST}
+    {3084710400 39600 1 AEDT}
+    {3100435200 36000 0 AEST}
+    {3116764800 39600 1 AEDT}
+    {3132489600 36000 0 AEST}
+    {3148214400 39600 1 AEDT}
+    {3163939200 36000 0 AEST}
+    {3179664000 39600 1 AEDT}
+    {3195388800 36000 0 AEST}
+    {3211113600 39600 1 AEDT}
+    {3226838400 36000 0 AEST}
+    {3242563200 39600 1 AEDT}
+    {3258288000 36000 0 AEST}
+    {3274012800 39600 1 AEDT}
+    {3289737600 36000 0 AEST}
+    {3306067200 39600 1 AEDT}
+    {3321792000 36000 0 AEST}
+    {3337516800 39600 1 AEDT}
+    {3353241600 36000 0 AEST}
+    {3368966400 39600 1 AEDT}
+    {3384691200 36000 0 AEST}
+    {3400416000 39600 1 AEDT}
+    {3416140800 36000 0 AEST}
+    {3431865600 39600 1 AEDT}
+    {3447590400 36000 0 AEST}
+    {3463315200 39600 1 AEDT}
+    {3479644800 36000 0 AEST}
+    {3495369600 39600 1 AEDT}
+    {3511094400 36000 0 AEST}
+    {3526819200 39600 1 AEDT}
+    {3542544000 36000 0 AEST}
+    {3558268800 39600 1 AEDT}
+    {3573993600 36000 0 AEST}
+    {3589718400 39600 1 AEDT}
+    {3605443200 36000 0 AEST}
+    {3621168000 39600 1 AEDT}
+    {3636892800 36000 0 AEST}
+    {3653222400 39600 1 AEDT}
+    {3668947200 36000 0 AEST}
+    {3684672000 39600 1 AEDT}
+    {3700396800 36000 0 AEST}
+    {3716121600 39600 1 AEDT}
+    {3731846400 36000 0 AEST}
+    {3747571200 39600 1 AEDT}
+    {3763296000 36000 0 AEST}
+    {3779020800 39600 1 AEDT}
+    {3794745600 36000 0 AEST}
+    {3810470400 39600 1 AEDT}
+    {3826195200 36000 0 AEST}
+    {3842524800 39600 1 AEDT}
+    {3858249600 36000 0 AEST}
+    {3873974400 39600 1 AEDT}
+    {3889699200 36000 0 AEST}
+    {3905424000 39600 1 AEDT}
+    {3921148800 36000 0 AEST}
+    {3936873600 39600 1 AEDT}
+    {3952598400 36000 0 AEST}
+    {3968323200 39600 1 AEDT}
+    {3984048000 36000 0 AEST}
+    {4000377600 39600 1 AEDT}
+    {4016102400 36000 0 AEST}
+    {4031827200 39600 1 AEDT}
+    {4047552000 36000 0 AEST}
+    {4063276800 39600 1 AEDT}
+    {4079001600 36000 0 AEST}
+    {4094726400 39600 1 AEDT}
 }
index 9b73dcc..95523c9 100644 (file)
@@ -3,16 +3,18 @@
 set TZData(:Asia/Gaza) {
     {-9223372036854775808 8272 0 LMT}
     {-2185409872 7200 0 EEST}
-    {-933645600 10800 1 EEST}
-    {-857358000 7200 0 EEST}
+    {-933638400 10800 1 EEST}
+    {-923097600 7200 0 EEST}
+    {-919036800 10800 1 EEST}
+    {-857347200 7200 0 EEST}
     {-844300800 10800 1 EEST}
-    {-825822000 7200 0 EEST}
-    {-812685600 10800 1 EEST}
-    {-794199600 7200 0 EEST}
-    {-779853600 10800 1 EEST}
-    {-762656400 7200 0 EEST}
+    {-825811200 7200 0 EEST}
+    {-812678400 10800 1 EEST}
+    {-794188800 7200 0 EEST}
+    {-779846400 10800 1 EEST}
+    {-762652800 7200 0 EEST}
     {-748310400 10800 1 EEST}
-    {-731127600 7200 0 EEST}
+    {-731116800 7200 0 EEST}
     {-682653600 7200 0 EET}
     {-399088800 10800 1 EEST}
     {-386650800 7200 0 EET}
@@ -40,12 +42,12 @@ set TZData(:Asia/Gaza) {
     {150843600 7200 0 IST}
     {167176800 10800 1 IDT}
     {178664400 7200 0 IST}
-    {334015200 10800 1 IDT}
-    {337644000 7200 0 IST}
-    {452556000 10800 1 IDT}
-    {462232800 7200 0 IST}
+    {334101600 10800 1 IDT}
+    {337730400 7200 0 IST}
+    {452642400 10800 1 IDT}
+    {462319200 7200 0 IST}
     {482277600 10800 1 IDT}
-    {495579600 7200 0 IST}
+    {494370000 7200 0 IST}
     {516751200 10800 1 IDT}
     {526424400 7200 0 IST}
     {545436000 10800 1 IDT}
@@ -110,7 +112,7 @@ set TZData(:Asia/Gaza) {
     {1395957600 10800 1 EEST}
     {1414098000 7200 0 EET}
     {1427493600 10800 1 EEST}
-    {1445547600 7200 0 EET}
+    {1445551200 7200 0 EET}
     {1458946800 10800 1 EEST}
     {1477692000 7200 0 EET}
     {1490396400 10800 1 EEST}
@@ -118,165 +120,165 @@ set TZData(:Asia/Gaza) {
     {1521846000 10800 1 EEST}
     {1540591200 7200 0 EET}
     {1553810400 10800 1 EEST}
-    {1572040800 7200 0 EET}
-    {1585260000 10800 1 EEST}
-    {1604095200 7200 0 EET}
-    {1616709600 10800 1 EEST}
+    {1572037200 7200 0 EET}
+    {1585346400 10800 1 EEST}
+    {1603490400 7200 0 EET}
+    {1616796000 10800 1 EEST}
     {1635544800 7200 0 EET}
-    {1648159200 10800 1 EEST}
+    {1648245600 10800 1 EEST}
     {1666994400 7200 0 EET}
-    {1680213600 10800 1 EEST}
+    {1679695200 10800 1 EEST}
     {1698444000 7200 0 EET}
-    {1711663200 10800 1 EEST}
+    {1711749600 10800 1 EEST}
     {1729893600 7200 0 EET}
-    {1743112800 10800 1 EEST}
+    {1743199200 10800 1 EEST}
     {1761343200 7200 0 EET}
-    {1774562400 10800 1 EEST}
-    {1793397600 7200 0 EET}
-    {1806012000 10800 1 EEST}
+    {1774648800 10800 1 EEST}
+    {1792792800 7200 0 EET}
+    {1806098400 10800 1 EEST}
     {1824847200 7200 0 EET}
-    {1838066400 10800 1 EEST}
+    {1837548000 10800 1 EEST}
     {1856296800 7200 0 EET}
-    {1869516000 10800 1 EEST}
+    {1868997600 10800 1 EEST}
     {1887746400 7200 0 EET}
-    {1900965600 10800 1 EEST}
+    {1901052000 10800 1 EEST}
     {1919196000 7200 0 EET}
-    {1932415200 10800 1 EEST}
+    {1932501600 10800 1 EEST}
     {1950645600 7200 0 EET}
-    {1963864800 10800 1 EEST}
+    {1963951200 10800 1 EEST}
     {1982700000 7200 0 EET}
-    {1995314400 10800 1 EEST}
+    {1995400800 10800 1 EEST}
     {2014149600 7200 0 EET}
-    {2027368800 10800 1 EEST}
+    {2026850400 10800 1 EEST}
     {2045599200 7200 0 EET}
-    {2058818400 10800 1 EEST}
+    {2058300000 10800 1 EEST}
     {2077048800 7200 0 EET}
-    {2090268000 10800 1 EEST}
+    {2090354400 10800 1 EEST}
     {2108498400 7200 0 EET}
-    {2121717600 10800 1 EEST}
-    {2140552800 7200 0 EET}
-    {2153167200 10800 1 EEST}
+    {2121804000 10800 1 EEST}
+    {2139948000 7200 0 EET}
+    {2153253600 10800 1 EEST}
     {2172002400 7200 0 EET}
-    {2184616800 10800 1 EEST}
+    {2184703200 10800 1 EEST}
     {2203452000 7200 0 EET}
-    {2216671200 10800 1 EEST}
+    {2216152800 10800 1 EEST}
     {2234901600 7200 0 EET}
-    {2248120800 10800 1 EEST}
+    {2248207200 10800 1 EEST}
     {2266351200 7200 0 EET}
-    {2279570400 10800 1 EEST}
+    {2279656800 10800 1 EEST}
     {2297800800 7200 0 EET}
-    {2311020000 10800 1 EEST}
-    {2329855200 7200 0 EET}
-    {2342469600 10800 1 EEST}
+    {2311106400 10800 1 EEST}
+    {2329250400 7200 0 EET}
+    {2342556000 10800 1 EEST}
     {2361304800 7200 0 EET}
-    {2374524000 10800 1 EEST}
+    {2374005600 10800 1 EEST}
     {2392754400 7200 0 EET}
-    {2405973600 10800 1 EEST}
+    {2405455200 10800 1 EEST}
     {2424204000 7200 0 EET}
-    {2437423200 10800 1 EEST}
+    {2437509600 10800 1 EEST}
     {2455653600 7200 0 EET}
-    {2468872800 10800 1 EEST}
-    {2487708000 7200 0 EET}
-    {2500322400 10800 1 EEST}
+    {2468959200 10800 1 EEST}
+    {2487103200 7200 0 EET}
+    {2500408800 10800 1 EEST}
     {2519157600 7200 0 EET}
-    {2531772000 10800 1 EEST}
+    {2531858400 10800 1 EEST}
     {2550607200 7200 0 EET}
-    {2563826400 10800 1 EEST}
+    {2563308000 10800 1 EEST}
     {2582056800 7200 0 EET}
-    {2595276000 10800 1 EEST}
+    {2595362400 10800 1 EEST}
     {2613506400 7200 0 EET}
-    {2626725600 10800 1 EEST}
+    {2626812000 10800 1 EEST}
     {2644956000 7200 0 EET}
-    {2658175200 10800 1 EEST}
-    {2677010400 7200 0 EET}
-    {2689624800 10800 1 EEST}
+    {2658261600 10800 1 EEST}
+    {2676405600 7200 0 EET}
+    {2689711200 10800 1 EEST}
     {2708460000 7200 0 EET}
-    {2721679200 10800 1 EEST}
+    {2721160800 10800 1 EEST}
     {2739909600 7200 0 EET}
-    {2753128800 10800 1 EEST}
+    {2752610400 10800 1 EEST}
     {2771359200 7200 0 EET}
-    {2784578400 10800 1 EEST}
+    {2784664800 10800 1 EEST}
     {2802808800 7200 0 EET}
-    {2816028000 10800 1 EEST}
+    {2816114400 10800 1 EEST}
     {2834258400 7200 0 EET}
-    {2847477600 10800 1 EEST}
+    {2847564000 10800 1 EEST}
     {2866312800 7200 0 EET}
-    {2878927200 10800 1 EEST}
+    {2879013600 10800 1 EEST}
     {2897762400 7200 0 EET}
-    {2910981600 10800 1 EEST}
+    {2910463200 10800 1 EEST}
     {2929212000 7200 0 EET}
-    {2942431200 10800 1 EEST}
+    {2941912800 10800 1 EEST}
     {2960661600 7200 0 EET}
-    {2973880800 10800 1 EEST}
+    {2973967200 10800 1 EEST}
     {2992111200 7200 0 EET}
-    {3005330400 10800 1 EEST}
-    {3024165600 7200 0 EET}
-    {3036780000 10800 1 EEST}
+    {3005416800 10800 1 EEST}
+    {3023560800 7200 0 EET}
+    {3036866400 10800 1 EEST}
     {3055615200 7200 0 EET}
-    {3068229600 10800 1 EEST}
+    {3068316000 10800 1 EEST}
     {3087064800 7200 0 EET}
-    {3100284000 10800 1 EEST}
+    {3099765600 10800 1 EEST}
     {3118514400 7200 0 EET}
-    {3131733600 10800 1 EEST}
+    {3131820000 10800 1 EEST}
     {3149964000 7200 0 EET}
-    {3163183200 10800 1 EEST}
+    {3163269600 10800 1 EEST}
     {3181413600 7200 0 EET}
-    {3194632800 10800 1 EEST}
-    {3213468000 7200 0 EET}
-    {3226082400 10800 1 EEST}
+    {3194719200 10800 1 EEST}
+    {3212863200 7200 0 EET}
+    {3226168800 10800 1 EEST}
     {3244917600 7200 0 EET}
-    {3258136800 10800 1 EEST}
+    {3257618400 10800 1 EEST}
     {3276367200 7200 0 EET}
-    {3289586400 10800 1 EEST}
+    {3289068000 10800 1 EEST}
     {3307816800 7200 0 EET}
-    {3321036000 10800 1 EEST}
+    {3321122400 10800 1 EEST}
     {3339266400 7200 0 EET}
-    {3352485600 10800 1 EEST}
-    {3371320800 7200 0 EET}
-    {3383935200 10800 1 EEST}
+    {3352572000 10800 1 EEST}
+    {3370716000 7200 0 EET}
+    {3384021600 10800 1 EEST}
     {3402770400 7200 0 EET}
-    {3415384800 10800 1 EEST}
+    {3415471200 10800 1 EEST}
     {3434220000 7200 0 EET}
-    {3447439200 10800 1 EEST}
+    {3446920800 10800 1 EEST}
     {3465669600 7200 0 EET}
-    {3478888800 10800 1 EEST}
+    {3478975200 10800 1 EEST}
     {3497119200 7200 0 EET}
-    {3510338400 10800 1 EEST}
+    {3510424800 10800 1 EEST}
     {3528568800 7200 0 EET}
-    {3541788000 10800 1 EEST}
-    {3560623200 7200 0 EET}
-    {3573237600 10800 1 EEST}
+    {3541874400 10800 1 EEST}
+    {3560018400 7200 0 EET}
+    {3573324000 10800 1 EEST}
     {3592072800 7200 0 EET}
-    {3605292000 10800 1 EEST}
+    {3604773600 10800 1 EEST}
     {3623522400 7200 0 EET}
-    {3636741600 10800 1 EEST}
+    {3636223200 10800 1 EEST}
     {3654972000 7200 0 EET}
-    {3668191200 10800 1 EEST}
+    {3668277600 10800 1 EEST}
     {3686421600 7200 0 EET}
-    {3699640800 10800 1 EEST}
+    {3699727200 10800 1 EEST}
     {3717871200 7200 0 EET}
-    {3731090400 10800 1 EEST}
+    {3731176800 10800 1 EEST}
     {3749925600 7200 0 EET}
-    {3762540000 10800 1 EEST}
+    {3762626400 10800 1 EEST}
     {3781375200 7200 0 EET}
-    {3794594400 10800 1 EEST}
+    {3794076000 10800 1 EEST}
     {3812824800 7200 0 EET}
-    {3826044000 10800 1 EEST}
+    {3825525600 10800 1 EEST}
     {3844274400 7200 0 EET}
-    {3857493600 10800 1 EEST}
+    {3857580000 10800 1 EEST}
     {3875724000 7200 0 EET}
-    {3888943200 10800 1 EEST}
-    {3907778400 7200 0 EET}
-    {3920392800 10800 1 EEST}
+    {3889029600 10800 1 EEST}
+    {3907173600 7200 0 EET}
+    {3920479200 10800 1 EEST}
     {3939228000 7200 0 EET}
-    {3951842400 10800 1 EEST}
+    {3951928800 10800 1 EEST}
     {3970677600 7200 0 EET}
-    {3983896800 10800 1 EEST}
+    {3983378400 10800 1 EEST}
     {4002127200 7200 0 EET}
-    {4015346400 10800 1 EEST}
+    {4015432800 10800 1 EEST}
     {4033576800 7200 0 EET}
-    {4046796000 10800 1 EEST}
+    {4046882400 10800 1 EEST}
     {4065026400 7200 0 EET}
-    {4078245600 10800 1 EEST}
-    {4097080800 7200 0 EET}
+    {4078332000 10800 1 EEST}
+    {4096476000 7200 0 EET}
 }
index fe8f7e1..3fdcd65 100644 (file)
@@ -3,16 +3,18 @@
 set TZData(:Asia/Hebron) {
     {-9223372036854775808 8423 0 LMT}
     {-2185410023 7200 0 EEST}
-    {-933645600 10800 1 EEST}
-    {-857358000 7200 0 EEST}
+    {-933638400 10800 1 EEST}
+    {-923097600 7200 0 EEST}
+    {-919036800 10800 1 EEST}
+    {-857347200 7200 0 EEST}
     {-844300800 10800 1 EEST}
-    {-825822000 7200 0 EEST}
-    {-812685600 10800 1 EEST}
-    {-794199600 7200 0 EEST}
-    {-779853600 10800 1 EEST}
-    {-762656400 7200 0 EEST}
+    {-825811200 7200 0 EEST}
+    {-812678400 10800 1 EEST}
+    {-794188800 7200 0 EEST}
+    {-779846400 10800 1 EEST}
+    {-762652800 7200 0 EEST}
     {-748310400 10800 1 EEST}
-    {-731127600 7200 0 EEST}
+    {-731116800 7200 0 EEST}
     {-682653600 7200 0 EET}
     {-399088800 10800 1 EEST}
     {-386650800 7200 0 EET}
@@ -40,12 +42,12 @@ set TZData(:Asia/Hebron) {
     {150843600 7200 0 IST}
     {167176800 10800 1 IDT}
     {178664400 7200 0 IST}
-    {334015200 10800 1 IDT}
-    {337644000 7200 0 IST}
-    {452556000 10800 1 IDT}
-    {462232800 7200 0 IST}
+    {334101600 10800 1 IDT}
+    {337730400 7200 0 IST}
+    {452642400 10800 1 IDT}
+    {462319200 7200 0 IST}
     {482277600 10800 1 IDT}
-    {495579600 7200 0 IST}
+    {494370000 7200 0 IST}
     {516751200 10800 1 IDT}
     {526424400 7200 0 IST}
     {545436000 10800 1 IDT}
@@ -109,7 +111,7 @@ set TZData(:Asia/Hebron) {
     {1395957600 10800 1 EEST}
     {1414098000 7200 0 EET}
     {1427493600 10800 1 EEST}
-    {1445547600 7200 0 EET}
+    {1445551200 7200 0 EET}
     {1458946800 10800 1 EEST}
     {1477692000 7200 0 EET}
     {1490396400 10800 1 EEST}
@@ -117,165 +119,165 @@ set TZData(:Asia/Hebron) {
     {1521846000 10800 1 EEST}
     {1540591200 7200 0 EET}
     {1553810400 10800 1 EEST}
-    {1572040800 7200 0 EET}
-    {1585260000 10800 1 EEST}
-    {1604095200 7200 0 EET}
-    {1616709600 10800 1 EEST}
+    {1572037200 7200 0 EET}
+    {1585346400 10800 1 EEST}
+    {1603490400 7200 0 EET}
+    {1616796000 10800 1 EEST}
     {1635544800 7200 0 EET}
-    {1648159200 10800 1 EEST}
+    {1648245600 10800 1 EEST}
     {1666994400 7200 0 EET}
-    {1680213600 10800 1 EEST}
+    {1679695200 10800 1 EEST}
     {1698444000 7200 0 EET}
-    {1711663200 10800 1 EEST}
+    {1711749600 10800 1 EEST}
     {1729893600 7200 0 EET}
-    {1743112800 10800 1 EEST}
+    {1743199200 10800 1 EEST}
     {1761343200 7200 0 EET}
-    {1774562400 10800 1 EEST}
-    {1793397600 7200 0 EET}
-    {1806012000 10800 1 EEST}
+    {1774648800 10800 1 EEST}
+    {1792792800 7200 0 EET}
+    {1806098400 10800 1 EEST}
     {1824847200 7200 0 EET}
-    {1838066400 10800 1 EEST}
+    {1837548000 10800 1 EEST}
     {1856296800 7200 0 EET}
-    {1869516000 10800 1 EEST}
+    {1868997600 10800 1 EEST}
     {1887746400 7200 0 EET}
-    {1900965600 10800 1 EEST}
+    {1901052000 10800 1 EEST}
     {1919196000 7200 0 EET}
-    {1932415200 10800 1 EEST}
+    {1932501600 10800 1 EEST}
     {1950645600 7200 0 EET}
-    {1963864800 10800 1 EEST}
+    {1963951200 10800 1 EEST}
     {1982700000 7200 0 EET}
-    {1995314400 10800 1 EEST}
+    {1995400800 10800 1 EEST}
     {2014149600 7200 0 EET}
-    {2027368800 10800 1 EEST}
+    {2026850400 10800 1 EEST}
     {2045599200 7200 0 EET}
-    {2058818400 10800 1 EEST}
+    {2058300000 10800 1 EEST}
     {2077048800 7200 0 EET}
-    {2090268000 10800 1 EEST}
+    {2090354400 10800 1 EEST}
     {2108498400 7200 0 EET}
-    {2121717600 10800 1 EEST}
-    {2140552800 7200 0 EET}
-    {2153167200 10800 1 EEST}
+    {2121804000 10800 1 EEST}
+    {2139948000 7200 0 EET}
+    {2153253600 10800 1 EEST}
     {2172002400 7200 0 EET}
-    {2184616800 10800 1 EEST}
+    {2184703200 10800 1 EEST}
     {2203452000 7200 0 EET}
-    {2216671200 10800 1 EEST}
+    {2216152800 10800 1 EEST}
     {2234901600 7200 0 EET}
-    {2248120800 10800 1 EEST}
+    {2248207200 10800 1 EEST}
     {2266351200 7200 0 EET}
-    {2279570400 10800 1 EEST}
+    {2279656800 10800 1 EEST}
     {2297800800 7200 0 EET}
-    {2311020000 10800 1 EEST}
-    {2329855200 7200 0 EET}
-    {2342469600 10800 1 EEST}
+    {2311106400 10800 1 EEST}
+    {2329250400 7200 0 EET}
+    {2342556000 10800 1 EEST}
     {2361304800 7200 0 EET}
-    {2374524000 10800 1 EEST}
+    {2374005600 10800 1 EEST}
     {2392754400 7200 0 EET}
-    {2405973600 10800 1 EEST}
+    {2405455200 10800 1 EEST}
     {2424204000 7200 0 EET}
-    {2437423200 10800 1 EEST}
+    {2437509600 10800 1 EEST}
     {2455653600 7200 0 EET}
-    {2468872800 10800 1 EEST}
-    {2487708000 7200 0 EET}
-    {2500322400 10800 1 EEST}
+    {2468959200 10800 1 EEST}
+    {2487103200 7200 0 EET}
+    {2500408800 10800 1 EEST}
     {2519157600 7200 0 EET}
-    {2531772000 10800 1 EEST}
+    {2531858400 10800 1 EEST}
     {2550607200 7200 0 EET}
-    {2563826400 10800 1 EEST}
+    {2563308000 10800 1 EEST}
     {2582056800 7200 0 EET}
-    {2595276000 10800 1 EEST}
+    {2595362400 10800 1 EEST}
     {2613506400 7200 0 EET}
-    {2626725600 10800 1 EEST}
+    {2626812000 10800 1 EEST}
     {2644956000 7200 0 EET}
-    {2658175200 10800 1 EEST}
-    {2677010400 7200 0 EET}
-    {2689624800 10800 1 EEST}
+    {2658261600 10800 1 EEST}
+    {2676405600 7200 0 EET}
+    {2689711200 10800 1 EEST}
     {2708460000 7200 0 EET}
-    {2721679200 10800 1 EEST}
+    {2721160800 10800 1 EEST}
     {2739909600 7200 0 EET}
-    {2753128800 10800 1 EEST}
+    {2752610400 10800 1 EEST}
     {2771359200 7200 0 EET}
-    {2784578400 10800 1 EEST}
+    {2784664800 10800 1 EEST}
     {2802808800 7200 0 EET}
-    {2816028000 10800 1 EEST}
+    {2816114400 10800 1 EEST}
     {2834258400 7200 0 EET}
-    {2847477600 10800 1 EEST}
+    {2847564000 10800 1 EEST}
     {2866312800 7200 0 EET}
-    {2878927200 10800 1 EEST}
+    {2879013600 10800 1 EEST}
     {2897762400 7200 0 EET}
-    {2910981600 10800 1 EEST}
+    {2910463200 10800 1 EEST}
     {2929212000 7200 0 EET}
-    {2942431200 10800 1 EEST}
+    {2941912800 10800 1 EEST}
     {2960661600 7200 0 EET}
-    {2973880800 10800 1 EEST}
+    {2973967200 10800 1 EEST}
     {2992111200 7200 0 EET}
-    {3005330400 10800 1 EEST}
-    {3024165600 7200 0 EET}
-    {3036780000 10800 1 EEST}
+    {3005416800 10800 1 EEST}
+    {3023560800 7200 0 EET}
+    {3036866400 10800 1 EEST}
     {3055615200 7200 0 EET}
-    {3068229600 10800 1 EEST}
+    {3068316000 10800 1 EEST}
     {3087064800 7200 0 EET}
-    {3100284000 10800 1 EEST}
+    {3099765600 10800 1 EEST}
     {3118514400 7200 0 EET}
-    {3131733600 10800 1 EEST}
+    {3131820000 10800 1 EEST}
     {3149964000 7200 0 EET}
-    {3163183200 10800 1 EEST}
+    {3163269600 10800 1 EEST}
     {3181413600 7200 0 EET}
-    {3194632800 10800 1 EEST}
-    {3213468000 7200 0 EET}
-    {3226082400 10800 1 EEST}
+    {3194719200 10800 1 EEST}
+    {3212863200 7200 0 EET}
+    {3226168800 10800 1 EEST}
     {3244917600 7200 0 EET}
-    {3258136800 10800 1 EEST}
+    {3257618400 10800 1 EEST}
     {3276367200 7200 0 EET}
-    {3289586400 10800 1 EEST}
+    {3289068000 10800 1 EEST}
     {3307816800 7200 0 EET}
-    {3321036000 10800 1 EEST}
+    {3321122400 10800 1 EEST}
     {3339266400 7200 0 EET}
-    {3352485600 10800 1 EEST}
-    {3371320800 7200 0 EET}
-    {3383935200 10800 1 EEST}
+    {3352572000 10800 1 EEST}
+    {3370716000 7200 0 EET}
+    {3384021600 10800 1 EEST}
     {3402770400 7200 0 EET}
-    {3415384800 10800 1 EEST}
+    {3415471200 10800 1 EEST}
     {3434220000 7200 0 EET}
-    {3447439200 10800 1 EEST}
+    {3446920800 10800 1 EEST}
     {3465669600 7200 0 EET}
-    {3478888800 10800 1 EEST}
+    {3478975200 10800 1 EEST}
     {3497119200 7200 0 EET}
-    {3510338400 10800 1 EEST}
+    {3510424800 10800 1 EEST}
     {3528568800 7200 0 EET}
-    {3541788000 10800 1 EEST}
-    {3560623200 7200 0 EET}
-    {3573237600 10800 1 EEST}
+    {3541874400 10800 1 EEST}
+    {3560018400 7200 0 EET}
+    {3573324000 10800 1 EEST}
     {3592072800 7200 0 EET}
-    {3605292000 10800 1 EEST}
+    {3604773600 10800 1 EEST}
     {3623522400 7200 0 EET}
-    {3636741600 10800 1 EEST}
+    {3636223200 10800 1 EEST}
     {3654972000 7200 0 EET}
-    {3668191200 10800 1 EEST}
+    {3668277600 10800 1 EEST}
     {3686421600 7200 0 EET}
-    {3699640800 10800 1 EEST}
+    {3699727200 10800 1 EEST}
     {3717871200 7200 0 EET}
-    {3731090400 10800 1 EEST}
+    {3731176800 10800 1 EEST}
     {3749925600 7200 0 EET}
-    {3762540000 10800 1 EEST}
+    {3762626400 10800 1 EEST}
     {3781375200 7200 0 EET}
-    {3794594400 10800 1 EEST}
+    {3794076000 10800 1 EEST}
     {3812824800 7200 0 EET}
-    {3826044000 10800 1 EEST}
+    {3825525600 10800 1 EEST}
     {3844274400 7200 0 EET}
-    {3857493600 10800 1 EEST}
+    {3857580000 10800 1 EEST}
     {3875724000 7200 0 EET}
-    {3888943200 10800 1 EEST}
-    {3907778400 7200 0 EET}
-    {3920392800 10800 1 EEST}
+    {3889029600 10800 1 EEST}
+    {3907173600 7200 0 EET}
+    {3920479200 10800 1 EEST}
     {3939228000 7200 0 EET}
-    {3951842400 10800 1 EEST}
+    {3951928800 10800 1 EEST}
     {3970677600 7200 0 EET}
-    {3983896800 10800 1 EEST}
+    {3983378400 10800 1 EEST}
     {4002127200 7200 0 EET}
-    {4015346400 10800 1 EEST}
+    {4015432800 10800 1 EEST}
     {4033576800 7200 0 EET}
-    {4046796000 10800 1 EEST}
+    {4046882400 10800 1 EEST}
     {4065026400 7200 0 EET}
-    {4078245600 10800 1 EEST}
-    {4097080800 7200 0 EET}
+    {4078332000 10800 1 EEST}
+    {4096476000 7200 0 EET}
 }
index e1e84f4..596deb3 100644 (file)
@@ -4,47 +4,49 @@ set TZData(:Asia/Jerusalem) {
     {-9223372036854775808 8454 0 LMT}
     {-2840149254 8440 0 JMT}
     {-1641003640 7200 0 IST}
-    {-933645600 10800 1 IDT}
-    {-857358000 7200 0 IST}
+    {-933638400 10800 1 IDT}
+    {-923097600 7200 0 IST}
+    {-919036800 10800 1 IDT}
+    {-857347200 7200 0 IST}
     {-844300800 10800 1 IDT}
-    {-825822000 7200 0 IST}
-    {-812685600 10800 1 IDT}
-    {-794199600 7200 0 IST}
-    {-779853600 10800 1 IDT}
-    {-762656400 7200 0 IST}
+    {-825811200 7200 0 IST}
+    {-812678400 10800 1 IDT}
+    {-794188800 7200 0 IST}
+    {-779846400 10800 1 IDT}
+    {-762652800 7200 0 IST}
     {-748310400 10800 1 IDT}
-    {-731127600 7200 0 IST}
-    {-681962400 14400 1 IDDT}
-    {-673243200 10800 1 IDT}
-    {-667962000 7200 0 IST}
-    {-652327200 10800 1 IDT}
-    {-636426000 7200 0 IST}
-    {-622087200 10800 1 IDT}
+    {-731116800 7200 0 IST}
+    {-681955200 14400 1 IDDT}
+    {-673228800 10800 1 IDT}
+    {-667958400 7200 0 IST}
+    {-652320000 10800 1 IDT}
+    {-636422400 7200 0 IST}
+    {-622080000 10800 1 IDT}
     {-608947200 7200 0 IST}
-    {-591847200 10800 1 IDT}
+    {-591840000 10800 1 IDT}
     {-572486400 7200 0 IST}
     {-558576000 10800 1 IDT}
     {-542851200 7200 0 IST}
     {-527731200 10800 1 IDT}
     {-514425600 7200 0 IST}
-    {-490845600 10800 1 IDT}
-    {-482986800 7200 0 IST}
-    {-459475200 10800 1 IDT}
-    {-451537200 7200 0 IST}
-    {-428551200 10800 1 IDT}
+    {-490838400 10800 1 IDT}
+    {-482976000 7200 0 IST}
+    {-459388800 10800 1 IDT}
+    {-451526400 7200 0 IST}
+    {-428544000 10800 1 IDT}
     {-418262400 7200 0 IST}
-    {-400032000 10800 1 IDT}
-    {-387428400 7200 0 IST}
+    {-400118400 10800 1 IDT}
+    {-387417600 7200 0 IST}
     {142380000 10800 1 IDT}
     {150843600 7200 0 IST}
     {167176800 10800 1 IDT}
     {178664400 7200 0 IST}
-    {334015200 10800 1 IDT}
-    {337644000 7200 0 IST}
-    {452556000 10800 1 IDT}
-    {462232800 7200 0 IST}
+    {334101600 10800 1 IDT}
+    {337730400 7200 0 IST}
+    {452642400 10800 1 IDT}
+    {462319200 7200 0 IST}
     {482277600 10800 1 IDT}
-    {495579600 7200 0 IST}
+    {494370000 7200 0 IST}
     {516751200 10800 1 IDT}
     {526424400 7200 0 IST}
     {545436000 10800 1 IDT}
index 66bc433..0fcf802 100644 (file)
@@ -3,6 +3,8 @@
 set TZData(:Asia/Shanghai) {
     {-9223372036854775808 29143 0 LMT}
     {-2177481943 28800 0 CST}
+    {-1600675200 32400 1 CDT}
+    {-1585904400 28800 0 CST}
     {-933667200 32400 1 CDT}
     {-922093200 28800 0 CST}
     {-908870400 32400 1 CDT}
index 2d4d983..40ab5d7 100644 (file)
@@ -2,7 +2,34 @@
 
 set TZData(:Atlantic/Bermuda) {
     {-9223372036854775808 -15558 0 LMT}
-    {-1262281242 -14400 0 AST}
+    {-2524506042 -15558 0 BMT}
+    {-1664307642 -11958 1 BMT}
+    {-1648932042 -15558 0 BMT}
+    {-1632080442 -11958 1 BMT}
+    {-1618692042 -15558 0 BST}
+    {-1262281242 -14400 0 AT}
+    {-882727200 -10800 1 ADT}
+    {-858538800 -14400 0 AST}
+    {-845229600 -10800 1 ADT}
+    {-825879600 -14400 0 AST}
+    {-814384800 -10800 1 ADT}
+    {-793825200 -14400 0 AST}
+    {-782935200 -10800 1 ADT}
+    {-762375600 -14400 0 AST}
+    {-713988000 -10800 1 ADT}
+    {-703710000 -14400 0 AST}
+    {-681933600 -10800 1 ADT}
+    {-672865200 -14400 0 AST}
+    {-650484000 -10800 1 ADT}
+    {-641415600 -14400 0 AST}
+    {-618429600 -10800 1 ADT}
+    {-609966000 -14400 0 AST}
+    {-586980000 -10800 1 ADT}
+    {-578516400 -14400 0 AST}
+    {-555530400 -10800 1 ADT}
+    {-546462000 -14400 0 AST}
+    {-429127200 -10800 1 ADT}
+    {-415825200 -14400 0 AST}
     {136360800 -10800 0 ADT}
     {152082000 -14400 0 AST}
     {167810400 -10800 1 ADT}
index 7e1b04e..5f7c1a4 100644 (file)
@@ -4,14 +4,14 @@ set TZData(:Australia/Adelaide) {
     {-9223372036854775808 33260 0 LMT}
     {-2364110060 32400 0 ACST}
     {-2230189200 34200 0 ACST}
-    {-1672565340 37800 1 ACDT}
-    {-1665390600 34200 0 ACST}
+    {-1672558200 37800 1 ACDT}
+    {-1665387000 34200 0 ACST}
     {-883639800 37800 1 ACDT}
-    {-876126600 34200 0 ACST}
+    {-876123000 34200 0 ACST}
     {-860398200 37800 1 ACDT}
-    {-844677000 34200 0 ACST}
+    {-844673400 34200 0 ACST}
     {-828343800 37800 1 ACDT}
-    {-813227400 34200 0 ACST}
+    {-813223800 34200 0 ACST}
     {31501800 34200 0 ACST}
     {57688200 37800 1 ACDT}
     {67969800 34200 0 ACST}
index 8422ae6..325313a 100644 (file)
@@ -3,14 +3,14 @@
 set TZData(:Australia/Brisbane) {
     {-9223372036854775808 36728 0 LMT}
     {-2366791928 36000 0 AEST}
-    {-1672567140 39600 1 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1672560000 39600 1 AEDT}
+    {-1665388800 36000 0 AEST}
     {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
+    {-876124800 36000 0 AEST}
     {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
+    {-844675200 36000 0 AEST}
     {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
+    {-813225600 36000 0 AEST}
     {31500000 36000 0 AEST}
     {57686400 39600 1 AEDT}
     {67968000 36000 0 AEST}
index c428061..2534b70 100644 (file)
@@ -5,14 +5,14 @@ set TZData(:Australia/Broken_Hill) {
     {-2364110748 36000 0 AEST}
     {-2314951200 32400 0 ACST}
     {-2230189200 34200 0 ACST}
-    {-1672565340 37800 1 ACDT}
-    {-1665390600 34200 0 ACST}
+    {-1672558200 37800 1 ACDT}
+    {-1665387000 34200 0 ACST}
     {-883639800 37800 1 ACDT}
-    {-876126600 34200 0 ACST}
+    {-876123000 34200 0 ACST}
     {-860398200 37800 1 ACDT}
-    {-844677000 34200 0 ACST}
+    {-844673400 34200 0 ACST}
     {-828343800 37800 1 ACDT}
-    {-813227400 34200 0 ACST}
+    {-813223800 34200 0 ACST}
     {31501800 34200 0 ACST}
     {57688200 37800 1 ACDT}
     {67969800 34200 0 ACST}
index 936327b..3315aa3 100644 (file)
@@ -1,273 +1,5 @@
 # created by tools/tclZIC.tcl - do not edit
-
-set TZData(:Australia/Currie) {
-    {-9223372036854775808 34528 0 LMT}
-    {-2345794528 36000 0 AEST}
-    {-1680508800 39600 1 AEDT}
-    {-1669892400 39600 0 AEDT}
-    {-1665392400 36000 0 AEST}
-    {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
-    {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
-    {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
-    {47138400 36000 0 AEST}
-    {57686400 39600 1 AEDT}
-    {67968000 36000 0 AEST}
-    {89136000 39600 1 AEDT}
-    {100022400 36000 0 AEST}
-    {120585600 39600 1 AEDT}
-    {131472000 36000 0 AEST}
-    {152035200 39600 1 AEDT}
-    {162921600 36000 0 AEST}
-    {183484800 39600 1 AEDT}
-    {194976000 36000 0 AEST}
-    {215539200 39600 1 AEDT}
-    {226425600 36000 0 AEST}
-    {246988800 39600 1 AEDT}
-    {257875200 36000 0 AEST}
-    {278438400 39600 1 AEDT}
-    {289324800 36000 0 AEST}
-    {309888000 39600 1 AEDT}
-    {320774400 36000 0 AEST}
-    {341337600 39600 1 AEDT}
-    {352224000 36000 0 AEST}
-    {372787200 39600 1 AEDT}
-    {386092800 36000 0 AEST}
-    {404841600 39600 1 AEDT}
-    {417542400 36000 0 AEST}
-    {436291200 39600 1 AEDT}
-    {447177600 36000 0 AEST}
-    {467740800 39600 1 AEDT}
-    {478627200 36000 0 AEST}
-    {499190400 39600 1 AEDT}
-    {510076800 36000 0 AEST}
-    {530035200 39600 1 AEDT}
-    {542736000 36000 0 AEST}
-    {562089600 39600 1 AEDT}
-    {574790400 36000 0 AEST}
-    {594144000 39600 1 AEDT}
-    {606240000 36000 0 AEST}
-    {625593600 39600 1 AEDT}
-    {637689600 36000 0 AEST}
-    {657043200 39600 1 AEDT}
-    {670348800 36000 0 AEST}
-    {686678400 39600 1 AEDT}
-    {701798400 36000 0 AEST}
-    {718128000 39600 1 AEDT}
-    {733248000 36000 0 AEST}
-    {749577600 39600 1 AEDT}
-    {764697600 36000 0 AEST}
-    {781027200 39600 1 AEDT}
-    {796147200 36000 0 AEST}
-    {812476800 39600 1 AEDT}
-    {828201600 36000 0 AEST}
-    {844531200 39600 1 AEDT}
-    {859651200 36000 0 AEST}
-    {875980800 39600 1 AEDT}
-    {891100800 36000 0 AEST}
-    {907430400 39600 1 AEDT}
-    {922550400 36000 0 AEST}
-    {938880000 39600 1 AEDT}
-    {954000000 36000 0 AEST}
-    {967305600 39600 1 AEDT}
-    {985449600 36000 0 AEST}
-    {1002384000 39600 1 AEDT}
-    {1017504000 36000 0 AEST}
-    {1033833600 39600 1 AEDT}
-    {1048953600 36000 0 AEST}
-    {1065283200 39600 1 AEDT}
-    {1080403200 36000 0 AEST}
-    {1096732800 39600 1 AEDT}
-    {1111852800 36000 0 AEST}
-    {1128182400 39600 1 AEDT}
-    {1143907200 36000 0 AEST}
-    {1159632000 39600 1 AEDT}
-    {1174752000 36000 0 AEST}
-    {1191686400 39600 1 AEDT}
-    {1207411200 36000 0 AEST}
-    {1223136000 39600 1 AEDT}
-    {1238860800 36000 0 AEST}
-    {1254585600 39600 1 AEDT}
-    {1270310400 36000 0 AEST}
-    {1286035200 39600 1 AEDT}
-    {1301760000 36000 0 AEST}
-    {1317484800 39600 1 AEDT}
-    {1333209600 36000 0 AEST}
-    {1349539200 39600 1 AEDT}
-    {1365264000 36000 0 AEST}
-    {1380988800 39600 1 AEDT}
-    {1396713600 36000 0 AEST}
-    {1412438400 39600 1 AEDT}
-    {1428163200 36000 0 AEST}
-    {1443888000 39600 1 AEDT}
-    {1459612800 36000 0 AEST}
-    {1475337600 39600 1 AEDT}
-    {1491062400 36000 0 AEST}
-    {1506787200 39600 1 AEDT}
-    {1522512000 36000 0 AEST}
-    {1538841600 39600 1 AEDT}
-    {1554566400 36000 0 AEST}
-    {1570291200 39600 1 AEDT}
-    {1586016000 36000 0 AEST}
-    {1601740800 39600 1 AEDT}
-    {1617465600 36000 0 AEST}
-    {1633190400 39600 1 AEDT}
-    {1648915200 36000 0 AEST}
-    {1664640000 39600 1 AEDT}
-    {1680364800 36000 0 AEST}
-    {1696089600 39600 1 AEDT}
-    {1712419200 36000 0 AEST}
-    {1728144000 39600 1 AEDT}
-    {1743868800 36000 0 AEST}
-    {1759593600 39600 1 AEDT}
-    {1775318400 36000 0 AEST}
-    {1791043200 39600 1 AEDT}
-    {1806768000 36000 0 AEST}
-    {1822492800 39600 1 AEDT}
-    {1838217600 36000 0 AEST}
-    {1853942400 39600 1 AEDT}
-    {1869667200 36000 0 AEST}
-    {1885996800 39600 1 AEDT}
-    {1901721600 36000 0 AEST}
-    {1917446400 39600 1 AEDT}
-    {1933171200 36000 0 AEST}
-    {1948896000 39600 1 AEDT}
-    {1964620800 36000 0 AEST}
-    {1980345600 39600 1 AEDT}
-    {1996070400 36000 0 AEST}
-    {2011795200 39600 1 AEDT}
-    {2027520000 36000 0 AEST}
-    {2043244800 39600 1 AEDT}
-    {2058969600 36000 0 AEST}
-    {2075299200 39600 1 AEDT}
-    {2091024000 36000 0 AEST}
-    {2106748800 39600 1 AEDT}
-    {2122473600 36000 0 AEST}
-    {2138198400 39600 1 AEDT}
-    {2153923200 36000 0 AEST}
-    {2169648000 39600 1 AEDT}
-    {2185372800 36000 0 AEST}
-    {2201097600 39600 1 AEDT}
-    {2216822400 36000 0 AEST}
-    {2233152000 39600 1 AEDT}
-    {2248876800 36000 0 AEST}
-    {2264601600 39600 1 AEDT}
-    {2280326400 36000 0 AEST}
-    {2296051200 39600 1 AEDT}
-    {2311776000 36000 0 AEST}
-    {2327500800 39600 1 AEDT}
-    {2343225600 36000 0 AEST}
-    {2358950400 39600 1 AEDT}
-    {2374675200 36000 0 AEST}
-    {2390400000 39600 1 AEDT}
-    {2406124800 36000 0 AEST}
-    {2422454400 39600 1 AEDT}
-    {2438179200 36000 0 AEST}
-    {2453904000 39600 1 AEDT}
-    {2469628800 36000 0 AEST}
-    {2485353600 39600 1 AEDT}
-    {2501078400 36000 0 AEST}
-    {2516803200 39600 1 AEDT}
-    {2532528000 36000 0 AEST}
-    {2548252800 39600 1 AEDT}
-    {2563977600 36000 0 AEST}
-    {2579702400 39600 1 AEDT}
-    {2596032000 36000 0 AEST}
-    {2611756800 39600 1 AEDT}
-    {2627481600 36000 0 AEST}
-    {2643206400 39600 1 AEDT}
-    {2658931200 36000 0 AEST}
-    {2674656000 39600 1 AEDT}
-    {2690380800 36000 0 AEST}
-    {2706105600 39600 1 AEDT}
-    {2721830400 36000 0 AEST}
-    {2737555200 39600 1 AEDT}
-    {2753280000 36000 0 AEST}
-    {2769609600 39600 1 AEDT}
-    {2785334400 36000 0 AEST}
-    {2801059200 39600 1 AEDT}
-    {2816784000 36000 0 AEST}
-    {2832508800 39600 1 AEDT}
-    {2848233600 36000 0 AEST}
-    {2863958400 39600 1 AEDT}
-    {2879683200 36000 0 AEST}
-    {2895408000 39600 1 AEDT}
-    {2911132800 36000 0 AEST}
-    {2926857600 39600 1 AEDT}
-    {2942582400 36000 0 AEST}
-    {2958912000 39600 1 AEDT}
-    {2974636800 36000 0 AEST}
-    {2990361600 39600 1 AEDT}
-    {3006086400 36000 0 AEST}
-    {3021811200 39600 1 AEDT}
-    {3037536000 36000 0 AEST}
-    {3053260800 39600 1 AEDT}
-    {3068985600 36000 0 AEST}
-    {3084710400 39600 1 AEDT}
-    {3100435200 36000 0 AEST}
-    {3116764800 39600 1 AEDT}
-    {3132489600 36000 0 AEST}
-    {3148214400 39600 1 AEDT}
-    {3163939200 36000 0 AEST}
-    {3179664000 39600 1 AEDT}
-    {3195388800 36000 0 AEST}
-    {3211113600 39600 1 AEDT}
-    {3226838400 36000 0 AEST}
-    {3242563200 39600 1 AEDT}
-    {3258288000 36000 0 AEST}
-    {3274012800 39600 1 AEDT}
-    {3289737600 36000 0 AEST}
-    {3306067200 39600 1 AEDT}
-    {3321792000 36000 0 AEST}
-    {3337516800 39600 1 AEDT}
-    {3353241600 36000 0 AEST}
-    {3368966400 39600 1 AEDT}
-    {3384691200 36000 0 AEST}
-    {3400416000 39600 1 AEDT}
-    {3416140800 36000 0 AEST}
-    {3431865600 39600 1 AEDT}
-    {3447590400 36000 0 AEST}
-    {3463315200 39600 1 AEDT}
-    {3479644800 36000 0 AEST}
-    {3495369600 39600 1 AEDT}
-    {3511094400 36000 0 AEST}
-    {3526819200 39600 1 AEDT}
-    {3542544000 36000 0 AEST}
-    {3558268800 39600 1 AEDT}
-    {3573993600 36000 0 AEST}
-    {3589718400 39600 1 AEDT}
-    {3605443200 36000 0 AEST}
-    {3621168000 39600 1 AEDT}
-    {3636892800 36000 0 AEST}
-    {3653222400 39600 1 AEDT}
-    {3668947200 36000 0 AEST}
-    {3684672000 39600 1 AEDT}
-    {3700396800 36000 0 AEST}
-    {3716121600 39600 1 AEDT}
-    {3731846400 36000 0 AEST}
-    {3747571200 39600 1 AEDT}
-    {3763296000 36000 0 AEST}
-    {3779020800 39600 1 AEDT}
-    {3794745600 36000 0 AEST}
-    {3810470400 39600 1 AEDT}
-    {3826195200 36000 0 AEST}
-    {3842524800 39600 1 AEDT}
-    {3858249600 36000 0 AEST}
-    {3873974400 39600 1 AEDT}
-    {3889699200 36000 0 AEST}
-    {3905424000 39600 1 AEDT}
-    {3921148800 36000 0 AEST}
-    {3936873600 39600 1 AEDT}
-    {3952598400 36000 0 AEST}
-    {3968323200 39600 1 AEDT}
-    {3984048000 36000 0 AEST}
-    {4000377600 39600 1 AEDT}
-    {4016102400 36000 0 AEST}
-    {4031827200 39600 1 AEDT}
-    {4047552000 36000 0 AEST}
-    {4063276800 39600 1 AEDT}
-    {4079001600 36000 0 AEST}
-    {4094726400 39600 1 AEDT}
+if {![info exists TZData(Australia/Hobart)]} {
+    LoadTimeZoneFile Australia/Hobart
 }
+set TZData(:Australia/Currie) $TZData(:Australia/Hobart)
index e77605d..13f13ee 100644 (file)
@@ -4,12 +4,12 @@ set TZData(:Australia/Darwin) {
     {-9223372036854775808 31400 0 LMT}
     {-2364108200 32400 0 ACST}
     {-2230189200 34200 0 ACST}
-    {-1672565340 37800 1 ACDT}
-    {-1665390600 34200 0 ACST}
+    {-1672558200 37800 1 ACDT}
+    {-1665387000 34200 0 ACST}
     {-883639800 37800 1 ACDT}
-    {-876126600 34200 0 ACST}
+    {-876123000 34200 0 ACST}
     {-860398200 37800 1 ACDT}
-    {-844677000 34200 0 ACST}
+    {-844673400 34200 0 ACST}
     {-828343800 37800 1 ACDT}
-    {-813227400 34200 0 ACST}
+    {-813223800 34200 0 ACST}
 }
index 8008980..1d81a3d 100644 (file)
@@ -3,12 +3,12 @@
 set TZData(:Australia/Eucla) {
     {-9223372036854775808 30928 0 LMT}
     {-2337928528 31500 0 +0945}
-    {-1672562640 35100 1 +0945}
-    {-1665387900 31500 0 +0945}
+    {-1672555500 35100 1 +0945}
+    {-1665384300 31500 0 +0945}
     {-883637100 35100 1 +0945}
-    {-876123900 31500 0 +0945}
+    {-876120300 31500 0 +0945}
     {-860395500 35100 1 +0945}
-    {-844674300 31500 0 +0945}
+    {-844670700 31500 0 +0945}
     {-836473500 35100 0 +0945}
     {152039700 35100 1 +0945}
     {162926100 31500 0 +0945}
index bf5adf0..5ff675e 100644 (file)
@@ -4,14 +4,18 @@ set TZData(:Australia/Hobart) {
     {-9223372036854775808 35356 0 LMT}
     {-2345795356 36000 0 AEST}
     {-1680508800 39600 1 AEDT}
-    {-1669892400 39600 0 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1665388800 36000 0 AEST}
+    {-1646640000 39600 1 AEDT}
+    {-1635753600 36000 0 AEST}
+    {-1615190400 39600 1 AEDT}
+    {-1604304000 36000 0 AEST}
+    {-1583920800 36000 0 AEST}
     {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
+    {-876124800 36000 0 AEST}
     {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
+    {-844675200 36000 0 AEST}
     {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
+    {-813225600 36000 0 AEST}
     {-94730400 36000 0 AEST}
     {-71136000 39600 1 AEDT}
     {-55411200 36000 0 AEST}
index 91ad0a6..1be6962 100644 (file)
@@ -3,14 +3,14 @@
 set TZData(:Australia/Lindeman) {
     {-9223372036854775808 35756 0 LMT}
     {-2366790956 36000 0 AEST}
-    {-1672567140 39600 1 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1672560000 39600 1 AEDT}
+    {-1665388800 36000 0 AEST}
     {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
+    {-876124800 36000 0 AEST}
     {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
+    {-844675200 36000 0 AEST}
     {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
+    {-813225600 36000 0 AEST}
     {31500000 36000 0 AEST}
     {57686400 39600 1 AEDT}
     {67968000 36000 0 AEST}
index 81777df..77e9067 100644 (file)
@@ -3,14 +3,14 @@
 set TZData(:Australia/Melbourne) {
     {-9223372036854775808 34792 0 LMT}
     {-2364111592 36000 0 AEST}
-    {-1672567140 39600 1 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1672560000 39600 1 AEDT}
+    {-1665388800 36000 0 AEST}
     {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
+    {-876124800 36000 0 AEST}
     {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
+    {-844675200 36000 0 AEST}
     {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
+    {-813225600 36000 0 AEST}
     {31500000 36000 0 AEST}
     {57686400 39600 1 AEDT}
     {67968000 36000 0 AEST}
index 6ccbca8..4ed3cba 100644 (file)
@@ -3,12 +3,12 @@
 set TZData(:Australia/Perth) {
     {-9223372036854775808 27804 0 LMT}
     {-2337925404 28800 0 AWST}
-    {-1672559940 32400 1 AWDT}
-    {-1665385200 28800 0 AWST}
+    {-1672552800 32400 1 AWDT}
+    {-1665381600 28800 0 AWST}
     {-883634400 32400 1 AWDT}
-    {-876121200 28800 0 AWST}
+    {-876117600 28800 0 AWST}
     {-860392800 32400 1 AWDT}
-    {-844671600 28800 0 AWST}
+    {-844668000 28800 0 AWST}
     {-836470800 32400 0 AWST}
     {152042400 32400 1 AWDT}
     {162928800 28800 0 AWST}
index b1c4411..fd01af6 100644 (file)
@@ -3,14 +3,14 @@
 set TZData(:Australia/Sydney) {
     {-9223372036854775808 36292 0 LMT}
     {-2364113092 36000 0 AEST}
-    {-1672567140 39600 1 AEDT}
-    {-1665392400 36000 0 AEST}
+    {-1672560000 39600 1 AEDT}
+    {-1665388800 36000 0 AEST}
     {-883641600 39600 1 AEDT}
-    {-876128400 36000 0 AEST}
+    {-876124800 36000 0 AEST}
     {-860400000 39600 1 AEDT}
-    {-844678800 36000 0 AEST}
+    {-844675200 36000 0 AEST}
     {-828345600 39600 1 AEDT}
-    {-813229200 36000 0 AEST}
+    {-813225600 36000 0 AEST}
     {31500000 36000 0 AEST}
     {57686400 39600 1 AEDT}
     {67968000 36000 0 AEST}
index e660ad1..4b92c5f 100644 (file)
@@ -2,17 +2,19 @@
 
 set TZData(:Europe/Budapest) {
     {-9223372036854775808 4580 0 LMT}
-    {-2500938980 3600 0 CET}
+    {-2498260580 3600 0 CET}
     {-1693706400 7200 1 CEST}
     {-1680483600 3600 0 CET}
     {-1663455600 7200 1 CEST}
     {-1650150000 3600 0 CET}
     {-1640998800 3600 0 CET}
-    {-1633212000 7200 1 CEST}
+    {-1632006000 7200 1 CEST}
     {-1618700400 3600 0 CET}
-    {-1600466400 7200 1 CEST}
-    {-1581202800 3600 0 CET}
-    {-906771600 3600 0 CET}
+    {-1600470000 7200 1 CEST}
+    {-1587250800 3600 0 CET}
+    {-1569711600 7200 1 CEST}
+    {-1555196400 3600 0 CET}
+    {-906775200 3600 0 CET}
     {-857257200 3600 0 CET}
     {-844556400 7200 1 CEST}
     {-828226800 3600 0 CET}
@@ -20,33 +22,32 @@ set TZData(:Europe/Budapest) {
     {-796777200 3600 0 CET}
     {-788922000 3600 0 CET}
     {-778471200 7200 1 CEST}
-    {-762660000 3600 0 CET}
+    {-762656400 3600 0 CET}
     {-749689200 7200 1 CEST}
-    {-733359600 3600 0 CET}
+    {-733276800 3600 0 CET}
     {-717634800 7200 1 CEST}
     {-701910000 3600 0 CET}
     {-686185200 7200 1 CEST}
     {-670460400 3600 0 CET}
     {-654130800 7200 1 CEST}
     {-639010800 3600 0 CET}
-    {-621990000 7200 1 CEST}
-    {-605660400 3600 0 CET}
     {-492656400 7200 1 CEST}
     {-481168800 3600 0 CET}
-    {-461120400 7200 1 CEST}
-    {-449632800 3600 0 CET}
-    {-428547600 7200 1 CEST}
-    {-418269600 3600 0 CET}
-    {-397094400 7200 1 CEST}
+    {-461199600 7200 1 CEST}
+    {-449708400 3600 0 CET}
+    {-428540400 7200 1 CEST}
+    {-418258800 3600 0 CET}
+    {-397090800 7200 1 CEST}
     {-386809200 3600 0 CET}
-    {323827200 7200 1 CEST}
-    {338950800 3600 0 CET}
-    {354675600 7200 1 CEST}
-    {370400400 3600 0 CET}
-    {386125200 7200 1 CEST}
-    {401850000 3600 0 CET}
-    {417574800 7200 1 CEST}
-    {433299600 3600 0 CET}
+    {323823600 7200 1 CEST}
+    {338943600 3600 0 CET}
+    {354668400 7200 1 CEST}
+    {370393200 3600 0 CET}
+    {386118000 7200 1 CEST}
+    {401842800 3600 0 CET}
+    {417567600 7200 1 CEST}
+    {433292400 3600 0 CET}
+    {441759600 3600 0 CET}
     {449024400 7200 1 CEST}
     {465354000 3600 0 CET}
     {481078800 7200 1 CEST}
index f887b0b..7428b2f 100644 (file)
@@ -2,8 +2,8 @@
 
 set TZData(:Europe/Monaco) {
     {-9223372036854775808 1772 0 LMT}
-    {-2486680172 561 0 PMT}
-    {-1855958961 0 0 WET}
+    {-2448318572 561 0 PMT}
+    {-1854403761 0 0 WET}
     {-1689814800 3600 1 WEST}
     {-1680397200 0 0 WET}
     {-1665363600 3600 1 WEST}
index 4b22a09..7208e55 100644 (file)
@@ -2,8 +2,8 @@
 
 set TZData(:Europe/Paris) {
     {-9223372036854775808 561 0 LMT}
-    {-2486678901 561 0 PMT}
-    {-1855958901 0 0 WET}
+    {-2486592561 561 0 PMT}
+    {-1855958961 0 0 WET}
     {-1689814800 3600 1 WEST}
     {-1680397200 0 0 WET}
     {-1665363600 3600 1 WEST}
index 3938683..2ce2dfe 100644 (file)
@@ -69,4 +69,5 @@ set TZData(:Europe/Volgograd) {
     {1301180400 14400 0 +04}
     {1414274400 10800 0 +03}
     {1540681200 14400 0 +04}
+    {1609020000 10800 0 +03}
 }
index 3dd5b40..dcafc36 100644 (file)
@@ -2,5 +2,5 @@
 
 set TZData(:Indian/Mahe) {
     {-9223372036854775808 13308 0 LMT}
-    {-2006653308 14400 0 +04}
+    {-1988163708 14400 0 +04}
 }
index a026ee1..5a22546 100644 (file)
@@ -3,9 +3,11 @@
 set TZData(:Pacific/Efate) {
     {-9223372036854775808 40396 0 LMT}
     {-1829387596 39600 0 +11}
+    {125409600 43200 1 +11}
+    {133876800 39600 0 +11}
     {433256400 43200 1 +11}
     {448977600 39600 0 +11}
-    {467298000 43200 1 +11}
+    {464706000 43200 1 +11}
     {480427200 39600 0 +11}
     {496760400 43200 1 +11}
     {511876800 39600 0 +11}
index e316b93..a062913 100644 (file)
@@ -29,7 +29,7 @@ set TZData(:Pacific/Fiji) {
     {1547301600 43200 0 +12}
     {1573308000 46800 1 +12}
     {1578751200 43200 0 +12}
-    {1604757600 46800 1 +12}
+    {1608386400 46800 1 +12}
     {1610805600 43200 0 +12}
     {1636812000 46800 1 +12}
     {1642255200 43200 0 +12}
index 3e4bc3a..828f13a 100644 (file)
@@ -4,8 +4,8 @@
 # strings. This file is primarily needed so Tk text and entry widgets behave
 # properly for different platforms.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
-# Copyright (c) 1998 by Scritpics Corporation.
+# Copyright (c) 1996 Sun Microsystems, Inc.
+# Copyright (c) 1998 Scritpics Corporation.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -146,7 +146,9 @@ proc tcl_startOfNextWord {str start} {
 proc tcl_startOfPreviousWord {str start} {
     variable ::tcl::WordBreakRE
     set word {-1 -1}
-    regexp -indices -- $WordBreakRE(previous) [string range $str 0 $start-1] \
-           result word
+    if {$start > 0} {
+       regexp -indices -- $WordBreakRE(previous) [string range $str 0 $start-1] \
+               result word
+    }
     return [lindex $word 0]
 }
index 56e5500..cdeb099 100644 (file)
@@ -32,6 +32,18 @@ MANDIR                       ?= ${PREFIX}/man
 # set to non-empty value to install manpages in addition to html help:
 INSTALL_MANPAGES       ?=
 
+# Checks and overrides for subframework builds
+ifeq (${SUBFRAMEWORK},1)
+ifeq (${DYLIB_INSTALL_DIR},)
+       @echo "Cannot install subframework with empty DYLIB_INSTALL_DIR !" && false
+endif
+ifeq (${DESTDIR},)
+       @echo "Cannot install subframework with empty DESTDIR !" && false
+endif
+override BUILD_DIR = ${DESTDIR}/build
+override INSTALL_PATH = /Frameworks
+endif
+
 #-------------------------------------------------------------------------------------------------------
 # meta targets
 
index c944c0a..c2bcc42 100644 (file)
@@ -165,3 +165,13 @@ If you only want to build and install the debug or optimized build, use the
 For example, to build and install only the optimized versions:
        make -C tcl${ver}/macosx deploy
        sudo make -C tcl${ver}/macosx install-deploy
+
+- To build a Tcl.framework for use as a subframework in another framework, use the
+install-embedded target and set SUBFRAMEWORK=1.  Set the DYLIB_INSTALL_DIR
+variable to the path which should be the install_name path of the Tcl library, set
+the DESTDIR variable to the pathname of a staging directory where the framework
+will be written .  For example, running this command in the Tcl source directory:
+       make -C macosx install-embedded SUBFRAMEWORK=1 DESTDIR=/tmp/tcl \
+       DYLIB_INSTALL_DIR=/Library/Frameworks/Some.framework/Versions/X.Y/Frameworks/Tcl.framework
+will produce a Tcl.framework intended for installing as a subframework of
+Some.framework.  The framework will be found in /tmp/tcl/Frameworks/
index 788aa8d..aceb929 100644 (file)
                F96D3E1F08F272A5004A47F5 /* CrtInterp.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtInterp.3; sourceTree = "<group>"; };
                F96D3E2008F272A5004A47F5 /* CrtMathFnc.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtMathFnc.3; sourceTree = "<group>"; };
                F96D3E2108F272A5004A47F5 /* CrtObjCmd.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtObjCmd.3; sourceTree = "<group>"; };
-               F96D3E2208F272A5004A47F5 /* CrtSlave.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtSlave.3; sourceTree = "<group>"; };
+               F96D3E2208F272A5004A47F5 /* CrtAlias.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtAlias.3; sourceTree = "<group>"; };
                F96D3E2308F272A5004A47F5 /* CrtTimerHdlr.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtTimerHdlr.3; sourceTree = "<group>"; };
                F96D3E2408F272A5004A47F5 /* CrtTrace.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtTrace.3; sourceTree = "<group>"; };
                F96D3E2508F272A5004A47F5 /* dde.n */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = dde.n; sourceTree = "<group>"; };
                                F96D3E1F08F272A5004A47F5 /* CrtInterp.3 */,
                                F96D3E2008F272A5004A47F5 /* CrtMathFnc.3 */,
                                F96D3E2108F272A5004A47F5 /* CrtObjCmd.3 */,
-                               F96D3E2208F272A5004A47F5 /* CrtSlave.3 */,
+                               F96D3E2208F272A5004A47F5 /* CrtAlias.3 */,
                                F96D3E2308F272A5004A47F5 /* CrtTimerHdlr.3 */,
                                F96D3E2408F272A5004A47F5 /* CrtTrace.3 */,
                                F96D3E2508F272A5004A47F5 /* dde.n */,
                        );
                        runOnlyForDeploymentPostprocessing = 0;
                        shellPath = /bin/bash;
-                       shellScript = "if [ \"${ACTION:-build}\" == \"build\" ]; then\nif [ -z \"${HOME}\" ]; then export HOME=\"$(echo ~)\"; fi\ncd \"${TARGET_TEMP_DIR}\"; rm -rf \"${DERIVED_FILE_DIR}\"; mkdir -p \"${DERIVED_FILE_DIR}\"\nprintf '%s%s%s%s%s' '\npackage require tcltest 2.2\nnamespace import tcltest::*\nconfigure -testdir [file normalize {' \"${TCL_SRCROOT}\" '/tests}]\nconfigure -tmpdir [file normalize {' \"${DERIVED_FILE_DIR}\" '}]\nconfigure -verbose [concat [configure -verbose] line]\nrunAllTests\n' | \"${TEST_RIG}\"; TEST_RIG_RESULT=$?\n[ ${TEST_RIG_RESULT} -ne 0 ] && echo \"tcltest:0: error: tcltest exited abnormally with code ${TEST_RIG_RESULT}.\"\nexit ${TEST_RIG_RESULT}\nfi";
+                       shellScript = "if [ \"${ACTION:-build}\" == \"build\" ]; then\nif [ -z \"${HOME}\" ]; then export HOME=\"$(echo ~)\"; fi\ncd \"${TARGET_TEMP_DIR}\"; rm -rf \"${DERIVED_FILE_DIR}\"; mkdir -p \"${DERIVED_FILE_DIR}\"\nprintf '%s%s%s%s%s' '\npackage require tcltest 2.5\nnamespace import tcltest::*\nconfigure -testdir [file normalize {' \"${TCL_SRCROOT}\" '/tests}]\nconfigure -tmpdir [file normalize {' \"${DERIVED_FILE_DIR}\" '}]\nconfigure -verbose [concat [configure -verbose] line]\nrunAllTests\n' | \"${TEST_RIG}\"; TEST_RIG_RESULT=$?\n[ ${TEST_RIG_RESULT} -ne 0 ] && echo \"tcltest:0: error: tcltest exited abnormally with code ${TEST_RIG_RESULT}.\"\nexit ${TEST_RIG_RESULT}\nfi";
                        showEnvVarsInLog = 0;
                };
                F97AF02F0B665DA900310EA2 /* Build Tcl */ = {
index 4362739..da16424 100644 (file)
                F96D3E1F08F272A5004A47F5 /* CrtInterp.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtInterp.3; sourceTree = "<group>"; };
                F96D3E2008F272A5004A47F5 /* CrtMathFnc.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtMathFnc.3; sourceTree = "<group>"; };
                F96D3E2108F272A5004A47F5 /* CrtObjCmd.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtObjCmd.3; sourceTree = "<group>"; };
-               F96D3E2208F272A5004A47F5 /* CrtSlave.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtSlave.3; sourceTree = "<group>"; };
+               F96D3E2208F272A5004A47F5 /* CrtAlias.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtAlias.3; sourceTree = "<group>"; };
                F96D3E2308F272A5004A47F5 /* CrtTimerHdlr.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtTimerHdlr.3; sourceTree = "<group>"; };
                F96D3E2408F272A5004A47F5 /* CrtTrace.3 */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = CrtTrace.3; sourceTree = "<group>"; };
                F96D3E2508F272A5004A47F5 /* dde.n */ = {isa = PBXFileReference; explicitFileType = text.man; fileEncoding = 4; path = dde.n; sourceTree = "<group>"; };
                                F96D3E1F08F272A5004A47F5 /* CrtInterp.3 */,
                                F96D3E2008F272A5004A47F5 /* CrtMathFnc.3 */,
                                F96D3E2108F272A5004A47F5 /* CrtObjCmd.3 */,
-                               F96D3E2208F272A5004A47F5 /* CrtSlave.3 */,
+                               F96D3E2208F272A5004A47F5 /* CrtAlias.3 */,
                                F96D3E2308F272A5004A47F5 /* CrtTimerHdlr.3 */,
                                F96D3E2408F272A5004A47F5 /* CrtTrace.3 */,
                                F96D3E2508F272A5004A47F5 /* dde.n */,
                        );
                        runOnlyForDeploymentPostprocessing = 0;
                        shellPath = /bin/bash;
-                       shellScript = "if [ \"${ACTION:-build}\" == \"build\" ]; then\nif [ -z \"${HOME}\" ]; then export HOME=\"$(echo ~)\"; fi\ncd \"${TARGET_TEMP_DIR}\"; rm -rf \"${DERIVED_FILE_DIR}\"; mkdir -p \"${DERIVED_FILE_DIR}\"\nprintf '%s%s%s%s%s' '\npackage require tcltest 2.2\nnamespace import tcltest::*\nconfigure -testdir [file normalize {' \"${TCL_SRCROOT}\" '/tests}]\nconfigure -tmpdir [file normalize {' \"${DERIVED_FILE_DIR}\" '}]\nconfigure -verbose [concat [configure -verbose] line]\nrunAllTests\n' | \"${TEST_RIG}\"; TEST_RIG_RESULT=$?\n[ ${TEST_RIG_RESULT} -ne 0 ] && echo \"tcltest:0: error: tcltest exited abnormally with code ${TEST_RIG_RESULT}.\"\nexit ${TEST_RIG_RESULT}\nfi";
+                       shellScript = "if [ \"${ACTION:-build}\" == \"build\" ]; then\nif [ -z \"${HOME}\" ]; then export HOME=\"$(echo ~)\"; fi\ncd \"${TARGET_TEMP_DIR}\"; rm -rf \"${DERIVED_FILE_DIR}\"; mkdir -p \"${DERIVED_FILE_DIR}\"\nprintf '%s%s%s%s%s' '\npackage require tcltest 2.5\nnamespace import tcltest::*\nconfigure -testdir [file normalize {' \"${TCL_SRCROOT}\" '/tests}]\nconfigure -tmpdir [file normalize {' \"${DERIVED_FILE_DIR}\" '}]\nconfigure -verbose [concat [configure -verbose] line]\nrunAllTests\n' | \"${TEST_RIG}\"; TEST_RIG_RESULT=$?\n[ ${TEST_RIG_RESULT} -ne 0 ] && echo \"tcltest:0: error: tcltest exited abnormally with code ${TEST_RIG_RESULT}.\"\nexit ${TEST_RIG_RESULT}\nfi";
                        showEnvVarsInLog = 0;
                };
                F97AF02F0B665DA900310EA2 /* Build Tcl */ = {
index 7bb6a2c..362f2a8 100755 (executable)
@@ -2377,7 +2377,7 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 TCL_VERSION=8.6
 TCL_MAJOR_VERSION=8
 TCL_MINOR_VERSION=6
-TCL_PATCH_LEVEL=".10"
+TCL_PATCH_LEVEL=".11"
 VERSION=${TCL_VERSION}
 
 EXTRA_INSTALL_BINARIES=${EXTRA_INSTALL_BINARIES:-"@:"}
@@ -4539,14 +4539,6 @@ else
   tcl_ok=yes
 fi
 
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
     if test "$tcl_ok" = "yes" ; then
        { $as_echo "$as_me:${as_lineno-$LINENO}: result: shared" >&5
 $as_echo "shared" >&6; }
@@ -5004,7 +4996,7 @@ fi
     if test "$GCC" = yes; then :
 
        CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
+       CFLAGS_WARNING="-Wall -Wpointer-arith"
 
 else
 
@@ -5272,7 +5264,7 @@ fi
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            ;;
-       CYGWIN_*|MINGW32*)
+       CYGWIN_*|MINGW32_*|MSYS_*)
            SHLIB_CFLAGS=""
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
@@ -5283,7 +5275,7 @@ fi
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            TCL_NEEDS_EXP_FILE=1
-           TCL_EXPORT_FILE_SUFFIX='${VERSION}\$\{DBGX\}.dll.a'
+           TCL_EXPORT_FILE_SUFFIX='${VERSION}.dll.a'
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
            { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
 $as_echo_n "checking for Cygwin version of gcc... " >&6; }
@@ -5489,7 +5481,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -5579,7 +5571,7 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            ;;
@@ -5597,7 +5589,7 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -5634,7 +5626,7 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
 
@@ -5674,7 +5666,7 @@ fi
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -5741,8 +5733,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        MP-RAS-02*)
@@ -5782,7 +5774,7 @@ fi
            DL_LIBS=""
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
@@ -5810,7 +5802,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "${TCL_THREADS}" = "1"; then :
@@ -5830,11 +5822,10 @@ fi
            SHLIB_SUFFIX=".so"
            DL_OBJS="tclLoadDl.o"
            DL_LIBS=""
-           LDFLAGS=""
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            if test "${TCL_THREADS}" = "1"; then :
 
@@ -6037,6 +6028,7 @@ fi
 
 $as_echo "#define MODULE_SCOPE __private_extern__" >>confdefs.h
 
+               tcl_cv_cc_visibility_hidden=yes
 
 fi
            CC_SEARCH_FLAGS=""
@@ -6227,7 +6219,7 @@ fi
            DL_LIBS=""
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -6630,7 +6622,7 @@ fi
        case $system in
            AIX-*) ;;
            BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*) ;;
+           CYGWIN_*|MINGW32_*|MSYS_*) ;;
            IRIX*) ;;
            NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
            Darwin-*) ;;
@@ -6660,7 +6652,7 @@ fi
     if test "${SHARED_BUILD}" = 1 -a "${SHLIB_SUFFIX}" != ""; then :
 
         LIB_SUFFIX=${SHARED_LIB_SUFFIX}
-        MAKE_LIB='${SHLIB_LD} -o $@ ${OBJS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
+        MAKE_LIB='${SHLIB_LD} -o $@ ${OBJS} ${LDFLAGS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
         if test "${SHLIB_SUFFIX}" = ".dll"; then :
 
             INSTALL_LIB='$(INSTALL_LIBRARY) $(LIB_FILE) "$(BIN_INSTALL_DIR)/$(LIB_FILE)";if test -f $(LIB_FILE).a; then $(INSTALL_DATA) $(LIB_FILE).a "$(LIB_INSTALL_DIR)"; fi;'
@@ -6801,7 +6793,6 @@ else
 fi
 
 # FIXME: Currently, LDFLAGS_DEFAULT is not used, it should work like CFLAGS_DEFAULT.
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT='$(CFLAGS_OPTIMIZE)'
        LDFLAGS_DEFAULT='$(LDFLAGS_OPTIMIZE)'
@@ -8630,7 +8621,7 @@ else
 int
 main ()
 {
-struct tm tm; tm.tm_gmtoff;
+struct tm tm; (void)tm.tm_gmtoff;
   ;
   return 0;
 }
@@ -8885,8 +8876,10 @@ else
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
+
+#include <stdlib.h>
+#include <string.h>
 int main() {
-    extern int strstr();
     exit(strstr("\0test", "test") ? 1 : 0);
 }
 _ACEOF
@@ -8944,8 +8937,10 @@ else
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
+
+#include <stdlib.h>
+#include <string.h>
 int main() {
-    extern int strtoul();
     char *term, *string = "0";
     exit(strtoul(string,&term,0) != 0 || term != string+1);
 }
@@ -9502,6 +9497,7 @@ else
 /* end confdefs.h.  */
 
        #include <stdlib.h>
+       #include <string.h>
        #define OURVAR "havecopy=yes"
        int main (int argc, char *argv[])
        {
@@ -10262,7 +10258,7 @@ $as_echo "static library" >&6; }
 
     TCL_SHLIB_LD_EXTRAS="-compatibility_version ${TCL_VERSION} -current_version ${TCL_VERSION}`echo ${TCL_PATCH_LEVEL} | awk '{match($0, "\\\.[0-9]+"); print substr($0,RSTART,RLENGTH)}'`"
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -install_name "${DYLIB_INSTALL_DIR}"/${TCL_LIB_FILE}'
-    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xa000000'
+    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xA000000'
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -sectcreate __TEXT __info_plist Tcl-Info.plist'
     EXTRA_TCLSH_LIBS='-sectcreate __TEXT __info_plist Tclsh-Info.plist'
     EXTRA_APP_CC_SWITCHES='-mdynamic-no-pic'
@@ -10300,7 +10296,7 @@ $as_echo "#define TCL_FRAMEWORK 1" >>confdefs.h
     PRIVATE_INCLUDE_DIR="${libdir}/PrivateHeaders"
     HTML_DIR="${libdir}/Resources/Documentation/Reference/Tcl"
     EXTRA_INSTALL="install-private-headers html-tcl"
-    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)"/TclTOC.html'
+    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)/TclTOC.html"'
     EXTRA_INSTALL_BINARIES='@echo "Installing Info.plist to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA_DIR) "$(LIB_INSTALL_DIR)/Resources" && $(INSTALL_DATA) Tcl-Info.plist "$(LIB_INSTALL_DIR)/Resources/Info.plist"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Installing license.terms to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA) "$(TOP_DIR)/license.terms" "$(LIB_INSTALL_DIR)/Resources"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Finalizing Tcl.framework" && rm -f "$(LIB_INSTALL_DIR)/../Current" && ln -s "$(VERSION)" "$(LIB_INSTALL_DIR)/../Current" && for f in "$(LIB_FILE)" tclConfig.sh Resources Headers PrivateHeaders; do rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/Current/$$f" "$(LIB_INSTALL_DIR)/../.."; done && f="$(STUB_LIB_FILE)" && rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/$(VERSION)/$$f" "$(LIB_INSTALL_DIR)/../.."'
@@ -10340,9 +10336,9 @@ if test "$FRAMEWORK_BUILD" = "1" ; then
     test -z "$TCL_MODULE_PATH"  && \
        TCL_MODULE_PATH="~/Library/Tcl /Library/Tcl"
 elif test "$prefix/lib" != "$libdir"; then
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${libdir} ${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${libdir}} {${prefix}/lib} ${TCL_PACKAGE_PATH}"
 else
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${prefix}/lib} ${TCL_PACKAGE_PATH}"
 fi
 
 #--------------------------------------------------------------------
@@ -10355,7 +10351,7 @@ fi
 #
 eval "TCL_STUB_LIB_FILE=libtclstub${TCL_UNSHARED_LIB_SUFFIX}"
 eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-eval "TCL_STUB_LIB_DIR=${libdir}"
+eval "TCL_STUB_LIB_DIR=\"${libdir}\""
 
 if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
     TCL_STUB_LIB_FLAG="-ltclstub${TCL_VERSION}"
index dad3733..beef2ed 100644 (file)
@@ -106,7 +106,7 @@ OpenResourceMap(
        if (tclMacOSXDarwinRelease >= 8)
 #endif
        {
-           openresourcemap = dlsym(RTLD_NEXT,
+           openresourcemap = (short (*)(CFBundleRef))dlsym(RTLD_NEXT,
                    "CFBundleOpenBundleResourceMap");
 #ifdef TCL_DEBUG_LOAD
            if (!openresourcemap) {
@@ -162,6 +162,7 @@ OpenResourceMap(
  *----------------------------------------------------------------------
  */
 
+#undef Tcl_MacOSXOpenBundleResources
 int
 Tcl_MacOSXOpenBundleResources(
     Tcl_Interp *interp,
index f34b280..6275aac 100644 (file)
@@ -106,7 +106,7 @@ typedef     struct finderinfo {
     u_int32_t extendedFileInfo[4];
 } __attribute__ ((__packed__)) finderinfo;
 
-typedef struct fileinfobuf {
+typedef struct {
     u_int32_t info_length;
     u_int32_t data[8];
 } fileinfobuf;
@@ -172,7 +172,7 @@ TclMacOSXGetFileAttribute(
     } else {
        alist.commonattr = ATTR_CMN_FNDRINFO;
     }
-    native = Tcl_FSGetNativePath(fileName);
+    native = (const char *)Tcl_FSGetNativePath(fileName);
     result = getattrlist(native, &alist, &finfo, sizeof(fileinfobuf), 0);
 
     if (result != 0) {
@@ -268,7 +268,7 @@ TclMacOSXSetFileAttribute(
     } else {
        alist.commonattr = ATTR_CMN_FNDRINFO;
     }
-    native = Tcl_FSGetNativePath(fileName);
+    native = (const char *)Tcl_FSGetNativePath(fileName);
     result = getattrlist(native, &alist, &finfo, sizeof(fileinfobuf), 0);
 
     if (result != 0) {
@@ -347,7 +347,7 @@ TclMacOSXSetFileAttribute(
            Tcl_DStringAppend(&ds, native, -1);
            Tcl_DStringAppend(&ds, _PATH_RSRCFORKSPEC, -1);
 
-           result = truncate(Tcl_DStringValue(&ds), (off_t)0);
+           result = truncate(Tcl_DStringValue(&ds), 0);
            if (result != 0) {
                /*
                 * truncate() on a valid resource fork path may fail with a
@@ -654,7 +654,7 @@ SetOSTypeFromAny(
        OSType osType;
        char bytes[4] = {'\0','\0','\0','\0'};
 
-       memcpy(bytes, Tcl_DStringValue(&ds), (size_t)Tcl_DStringLength(&ds));
+       memcpy(bytes, Tcl_DStringValue(&ds), Tcl_DStringLength(&ds));
        osType = (OSType) bytes[0] << 24 |
                 (OSType) bytes[1] << 16 |
                 (OSType) bytes[2] <<  8 |
@@ -689,7 +689,7 @@ SetOSTypeFromAny(
 
 static void
 UpdateStringOfOSType(
-    register Tcl_Obj *objPtr)  /* OSType object whose string rep to
+    Tcl_Obj *objPtr)   /* OSType object whose string rep to
                                 * update. */
 {
     char string[5];
index 9b7bd1a..bbbac65 100644 (file)
  */
 
 #include "tclInt.h"
+
+/*
+ * In macOS 10.12 the os_unfair_lock was introduced as a replacement for the
+ * OSSpinLock, and the OSSpinLock was deprecated.
+ */
+
+#if MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
+#define USE_OS_UNFAIR_LOCK
+#include <os/lock.h>
+#undef TCL_MAC_DEBUG_NOTIFIER
+#endif
+
 #ifdef HAVE_COREFOUNDATION     /* Traditional unix select-based notifier is
                                 * in tclUnixNotfy.c */
 #include <CoreFoundation/CoreFoundation.h>
@@ -21,6 +33,8 @@
 
 /* #define TCL_MAC_DEBUG_NOTIFIER 1 */
 
+#if  !defined(USE_OS_UNFAIR_LOCK)
+
 /*
  * We use the Darwin-native spinlock API rather than pthread mutexes for
  * notifier locking: this radically simplifies the implementation and lowers
@@ -31,6 +45,9 @@
  */
 
 #if defined(HAVE_LIBKERN_OSATOMIC_H) && defined(HAVE_OSSPINLOCKLOCK)
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#pragma GCC diagnostic ignored "-Wunused-function"
 /*
  * Use OSSpinLock API where available (Tiger or later).
  */
  * Support for weakly importing spinlock API.
  */
 #define WEAK_IMPORT_SPINLOCKLOCK
+
 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
 #define VOLATILE volatile
 #else
 #define VOLATILE
 #endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 */
+
 #ifndef bool
 #define bool int
 #endif
+
 extern void            OSSpinLockLock(VOLATILE OSSpinLock *lock)
                            WEAK_IMPORT_ATTRIBUTE;
 extern void            OSSpinLockUnlock(VOLATILE OSSpinLock *lock)
@@ -101,27 +121,47 @@ extern int                _spin_lock_try(OSSpinLock *lock);
 #define SpinLockTry(p)         _spin_lock_try(p)
 #define SPINLOCK_INIT          0
 
+#pragma GCC diagnostic pop
 #endif /* HAVE_LIBKERN_OSATOMIC_H && HAVE_OSSPINLOCKLOCK */
+#endif /* not using os_unfair_lock */
 
 /*
- * These spinlocks lock access to the global notifier state.
+ * These locks control access to the global notifier state.
  */
 
+#if defined(USE_OS_UNFAIR_LOCK)
+static os_unfair_lock notifierInitLock = OS_UNFAIR_LOCK_INIT;
+static os_unfair_lock notifierLock     = OS_UNFAIR_LOCK_INIT;
+#else
 static OSSpinLock notifierInitLock = SPINLOCK_INIT;
 static OSSpinLock notifierLock     = SPINLOCK_INIT;
+#endif
 
 /*
- * Macros abstracting notifier locking/unlocking
+ * Macros that abstract notifier locking/unlocking
  */
 
+#if defined(USE_OS_UNFAIR_LOCK)
+#define LOCK_NOTIFIER_INIT     os_unfair_lock_lock(&notifierInitLock)
+#define UNLOCK_NOTIFIER_INIT   os_unfair_lock_unlock(&notifierInitLock)
+#define LOCK_NOTIFIER          os_unfair_lock_lock(&notifierLock)
+#define UNLOCK_NOTIFIER                os_unfair_lock_unlock(&notifierLock)
+#define LOCK_NOTIFIER_TSD      os_unfair_lock_lock(&tsdPtr->tsdLock)
+#define UNLOCK_NOTIFIER_TSD    os_unfair_lock_unlock(&tsdPtr->tsdLock)
+#else
 #define LOCK_NOTIFIER_INIT     SpinLockLock(&notifierInitLock)
 #define UNLOCK_NOTIFIER_INIT   SpinLockUnlock(&notifierInitLock)
 #define LOCK_NOTIFIER          SpinLockLock(&notifierLock)
 #define UNLOCK_NOTIFIER                SpinLockUnlock(&notifierLock)
 #define LOCK_NOTIFIER_TSD      SpinLockLock(&tsdPtr->tsdLock)
 #define UNLOCK_NOTIFIER_TSD    SpinLockUnlock(&tsdPtr->tsdLock)
+#endif
+
+/*
+ * The debug version of the Notifier only works if using OSSpinLock.
+ */
 
-#ifdef TCL_MAC_DEBUG_NOTIFIER
+#if defined(TCL_MAC_DEBUG_NOTIFIER) && !defined(USE_OS_UNFAIR_LOCK)
 #define TclMacOSXNotifierDbgMsg(m, ...) \
     do {                                                               \
        fprintf(notifierLog?notifierLog:stderr, "tclMacOSXNotify.c:%d: " \
@@ -148,7 +188,7 @@ static OSSpinLock notifierLock     = SPINLOCK_INIT;
 #undef LOCK_NOTIFIER
 #define LOCK_NOTIFIER          SpinLockLockDbg(&notifierLock)
 #undef LOCK_NOTIFIER_TSD
-#define LOCK_NOTIFIER_TSD      SpinLockLockDbg(&tsdPtr->tsdLock)
+#define LOCK_NOTIFIER_TSD      SpinLockLockDbg(tsdPtr->tsdLock)
 #include <asl.h>
 static FILE *notifierLog = NULL;
 #ifndef NOTIFIER_LOG
@@ -217,7 +257,7 @@ typedef struct FileHandler {
  * handlers are ready to fire.
  */
 
-typedef struct FileHandlerEvent {
+typedef struct {
     Tcl_Event header;          /* Information that is standard for all
                                 * events. */
     int fd;                    /* File descriptor that is ready. Used to find
@@ -232,7 +272,7 @@ typedef struct FileHandlerEvent {
  * writable, and exceptional conditions.
  */
 
-typedef struct SelectMasks {
+typedef struct {
     fd_set readable;
     fd_set writable;
     fd_set exceptional;
@@ -255,8 +295,6 @@ typedef struct ThreadSpecificData {
     int runLoopRunning;                /* True if this thread's Tcl runLoop is
                                 * running. */
     int runLoopNestingLevel;   /* Level of nested runLoop invocations. */
-    int runLoopServicingEvents;        /* True if this thread's runLoop is servicing
-                                * Tcl events. */
 
     /* Must hold the notifierLock before accessing the following fields: */
     /* Start notifierLock section */
@@ -269,9 +307,14 @@ typedef struct ThreadSpecificData {
                                 * from these pointers. */
     /* End notifierLock section */
 
+#if defined(USE_OS_UNFAIR_LOCK)
+    os_unfair_lock tsdLock;
+#else
     OSSpinLock tsdLock;                /* Must hold this lock before acessing the
                                 * following fields from more than one
                                 * thread. */
+#endif
+
     /* Start tsdLock section */
     SelectMasks checkMasks;    /* This structure is used to build up the
                                 * masks to be used in the next call to
@@ -457,7 +500,6 @@ Tcl_InitNotifier(void)
     /*
      * Initialize support for weakly imported spinlock API.
      */
-
     if (pthread_once(&spinLockLockInitControl, SpinLockLockInit)) {
        Tcl_Panic("Tcl_InitNotifier: pthread_once failed");
     }
@@ -494,7 +536,7 @@ Tcl_InitNotifier(void)
        bzero(&runLoopObserverContext, sizeof(CFRunLoopObserverContext));
        runLoopObserverContext.info = tsdPtr;
        runLoopObserver = CFRunLoopObserverCreate(NULL,
-               kCFRunLoopEntry|kCFRunLoopExit|kCFRunLoopBeforeWaiting, TRUE,
+               kCFRunLoopEntry|kCFRunLoopExit, TRUE,
                LONG_MIN, UpdateWaitingListAndServiceEvents,
                &runLoopObserverContext);
        if (!runLoopObserver) {
@@ -512,7 +554,7 @@ Tcl_InitNotifier(void)
         */
 
        runLoopObserverTcl = CFRunLoopObserverCreate(NULL,
-               kCFRunLoopEntry|kCFRunLoopExit|kCFRunLoopBeforeWaiting, TRUE,
+               kCFRunLoopEntry|kCFRunLoopExit, TRUE,
                LONG_MIN, UpdateWaitingListAndServiceEvents,
                &runLoopObserverContext);
        if (!runLoopObserverTcl) {
@@ -528,7 +570,11 @@ Tcl_InitNotifier(void)
        tsdPtr->runLoopObserverTcl = runLoopObserverTcl;
        tsdPtr->runLoopTimer = NULL;
        tsdPtr->waitTime = CF_TIMEINTERVAL_FOREVER;
+#if defined(USE_OS_UNFAIR_LOCK)
+       tsdPtr->tsdLock = OS_UNFAIR_LOCK_INIT;
+#else
        tsdPtr->tsdLock = SPINLOCK_INIT;
+#endif
     }
 
     LOCK_NOTIFIER_INIT;
@@ -586,7 +632,6 @@ Tcl_InitNotifier(void)
     ENABLE_ASL;
     notifierCount++;
     UNLOCK_NOTIFIER_INIT;
-
     return tsdPtr;
 }
 \f
@@ -686,7 +731,7 @@ StartNotifierThread(void)
 
 void
 Tcl_FinalizeNotifier(
-    ClientData clientData)             /* Not used. */
+    ClientData clientData)
 {
     ThreadSpecificData *tsdPtr;
 
@@ -789,7 +834,7 @@ void
 Tcl_AlertNotifier(
     ClientData clientData)
 {
-    ThreadSpecificData *tsdPtr = clientData;
+    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)clientData;
 
     if (tclNotifierHooks.alertNotifierProc) {
        tclNotifierHooks.alertNotifierProc(clientData);
@@ -967,7 +1012,7 @@ Tcl_CreateFileHandler(
        }
     }
     if (filePtr == NULL) {
-       filePtr = ckalloc(sizeof(FileHandler));
+       filePtr = (FileHandler *)ckalloc(sizeof(FileHandler));
        filePtr->fd = fd;
        filePtr->readyMask = 0;
        filePtr->nextPtr = tsdPtr->firstFileHandlerPtr;
@@ -1222,6 +1267,10 @@ Tcl_WaitForEvent(
        Tcl_Panic("Tcl_WaitForEvent: Notifier not initialized");
     }
 
+    /*
+     * A NULL timePtr means wait forever.
+     */
+
     if (timePtr) {
        Tcl_Time vTime = *timePtr;
 
@@ -1235,14 +1284,23 @@ Tcl_WaitForEvent(
            tclScaleTimeProcPtr(&vTime, tclTimeClientData);
            waitTime = vTime.sec + 1.0e-6 * vTime.usec;
        } else {
+
            /*
-            * Polling: pretend to wait for files and tell the notifier thread
-            * what we are doing. The notifier thread makes sure it goes
-            * through select with its select mask in the same state as ours
-            * currently is. We block until that happens.
+            * The max block time was set to 0.
+            *
+            * If we set the waitTime to 0, then the call to CFRunLoopInMode
+            * may return without processing all of its sources.  The Apple
+            * documentation says that if the waitTime is 0 "only one pass is
+            * made through the run loop before returning; if multiple sources
+            * or timers are ready to fire immediately, only one (possibly two
+            * if one is a version 0 source) will be fired, regardless of the
+            * value of returnAfterSourceHandled."  This can cause some chanio
+            * tests to fail.  So we use a small positive waitTime unless there
+            * is another RunLoop running.
             */
 
            polling = 1;
+           waitTime = tsdPtr->runLoopRunning ? 0 : 0.0001;
        }
     }
 
@@ -1255,18 +1313,18 @@ Tcl_WaitForEvent(
 
     /*
      * If the Tcl runloop is already running (e.g. if Tcl_WaitForEvent was
-     * called recursively) or is servicing events via the runloop observer,
-     * re-run it in a custom runloop mode containing only the source for the
-     * notifier thread, otherwise wakeups from other sources added to the
-     * common runloop modes might get lost or 3rd party event handlers might
-     * get called when they do not expect to be.
+     * called recursively) start a new runloop in a custom runloop mode
+     * containing only the source for the notifier thread.  Otherwise wakeups
+     * from other sources added to the common runloop mode might get lost or
+     * 3rd party event handlers might get called when they do not expect to
+     * be.
      */
 
     runLoopRunning = tsdPtr->runLoopRunning;
     tsdPtr->runLoopRunning = 1;
-    runLoopStatus = CFRunLoopRunInMode(tsdPtr->runLoopServicingEvents ||
-           runLoopRunning ? tclEventsOnlyRunLoopMode : kCFRunLoopDefaultMode,
-           waitTime, TRUE);
+    runLoopStatus = CFRunLoopRunInMode(
+       runLoopRunning ? tclEventsOnlyRunLoopMode : kCFRunLoopDefaultMode,
+       waitTime, TRUE);
     tsdPtr->runLoopRunning = runLoopRunning;
 
     LOCK_NOTIFIER_TSD;
@@ -1311,7 +1369,7 @@ QueueFileEvents(
 {
     SelectMasks readyMasks;
     FileHandler *filePtr;
-    ThreadSpecificData *tsdPtr = info;
+    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)info;
 
     /*
      * Queue all detected file events.
@@ -1350,7 +1408,7 @@ QueueFileEvents(
         */
 
        if (filePtr->readyMask == 0) {
-           FileHandlerEvent *fileEvPtr = ckalloc(sizeof(FileHandlerEvent));
+           FileHandlerEvent *fileEvPtr = (FileHandlerEvent *)ckalloc(sizeof(FileHandlerEvent));
 
            fileEvPtr->header.proc = FileHandlerEventProc;
            fileEvPtr->fd = filePtr->fd;
@@ -1383,8 +1441,7 @@ UpdateWaitingListAndServiceEvents(
     CFRunLoopActivity activity,
     void *info)
 {
-    ThreadSpecificData *tsdPtr = info;
-
+    ThreadSpecificData *tsdPtr = (ThreadSpecificData *)info;
     if (tsdPtr->sleeping) {
        return;
     }
@@ -1407,16 +1464,6 @@ UpdateWaitingListAndServiceEvents(
        }
        tsdPtr->runLoopNestingLevel--;
        break;
-    case kCFRunLoopBeforeWaiting:
-       if (tsdPtr->runLoopTimer && !tsdPtr->runLoopServicingEvents &&
-               (tsdPtr->runLoopNestingLevel > 1
-                       || !tsdPtr->runLoopRunning)) {
-           tsdPtr->runLoopServicingEvents = 1;
-            /* This call seems to simply force event processing through and prevents hangups that have long been observed with Tk-Cocoa.  */
-           Tcl_ServiceAll();
-           tsdPtr->runLoopServicingEvents = 0;
-       }
-       break;
     default:
        break;
     }
@@ -1449,7 +1496,7 @@ OnOffWaitingList(
 {
     int changeWaitingList;
 
-#ifdef TCL_MAC_DEBUG_NOTIFIER
+#if defined(TCL_MAC_DEBUG_NOTIFIER) && !defined(USE_OS_UNFAIR_LOCK)
     if (SpinLockTry(&notifierLock)) {
        Tcl_Panic("OnOffWaitingList: notifierLock unlocked");
     }
@@ -1980,9 +2027,19 @@ AtForkChild(void)
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
-    UNLOCK_NOTIFIER_TSD;
-    UNLOCK_NOTIFIER;
-    UNLOCK_NOTIFIER_INIT;
+    /*
+     * If a child process unlocks an os_unfair_lock that was created in its parent
+     * the child will exit with an illegal instruction error.  So we reinitialize
+     * the lock in the child rather than attempt to unlock it.
+     */
+
+#if defined(USE_OS_UNFAIR_LOCK)
+    tsdPtr->tsdLock = OS_UNFAIR_LOCK_INIT;
+#else
+       UNLOCK_NOTIFIER_TSD;
+       UNLOCK_NOTIFIER;
+       UNLOCK_NOTIFIER_INIT;
+#endif
     if (tsdPtr->runLoop) {
        tsdPtr->runLoop = NULL;
        if (!noCFafterFork) {
diff --git a/manifest.uuid b/manifest.uuid
new file mode 100644 (file)
index 0000000..6720936
--- /dev/null
@@ -0,0 +1 @@
+f3fe83e715e2625b8f2e8aa2cb5d3f243bdf15b6ba3bc3d0eb32cd54ca3ab186
index 159a237..4633e0b 100644 (file)
@@ -17,7 +17,7 @@ needs to conform to the following conventions.
   "configure".  When the program "configure" is run, it should generate
   a file "Makefile" in the current working directory.  The "configure"
   program should be able to accept as command line arguments all the
-  arguments that can be passed to the master unix/configure program.  It
+  arguments that can be passed to the top unix/configure program.  It
   should also accept the --with-tcl= and --with-tclinclude= options in
   the conventional way.
 
diff --git a/pkgs/itcl4.2.0/win/rules-ext.vc b/pkgs/itcl4.2.0/win/rules-ext.vc
deleted file mode 100644 (file)
index 58c70fa..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-# This file should only be included in makefiles for Tcl extensions,\r
-# NOT in the makefile for Tcl itself.\r
-\r
-!ifndef _RULES_EXT_VC\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-!if "$(PROJECT)" == "tcl"\r
-!error The rules-ext.vc file is not intended for Tcl itself.\r
-!endif\r
-\r
-# We extract version numbers using the nmakehlp program. For now use\r
-# the local copy of nmakehlp. Once we locate Tcl, we will use that\r
-# one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
-!endif\r
-\r
-# First locate the Tcl directory that we are working with.\r
-!ifdef TCLDIR\r
-\r
-_RULESDIR = $(TCLDIR:/=\)\r
-\r
-!else\r
-\r
-# If an installation path is specified, that is also the Tcl directory.\r
-# Also Tk never builds against an installed Tcl, it needs Tcl sources\r
-!if defined(INSTALLDIR) && "$(PROJECT)" != "tk"\r
-_RULESDIR=$(INSTALLDIR:/=\)\r
-!else\r
-# Locate Tcl sources\r
-!if [echo _RULESDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-_RULESDIR = ..\..\tcl\r
-!else\r
-!include nmakehlp.out\r
-!endif\r
-\r
-!endif # defined(INSTALLDIR)....\r
-\r
-!endif # ifndef TCLDIR\r
-\r
-# Now look for the targets.vc file under the Tcl root. Note we check this\r
-# file and not rules.vc because the latter also exists on older systems.\r
-!if exist("$(_RULESDIR)\lib\nmake\targets.vc") # Building against installed Tcl\r
-_RULESDIR = $(_RULESDIR)\lib\nmake\r
-!elseif exist("$(_RULESDIR)\win\targets.vc")   # Building against Tcl sources\r
-_RULESDIR = $(_RULESDIR)\win\r
-!else\r
-# If we have not located Tcl's targets file, most likely we are compiling\r
-# against an older version of Tcl and so must use our own support files.\r
-_RULESDIR = .\r
-!endif\r
-\r
-!if "$(_RULESDIR)" != "."\r
-# Potentially using Tcl's support files. If this extension has its own\r
-# nmake support files, need to compare the versions and pick newer.\r
-\r
-!if exist("rules.vc") # The extension has its own copy\r
-\r
-!if [echo TCL_RULES_MAJOR = \> versions.vc] \\r
-   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
-!endif\r
-!if [echo TCL_RULES_MINOR = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
-!endif\r
-\r
-!if [echo OUR_RULES_MAJOR = \>> versions.vc] \\r
-   && [nmakehlp -V "rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
-!endif\r
-!if [echo OUR_RULES_MINOR = \>> versions.vc] \\r
-   && [nmakehlp -V "rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
-!endif\r
-!include versions.vc\r
-# We have a newer version of the support files, use them\r
-!if ($(TCL_RULES_MAJOR) != $(OUR_RULES_MAJOR)) || ($(TCL_RULES_MINOR) < $(OUR_RULES_MINOR))\r
-_RULESDIR = .\r
-!endif\r
-\r
-!endif # if exist("rules.vc")\r
-\r
-!endif # if $(_RULESDIR) != "."\r
-\r
-# Let rules.vc know what copy of nmakehlp.c to use.\r
-NMAKEHLPC = $(_RULESDIR)\nmakehlp.c\r
-\r
-# Get rid of our internal defines before calling rules.vc\r
-!undef TCL_RULES_MAJOR\r
-!undef TCL_RULES_MINOR\r
-!undef OUR_RULES_MAJOR\r
-!undef OUR_RULES_MINOR\r
-\r
-!if exist("$(_RULESDIR)\rules.vc")\r
-!message *** Using $(_RULESDIR)\rules.vc\r
-!include "$(_RULESDIR)\rules.vc"\r
-!else\r
-!error *** Could not locate rules.vc in $(_RULESDIR)\r
-!endif\r
-\r
-!endif # _RULES_EXT_VC
\ No newline at end of file
similarity index 94%
rename from pkgs/itcl4.2.0/Makefile.in
rename to pkgs/itcl4.2.1/Makefile.in
index ab22866..ef1cba0 100644 (file)
@@ -143,7 +143,7 @@ TCLSH               = $(TCLSH_ENV) $(PKG_ENV) $(TCLSH_PROG)
 
 TESTLOADARG = if {[catch {package present ${PACKAGE_NAME}}]} {package forget ${PACKAGE_NAME}}; \
                    package ifneeded ${PACKAGE_NAME} ${PACKAGE_VERSION} \
-                       [list load `@CYGPATH@ $(top_builddir)/$(PKG_LIB_FILE)` $(PACKAGE_NAME)]
+                       [list load `@CYGPATH@ $(top_builddir)/$(PKG_LIB_FILE)` [string totitle $(PACKAGE_NAME)]]
 
 #WISH_ENV      = TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library`
 #WISH_PROG     = @WISH_PROG@
@@ -163,7 +163,7 @@ PKG_CFLAGS  = @PKG_CFLAGS@
 # you do not compile with a similar machine setup as the Tcl core was
 # compiled with.
 #DEFS          = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
-DEFS           = @DEFS@ $(PKG_CFLAGS) -DITCL_LIBRARY=\"$(pkglibdir)\"
+DEFS           = @DEFS@ $(PKG_CFLAGS) -DITCL_LIBRARY="$(pkglibdir)"
 
 # Move pkgIndex.tcl to 'BINARIES' var if it is generated in the Makefile
 CONFIG_CLEAN_FILES = @CONFIG_CLEAN_FILES@ Makefile itclConfig.sh pkgIndex.tcl
@@ -225,11 +225,11 @@ install-binaries: binaries install-lib-binaries install-bin-binaries
 #========================================================================
 
 install-libraries: libraries
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(includedir)
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(includedir)"
        @echo "Installing header files in $(DESTDIR)$(includedir)"
        @list='$(PKG_HEADERS)'; for i in $$list; do \
            echo "Installing $(srcdir)/$$i" ; \
-           $(INSTALL_DATA) $(srcdir)/$$i $(DESTDIR)$(includedir) ; \
+           $(INSTALL_DATA) $(srcdir)/$$i "$(DESTDIR)$(includedir)" ; \
        done;
 
 #========================================================================
@@ -238,14 +238,14 @@ install-libraries: libraries
 #========================================================================
 
 install-doc: doc
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(mandir)/mann
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(mandir)/mann"
        @echo "Installing documentation in $(DESTDIR)$(mandir)"
        @list='$(srcdir)/doc/*.n'; for i in $$list; do \
            if test X"$$i" = X'$(srcdir)/doc/*.n'; then break; fi; \
            bi=`basename $$i`; \
            echo "Installing $$bi"; \
            sed -e '/man\.macros/r $(srcdir)/doc/man.macros' -e '/man\.macros/d' $$i > $$bi.tmp \
-           && $(INSTALL_DATA) $$bi.tmp $(DESTDIR)$(mandir)/mann/$$bi \
+           && $(INSTALL_DATA) $$bi.tmp "$(DESTDIR)$(mandir)/mann/$$bi" \
            && rm -f $$bi.tmp; \
        done
 
@@ -401,17 +401,17 @@ distclean: clean
 #========================================================================
 
 install-lib-binaries: binaries
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(pkglibdir)
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(pkglibdir)"
        @list='$(lib_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_LIBRARY) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
-           $(INSTALL_LIBRARY) $$p $(DESTDIR)$(pkglibdir)/$$p; \
+           $(INSTALL_LIBRARY) $$p "$(DESTDIR)$(pkglibdir)/$$p"; \
            ext=`echo $$p|sed -e "s/.*\.//"`; \
            if test "x$$ext" = "xdll"; then \
                lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
                if test -f $$lib; then \
                    echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
-                   $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
+                   $(INSTALL_DATA) $$lib "$(DESTDIR)$(pkglibdir)/$$lib"; \
                fi; \
            fi; \
          fi; \
@@ -420,14 +420,14 @@ install-lib-binaries: binaries
          if test -f $(srcdir)/$$p; then \
            destp=`basename $$p`; \
            echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
-           $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
+           $(INSTALL_DATA) $(srcdir)/$$p "$(DESTDIR)$(pkglibdir)/$$destp"; \
          fi; \
        done
        @if test "x$(SHARED_BUILD)" = "x1"; then \
            echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \
-           $(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \
+           $(INSTALL_DATA) pkgIndex.tcl "$(DESTDIR)$(pkglibdir)"; \
        fi
-       $(INSTALL_DATA) itclConfig.sh $(DESTDIR)$(pkglibdir)
+       $(INSTALL_DATA) itclConfig.sh "$(DESTDIR)$(pkglibdir)"
 
 #========================================================================
 # Install binary executables (e.g. .exe files and dependent .dll files)
@@ -443,7 +443,7 @@ install-bin-binaries: binaries
        @list='$(bin_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
-           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
+           $(INSTALL_PROGRAM) $$p "$(DESTDIR)$(bindir)/$$p"; \
          fi; \
        done
 
@@ -453,14 +453,14 @@ Makefile: $(srcdir)/Makefile.in  $(top_builddir)/config.status
 
 uninstall-binaries:
        list='$(lib_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
          p=`basename $$p`; \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(bin_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(bindir)/$$p; \
+         rm -f "$(DESTDIR)$(bindir)/$$p"; \
        done
 
 .PHONY: all binaries clean depend distclean doc install libraries test
similarity index 96%
rename from pkgs/itcl4.2.0/README
rename to pkgs/itcl4.2.1/README
index 9544825..bb59134 100644 (file)
@@ -1,6 +1,6 @@
 README: Itcl
 
-This is the 4.2.0 source distribution of Itcl, an object oriented
+This is the 4.2.1 source distribution of Itcl, an object oriented
 extension for Tcl. Itcl releases are available from Sourceforge at:
 
 https://sourceforge.net/projects/incrtcl/files/%5Bincr%20Tcl_Tk%5D-4-source/
similarity index 100%
rename from pkgs/itcl4.2.0/TODO
rename to pkgs/itcl4.2.1/TODO
similarity index 98%
rename from pkgs/itcl4.2.0/configure
rename to pkgs/itcl4.2.1/configure
index 070003c..1cfaa12 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for itcl 4.2.0.
+# Generated by GNU Autoconf 2.69 for itcl 4.2.1.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='itcl'
 PACKAGE_TARNAME='itcl'
-PACKAGE_VERSION='4.2.0'
-PACKAGE_STRING='itcl 4.2.0'
+PACKAGE_VERSION='4.2.1'
+PACKAGE_STRING='itcl 4.2.1'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -638,7 +638,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -646,6 +645,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1305,7 +1306,7 @@ 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 itcl 4.2.0 to adapt to many kinds of systems.
+\`configure' configures itcl 4.2.1 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1366,7 +1367,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of itcl 4.2.0:";;
+     short | recursive ) echo "Configuration of itcl 4.2.1:";;
    esac
   cat <<\_ACEOF
 
@@ -1466,7 +1467,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-itcl configure 4.2.0
+itcl configure 4.2.1
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1885,7 +1886,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by itcl $as_me 4.2.0, which was
+It was created by itcl $as_me 4.2.1, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3426,10 +3427,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3463,12 +3460,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -5087,7 +5078,7 @@ $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6127,7 +6118,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6152,7 +6143,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6301,14 +6292,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6389,14 +6380,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6411,7 +6402,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6487,39 +6478,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -6644,8 +6602,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -6672,7 +6630,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -6741,8 +6699,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -6758,8 +6716,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -6768,8 +6726,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -6797,8 +6755,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -6821,7 +6779,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -6831,9 +6789,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -6898,8 +6869,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -6916,11 +6887,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -6938,7 +6909,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -6946,32 +6917,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7280,7 +7225,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7350,13 +7295,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7456,7 +7401,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7493,8 +7438,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -7793,6 +7738,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8187,7 +8134,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8201,11 +8147,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8291,7 +8232,7 @@ fi
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8317,7 +8258,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8405,14 +8346,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8420,9 +8361,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -8453,11 +8394,11 @@ $as_echo "${TCLSH_PROG}" >&6; }
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="${libdir}/itcl${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval itcl_LIB_FLAG="-litcl${PACKAGE_VERSION}${DBGX}"
-       eval itcl_STUB_LIB_FLAG="-litclstub${PACKAGE_VERSION}${DBGX}"
+       eval itcl_LIB_FLAG="-litcl${PACKAGE_VERSION}"
+       eval itcl_STUB_LIB_FLAG="-litclstub${PACKAGE_VERSION}"
     else
-       eval itcl_LIB_FLAG="-litcl`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval itcl_STUB_LIB_FLAG="-litclstub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval itcl_LIB_FLAG="-litcl`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval itcl_STUB_LIB_FLAG="-litclstub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     itcl_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${itcl_LIB_FLAG}"
     itcl_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${itcl_LIB_FLAG}"
@@ -9038,7 +8979,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by itcl $as_me 4.2.0, which was
+This file was extended by itcl $as_me 4.2.1, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9091,7 +9032,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-itcl config.status 4.2.0
+itcl config.status 4.2.1
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/itcl4.2.0/configure.ac
rename to pkgs/itcl4.2.1/configure.ac
index 90c90eb..eb2860d 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([itcl], [4.2.0])
+AC_INIT([itcl],[4.2.1])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
@@ -272,4 +272,5 @@ AC_SUBST(itcl_INCLUDE_SPEC)
 # which require substituting the AC variables in. Include these here.
 #--------------------------------------------------------------------
 
-AC_OUTPUT([Makefile pkgIndex.tcl itclConfig.sh])
+AC_CONFIG_FILES([Makefile pkgIndex.tcl itclConfig.sh])
+AC_OUTPUT
similarity index 97%
rename from pkgs/itcl4.2.0/doc/Preserve.3
rename to pkgs/itcl4.2.1/doc/Preserve.3
index e6be3c1..a713925 100644 (file)
@@ -53,7 +53,7 @@ alternative that does not suffer from them.
 of memory of at least \fIsize\fR bytes. All \fIsize\fR bytes are
 initialized to zero.
 .PP
-A module calls \fBItcl_PreserveData\fR on a pointer \fIptr\fR 
+A module calls \fBItcl_PreserveData\fR on a pointer \fIptr\fR
 allocated by \fBItcl_Alloc\fR to prevent deallocation of that memory while
 the module remains interested in it.
 .PP
similarity index 99%
rename from pkgs/itcl4.2.0/doc/class.n
rename to pkgs/itcl4.2.1/doc/class.n
index ea5d828..c633498 100644 (file)
@@ -385,21 +385,21 @@ this list.
 .
 With no arguments, this command returns a list of all object-specific
 variables and common data members.  If \fIvarName\fR is specified, it
-returns information for a specific data member.  
-Flags can be specified with \fIvarName\fR in an arbitrary order. 
+returns information for a specific data member.
+Flags can be specified with \fIvarName\fR in an arbitrary order.
 The result is a list of the specific information in exactly the
 same order as the flags are specified.
 
-If no flags are given, this command returns a list 
+If no flags are given, this command returns a list
 as if the followings flags have been specified:
 .IP
 \fB-protection\fR \fB-type\fR \fB-name\fR \fB-init\fR \fB-value\fR ?\fB-config\fR?
 
 The \fB-config\fR result is only present if \fIvarName\fR is a public
-variable. It contains the code that is executed at initialization 
+variable. It contains the code that is executed at initialization
 of \fIvarName\fR. The \fB-scope\fR flag gives the namespace context
-of \fIvarName\fR. Herewith the variable can be accessed from outside 
-the object like any other variable. It is similar to the result of 
+of \fIvarName\fR. Herewith the variable can be accessed from outside
+the object like any other variable. It is similar to the result of
 the \fBitcl::scope\fR command.
 
 .RE
diff --git a/pkgs/itcl4.2.1/generic/clientData b/pkgs/itcl4.2.1/generic/clientData
new file mode 100644 (file)
index 0000000..62e3f3c
--- /dev/null
@@ -0,0 +1,16 @@
+itcl2TclOO.c:    framePtr->clientData = NULL;
+itcl2TclOO.c:    framePtr->objc = objc;
+itcl2TclOO.c:    framePtr->objv = objv;
+itcl2TclOO.c:    framePtr->procPtr = procPtr;
+itcl2TclOO.c:    if (framePtr == NULL || !(framePtr->isProcCallFrame & FRAME_IS_METHOD)) {
+itcl2TclOO.c:    contextPtr = framePtr->clientData;
+itcl2TclOO.c:    if (framePtr == NULL || !(framePtr->isProcCallFrame & FRAME_IS_METHOD)) {
+itclMigrate2TclCore.c:        framePtr->isProcCallFrame |= FRAME_HAS_RESOLVER;
+itclMigrate2TclCore.c: framePtr->resolvePtr = resolvePtr;
+itclMigrate2TclCore.c:        framePtr = framePtr->callerVarPtr;
+itclMigrate2TclCore.c:        framePtr = framePtr->callerVarPtr;
+itclMigrate2TclCore.c:    return (Tcl_Namespace *)framePtr->nsPtr;
+itclMigrate2TclCore.c:    return framePtr->clientData;
+itclMigrate2TclCore.c:    ((Interp *)interp)->framePtr->nsPtr = (Namespace *)nsPtr;
+itclMigrate2TclCore.c:    return ((Interp *)interp)->framePtr->objc;
+itclMigrate2TclCore.c:    return ((Interp *)interp)->framePtr->objv;
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itcl.h
rename to pkgs/itcl4.2.1/generic/itcl.h
index e31ea77..0c7e8ac 100644 (file)
@@ -85,7 +85,7 @@ extern "C" {
 #define ITCL_RELEASE_SERIAL     0
 
 #define ITCL_VERSION            "4.2"
-#define ITCL_PATCH_LEVEL        "4.2.0"
+#define ITCL_PATCH_LEVEL        "4.2.1"
 
 
 /*
similarity index 96%
rename from pkgs/itcl4.2.0/generic/itcl2TclOO.c
rename to pkgs/itcl4.2.1/generic/itcl2TclOO.c
index e284e61..9176309 100644 (file)
@@ -52,11 +52,12 @@ CallFinalizePMCall(
 static int
 FreeCommand(
     void *data[],
-    Tcl_Interp *interp,
+    Tcl_Interp *dummy,
     int result)
 {
     Command *cmdPtr = (Command *)data[0];
     Proc *procPtr = (Proc *)data[1];
+    (void)dummy;
 
     ckfree(cmdPtr);
     procPtr->cmdPtr = NULL;
@@ -168,10 +169,12 @@ Itcl_InvokeProcedureMethod(
 static int
 FreeProcedureMethod(
     void *data[],
-    Tcl_Interp *interp,
+    Tcl_Interp *dummy,
     int result)
 {
     ProcedureMethod *pmPtr = (ProcedureMethod *)data[0];
+    (void)dummy;
+
     ckfree(pmPtr);
     return result;
 }
@@ -237,8 +240,15 @@ Itcl_PublicObjectCmd(
     Tcl_Object oPtr = (Tcl_Object)clientData;
     int result;
 
-    result = TclOOInvokeObject(interp, oPtr, clsPtr, PUBLIC_METHOD,
+    if (oPtr) {
+       result = TclOOInvokeObject(interp, oPtr, clsPtr, PUBLIC_METHOD,
             objc, objv);
+    } else {
+       Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
+           "cannot access object-specific info without an object context",
+           NULL);
+       return TCL_ERROR;
+    }
     return result;
 }
 \f
@@ -352,7 +362,7 @@ Itcl_TclOOObjectName(
 
 int
 Itcl_SelfCmd(
-    void *clientData,
+    void *dummy,
     Tcl_Interp *interp,
     int objc,
     Tcl_Obj *const *objv)
@@ -360,6 +370,7 @@ Itcl_SelfCmd(
     Interp *iPtr = (Interp *) interp;
     CallFrame *framePtr = iPtr->varFramePtr;
     CallContext *contextPtr;
+    (void)dummy;
 
     if (!Itcl_IsMethodCallFrame(interp)) {
         Tcl_AppendResult(interp, TclGetString(objv[0]),
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclBase.c
rename to pkgs/itcl4.2.1/generic/itclBase.c
index 338f900..8550dc2 100644 (file)
@@ -466,15 +466,16 @@ Itcl_SafeInit (
 static int
 ItclSetHullWindowName(
     void *clientData,   /* infoPtr */
-    Tcl_Interp *interp,      /* current interpreter */
+    Tcl_Interp *dummy,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
     ItclObjectInfo *infoPtr;
+    (void)dummy;
 
     infoPtr = (ItclObjectInfo *)clientData;
-    if (infoPtr->currIoPtr != NULL) {
-        infoPtr->currIoPtr->hullWindowNamePtr = objv[1];
+    if ((infoPtr->currIoPtr != NULL) && (objc > 1)) {
+       infoPtr->currIoPtr->hullWindowNamePtr = objv[1];
        Tcl_IncrRefCount(infoPtr->currIoPtr->hullWindowNamePtr);
     }
     return TCL_OK;
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclBuiltin.c
rename to pkgs/itcl4.2.1/generic/itclBuiltin.c
index fda2185..c0134a6 100644 (file)
@@ -364,7 +364,7 @@ Itcl_BiInit(
         return TCL_ERROR;
     }
     /*
-     * Install into the master [info] ensemble.
+     * Install into the [info] ensemble.
      */
 
     infoCmd = Tcl_FindCommand(interp, "info", NULL, TCL_GLOBAL_ONLY);
@@ -490,7 +490,7 @@ Itcl_InstallBiMethods(
 /* ARGSUSED */
 int
 Itcl_BiIsaCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -500,6 +500,7 @@ Itcl_BiIsaCmd(
 
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -569,7 +570,7 @@ Itcl_BiIsaCmd(
 /* ARGSUSED */
 int
 Itcl_BiConfigureCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -597,6 +598,7 @@ Itcl_BiConfigureCmd(
     int i;
     int unparsedObjc;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_BiConfigureCmd", objc, objv);
     vlookup = NULL;
@@ -843,7 +845,7 @@ configureDone:
 /* ARGSUSED */
 int
 Itcl_BiCgetCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -856,6 +858,7 @@ Itcl_BiCgetCmd(
     const char *name;
     const char *val;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1,"Itcl_BiCgetCmd", objc, objv);
     /*
@@ -1100,6 +1103,7 @@ NRBiChainCmd(
     int cObjc;
     int idx;
     Tcl_Obj *objPtr;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_BiChainCmd", objc, objv);
 
@@ -1923,7 +1927,7 @@ static Tcl_Obj *makeAsOptionInfo(
 /* ARGSUSED */
 static int
 ItclExtendedConfigure(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1966,7 +1970,8 @@ ItclExtendedConfigure(
     int j;
     int isNew;
     int result;
-           int isOneOption;
+    int isOneOption;
+    (void)dummy;
 
     ItclShowArgs(1, "ItclExtendedConfigure", objc, objv);
     ioptPtr = NULL;
@@ -2590,7 +2595,7 @@ ItclExtendedConfigure(
 /* ARGSUSED */
 static int
 ItclExtendedCget(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -2614,6 +2619,7 @@ ItclExtendedCget(
     const char *val;
     int i;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1,"ItclExtendedCget", objc, objv);
     /*
@@ -2828,7 +2834,7 @@ ItclExtendedCget(
 /* ARGSUSED */
 static int
 ItclExtendedSetGet(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -2844,6 +2850,7 @@ ItclExtendedSetGet(
     const char *val;
     int result;
     int setValue;
+    (void)dummy;
 
     ItclShowArgs(1, "ItclExtendedSetGet", objc, objv);
     imvPtr = NULL;
@@ -2946,7 +2953,7 @@ ItclExtendedSetGet(
 /* ARGSUSED */
 int
 Itcl_BiInstallComponentCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -2962,7 +2969,7 @@ Itcl_BiInstallComponentCmd(
     const char *token;
     int numOpts;
     int result;
-
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_BiInstallComponentCmd", objc, objv);
     /*
@@ -3081,7 +3088,7 @@ Itcl_BiInstallComponentCmd(
 /* ARGSUSED */
 static int
 Itcl_BiDestroyCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3090,6 +3097,7 @@ Itcl_BiDestroyCmd(
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
     int result;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3158,7 +3166,7 @@ Itcl_BiDestroyCmd(
 /* ARGSUSED */
 int
 Itcl_BiCallInstanceCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3171,6 +3179,7 @@ Itcl_BiCallInstanceCmd(
     ItclObject *ioPtr;
     const char *token;
     int result;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3225,7 +3234,7 @@ Itcl_BiCallInstanceCmd(
 /* ARGSUSED */
 int
 Itcl_BiGetInstanceVarCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3238,6 +3247,7 @@ Itcl_BiGetInstanceVarCmd(
     ItclObject *ioPtr;
     const char *token;
     int result;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3291,7 +3301,7 @@ Itcl_BiGetInstanceVarCmd(
 /* ARGSUSED */
 int
 Itcl_BiMyTypeMethodCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3301,6 +3311,7 @@ Itcl_BiMyTypeMethodCmd(
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
     int i;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3341,7 +3352,7 @@ Itcl_BiMyTypeMethodCmd(
 /* ARGSUSED */
 int
 Itcl_BiMyMethodCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3350,6 +3361,7 @@ Itcl_BiMyMethodCmd(
     int i;
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3390,7 +3402,7 @@ Itcl_BiMyMethodCmd(
 /* ARGSUSED */
 int
 Itcl_BiMyProcCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3400,6 +3412,7 @@ Itcl_BiMyProcCmd(
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
     int i;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3441,7 +3454,7 @@ Itcl_BiMyProcCmd(
 /* ARGSUSED */
 int
 Itcl_BiMyTypeVarCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3451,6 +3464,7 @@ Itcl_BiMyTypeVarCmd(
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
     int i;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3493,7 +3507,7 @@ Itcl_BiMyTypeVarCmd(
 /* ARGSUSED */
 int
 Itcl_BiMyVarCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3501,6 +3515,7 @@ Itcl_BiMyVarCmd(
     Tcl_Obj *resultPtr;
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
+    (void)dummy;
 
     /*
      *  Make sure that this command is being invoked in the proper
@@ -3511,7 +3526,7 @@ Itcl_BiMyVarCmd(
     if (Itcl_GetContext(interp, &contextIclsPtr, &contextIoPtr) != TCL_OK) {
         return TCL_ERROR;
     }
-    if (contextIoPtr != NULL) {
+    if ((contextIoPtr != NULL) && (objc > 1)) {
         resultPtr = Tcl_NewStringObj(Tcl_GetString(contextIoPtr->varNsNamePtr),
                -1);
        Tcl_AppendToObj(resultPtr, "::", -1);
@@ -3537,7 +3552,7 @@ Itcl_BiMyVarCmd(
 /* ARGSUSED */
 int
 Itcl_BiItclHullCmd(
-    void *clientData,   /* class definition */
+    void *dummy,   /* class definition */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -3545,6 +3560,9 @@ Itcl_BiItclHullCmd(
     ItclClass *contextIclsPtr;
     ItclObject *contextIoPtr;
     const char *val;
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     /*
      *  Make sure that this command is being invoked in the proper
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclClass.c
rename to pkgs/itcl4.2.1/generic/itclClass.c
index d86b699..c0cb53a 100644 (file)
@@ -57,11 +57,13 @@ ItclReleaseClass(
 {
     ItclClass *iclsPtr = (ItclClass *)clientData;
 
+    assert(iclsPtr->refCount != 0);
     if (iclsPtr->refCount-- <= 1) {
        ItclFreeClass((char *) clientData);
     }
 }
-\f
+
+
 /*
  * ------------------------------------------------------------------------
  *  Itcl_DeleteMemberFunc()
@@ -133,7 +135,6 @@ ItclDeleteClassMetadata(
     } else {
        ItclDestroyClass2(iclsPtr);
     }
-    ItclReleaseClass(iclsPtr);
 }
 \f
 static int
@@ -146,6 +147,7 @@ CallNewObjectInstance(
     const char *path = (const char *)data[1];
     Tcl_Object *oPtr = (Tcl_Object *)data[2];
     Tcl_Obj *nameObjPtr = (Tcl_Obj *)data[3];
+    (void)result;
 
     *oPtr = NULL;
     if (infoPtr->clazzClassPtr) {
@@ -566,6 +568,8 @@ ItclDeleteClassVariablesNamespace(
     Tcl_Interp *interp,
     ItclClass *iclsPtr)
 {
+    (void)interp;
+    (void)iclsPtr;
     /* TODO: why is this being skipped? */
     return;
 }
@@ -1635,7 +1639,7 @@ ItclResolveVarEntry(
        Tcl_Obj *vnObjPtr;
        int newEntry, processAncestors;
        size_t varLen;
-      
+
        /* (de)qualify to simple name */
        varName = simpleName = lookupName;
        while(*varName) {
@@ -1644,7 +1648,7 @@ ItclResolveVarEntry(
            };
        }
        vnObjPtr = Tcl_NewStringObj(simpleName, -1);
-       
+
        processAncestors = simpleName != lookupName;
 
        Tcl_DStringInit(&buffer);
@@ -1707,7 +1711,7 @@ ItclResolveVarEntry(
                            }
                            /* check leastQualName correction needed */
                            if (!vlookup->leastQualName) {
-                               vlookup->leastQualName = 
+                               vlookup->leastQualName = (char *)
                                    Tcl_GetHashKey(&iclsPtr->resolveVars, hPtr);
                            }
                            /* reset vlookup for full-qualified names - new lookup */
@@ -1725,7 +1729,7 @@ ItclResolveVarEntry(
                        setResVar:
 
                            vlookup->ivPtr = ivPtr;
-                           vlookup->leastQualName = 
+                           vlookup->leastQualName = (char *)
                                Tcl_GetHashKey(&iclsPtr->resolveVars, hPtr);
 
                            /*
@@ -1859,7 +1863,7 @@ Itcl_BuildVirtualTables(
         if (hPtr == NULL) {
             break;
         }
-        clookupPtr = Tcl_GetHashValue(hPtr);
+        clookupPtr = (ItclCmdLookup *)Tcl_GetHashValue(hPtr);
         ckfree((char *)clookupPtr);
        Tcl_DeleteHashEntry(hPtr);
     }
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclCmd.c
rename to pkgs/itcl4.2.1/generic/itclCmd.c
index b2f08f9..b0b83b5 100644 (file)
@@ -169,7 +169,7 @@ ItclShowArgs(1, "EVAL2", objc+1, newObjv);
 /* ARGSUSED */
 int
 Itcl_FindClassesCmd(
-    ClientData clientData,   /* class/object info */
+    ClientData dummy,   /* class/object info */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -189,6 +189,7 @@ Itcl_FindClassesCmd(
     int newEntry;
     int handledActiveNs;
     int forceFullNames = 0;
+    (void)dummy;
 
     ItclShowArgs(2, "Itcl_FindClassesCmd", objc, objv);
     if (objc > 2) {
@@ -302,7 +303,7 @@ Itcl_FindClassesCmd(
  */
 int
 Itcl_FindObjectsCmd(
-    ClientData clientData,   /* class/object info */
+    ClientData dummy,   /* class/object info */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -332,6 +333,7 @@ Itcl_FindObjectsCmd(
     Tcl_CmdInfo cmdInfo;
     Tcl_Namespace *nsPtr;
     Tcl_Obj *objPtr;
+    (void)dummy;
 
     /*
      *  Parse arguments:
@@ -501,7 +503,7 @@ Itcl_FindObjectsCmd(
 /* ARGSUSED */
 static int
 NRDelClassCmd(
-    ClientData clientData,   /* unused */
+    ClientData dummy,   /* unused */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -509,6 +511,7 @@ NRDelClassCmd(
     int i;
     char *name;
     ItclClass *iclsPtr;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_DelClassCmd", objc, objv);
     /*
@@ -586,7 +589,7 @@ CallDeleteObject(
 
 static int
 NRDelObjectCmd(
-    ClientData clientData,   /* object management info */
+    ClientData dummy,   /* object management info */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -596,6 +599,7 @@ NRDelObjectCmd(
     void *callbackPtr;
     int i;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_DelObjectCmd", objc, objv);
     /*
@@ -688,6 +692,7 @@ Itcl_ScopeCmd(
     char *token;
     int doAppend;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_ScopeCmd", objc, objv);
     if (objc != 2) {
@@ -907,6 +912,7 @@ Itcl_CodeCmd(
     Tcl_Obj *objPtr;
     const char *token;
     int pos;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_CodeCmd", objc, objv);
     /*
@@ -997,7 +1003,7 @@ Itcl_CodeCmd(
  */
 int
 Itcl_IsObjectCmd(
-    ClientData clientData,   /* class/object info */
+    ClientData dummy,   /* class/object info */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1012,6 +1018,7 @@ Itcl_IsObjectCmd(
     Tcl_Command     cmd;
     Tcl_Namespace   *contextNs = NULL;
     ItclClass       *iclsPtr = NULL;
+    (void)dummy;
 
     /*
      *    Handle the arguments.
@@ -1115,7 +1122,7 @@ Itcl_IsObjectCmd(
  */
 int
 Itcl_IsClassCmd(
-    ClientData clientData,   /* class/object info */
+    ClientData dummy,   /* class/object info */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1125,6 +1132,7 @@ Itcl_IsClassCmd(
     char           *name;
     ItclClass      *iclsPtr = NULL;
     Tcl_Namespace  *contextNs = NULL;
+    (void)dummy;
 
     /*
      *    Need itcl::is class classname
@@ -1183,6 +1191,7 @@ Itcl_FilterAddCmd(
 {
     Tcl_Obj **newObjv;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_FilterCmd", objc, objv);
 /*    Tcl_Namespace *contextNs = Tcl_GetCurrentNamespace(interp); */
@@ -1223,6 +1232,8 @@ Itcl_FilterDeleteCmd(
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
+    (void)dummy;
+
     ItclShowArgs(1, "Itcl_FilterDeleteCmd", objc, objv);
 /*    Tcl_Namespace *contextNs = Tcl_GetCurrentNamespace(interp); */
 
@@ -1252,6 +1263,7 @@ Itcl_ForwardAddCmd(
     Tcl_Method mPtr;
     ItclObjectInfo *infoPtr;
     ItclClass *iclsPtr;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_ForwardAddCmd", objc, objv);
     if (objc < 3) {
@@ -1296,6 +1308,8 @@ Itcl_ForwardDeleteCmd(
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
+    (void)dummy;
+
     ItclShowArgs(1, "Itcl_ForwardDeleteCmd", objc, objv);
 /*    Tcl_Namespace *contextNs = Tcl_GetCurrentNamespace(interp); */
 
@@ -1322,6 +1336,7 @@ Itcl_MixinAddCmd(
 {
     Tcl_Obj **newObjv;
     int result;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_MixinAddCmd", objc, objv);
     if (objc < 3) {
@@ -1360,6 +1375,8 @@ Itcl_MixinDeleteCmd(
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
+    (void)dummy;
+
     ItclShowArgs(1, "Itcl_MixinDeleteCmd", objc, objv);
 /*    Tcl_Namespace *contextNs = Tcl_GetCurrentNamespace(interp); */
 
@@ -1716,7 +1733,7 @@ Itcl_AddDelegatedFunctionCmd(
 /* ARGSUSED */
 int
 Itcl_AddComponentCmd(
-    ClientData clientData,   /* infoPtr */
+    ClientData dummy,   /* infoPtr */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1736,6 +1753,7 @@ Itcl_AddComponentCmd(
     const char *varName;
     int isNew;
     int result;
+    (void)dummy;
 
     result = TCL_OK;
     contextIoPtr = NULL;
@@ -1880,7 +1898,7 @@ Itcl_AddComponentCmd(
 /* ARGSUSED */
 int
 Itcl_SetComponentCmd(
-    ClientData clientData,   /* infoPtr */
+    ClientData dummy,   /* infoPtr */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1895,6 +1913,7 @@ Itcl_SetComponentCmd(
     const char *name;
     const char *val;
     int result;
+    (void)dummy;
 
     result = TCL_OK;
     contextIoPtr = NULL;
similarity index 98%
rename from pkgs/itcl4.2.0/generic/itclEnsemble.c
rename to pkgs/itcl4.2.1/generic/itclEnsemble.c
index 19bf59e..f6be869 100644 (file)
@@ -82,8 +82,8 @@ typedef struct Ensemble {
  *  Data shared by ensemble access commands and ensemble parser:
  */
 typedef struct EnsembleParser {
-    Tcl_Interp* master;           /* master interp containing ensembles */
-    Tcl_Interp* parser;           /* slave interp for parsing */
+    Tcl_Interp* interp;           /* interpreter containing ensembles */
+    Tcl_Interp* parser;           /* child interp for parsing */
     Ensemble* ensData;            /* add parts to this ensemble */
 } EnsembleParser;
 
@@ -1681,22 +1681,22 @@ Itcl_EnsembleCmd(
     ensName = Tcl_GetString(objv[1]);
 
     if (ensData) {
-        if (FindEnsemblePart(ensInfo->master, ensData, ensName, &ensPart) != TCL_OK) {
+        if (FindEnsemblePart(ensInfo->interp, ensData, ensName, &ensPart) != TCL_OK) {
             ensPart = NULL;
         }
         if (ensPart == NULL) {
-            if (CreateEnsemble(ensInfo->master, ensData, ensName) != TCL_OK) {
-               Tcl_TransferResult(ensInfo->master, TCL_ERROR, interp);
+            if (CreateEnsemble(ensInfo->interp, ensData, ensName) != TCL_OK) {
+               Tcl_TransferResult(ensInfo->interp, TCL_ERROR, interp);
                 return TCL_ERROR;
             }
-            if (FindEnsemblePart(ensInfo->master, ensData, ensName, &ensPart)
+            if (FindEnsemblePart(ensInfo->interp, ensData, ensName, &ensPart)
                     != TCL_OK) {
                 Tcl_Panic("Itcl_EnsembleCmd: can't create ensemble");
             }
         }
 
         cmd = ensPart->cmdPtr;
-        infoPtr = (ItclObjectInfo *)Tcl_GetAssocData(ensInfo->master, ITCL_INTERP_DATA, NULL);
+        infoPtr = (ItclObjectInfo *)Tcl_GetAssocData(ensInfo->interp, ITCL_INTERP_DATA, NULL);
         hPtr = Tcl_FindHashEntry(&infoPtr->ensembleInfo->ensembles,
                (char *)ensPart->cmdPtr);
         if (hPtr == NULL) {
@@ -1764,7 +1764,7 @@ Itcl_EnsembleCmd(
 
     /*
      *  Copy the result from the parser interpreter to the
-     *  master interpreter.  If an error was encountered,
+     *  parent interpreter.  If an error was encountered,
      *  copy the error info first, and then set the result.
      *  Otherwise, the offending command is reported twice.
      */
@@ -1795,7 +1795,7 @@ Itcl_EnsembleCmd(
  *
  * GetEnsembleParser --
  *
- *      Returns the slave interpreter that acts as a parser for
+ *      Returns the child interpreter that acts as a parser for
  *      the body of an "ensemble" definition.  The first time that
  *      this is called for an interpreter, the parser is created
  *      and registered as associated data.  After that, it is
@@ -1828,11 +1828,11 @@ GetEnsembleParser(
     }
 
     /*
-     *  Create a slave interpreter that can be used to parse
+     *  Create a child interpreter that can be used to parse
      *  the body of an ensemble definition.
      */
     ensInfo = (EnsembleParser*)ckalloc(sizeof(EnsembleParser));
-    ensInfo->master = interp;
+    ensInfo->interp = interp;
     ensInfo->parser = Tcl_CreateInterp();
     ensInfo->ensData = NULL;
 
@@ -1867,7 +1867,7 @@ GetEnsembleParser(
  * DeleteEnsParser --
  *
  *      Called when an interpreter is destroyed to clean up the
- *      ensemble parser within it.  Destroys the slave interpreter
+ *      ensemble parser within it.  Destroys the child interpreter
  *      and frees up the data associated with it.
  *
  * Results:
@@ -1882,9 +1882,11 @@ GetEnsembleParser(
 static void
 DeleteEnsParser(
     ClientData clientData,    /* client data for ensemble-related commands */
-    Tcl_Interp *interp)       /* interpreter containing the data */
+    Tcl_Interp *dummy)       /* interpreter containing the data */
 {
     EnsembleParser* ensInfo = (EnsembleParser*)clientData;
+    (void)dummy;
+
     Tcl_DeleteInterp(ensInfo->parser);
     ckfree((char*)ensInfo);
 }
@@ -1966,9 +1968,9 @@ Itcl_EnsPartCmd(
        result = TCL_ERROR;
        goto errorOut;
     }
-    if (Tcl_CreateProc(ensInfo->master, cmdInfo.namespacePtr, partName, objv[2], objv[3],
+    if (Tcl_CreateProc(ensInfo->interp, cmdInfo.namespacePtr, partName, objv[2], objv[3],
             &procPtr) != TCL_OK) {
-       Tcl_TransferResult(ensInfo->master, TCL_ERROR, interp);
+       Tcl_TransferResult(ensInfo->interp, TCL_ERROR, interp);
        result = TCL_ERROR;
        goto errorOut;
     }
@@ -1981,13 +1983,13 @@ Itcl_EnsPartCmd(
      *  if we try to compile the Tcl code for the part.  If
      *  anything goes wrong, clean up before bailing out.
      */
-    result = AddEnsemblePart(ensInfo->master, ensData, partName, usage,
+    result = AddEnsemblePart(ensInfo->interp, ensData, partName, usage,
         (Tcl_ObjCmdProc *)Tcl_GetObjInterpProc(), procPtr, _Tcl_ProcDeleteProc,
         ITCL_ENSEMBLE_ENSEMBLE, &ensPart);
     if (result == TCL_ERROR) {
        _Tcl_ProcDeleteProc(procPtr);
     }
-    Tcl_TransferResult(ensInfo->master, result, interp);
+    Tcl_TransferResult(ensInfo->interp, result, interp);
 
 errorOut:
     Tcl_DecrRefCount(usagePtr);
@@ -2031,6 +2033,7 @@ Itcl_EnsembleErrorCmd(
 
     char *cmdName;
     Tcl_Obj *objPtr;
+    (void)objc;
 
     cmdName = Tcl_GetString(objv[0]);
 
@@ -2130,6 +2133,7 @@ EnsembleUnknownCmd(
     ItclObjectInfo *infoPtr;
     EnsemblePart *ensPart;
     Ensemble *ensData;
+    (void)dummy;
 
     ItclShowArgs(2, "EnsembleUnknownCmd", objc, objv);
     cmd = Tcl_GetCommandFromObj(interp, objv[1]);
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclHelpers.c
rename to pkgs/itcl4.2.1/generic/itclHelpers.c
index 8decb42..5f51efb 100644 (file)
@@ -82,7 +82,7 @@ ItclCreateArgList(
     Tcl_Obj **usagePtr,         /* store usage message for arguments here */
     ItclArgList **arglistPtrPtr,
                                /* returns pointer to parsed argument list */
-    ItclMemberFunc *mPtr,
+    ItclMemberFunc *dummy,
     const char *commandName)
 {
     int argc;
@@ -94,6 +94,7 @@ ItclCreateArgList(
     int i;
     int hadArgsArgument;
     int result;
+    (void)dummy;
 
     *arglistPtrPtr = NULL;
     lastArglistPtr = NULL;
@@ -296,13 +297,14 @@ Itcl_EvalArgs(
  */
 Tcl_Obj*
 Itcl_CreateArgs(
-    Tcl_Interp *interp,      /* current interpreter */
+    Tcl_Interp *dummy,      /* current interpreter */
     const char *string,      /* first command word */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
     int i;
     Tcl_Obj *listPtr;
+    (void)dummy;
 
     ItclShowArgs(1, "Itcl_CreateArgs", objc, objv);
     listPtr = Tcl_NewListObj(objc+2, NULL);
@@ -323,7 +325,7 @@ Itcl_CreateArgs(
 
 int
 ItclEnsembleSubCmd(
-    ClientData clientData,
+    ClientData dummy,
     Tcl_Interp *interp,
     const char *ensembleName,
     int objc,
@@ -333,6 +335,10 @@ ItclEnsembleSubCmd(
     int result;
     Tcl_Obj **newObjv;
     int isRootEnsemble;
+    (void)dummy;
+    (void)ensembleName;
+    (void)functionName;
+
     ItclShowArgs(2, functionName, objc, objv);
 
     newObjv = (Tcl_Obj **)ckalloc(sizeof(Tcl_Obj *)*(objc));
similarity index 98%
rename from pkgs/itcl4.2.0/generic/itclInfo.c
rename to pkgs/itcl4.2.1/generic/itclInfo.c
index 884728c..8f7e1ba 100644 (file)
@@ -313,7 +313,7 @@ static void ItclGetInfoUsage(Tcl_Interp *interp, Tcl_Obj*objPtr,
 static int
 InfoGutsFinish(
     ClientData data[],
-    Tcl_Interp *interp,
+    TCL_UNUSED(Tcl_Interp *),
     int result)
 {
     Tcl_CallFrame *framePtr = (Tcl_CallFrame *) data[0];
@@ -556,13 +556,13 @@ void
 ItclGetInfoUsage(
     Tcl_Interp *interp,
     Tcl_Obj *objPtr,       /* returns: summary of usage info */
-    ItclObjectInfo *infoPtr,
+    TCL_UNUSED(ItclObjectInfo *),
     ItclClass *iclsPtr)
 {
     const char *spaces = "  ";
     int i;
-
     ItclObject *ioPtr;
+
     if (iclsPtr == NULL) {
     if (TCL_ERROR == Itcl_GetContext(interp, &iclsPtr, &ioPtr)) {
        return;
@@ -600,7 +600,7 @@ static void
 ItclGetInfoDelegatedUsage(
     Tcl_Interp *interp,
     Tcl_Obj *objPtr,       /* returns: summary of usage info */
-    ItclObjectInfo *infoPtr)
+    TCL_UNUSED(ItclObjectInfo *))
 {
     ItclClass *iclsPtr;
     const char *name;
@@ -610,6 +610,7 @@ ItclGetInfoDelegatedUsage(
     int i;
 
     ItclObject *ioPtr;
+
     if (TCL_ERROR == Itcl_GetContext(interp, &iclsPtr, &ioPtr)) {
        return;
     }
@@ -660,7 +661,7 @@ ItclGetInfoDelegatedUsage(
 /* ARGSUSED */
 int
 Itcl_BiInfoClassCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -740,7 +741,7 @@ Itcl_BiInfoClassCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoClassOptionsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -851,7 +852,7 @@ Itcl_BiInfoClassOptionsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoContextCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -890,7 +891,7 @@ Itcl_BiInfoContextCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoInheritCmd(
-    ClientData clientdata, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -950,7 +951,7 @@ Itcl_BiInfoInheritCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoHeritageCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -1020,7 +1021,7 @@ Itcl_BiInfoHeritageCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoFunctionCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -1260,7 +1261,7 @@ Itcl_BiInfoFunctionCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoVariableCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -1829,7 +1830,7 @@ Itcl_BiInfoUnknownCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoBodyCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -1932,7 +1933,7 @@ Itcl_BiInfoBodyCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoArgsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2041,7 +2042,7 @@ Itcl_BiInfoArgsCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoOptionCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2344,7 +2345,7 @@ Itcl_BiInfoOptionCmd(
 /* ARGSUSED */
 int
 Itcl_BiInfoComponentCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2563,7 +2564,7 @@ Itcl_BiInfoComponentCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoWidgetCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2655,7 +2656,7 @@ Itcl_BiInfoWidgetCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoExtendedClassCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2715,6 +2716,10 @@ Itcl_BiInfoExtendedClassCmd(
     }
     contextIclsPtr = Tcl_GetHashValue(hPtr);
 
+#elif defined __cplusplus
+    (void)interp;
+    (void)objc;
+    (void)objv;
 #endif
 
     return TCL_OK;
@@ -2738,7 +2743,7 @@ Itcl_BiInfoExtendedClassCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2798,6 +2803,10 @@ Itcl_BiInfoDelegatedCmd(
     }
     contextIclsPtr = Tcl_GetHashValue(hPtr);
 
+#elif defined __cplusplus
+    (void)interp;
+    (void)objc;
+    (void)objv;
 #endif
 
     return TCL_OK;
@@ -2819,7 +2828,7 @@ Itcl_BiInfoDelegatedCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoTypeCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2907,7 +2916,7 @@ Itcl_BiInfoTypeCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoHullTypeCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -2974,7 +2983,7 @@ Itcl_BiInfoHullTypeCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDefaultCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3069,7 +3078,7 @@ Itcl_BiInfoDefaultCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoMethodCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3296,7 +3305,7 @@ Itcl_BiInfoMethodCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoMethodsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3394,7 +3403,7 @@ Itcl_BiInfoMethodsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoOptionsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3567,7 +3576,7 @@ Itcl_BiInfoTypesCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoComponentsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3638,7 +3647,7 @@ Itcl_BiInfoComponentsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoTypeMethodCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3866,7 +3875,7 @@ Itcl_BiInfoTypeMethodCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoTypeMethodsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -3971,7 +3980,7 @@ Itcl_BiInfoTypeMethodsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoTypeVarsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4028,7 +4037,7 @@ Itcl_BiInfoTypeVarsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoTypeVariableCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4278,7 +4287,7 @@ Itcl_BiInfoTypeVariableCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoVariablesCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4303,7 +4312,7 @@ Itcl_BiInfoVariablesCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoWidgetadaptorCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4459,7 +4468,7 @@ Itcl_BiInfoInstancesCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedOptionsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4530,7 +4539,7 @@ Itcl_BiInfoDelegatedOptionsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedMethodsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4603,7 +4612,7 @@ Itcl_BiInfoDelegatedMethodsCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedTypeMethodsCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4707,7 +4716,7 @@ Itcl_BiInfoDelegatedUnknownCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedOptionCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -4941,7 +4950,7 @@ Itcl_BiInfoDelegatedOptionCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedMethodCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
@@ -5165,7 +5174,7 @@ Itcl_BiInfoDelegatedMethodCmd(
 /* ARGSUSED */
 static int
 Itcl_BiInfoDelegatedTypeMethodCmd(
-    ClientData clientData, /* ItclObjectInfo Ptr */
+    TCL_UNUSED(ClientData), /* ItclObjectInfo Ptr */
     Tcl_Interp *interp,    /* current interpreter */
     int objc,              /* number of arguments */
     Tcl_Obj *const objv[]) /* argument objects */
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclInt.h
rename to pkgs/itcl4.2.1/generic/itclInt.h
index c5b856c..4d637b3 100644 (file)
 #   endif
 #endif
 
+#ifndef JOIN
+#  define JOIN(a,b) JOIN1(a,b)
+#  define JOIN1(a,b) a##b
+#endif
+
+#ifndef TCL_UNUSED
+#   if defined(__cplusplus)
+#      define TCL_UNUSED(T) T
+#   else
+#      define TCL_UNUSED(T) T JOIN(dummy, __LINE__)
+#   endif
+#endif
+
 /*
  * Since the Tcl/Tk distribution doesn't perform any asserts,
  * dynamic loading can fail to find the __assert function.
@@ -653,7 +666,7 @@ MODULE_SCOPE int _itcl_debug_level;
 MODULE_SCOPE void ItclShowArgs(int level, const char *str, int objc,
        Tcl_Obj * const* objv);
 #else
-#define ItclShowArgs(a,b,c,d)
+#define ItclShowArgs(a,b,c,d) do {(void)(c);(void)(d);} while(0)
 #endif
 
 MODULE_SCOPE Tcl_ObjCmdProc ItclCallCCommand;
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclLinkage.c
rename to pkgs/itcl4.2.1/generic/itclLinkage.c
index 0188efa..aa43ffd 100644 (file)
@@ -303,7 +303,7 @@ ItclGetRegisteredProcs(
 static void
 ItclFreeC(
     ClientData clientData,       /* associated data */
-    Tcl_Interp *interp)          /* intepreter being deleted */
+    TCL_UNUSED(Tcl_Interp *))    /* interpreter being deleted */
 {
     Tcl_HashTable *tablePtr = (Tcl_HashTable*)clientData;
     Tcl_HashSearch place;
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclMethod.c
rename to pkgs/itcl4.2.1/generic/itclMethod.c
index 970e376..ce226e8 100644 (file)
@@ -64,7 +64,7 @@ static void FreeMemberCode(ItclMemberCode *mcodePtr);
  */
 static int
 NRBodyCmd(
-    ClientData clientData,   /*  */
+    TCL_UNUSED(ClientData),   /*  */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const *objv)    /* argument objects */
@@ -189,7 +189,7 @@ Itcl_BodyCmd(
 /* ARGSUSED */
 static int
 NRConfigBodyCmd(
-    ClientData dummy,        /* unused */
+    TCL_UNUSED(ClientData),        /* unused */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -1319,7 +1319,7 @@ Itcl_EvalMemberCode(
 
 static int
 EquivArgLists(
-    Tcl_Interp *interp,
+    TCL_UNUSED(Tcl_Interp*),
     ItclArgList *origArgs,
     ItclArgList *realArgs)
 {
@@ -2056,10 +2056,10 @@ Itcl_InvokeMethodIfExists(
  */
 int
 Itcl_ReportFuncErrors(
-    Tcl_Interp* interp,        /* interpreter being modified */
-    ItclMemberFunc *imPtr,     /* command member that was invoked */
-    ItclObject *contextObj,    /* object context for this command */
-    int result)                /* integer status code from proc body */
+    TCL_UNUSED(Tcl_Interp*),     /* interpreter being modified */
+    TCL_UNUSED(ItclMemberFunc*), /* command member that was invoked */
+    TCL_UNUSED(ItclObject*),     /* object context for this command */
+    int result)                 /* integer status code from proc body */
 {
 /* FIXME !!! */
 /* adapt to use of ItclProcErrorProc for stubs compatibility !! */
@@ -2189,7 +2189,7 @@ Itcl_CmdAliasProc(
  */
 Tcl_Var
 Itcl_VarAliasProc(
-    Tcl_Interp *interp,
+    TCL_UNUSED(Tcl_Interp*),
     Tcl_Namespace *nsPtr,
     const char *varName,
     ClientData clientData)
@@ -2266,8 +2266,8 @@ int
 ItclCheckCallProc(
     ClientData clientData,
     Tcl_Interp *interp,
-    Tcl_ObjectContext contextPtr,
-    Tcl_CallFrame *framePtr,
+    TCL_UNUSED(Tcl_ObjectContext),
+    TCL_UNUSED(Tcl_CallFrame*),
     int *isFinished)
 {
     int result;
@@ -2456,8 +2456,8 @@ ItclCheckCallMethod(
     Itcl_PushStack(framePtr, stackPtr);
 
     if (ioPtr != NULL) {
-        ioPtr->callRefCount++;
-       Itcl_PreserveData(ioPtr);
+       ioPtr->callRefCount++;
+       Itcl_PreserveData(ioPtr); /* ++ preserve until ItclAfterCallMethod releases it */
     }
     imPtr->iclsPtr->callRefCount++;
     if (!imPtr->iclsPtr->infoPtr->useOldResolvers) {
@@ -2486,7 +2486,7 @@ ItclAfterCallMethod(
     ClientData clientData,
     Tcl_Interp *interp,
     Tcl_ObjectContext contextPtr,
-    Tcl_Namespace *nsPtr,
+    TCL_UNUSED(Tcl_Namespace*),
     int call_result)
 {
     Tcl_HashEntry *hPtr;
@@ -2571,11 +2571,14 @@ ItclAfterCallMethod(
             if (hPtr == NULL) {
                 ckfree((char *)callContextPtr);
            }
-           Itcl_ReleaseData(ioPtr);
         } else {
             ckfree((char *)callContextPtr);
         }
     }
+
+    if (ioPtr != NULL) {
+       Itcl_ReleaseData(ioPtr); /* -- paired release for preserve in ItclCheckCallMethod */
+    }
     result = call_result;
 finishReturn:
     Itcl_ReleaseData(imPtr);
@@ -2585,7 +2588,7 @@ finishReturn:
 void
 ItclProcErrorProc(
     Tcl_Interp *interp,
-    Tcl_Obj *procNameObj)
+    TCL_UNUSED(Tcl_Obj*))
 {
     Tcl_Obj *objPtr;
     Tcl_HashEntry *hPtr;
similarity index 96%
rename from pkgs/itcl4.2.0/generic/itclMigrate2TclCore.c
rename to pkgs/itcl4.2.1/generic/itclMigrate2TclCore.c
index 721599b..5fa2ee0 100644 (file)
@@ -26,10 +26,12 @@ Itcl_SetCallFrameResolver(
     CallFrame *framePtr = ((Interp *)interp)->framePtr;
     if (framePtr != NULL) {
 #ifdef ITCL_USE_MODIFIED_TCL_H
-        framePtr->isProcCallFrame |= FRAME_HAS_RESOLVER;
+       framePtr->isProcCallFrame |= FRAME_HAS_RESOLVER;
        framePtr->resolvePtr = resolvePtr;
+#elif defined(__cplusplus)
+       (void)resolvePtr;
 #endif
-        return TCL_OK;
+       return TCL_OK;
     }
     return TCL_ERROR;
 }
@@ -44,13 +46,15 @@ _Tcl_SetNamespaceResolver(
     }
 #ifdef ITCL_USE_MODIFIED_TCL_H
     ((Namespace *)nsPtr)->resolvePtr = resolvePtr;
+#elif defined(__cplusplus)
+    (void)resolvePtr;
 #endif
     return TCL_OK;
 }
 
 Tcl_Var
 Tcl_NewNamespaceVar(
-    Tcl_Interp *interp,
+    TCL_UNUSED(Tcl_Interp *),
     Tcl_Namespace *nsPtr,
     const char *varName)
 {
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclObject.c
rename to pkgs/itcl4.2.1/generic/itclObject.c
index e51f35d..3a44791 100644 (file)
@@ -109,13 +109,16 @@ ItclDeleteObjectMetadata(
 static void
 ObjectRenamedTrace(
     ClientData clientData,      /* The object being deleted. */
-    Tcl_Interp *interp,         /* The interpreter containing the object. */
+    Tcl_Interp *dummy,         /* The interpreter containing the object. */
     const char *oldName,        /* What the object was (last) called. */
     const char *newName,        /* Always NULL ??. not for itk!! */
     int flags)                  /* Why was the object deleted? */
 {
     ItclObject *ioPtr = (ItclObject *)clientData;
     Itcl_InterpState istate;
+    (void)dummy;
+    (void)oldName;
+    (void)flags;
 
     if (newName != NULL) {
        /* FIXME should enter the new name in the hashtables for objects etc. */
@@ -733,6 +736,11 @@ ItclInitObjectCommands(
    ItclClass *iclsPtr,
    const char *name)
 {
+    (void)interp;
+    (void)ioPtr;
+    (void)iclsPtr;
+    (void)name;
+
     return TCL_OK;
 }
 \f
@@ -1150,7 +1158,7 @@ ItclInitObjectOptions(
  */
 int
 ItclInitObjectMethodVariables(
-   Tcl_Interp *interp,
+   Tcl_Interp *dummy,
    ItclObject *ioPtr,
    ItclClass *iclsPtr,
    const char *name)
@@ -1162,6 +1170,8 @@ ItclInitObjectMethodVariables(
     Tcl_HashEntry *hPtr2;
     Tcl_HashSearch place;
     int isNew;
+    (void)dummy;
+    (void)name;
 
     imvPtr = NULL;
     Itcl_InitHierIter(&hier, iclsPtr);
@@ -1940,6 +1950,7 @@ ItclReportObjectUsage(
     char *name;
     int ignore;
     int cmp;
+    (void)callerNsPtr;
 
     if (contextIoPtr == NULL) {
         resultPtr = Tcl_GetObjResult(interp);
@@ -2081,6 +2092,7 @@ ItclTraceThisVar(
     ItclObject *contextIoPtr = (ItclObject*)cdata;
     Tcl_Obj *objPtr;
     const char *objName;
+    (void)name2;
 
     /* because of SF bug #187 use a different trace handler for "this", "win", "type"
      * *self" and "selfns"
@@ -2141,6 +2153,7 @@ ItclTraceWinVar(
     const char *objName;
     const char *head;
     const char *tail;
+    (void)name2;
 
     /*
      *  Handle read traces on "win"
@@ -2198,6 +2211,7 @@ ItclTraceTypeVar(
     ItclObject *contextIoPtr = (ItclObject*)cdata;
     Tcl_Obj *objPtr;
     const char *objName;
+    (void)name2;
 
     /*
      *  Handle read traces on "type"
@@ -2249,6 +2263,7 @@ ItclTraceSelfVar(
     ItclObject *contextIoPtr = (ItclObject*)cdata;
     Tcl_Obj *objPtr;
     const char *objName;
+    (void)name2;
 
     /*
      *  Handle read traces on "self"
@@ -2316,6 +2331,7 @@ ItclTraceSelfnsVar(
     ItclObject *contextIoPtr = (ItclObject*)cdata;
     Tcl_Obj *objPtr;
     const char *objName;
+    (void)name2;
 
     /*
      *  Handle read traces on "selfns"
@@ -2363,6 +2379,9 @@ ItclTraceOptionVar(
 {
     ItclObject *ioPtr;
     ItclOption *ioptPtr;
+    (void)interp;
+    (void)name1;
+    (void)name2;
 
 /* FIXME !!! */
 /* don't know yet if ItclTraceOptionVar is really needed !! */
@@ -2419,6 +2438,7 @@ ItclTraceComponentVar(
     ItclComponent *icPtr;
     ItclDelegatedFunction *idmPtr;
     const char *val;
+    (void)name2;
 
 /* FIXME should free memory on unset or rename!! */
     if (cdata != NULL) {
@@ -2516,6 +2536,7 @@ ItclTraceItclHullVar(
     ItclObjectInfo *infoPtr;
     ItclObject *ioPtr;
     ItclVariable *ivPtr;
+    (void)name2;
 
 /* FIXME !!! */
 /* FIXME should free memory on unset or rename!! */
@@ -3311,8 +3332,8 @@ ExpandDelegateAs(
                            }
                            break;
                        } else {
-                           /* fall through */
                        }
+                   /* FALLTHRU */
                    default:
                      {
                        char buf[2];
@@ -3437,7 +3458,7 @@ DelegateFunction(
 
 int
 DelegatedOptionsInstall(
-    Tcl_Interp *interp,
+    Tcl_Interp *dummy,
     ItclClass *iclsPtr)
 {
     Tcl_HashEntry *hPtr2;
@@ -3446,6 +3467,7 @@ DelegatedOptionsInstall(
     ItclOption *ioptPtr;
     FOREACH_HASH_DECLS;
     char *optionName;
+    (void)dummy;
 
     FOREACH_HASH_VALUE(idoPtr, &iclsPtr->delegatedOptions) {
        optionName = Tcl_GetString(idoPtr->namePtr);
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclParse.c
rename to pkgs/itcl4.2.1/generic/itclParse.c
index 0d7783d..02845d9 100644 (file)
@@ -652,10 +652,12 @@ static const Tcl_MethodType itclArgMethodType = {
 
 static int
 CloneProc(
-    Tcl_Interp *interp,
+    Tcl_Interp *dummy,
     ClientData original,
     ClientData *copyPtr)
 {
+    (void)dummy;
+
     Itcl_PreserveData((ItclMemberFunc *)original);
     *copyPtr = original;
     return TCL_OK;
@@ -668,6 +670,7 @@ CallAfterCallMethod(
     int result)
 {
     ClientData clientData = data[0];
+
     Tcl_ObjectContext context = (Tcl_ObjectContext)data[1];
 
     return ItclAfterCallMethod(clientData, interp, context, NULL, result);
@@ -706,6 +709,12 @@ ArgCallProc(
     int objc,
     Tcl_Obj *const *objv)
 {
+    (void)clientData;
+    (void)interp;
+    (void)context;
+    (void)objc;
+    (void)objv;
+
     return TCL_ERROR;
 }
 
@@ -2476,6 +2485,9 @@ Itcl_ClassMixinCmd(
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
 {
+    (void)clientData;
+    (void)interp;
+
     ItclShowArgs(0, "Itcl_ClassMixinCmd", objc, objv);
     return TCL_OK;
 }
@@ -2594,6 +2606,7 @@ ItclParseOption(
     int result;
     int i;
     const char *cp;
+    (void)infoPtr;
 
     ItclShowArgs(1, "ItclParseOption", objc, objv);
     pLevel = Itcl_Protection(interp, 0);
@@ -3050,7 +3063,7 @@ ItclHandleClassComponent(
                " Only these can have components", NULL);
        return TCL_ERROR;
     }
-    if ((objc < 2) && (objc > 6)) {
+    if ((objc < 2) || (objc > 6)) {
         Tcl_AppendResult(interp, "wrong # args should be: ", usage, NULL);
         return TCL_ERROR;
     }
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclResolve.c
rename to pkgs/itcl4.2.1/generic/itclResolve.c
index 86e8ddb..b2584c9 100644 (file)
@@ -649,6 +649,7 @@ Itcl_ParseVarResolver(
 
     Tcl_HashEntry *hPtr;
     ItclVarLookup *vlookup;
+    (void)flags;
 
     /*
      *  See if the requested variable is a recognized "common" member.
similarity index 98%
rename from pkgs/itcl4.2.0/generic/itclStubs.c
rename to pkgs/itcl4.2.1/generic/itclStubs.c
index 098a077..f5c6e99 100644 (file)
@@ -62,7 +62,7 @@ Itcl_IsStub(
  */
 int
 Itcl_StubCreateCmd(
-    ClientData clientData,   /* not used */
+    TCL_UNUSED(ClientData),   /* not used */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -112,7 +112,7 @@ Itcl_StubCreateCmd(
  */
 int
 Itcl_StubExistsCmd(
-    ClientData clientData,   /* not used */
+    TCL_UNUSED(ClientData),   /* not used */
     Tcl_Interp *interp,      /* current interpreter */
     int objc,                /* number of arguments */
     Tcl_Obj *const objv[])   /* argument objects */
@@ -224,7 +224,7 @@ ItclHandleStubCmd(
 /* ARGSUSED */
 static void
 ItclDeleteStub(
-    ClientData cdata)      /* not used */
+    TCL_UNUSED(ClientData))      /* not used */
 {
     /* do nothing */
 }
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclTclIntStubsFcn.c
rename to pkgs/itcl4.2.1/generic/itclTclIntStubsFcn.c
index df40468..7c7f4de 100644 (file)
@@ -126,7 +126,7 @@ Itcl_InitRewriteEnsemble(
     Tcl_Interp *interp,
     int numRemoved,
     int numInserted,
-    int objc,
+    TCL_UNUSED(int) /* objc */,
     Tcl_Obj *const *objv)
 {
     return TclInitRewriteEnsemble(interp, numRemoved, numInserted, objv);
similarity index 99%
rename from pkgs/itcl4.2.0/generic/itclUtil.c
rename to pkgs/itcl4.2.1/generic/itclUtil.c
index dc1c035..1bd8a1e 100644 (file)
@@ -628,7 +628,7 @@ Itcl_ReleaseData(
     /* Free cdata now */
     freeProc = blk->freeProc;
     blk->freeProc = NULL;
-    freeProc(cdata);
+    freeProc((char *)cdata);
 }
 \f
 /*
@@ -674,7 +674,7 @@ void * Itcl_Alloc(
  */
 void Itcl_Free(void *ptr) {
     PresMemoryPrefix *blk;
-    
+
     if (ptr == NULL) {
        return;
     }
similarity index 93%
rename from pkgs/itcl4.2.0/pkgIndex.tcl.in
rename to pkgs/itcl4.2.1/pkgIndex.tcl.in
index 0d6ec0e..0791584 100644 (file)
@@ -1,7 +1,7 @@
 # Tcl package index file, version 1.0
 #
 # Do NOT try this command
-# 
+#
 #   if {![package vsatisfies [package provide Tcl] 8.6-]} {return}
 #
 # as a way to accept working with all of Tcl 8.6, Tcl 8.X, X>6, and
@@ -17,5 +17,5 @@
 
 if {![package vsatisfies [package provide Tcl] 8.6]} {return}
 
-package ifneeded itcl @PACKAGE_VERSION@ [list load [file join $dir "@PKG_LIB_FILE@"] itcl]
-package ifneeded Itcl @PACKAGE_VERSION@ [list load [file join $dir "@PKG_LIB_FILE@"] itcl]
+package ifneeded itcl @PACKAGE_VERSION@ [list load [file join $dir "@PKG_LIB_FILE@"] Itcl]
+package ifneeded Itcl @PACKAGE_VERSION@ [list load [file join $dir "@PKG_LIB_FILE@"] Itcl]
similarity index 81%
rename from pkgs/tdbcmysql1.1.1/tclconfig/README.txt
rename to pkgs/itcl4.2.1/tclconfig/README.txt
index 59b5a3e..715cb9d 100644 (file)
@@ -3,10 +3,10 @@ Architecture (TEA) extension.  For more information on TEA see:
 
        http://www.tcl.tk/doc/tea/
 
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
 
-       http://tcl.sourceforge.net/
+       https://core.tcl-lang.org/tclconfig
 
 This package is a freely available open source package.  You can do
 virtually anything you like with it, such as modifying it, redistributing
similarity index 55%
rename from pkgs/tdbc1.1.1/tclconfig/install-sh
rename to pkgs/itcl4.2.1/tclconfig/install-sh
index 7c34c3f..21b733a 100644 (file)
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-04-20.01; # UTC
+scriptversion=2020-07-26.22; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -35,25 +35,21 @@ scriptversion=2011-04-20.01; # UTC
 # FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
+# '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.
 
+tab='  '
 nl='
 '
-IFS=" ""       $nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,22 +64,15 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
 mode=0755
 
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
 chgrpcmd=
 chmodcmd=$chmodprog
 chowncmd=
@@ -97,7 +86,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -120,7 +109,7 @@ Options:
   -m MODE       $chmodprog installed files to MODE.
   -o USER       $chownprog installed files to USER.
   -s            $stripprog installed files.
-  -S            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
   -t DIRECTORY  install into DIRECTORY.
   -T            report an error if DSTFILE is a directory.
 
@@ -138,45 +127,60 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-       shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-       shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
     -S) stripcmd="$stripprog $2"
-       shift;;
+        shift;;
 
-    -t) dst_arg=$2
-       shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)        shift
-       break;;
+    --) shift
+        break;;
 
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -190,6 +194,10 @@ if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
     fi
     shift # arg
     dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
   done
 fi
 
@@ -198,12 +206,21 @@ if test $# -eq 0; then
     echo "$0: no input file specified." >&2
     exit 1
   fi
-  # It's OK to call `install-sh -d' without argument.
+  # It's OK to call 'install-sh -d' without argument.
   # This can happen when creating conditional directories.
   exit 0
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -219,16 +236,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -236,9 +253,9 @@ fi
 
 for src
 do
-  # Protect names starting with `-'.
+  # Protect names problematic for 'test' and other utilities.
   case $src in
-    -*) src=./$src;;
+    -* | [=\(\)!]) src=./$src;;
   esac
 
   if test -n "$dir_arg"; then
@@ -260,185 +277,150 @@ do
       echo "$0: no destination specified." >&2
       exit 1
     fi
-
     dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
 
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
+    # If destination is a directory, append the input filename.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
-      dst=$dstdir/`basename "$src"`
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
   fi
 
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
   obsolete_mkdir_used=false
 
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
        else
-         mkdir_mode=
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
        fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
+       trap '' 0;;
     esac
 
     if
       $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
 
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # mkdir does not conform to POSIX,
       # or it failed possibly due to a race condition.  Create the
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -451,14 +433,25 @@ do
   else
 
     # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
 
     # Trap to clean up those temp files at exit.
     trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
 
     # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
 
     # and set any options; do chmod last to preserve setuid bits.
     #
@@ -473,15 +466,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -494,24 +484,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
@@ -520,9 +510,9 @@ do
 done
 
 # Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
+# eval: (add-hook 'before-save-hook 'time-stamp)
 # time-stamp-start: "scriptversion="
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
+# time-stamp-time-zone: "UTC0"
 # time-stamp-end: "; # UTC"
-# End:
+# End:
\ No newline at end of file
similarity index 95%
rename from pkgs/tdbc1.1.1/tclconfig/tcl.m4
rename to pkgs/itcl4.2.1/tclconfig/tcl.m4
index 7d901f9..8d24e7f 100644 (file)
@@ -50,9 +50,9 @@ AC_DEFUN([TEA_PATH_TCLCONFIG], [
        # we reset no_tcl in case something fails here
        no_tcl=true
        AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
+           AS_HELP_STRING([--with-tcl],
                [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
+           [with_tclconfig="${withval}"])
        AC_MSG_CHECKING([for Tcl configuration])
        AC_CACHE_VAL(ac_cv_c_tclconfig,[
 
@@ -212,9 +212,9 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
        # we reset no_tk in case something fails here
        no_tk=true
        AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
+           AS_HELP_STRING([--with-tk],
                [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
+           [with_tkconfig="${withval}"])
        AC_MSG_CHECKING([for Tk configuration])
        AC_CACHE_VAL(ac_cv_c_tkconfig,[
 
@@ -266,9 +266,6 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
                        `ls -d /Library/Frameworks 2>/dev/null` \
                        `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
                        ; do
                    if test -f "$i/Tk.framework/tkConfig.sh" ; then
                        ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
@@ -285,10 +282,10 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                        `ls -d /usr/local/lib 2>/dev/null` \
                        `ls -d /usr/contrib/lib 2>/dev/null` \
                        `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
                        `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
@@ -375,10 +372,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
         AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -412,12 +405,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
     AC_SUBST(TCL_VERSION)
     AC_SUBST(TCL_PATCH_LEVEL)
     AC_SUBST(TCL_BIN_DIR)
@@ -493,10 +480,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
         AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
     # If the TK_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TK_LIB_SPEC will be set to the value
@@ -530,12 +513,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
        esac
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
     # TEA specific: Ensure windowingsystem is defined
     if test "${TEA_PLATFORM}" = "unix" ; then
        case ${TK_DEFS} in
@@ -592,14 +569,14 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -607,9 +584,9 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -650,14 +627,14 @@ AC_DEFUN([TEA_PROG_WISH], [
     if test -f "${TK_BIN_DIR}/Makefile" ; then
         # tkConfig.sh is in Tk build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             WISH_PROG="${TK_BIN_DIR}/wish"
@@ -665,9 +642,9 @@ AC_DEFUN([TEA_PROG_WISH], [
     else
         # tkConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
         else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
         fi
         list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
@@ -713,7 +690,7 @@ AC_DEFUN([TEA_PROG_WISH], [
 AC_DEFUN([TEA_ENABLE_SHARED], [
     AC_MSG_CHECKING([how to build libraries])
     AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
+       AS_HELP_STRING([--enable-shared],
            [build and link with shared libraries (default: on)]),
        [shared_ok=$enableval], [shared_ok=yes])
 
@@ -725,7 +702,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
     fi
 
     AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
+       AS_HELP_STRING([--enable-stubs],
            [build and link with stub libraries. Always true for shared builds (default: on)]),
        [stubs_ok=$enableval], [stubs_ok=yes])
 
@@ -797,7 +774,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
 
 AC_DEFUN([TEA_ENABLE_THREADS], [
     AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
+       AS_HELP_STRING([--enable-threads],
            [build with threads (default: on)]),
        [tcl_ok=$enableval], [tcl_ok=yes])
 
@@ -911,8 +888,6 @@ AC_DEFUN([TEA_ENABLE_THREADS], [
 #                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
 #              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
 #                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
 #------------------------------------------------------------------------
 
 AC_DEFUN([TEA_ENABLE_SYMBOLS], [
@@ -920,10 +895,9 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
     AC_REQUIRE([TEA_CONFIG_CFLAGS])
     AC_MSG_CHECKING([for build with symbols])
     AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
+       AS_HELP_STRING([--enable-symbols],
            [build with debugging symbols (default: off)]),
        [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -935,13 +909,8 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
            AC_MSG_RESULT([yes (standard debugging)])
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
     AC_SUBST(CFLAGS_DEFAULT)
     AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
 
     if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
        AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
@@ -976,7 +945,7 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
 
 AC_DEFUN([TEA_ENABLE_LANGINFO], [
     AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
+       AS_HELP_STRING([--enable-langinfo],
            [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
        [langinfo_ok=$enableval], [langinfo_ok=yes])
 
@@ -1108,7 +1077,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit support is requested])
     AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
+       AS_HELP_STRING([--enable-64bit],
            [enable 64bit support (default: off)]),
        [do64bit=$enableval], [do64bit=no])
     AC_MSG_RESULT([$do64bit])
@@ -1117,7 +1086,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
     AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
+       AS_HELP_STRING([--enable-64bit-vis],
            [enable 64bit Sparc VIS support (default: off)]),
        [do64bitVIS=$enableval], [do64bitVIS=no])
     AC_MSG_RESULT([$do64bitVIS])
@@ -1146,7 +1115,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if rpath support is requested])
     AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
+       AS_HELP_STRING([--disable-rpath],
            [disable rpath support (default: on)]),
        [doRpath=$enableval], [doRpath=yes])
     AC_MSG_RESULT([$doRpath])
@@ -1260,14 +1229,14 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -1336,11 +1305,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
                ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ], [
                AS_IF([test "$GCC" = yes], [
                    SHLIB_LD='${CC} -shared -Wl,-bexpall'
@@ -1349,7 +1318,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    LDFLAGS="$LDFLAGS -brtl"
                ])
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1385,19 +1354,6 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -1435,8 +1391,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ])
            AS_IF([test "$GCC" = yes], [
@@ -1455,7 +1411,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
                            AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
@@ -1476,8 +1432,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ]) ;;
        IRIX-5.*)
@@ -1486,16 +1442,16 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            ;;
        IRIX-6.*)
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            AS_IF([test "$GCC" = yes], [
                CFLAGS="$CFLAGS -mabi=n32"
                LDFLAGS="$LDFLAGS -mabi=n32"
@@ -1517,8 +1473,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
 
            # Check to enable 64-bit flags for compiler/linker
 
@@ -1533,7 +1489,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                ])
            ])
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -1543,8 +1499,19 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
            AS_IF([test $do64bit = yes], [
@@ -1574,8 +1541,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            LD_FLAGS="-Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            ;;
        OpenBSD-*)
            arch=`arch -s`
@@ -1590,10 +1557,10 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -1610,37 +1577,13 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            LDFLAGS="$LDFLAGS -export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
            LIBS=`echo $LIBS | sed s/-pthread//`
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -1774,7 +1717,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            ])
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
@@ -1827,11 +1770,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ], [
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1897,7 +1840,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                AS_IF([test "$do64bit_ok" = yes], [
                    AS_IF([test "$arch" = "sparcv9 sparc"], [
@@ -1924,8 +1867,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ])
            ;;
        UNIX_SV* | UnixWare-5*)
@@ -2091,6 +2034,8 @@ dnl # preprocessing tests use only CPPFLAGS.
     AC_SUBST(CFLAGS_DEBUG)
     AC_SUBST(CFLAGS_OPTIMIZE)
     AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
 
     AC_SUBST(STLIB_LD)
     AC_SUBST(SHLIB_LD)
@@ -2374,6 +2319,7 @@ AC_DEFUN([TEA_BLOCKING_STYLE], [
 #              HAVE_TM_GMTOFF
 #              HAVE_TM_TZADJ
 #              HAVE_TIMEZONE_VAR
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TIME_HANDLER], [
@@ -2381,7 +2327,7 @@ AC_DEFUN([TEA_TIME_HANDLER], [
     AC_HEADER_TIME
     AC_STRUCT_TIMEZONE
 
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
 
     AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
        AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
@@ -2449,6 +2395,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
     if test "$tcl_strtod" = 1; then
        AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
            AC_TRY_RUN([
+               #include <stdlib.h>
                extern double strtod();
                int main() {
                    char *infString="Inf", *nanString="NaN", *spaceString=" ";
@@ -2478,6 +2425,81 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 ])
 
 #--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
 # TEA_TCL_EARLY_FLAGS
 #
 #      Check for what flags are needed to be passed so the correct OS
@@ -2492,6 +2514,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 #              _ISOC99_SOURCE
 #              _LARGEFILE64_SOURCE
 #              _LARGEFILE_SOURCE64
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TCL_EARLY_FLAG],[
@@ -2912,7 +2935,7 @@ AC_DEFUN([TEA_ADD_LIBS], [
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3099,7 +3122,7 @@ AC_DEFUN([TEA_SETUP_COMPILER], [
 AC_DEFUN([TEA_MAKE_LIB], [
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        AC_EGREP_CPP([manifest needed], [
 #if defined(_MSC_VER) && _MSC_VER >= 1400
 print("manifest needed")
@@ -3114,7 +3137,7 @@ print("manifest needed")
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -3856,11 +3879,11 @@ AC_DEFUN([TEA_EXPORT_CONFIG], [
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
     else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
     $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
similarity index 99%
rename from pkgs/itcl4.2.0/tests/basic.test
rename to pkgs/itcl4.2.1/tests/basic.test
index eeb568a..6aca7c9 100644 (file)
@@ -114,12 +114,12 @@ test basic-1.6 {objects have an access command
     namespace which -command x
 } -cleanup $cleanup2 -result ::x
 
-test basic-1.7a {objects are added to the master list
+test basic-1.7a {objects are added to the global list
 } -setup $setup2 -body {
     itcl::find objects x
 } -cleanup $cleanup2 -result x
 
-test basic-1.7b {objects are added to the master list
+test basic-1.7b {objects are added to the global list
 } -setup $setup2 -body {
     itcl::find objects -class Counter x
 } -cleanup $cleanup2 -result x
similarity index 97%
rename from pkgs/itcl4.2.0/tests/import.test
rename to pkgs/itcl4.2.1/tests/import.test
index ee8ce00..e444177 100644 (file)
@@ -14,7 +14,8 @@
 package require tcltest 2.2
 namespace import ::tcltest::test
 ::tcltest::loadTestedCommands
-set ::itcllib [lindex [package ifneeded itcl [package require itcl]] 1]
+package require itcl
+set ::itcllib [lindex [lsearch -exact -index 1 -inline [info loaded] Itcl] 0]
 
 # ----------------------------------------------------------------------
 #  Test "itcl::import::stub" command
@@ -45,7 +46,7 @@ test import-1.3 {"stub exists" requires one argument} {
 set interp [interp create]
 $interp eval {set ::tcl::inl_mem_test 0}
 $interp eval "
-    [list ::load $::itcllib itcl]
+    [list ::load $::itcllib Itcl]
     [::tcltest::configure -load]
     proc auto_load {cmd {namespace {}}} {
         global debug
@@ -95,7 +96,7 @@ catch {interp delete $interp}
 set interp [interp create]
 $interp eval {set ::tcl::inl_mem_test 0}
 $interp eval "
-    [list ::load $::itcllib itcl]
+    [list ::load $::itcllib Itcl]
     [::tcltest::configure -load]
     proc auto_load {cmd {namespace {}}} {
         proc \$cmd {args} \[format {return \"%s: \$args\"} \$cmd\]
similarity index 68%
rename from pkgs/itcl4.2.0/tests/interp.test
rename to pkgs/itcl4.2.1/tests/interp.test
index a1dce2b..fb05aa2 100644 (file)
@@ -1,5 +1,5 @@
 #
-# Tests for using [incr Tcl] in slave interpreters
+# Tests for using [incr Tcl] in child interpreters
 # ----------------------------------------------------------------------
 #   AUTHOR:  Michael J. McLennan
 #            Bell Labs Innovations for Lucent Technologies
@@ -17,26 +17,26 @@ namespace import ::tcltest::test
 package require itcl
 
 # ----------------------------------------------------------------------
-#  Make sure that slave interpreters can be created and loaded
+#  Make sure that child interpreters can be created and loaded
 #  with [incr Tcl]...
 # ----------------------------------------------------------------------
-test interp-1.1 {create a slave interp with [incr Tcl]} {
-    interp create slave
-    load "" Itcl slave
-    list [slave eval "namespace children :: itcl"] [interp delete slave]
+test interp-1.1 {create a child interp with [incr Tcl]} {
+    interp create child
+    load "" Itcl child
+    list [child eval "namespace children :: itcl"] [interp delete child]
 } {::itcl {}}
 
-test interp-1.2 {create a safe slave interp with [incr Tcl]} {
-    interp create -safe slave
-    load "" Itcl slave
-    list [slave eval "namespace children :: itcl"] [interp delete slave]
+test interp-1.2 {create a safe child interp with [incr Tcl]} {
+    interp create -safe child
+    load "" Itcl child
+    list [child eval "namespace children :: itcl"] [interp delete child]
 } {::itcl {}}
 
-test interp-1.3 {errors are okay when slave interp is deleted} {
-catch {interp delete slave}
-    interp create slave
-    load "" Itcl slave
-    slave eval {
+test interp-1.3 {errors are okay when child interp is deleted} {
+catch {interp delete child}
+    interp create child
+    load "" Itcl child
+    child eval {
         itcl::class Troublemaker {
             destructor { error "cannot delete this object" }
         }
@@ -51,13 +51,13 @@ catch {interp delete slave}
         }
         Foo f
     }
-    interp delete slave
+    interp delete child
 } {}
 
 test interp-1.4 {one namespace can cause another to be destroyed} {
-    interp create slave
-    load "" Itcl slave
-    slave eval {
+    interp create child
+    load "" Itcl child
+    child eval {
         namespace eval group {
             itcl::class base1 {}
             itcl::class base2 {}
@@ -66,14 +66,14 @@ test interp-1.4 {one namespace can cause another to be destroyed} {
             inherit group::base1 group::base2
         }
     }
-    interp delete slave
+    interp delete child
 } {}
 
 test interp-1.5 {cleanup interp object list, this should not
         include an object that deletes itself in ctor} {
-    interp create slave
-    load "" Itcl slave
-    slave eval {
+    interp create child
+    load "" Itcl child
+    child eval {
         itcl::class DeleteSelf {
             constructor {} {
                 itcl::delete object $this
@@ -81,7 +81,7 @@ test interp-1.5 {cleanup interp object list, this should not
         }
         DeleteSelf ds
     }
-    interp delete slave
+    interp delete child
 } {}
 
 ::tcltest::cleanupTests
similarity index 83%
rename from pkgs/itcl4.2.0/tests/methods.test
rename to pkgs/itcl4.2.1/tests/methods.test
index bd83a67..744b07f 100644 (file)
@@ -153,6 +153,49 @@ test methods-2.1 {covers leak condition test for compiled locals, no args} {
     }
     list 0
 } 0
+test methods-2.2 {covers leak condition test for nested methods calls within eval, bug [8e632ce049]} -setup {
+    itcl::class C1 {
+       proc factory {} {
+           set obj [C1 #auto]
+           $obj myeval [list $obj read]
+           itcl::delete object $obj
+       }
+       method myeval {script} { eval $script }
+       method read {} { myeval {} }
+    }
+} -body {
+    time { C1::factory } 50
+    list 0
+} -result 0 -cleanup {
+    itcl::delete class C1
+}
+test methods-2.3 {call of method after object is destroyed inside other methods, SF-bug [c1289b1c32]} -setup {
+    proc c1test {} {
+       return c1test
+    }
+    itcl::class C1 {
+       public method m1 {} {
+           itcl::delete object $this
+           c1test
+       }
+       public method m2 {} {
+           rename $this {}
+           c1test
+       }
+       public method c1test {} {
+          return C1::c1test
+       }
+    }
+} -body {
+    set result {}
+    set obj [C1 #auto]
+    lappend result [catch {$obj m1} v] $v [namespace which -command $obj]
+    set obj [C1 #auto]
+    lappend result [catch {$obj m2} v] $v [namespace which -command $obj]
+} -match glob -result {1 * {} 1 * {}} -cleanup {
+    itcl::delete class C1
+    rename c1test {}
+}
 
 # ----------------------------------------------------------------------
 #  Clean up
similarity index 99%
rename from pkgs/itcl4.2.0/tests/sfbugs.test
rename to pkgs/itcl4.2.1/tests/sfbugs.test
index 6dd88bd..8c07b43 100644 (file)
@@ -457,12 +457,12 @@ test sfbug-257 { SF bug #257
   -cleanup {interp delete $interp}
 
 test sfbug-259 { SF bug #257 } -setup {
-    interp create slave
-    load {} Itcl slave
+    interp create child
+    load {} Itcl child
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -body {
-    slave eval {
+    child eval {
 proc do_uplevel { body } {
     uplevel 1 $body
 }
similarity index 94%
rename from pkgs/tdbc1.1.1/win/rules-ext.vc
rename to pkgs/itcl4.2.1/win/rules-ext.vc
index 531e070..6da5689 100644 (file)
@@ -31,7 +31,7 @@ macro to the name of the project makefile.
 # We extract version numbers using the nmakehlp program. For now use\r
 # the local copy of nmakehlp. Once we locate Tcl, we will use that\r
 # one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
 !endif\r
 \r
 # First locate the Tcl directory that we are working with.\r
similarity index 89%
rename from pkgs/tdbc1.1.1/win/rules.vc
rename to pkgs/itcl4.2.1/win/rules.vc
index 325357c..13e3879 100644 (file)
@@ -6,7 +6,7 @@
 # compiler switches, defining common targets and macros. The Tcl makefile\r
 # directly includes this. Extensions include it via "rules-ext.vc".\r
 #\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
@@ -24,7 +24,7 @@ _RULES_VC = 1
 # For modifications that are not backward-compatible, you *must* change\r
 # the major version.\r
 RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
+RULES_VERSION_MINOR = 8\r
 \r
 # The PROJECT macro must be defined by parent makefile.\r
 !if "$(PROJECT)" == ""\r
@@ -302,7 +302,7 @@ TCLDIR          = $(_INSTALLDIR)\..
 _TCLDIR                = $(_INSTALLDIR)\..\r
 _TCL_H          = $(_TCLDIR)\include\tcl.h\r
 \r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !if [echo _TCLDIR = \> nmakehlp.out] \\r
    || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
@@ -313,7 +313,7 @@ TCLINSTALL      = 0
 TCLDIR         = $(_TCLDIR)\r
 _TCL_H          = $(_TCLDIR)\generic\tcl.h\r
 \r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !endif # TCLDIR\r
 \r
@@ -415,9 +415,6 @@ _INSTALLDIR=$(_INSTALLDIR)\lib
 # NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
 # MACHINE - same as $(ARCH) - legacy\r
 # _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
 \r
 cc32           = $(CC)   # built-in default.\r
 link32         = link\r
@@ -503,10 +500,6 @@ _VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -ou
 _VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
 !endif\r
 \r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
 ################################################################\r
 # 4. Build the nmakehlp program\r
 # This is a helper app we need to overcome nmake's limiting\r
@@ -514,7 +507,7 @@ CFG_ENCODING        = \"cp1252\"
 # information about supported compiler options etc.\r
 #\r
 # Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
+# in its own source. It will be kept updated there.\r
 #\r
 # Extensions built against an installed Tcl will use the installed\r
 # copy of Tcl's nmakehlp.c if there is one and their own version\r
@@ -537,7 +530,7 @@ NMAKEHLPC = nmakehlp.c
 !if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
 !endif\r
-!else # ! $(TCLINSTALL)\r
+!else # !$(TCLINSTALL)\r
 !if exist("$(_TCLDIR)\win\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
 !endif\r
@@ -659,8 +652,130 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 !endif\r
 !endif\r
 \r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
 ########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
 # Based on this, we will construct the actual switches to be passed to the\r
 # compiler and linker using the macros defined in the previous section.\r
 # The following macros are defined by this section based on OPTS\r
@@ -674,9 +789,10 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
 #           0 -> link to static C runtime for static Tcl build.\r
 #           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
 # TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
 # USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
 #           0 -> Use the non-thread allocator.\r
 # UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
@@ -685,7 +801,9 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
 #           configuration (ignored for Tcl itself)\r
 # _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
 # Further, LINKERFLAGS are modified based on above.\r
 \r
 # Default values for all the above\r
@@ -728,11 +846,8 @@ MSVCRT             = 0
 !else\r
 !if [nmakehlp -f $(OPTS) "msvcrt"]\r
 !message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
 !else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
 MSVCRT         = 0\r
 !endif\r
 !endif\r
@@ -741,24 +856,26 @@ MSVCRT            = 0
 !if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
 !message *** Doing staticpkg\r
 TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
 !endif\r
 \r
 !if [nmakehlp -f $(OPTS) "nothreads"]\r
 !message *** Compile explicitly for non-threaded tcl\r
 TCL_THREADS = 0\r
 USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
 !endif\r
 \r
+!if $(TCL_MAJOR_VERSION) == 8\r
 !if [nmakehlp -f $(OPTS) "time64bit"]\r
 !message *** Force 64-bit time_t\r
 _USE_64BIT_TIME_T = 1\r
 !endif\r
 \r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
 # Yes, it's weird that the "symbols" option controls DEBUG and\r
 # the "pdbs" option controls SYMBOLS. That's historical.\r
 !if [nmakehlp -f $(OPTS) "symbols"]\r
@@ -842,7 +959,7 @@ This compiler does not support profile guided optimization.
 !endif\r
 \r
 ################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
+# 8. Parse the STATS macro to configure code instrumentation\r
 # The following macros are set by this section:\r
 # TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
 #                 0 -> disables\r
@@ -872,7 +989,7 @@ TCL_COMPILE_DEBUG   = 0
 !endif\r
 \r
 ####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
 # The following macros are set by this section:\r
 # WARNINGS - compiler switches that control the warnings level\r
 # TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
@@ -904,86 +1021,6 @@ WARNINGS              = $(WARNINGS) -Wp64
 \r
 !endif\r
 \r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
 \r
 ################################################################\r
 # 10. Construct output directory and file paths\r
@@ -1029,7 +1066,7 @@ BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)
 BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
 !endif\r
 \r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
 SUFX       = $(SUFX:g=)\r
 !endif\r
 \r
@@ -1080,20 +1117,35 @@ OUT_DIR     = $(TMP_DIR)
 # The name of the stubs library for the project being built\r
 STUBPREFIX      = $(PROJECT)stub\r
 \r
+#\r
 # Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
+#\r
 \r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
 TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
 TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
 TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
 TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
 TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
 \r
 TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
 TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
 TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
 \r
-!else # ! $(DOING_TCL)\r
+!else # !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 \r
@@ -1115,6 +1167,7 @@ TCLIMPLIB = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\lib\r
 TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
 TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
 \r
@@ -1134,6 +1187,7 @@ TCLIMPLIB = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\library\r
 TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = $(_TCLDIR)\tools\r
 TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
 \r
@@ -1166,7 +1220,8 @@ WISH              = $(OUT_DIR)\$(WISHNAME)
 TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
 TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
 \r
 !else # effectively NEED_TK\r
 \r
@@ -1181,7 +1236,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
 !else # Building against Tk sources\r
+\r
 WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
 TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
@@ -1192,7 +1250,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
 !endif # TKINSTALL\r
+\r
 tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
 \r
 !endif # $(DOING_TK)\r
@@ -1233,6 +1294,7 @@ BIN_INSTALL_DIR           = $(_INSTALLDIR)\bin
 DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
 !if $(DOING_TCL)\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
 !else # DOING_TK\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
 !endif\r
@@ -1277,7 +1339,15 @@ INCLUDE_INSTALL_DIR      = $(_INSTALLDIR)\..\include
 # baselibs - minimum Windows libraries required. Parent makefile can\r
 #    define PRJ_LIBS before including rules.rc if additional libs are needed\r
 \r
-OPTDEFINES     = /DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) /DSTDC_HEADERS\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
 \r
 !if $(TCL_MEM_DEBUG)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
@@ -1293,6 +1363,11 @@ OPTDEFINES       = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1
 !endif\r
 !if $(STATIC_BUILD)\r
 OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
 !endif\r
 !if $(TCL_NO_DEPRECATED)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
@@ -1301,7 +1376,7 @@ OPTDEFINES        = $(OPTDEFINES) /DTCL_NO_DEPRECATED
 !if $(USE_STUBS)\r
 # Note we do not define USE_TCL_STUBS even when building tk since some\r
 # test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
 !if $(NEED_TK)\r
 USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
@@ -1322,15 +1397,20 @@ OPTDEFINES      = $(OPTDEFINES) /DTCL_CFG_PROFILED
 OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
 !endif\r
 !if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
 !endif\r
 \r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
 !if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
 !endif\r
 \r
 # _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
 COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
 \r
 # Like the TEA system only set this non empty for non-Tk extensions\r
 # Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
@@ -1455,18 +1535,6 @@ lflags   = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)
 lflags = $(lflags) -nodefaultlib:libucrt.lib\r
 !endif\r
 \r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
 dlllflags = $(lflags) -dll\r
 conlflags = $(lflags) -subsystem:console\r
 guilflags = $(lflags) -subsystem:windows\r
@@ -1508,7 +1576,7 @@ GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)
 RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
            $(TCL_INCLUDES) \\r
            /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           /DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
            /DDOTVERSION=\"$(DOTVERSION)\" \\r
            /DVERSION=\"$(VERSION)\" \\r
            /DSUFX=\"$(SUFX)\" \\r
@@ -1524,11 +1592,11 @@ default-target: $(DEFAULT_BUILD_TARGET)
 !if $(MULTIPLATFORM_INSTALL)\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !else\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !endif\r
 \r
 default-pkgindex-tea:\r
@@ -1574,6 +1642,8 @@ default-install-pdbs:
        @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
        @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
 \r
+# "emacs font-lock highlighting fix\r
+\r
 default-install-docs-html:\r
        @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
        @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
@@ -1636,7 +1706,7 @@ default-shell: default-setup $(PROJECT)
 !ifdef RCFILE\r
 \r
 # Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
+# and only the "main" rc must be passed to the resource compiler\r
 $(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
        $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
 \r
@@ -1690,7 +1760,7 @@ DISABLE_IMPLICIT_RULES = 0
 \r
 !if !$(DISABLE_IMPLICIT_RULES)\r
 # Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
+# main application, the makefile should define explicit rules.\r
 \r
 {$(ROOT)}.c{$(TMP_DIR)}.obj::\r
        $(CCPKGCMD) @<<\r
@@ -1731,15 +1801,15 @@ $<
 # When building an extension, certain configuration options should\r
 # match the ones used when Tcl was built. Here we check and\r
 # warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 !if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
 TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
 !endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
 !endif\r
 !endif # TCLINSTALL\r
 \r
@@ -1760,7 +1830,7 @@ TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"
 \r
 !endif # TCLNMAKECONFIG\r
 \r
-!endif # ! $(DOING_TCL)\r
+!endif # !$(DOING_TCL)\r
 \r
 \r
 #----------------------------------------------------------\r
similarity index 93%
rename from pkgs/sqlite3.30.1.2/win/targets.vc
rename to pkgs/itcl4.2.1/win/targets.vc
index 7f1d388..077e8f7 100644 (file)
@@ -4,7 +4,7 @@
 # Part of the nmake based build system for Tcl and its extensions.\r
 # This file defines some standard targets for the convenience of extensions\r
 # and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
 \r
 $(PROJECT): setup pkgindex $(PRJLIB)\r
 \r
diff --git a/pkgs/sqlite3.30.1.2/win/sqlite.rc b/pkgs/sqlite3.30.1.2/win/sqlite.rc
deleted file mode 100755 (executable)
index be6965c..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-#include <winver.h>\r
-\r
-VS_VERSION_INFO VERSIONINFO\r
- FILEVERSION   3,30,1,2\r
- PRODUCTVERSION        3,30,1,2\r
- FILEFLAGSMASK 0x3fL\r
-#ifdef DEBUG\r
- FILEFLAGS     VS_FF_DEBUG\r
-#else\r
- FILEFLAGS     0x0L\r
-#endif\r
- FILEOS                VOS_NT_WINDOWS32\r
- FILETYPE      VFT_DLL\r
- FILESUBTYPE   0x0L\r
-BEGIN\r
-    BLOCK "StringFileInfo"\r
-    BEGIN\r
-        BLOCK "040904b0"\r
-        BEGIN\r
-            VALUE "FileDescription",  "Tcl extension " PROJECT\r
-            VALUE "OriginalFilename", PRJLIBNAME\r
-            VALUE "FileVersion",      DOTVERSION\r
-            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
-            VALUE "ProductVersion",   DOTVERSION\r
-        END\r
-    END\r
-    BLOCK "VarFileInfo"\r
-    BEGIN\r
-        VALUE "Translation", 0x409, 1200\r
-    END\r
-END\r
-\r
similarity index 93%
rename from pkgs/sqlite3.30.1.2/Makefile.in
rename to pkgs/sqlite3.34.0/Makefile.in
index 196ae0c..6b73e35 100644 (file)
@@ -166,7 +166,17 @@ CPPFLAGS   = @CPPFLAGS@
 LIBS           = @PKG_LIBS@ @LIBS@
 AR             = @AR@
 CFLAGS         = @CFLAGS@
-COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LDFLAGS                = @LDFLAGS@
+LDFLAGS_DEFAULT                        = @LDFLAGS_DEFAULT@
+COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
+                         $(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
+
+GDB            = gdb
+VALGRIND       = valgrind
+VALGRINDARGS   = --tool=memcheck --num-callers=8 --leak-resolution=high \
+                 --leak-check=yes --show-reachable=yes -v
+
+.SUFFIXES: .c .$(OBJEXT)
 
 #========================================================================
 # Start of user-definable TARGETS section
@@ -233,8 +243,8 @@ install-doc: doc
        @echo "Installing documentation in $(DESTDIR)$(mandir)"
        @list='$(srcdir)/doc/*.n'; for i in $$list; do \
            echo "Installing $$i"; \
-           rm -f $(DESTDIR)$(mandir)/mann/`basename $$i`; \
-           $(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \
+           rm -f "$(DESTDIR)$(mandir)/mann/`basename $$i`"; \
+           $(INSTALL_DATA) $$i "$(DESTDIR)$(mandir)/mann" ; \
        done
 
 test: binaries libraries
@@ -364,25 +374,25 @@ distclean: clean
 #========================================================================
 
 install-lib-binaries: binaries
-       @mkdir -p $(DESTDIR)$(pkglibdir)
+       @mkdir -p "$(DESTDIR)$(pkglibdir)"
        @list='$(lib_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
-           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(pkglibdir)/$$p; \
+           $(INSTALL_PROGRAM) $$p "$(DESTDIR)$(pkglibdir)/$$p"; \
            stub=`echo $$p|sed -e "s/.*\(stub\).*/\1/"`; \
            if test "x$$stub" = "xstub"; then \
                echo " $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p"; \
-               $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p; \
+               $(RANLIB_STUB) "$(DESTDIR)$(pkglibdir)/$$p"; \
            else \
                echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \
-               $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \
+               $(RANLIB) "$(DESTDIR)$(pkglibdir)/$$p"; \
            fi; \
            ext=`echo $$p|sed -e "s/.*\.//"`; \
            if test "x$$ext" = "xdll"; then \
                lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
                if test -f $$lib; then \
                    echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
-                   $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
+                   $(INSTALL_DATA) $$lib "$(DESTDIR)$(pkglibdir)/$$lib"; \
                fi; \
            fi; \
          fi; \
@@ -391,12 +401,12 @@ install-lib-binaries: binaries
          if test -f $(srcdir)/$$p; then \
            destp=`basename $$p`; \
            echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
-           $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
+           $(INSTALL_DATA) $(srcdir)/$$p "$(DESTDIR)$(pkglibdir)/$$destp"; \
          fi; \
        done
        @if test "x$(SHARED_BUILD)" = "x1"; then \
            echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \
-           $(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \
+           $(INSTALL_DATA) pkgIndex.tcl "$(DESTDIR)$(pkglibdir)"; \
        fi
 
 #========================================================================
@@ -409,14 +419,14 @@ install-lib-binaries: binaries
 #========================================================================
 
 install-bin-binaries: binaries
-       @mkdir -p $(DESTDIR)$(bindir)
+       @mkdir -p "$(DESTDIR)$(bindir)"
        @list='$(bin_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
-           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
+           $(INSTALL_PROGRAM) $$p "$(DESTDIR)$(bindir)/$$p"; \
          fi; \
        done
-       $(INSTALL_PROGRAM) $(srcdir)/compat/sqlite3/spaceanal.tcl $(DESTDIR)$(bindir)/sqlite3_analyzer
+       $(INSTALL_PROGRAM) $(srcdir)/compat/sqlite3/spaceanal.tcl "$(DESTDIR)$(bindir)/sqlite3_analyzer"
 
 .SUFFIXES: .c .$(OBJEXT)
 
@@ -426,14 +436,14 @@ Makefile: $(srcdir)/Makefile.in  $(top_builddir)/config.status
 
 uninstall-binaries:
        list='$(lib_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
          p=`basename $$p`; \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(bin_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(bindir)/$$p; \
+         rm -f "$(DESTDIR)$(bindir)/$$p"; \
        done
 
 .PHONY: all binaries clean depend distclean doc install libraries test
similarity index 87%
rename from pkgs/sqlite3.30.1.2/compat/sqlite3/shell.c
rename to pkgs/sqlite3.34.0/compat/sqlite3/shell.c
index 0d4d11f..6aabe0a 100644 (file)
 #endif
 
 /*
+** Determine if we are dealing with WinRT, which provides only a subset of
+** the full Win32 API.
+*/
+#if !defined(SQLITE_OS_WINRT)
+# define SQLITE_OS_WINRT 0
+#endif
+
+/*
 ** Warning pragmas copied from msvc.h in the core.
 */
 #if defined(_MSC_VER)
@@ -147,22 +155,26 @@ typedef unsigned char u8;
 
 
 #if defined(_WIN32) || defined(WIN32)
-# include <io.h>
-# include <fcntl.h>
-# define isatty(h) _isatty(h)
-# ifndef access
-#  define access(f,m) _access((f),(m))
-# endif
-# ifndef unlink
-#  define unlink _unlink
-# endif
-# ifndef strdup
-#  define strdup _strdup
+# if SQLITE_OS_WINRT
+#  define SQLITE_OMIT_POPEN 1
+# else
+#  include <io.h>
+#  include <fcntl.h>
+#  define isatty(h) _isatty(h)
+#  ifndef access
+#   define access(f,m) _access((f),(m))
+#  endif
+#  ifndef unlink
+#   define unlink _unlink
+#  endif
+#  ifndef strdup
+#   define strdup _strdup
+#  endif
+#  undef popen
+#  define popen _popen
+#  undef pclose
+#  define pclose _pclose
 # endif
-# undef popen
-# define popen _popen
-# undef pclose
-# define pclose _pclose
 #else
  /* Make sure isatty() has a prototype. */
  extern int isatty(int);
@@ -191,6 +203,9 @@ typedef unsigned char u8;
 #define ToLower(X)  (char)tolower((unsigned char)X)
 
 #if defined(_WIN32) || defined(WIN32)
+#if SQLITE_OS_WINRT
+#include <intrin.h>
+#endif
 #include <windows.h>
 
 /* string conversion routines only needed on Win32 */
@@ -206,7 +221,7 @@ extern LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText);
 ** rendering quoted strings that contain \n characters).  The following
 ** routines take care of that.
 */
-#if defined(_WIN32) || defined(WIN32)
+#if (defined(_WIN32) || defined(WIN32)) && !SQLITE_OS_WINRT
 static void setBinaryMode(FILE *file, int isOutput){
   if( isOutput ) fflush(file);
   _setmode(_fileno(file), _O_BINARY);
@@ -384,6 +399,15 @@ static sqlite3 *globalDb = 0;
 */
 static volatile int seenInterrupt = 0;
 
+#ifdef SQLITE_DEBUG
+/*
+** Out-of-memory simulator variables
+*/
+static unsigned int oomCounter = 0;    /* Simulate OOM when equals 1 */
+static unsigned int oomRepeat = 0;     /* Number of OOMs in a row */
+static void*(*defaultMalloc)(int) = 0; /* The low-level malloc routine */
+#endif /* SQLITE_DEBUG */
+
 /*
 ** This is the name of our program. It is set in main(), used
 ** in a number of other places, mostly for error messages.
@@ -435,6 +459,49 @@ static void shell_out_of_memory(void){
   exit(1);
 }
 
+#ifdef SQLITE_DEBUG
+/* This routine is called when a simulated OOM occurs.  It is broken
+** out as a separate routine to make it easy to set a breakpoint on
+** the OOM
+*/
+void shellOomFault(void){
+  if( oomRepeat>0 ){
+    oomRepeat--;
+  }else{
+    oomCounter--;
+  }
+}
+#endif /* SQLITE_DEBUG */
+
+#ifdef SQLITE_DEBUG
+/* This routine is a replacement malloc() that is used to simulate
+** Out-Of-Memory (OOM) errors for testing purposes.
+*/
+static void *oomMalloc(int nByte){
+  if( oomCounter ){
+    if( oomCounter==1 ){
+      shellOomFault();
+      return 0;
+    }else{
+      oomCounter--;
+    }
+  }
+  return defaultMalloc(nByte);
+}
+#endif /* SQLITE_DEBUG */
+
+#ifdef SQLITE_DEBUG
+/* Register the OOM simulator.  This must occur before any memory
+** allocations */
+static void registerOomSimulator(void){
+  sqlite3_mem_methods mem;
+  sqlite3_config(SQLITE_CONFIG_GETMALLOC, &mem);
+  defaultMalloc = mem.xMalloc;
+  mem.xMalloc = oomMalloc;
+  sqlite3_config(SQLITE_CONFIG_MALLOC, &mem);
+}
+#endif
+
 /*
 ** Write I/O traces to the following stream.
 */
@@ -471,8 +538,6 @@ static void utf8_width_print(FILE *pOut, int w, const char *zUtf){
   int i;
   int n;
   int aw = w<0 ? -w : w;
-  char zBuf[1000];
-  if( aw>(int)sizeof(zBuf)/3 ) aw = (int)sizeof(zBuf)/3;
   for(i=n=0; zUtf[i]; i++){
     if( (zUtf[i]&0xc0)!=0x80 ){
       n++;
@@ -542,6 +607,21 @@ static int strlenChar(const char *z){
 }
 
 /*
+** Return true if zFile does not exist or if it is not an ordinary file.
+*/
+#ifdef _WIN32
+# define notNormalFile(X) 0
+#else
+static int notNormalFile(const char *zFile){
+  struct stat x;
+  int rc;
+  memset(&x, 0, sizeof(x));
+  rc = stat(zFile, &x);
+  return rc || !S_ISREG(x.st_mode);
+}
+#endif
+
+/*
 ** This routine reads a line of text from FILE in, stores
 ** the text in memory obtained from malloc() and returns a pointer
 ** to the text.  NULL is returned at end of file, or if malloc()
@@ -853,7 +933,7 @@ static void shellModuleSchema(
 **    CREATE VIRTUAL TABLE
 **
 ** This UDF is used by the .schema command to insert the schema name of
-** attached databases into the middle of the sqlite_master.sql field.
+** attached databases into the middle of the sqlite_schema.sql field.
 */
 static void shellAddSchemaName(
   sqlite3_context *pCtx,
@@ -1353,10 +1433,6 @@ struct SHA3Context {
   unsigned ixMask;       /* Insert next input into u.x[nLoaded^ixMask]. */
 };
 
-/* Allow the following routine to use the B0 variable, which is also
-** a macro in the termios.h header file */
-#undef B0
-
 /*
 ** A single step of the Keccak mixing function for a 1600-bit state
 */
@@ -1980,19 +2056,23 @@ int sqlite3_shathree_init(
   int rc = SQLITE_OK;
   SQLITE_EXTENSION_INIT2(pApi);
   (void)pzErrMsg;  /* Unused parameter */
-  rc = sqlite3_create_function(db, "sha3", 1, SQLITE_UTF8, 0,
-                               sha3Func, 0, 0);
+  rc = sqlite3_create_function(db, "sha3", 1,
+                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
+                      0, sha3Func, 0, 0);
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "sha3", 2, SQLITE_UTF8, 0,
-                                 sha3Func, 0, 0);
+    rc = sqlite3_create_function(db, "sha3", 2,
+                      SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
+                      0, sha3Func, 0, 0);
   }
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "sha3_query", 1, SQLITE_UTF8, 0,
-                                 sha3QueryFunc, 0, 0);
+    rc = sqlite3_create_function(db, "sha3_query", 1,
+                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
+                      0, sha3QueryFunc, 0, 0);
   }
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "sha3_query", 2, SQLITE_UTF8, 0,
-                                 sha3QueryFunc, 0, 0);
+    rc = sqlite3_create_function(db, "sha3_query", 2,
+                      SQLITE_UTF8 | SQLITE_DIRECTONLY,
+                      0, sha3QueryFunc, 0, 0);
   }
   return rc;
 }
@@ -2394,6 +2474,7 @@ static int writeFile(
 
   if( mtime>=0 ){
 #if defined(_WIN32)
+#if !SQLITE_OS_WINRT
     /* Windows */
     FILETIME lastAccess;
     FILETIME lastWrite;
@@ -2424,6 +2505,7 @@ static int writeFile(
     }else{
       return 1;
     }
+#endif
 #elif defined(AT_FDCWD) && 0 /* utimensat() is not universally available */
     /* Recent unix */
     struct timespec times[2];
@@ -2591,6 +2673,7 @@ static int fsdirConnect(
     pNew = (fsdir_tab*)sqlite3_malloc( sizeof(*pNew) );
     if( pNew==0 ) return SQLITE_NOMEM;
     memset(pNew, 0, sizeof(*pNew));
+    sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
   }
   *ppVtab = (sqlite3_vtab*)pNew;
   return rc;
@@ -2984,10 +3067,12 @@ int sqlite3_fileio_init(
   int rc = SQLITE_OK;
   SQLITE_EXTENSION_INIT2(pApi);
   (void)pzErrMsg;  /* Unused parameter */
-  rc = sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
+  rc = sqlite3_create_function(db, "readfile", 1, 
+                               SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
                                readfileFunc, 0, 0);
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "writefile", -1, SQLITE_UTF8, 0,
+    rc = sqlite3_create_function(db, "writefile", -1,
+                                 SQLITE_UTF8|SQLITE_DIRECTONLY, 0,
                                  writefileFunc, 0, 0);
   }
   if( rc==SQLITE_OK ){
@@ -3122,6 +3207,7 @@ static int completionConnect(
 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
 
+  sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
   rc = sqlite3_declare_vtab(db,
       "CREATE TABLE x("
       "  candidate TEXT,"
@@ -3229,7 +3315,7 @@ static int completionNext(sqlite3_vtab_cursor *cur){
             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
             zSql = sqlite3_mprintf(
                "%z%s"
-               "SELECT name FROM \"%w\".sqlite_master",
+               "SELECT name FROM \"%w\".sqlite_schema",
                zSql, zSep, zDb
             );
             if( zSql==0 ) return SQLITE_NOMEM;
@@ -3253,7 +3339,7 @@ static int completionNext(sqlite3_vtab_cursor *cur){
             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
             zSql = sqlite3_mprintf(
                "%z%s"
-               "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
+               "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
                " WHERE sm.type='table'",
                zSql, zSep, zDb, zDb
@@ -3946,7 +4032,7 @@ static int apndOpen(
   p = (ApndFile*)pFile;
   memset(p, 0, sizeof(*p));
   pSubFile = ORIGFILE(pFile);
-  p->base.pMethods = &apnd_io_methods;
+  pFile->pMethods = &apnd_io_methods;
   rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
   if( rc ) goto apnd_open_done;
   rc = pSubFile->pMethods->xFileSize(pSubFile, &sz);
@@ -4117,72 +4203,1526 @@ static void memtraceFree(void *p){
   if( memtraceOut ){
     fprintf(memtraceOut, "MEMTRACE: free %d bytes\n", memtraceBase.xSize(p));
   }
-  memtraceBase.xFree(p);
-}
-static void *memtraceRealloc(void *p, int n){
-  if( p==0 ) return memtraceMalloc(n);
-  if( n==0 ){
-    memtraceFree(p);
-    return 0;
+  memtraceBase.xFree(p);
+}
+static void *memtraceRealloc(void *p, int n){
+  if( p==0 ) return memtraceMalloc(n);
+  if( n==0 ){
+    memtraceFree(p);
+    return 0;
+  }
+  if( memtraceOut ){
+    fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
+            memtraceBase.xSize(p), memtraceBase.xRoundup(n));
+  }
+  return memtraceBase.xRealloc(p, n);
+}
+static int memtraceSize(void *p){
+  return memtraceBase.xSize(p);
+}
+static int memtraceRoundup(int n){
+  return memtraceBase.xRoundup(n);
+}
+static int memtraceInit(void *p){
+  return memtraceBase.xInit(p);
+}
+static void memtraceShutdown(void *p){
+  memtraceBase.xShutdown(p);
+}
+
+/* The substitute memory allocator */
+static sqlite3_mem_methods ersaztMethods = {
+  memtraceMalloc,
+  memtraceFree,
+  memtraceRealloc,
+  memtraceSize,
+  memtraceRoundup,
+  memtraceInit,
+  memtraceShutdown,
+  0
+};
+
+/* Begin tracing memory allocations to out. */
+int sqlite3MemTraceActivate(FILE *out){
+  int rc = SQLITE_OK;
+  if( memtraceBase.xMalloc==0 ){
+    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
+    if( rc==SQLITE_OK ){
+      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
+    }
+  }
+  memtraceOut = out;
+  return rc;
+}
+
+/* Deactivate memory tracing */
+int sqlite3MemTraceDeactivate(void){
+  int rc = SQLITE_OK;
+  if( memtraceBase.xMalloc!=0 ){
+    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
+    if( rc==SQLITE_OK ){
+      memset(&memtraceBase, 0, sizeof(memtraceBase));
+    }
+  }
+  memtraceOut = 0;
+  return rc;
+}
+
+/************************* End ../ext/misc/memtrace.c ********************/
+/************************* Begin ../ext/misc/uint.c ******************/
+/*
+** 2020-04-14
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This SQLite extension implements the UINT collating sequence.
+**
+** UINT works like BINARY for text, except that embedded strings
+** of digits compare in numeric order.
+**
+**     *   Leading zeros are handled properly, in the sense that
+**         they do not mess of the maginitude comparison of embedded
+**         strings of digits.  "x00123y" is equal to "x123y".
+**
+**     *   Only unsigned integers are recognized.  Plus and minus
+**         signs are ignored.  Decimal points and exponential notation
+**         are ignored.
+**
+**     *   Embedded integers can be of arbitrary length.  Comparison
+**         is *not* limited integers that can be expressed as a
+**         64-bit machine integer.
+*/
+/* #include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+
+/*
+** Compare text in lexicographic order, except strings of digits
+** compare in numeric order.
+*/
+static int uintCollFunc(
+  void *notUsed,
+  int nKey1, const void *pKey1,
+  int nKey2, const void *pKey2
+){
+  const unsigned char *zA = (const unsigned char*)pKey1;
+  const unsigned char *zB = (const unsigned char*)pKey2;
+  int i=0, j=0, x;
+  (void)notUsed;
+  while( i<nKey1 && j<nKey2 ){
+    x = zA[i] - zB[j];
+    if( isdigit(zA[i]) ){
+      int k;
+      if( !isdigit(zB[j]) ) return x;
+      while( i<nKey1 && zA[i]=='0' ){ i++; }
+      while( j<nKey2 && zB[j]=='0' ){ j++; }
+      k = 0;
+      while( i+k<nKey1 && isdigit(zA[i+k])
+             && j+k<nKey2 && isdigit(zB[j+k]) ){
+        k++;
+      }
+      if( i+k<nKey1 && isdigit(zA[i+k]) ){
+        return +1;
+      }else if( j+k<nKey2 && isdigit(zB[j+k]) ){
+        return -1;
+      }else{
+        x = memcmp(zA+i, zB+j, k);
+        if( x ) return x;
+        i += k;
+        j += k;
+      }
+    }else if( x ){
+      return x;
+    }else{
+      i++;
+      j++;
+    }
+  }
+  return (nKey1 - i) - (nKey2 - j);
+}
+
+#ifdef _WIN32
+
+#endif
+int sqlite3_uint_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
+  SQLITE_EXTENSION_INIT2(pApi);
+  (void)pzErrMsg;  /* Unused parameter */
+  return sqlite3_create_collation(db, "uint", SQLITE_UTF8, 0, uintCollFunc);
+}
+
+/************************* End ../ext/misc/uint.c ********************/
+/************************* Begin ../ext/misc/decimal.c ******************/
+/*
+** 2020-06-22
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** Routines to implement arbitrary-precision decimal math.
+**
+** The focus here is on simplicity and correctness, not performance.
+*/
+/* #include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+#include <ctype.h>
+#include <stdlib.h>
+
+/* Mark a function parameter as unused, to suppress nuisance compiler
+** warnings. */
+#ifndef UNUSED_PARAMETER
+# define UNUSED_PARAMETER(X)  (void)(X)
+#endif
+
+
+/* A decimal object */
+typedef struct Decimal Decimal;
+struct Decimal {
+  char sign;        /* 0 for positive, 1 for negative */
+  char oom;         /* True if an OOM is encountered */
+  char isNull;      /* True if holds a NULL rather than a number */
+  char isInit;      /* True upon initialization */
+  int nDigit;       /* Total number of digits */
+  int nFrac;        /* Number of digits to the right of the decimal point */
+  signed char *a;   /* Array of digits.  Most significant first. */
+};
+
+/*
+** Release memory held by a Decimal, but do not free the object itself.
+*/
+static void decimal_clear(Decimal *p){
+  sqlite3_free(p->a);
+}
+
+/*
+** Destroy a Decimal object
+*/
+static void decimal_free(Decimal *p){
+  if( p ){
+    decimal_clear(p);
+    sqlite3_free(p);
+  }
+}
+
+/*
+** Allocate a new Decimal object.  Initialize it to the number given
+** by the input string.
+*/
+static Decimal *decimal_new(
+  sqlite3_context *pCtx,
+  sqlite3_value *pIn,
+  int nAlt,
+  const unsigned char *zAlt
+){
+  Decimal *p;
+  int n, i;
+  const unsigned char *zIn;
+  int iExp = 0;
+  p = sqlite3_malloc( sizeof(*p) );
+  if( p==0 ) goto new_no_mem;
+  p->sign = 0;
+  p->oom = 0;
+  p->isInit = 1;
+  p->isNull = 0;
+  p->nDigit = 0;
+  p->nFrac = 0;
+  if( zAlt ){
+    n = nAlt,
+    zIn = zAlt;
+  }else{
+    if( sqlite3_value_type(pIn)==SQLITE_NULL ){
+      p->a = 0;
+      p->isNull = 1;
+      return p;
+    }
+    n = sqlite3_value_bytes(pIn);
+    zIn = sqlite3_value_text(pIn);
+  }
+  p->a = sqlite3_malloc64( n+1 );
+  if( p->a==0 ) goto new_no_mem;
+  for(i=0; isspace(zIn[i]); i++){}
+  if( zIn[i]=='-' ){
+    p->sign = 1;
+    i++;
+  }else if( zIn[i]=='+' ){
+    i++;
+  }
+  while( i<n && zIn[i]=='0' ) i++;
+  while( i<n ){
+    char c = zIn[i];
+    if( c>='0' && c<='9' ){
+      p->a[p->nDigit++] = c - '0';
+    }else if( c=='.' ){
+      p->nFrac = p->nDigit + 1;
+    }else if( c=='e' || c=='E' ){
+      int j = i+1;
+      int neg = 0;
+      if( j>=n ) break;
+      if( zIn[j]=='-' ){
+        neg = 1;
+        j++;
+      }else if( zIn[j]=='+' ){
+        j++;
+      }
+      while( j<n && iExp<1000000 ){
+        if( zIn[j]>='0' && zIn[j]<='9' ){
+          iExp = iExp*10 + zIn[j] - '0';
+        }
+        j++;
+      }
+      if( neg ) iExp = -iExp;
+      break;
+    }
+    i++;
+  }
+  if( p->nFrac ){
+    p->nFrac = p->nDigit - (p->nFrac - 1);
+  }
+  if( iExp>0 ){
+    if( p->nFrac>0 ){
+      if( iExp<=p->nFrac ){
+        p->nFrac -= iExp;
+        iExp = 0;
+      }else{
+        iExp -= p->nFrac;
+        p->nFrac = 0;
+      }
+    }
+    if( iExp>0 ){   
+      p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
+      if( p->a==0 ) goto new_no_mem;
+      memset(p->a+p->nDigit, 0, iExp);
+      p->nDigit += iExp;
+    }
+  }else if( iExp<0 ){
+    int nExtra;
+    iExp = -iExp;
+    nExtra = p->nDigit - p->nFrac - 1;
+    if( nExtra ){
+      if( nExtra>=iExp ){
+        p->nFrac += iExp;
+        iExp  = 0;
+      }else{
+        iExp -= nExtra;
+        p->nFrac = p->nDigit - 1;
+      }
+    }
+    if( iExp>0 ){
+      p->a = sqlite3_realloc64(p->a, p->nDigit + iExp + 1 );
+      if( p->a==0 ) goto new_no_mem;
+      memmove(p->a+iExp, p->a, p->nDigit);
+      memset(p->a, 0, iExp);
+      p->nDigit += iExp;
+      p->nFrac += iExp;
+    }
+  }
+  return p;
+
+new_no_mem:
+  if( pCtx ) sqlite3_result_error_nomem(pCtx);
+  sqlite3_free(p);
+  return 0;
+}
+
+/*
+** Make the given Decimal the result.
+*/
+static void decimal_result(sqlite3_context *pCtx, Decimal *p){
+  char *z;
+  int i, j;
+  int n;
+  if( p==0 || p->oom ){
+    sqlite3_result_error_nomem(pCtx);
+    return;
+  }
+  if( p->isNull ){
+    sqlite3_result_null(pCtx);
+    return;
+  }
+  z = sqlite3_malloc( p->nDigit+4 );
+  if( z==0 ){
+    sqlite3_result_error_nomem(pCtx);
+    return;
+  }
+  i = 0;
+  if( p->nDigit==0 || (p->nDigit==1 && p->a[0]==0) ){
+    p->sign = 0;
+  }
+  if( p->sign ){
+    z[0] = '-';
+    i = 1;
+  }
+  n = p->nDigit - p->nFrac;
+  if( n<=0 ){
+    z[i++] = '0';
+  }
+  j = 0;
+  while( n>1 && p->a[j]==0 ){
+    j++;
+    n--;
+  }
+  while( n>0  ){
+    z[i++] = p->a[j] + '0';
+    j++;
+    n--;
+  }
+  if( p->nFrac ){
+    z[i++] = '.';
+    do{
+      z[i++] = p->a[j] + '0';
+      j++;
+    }while( j<p->nDigit );
+  }
+  z[i] = 0;
+  sqlite3_result_text(pCtx, z, i, sqlite3_free);
+}
+
+/*
+** SQL Function:   decimal(X)
+**
+** Convert input X into decimal and then back into text
+*/
+static void decimalFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *p = decimal_new(context, argv[0], 0, 0);
+  UNUSED_PARAMETER(argc);
+  decimal_result(context, p);
+  decimal_free(p);
+}
+
+/*
+** Compare to Decimal objects.  Return negative, 0, or positive if the
+** first object is less than, equal to, or greater than the second.
+**
+** Preconditions for this routine:
+**
+**    pA!=0
+**    pA->isNull==0
+**    pB!=0
+**    pB->isNull==0
+*/
+static int decimal_cmp(const Decimal *pA, const Decimal *pB){
+  int nASig, nBSig, rc, n;
+  if( pA->sign!=pB->sign ){
+    return pA->sign ? -1 : +1;
+  }
+  if( pA->sign ){
+    const Decimal *pTemp = pA;
+    pA = pB;
+    pB = pTemp;
+  }
+  nASig = pA->nDigit - pA->nFrac;
+  nBSig = pB->nDigit - pB->nFrac;
+  if( nASig!=nBSig ){
+    return nASig - nBSig;
+  }
+  n = pA->nDigit;
+  if( n>pB->nDigit ) n = pB->nDigit;
+  rc = memcmp(pA->a, pB->a, n);
+  if( rc==0 ){
+    rc = pA->nDigit - pB->nDigit;
+  }
+  return rc;
+}
+
+/*
+** SQL Function:   decimal_cmp(X, Y)
+**
+** Return negative, zero, or positive if X is less then, equal to, or
+** greater than Y.
+*/
+static void decimalCmpFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *pA = 0, *pB = 0;
+  int rc;
+
+  UNUSED_PARAMETER(argc);
+  pA = decimal_new(context, argv[0], 0, 0);
+  if( pA==0 || pA->isNull ) goto cmp_done;
+  pB = decimal_new(context, argv[1], 0, 0);
+  if( pB==0 || pB->isNull ) goto cmp_done;
+  rc = decimal_cmp(pA, pB);
+  if( rc<0 ) rc = -1;
+  else if( rc>0 ) rc = +1;
+  sqlite3_result_int(context, rc);
+cmp_done:
+  decimal_free(pA);
+  decimal_free(pB);
+}
+
+/*
+** Expand the Decimal so that it has a least nDigit digits and nFrac
+** digits to the right of the decimal point.
+*/
+static void decimal_expand(Decimal *p, int nDigit, int nFrac){
+  int nAddSig;
+  int nAddFrac;
+  if( p==0 ) return;
+  nAddFrac = nFrac - p->nFrac;
+  nAddSig = (nDigit - p->nDigit) - nAddFrac;
+  if( nAddFrac==0 && nAddSig==0 ) return;
+  p->a = sqlite3_realloc64(p->a, nDigit+1);
+  if( p->a==0 ){
+    p->oom = 1;
+    return;
+  }
+  if( nAddSig ){
+    memmove(p->a+nAddSig, p->a, p->nDigit);
+    memset(p->a, 0, nAddSig);
+    p->nDigit += nAddSig;
+  }
+  if( nAddFrac ){
+    memset(p->a+p->nDigit, 0, nAddFrac);
+    p->nDigit += nAddFrac;
+    p->nFrac += nAddFrac;
+  }
+}
+
+/*
+** Add the value pB into pA.
+**
+** Both pA and pB might become denormalized by this routine.
+*/
+static void decimal_add(Decimal *pA, Decimal *pB){
+  int nSig, nFrac, nDigit;
+  int i, rc;
+  if( pA==0 ){
+    return;
+  }
+  if( pA->oom || pB==0 || pB->oom ){
+    pA->oom = 1;
+    return;
+  }
+  if( pA->isNull || pB->isNull ){
+    pA->isNull = 1;
+    return;
+  }
+  nSig = pA->nDigit - pA->nFrac;
+  if( nSig && pA->a[0]==0 ) nSig--;
+  if( nSig<pB->nDigit-pB->nFrac ){
+    nSig = pB->nDigit - pB->nFrac;
+  }
+  nFrac = pA->nFrac;
+  if( nFrac<pB->nFrac ) nFrac = pB->nFrac;
+  nDigit = nSig + nFrac + 1;
+  decimal_expand(pA, nDigit, nFrac);
+  decimal_expand(pB, nDigit, nFrac);
+  if( pA->oom || pB->oom ){
+    pA->oom = 1;
+  }else{
+    if( pA->sign==pB->sign ){
+      int carry = 0;
+      for(i=nDigit-1; i>=0; i--){
+        int x = pA->a[i] + pB->a[i] + carry;
+        if( x>=10 ){
+          carry = 1;
+          pA->a[i] = x - 10;
+        }else{
+          carry = 0;
+          pA->a[i] = x;
+        }
+      }
+    }else{
+      signed char *aA, *aB;
+      int borrow = 0;
+      rc = memcmp(pA->a, pB->a, nDigit);
+      if( rc<0 ){
+        aA = pB->a;
+        aB = pA->a;
+        pA->sign = !pA->sign;
+      }else{
+        aA = pA->a;
+        aB = pB->a;
+      }
+      for(i=nDigit-1; i>=0; i--){
+        int x = aA[i] - aB[i] - borrow;
+        if( x<0 ){
+          pA->a[i] = x+10;
+          borrow = 1;
+        }else{
+          pA->a[i] = x;
+          borrow = 0;
+        }
+      }
+    }
+  }
+}
+
+/*
+** Compare text in decimal order.
+*/
+static int decimalCollFunc(
+  void *notUsed,
+  int nKey1, const void *pKey1,
+  int nKey2, const void *pKey2
+){
+  const unsigned char *zA = (const unsigned char*)pKey1;
+  const unsigned char *zB = (const unsigned char*)pKey2;
+  Decimal *pA = decimal_new(0, 0, nKey1, zA);
+  Decimal *pB = decimal_new(0, 0, nKey2, zB);
+  int rc;
+  UNUSED_PARAMETER(notUsed);
+  if( pA==0 || pB==0 ){
+    rc = 0;
+  }else{
+    rc = decimal_cmp(pA, pB);
+  }
+  decimal_free(pA);
+  decimal_free(pB);
+  return rc;
+}
+
+
+/*
+** SQL Function:   decimal_add(X, Y)
+**                 decimal_sub(X, Y)
+**
+** Return the sum or difference of X and Y.
+*/
+static void decimalAddFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *pA = decimal_new(context, argv[0], 0, 0);
+  Decimal *pB = decimal_new(context, argv[1], 0, 0);
+  UNUSED_PARAMETER(argc);
+  decimal_add(pA, pB);
+  decimal_result(context, pA);
+  decimal_free(pA);
+  decimal_free(pB);
+}
+static void decimalSubFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *pA = decimal_new(context, argv[0], 0, 0);
+  Decimal *pB = decimal_new(context, argv[1], 0, 0);
+  UNUSED_PARAMETER(argc);
+  if( pB==0 ) return;
+  pB->sign = !pB->sign;
+  decimal_add(pA, pB);
+  decimal_result(context, pA);
+  decimal_free(pA);
+  decimal_free(pB);
+}
+
+/* Aggregate funcion:   decimal_sum(X)
+**
+** Works like sum() except that it uses decimal arithmetic for unlimited
+** precision.
+*/
+static void decimalSumStep(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *p;
+  Decimal *pArg;
+  UNUSED_PARAMETER(argc);
+  p = sqlite3_aggregate_context(context, sizeof(*p));
+  if( p==0 ) return;
+  if( !p->isInit ){
+    p->isInit = 1;
+    p->a = sqlite3_malloc(2);
+    if( p->a==0 ){
+      p->oom = 1;
+    }else{
+      p->a[0] = 0;
+    }
+    p->nDigit = 1;
+    p->nFrac = 0;
+  }
+  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+  pArg = decimal_new(context, argv[0], 0, 0);
+  decimal_add(p, pArg);
+  decimal_free(pArg);
+}
+static void decimalSumInverse(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *p;
+  Decimal *pArg;
+  UNUSED_PARAMETER(argc);
+  p = sqlite3_aggregate_context(context, sizeof(*p));
+  if( p==0 ) return;
+  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
+  pArg = decimal_new(context, argv[0], 0, 0);
+  if( pArg ) pArg->sign = !pArg->sign;
+  decimal_add(p, pArg);
+  decimal_free(pArg);
+}
+static void decimalSumValue(sqlite3_context *context){
+  Decimal *p = sqlite3_aggregate_context(context, 0);
+  if( p==0 ) return;
+  decimal_result(context, p);
+}
+static void decimalSumFinalize(sqlite3_context *context){
+  Decimal *p = sqlite3_aggregate_context(context, 0);
+  if( p==0 ) return;
+  decimal_result(context, p);
+  decimal_clear(p);
+}
+
+/*
+** SQL Function:   decimal_mul(X, Y)
+**
+** Return the product of X and Y.
+**
+** All significant digits after the decimal point are retained.
+** Trailing zeros after the decimal point are omitted as long as
+** the number of digits after the decimal point is no less than
+** either the number of digits in either input.
+*/
+static void decimalMulFunc(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  Decimal *pA = decimal_new(context, argv[0], 0, 0);
+  Decimal *pB = decimal_new(context, argv[1], 0, 0);
+  signed char *acc = 0;
+  int i, j, k;
+  int minFrac;
+  UNUSED_PARAMETER(argc);
+  if( pA==0 || pA->oom || pA->isNull
+   || pB==0 || pB->oom || pB->isNull 
+  ){
+    goto mul_end;
+  }
+  acc = sqlite3_malloc64( pA->nDigit + pB->nDigit + 2 );
+  if( acc==0 ){
+    sqlite3_result_error_nomem(context);
+    goto mul_end;
+  }
+  memset(acc, 0, pA->nDigit + pB->nDigit + 2);
+  minFrac = pA->nFrac;
+  if( pB->nFrac<minFrac ) minFrac = pB->nFrac;
+  for(i=pA->nDigit-1; i>=0; i--){
+    signed char f = pA->a[i];
+    int carry = 0, x;
+    for(j=pB->nDigit-1, k=i+j+3; j>=0; j--, k--){
+      x = acc[k] + f*pB->a[j] + carry;
+      acc[k] = x%10;
+      carry = x/10;
+    }
+    x = acc[k] + carry;
+    acc[k] = x%10;
+    acc[k-1] += x/10;
+  }
+  sqlite3_free(pA->a);
+  pA->a = acc;
+  acc = 0;
+  pA->nDigit += pB->nDigit + 2;
+  pA->nFrac += pB->nFrac;
+  pA->sign ^= pB->sign;
+  while( pA->nFrac>minFrac && pA->a[pA->nDigit-1]==0 ){
+    pA->nFrac--;
+    pA->nDigit--;
+  }
+  decimal_result(context, pA);
+
+mul_end:
+  sqlite3_free(acc);
+  decimal_free(pA);
+  decimal_free(pB);
+}
+
+#ifdef _WIN32
+
+#endif
+int sqlite3_decimal_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
+  int rc = SQLITE_OK;
+  static const struct {
+    const char *zFuncName;
+    int nArg;
+    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+  } aFunc[] = {
+    { "decimal",       1,   decimalFunc        },
+    { "decimal_cmp",   2,   decimalCmpFunc     },
+    { "decimal_add",   2,   decimalAddFunc     },
+    { "decimal_sub",   2,   decimalSubFunc     },
+    { "decimal_mul",   2,   decimalMulFunc     },
+  };
+  unsigned int i;
+  (void)pzErrMsg;  /* Unused parameter */
+
+  SQLITE_EXTENSION_INIT2(pApi);
+
+  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
+    rc = sqlite3_create_function(db, aFunc[i].zFuncName, aFunc[i].nArg,
+                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC,
+                   0, aFunc[i].xFunc, 0, 0);
+  }
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_window_function(db, "decimal_sum", 1,
+                   SQLITE_UTF8|SQLITE_INNOCUOUS|SQLITE_DETERMINISTIC, 0,
+                   decimalSumStep, decimalSumFinalize,
+                   decimalSumValue, decimalSumInverse, 0);
+  }
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_collation(db, "decimal", SQLITE_UTF8,
+                                  0, decimalCollFunc);
+  }
+  return rc;
+}
+
+/************************* End ../ext/misc/decimal.c ********************/
+/************************* Begin ../ext/misc/ieee754.c ******************/
+/*
+** 2013-04-17
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+******************************************************************************
+**
+** This SQLite extension implements functions for the exact display
+** and input of IEEE754 Binary64 floating-point numbers.
+**
+**   ieee754(X)
+**   ieee754(Y,Z)
+**
+** In the first form, the value X should be a floating-point number.
+** The function will return a string of the form 'ieee754(Y,Z)' where
+** Y and Z are integers such that X==Y*pow(2,Z).
+**
+** In the second form, Y and Z are integers which are the mantissa and
+** base-2 exponent of a new floating point number.  The function returns
+** a floating-point value equal to Y*pow(2,Z).
+**
+** Examples:
+**
+**     ieee754(2.0)             ->     'ieee754(2,0)'
+**     ieee754(45.25)           ->     'ieee754(181,-2)'
+**     ieee754(2, 0)            ->     2.0
+**     ieee754(181, -2)         ->     45.25
+**
+** Two additional functions break apart the one-argument ieee754()
+** result into separate integer values:
+**
+**     ieee754_mantissa(45.25)  ->     181
+**     ieee754_exponent(45.25)  ->     -2
+**
+** These functions convert binary64 numbers into blobs and back again.
+**
+**     ieee754_from_blob(x'3ff0000000000000')  ->  1.0
+**     ieee754_to_blob(1.0)                    ->  x'3ff0000000000000'
+**
+** In all single-argument functions, if the argument is an 8-byte blob
+** then that blob is interpreted as a big-endian binary64 value.
+**
+**
+** EXACT DECIMAL REPRESENTATION OF BINARY64 VALUES
+** -----------------------------------------------
+**
+** This extension in combination with the separate 'decimal' extension
+** can be used to compute the exact decimal representation of binary64
+** values.  To begin, first compute a table of exponent values:
+**
+**    CREATE TABLE pow2(x INTEGER PRIMARY KEY, v TEXT);
+**    WITH RECURSIVE c(x,v) AS (
+**      VALUES(0,'1')
+**      UNION ALL
+**      SELECT x+1, decimal_mul(v,'2') FROM c WHERE x+1<=971
+**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
+**    WITH RECURSIVE c(x,v) AS (
+**      VALUES(-1,'0.5')
+**      UNION ALL
+**      SELECT x-1, decimal_mul(v,'0.5') FROM c WHERE x-1>=-1075
+**    ) INSERT INTO pow2(x,v) SELECT x, v FROM c;
+**
+** Then, to compute the exact decimal representation of a floating
+** point value (the value 47.49 is used in the example) do:
+**
+**    WITH c(n) AS (VALUES(47.49))
+**          ---------------^^^^^---- Replace with whatever you want
+**    SELECT decimal_mul(ieee754_mantissa(c.n),pow2.v)
+**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.n);
+**
+** Here is a query to show various boundry values for the binary64
+** number format:
+**
+**    WITH c(name,bin) AS (VALUES
+**       ('minimum positive value',        x'0000000000000001'),
+**       ('maximum subnormal value',       x'000fffffffffffff'),
+**       ('mininum positive nornal value', x'0010000000000000'),
+**       ('maximum value',                 x'7fefffffffffffff'))
+**    SELECT c.name, decimal_mul(ieee754_mantissa(c.bin),pow2.v)
+**      FROM pow2, c WHERE pow2.x=ieee754_exponent(c.bin);
+**
+*/
+/* #include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+
+/* Mark a function parameter as unused, to suppress nuisance compiler
+** warnings. */
+#ifndef UNUSED_PARAMETER
+# define UNUSED_PARAMETER(X)  (void)(X)
+#endif
+
+/*
+** Implementation of the ieee754() function
+*/
+static void ieee754func(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  if( argc==1 ){
+    sqlite3_int64 m, a;
+    double r;
+    int e;
+    int isNeg;
+    char zResult[100];
+    assert( sizeof(m)==sizeof(r) );
+    if( sqlite3_value_type(argv[0])==SQLITE_BLOB
+     && sqlite3_value_bytes(argv[0])==sizeof(r)
+    ){
+      const unsigned char *x = sqlite3_value_blob(argv[0]);
+      unsigned int i;
+      sqlite3_uint64 v = 0;
+      for(i=0; i<sizeof(r); i++){
+        v = (v<<8) | x[i];
+      }
+      memcpy(&r, &v, sizeof(r));
+    }else{
+      r = sqlite3_value_double(argv[0]);
+    }
+    if( r<0.0 ){
+      isNeg = 1;
+      r = -r;
+    }else{
+      isNeg = 0;
+    }
+    memcpy(&a,&r,sizeof(a));
+    if( a==0 ){
+      e = 0;
+      m = 0;
+    }else{
+      e = a>>52;
+      m = a & ((((sqlite3_int64)1)<<52)-1);
+      if( e==0 ){
+        m <<= 1;
+      }else{
+        m |= ((sqlite3_int64)1)<<52;
+      }
+      while( e<1075 && m>0 && (m&1)==0 ){
+        m >>= 1;
+        e++;
+      }
+      if( isNeg ) m = -m;
+    }
+    switch( *(int*)sqlite3_user_data(context) ){
+      case 0:
+        sqlite3_snprintf(sizeof(zResult), zResult, "ieee754(%lld,%d)",
+                         m, e-1075);
+        sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT);
+        break;
+      case 1:
+        sqlite3_result_int64(context, m);
+        break;
+      case 2:
+        sqlite3_result_int(context, e-1075);
+        break;
+    }
+  }else{
+    sqlite3_int64 m, e, a;
+    double r;
+    int isNeg = 0;
+    m = sqlite3_value_int64(argv[0]);
+    e = sqlite3_value_int64(argv[1]);
+    if( m<0 ){
+      isNeg = 1;
+      m = -m;
+      if( m<0 ) return;
+    }else if( m==0 && e>-1000 && e<1000 ){
+      sqlite3_result_double(context, 0.0);
+      return;
+    }
+    while( (m>>32)&0xffe00000 ){
+      m >>= 1;
+      e++;
+    }
+    while( m!=0 && ((m>>32)&0xfff00000)==0 ){
+      m <<= 1;
+      e--;
+    }
+    e += 1075;
+    if( e<=0 ){
+      /* Subnormal */
+      m >>= 1-e;
+      e = 0;
+    }else if( e>0x7ff ){
+      e = 0x7ff;
+    }
+    a = m & ((((sqlite3_int64)1)<<52)-1);
+    a |= e<<52;
+    if( isNeg ) a |= ((sqlite3_uint64)1)<<63;
+    memcpy(&r, &a, sizeof(r));
+    sqlite3_result_double(context, r);
+  }
+}
+
+/*
+** Functions to convert between blobs and floats.
+*/
+static void ieee754func_from_blob(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  UNUSED_PARAMETER(argc);
+  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
+   && sqlite3_value_bytes(argv[0])==sizeof(double)
+  ){
+    double r;
+    const unsigned char *x = sqlite3_value_blob(argv[0]);
+    unsigned int i;
+    sqlite3_uint64 v = 0;
+    for(i=0; i<sizeof(r); i++){
+      v = (v<<8) | x[i];
+    }
+    memcpy(&r, &v, sizeof(r));
+    sqlite3_result_double(context, r);
+  }
+}
+static void ieee754func_to_blob(
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv
+){
+  UNUSED_PARAMETER(argc);
+  if( sqlite3_value_type(argv[0])==SQLITE_FLOAT
+   || sqlite3_value_type(argv[0])==SQLITE_INTEGER
+  ){
+    double r = sqlite3_value_double(argv[0]);
+    sqlite3_uint64 v;
+    unsigned char a[sizeof(r)];
+    unsigned int i;
+    memcpy(&v, &r, sizeof(r));
+    for(i=1; i<=sizeof(r); i++){
+      a[sizeof(r)-i] = v&0xff;
+      v >>= 8;
+    }
+    sqlite3_result_blob(context, a, sizeof(r), SQLITE_TRANSIENT);
+  }
+}
+
+
+#ifdef _WIN32
+
+#endif
+int sqlite3_ieee_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
+  static const struct {
+    char *zFName;
+    int nArg;
+    int iAux;
+    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
+  } aFunc[] = {
+    { "ieee754",           1,   0, ieee754func },
+    { "ieee754",           2,   0, ieee754func },
+    { "ieee754_mantissa",  1,   1, ieee754func },
+    { "ieee754_exponent",  1,   2, ieee754func },
+    { "ieee754_to_blob",   1,   0, ieee754func_to_blob },
+    { "ieee754_from_blob", 1,   0, ieee754func_from_blob },
+
+  };
+  unsigned int i;
+  int rc = SQLITE_OK;
+  SQLITE_EXTENSION_INIT2(pApi);
+  (void)pzErrMsg;  /* Unused parameter */
+  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
+    rc = sqlite3_create_function(db, aFunc[i].zFName, aFunc[i].nArg,   
+                               SQLITE_UTF8|SQLITE_INNOCUOUS,
+                               (void*)&aFunc[i].iAux,
+                               aFunc[i].xFunc, 0, 0);
+  }
+  return rc;
+}
+
+/************************* End ../ext/misc/ieee754.c ********************/
+/************************* Begin ../ext/misc/series.c ******************/
+/*
+** 2015-08-18
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file demonstrates how to create a table-valued-function using
+** a virtual table.  This demo implements the generate_series() function
+** which gives similar results to the eponymous function in PostgreSQL.
+** Examples:
+**
+**      SELECT * FROM generate_series(0,100,5);
+**
+** The query above returns integers from 0 through 100 counting by steps
+** of 5.
+**
+**      SELECT * FROM generate_series(0,100);
+**
+** Integers from 0 through 100 with a step size of 1.
+**
+**      SELECT * FROM generate_series(20) LIMIT 10;
+**
+** Integers 20 through 29.
+**
+** HOW IT WORKS
+**
+** The generate_series "function" is really a virtual table with the
+** following schema:
+**
+**     CREATE TABLE generate_series(
+**       value,
+**       start HIDDEN,
+**       stop HIDDEN,
+**       step HIDDEN
+**     );
+**
+** Function arguments in queries against this virtual table are translated
+** into equality constraints against successive hidden columns.  In other
+** words, the following pairs of queries are equivalent to each other:
+**
+**    SELECT * FROM generate_series(0,100,5);
+**    SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
+**
+**    SELECT * FROM generate_series(0,100);
+**    SELECT * FROM generate_series WHERE start=0 AND stop=100;
+**
+**    SELECT * FROM generate_series(20) LIMIT 10;
+**    SELECT * FROM generate_series WHERE start=20 LIMIT 10;
+**
+** The generate_series virtual table implementation leaves the xCreate method
+** set to NULL.  This means that it is not possible to do a CREATE VIRTUAL
+** TABLE command with "generate_series" as the USING argument.  Instead, there
+** is a single generate_series virtual table that is always available without
+** having to be created first.
+**
+** The xBestIndex method looks for equality constraints against the hidden
+** start, stop, and step columns, and if present, it uses those constraints
+** to bound the sequence of generated values.  If the equality constraints
+** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
+** xBestIndex returns a small cost when both start and stop are available,
+** and a very large cost if either start or stop are unavailable.  This
+** encourages the query planner to order joins such that the bounds of the
+** series are well-defined.
+*/
+/* #include "sqlite3ext.h" */
+SQLITE_EXTENSION_INIT1
+#include <assert.h>
+#include <string.h>
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+
+
+/* series_cursor is a subclass of sqlite3_vtab_cursor which will
+** serve as the underlying representation of a cursor that scans
+** over rows of the result
+*/
+typedef struct series_cursor series_cursor;
+struct series_cursor {
+  sqlite3_vtab_cursor base;  /* Base class - must be first */
+  int isDesc;                /* True to count down rather than up */
+  sqlite3_int64 iRowid;      /* The rowid */
+  sqlite3_int64 iValue;      /* Current value ("value") */
+  sqlite3_int64 mnValue;     /* Mimimum value ("start") */
+  sqlite3_int64 mxValue;     /* Maximum value ("stop") */
+  sqlite3_int64 iStep;       /* Increment ("step") */
+};
+
+/*
+** The seriesConnect() method is invoked to create a new
+** series_vtab that describes the generate_series virtual table.
+**
+** Think of this routine as the constructor for series_vtab objects.
+**
+** All this routine needs to do is:
+**
+**    (1) Allocate the series_vtab object and initialize all fields.
+**
+**    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
+**        result set of queries against generate_series will look like.
+*/
+static int seriesConnect(
+  sqlite3 *db,
+  void *pUnused,
+  int argcUnused, const char *const*argvUnused,
+  sqlite3_vtab **ppVtab,
+  char **pzErrUnused
+){
+  sqlite3_vtab *pNew;
+  int rc;
+
+/* Column numbers */
+#define SERIES_COLUMN_VALUE 0
+#define SERIES_COLUMN_START 1
+#define SERIES_COLUMN_STOP  2
+#define SERIES_COLUMN_STEP  3
+
+  (void)pUnused;
+  (void)argcUnused;
+  (void)argvUnused;
+  (void)pzErrUnused;
+  rc = sqlite3_declare_vtab(db,
+     "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
+  if( rc==SQLITE_OK ){
+    pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
+    if( pNew==0 ) return SQLITE_NOMEM;
+    memset(pNew, 0, sizeof(*pNew));
+    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
+  }
+  return rc;
+}
+
+/*
+** This method is the destructor for series_cursor objects.
+*/
+static int seriesDisconnect(sqlite3_vtab *pVtab){
+  sqlite3_free(pVtab);
+  return SQLITE_OK;
+}
+
+/*
+** Constructor for a new series_cursor object.
+*/
+static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
+  series_cursor *pCur;
+  (void)pUnused;
+  pCur = sqlite3_malloc( sizeof(*pCur) );
+  if( pCur==0 ) return SQLITE_NOMEM;
+  memset(pCur, 0, sizeof(*pCur));
+  *ppCursor = &pCur->base;
+  return SQLITE_OK;
+}
+
+/*
+** Destructor for a series_cursor.
+*/
+static int seriesClose(sqlite3_vtab_cursor *cur){
+  sqlite3_free(cur);
+  return SQLITE_OK;
+}
+
+
+/*
+** Advance a series_cursor to its next row of output.
+*/
+static int seriesNext(sqlite3_vtab_cursor *cur){
+  series_cursor *pCur = (series_cursor*)cur;
+  if( pCur->isDesc ){
+    pCur->iValue -= pCur->iStep;
+  }else{
+    pCur->iValue += pCur->iStep;
+  }
+  pCur->iRowid++;
+  return SQLITE_OK;
+}
+
+/*
+** Return values of columns for the row at which the series_cursor
+** is currently pointing.
+*/
+static int seriesColumn(
+  sqlite3_vtab_cursor *cur,   /* The cursor */
+  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
+  int i                       /* Which column to return */
+){
+  series_cursor *pCur = (series_cursor*)cur;
+  sqlite3_int64 x = 0;
+  switch( i ){
+    case SERIES_COLUMN_START:  x = pCur->mnValue; break;
+    case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
+    case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
+    default:                   x = pCur->iValue;  break;
+  }
+  sqlite3_result_int64(ctx, x);
+  return SQLITE_OK;
+}
+
+/*
+** Return the rowid for the current row. In this implementation, the
+** first row returned is assigned rowid value 1, and each subsequent
+** row a value 1 more than that of the previous.
+*/
+static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+  series_cursor *pCur = (series_cursor*)cur;
+  *pRowid = pCur->iRowid;
+  return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the cursor has been moved off of the last
+** row of output.
+*/
+static int seriesEof(sqlite3_vtab_cursor *cur){
+  series_cursor *pCur = (series_cursor*)cur;
+  if( pCur->isDesc ){
+    return pCur->iValue < pCur->mnValue;
+  }else{
+    return pCur->iValue > pCur->mxValue;
+  }
+}
+
+/* True to cause run-time checking of the start=, stop=, and/or step= 
+** parameters.  The only reason to do this is for testing the
+** constraint checking logic for virtual tables in the SQLite core.
+*/
+#ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
+# define SQLITE_SERIES_CONSTRAINT_VERIFY 0
+#endif
+
+/*
+** This method is called to "rewind" the series_cursor object back
+** to the first row of output.  This method is always called at least
+** once prior to any call to seriesColumn() or seriesRowid() or 
+** seriesEof().
+**
+** The query plan selected by seriesBestIndex is passed in the idxNum
+** parameter.  (idxStr is not used in this implementation.)  idxNum
+** is a bitmask showing which constraints are available:
+**
+**    1:    start=VALUE
+**    2:    stop=VALUE
+**    4:    step=VALUE
+**
+** Also, if bit 8 is set, that means that the series should be output
+** in descending order rather than in ascending order.
+**
+** This routine should initialize the cursor and position it so that it
+** is pointing at the first row, or pointing off the end of the table
+** (so that seriesEof() will return true) if the table is empty.
+*/
+static int seriesFilter(
+  sqlite3_vtab_cursor *pVtabCursor, 
+  int idxNum, const char *idxStrUnused,
+  int argc, sqlite3_value **argv
+){
+  series_cursor *pCur = (series_cursor *)pVtabCursor;
+  int i = 0;
+  (void)idxStrUnused;
+  if( idxNum & 1 ){
+    pCur->mnValue = sqlite3_value_int64(argv[i++]);
+  }else{
+    pCur->mnValue = 0;
+  }
+  if( idxNum & 2 ){
+    pCur->mxValue = sqlite3_value_int64(argv[i++]);
+  }else{
+    pCur->mxValue = 0xffffffff;
+  }
+  if( idxNum & 4 ){
+    pCur->iStep = sqlite3_value_int64(argv[i++]);
+    if( pCur->iStep<1 ) pCur->iStep = 1;
+  }else{
+    pCur->iStep = 1;
+  }
+  for(i=0; i<argc; i++){
+    if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
+      /* If any of the constraints have a NULL value, then return no rows.
+      ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
+      pCur->mnValue = 1;
+      pCur->mxValue = 0;
+      break;
+    }
+  }
+  if( idxNum & 8 ){
+    pCur->isDesc = 1;
+    pCur->iValue = pCur->mxValue;
+    if( pCur->iStep>0 ){
+      pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
+    }
+  }else{
+    pCur->isDesc = 0;
+    pCur->iValue = pCur->mnValue;
+  }
+  pCur->iRowid = 1;
+  return SQLITE_OK;
+}
+
+/*
+** SQLite will invoke this method one or more times while planning a query
+** that uses the generate_series virtual table.  This routine needs to create
+** a query plan for each invocation and compute an estimated cost for that
+** plan.
+**
+** In this implementation idxNum is used to represent the
+** query plan.  idxStr is unused.
+**
+** The query plan is represented by bits in idxNum:
+**
+**  (1)  start = $value  -- constraint exists
+**  (2)  stop = $value   -- constraint exists
+**  (4)  step = $value   -- constraint exists
+**  (8)  output in descending order
+*/
+static int seriesBestIndex(
+  sqlite3_vtab *tabUnused,
+  sqlite3_index_info *pIdxInfo
+){
+  int i, j;              /* Loop over constraints */
+  int idxNum = 0;        /* The query plan bitmask */
+  int unusableMask = 0;  /* Mask of unusable constraints */
+  int nArg = 0;          /* Number of arguments that seriesFilter() expects */
+  int aIdx[3];           /* Constraints on start, stop, and step */
+  const struct sqlite3_index_constraint *pConstraint;
+
+  /* This implementation assumes that the start, stop, and step columns
+  ** are the last three columns in the virtual table. */
+  assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
+  assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
+  (void)tabUnused;
+  aIdx[0] = aIdx[1] = aIdx[2] = -1;
+  pConstraint = pIdxInfo->aConstraint;
+  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
+    int iCol;    /* 0 for start, 1 for stop, 2 for step */
+    int iMask;   /* bitmask for those column */
+    if( pConstraint->iColumn<SERIES_COLUMN_START ) continue;
+    iCol = pConstraint->iColumn - SERIES_COLUMN_START;
+    assert( iCol>=0 && iCol<=2 );
+    iMask = 1 << iCol;
+    if( pConstraint->usable==0 ){
+      unusableMask |=  iMask;
+      continue;
+    }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
+      idxNum |= iMask;
+      aIdx[iCol] = i;
+    }
+  }
+  for(i=0; i<3; i++){
+    if( (j = aIdx[i])>=0 ){
+      pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
+      pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
+    }
   }
-  if( memtraceOut ){
-    fprintf(memtraceOut, "MEMTRACE: resize %d -> %d bytes\n",
-            memtraceBase.xSize(p), memtraceBase.xRoundup(n));
+  if( (unusableMask & ~idxNum)!=0 ){
+    /* The start, stop, and step columns are inputs.  Therefore if there
+    ** are unusable constraints on any of start, stop, or step then
+    ** this plan is unusable */
+    return SQLITE_CONSTRAINT;
   }
-  return memtraceBase.xRealloc(p, n);
-}
-static int memtraceSize(void *p){
-  return memtraceBase.xSize(p);
-}
-static int memtraceRoundup(int n){
-  return memtraceBase.xRoundup(n);
-}
-static int memtraceInit(void *p){
-  return memtraceBase.xInit(p);
-}
-static void memtraceShutdown(void *p){
-  memtraceBase.xShutdown(p);
+  if( (idxNum & 3)==3 ){
+    /* Both start= and stop= boundaries are available.  This is the 
+    ** the preferred case */
+    pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
+    pIdxInfo->estimatedRows = 1000;
+    if( pIdxInfo->nOrderBy==1 ){
+      if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
+      pIdxInfo->orderByConsumed = 1;
+    }
+  }else{
+    /* If either boundary is missing, we have to generate a huge span
+    ** of numbers.  Make this case very expensive so that the query
+    ** planner will work hard to avoid it. */
+    pIdxInfo->estimatedRows = 2147483647;
+  }
+  pIdxInfo->idxNum = idxNum;
+  return SQLITE_OK;
 }
 
-/* The substitute memory allocator */
-static sqlite3_mem_methods ersaztMethods = {
-  memtraceMalloc,
-  memtraceFree,
-  memtraceRealloc,
-  memtraceSize,
-  memtraceRoundup,
-  memtraceInit,
-  memtraceShutdown,
-  0
+/*
+** This following structure defines all the methods for the 
+** generate_series virtual table.
+*/
+static const sqlite3_module seriesModule = {
+  0,                         /* iVersion */
+  0,                         /* xCreate */
+  seriesConnect,             /* xConnect */
+  seriesBestIndex,           /* xBestIndex */
+  seriesDisconnect,          /* xDisconnect */
+  0,                         /* xDestroy */
+  seriesOpen,                /* xOpen - open a cursor */
+  seriesClose,               /* xClose - close a cursor */
+  seriesFilter,              /* xFilter - configure scan constraints */
+  seriesNext,                /* xNext - advance a cursor */
+  seriesEof,                 /* xEof - check for end of scan */
+  seriesColumn,              /* xColumn - read data */
+  seriesRowid,               /* xRowid - read data */
+  0,                         /* xUpdate */
+  0,                         /* xBegin */
+  0,                         /* xSync */
+  0,                         /* xCommit */
+  0,                         /* xRollback */
+  0,                         /* xFindMethod */
+  0,                         /* xRename */
+  0,                         /* xSavepoint */
+  0,                         /* xRelease */
+  0,                         /* xRollbackTo */
+  0                          /* xShadowName */
 };
 
-/* Begin tracing memory allocations to out. */
-int sqlite3MemTraceActivate(FILE *out){
-  int rc = SQLITE_OK;
-  if( memtraceBase.xMalloc==0 ){
-    rc = sqlite3_config(SQLITE_CONFIG_GETMALLOC, &memtraceBase);
-    if( rc==SQLITE_OK ){
-      rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &ersaztMethods);
-    }
-  }
-  memtraceOut = out;
-  return rc;
-}
+#endif /* SQLITE_OMIT_VIRTUALTABLE */
 
-/* Deactivate memory tracing */
-int sqlite3MemTraceDeactivate(void){
+#ifdef _WIN32
+
+#endif
+int sqlite3_series_init(
+  sqlite3 *db, 
+  char **pzErrMsg, 
+  const sqlite3_api_routines *pApi
+){
   int rc = SQLITE_OK;
-  if( memtraceBase.xMalloc!=0 ){
-    rc = sqlite3_config(SQLITE_CONFIG_MALLOC, &memtraceBase);
-    if( rc==SQLITE_OK ){
-      memset(&memtraceBase, 0, sizeof(memtraceBase));
-    }
+  SQLITE_EXTENSION_INIT2(pApi);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  if( sqlite3_libversion_number()<3008012 ){
+    *pzErrMsg = sqlite3_mprintf(
+        "generate_series() requires SQLite 3.8.12 or later");
+    return SQLITE_ERROR;
   }
-  memtraceOut = 0;
+  rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
+#endif
   return rc;
 }
 
-/************************* End ../ext/misc/memtrace.c ********************/
+/************************* End ../ext/misc/series.c ********************/
 #ifdef SQLITE_HAVE_ZLIB
 /************************* Begin ../ext/misc/zipfile.c ******************/
 /*
@@ -4561,6 +6101,7 @@ static int zipfileConnect(
       zipfileDequote(pNew->zFile);
     }
   }
+  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
   *ppVtab = (sqlite3_vtab*)pNew;
   return rc;
 }
@@ -4714,14 +6255,16 @@ static int zipfileAppendData(
   const u8 *aWrite,
   int nWrite
 ){
-  size_t n;
-  fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
-  n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
-  if( (int)n!=nWrite ){
-    pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
-    return SQLITE_ERROR;
+  if( nWrite>0 ){
+    size_t n = nWrite;
+    fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET);
+    n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd);
+    if( (int)n!=nWrite ){
+      pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()");
+      return SQLITE_ERROR;
+    }
+    pTab->szCurrent += nWrite;
   }
-  pTab->szCurrent += nWrite;
   return SQLITE_OK;
 }
 
@@ -5173,25 +6716,25 @@ static int zipfileDeflate(
   u8 **ppOut, size_t *pnOut,         /* Output */
   char **pzErr                    /* OUT: Error message */
 ){
-  size_t nAlloc = compressBound(nIn);
-  u8 *aOut;
   int rc = SQLITE_OK;
+  size_t nAlloc;
+  z_stream str;
+  u8 *aOut;
 
+  memset(&str, 0, sizeof(str));
+  str.next_in = (Bytef*)aIn;
+  str.avail_in = nIn;
+  deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
+
+  nAlloc = deflateBound(&str, nIn);
   aOut = (u8*)sqlite3_malloc(nAlloc);
   if( aOut==0 ){
     rc = SQLITE_NOMEM;
   }else{
     int res;
-    z_stream str;
-    memset(&str, 0, sizeof(str));
-    str.next_in = (Bytef*)aIn;
-    str.avail_in = nIn;
     str.next_out = aOut;
     str.avail_out = nAlloc;
-
-    deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
     res = deflate(&str, Z_FINISH);
-
     if( res==Z_STREAM_END ){
       *ppOut = aOut;
       *pnOut = str.total_out;
@@ -5500,10 +7043,10 @@ static int zipfileBestIndex(
       idx = i;
     }
   }
+  pIdxInfo->estimatedCost = 1000.0;
   if( idx>=0 ){
     pIdxInfo->aConstraintUsage[idx].argvIndex = 1;
     pIdxInfo->aConstraintUsage[idx].omit = 1;
-    pIdxInfo->estimatedCost = 1000.0;
     pIdxInfo->idxNum = 1;
   }else if( unusable ){
     return SQLITE_CONSTRAINT;
@@ -5625,8 +7168,8 @@ static int zipfileGetMode(
 ** identical, ignoring any trailing '/' character in either path.  */
 static int zipfileComparePath(const char *zA, const char *zB, int nB){
   int nA = (int)strlen(zA);
-  if( zA[nA-1]=='/' ) nA--;
-  if( zB[nB-1]=='/' ) nB--;
+  if( nA>0 && zA[nA-1]=='/' ) nA--;
+  if( nB>0 && zB[nB-1]=='/' ) nB--;
   if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0;
   return 1;
 }
@@ -5636,6 +7179,10 @@ static int zipfileBegin(sqlite3_vtab *pVtab){
   int rc = SQLITE_OK;
 
   assert( pTab->pWriteFd==0 );
+  if( pTab->zFile==0 || pTab->zFile[0]==0 ){
+    pTab->base.zErrMsg = sqlite3_mprintf("zipfile: missing filename");
+    return SQLITE_ERROR;
+  }
 
   /* Open a write fd on the file. Also load the entire central directory
   ** structure into memory. During the transaction any new file data is 
@@ -5810,6 +7357,7 @@ static int zipfileUpdate(
 
     if( rc==SQLITE_OK ){
       zPath = (const char*)sqlite3_value_text(apVal[2]);
+      if( zPath==0 ) zPath = "";
       nPath = (int)strlen(zPath);
       mTime = zipfileGetTime(apVal[4]);
     }
@@ -5819,11 +7367,15 @@ static int zipfileUpdate(
       ** '/'. This appears to be required for compatibility with info-zip
       ** (the unzip command on unix). It does not create directories
       ** otherwise.  */
-      if( zPath[nPath-1]!='/' ){
+      if( nPath<=0 || zPath[nPath-1]!='/' ){
         zFree = sqlite3_mprintf("%s/", zPath);
-        if( zFree==0 ){ rc = SQLITE_NOMEM; }
         zPath = (const char*)zFree;
-        nPath++;
+        if( zFree==0 ){
+          rc = SQLITE_NOMEM;
+          nPath = 0;
+        }else{
+          nPath = (int)strlen(zPath);
+        }
       }
     }
 
@@ -6216,19 +7768,19 @@ void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){
   ** at the end of the path. Or, if this is not a directory and the path
   ** ends in '/' it is an error. */
   if( bIsDir==0 ){
-    if( zName[nName-1]=='/' ){
+    if( nName>0 && zName[nName-1]=='/' ){
       zErr = sqlite3_mprintf("non-directory name must not end with /");
       rc = SQLITE_ERROR;
       goto zipfile_step_out;
     }
   }else{
-    if( zName[nName-1]!='/' ){
+    if( nName==0 || zName[nName-1]!='/' ){
       zName = zFree = sqlite3_mprintf("%s/", zName);
-      nName++;
       if( zName==0 ){
         rc = SQLITE_NOMEM;
         goto zipfile_step_out;
       }
+      nName = (int)strlen(zName);
     }else{
       while( nName>1 && zName[nName-2]=='/' ) nName--;
     }
@@ -6390,6 +7942,7 @@ int sqlite3_zipfile_init(
 /* #include "sqlite3ext.h" */
 SQLITE_EXTENSION_INIT1
 #include <zlib.h>
+#include <assert.h>
 
 /*
 ** Implementation of the "sqlar_compress(X)" SQL function.
@@ -6484,10 +8037,12 @@ int sqlite3_sqlar_init(
   int rc = SQLITE_OK;
   SQLITE_EXTENSION_INIT2(pApi);
   (void)pzErrMsg;  /* Unused parameter */
-  rc = sqlite3_create_function(db, "sqlar_compress", 1, SQLITE_UTF8, 0,
+  rc = sqlite3_create_function(db, "sqlar_compress", 1, 
+                               SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
                                sqlarCompressFunc, 0, 0);
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "sqlar_uncompress", 2, SQLITE_UTF8, 0,
+    rc = sqlite3_create_function(db, "sqlar_uncompress", 2,
+                                 SQLITE_UTF8|SQLITE_INNOCUOUS, 0,
                                  sqlarUncompressFunc, 0, 0);
   }
   return rc;
@@ -6508,8 +8063,8 @@ int sqlite3_sqlar_init(
 **
 *************************************************************************
 */
-
-
+#if !defined(SQLITEEXPERT_H)
+#define SQLITEEXPERT_H 1
 /* #include "sqlite3.h" */
 
 typedef struct sqlite3expert sqlite3expert;
@@ -6663,7 +8218,7 @@ const char *sqlite3_expert_report(sqlite3expert*, int iStmt, int eReport);
 */
 void sqlite3_expert_destroy(sqlite3expert*);
 
-
+#endif  /* !defined(SQLITEEXPERT_H) */
 
 /************************* End ../ext/expert/sqlite3expert.h ********************/
 /************************* Begin ../ext/expert/sqlite3expert.c ******************/
@@ -7354,6 +8909,7 @@ static int idxGetTableInfo(
   IdxTable *pNew = 0;
   int rc, rc2;
   char *pCsr = 0;
+  int nPk = 0;
 
   rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_info=%Q", zTab);
   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
@@ -7364,6 +8920,7 @@ static int idxGetTableInfo(
     );
     nByte += 1 + STRLEN(zCol);
     nCol++;
+    nPk += (sqlite3_column_int(p1, 5)>0);
   }
   rc2 = sqlite3_reset(p1);
   if( rc==SQLITE_OK ) rc = rc2;
@@ -7383,7 +8940,7 @@ static int idxGetTableInfo(
     const char *zCol = (const char*)sqlite3_column_text(p1, 1);
     int nCopy = STRLEN(zCol) + 1;
     pNew->aCol[nCol].zName = pCsr;
-    pNew->aCol[nCol].iPk = sqlite3_column_int(p1, 5);
+    pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
     memcpy(pCsr, zCol, nCopy);
     pCsr += nCopy;
 
@@ -7797,14 +9354,19 @@ int idxFindIndexes(
       /* int iParent = sqlite3_column_int(pExplain, 1); */
       /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
       const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
-      int nDetail = STRLEN(zDetail);
+      int nDetail;
       int i;
 
+      if( !zDetail ) continue;
+      nDetail = STRLEN(zDetail);
+
       for(i=0; i<nDetail; i++){
         const char *zIdx = 0;
-        if( memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
+        if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
           zIdx = &zDetail[i+13];
-        }else if( memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 ){
+        }else if( i+22<nDetail 
+            && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0 
+        ){
           zIdx = &zDetail[i+22];
         }
         if( zIdx ){
@@ -7887,7 +9449,7 @@ static int idxProcessOneTrigger(
   IdxTable *pTab = pWrite->pTab;
   const char *zTab = pTab->zName;
   const char *zSql = 
-    "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_master "
+    "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
     "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
     "ORDER BY type;";
   sqlite3_stmt *pSelect = 0;
@@ -7987,12 +9549,12 @@ static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
   **   2) Create the equivalent virtual table in dbv.
   */
   rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
-      "SELECT type, name, sql, 1 FROM sqlite_master "
+      "SELECT type, name, sql, 1 FROM sqlite_schema "
       "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%%' "
       " UNION ALL "
-      "SELECT type, name, sql, 2 FROM sqlite_master "
+      "SELECT type, name, sql, 2 FROM sqlite_schema "
       "WHERE type = 'trigger'"
-      "  AND tbl_name IN(SELECT name FROM sqlite_master WHERE type = 'view') "
+      "  AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
       "ORDER BY 4, 1"
   );
   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
@@ -8162,7 +9724,7 @@ static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
   int rc = SQLITE_OK;
   const char *zMax = 
     "SELECT max(i.seqno) FROM "
-    "  sqlite_master AS s, "
+    "  sqlite_schema AS s, "
     "  pragma_index_list(s.name) AS l, "
     "  pragma_index_info(l.name) AS i "
     "WHERE s.type = 'table'";
@@ -8315,7 +9877,7 @@ static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
 
   const char *zAllIndex =
     "SELECT s.rowid, s.name, l.name FROM "
-    "  sqlite_master AS s, "
+    "  sqlite_schema AS s, "
     "  pragma_index_list(s.name) AS l "
     "WHERE s.type = 'table'";
   const char *zIndexXInfo = 
@@ -8389,7 +9951,7 @@ static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
   sqlite3_free(pCtx);
 
   if( rc==SQLITE_OK ){
-    rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_master", 0, 0, 0);
+    rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
   }
 
   sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
@@ -8428,7 +9990,7 @@ sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
   if( rc==SQLITE_OK ){
     sqlite3_stmt *pSql;
     rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg, 
-        "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%%'"
+        "SELECT sql FROM sqlite_schema WHERE name NOT LIKE 'sqlite_%%'"
         " AND sql NOT LIKE 'CREATE VIRTUAL %%'"
     );
     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
@@ -8619,7 +10181,7 @@ void sqlite3_expert_destroy(sqlite3expert *p){
   }
 }
 
-#endif /* ifndef SQLITE_OMIT_VIRTUAL_TABLE */
+#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
 
 /************************* End ../ext/expert/sqlite3expert.c ********************/
 
@@ -9493,18 +11055,6 @@ struct OpenSession {
 };
 #endif
 
-/*
-** Shell output mode information from before ".explain on",
-** saved so that it can be restored by ".explain off"
-*/
-typedef struct SavedModeInfo SavedModeInfo;
-struct SavedModeInfo {
-  int valid;          /* Is there legit data in here? */
-  int mode;           /* Mode prior to ".explain on" */
-  int showHeader;     /* The ".header" setting prior to ".explain on" */
-  int colWidth[100];  /* Column widths prior to ".explain on" */
-};
-
 typedef struct ExpertInfo ExpertInfo;
 struct ExpertInfo {
   sqlite3expert *pExpert;
@@ -9549,6 +11099,7 @@ struct ShellState {
   int outCount;          /* Revert to stdout when reaching zero */
   int cnt;               /* Number of records displayed so far */
   int lineno;            /* Line number of last line read from in */
+  int openFlags;         /* Additional flags to open.  (SQLITE_OPEN_NOFOLLOW) */
   FILE *in;              /* Read commands from this stream */
   FILE *out;             /* Write results here */
   FILE *traceOut;        /* Output for sqlite3_trace() */
@@ -9564,6 +11115,7 @@ struct ShellState {
   unsigned mxProgress;   /* Maximum progress callbacks before failing */
   unsigned flgProgress;  /* Flags for the progress callback */
   unsigned shellFlgs;    /* Various flags */
+  unsigned priorShFlgs;  /* Saved copy of flags */
   sqlite3_int64 szMax;   /* --maxsize argument to .open */
   char *zDestTable;      /* Name of destination table when MODE_Insert */
   char *zTempFile;       /* Temporary file that might need deleting */
@@ -9572,8 +11124,9 @@ struct ShellState {
   char rowSeparator[20]; /* Row separator character for MODE_Ascii */
   char colSepPrior[20];  /* Saved column separator */
   char rowSepPrior[20];  /* Saved row separator */
-  int colWidth[100];     /* Requested width of each column when in column mode*/
-  int actualWidth[100];  /* Actual width of each column */
+  int *colWidth;         /* Requested width of each column in columnar modes */
+  int *actualWidth;      /* Actual width of each column */
+  int nWidth;            /* Number of slots in colWidth[] and actualWidth[] */
   char nullValue[20];    /* The text to print when a NULL comes back from
                          ** the database */
   char outfile[FILENAME_MAX]; /* Filename for *out */
@@ -9634,6 +11187,9 @@ struct ShellState {
 #define SHFLG_Newlines       0x00000010 /* .dump --newline flag */
 #define SHFLG_CountChanges   0x00000020 /* .changes setting */
 #define SHFLG_Echo           0x00000040 /* .echo or --echo setting */
+#define SHFLG_HeaderSet      0x00000080 /* .header has been used */
+#define SHFLG_DumpDataOnly   0x00000100 /* .dump show data only */
+#define SHFLG_DumpNoSys      0x00000200 /* .dump omits system tables */
 
 /*
 ** Macros for testing and setting shellFlgs
@@ -9658,6 +11214,10 @@ struct ShellState {
 #define MODE_Ascii   10  /* Use ASCII unit and record separators (0x1F/0x1E) */
 #define MODE_Pretty  11  /* Pretty-print schemas */
 #define MODE_EQP     12  /* Converts EXPLAIN QUERY PLAN output into a graph */
+#define MODE_Json    13  /* Output JSON */
+#define MODE_Markdown 14 /* Markdown formatting */
+#define MODE_Table   15  /* MySQL-style table formatting */
+#define MODE_Box     16  /* Unicode box-drawing characters */
 
 static const char *const modeDescr[] = {
   "line",
@@ -9672,7 +11232,11 @@ static const char *const modeDescr[] = {
   "explain",
   "ascii",
   "prettyprint",
-  "eqp"
+  "eqp",
+  "json",
+  "markdown",
+  "table",
+  "box"
 };
 
 /*
@@ -9864,11 +11428,13 @@ edit_func_end:
 */
 static void outputModePush(ShellState *p){
   p->modePrior = p->mode;
+  p->priorShFlgs = p->shellFlgs;
   memcpy(p->colSepPrior, p->colSeparator, sizeof(p->colSeparator));
   memcpy(p->rowSepPrior, p->rowSeparator, sizeof(p->rowSeparator));
 }
 static void outputModePop(ShellState *p){
   p->mode = p->modePrior;
+  p->shellFlgs = p->priorShFlgs;
   memcpy(p->colSeparator, p->colSepPrior, sizeof(p->colSeparator));
   memcpy(p->rowSeparator, p->rowSepPrior, sizeof(p->rowSeparator));
 }
@@ -10039,6 +11605,40 @@ static void output_c_string(FILE *out, const char *z){
 }
 
 /*
+** Output the given string as a quoted according to JSON quoting rules.
+*/
+static void output_json_string(FILE *out, const char *z, int n){
+  unsigned int c;
+  if( n<0 ) n = (int)strlen(z);
+  fputc('"', out);
+  while( n-- ){
+    c = *(z++);
+    if( c=='\\' || c=='"' ){
+      fputc('\\', out);
+      fputc(c, out);
+    }else if( c<=0x1f ){
+      fputc('\\', out);
+      if( c=='\b' ){
+        fputc('b', out);
+      }else if( c=='\f' ){
+        fputc('f', out);
+      }else if( c=='\n' ){
+        fputc('n', out);
+      }else if( c=='\r' ){
+        fputc('r', out);
+      }else if( c=='\t' ){
+        fputc('t', out);
+      }else{
+         raw_printf(out, "u%04x",c);
+      }
+    }else{
+      fputc(c, out);
+    }
+  }
+  fputc('"', out);
+}
+
+/*
 ** Output the given string with characters that are special to
 ** HTML escaped.
 */
@@ -10348,6 +11948,40 @@ static int progress_handler(void *pClientData) {
 #endif /* SQLITE_OMIT_PROGRESS_CALLBACK */
 
 /*
+** Print N dashes
+*/
+static void print_dashes(FILE *out, int N){
+  const char zDash[] = "--------------------------------------------------";
+  const int nDash = sizeof(zDash) - 1;
+  while( N>nDash ){
+    fputs(zDash, out);
+    N -= nDash;
+  }
+  raw_printf(out, "%.*s", N, zDash);
+}
+
+/*
+** Print a markdown or table-style row separator using ascii-art
+*/
+static void print_row_separator(
+  ShellState *p,
+  int nArg,
+  const char *zSep
+){
+  int i;
+  if( nArg>0 ){
+    fputs(zSep, p->out);
+    print_dashes(p->out, p->actualWidth[0]+2);
+    for(i=1; i<nArg; i++){
+      fputs(zSep, p->out);
+      print_dashes(p->out, p->actualWidth[i]+2);
+    }
+    fputs(zSep, p->out);
+  }
+  fputs("\n", p->out);
+}
+
+/*
 ** This is the callback routine that the shell
 ** invokes for each row of a query result.
 */
@@ -10356,7 +11990,7 @@ static int shell_callback(
   int nArg,        /* Number of result columns */
   const char **azArg,/* Text of each result column */
   const char **azCol,/* Column names */
-  int *aiType      /* Column types */
+  int *aiType      /* Column types.  Might be NULL */
 ){
   int i;
   ShellState *p = (ShellState*)pArg;
@@ -10377,68 +12011,27 @@ static int shell_callback(
       }
       break;
     }
-    case MODE_Explain:
-    case MODE_Column: {
-      static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13};
-      const int *colWidth;
-      int showHdr;
-      const char *rowSep;
-      if( p->cMode==MODE_Column ){
-        colWidth = p->colWidth;
-        showHdr = p->showHeader;
-        rowSep = p->rowSeparator;
-      }else{
-        colWidth = aExplainWidths;
-        showHdr = 1;
-        rowSep = SEP_Row;
+    case MODE_Explain: {
+      static const int aExplainWidth[] = {4, 13, 4, 4, 4, 13, 2, 13};
+      if( nArg>ArraySize(aExplainWidth) ){
+        nArg = ArraySize(aExplainWidth);
       }
       if( p->cnt++==0 ){
         for(i=0; i<nArg; i++){
-          int w, n;
-          if( i<ArraySize(p->colWidth) ){
-            w = colWidth[i];
-          }else{
-            w = 0;
-          }
-          if( w==0 ){
-            w = strlenChar(azCol[i] ? azCol[i] : "");
-            if( w<10 ) w = 10;
-            n = strlenChar(azArg && azArg[i] ? azArg[i] : p->nullValue);
-            if( w<n ) w = n;
-          }
-          if( i<ArraySize(p->actualWidth) ){
-            p->actualWidth[i] = w;
-          }
-          if( showHdr ){
-            utf8_width_print(p->out, w, azCol[i]);
-            utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
-          }
+          int w = aExplainWidth[i];
+          utf8_width_print(p->out, w, azCol[i]);
+          fputs(i==nArg-1 ? "\n" : "  ", p->out);
         }
-        if( showHdr ){
-          for(i=0; i<nArg; i++){
-            int w;
-            if( i<ArraySize(p->actualWidth) ){
-               w = p->actualWidth[i];
-               if( w<0 ) w = -w;
-            }else{
-               w = 10;
-            }
-            utf8_printf(p->out,"%-*.*s%s",w,w,
-                   "----------------------------------------------------------"
-                   "----------------------------------------------------------",
-                    i==nArg-1 ? rowSep : "  ");
-          }
+        for(i=0; i<nArg; i++){
+          int w = aExplainWidth[i];
+          print_dashes(p->out, w);
+          fputs(i==nArg-1 ? "\n" : "  ", p->out);
         }
       }
       if( azArg==0 ) break;
       for(i=0; i<nArg; i++){
-        int w;
-        if( i<ArraySize(p->actualWidth) ){
-           w = p->actualWidth[i];
-        }else{
-           w = 10;
-        }
-        if( p->cMode==MODE_Explain && azArg[i] && strlenChar(azArg[i])>w ){
+        int w = aExplainWidth[i];
+        if( azArg[i] && strlenChar(azArg[i])>w ){
           w = strlenChar(azArg[i]);
         }
         if( i==1 && p->aiIndent && p->pStmt ){
@@ -10448,7 +12041,7 @@ static int shell_callback(
           p->iIndent++;
         }
         utf8_width_print(p->out, w, azArg[i] ? azArg[i] : p->nullValue);
-        utf8_printf(p->out, "%s", i==nArg-1 ? rowSep : "  ");
+        fputs(i==nArg-1 ? "\n" : "  ", p->out);
       }
       break;
     }
@@ -10652,18 +12245,60 @@ static int shell_callback(
       raw_printf(p->out,");\n");
       break;
     }
+    case MODE_Json: {
+      if( azArg==0 ) break;
+      if( p->cnt==0 ){
+        fputs("[{", p->out);
+      }else{
+        fputs(",\n{", p->out);
+      }
+      p->cnt++;
+      for(i=0; i<nArg; i++){
+        output_json_string(p->out, azCol[i], -1);
+        putc(':', p->out);
+        if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
+          fputs("null",p->out);
+        }else if( aiType && aiType[i]==SQLITE_FLOAT ){
+          char z[50];
+          double r = sqlite3_column_double(p->pStmt, i);
+          sqlite3_uint64 ur;
+          memcpy(&ur,&r,sizeof(r));
+          if( ur==0x7ff0000000000000LL ){
+            raw_printf(p->out, "1e999");
+          }else if( ur==0xfff0000000000000LL ){
+            raw_printf(p->out, "-1e999");
+          }else{
+            sqlite3_snprintf(50,z,"%!.20g", r);
+            raw_printf(p->out, "%s", z);
+          }
+        }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){
+          const void *pBlob = sqlite3_column_blob(p->pStmt, i);
+          int nBlob = sqlite3_column_bytes(p->pStmt, i);
+          output_json_string(p->out, pBlob, nBlob);
+        }else if( aiType && aiType[i]==SQLITE_TEXT ){
+          output_json_string(p->out, azArg[i], -1);
+        }else{
+          utf8_printf(p->out,"%s", azArg[i]);
+        }
+        if( i<nArg-1 ){
+          putc(',', p->out);
+        }
+      }
+      putc('}', p->out);
+      break;
+    }
     case MODE_Quote: {
       if( azArg==0 ) break;
       if( p->cnt==0 && p->showHeader ){
         for(i=0; i<nArg; i++){
-          if( i>0 ) raw_printf(p->out, ",");
+          if( i>0 ) fputs(p->colSeparator, p->out);
           output_quoted_string(p->out, azCol[i]);
         }
-        raw_printf(p->out,"\n");
+        fputs(p->rowSeparator, p->out);
       }
       p->cnt++;
       for(i=0; i<nArg; i++){
-        if( i>0 ) raw_printf(p->out, ",");
+        if( i>0 ) fputs(p->colSeparator, p->out);
         if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){
           utf8_printf(p->out,"NULL");
         }else if( aiType && aiType[i]==SQLITE_TEXT ){
@@ -10685,7 +12320,7 @@ static int shell_callback(
           output_quoted_string(p->out, azArg[i]);
         }
       }
-      raw_printf(p->out,"\n");
+      fputs(p->rowSeparator, p->out);
       break;
     }
     case MODE_Ascii: {
@@ -10758,16 +12393,16 @@ static void createSelftestTable(ShellState *p){
     "INSERT INTO [_shell$self]\n"
     "  SELECT 'run',\n"
     "    'SELECT hex(sha3_query(''SELECT type,name,tbl_name,sql "
-                                 "FROM sqlite_master ORDER BY 2'',224))',\n"
+                                 "FROM sqlite_schema ORDER BY 2'',224))',\n"
     "    hex(sha3_query('SELECT type,name,tbl_name,sql "
-                          "FROM sqlite_master ORDER BY 2',224));\n"
+                          "FROM sqlite_schema ORDER BY 2',224));\n"
     "INSERT INTO [_shell$self]\n"
     "  SELECT 'run',"
     "    'SELECT hex(sha3_query(''SELECT * FROM \"' ||"
     "        printf('%w',name) || '\" NOT INDEXED'',224))',\n"
     "    hex(sha3_query(printf('SELECT * FROM \"%w\" NOT INDEXED',name),224))\n"
     "  FROM (\n"
-    "    SELECT name FROM sqlite_master\n"
+    "    SELECT name FROM sqlite_schema\n"
     "     WHERE type='table'\n"
     "       AND name<>'selftest'\n"
     "       AND coalesce(rootpage,0)>0\n"
@@ -10830,8 +12465,7 @@ static void set_table_name(ShellState *p, const char *zName){
 */
 static int run_table_dump_query(
   ShellState *p,           /* Query context */
-  const char *zSelect,     /* SELECT statement to extract content */
-  const char *zFirstRow    /* Print before first row, if not NULL */
+  const char *zSelect      /* SELECT statement to extract content */
 ){
   sqlite3_stmt *pSelect;
   int rc;
@@ -10848,10 +12482,6 @@ static int run_table_dump_query(
   rc = sqlite3_step(pSelect);
   nResult = sqlite3_column_count(pSelect);
   while( rc==SQLITE_ROW ){
-    if( zFirstRow ){
-      utf8_printf(p->out, "%s", zFirstRow);
-      zFirstRow = 0;
-    }
     z = (const char*)sqlite3_column_text(pSelect, 0);
     utf8_printf(p->out, "%s", z);
     for(i=1; i<nResult; i++){
@@ -11255,36 +12885,26 @@ static void explain_data_delete(ShellState *p){
 /*
 ** Disable and restore .wheretrace and .selecttrace settings.
 */
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
-extern int sqlite3SelectTrace;
-static int savedSelectTrace;
-#endif
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
-extern int sqlite3WhereTrace;
-static int savedWhereTrace;
-#endif
+static unsigned int savedSelectTrace;
+static unsigned int savedWhereTrace;
 static void disable_debug_trace_modes(void){
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
-  savedSelectTrace = sqlite3SelectTrace;
-  sqlite3SelectTrace = 0;
-#endif
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
-  savedWhereTrace = sqlite3WhereTrace;
-  sqlite3WhereTrace = 0;
-#endif
+  unsigned int zero = 0;
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 0, &savedSelectTrace);
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &zero);
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 2, &savedWhereTrace);
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &zero);
 }
 static void restore_debug_trace_modes(void){
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
-  sqlite3SelectTrace = savedSelectTrace;
-#endif
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
-  sqlite3WhereTrace = savedWhereTrace;
-#endif
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &savedSelectTrace);
+  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &savedWhereTrace);
 }
 
 /* Create the TEMP table used to store parameter bindings */
 static void bind_table_init(ShellState *p){
   int wrSchema = 0;
+  int defensiveMode = 0;
+  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, -1, &defensiveMode);
+  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, 0, 0);
   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, -1, &wrSchema);
   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0);
   sqlite3_exec(p->db,
@@ -11294,6 +12914,7 @@ static void bind_table_init(ShellState *p){
     ") WITHOUT ROWID;",
     0, 0, 0);
   sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, wrSchema, 0);
+  sqlite3_db_config(p->db, SQLITE_DBCONFIG_DEFENSIVE, defensiveMode, 0);
 }
 
 /*
@@ -11304,9 +12925,9 @@ static void bind_table_init(ShellState *p){
 **    CREATE TEMP TABLE sqlite_parameters(key TEXT PRIMARY KEY, value)
 **    WITHOUT ROWID;
 **
-** No bindings occur if this table does not exist.  The special character '$'
-** is included in the table name to help prevent collisions with actual tables.
-** The table must be in the TEMP schema.
+** No bindings occur if this table does not exist.  The name of the table
+** begins with "sqlite_" so that it will not collide with ordinary application
+** tables.  The table must be in the TEMP schema.
 */
 static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
   int nVar;
@@ -11331,15 +12952,241 @@ static void bind_prepared_stmt(ShellState *pArg, sqlite3_stmt *pStmt){
       sqlite3_snprintf(sizeof(zNum),zNum,"?%d",i);
       zVar = zNum;
     }
-    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
-    if( sqlite3_step(pQ)==SQLITE_ROW ){
-      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
+    sqlite3_bind_text(pQ, 1, zVar, -1, SQLITE_STATIC);
+    if( sqlite3_step(pQ)==SQLITE_ROW ){
+      sqlite3_bind_value(pStmt, i, sqlite3_column_value(pQ, 0));
+    }else{
+      sqlite3_bind_null(pStmt, i);
+    }
+    sqlite3_reset(pQ);
+  }
+  sqlite3_finalize(pQ);
+}
+
+/*
+** UTF8 box-drawing characters.  Imagine box lines like this:
+**
+**           1
+**           |
+**       4 --+-- 2
+**           |
+**           3
+**
+** Each box characters has between 2 and 4 of the lines leading from
+** the center.  The characters are here identified by the numbers of
+** their corresponding lines.
+*/
+#define BOX_24   "\342\224\200"  /* U+2500 --- */
+#define BOX_13   "\342\224\202"  /* U+2502  |  */
+#define BOX_23   "\342\224\214"  /* U+250c  ,- */
+#define BOX_34   "\342\224\220"  /* U+2510 -,  */
+#define BOX_12   "\342\224\224"  /* U+2514  '- */
+#define BOX_14   "\342\224\230"  /* U+2518 -'  */
+#define BOX_123  "\342\224\234"  /* U+251c  |- */
+#define BOX_134  "\342\224\244"  /* U+2524 -|  */
+#define BOX_234  "\342\224\254"  /* U+252c -,- */
+#define BOX_124  "\342\224\264"  /* U+2534 -'- */
+#define BOX_1234 "\342\224\274"  /* U+253c -|- */
+
+/* Draw horizontal line N characters long using unicode box
+** characters
+*/
+static void print_box_line(FILE *out, int N){
+  const char zDash[] = 
+      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24
+      BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24 BOX_24;
+  const int nDash = sizeof(zDash) - 1;
+  N *= 3;
+  while( N>nDash ){
+    utf8_printf(out, zDash);
+    N -= nDash;
+  }
+  utf8_printf(out, "%.*s", N, zDash);
+}
+
+/*
+** Draw a horizontal separator for a MODE_Box table.
+*/
+static void print_box_row_separator(
+  ShellState *p,
+  int nArg,
+  const char *zSep1,
+  const char *zSep2,
+  const char *zSep3
+){
+  int i;
+  if( nArg>0 ){
+    utf8_printf(p->out, "%s", zSep1);
+    print_box_line(p->out, p->actualWidth[0]+2);
+    for(i=1; i<nArg; i++){
+      utf8_printf(p->out, "%s", zSep2);
+      print_box_line(p->out, p->actualWidth[i]+2);
+    }
+    utf8_printf(p->out, "%s", zSep3);
+  }
+  fputs("\n", p->out);
+}
+
+
+
+/*
+** Run a prepared statement and output the result in one of the
+** table-oriented formats: MODE_Column, MODE_Markdown, MODE_Table,
+** or MODE_Box.
+**
+** This is different from ordinary exec_prepared_stmt() in that
+** it has to run the entire query and gather the results into memory
+** first, in order to determine column widths, before providing
+** any output.
+*/
+static void exec_prepared_stmt_columnar(
+  ShellState *p,                        /* Pointer to ShellState */
+  sqlite3_stmt *pStmt                   /* Statment to run */
+){
+  sqlite3_int64 nRow = 0;
+  int nColumn = 0;
+  char **azData = 0;
+  sqlite3_int64 nAlloc = 0;
+  const char *z;
+  int rc;
+  sqlite3_int64 i, nData;
+  int j, nTotal, w, n;
+  const char *colSep = 0;
+  const char *rowSep = 0;
+
+  rc = sqlite3_step(pStmt);
+  if( rc!=SQLITE_ROW ) return;
+  nColumn = sqlite3_column_count(pStmt);
+  nAlloc = nColumn*4;
+  azData = sqlite3_malloc64( nAlloc*sizeof(char*) );
+  if( azData==0 ) shell_out_of_memory();
+  for(i=0; i<nColumn; i++){
+    azData[i] = strdup(sqlite3_column_name(pStmt,i));
+  }
+  do{
+    if( (nRow+2)*nColumn >= nAlloc ){
+      nAlloc *= 2;
+      azData = sqlite3_realloc64(azData, nAlloc*sizeof(char*));
+      if( azData==0 ) shell_out_of_memory();
+    }
+    nRow++;
+    for(i=0; i<nColumn; i++){
+      z = (const char*)sqlite3_column_text(pStmt,i);
+      azData[nRow*nColumn + i] = z ? strdup(z) : 0;
+    }
+  }while( (rc = sqlite3_step(pStmt))==SQLITE_ROW );
+  if( nColumn>p->nWidth ){
+    p->colWidth = realloc(p->colWidth, nColumn*2*sizeof(int));
+    if( p->colWidth==0 ) shell_out_of_memory();
+    for(i=p->nWidth; i<nColumn; i++) p->colWidth[i] = 0;
+    p->nWidth = nColumn;
+    p->actualWidth = &p->colWidth[nColumn];
+  }
+  memset(p->actualWidth, 0, nColumn*sizeof(int));
+  for(i=0; i<nColumn; i++){
+    w = p->colWidth[i];
+    if( w<0 ) w = -w;
+    p->actualWidth[i] = w;
+  }
+  nTotal = nColumn*(nRow+1);
+  for(i=0; i<nTotal; i++){
+    z = azData[i];
+    if( z==0 ) z = p->nullValue;
+    n = strlenChar(z);
+    j = i%nColumn;
+    if( n>p->actualWidth[j] ) p->actualWidth[j] = n;
+  }
+  if( seenInterrupt ) goto columnar_end;
+  switch( p->cMode ){
+    case MODE_Column: {
+      colSep = "  ";
+      rowSep = "\n";
+      if( p->showHeader ){
+        for(i=0; i<nColumn; i++){
+          w = p->actualWidth[i];
+          if( p->colWidth[i]<0 ) w = -w;
+          utf8_width_print(p->out, w, azData[i]);
+          fputs(i==nColumn-1?"\n":"  ", p->out);
+        }
+        for(i=0; i<nColumn; i++){
+          print_dashes(p->out, p->actualWidth[i]);
+          fputs(i==nColumn-1?"\n":"  ", p->out);
+        }
+      }
+      break;
+    }
+    case MODE_Table: {
+      colSep = " | ";
+      rowSep = " |\n";
+      print_row_separator(p, nColumn, "+");
+      fputs("| ", p->out);
+      for(i=0; i<nColumn; i++){
+        w = p->actualWidth[i];
+        n = strlenChar(azData[i]);
+        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
+        fputs(i==nColumn-1?" |\n":" | ", p->out);
+      }
+      print_row_separator(p, nColumn, "+");
+      break;
+    }
+    case MODE_Markdown: {
+      colSep = " | ";
+      rowSep = " |\n";
+      fputs("| ", p->out);
+      for(i=0; i<nColumn; i++){
+        w = p->actualWidth[i];
+        n = strlenChar(azData[i]);
+        utf8_printf(p->out, "%*s%s%*s", (w-n)/2, "", azData[i], (w-n+1)/2, "");
+        fputs(i==nColumn-1?" |\n":" | ", p->out);
+      }
+      print_row_separator(p, nColumn, "|");
+      break;
+    }
+    case MODE_Box: {
+      colSep = " " BOX_13 " ";
+      rowSep = " " BOX_13 "\n";
+      print_box_row_separator(p, nColumn, BOX_23, BOX_234, BOX_34);
+      utf8_printf(p->out, BOX_13 " ");
+      for(i=0; i<nColumn; i++){
+        w = p->actualWidth[i];
+        n = strlenChar(azData[i]);
+        utf8_printf(p->out, "%*s%s%*s%s",
+            (w-n)/2, "", azData[i], (w-n+1)/2, "",
+            i==nColumn-1?" "BOX_13"\n":" "BOX_13" ");
+      }
+      print_box_row_separator(p, nColumn, BOX_123, BOX_1234, BOX_134);
+      break;
+    }
+  }
+  for(i=nColumn, j=0; i<nTotal; i++, j++){
+    if( j==0 && p->cMode!=MODE_Column ){
+      utf8_printf(p->out, "%s", p->cMode==MODE_Box?BOX_13" ":"| ");
+    }
+    z = azData[i];
+    if( z==0 ) z = p->nullValue;
+    w = p->actualWidth[j];
+    if( p->colWidth[j]<0 ) w = -w;
+    utf8_width_print(p->out, w, z);
+    if( j==nColumn-1 ){
+      utf8_printf(p->out, "%s", rowSep);
+      j = -1;
+      if( seenInterrupt ) goto columnar_end;
     }else{
-      sqlite3_bind_null(pStmt, i);
+      utf8_printf(p->out, "%s", colSep);
     }
-    sqlite3_reset(pQ);
   }
-  sqlite3_finalize(pQ);
+  if( p->cMode==MODE_Table ){
+    print_row_separator(p, nColumn, "+");
+  }else if( p->cMode==MODE_Box ){
+    print_box_row_separator(p, nColumn, BOX_12, BOX_124, BOX_14);
+  }
+columnar_end:
+  if( seenInterrupt ){
+    utf8_printf(p->out, "Interrupt\n");
+  }
+  nData = (nRow+1)*nColumn;
+  for(i=0; i<nData; i++) free(azData[i]);
+  sqlite3_free(azData);
 }
 
 /*
@@ -11351,6 +13198,15 @@ static void exec_prepared_stmt(
 ){
   int rc;
 
+  if( pArg->cMode==MODE_Column
+   || pArg->cMode==MODE_Table
+   || pArg->cMode==MODE_Box
+   || pArg->cMode==MODE_Markdown
+  ){
+    exec_prepared_stmt_columnar(pArg, pStmt);
+    return;
+  }
+
   /* perform the first step.  this will tell us if we
   ** have a result set or not and how wide it is.
   */
@@ -11398,6 +13254,9 @@ static void exec_prepared_stmt(
         }
       } while( SQLITE_ROW == rc );
       sqlite3_free(pData);
+      if( pArg->cMode==MODE_Json ){
+        fputs("]\n", pArg->out);
+      }
     }
   }
 }
@@ -11610,6 +13469,7 @@ static int shell_exec(
             const char *zEQPLine = (const char*)sqlite3_column_text(pExplain,3);
             int iEqpId = sqlite3_column_int(pExplain, 0);
             int iParentId = sqlite3_column_int(pExplain, 1);
+            if( zEQPLine==0 ) zEQPLine = "";
             if( zEQPLine[0]=='-' ) eqp_render(pArg);
             eqp_append(pArg, iEqpId, iParentId, zEQPLine);
           }
@@ -11837,19 +13697,25 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
   const char *zType;
   const char *zSql;
   ShellState *p = (ShellState *)pArg;
+  int dataOnly;
+  int noSys;
 
   UNUSED_PARAMETER(azNotUsed);
   if( nArg!=3 || azArg==0 ) return 0;
   zTable = azArg[0];
   zType = azArg[1];
   zSql = azArg[2];
+  dataOnly = (p->shellFlgs & SHFLG_DumpDataOnly)!=0;
+  noSys    = (p->shellFlgs & SHFLG_DumpNoSys)!=0;
 
-  if( strcmp(zTable, "sqlite_sequence")==0 ){
-    raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
-  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){
-    raw_printf(p->out, "ANALYZE sqlite_master;\n");
+  if( strcmp(zTable, "sqlite_sequence")==0 && !noSys ){
+    if( !dataOnly ) raw_printf(p->out, "DELETE FROM sqlite_sequence;\n");
+  }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 && !noSys ){
+    if( !dataOnly ) raw_printf(p->out, "ANALYZE sqlite_schema;\n");
   }else if( strncmp(zTable, "sqlite_", 7)==0 ){
     return 0;
+  }else if( dataOnly ){
+    /* no-op */
   }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){
     char *zIns;
     if( !p->writableSchema ){
@@ -11857,7 +13723,7 @@ static int dump_callback(void *pArg, int nArg, char **azArg, char **azNotUsed){
       p->writableSchema = 1;
     }
     zIns = sqlite3_mprintf(
-       "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"
+       "INSERT INTO sqlite_schema(type,name,tbl_name,rootpage,sql)"
        "VALUES('table','%q','%q',0,'%q');",
        zTable, zTable, zSql);
     utf8_printf(p->out, "%s\n", zIns);
@@ -12020,11 +13886,14 @@ static const char *(azHelp[]) = {
   ".databases               List names and files of attached databases",
   ".dbconfig ?op? ?val?     List or change sqlite3_db_config() options",
   ".dbinfo ?DB?             Show status information about the database",
-  ".dump ?TABLE? ...        Render all database content as SQL",
+  ".dump ?TABLE?            Render database content as SQL",
   "   Options:",
-  "     --preserve-rowids      Include ROWID values in the output",
+  "     --data-only            Output only INSERT statements",
   "     --newlines             Allow unescaped newline characters in output",
+  "     --nosys                Omit system tables (ex: \"sqlite_stat1\")",
+  "     --preserve-rowids      Include ROWID values in the output",
   "   TABLE is a LIKE pattern for the tables to dump",
+  "   Additional LIKE patterns can be given in subsequent arguments",
   ".echo on|off             Turn command echo on or off",
   ".eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN",
   "   Other Modes:",
@@ -12034,17 +13903,29 @@ static const char *(azHelp[]) = {
 #endif
   "      trigger               Like \"full\" but also show trigger bytecode",
   ".excel                   Display the output of next command in spreadsheet",
+  "   --bom                   Put a UTF8 byte-order mark on intermediate file",
   ".exit ?CODE?             Exit this program with return-code CODE",
   ".expert                  EXPERIMENTAL. Suggest indexes for queries",
-/* Because explain mode comes on automatically now, the ".explain" mode
-** is removed from the help screen. It is still supported for legacy, however */
-/*".explain ?on|off|auto?   Turn EXPLAIN output mode on or off",*/
+  ".explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto",
   ".filectrl CMD ...        Run various sqlite3_file_control() operations",
-  "                           Run \".filectrl\" with no arguments for details",
+  "   --schema SCHEMA         Use SCHEMA instead of \"main\"",
+  "   --help                  Show CMD details",
   ".fullschema ?--indent?   Show schema and the content of sqlite_stat tables",
   ".headers on|off          Turn display of headers on or off",
   ".help ?-all? ?PATTERN?   Show help text for PATTERN",
   ".import FILE TABLE       Import data from FILE into TABLE",
+  "   Options:",
+  "     --ascii               Use \\037 and \\036 as column and row separators",
+  "     --csv                 Use , and \\n as column and row separators",
+  "     --skip N              Skip the first N rows of input",
+  "     -v                    \"Verbose\" - increase auxiliary output",
+  "   Notes:",
+  "     *  If TABLE does not exist, it is created.  The first row of input",
+  "        determines the column names.",
+  "     *  If neither --csv or --ascii are used, the input mode is derived",
+  "        from the \".mode\" output mode",
+  "     *  If FILE begins with \"|\" then it is a command that generates the",
+  "        input text.",
 #ifndef SQLITE_OMIT_TEST_CONTROL
   ".imposter INDEX TABLE    Create imposter table TABLE on index INDEX",
 #endif
@@ -12064,22 +13945,29 @@ static const char *(azHelp[]) = {
   ".log FILE|off            Turn logging on or off.  FILE can be stderr/stdout",
   ".mode MODE ?TABLE?       Set output mode",
   "   MODE is one of:",
-  "     ascii    Columns/rows delimited by 0x1F and 0x1E",
-  "     csv      Comma-separated values",
-  "     column   Left-aligned columns.  (See .width)",
-  "     html     HTML <table> code",
-  "     insert   SQL insert statements for TABLE",
-  "     line     One value per line",
-  "     list     Values delimited by \"|\"",
-  "     quote    Escape answers as for SQL",
-  "     tabs     Tab-separated values",
-  "     tcl      TCL list elements",
+  "     ascii     Columns/rows delimited by 0x1F and 0x1E",
+  "     box       Tables using unicode box-drawing characters",
+  "     csv       Comma-separated values",
+  "     column    Output in columns.  (See .width)",
+  "     html      HTML <table> code",
+  "     insert    SQL insert statements for TABLE",
+  "     json      Results in a JSON array",
+  "     line      One value per line",
+  "     list      Values delimited by \"|\"",
+  "     markdown  Markdown table format",
+  "     quote     Escape answers as for SQL",
+  "     table     ASCII-art table",
+  "     tabs      Tab-separated values",
+  "     tcl       TCL list elements",
   ".nullvalue STRING        Use STRING in place of NULL values",
-  ".once (-e|-x|FILE)       Output for the next SQL command only to FILE",
+  ".once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE",
   "     If FILE begins with '|' then open as a pipe",
-  "     Other options:",
-  "       -e    Invoke system text editor",
-  "       -x    Open in a spreadsheet",
+  "       --bom  Put a UTF8 byte-order mark at the beginning",
+  "       -e     Send output to the system text editor",
+  "       -x     Send output as CSV to a spreadsheet (same as \".excel\")",
+#ifdef SQLITE_DEBUG
+  ".oom ?--repeat M? ?N?    Simulate an OOM error on the N-th allocation",
+#endif 
   ".open ?OPTIONS? ?FILE?   Close existing database and reopen FILE",
   "     Options:",
   "        --append        Use appendvfs to append database to the end of FILE",
@@ -12089,10 +13977,15 @@ static const char *(azHelp[]) = {
   "        --maxsize N     Maximum size for --hexdb or --deserialized database",
 #endif
   "        --new           Initialize FILE to an empty database",
+  "        --nofollow      Do not follow symbolic links",
   "        --readonly      Open FILE readonly",
   "        --zip           FILE is a ZIP archive",
   ".output ?FILE?           Send output to FILE or stdout if FILE is omitted",
-  "     If FILE begins with '|' then open it as a pipe.",
+  "   If FILE begins with '|' then open it as a pipe.",
+  "   Options:",
+  "     --bom                 Prefix output with a UTF8 byte-order mark",
+  "     -e                    Send output to the system text editor",
+  "     -x                    Send output as CSV to a spreadsheet",
   ".parameter CMD ...       Manage SQL parameter bindings",
   "   clear                   Erase all bindings",
   "   init                    Initialize the TEMP table that holds bindings",
@@ -12123,8 +14016,9 @@ static const char *(azHelp[]) = {
   ".save FILE               Write in-memory database into FILE",
   ".scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off",
   ".schema ?PATTERN?        Show the CREATE statements matching PATTERN",
-  "     Options:",
-  "         --indent            Try to pretty-print the schema",
+  "   Options:",
+  "      --indent             Try to pretty-print the schema",
+  "      --nosys              Omit objects whose names start with \"sqlite_\"",
 #ifdef SQLITE_DEBUG
   ".selftest ?OPTIONS?      Run tests defined in the SELFTEST table",
   "    Options:",
@@ -12149,7 +14043,7 @@ static const char *(azHelp[]) = {
 #endif
   ".sha3sum ...             Compute a SHA3 hash of database content",
   "    Options:",
-  "      --schema              Also hash the sqlite_master table",
+  "      --schema              Also hash the sqlite_schema table",
   "      --sha3-224            Use the sha3-224 algorithm",
   "      --sha3-256            Use the sha3-256 algorithm (default)",
   "      --sha3-384            Use the sha3-384 algorithm",
@@ -12192,7 +14086,7 @@ static const char *(azHelp[]) = {
   ".vfsinfo ?AUX?           Information about the top-level VFS",
   ".vfslist                 List all available VFSes",
   ".vfsname ?AUX?           Print the name of the VFS stack",
-  ".width NUM1 NUM2 ...     Set column widths for \"column\" mode",
+  ".width NUM1 NUM2 ...     Set minimum column widths for columnar output",
   "     Negative values right-justify",
 };
 
@@ -12214,6 +14108,7 @@ static int showHelp(FILE *out, const char *zPattern){
    || zPattern[0]=='0'
    || strcmp(zPattern,"-a")==0
    || strcmp(zPattern,"-all")==0
+   || strcmp(zPattern,"--all")==0
   ){
     /* Show all commands, but only one line per command */
     if( zPattern==0 ) zPattern = "";
@@ -12535,6 +14430,20 @@ static void shellIdQuote(
 }
 
 /*
+** Scalar function "usleep(X)" invokes sqlite3_sleep(X) and returns X.
+*/
+static void shellUSleepFunc(
+  sqlite3_context *context, 
+  int argcUnused, 
+  sqlite3_value **argv
+){
+  int sleep = sqlite3_value_int(argv[0]);
+  (void)argcUnused;
+  sqlite3_sleep(sleep/1000);
+  sqlite3_result_int(context, sleep);
+}
+
+/*
 ** Scalar function "shell_escape_crnl" used by the .recover command.
 ** The argument passed to this function is the output of built-in
 ** function quote(). If the first character of the input is "'", 
@@ -12655,7 +14564,7 @@ static void open_db(ShellState *p, int openFlags){
     switch( p->openMode ){
       case SHELL_OPEN_APPENDVFS: {
         sqlite3_open_v2(p->zDbFilename, &p->db, 
-           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, "apndvfs");
+           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, "apndvfs");
         break;
       }
       case SHELL_OPEN_HEXDB:
@@ -12668,12 +14577,14 @@ static void open_db(ShellState *p, int openFlags){
         break;
       }
       case SHELL_OPEN_READONLY: {
-        sqlite3_open_v2(p->zDbFilename, &p->db, SQLITE_OPEN_READONLY, 0);
+        sqlite3_open_v2(p->zDbFilename, &p->db,
+            SQLITE_OPEN_READONLY|p->openFlags, 0);
         break;
       }
       case SHELL_OPEN_UNSPEC:
       case SHELL_OPEN_NORMAL: {
-        sqlite3_open(p->zDbFilename, &p->db);
+        sqlite3_open_v2(p->zDbFilename, &p->db,
+           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|p->openFlags, 0);
         break;
       }
     }
@@ -12693,6 +14604,10 @@ static void open_db(ShellState *p, int openFlags){
     sqlite3_fileio_init(p->db, 0, 0);
     sqlite3_shathree_init(p->db, 0, 0);
     sqlite3_completion_init(p->db, 0, 0);
+    sqlite3_uint_init(p->db, 0, 0);
+    sqlite3_decimal_init(p->db, 0, 0);
+    sqlite3_ieee_init(p->db, 0, 0);
+    sqlite3_series_init(p->db, 0, 0);
 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB)
     sqlite3_dbdata_init(p->db, 0, 0);
 #endif
@@ -12712,6 +14627,8 @@ static void open_db(ShellState *p, int openFlags){
                             shellInt32, 0, 0);
     sqlite3_create_function(p->db, "shell_idquote", 1, SQLITE_UTF8, 0,
                             shellIdQuote, 0, 0);
+    sqlite3_create_function(p->db, "usleep",1,SQLITE_UTF8,0,
+                            shellUSleepFunc, 0, 0);
 #ifndef SQLITE_NOHAVE_SYSTEM
     sqlite3_create_function(p->db, "edit", 1, SQLITE_UTF8, 0,
                             editFunc, 0, 0);
@@ -13025,16 +14942,29 @@ typedef struct ImportCtx ImportCtx;
 struct ImportCtx {
   const char *zFile;  /* Name of the input file */
   FILE *in;           /* Read the CSV text from this input stream */
+  int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close in */
   char *z;            /* Accumulated text for a field */
   int n;              /* Number of bytes in z */
   int nAlloc;         /* Space allocated for z[] */
   int nLine;          /* Current line number */
+  int nRow;           /* Number of rows imported */
+  int nErr;           /* Number of errors encountered */
   int bNotFirst;      /* True if one or more bytes already read */
   int cTerm;          /* Character that terminated the most recent field */
   int cColSep;        /* The column separator character.  (Usually ",") */
   int cRowSep;        /* The row separator character.  (Usually "\n") */
 };
 
+/* Clean up resourced used by an ImportCtx */
+static void import_cleanup(ImportCtx *p){
+  if( p->in!=0 && p->xCloser!=0 ){
+    p->xCloser(p->in);
+    p->in = 0;
+  }
+  sqlite3_free(p->z);
+  p->z = 0;
+}
+
 /* Append a single byte to z[] */
 static void import_append_char(ImportCtx *p, int c){
   if( p->n+1>=p->nAlloc ){
@@ -13283,7 +15213,7 @@ end_data_xfer:
 ** Try to transfer all rows of the schema that match zWhere.  For
 ** each row, invoke xForEach() on the object defined by that row.
 ** If an error is encountered while moving forward through the
-** sqlite_master table, try again moving backwards.
+** sqlite_schema table, try again moving backwards.
 */
 static void tryToCloneSchema(
   ShellState *p,
@@ -13298,7 +15228,7 @@ static void tryToCloneSchema(
   const unsigned char *zSql;
   char *zErrMsg = 0;
 
-  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
+  zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
                            " WHERE %s", zWhere);
   rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
   if( rc ){
@@ -13325,7 +15255,7 @@ static void tryToCloneSchema(
   if( rc!=SQLITE_DONE ){
     sqlite3_finalize(pQuery);
     sqlite3_free(zQuery);
-    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master"
+    zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_schema"
                              " WHERE %s ORDER BY rowid DESC", zWhere);
     rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0);
     if( rc ){
@@ -13410,11 +15340,15 @@ static void output_reset(ShellState *p){
       zCmd = sqlite3_mprintf("%s %s", zXdgOpenCmd, p->zTempFile);
       if( system(zCmd) ){
         utf8_printf(stderr, "Failed: [%s]\n", zCmd);
+      }else{
+        /* Give the start/open/xdg-open command some time to get
+        ** going before we continue, and potential delete the
+        ** p->zTempFile data file out from under it */
+        sqlite3_sleep(2000);
       }
       sqlite3_free(zCmd);
       outputModePop(p);
       p->doXdgOpen = 0;
-      sqlite3_sleep(100);
     }
 #endif /* !defined(SQLITE_NOHAVE_SYSTEM) */
   }
@@ -13447,7 +15381,7 @@ static unsigned int get4byteInt(unsigned char *a){
 }
 
 /*
-** Implementation of the ".info" command.
+** Implementation of the ".dbinfo" command.
 **
 ** Return 1 on error, 2 to exit, and 0 otherwise.
 */
@@ -13490,12 +15424,7 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
              "SELECT data FROM sqlite_dbpage(?1) WHERE pgno=1",
              -1, &pStmt, 0);
   if( rc ){
-    if( !sqlite3_compileoption_used("ENABLE_DBPAGE_VTAB") ){
-      utf8_printf(stderr, "the \".dbinfo\" command requires the "
-                          "-DSQLITE_ENABLE_DBPAGE_VTAB compile-time options\n");
-    }else{
-      utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
-    }
+    utf8_printf(stderr, "error: %s\n", sqlite3_errmsg(p->db));
     sqlite3_finalize(pStmt);
     return 1;
   }
@@ -13530,11 +15459,11 @@ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){
     raw_printf(p->out, "\n");
   }
   if( zDb==0 ){
-    zSchemaTab = sqlite3_mprintf("main.sqlite_master");
+    zSchemaTab = sqlite3_mprintf("main.sqlite_schema");
   }else if( strcmp(zDb,"temp")==0 ){
-    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master");
+    zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_schema");
   }else{
-    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb);
+    zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_schema", zDb);
   }
   for(i=0; i<ArraySize(aQuery); i++){
     char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab);
@@ -13704,9 +15633,21 @@ static void newTempFile(ShellState *p, const char *zSuffix){
     sqlite3_file_control(p->db, 0, SQLITE_FCNTL_TEMPFILENAME, &p->zTempFile);
   }
   if( p->zTempFile==0 ){
+    /* If p->db is an in-memory database then the TEMPFILENAME file-control
+    ** will not work and we will need to fallback to guessing */
+    char *zTemp;
     sqlite3_uint64 r;
     sqlite3_randomness(sizeof(r), &r);
-    p->zTempFile = sqlite3_mprintf("temp%llx.%s", r, zSuffix);
+    zTemp = getenv("TEMP");
+    if( zTemp==0 ) zTemp = getenv("TMP");
+    if( zTemp==0 ){
+#ifdef _WIN32
+      zTemp = "\\tmp";
+#else
+      zTemp = "/tmp";
+#endif
+    }
+    p->zTempFile = sqlite3_mprintf("%s/temp%llx.%s", zTemp, r, zSuffix);
   }else{
     p->zTempFile = sqlite3_mprintf("%z.%s", p->zTempFile, zSuffix);
   }
@@ -13844,7 +15785,7 @@ static int lintFkeyIndexes(
     "  || ');'"
     ", "
     "     f.[table] "
-    "FROM sqlite_master AS s, pragma_foreign_key_list(s.name) AS f "
+    "FROM sqlite_schema AS s, pragma_foreign_key_list(s.name) AS f "
     "LEFT JOIN pragma_table_info AS p ON (pk-1=seq AND p.arg=f.[table]) "
     "GROUP BY s.name, f.id "
     "ORDER BY (CASE WHEN ? THEN f.[table] ELSE s.name END)"
@@ -14919,7 +16860,7 @@ static RecoverTable *recoverNewTable(
     shellPreparePrintf(dbtmp, &rc, &pStmt, 
       "SELECT ("
       "  SELECT substr(data,1,1)==X'0D' FROM sqlite_dbpage WHERE pgno=rootpage"
-      ") FROM sqlite_master WHERE name = %Q", zName
+      ") FROM sqlite_schema WHERE name = %Q", zName
     );
     if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
       bSqlIntkey = sqlite3_column_int(pStmt, 0);
@@ -14991,7 +16932,7 @@ static RecoverTable *recoverNewTable(
 
 /*
 ** This function is called to search the schema recovered from the
-** sqlite_master table of the (possibly) corrupt database as part
+** sqlite_schema table of the (possibly) corrupt database as part
 ** of a ".recover" command. Specifically, for a table with root page
 ** iRoot and at least nCol columns. Additionally, if bIntkey is 0, the
 ** table must be a WITHOUT ROWID table, or if non-zero, not one of
@@ -15254,7 +17195,7 @@ static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
     ");"
 
     /* Extract data from page 1 and any linked pages into table
-    ** recovery.schema. With the same schema as an sqlite_master table.  */
+    ** recovery.schema. With the same schema as an sqlite_schema table.  */
     "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);"
     "INSERT INTO recovery.schema SELECT "
     "  max(CASE WHEN field=0 THEN value ELSE NULL END),"
@@ -15406,7 +17347,7 @@ static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
       if( sqlite3_strnicmp(zSql, "create virt", 11)==0 ){
         const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
         char *zPrint = shellMPrintf(&rc, 
-          "INSERT INTO sqlite_master VALUES('table', %Q, %Q, 0, %Q)",
+          "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)",
           zName, zName, zSql
         );
         raw_printf(pState->out, "%s;\n", zPrint);
@@ -15662,21 +17603,41 @@ static int do_meta_command(char *zLine, ShellState *p){
   }else
 
   if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){
-    ShellState data;
-    char *zErrMsg = 0;
+    char **azName = 0;
+    int nName = 0;
+    sqlite3_stmt *pStmt;
+    int i;
     open_db(p, 0);
-    memcpy(&data, p, sizeof(data));
-    data.showHeader = 0;
-    data.cMode = data.mode = MODE_List;
-    sqlite3_snprintf(sizeof(data.colSeparator),data.colSeparator,": ");
-    data.cnt = 0;
-    sqlite3_exec(p->db, "SELECT name, file FROM pragma_database_list",
-                 callback, &data, &zErrMsg);
-    if( zErrMsg ){
-      utf8_printf(stderr,"Error: %s\n", zErrMsg);
-      sqlite3_free(zErrMsg);
+    rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0);
+    if( rc ){
+      utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
       rc = 1;
+    }else{
+      while( sqlite3_step(pStmt)==SQLITE_ROW ){
+        const char *zSchema = (const char *)sqlite3_column_text(pStmt,1);
+        const char *zFile = (const char*)sqlite3_column_text(pStmt,2);
+        azName = sqlite3_realloc(azName, (nName+1)*2*sizeof(char*));
+        if( azName==0 ){ shell_out_of_memory();  /* Does not return */ }
+        azName[nName*2] = strdup(zSchema);
+        azName[nName*2+1] = strdup(zFile);
+        nName++;
+      }
     }
+    sqlite3_finalize(pStmt);
+    for(i=0; i<nName; i++){
+      int eTxn = sqlite3_txn_state(p->db, azName[i*2]);
+      int bRdonly = sqlite3_db_readonly(p->db, azName[i*2]);
+      const char *z = azName[i*2+1];
+      utf8_printf(p->out, "%s: %s %s%s\n",
+         azName[i*2],
+         z && z[0] ? z : "\"\"",
+         bRdonly ? "r/o" : "r/w",
+         eTxn==SQLITE_TXN_NONE ? "" :
+            eTxn==SQLITE_TXN_READ ? " read-txn" : " write-txn");
+      free(azName[i*2]);
+      free(azName[i*2+1]);
+    }
+    sqlite3_free(azName);
   }else
 
   if( c=='d' && n>=3 && strncmp(azArg[0], "dbconfig", n)==0 ){
@@ -15684,20 +17645,22 @@ static int do_meta_command(char *zLine, ShellState *p){
       const char *zName;
       int op;
     } aDbConfig[] = {
+        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
+        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
+        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
+        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
+        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
+        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
-        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
-        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
-        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
+        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
+        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
-        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
-        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
-        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
     };
     int ii, v;
     open_db(p, 0);
@@ -15707,7 +17670,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         sqlite3_db_config(p->db, aDbConfig[ii].op, booleanValue(azArg[2]), 0);
       }
       sqlite3_db_config(p->db, aDbConfig[ii].op, -1, &v);
-      utf8_printf(p->out, "%18s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
+      utf8_printf(p->out, "%19s %s\n", aDbConfig[ii].zName, v ? "on" : "off");
       if( nArg>1 ) break;
     }
     if( nArg>1 && ii==ArraySize(aDbConfig) ){
@@ -15728,11 +17691,14 @@ static int do_meta_command(char *zLine, ShellState *p){
 #endif /* !(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_ENABLE_DBPAGE_VTAB) */
 
   if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){
-    const char *zLike = 0;
+    char *zLike = 0;
+    char *zSql;
     int i;
     int savedShowHeader = p->showHeader;
     int savedShellFlags = p->shellFlgs;
-    ShellClearFlag(p, SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo);
+    ShellClearFlag(p, 
+       SHFLG_PreserveRowid|SHFLG_Newlines|SHFLG_Echo
+       |SHFLG_DumpDataOnly|SHFLG_DumpNoSys);
     for(i=1; i<nArg; i++){
       if( azArg[i][0]=='-' ){
         const char *z = azArg[i]+1;
@@ -15742,6 +17708,7 @@ static int do_meta_command(char *zLine, ShellState *p){
           raw_printf(stderr, "The --preserve-rowids option is not compatible"
                              " with SQLITE_OMIT_VIRTUALTABLE\n");
           rc = 1;
+          sqlite3_free(zLike);
           goto meta_command_exit;
 #else
           ShellSetFlag(p, SHFLG_PreserveRowid);
@@ -15750,71 +17717,72 @@ static int do_meta_command(char *zLine, ShellState *p){
         if( strcmp(z,"newlines")==0 ){
           ShellSetFlag(p, SHFLG_Newlines);
         }else
+        if( strcmp(z,"data-only")==0 ){
+          ShellSetFlag(p, SHFLG_DumpDataOnly);
+        }else
+        if( strcmp(z,"nosys")==0 ){
+          ShellSetFlag(p, SHFLG_DumpNoSys);
+        }else
         {
           raw_printf(stderr, "Unknown option \"%s\" on \".dump\"\n", azArg[i]);
           rc = 1;
+          sqlite3_free(zLike);
           goto meta_command_exit;
         }
       }else if( zLike ){
-        raw_printf(stderr, "Usage: .dump ?--preserve-rowids? "
-                           "?--newlines? ?LIKE-PATTERN?\n");
-        rc = 1;
-        goto meta_command_exit;
+        zLike = sqlite3_mprintf("%z OR name LIKE %Q ESCAPE '\\'",
+                zLike, azArg[i]);
       }else{
-        zLike = azArg[i];
+        zLike = sqlite3_mprintf("name LIKE %Q ESCAPE '\\'", azArg[i]);
       }
     }
 
     open_db(p, 0);
 
-    /* When playing back a "dump", the content might appear in an order
-    ** which causes immediate foreign key constraints to be violated.
-    ** So disable foreign-key constraint enforcement to prevent problems. */
-    raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
-    raw_printf(p->out, "BEGIN TRANSACTION;\n");
+    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
+      /* When playing back a "dump", the content might appear in an order
+      ** which causes immediate foreign key constraints to be violated.
+      ** So disable foreign-key constraint enforcement to prevent problems. */
+      raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n");
+      raw_printf(p->out, "BEGIN TRANSACTION;\n");
+    }
     p->writableSchema = 0;
     p->showHeader = 0;
     /* Set writable_schema=ON since doing so forces SQLite to initialize
-    ** as much of the schema as it can even if the sqlite_master table is
+    ** as much of the schema as it can even if the sqlite_schema table is
     ** corrupt. */
     sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0);
     p->nErr = 0;
-    if( zLike==0 ){
-      run_schema_dump_query(p,
-        "SELECT name, type, sql FROM sqlite_master "
-        "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'"
-      );
-      run_schema_dump_query(p,
-        "SELECT name, type, sql FROM sqlite_master "
-        "WHERE name=='sqlite_sequence'"
-      );
-      run_table_dump_query(p,
-        "SELECT sql FROM sqlite_master "
-        "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0
-      );
-    }else{
-      char *zSql;
-      zSql = sqlite3_mprintf(
-        "SELECT name, type, sql FROM sqlite_master "
-        "WHERE tbl_name LIKE %Q AND type=='table'"
-        "  AND sql NOT NULL", zLike);
-      run_schema_dump_query(p,zSql);
-      sqlite3_free(zSql);
+    if( zLike==0 ) zLike = sqlite3_mprintf("true");
+    zSql = sqlite3_mprintf(
+      "SELECT name, type, sql FROM sqlite_schema "
+      "WHERE (%s) AND type=='table'"
+      "  AND sql NOT NULL"
+      " ORDER BY tbl_name='sqlite_sequence', rowid",
+      zLike
+    );
+    run_schema_dump_query(p,zSql);
+    sqlite3_free(zSql);
+    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
       zSql = sqlite3_mprintf(
-        "SELECT sql FROM sqlite_master "
-        "WHERE sql NOT NULL"
-        "  AND type IN ('index','trigger','view')"
-        "  AND tbl_name LIKE %Q", zLike);
-      run_table_dump_query(p, zSql, 0);
+        "SELECT sql FROM sqlite_schema "
+        "WHERE (%s) AND sql NOT NULL"
+        "  AND type IN ('index','trigger','view')",
+        zLike
+      );
+      run_table_dump_query(p, zSql);
       sqlite3_free(zSql);
     }
+    sqlite3_free(zLike);
     if( p->writableSchema ){
       raw_printf(p->out, "PRAGMA writable_schema=OFF;\n");
       p->writableSchema = 0;
     }
     sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0);
     sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
-    raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
+    if( (p->shellFlgs & SHFLG_DumpDataOnly)==0 ){
+      raw_printf(p->out, p->nErr?"ROLLBACK; -- due to errors\n":"COMMIT;\n");
+    }
     p->showHeader = savedShowHeader;
     p->shellFlgs = savedShellFlags;
   }else
@@ -15847,7 +17815,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         p->autoEQP = AUTOEQP_full;
         p->autoEQPtrace = 1;
         open_db(p, 0);
-        sqlite3_exec(p->db, "SELECT name FROM sqlite_master LIMIT 1", 0, 0, 0);
+        sqlite3_exec(p->db, "SELECT name FROM sqlite_schema LIMIT 1", 0, 0, 0);
         sqlite3_exec(p->db, "PRAGMA vdbe_trace=ON;", 0, 0, 0);
 #endif
       }else{
@@ -15901,15 +17869,17 @@ static int do_meta_command(char *zLine, ShellState *p){
        int ctrlCode;            /* Integer code for that option */
        const char *zUsage;      /* Usage notes */
     } aCtrl[] = {
-      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
       { "chunk_size",     SQLITE_FCNTL_CHUNK_SIZE,      "SIZE"           },
-   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
+      { "data_version",   SQLITE_FCNTL_DATA_VERSION,    ""               },
+      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
+      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
       { "persist_wal",    SQLITE_FCNTL_PERSIST_WAL,     "[BOOLEAN]"      },
-      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
    /* { "pragma",         SQLITE_FCNTL_PRAGMA,          "NAME ARG"       },*/
+      { "psow",       SQLITE_FCNTL_POWERSAFE_OVERWRITE, "[BOOLEAN]"      },
+      { "reserve_bytes",  SQLITE_FCNTL_RESERVE_BYTES,   "[N]"            },
+      { "size_limit",     SQLITE_FCNTL_SIZE_LIMIT,      "[LIMIT]"        },
       { "tempfilename",   SQLITE_FCNTL_TEMPFILENAME,    ""               },
-      { "has_moved",      SQLITE_FCNTL_HAS_MOVED,       ""               },  
-      { "lock_timeout",   SQLITE_FCNTL_LOCK_TIMEOUT,    "MILLISEC"       },
+   /* { "win32_av_retry", SQLITE_FCNTL_WIN32_AV_RETRY,  "COUNT DELAY"    },*/
     };
     int filectrl = -1;
     int iCtrl = -1;
@@ -15917,10 +17887,21 @@ static int do_meta_command(char *zLine, ShellState *p){
     int isOk = 0;            /* 0: usage  1: %lld  2: no-result */
     int n2, i;
     const char *zCmd = 0;
+    const char *zSchema = 0;
 
     open_db(p, 0);
     zCmd = nArg>=2 ? azArg[1] : "help";
 
+    if( zCmd[0]=='-' 
+     && (strcmp(zCmd,"--schema")==0 || strcmp(zCmd,"-schema")==0)
+     && nArg>=4
+    ){
+      zSchema = azArg[2];
+      for(i=3; i<nArg; i++) azArg[i-2] = azArg[i];
+      nArg -= 2;
+      zCmd = azArg[1];
+    }
+
     /* The argument can optionally begin with "-" or "--" */
     if( zCmd[0]=='-' && zCmd[1] ){
       zCmd++;
@@ -15962,7 +17943,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         case SQLITE_FCNTL_SIZE_LIMIT: {
           if( nArg!=2 && nArg!=3 ) break;
           iRes = nArg==3 ? integerValue(azArg[2]) : -1;
-          sqlite3_file_control(p->db, 0, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
+          sqlite3_file_control(p->db, zSchema, SQLITE_FCNTL_SIZE_LIMIT, &iRes);
           isOk = 1;
           break;
         }
@@ -15971,7 +17952,7 @@ static int do_meta_command(char *zLine, ShellState *p){
           int x;
           if( nArg!=3 ) break;
           x = (int)integerValue(azArg[2]);
-          sqlite3_file_control(p->db, 0, filectrl, &x);
+          sqlite3_file_control(p->db, zSchema, filectrl, &x);
           isOk = 2;
           break;
         }
@@ -15980,15 +17961,16 @@ static int do_meta_command(char *zLine, ShellState *p){
           int x;
           if( nArg!=2 && nArg!=3 ) break;
           x = nArg==3 ? booleanValue(azArg[2]) : -1;
-          sqlite3_file_control(p->db, 0, filectrl, &x);
+          sqlite3_file_control(p->db, zSchema, filectrl, &x);
           iRes = x;
           isOk = 1;
           break;
         }
+        case SQLITE_FCNTL_DATA_VERSION:
         case SQLITE_FCNTL_HAS_MOVED: {
           int x;
           if( nArg!=2 ) break;
-          sqlite3_file_control(p->db, 0, filectrl, &x);
+          sqlite3_file_control(p->db, zSchema, filectrl, &x);
           iRes = x;
           isOk = 1;
           break;
@@ -15996,7 +17978,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         case SQLITE_FCNTL_TEMPFILENAME: {
           char *z = 0;
           if( nArg!=2 ) break;
-          sqlite3_file_control(p->db, 0, filectrl, &z);
+          sqlite3_file_control(p->db, zSchema, filectrl, &z);
           if( z ){
             utf8_printf(p->out, "%s\n", z);
             sqlite3_free(z);
@@ -16004,6 +17986,18 @@ static int do_meta_command(char *zLine, ShellState *p){
           isOk = 2;
           break;
         }
+        case SQLITE_FCNTL_RESERVE_BYTES: {
+          int x;
+          if( nArg>=3 ){
+            x = atoi(azArg[2]);
+            sqlite3_file_control(p->db, zSchema, filectrl, &x);
+          }
+          x = -1;
+          sqlite3_file_control(p->db, zSchema, filectrl, &x);
+          utf8_printf(p->out,"%d\n", x);
+          isOk = 2;
+          break;
+        }
       }
     }
     if( isOk==0 && iCtrl>=0 ){
@@ -16036,8 +18030,8 @@ static int do_meta_command(char *zLine, ShellState *p){
     rc = sqlite3_exec(p->db,
        "SELECT sql FROM"
        "  (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x"
-       "     FROM sqlite_master UNION ALL"
-       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) "
+       "     FROM sqlite_schema UNION ALL"
+       "   SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_schema) "
        "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' "
        "ORDER BY rowid",
        callback, &data, &zErrMsg
@@ -16045,7 +18039,7 @@ static int do_meta_command(char *zLine, ShellState *p){
     if( rc==SQLITE_OK ){
       sqlite3_stmt *pStmt;
       rc = sqlite3_prepare_v2(p->db,
-               "SELECT rowid FROM sqlite_master"
+               "SELECT rowid FROM sqlite_schema"
                " WHERE name GLOB 'sqlite_stat[134]'",
                -1, &pStmt, 0);
       doStats = sqlite3_step(pStmt)==SQLITE_ROW;
@@ -16054,19 +18048,20 @@ static int do_meta_command(char *zLine, ShellState *p){
     if( doStats==0 ){
       raw_printf(p->out, "/* No STAT tables available */\n");
     }else{
-      raw_printf(p->out, "ANALYZE sqlite_master;\n");
-      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'",
+      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
+      sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_schema'",
                    callback, &data, &zErrMsg);
       data.cMode = data.mode = MODE_Insert;
       data.zDestTable = (char *)"sqlite_stat4";
       shell_exec(&data, "SELECT * FROM sqlite_stat4", &zErrMsg);
-      raw_printf(p->out, "ANALYZE sqlite_master;\n");
+      raw_printf(p->out, "ANALYZE sqlite_schema;\n");
     }
   }else
 
   if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){
     if( nArg==2 ){
       p->showHeader = booleanValue(azArg[1]);
+      p->shellFlgs |= SHFLG_HeaderSet;
     }else{
       raw_printf(stderr, "Usage: .headers on|off\n");
       rc = 1;
@@ -16085,8 +18080,8 @@ static int do_meta_command(char *zLine, ShellState *p){
   }else
 
   if( c=='i' && strncmp(azArg[0], "import", n)==0 ){
-    char *zTable;               /* Insert data into this table */
-    char *zFile;                /* Name of file to extra content from */
+    char *zTable = 0;           /* Insert data into this table */
+    char *zFile = 0;            /* Name of file to extra content from */
     sqlite3_stmt *pStmt = NULL; /* A statement */
     int nCol;                   /* Number of columns in the table */
     int nByte;                  /* Number of bytes in an SQL string */
@@ -16096,82 +18091,146 @@ static int do_meta_command(char *zLine, ShellState *p){
     char *zSql;                 /* An SQL statement */
     ImportCtx sCtx;             /* Reader context */
     const char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */
-    int (SQLITE_CDECL *xCloser)(FILE*);      /* Func to close file */
+    int eVerbose = 0;           /* Larger for more console output */
+    int nSkip = 0;              /* Initial lines to skip */
+    int useOutputMode = 1;      /* Use output mode to determine separators */
 
-    if( nArg!=3 ){
-      raw_printf(stderr, "Usage: .import FILE TABLE\n");
-      goto meta_command_exit;
-    }
-    zFile = azArg[1];
-    zTable = azArg[2];
-    seenInterrupt = 0;
     memset(&sCtx, 0, sizeof(sCtx));
-    open_db(p, 0);
-    nSep = strlen30(p->colSeparator);
-    if( nSep==0 ){
-      raw_printf(stderr,
-                 "Error: non-null column separator required for import\n");
-      return 1;
+    if( p->mode==MODE_Ascii ){
+      xRead = ascii_read_one_field;
+    }else{
+      xRead = csv_read_one_field;
     }
-    if( nSep>1 ){
-      raw_printf(stderr, "Error: multi-character column separators not allowed"
-                      " for import\n");
-      return 1;
+    for(i=1; i<nArg; i++){
+      char *z = azArg[i];
+      if( z[0]=='-' && z[1]=='-' ) z++;
+      if( z[0]!='-' ){
+        if( zFile==0 ){
+          zFile = z;
+        }else if( zTable==0 ){
+          zTable = z;
+        }else{
+          utf8_printf(p->out, "ERROR: extra argument: \"%s\".  Usage:\n", z);
+          showHelp(p->out, "import");
+          rc = 1;
+          goto meta_command_exit;
+        }
+      }else if( strcmp(z,"-v")==0 ){
+        eVerbose++;
+      }else if( strcmp(z,"-skip")==0 && i<nArg-1 ){
+        nSkip = integerValue(azArg[++i]);
+      }else if( strcmp(z,"-ascii")==0 ){
+        sCtx.cColSep = SEP_Unit[0];
+        sCtx.cRowSep = SEP_Record[0];
+        xRead = ascii_read_one_field;
+        useOutputMode = 0;
+      }else if( strcmp(z,"-csv")==0 ){
+        sCtx.cColSep = ',';
+        sCtx.cRowSep = '\n';
+        xRead = csv_read_one_field;
+        useOutputMode = 0;
+      }else{
+        utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n", z);
+        showHelp(p->out, "import");
+        rc = 1;
+        goto meta_command_exit;
+      }
     }
-    nSep = strlen30(p->rowSeparator);
-    if( nSep==0 ){
-      raw_printf(stderr, "Error: non-null row separator required for import\n");
-      return 1;
+    if( zTable==0 ){
+      utf8_printf(p->out, "ERROR: missing %s argument. Usage:\n",
+                  zFile==0 ? "FILE" : "TABLE");
+      showHelp(p->out, "import");
+      rc = 1;
+      goto meta_command_exit;
     }
-    if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){
-      /* When importing CSV (only), if the row separator is set to the
-      ** default output row separator, change it to the default input
-      ** row separator.  This avoids having to maintain different input
-      ** and output row separators. */
-      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
+    seenInterrupt = 0;
+    open_db(p, 0);
+    if( useOutputMode ){
+      /* If neither the --csv or --ascii options are specified, then set
+      ** the column and row separator characters from the output mode. */
+      nSep = strlen30(p->colSeparator);
+      if( nSep==0 ){
+        raw_printf(stderr,
+                   "Error: non-null column separator required for import\n");
+        rc = 1;
+        goto meta_command_exit;
+      }
+      if( nSep>1 ){
+        raw_printf(stderr, 
+              "Error: multi-character column separators not allowed"
+              " for import\n");
+        rc = 1;
+        goto meta_command_exit;
+      }
       nSep = strlen30(p->rowSeparator);
-    }
-    if( nSep>1 ){
-      raw_printf(stderr, "Error: multi-character row separators not allowed"
-                      " for import\n");
-      return 1;
+      if( nSep==0 ){
+        raw_printf(stderr,
+            "Error: non-null row separator required for import\n");
+        rc = 1;
+        goto meta_command_exit;
+      }
+      if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator,SEP_CrLf)==0 ){
+        /* When importing CSV (only), if the row separator is set to the
+        ** default output row separator, change it to the default input
+        ** row separator.  This avoids having to maintain different input
+        ** and output row separators. */
+        sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
+        nSep = strlen30(p->rowSeparator);
+      }
+      if( nSep>1 ){
+        raw_printf(stderr, "Error: multi-character row separators not allowed"
+                           " for import\n");
+        rc = 1;
+        goto meta_command_exit;
+      }
+      sCtx.cColSep = p->colSeparator[0];
+      sCtx.cRowSep = p->rowSeparator[0];
     }
     sCtx.zFile = zFile;
     sCtx.nLine = 1;
     if( sCtx.zFile[0]=='|' ){
 #ifdef SQLITE_OMIT_POPEN
       raw_printf(stderr, "Error: pipes are not supported in this OS\n");
-      return 1;
+      rc = 1;
+      goto meta_command_exit;
 #else
       sCtx.in = popen(sCtx.zFile+1, "r");
       sCtx.zFile = "<pipe>";
-      xCloser = pclose;
+      sCtx.xCloser = pclose;
 #endif
     }else{
       sCtx.in = fopen(sCtx.zFile, "rb");
-      xCloser = fclose;
-    }
-    if( p->mode==MODE_Ascii ){
-      xRead = ascii_read_one_field;
-    }else{
-      xRead = csv_read_one_field;
+      sCtx.xCloser = fclose;
     }
     if( sCtx.in==0 ){
       utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile);
-      return 1;
+      rc = 1;
+      goto meta_command_exit;
     }
-    sCtx.cColSep = p->colSeparator[0];
-    sCtx.cRowSep = p->rowSeparator[0];
-    zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
+    if( eVerbose>=2 || (eVerbose>=1 && useOutputMode) ){
+      char zSep[2];
+      zSep[1] = 0;
+      zSep[0] = sCtx.cColSep;
+      utf8_printf(p->out, "Column separator ");
+      output_c_string(p->out, zSep);
+      utf8_printf(p->out, ", row separator ");
+      zSep[0] = sCtx.cRowSep;
+      output_c_string(p->out, zSep);
+      utf8_printf(p->out, "\n");
+    }
+    while( (nSkip--)>0 ){
+      while( xRead(&sCtx) && sCtx.cTerm==sCtx.cColSep ){}
+    }
+    zSql = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable);
     if( zSql==0 ){
-      xCloser(sCtx.in);
+      import_cleanup(&sCtx);
       shell_out_of_memory();
     }
     nByte = strlen30(zSql);
     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
     import_append_char(&sCtx, 0);    /* To ensure sCtx.z is allocated */
     if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){
-      char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
+      char *zCreate = sqlite3_mprintf("CREATE TABLE \"%w\"", zTable);
       char cSep = '(';
       while( xRead(&sCtx) ){
         zCreate = sqlite3_mprintf("%z%c\n  \"%w\" TEXT", zCreate, cSep, sCtx.z);
@@ -16180,20 +18239,23 @@ static int do_meta_command(char *zLine, ShellState *p){
       }
       if( cSep=='(' ){
         sqlite3_free(zCreate);
-        sqlite3_free(sCtx.z);
-        xCloser(sCtx.in);
+        import_cleanup(&sCtx);
         utf8_printf(stderr,"%s: empty file\n", sCtx.zFile);
-        return 1;
+        rc = 1;
+        goto meta_command_exit;
       }
       zCreate = sqlite3_mprintf("%z\n)", zCreate);
+      if( eVerbose>=1 ){
+        utf8_printf(p->out, "%s\n", zCreate);
+      }
       rc = sqlite3_exec(p->db, zCreate, 0, 0, 0);
       sqlite3_free(zCreate);
       if( rc ){
-        utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
+        utf8_printf(stderr, "CREATE TABLE \"%s\"(...) failed: %s\n", zTable,
                 sqlite3_errmsg(p->db));
-        sqlite3_free(sCtx.z);
-        xCloser(sCtx.in);
-        return 1;
+        import_cleanup(&sCtx);
+        rc = 1;
+        goto meta_command_exit;
       }
       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
     }
@@ -16201,8 +18263,9 @@ static int do_meta_command(char *zLine, ShellState *p){
     if( rc ){
       if (pStmt) sqlite3_finalize(pStmt);
       utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db));
-      xCloser(sCtx.in);
-      return 1;
+      import_cleanup(&sCtx);
+      rc = 1;
+      goto meta_command_exit;
     }
     nCol = sqlite3_column_count(pStmt);
     sqlite3_finalize(pStmt);
@@ -16210,7 +18273,7 @@ static int do_meta_command(char *zLine, ShellState *p){
     if( nCol==0 ) return 0; /* no columns, no error */
     zSql = sqlite3_malloc( nByte*2 + 20 + nCol*2 );
     if( zSql==0 ){
-      xCloser(sCtx.in);
+      import_cleanup(&sCtx);
       shell_out_of_memory();
     }
     sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable);
@@ -16221,13 +18284,17 @@ static int do_meta_command(char *zLine, ShellState *p){
     }
     zSql[j++] = ')';
     zSql[j] = 0;
+    if( eVerbose>=2 ){
+      utf8_printf(p->out, "Insert using: %s\n", zSql);
+    }
     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
     sqlite3_free(zSql);
     if( rc ){
       utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db));
       if (pStmt) sqlite3_finalize(pStmt);
-      xCloser(sCtx.in);
-      return 1;
+      import_cleanup(&sCtx);
+      rc = 1;
+      goto meta_command_exit;
     }
     needCommit = sqlite3_get_autocommit(p->db);
     if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0);
@@ -16270,14 +18337,21 @@ static int do_meta_command(char *zLine, ShellState *p){
         if( rc!=SQLITE_OK ){
           utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile,
                       startLine, sqlite3_errmsg(p->db));
+          sCtx.nErr++;
+        }else{
+          sCtx.nRow++;
         }
       }
     }while( sCtx.cTerm!=EOF );
 
-    xCloser(sCtx.in);
-    sqlite3_free(sCtx.z);
+    import_cleanup(&sCtx);
     sqlite3_finalize(pStmt);
     if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
+    if( eVerbose>0 ){
+      utf8_printf(p->out,
+          "Added %d rows with %d errors using %d lines of input\n",
+          sCtx.nRow, sCtx.nErr, sCtx.nLine-1);
+    }
   }else
 
 #ifndef SQLITE_UNTESTABLE
@@ -16286,10 +18360,19 @@ static int do_meta_command(char *zLine, ShellState *p){
     char *zCollist = 0;
     sqlite3_stmt *pStmt;
     int tnum = 0;
+    int isWO = 0;  /* True if making an imposter of a WITHOUT ROWID table */
+    int lenPK = 0; /* Length of the PRIMARY KEY string for isWO tables */
     int i;
     if( !(nArg==3 || (nArg==2 && sqlite3_stricmp(azArg[1],"off")==0)) ){
       utf8_printf(stderr, "Usage: .imposter INDEX IMPOSTER\n"
                           "       .imposter off\n");
+      /* Also allowed, but not documented:
+      **
+      **    .imposter TABLE IMPOSTER
+      **
+      ** where TABLE is a WITHOUT ROWID table.  In that case, the
+      ** imposter is another WITHOUT ROWID table with the columns in
+      ** storage order. */
       rc = 1;
       goto meta_command_exit;
     }
@@ -16298,19 +18381,22 @@ static int do_meta_command(char *zLine, ShellState *p){
       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 0, 1);
       goto meta_command_exit;
     }
-    zSql = sqlite3_mprintf("SELECT rootpage FROM sqlite_master"
-                           " WHERE name='%q' AND type='index'", azArg[1]);
+    zSql = sqlite3_mprintf(
+      "SELECT rootpage, 0 FROM sqlite_schema"
+      " WHERE name='%q' AND type='index'"
+      "UNION ALL "
+      "SELECT rootpage, 1 FROM sqlite_schema"
+      " WHERE name='%q' AND type='table'"
+      "   AND sql LIKE '%%without%%rowid%%'",
+      azArg[1], azArg[1]
+    );
     sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
     sqlite3_free(zSql);
     if( sqlite3_step(pStmt)==SQLITE_ROW ){
       tnum = sqlite3_column_int(pStmt, 0);
+      isWO = sqlite3_column_int(pStmt, 1);
     }
     sqlite3_finalize(pStmt);
-    if( tnum==0 ){
-      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
-      rc = 1;
-      goto meta_command_exit;
-    }
     zSql = sqlite3_mprintf("PRAGMA index_xinfo='%q'", azArg[1]);
     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
     sqlite3_free(zSql);
@@ -16327,6 +18413,9 @@ static int do_meta_command(char *zLine, ShellState *p){
           zCol = zLabel;
         }
       }
+      if( isWO && lenPK==0 && sqlite3_column_int(pStmt,5)==0 && zCollist ){
+        lenPK = (int)strlen(zCollist);
+      }
       if( zCollist==0 ){
         zCollist = sqlite3_mprintf("\"%w\"", zCol);
       }else{
@@ -16334,9 +18423,16 @@ static int do_meta_command(char *zLine, ShellState *p){
       }
     }
     sqlite3_finalize(pStmt);
+    if( i==0 || tnum==0 ){
+      utf8_printf(stderr, "no such index: \"%s\"\n", azArg[1]);
+      rc = 1;
+      sqlite3_free(zCollist);
+      goto meta_command_exit;
+    }
+    if( lenPK==0 ) lenPK = 100000;
     zSql = sqlite3_mprintf(
-          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%s))WITHOUT ROWID",
-          azArg[2], zCollist, zCollist);
+          "CREATE TABLE \"%w\"(%s,PRIMARY KEY(%.*s))WITHOUT ROWID",
+          azArg[2], zCollist, lenPK, zCollist);
     sqlite3_free(zCollist);
     rc = sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->db, "main", 1, tnum);
     if( rc==SQLITE_OK ){
@@ -16347,7 +18443,8 @@ static int do_meta_command(char *zLine, ShellState *p){
       }else{
         utf8_printf(stdout, "%s;\n", zSql);
         raw_printf(stdout,
-           "WARNING: writing to an imposter table will corrupt the index!\n"
+          "WARNING: writing to an imposter table will corrupt the \"%s\" %s!\n",
+          azArg[1], isWO ? "table" : "index"
         );
       }
     }else{
@@ -16486,6 +18583,9 @@ static int do_meta_command(char *zLine, ShellState *p){
       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
     }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){
       p->mode = MODE_Column;
+      if( (p->shellFlgs & SHFLG_HeaderSet)==0 ){
+        p->showHeader = 1;
+      }
       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
     }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){
       p->mode = MODE_List;
@@ -16509,15 +18609,26 @@ static int do_meta_command(char *zLine, ShellState *p){
       set_table_name(p, nArg>=3 ? azArg[2] : "table");
     }else if( c2=='q' && strncmp(azArg[1],"quote",n2)==0 ){
       p->mode = MODE_Quote;
+      sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
+      sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row);
     }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){
       p->mode = MODE_Ascii;
       sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit);
       sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record);
+    }else if( c2=='m' && strncmp(azArg[1],"markdown",n2)==0 ){
+      p->mode = MODE_Markdown;
+    }else if( c2=='t' && strncmp(azArg[1],"table",n2)==0 ){
+      p->mode = MODE_Table;
+    }else if( c2=='b' && strncmp(azArg[1],"box",n2)==0 ){
+      p->mode = MODE_Box;
+    }else if( c2=='j' && strncmp(azArg[1],"json",n2)==0 ){
+      p->mode = MODE_Json;
     }else if( nArg==1 ){
       raw_printf(p->out, "current output mode: %s\n", modeDescr[p->mode]);
     }else{
       raw_printf(stderr, "Error: mode should be one of: "
-         "ascii column csv html insert line list quote tabs tcl\n");
+         "ascii box column csv html insert json line list markdown "
+         "quote table tabs tcl\n");
       rc = 1;
     }
     p->cMode = p->mode;
@@ -16533,10 +18644,38 @@ static int do_meta_command(char *zLine, ShellState *p){
     }
   }else
 
+#ifdef SQLITE_DEBUG
+  if( c=='o' && strcmp(azArg[0],"oom")==0 ){
+    int i;
+    for(i=1; i<nArg; i++){
+      const char *z = azArg[i];
+      if( z[0]=='-' && z[1]=='-' ) z++;
+      if( strcmp(z,"-repeat")==0 ){
+        if( i==nArg-1 ){
+          raw_printf(p->out, "missing argument on \"%s\"\n", azArg[i]);
+          rc = 1;
+        }else{
+          oomRepeat = (int)integerValue(azArg[++i]);
+        }
+      }else if( IsDigit(z[0]) ){
+        oomCounter = (int)integerValue(azArg[i]);
+      }else{
+        raw_printf(p->out, "unknown argument: \"%s\"\n", azArg[i]);
+        raw_printf(p->out, "Usage: .oom [--repeat N] [M]\n");
+        rc = 1;
+      }
+    }
+    if( rc==0 ){
+      raw_printf(p->out, "oomCounter = %d\n", oomCounter);
+      raw_printf(p->out, "oomRepeat  = %d\n", oomRepeat);
+    }
+  }else
+#endif /* SQLITE_DEBUG */
+
   if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){
-    char *zNewFilename;  /* Name of the database file to open */
-    int iName = 1;       /* Index in azArg[] of the filename */
-    int newFlag = 0;     /* True to delete file before opening */
+    char *zNewFilename = 0;  /* Name of the database file to open */
+    int iName = 1;           /* Index in azArg[] of the filename */
+    int newFlag = 0;         /* True to delete file before opening */
     /* Close the existing database */
     session_close_all(p);
     close_db(p->db);
@@ -16545,9 +18684,10 @@ static int do_meta_command(char *zLine, ShellState *p){
     sqlite3_free(p->zFreeOnClose);
     p->zFreeOnClose = 0;
     p->openMode = SHELL_OPEN_UNSPEC;
+    p->openFlags = 0;
     p->szMax = 0;
     /* Check for command-line arguments */
-    for(iName=1; iName<nArg && azArg[iName][0]=='-'; iName++){
+    for(iName=1; iName<nArg; iName++){
       const char *z = azArg[iName];
       if( optionMatch(z,"new") ){
         newFlag = 1;
@@ -16559,6 +18699,8 @@ static int do_meta_command(char *zLine, ShellState *p){
         p->openMode = SHELL_OPEN_APPENDVFS;
       }else if( optionMatch(z, "readonly") ){
         p->openMode = SHELL_OPEN_READONLY;
+      }else if( optionMatch(z, "nofollow") ){
+        p->openFlags |= SQLITE_OPEN_NOFOLLOW;
 #ifdef SQLITE_ENABLE_DESERIALIZE
       }else if( optionMatch(z, "deserialize") ){
         p->openMode = SHELL_OPEN_DESERIALIZE;
@@ -16571,10 +18713,15 @@ static int do_meta_command(char *zLine, ShellState *p){
         utf8_printf(stderr, "unknown option: %s\n", z);
         rc = 1;
         goto meta_command_exit;
+      }else if( zNewFilename ){
+        utf8_printf(stderr, "extra argument: \"%s\"\n", z);
+        rc = 1;
+        goto meta_command_exit;
+      }else{
+        zNewFilename = sqlite3_mprintf("%s", z);
       }
     }
     /* If a filename is specified, try to open it first */
-    zNewFilename = nArg>iName ? sqlite3_mprintf("%s", azArg[iName]) : 0;
     if( zNewFilename || p->openMode==SHELL_OPEN_HEXDB ){
       if( newFlag ) shellDeleteFile(zNewFilename);
       p->zDbFilename = zNewFilename;
@@ -16597,42 +18744,66 @@ static int do_meta_command(char *zLine, ShellState *p){
         && (strncmp(azArg[0], "output", n)==0||strncmp(azArg[0], "once", n)==0))
    || (c=='e' && n==5 && strcmp(azArg[0],"excel")==0)
   ){
-    const char *zFile = nArg>=2 ? azArg[1] : "stdout";
+    const char *zFile = 0;
     int bTxtMode = 0;
-    if( azArg[0][0]=='e' ){
-      /* Transform the ".excel" command into ".once -x" */
-      nArg = 2;
-      azArg[0] = (char *)"once";
-      zFile = azArg[1] = (char *)"-x";
-      n = 4;
-    }
-    if( nArg>2 ){
-      utf8_printf(stderr, "Usage: .%s [-e|-x|FILE]\n", azArg[0]);
-      rc = 1;
-      goto meta_command_exit;
+    int i;
+    int eMode = 0;
+    int bBOM = 0;
+    int bOnce = 0;  /* 0: .output, 1: .once, 2: .excel */
+
+    if( c=='e' ){
+      eMode = 'x';
+      bOnce = 2;
+    }else if( strncmp(azArg[0],"once",n)==0 ){
+      bOnce = 1;
     }
-    if( n>1 && strncmp(azArg[0], "once", n)==0 ){
-      if( nArg<2 ){
-        raw_printf(stderr, "Usage: .once (-e|-x|FILE)\n");
+    for(i=1; i<nArg; i++){
+      char *z = azArg[i];
+      if( z[0]=='-' ){
+        if( z[1]=='-' ) z++;
+        if( strcmp(z,"-bom")==0 ){
+          bBOM = 1;
+        }else if( c!='e' && strcmp(z,"-x")==0 ){
+          eMode = 'x';  /* spreadsheet */
+        }else if( c!='e' && strcmp(z,"-e")==0 ){
+          eMode = 'e';  /* text editor */
+        }else{
+          utf8_printf(p->out, "ERROR: unknown option: \"%s\".  Usage:\n",
+                      azArg[i]);
+          showHelp(p->out, azArg[0]);
+          rc = 1;
+          goto meta_command_exit;
+        }
+      }else if( zFile==0 ){
+        zFile = z;
+      }else{
+        utf8_printf(p->out,"ERROR: extra parameter: \"%s\".  Usage:\n",
+                    azArg[i]);
+        showHelp(p->out, azArg[0]);
         rc = 1;
         goto meta_command_exit;
       }
+    }
+    if( zFile==0 ) zFile = "stdout";
+    if( bOnce ){
       p->outCount = 2;
     }else{
       p->outCount = 0;
     }
     output_reset(p);
-    if( zFile[0]=='-' && zFile[1]=='-' ) zFile++;
 #ifndef SQLITE_NOHAVE_SYSTEM
-    if( strcmp(zFile, "-e")==0 || strcmp(zFile, "-x")==0 ){
+    if( eMode=='e' || eMode=='x' ){
       p->doXdgOpen = 1;
       outputModePush(p);
-      if( zFile[1]=='x' ){
+      if( eMode=='x' ){
+        /* spreadsheet mode.  Output as CSV. */
         newTempFile(p, "csv");
+        ShellClearFlag(p, SHFLG_Echo);
         p->mode = MODE_Csv;
         sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma);
         sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf);
       }else{
+        /* text editor mode */
         newTempFile(p, "txt");
         bTxtMode = 1;
       }
@@ -16651,6 +18822,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         p->out = stdout;
         rc = 1;
       }else{
+        if( bBOM ) fprintf(p->out,"\357\273\277");
         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
       }
 #endif
@@ -16663,6 +18835,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         p->out = stdout;
         rc = 1;
       } else {
+        if( bBOM ) fprintf(p->out,"\357\273\277");
         sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile);
       }
     }
@@ -16848,8 +19021,16 @@ static int do_meta_command(char *zLine, ShellState *p){
       rc = 1;
       goto meta_command_exit;
     }
-    p->in = fopen(azArg[1], "rb");
-    if( p->in==0 ){
+    if( azArg[1][0]=='|' ){
+      p->in = popen(azArg[1]+1, "r");
+      if( p->in==0 ){
+        utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]);
+        rc = 1;
+      }else{
+        rc = process_input(p);
+        pclose(p->in);
+      }
+    }else if( notNormalFile(azArg[1]) || (p->in = fopen(azArg[1], "rb"))==0 ){
       utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]);
       rc = 1;
     }else{
@@ -16931,6 +19112,7 @@ static int do_meta_command(char *zLine, ShellState *p){
     const char *zName = 0;
     int iSchema = 0;
     int bDebug = 0;
+    int bNoSystemTabs = 0;
     int ii;
 
     open_db(p, 0);
@@ -16943,17 +19125,26 @@ static int do_meta_command(char *zLine, ShellState *p){
         data.cMode = data.mode = MODE_Pretty;
       }else if( optionMatch(azArg[ii],"debug") ){
         bDebug = 1;
+      }else if( optionMatch(azArg[ii],"nosys") ){
+        bNoSystemTabs = 1;
+      }else if( azArg[ii][0]=='-' ){
+        utf8_printf(stderr, "Unknown option: \"%s\"\n", azArg[ii]);
+        rc = 1;
+        goto meta_command_exit;
       }else if( zName==0 ){
         zName = azArg[ii];
       }else{
-        raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n");
+        raw_printf(stderr, "Usage: .schema ?--indent? ?--nosys? ?LIKE-PATTERN?\n");
         rc = 1;
         goto meta_command_exit;
       }
     }
     if( zName!=0 ){
-      int isMaster = sqlite3_strlike(zName, "sqlite_master", '\\')==0;
-      if( isMaster || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0 ){
+      int isSchema = sqlite3_strlike(zName, "sqlite_master", '\\')==0
+                  || sqlite3_strlike(zName, "sqlite_schema", '\\')==0
+                  || sqlite3_strlike(zName,"sqlite_temp_master", '\\')==0
+                  || sqlite3_strlike(zName,"sqlite_temp_schema", '\\')==0;
+      if( isSchema ){
         char *new_argv[2], *new_colv[2];
         new_argv[0] = sqlite3_mprintf(
                       "CREATE TABLE %s (\n"
@@ -16962,7 +19153,7 @@ static int do_meta_command(char *zLine, ShellState *p){
                       "  tbl_name text,\n"
                       "  rootpage integer,\n"
                       "  sql text\n"
-                      ")", isMaster ? "sqlite_master" : "sqlite_temp_master");
+                      ")", zName);
         new_argv[1] = 0;
         new_colv[0] = (char *)"sql";
         new_colv[1] = 0;
@@ -17000,7 +19191,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         appendText(&sSelect, zDb, '\'');
         appendText(&sSelect, " AS sname FROM ", 0);
         appendText(&sSelect, zDb, quoteChar(zDb));
-        appendText(&sSelect, ".sqlite_master", 0);
+        appendText(&sSelect, ".sqlite_schema", 0);
       }
       sqlite3_finalize(pStmt);
 #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
@@ -17029,7 +19220,10 @@ static int do_meta_command(char *zLine, ShellState *p){
         appendText(&sSelect, " AND ", 0);
         sqlite3_free(zQarg);
       }
-      appendText(&sSelect, "type!='meta' AND sql IS NOT NULL"
+      if( bNoSystemTabs ){
+        appendText(&sSelect, "name NOT LIKE 'sqlite_%%' AND ", 0);
+      }
+      appendText(&sSelect, "sql IS NOT NULL"
                            " ORDER BY snum, rowid", 0);
       if( bDebug ){
         utf8_printf(p->out, "SQL: %s;\n", sSelect.z);
@@ -17050,11 +19244,10 @@ static int do_meta_command(char *zLine, ShellState *p){
     }
   }else
 
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE)
   if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){
-    sqlite3SelectTrace = (int)integerValue(azArg[1]);
+    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
+    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 1, &x);
   }else
-#endif
 
 #if defined(SQLITE_ENABLE_SESSION)
   if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){
@@ -17444,12 +19637,12 @@ static int do_meta_command(char *zLine, ShellState *p){
       }
     }
     if( bSchema ){
-      zSql = (char *)"SELECT lower(name) FROM sqlite_master"
+      zSql = (char *)"SELECT lower(name) FROM sqlite_schema"
              " WHERE type='table' AND coalesce(rootpage,0)>1"
-             " UNION ALL SELECT 'sqlite_master'"
+             " UNION ALL SELECT 'sqlite_schema'"
              " ORDER BY 1 collate nocase";
     }else{
-      zSql = (char *)"SELECT lower(name) FROM sqlite_master"
+      zSql = (char *)"SELECT lower(name) FROM sqlite_schema"
              " WHERE type='table' AND coalesce(rootpage,0)>1"
              " AND name NOT LIKE 'sqlite_%'"
              " ORDER BY 1 collate nocase";
@@ -17466,8 +19659,8 @@ static int do_meta_command(char *zLine, ShellState *p){
         appendText(&sQuery,"SELECT * FROM ", 0);
         appendText(&sQuery,zTab,'"');
         appendText(&sQuery," NOT INDEXED;", 0);
-      }else if( strcmp(zTab, "sqlite_master")==0 ){
-        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_master"
+      }else if( strcmp(zTab, "sqlite_schema")==0 ){
+        appendText(&sQuery,"SELECT type,name,tbl_name,sql FROM sqlite_schema"
                            " ORDER BY name;", 0);
       }else if( strcmp(zTab, "sqlite_sequence")==0 ){
         appendText(&sQuery,"SELECT name,seq FROM sqlite_sequence"
@@ -17561,7 +19754,7 @@ static int do_meta_command(char *zLine, ShellState *p){
       raw_printf(p->out, "\n");
     utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]);
     utf8_printf(p->out, "%12.12s: ", "width");
-    for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) {
+    for (i=0;i<p->nWidth;i++) {
       raw_printf(p->out, "%d ", p->colWidth[i]);
     }
     raw_printf(p->out, "\n");
@@ -17618,7 +19811,7 @@ static int do_meta_command(char *zLine, ShellState *p){
         appendText(&s, "||'.'||name FROM ", 0);
       }
       appendText(&s, zDbName, '"');
-      appendText(&s, ".sqlite_master ", 0);
+      appendText(&s, ".sqlite_schema ", 0);
       if( c=='t' ){
         appendText(&s," WHERE type IN ('table','view')"
                       "   AND name NOT LIKE 'sqlite_%'"
@@ -17715,7 +19908,7 @@ static int do_meta_command(char *zLine, ShellState *p){
       { "extra_schema_checks",SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS,"BOOLEAN"   },
     /*{ "fault_install",      SQLITE_TESTCTRL_FAULT_INSTALL, ""             },*/
       { "imposter",         SQLITE_TESTCTRL_IMPOSTER, "SCHEMA ON/OFF ROOTPAGE"},
-      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "BOOLEAN"   },
+      { "internal_functions", SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, "" },
       { "localtime_fault",    SQLITE_TESTCTRL_LOCALTIME_FAULT,"BOOLEAN"       },
       { "never_corrupt",      SQLITE_TESTCTRL_NEVER_CORRUPT, "BOOLEAN"        },
       { "optimizations",      SQLITE_TESTCTRL_OPTIMIZATIONS, "DISABLE-MASK"   },
@@ -17726,7 +19919,7 @@ static int do_meta_command(char *zLine, ShellState *p){
       { "prng_restore",       SQLITE_TESTCTRL_PRNG_RESTORE,  ""               },
       { "prng_save",          SQLITE_TESTCTRL_PRNG_SAVE,     ""               },
       { "prng_seed",          SQLITE_TESTCTRL_PRNG_SEED,     "SEED ?db?"      },
-      { "reserve",            SQLITE_TESTCTRL_RESERVE,      "BYTES-OF-RESERVE"},
+      { "seek_count",         SQLITE_TESTCTRL_SEEK_COUNT,    ""               },
     };
     int testctrl = -1;
     int iCtrl = -1;
@@ -17779,7 +19972,6 @@ static int do_meta_command(char *zLine, ShellState *p){
 
         /* sqlite3_test_control(int, db, int) */
         case SQLITE_TESTCTRL_OPTIMIZATIONS:
-        case SQLITE_TESTCTRL_RESERVE:
           if( nArg==3 ){
             int opt = (int)strtol(azArg[2], 0, 0);
             rc2 = sqlite3_test_control(testctrl, p->db, opt);
@@ -17790,7 +19982,6 @@ static int do_meta_command(char *zLine, ShellState *p){
         /* sqlite3_test_control(int) */
         case SQLITE_TESTCTRL_PRNG_SAVE:
         case SQLITE_TESTCTRL_PRNG_RESTORE:
-        case SQLITE_TESTCTRL_PRNG_RESET:
         case SQLITE_TESTCTRL_BYTEORDER:
           if( nArg==2 ){
             rc2 = sqlite3_test_control(testctrl);
@@ -17831,7 +20022,6 @@ static int do_meta_command(char *zLine, ShellState *p){
         /* sqlite3_test_control(int, int) */
         case SQLITE_TESTCTRL_ASSERT:
         case SQLITE_TESTCTRL_ALWAYS:
-        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
           if( nArg==3 ){
             int opt = booleanValue(azArg[2]);
             rc2 = sqlite3_test_control(testctrl, opt);
@@ -17849,6 +20039,12 @@ static int do_meta_command(char *zLine, ShellState *p){
           }
           break;
 
+        /* sqlite3_test_control(sqlite3*) */
+        case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS:
+          rc2 = sqlite3_test_control(testctrl, p->db);
+          isOk = 3;
+          break;
+
         case SQLITE_TESTCTRL_IMPOSTER:
           if( nArg==5 ){
             rc2 = sqlite3_test_control(testctrl, p->db,
@@ -17859,6 +20055,14 @@ static int do_meta_command(char *zLine, ShellState *p){
           }
           break;
 
+        case SQLITE_TESTCTRL_SEEK_COUNT: {
+          u64 x = 0;
+          rc2 = sqlite3_test_control(testctrl, p->db, &x);
+          utf8_printf(p->out, "%llu\n", x);
+          isOk = 3;
+          break;
+        }
+
 #ifdef YYCOVERAGE
         case SQLITE_TESTCTRL_PARSER_COVERAGE:
           if( nArg==2 ){
@@ -18098,16 +20302,19 @@ static int do_meta_command(char *zLine, ShellState *p){
     }
   }else
 
-#if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE)
   if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){
-    sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff;
+    unsigned int x = nArg>=2 ? (unsigned int)integerValue(azArg[1]) : 0xffffffff;
+    sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, 3, &x);
   }else
-#endif
 
   if( c=='w' && strncmp(azArg[0], "width", n)==0 ){
     int j;
     assert( nArg<=ArraySize(azArg) );
-    for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
+    p->nWidth = nArg-1;
+    p->colWidth = realloc(p->colWidth, p->nWidth*sizeof(int)*2);
+    if( p->colWidth==0 && p->nWidth>0 ) shell_out_of_memory();
+    if( p->nWidth ) p->actualWidth = &p->colWidth[p->nWidth];
+    for(j=1; j<nArg; j++){
       p->colWidth[j-1] = (int)integerValue(azArg[j]);
     }
   }else
@@ -18433,8 +20640,11 @@ static void process_sqliterc(
     if( stdin_is_interactive ){
       utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc);
     }
-    process_input(p);
+    if( process_input(p) && bail_on_error ) exit(1);
     fclose(p->in);
+  }else if( sqliterc_override!=0 ){
+    utf8_printf(stderr,"cannot open: \"%s\"\n", sqliterc);
+    if( bail_on_error ) exit(1);
   }
   p->in = inSaved;
   p->lineno = savedLineno;
@@ -18452,6 +20662,7 @@ static const char zOptions[] =
   "   -ascii               set output mode to 'ascii'\n"
   "   -bail                stop after hitting an error\n"
   "   -batch               force batch I/O\n"
+  "   -box                 set output mode to 'box'\n"
   "   -column              set output mode to 'column'\n"
   "   -cmd COMMAND         run \"COMMAND\" before reading stdin\n"
   "   -csv                 set output mode to 'csv'\n"
@@ -18467,11 +20678,13 @@ static const char zOptions[] =
   "   -help                show this message\n"
   "   -html                set output mode to HTML\n"
   "   -interactive         force interactive I/O\n"
+  "   -json                set output mode to 'json'\n"
   "   -line                set output mode to 'line'\n"
   "   -list                set output mode to 'list'\n"
 #ifndef SQLITE_OMIT_LOOKASIDE
   "   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory\n"
 #endif
+  "   -markdown            set output mode to 'markdown'\n"
 #if defined(SQLITE_ENABLE_DESERIALIZE)
   "   -maxsize N           maximum size for a --deserialize database\n"
 #endif
@@ -18481,6 +20694,7 @@ static const char zOptions[] =
   "   -multiplex           enable the multiplexor VFS\n"
 #endif
   "   -newline SEP         set output row separator. Default: '\\n'\n"
+  "   -nofollow            refuse to open symbolic links to database files\n"
   "   -nullvalue TEXT      set text string for NULL values. Default ''\n"
   "   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory\n"
   "   -quote               set output mode to 'quote'\n"
@@ -18491,6 +20705,8 @@ static const char zOptions[] =
   "   -sorterref SIZE      sorter references threshold size\n"
 #endif
   "   -stats               print memory stats before each finalize\n"
+  "   -table               set output mode to 'table'\n"
+  "   -tabs                set output mode to 'tabs'\n"
   "   -version             show SQLite version\n"
   "   -vfs NAME            use NAME as the default VFS\n"
 #ifdef SQLITE_ENABLE_VFSTRACE
@@ -18548,14 +20764,18 @@ static void main_init(ShellState *data) {
 */
 #ifdef _WIN32
 static void printBold(const char *zText){
+#if !SQLITE_OS_WINRT
   HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
   CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo;
   GetConsoleScreenBufferInfo(out, &defaultScreenInfo);
   SetConsoleTextAttribute(out,
          FOREGROUND_RED|FOREGROUND_INTENSITY
   );
+#endif
   printf("%s", zText);
+#if !SQLITE_OS_WINRT
   SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes);
+#endif
 }
 #else
 static void printBold(const char *zText){
@@ -18614,6 +20834,10 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
   stdin_is_interactive = isatty(0);
   stdout_is_console = isatty(1);
 
+#ifdef SQLITE_DEBUG
+  registerOomSimulator();
+#endif
+
 #if !defined(_WIN32_WCE)
   if( getenv("SQLITE_DEBUG_BREAK") ){
     if( isatty(0) && isatty(2) ){
@@ -18623,7 +20847,11 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       fgetc(stdin);
     }else{
 #if defined(_WIN32) || defined(WIN32)
+#if SQLITE_OS_WINRT
+      __debugbreak();
+#else
       DebugBreak();
+#endif
 #elif defined(SIGTRAP)
       raise(SIGTRAP);
 #endif
@@ -18740,11 +20968,14 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       (void)cmdline_option_value(argc, argv, ++i);
 #endif
     }else if( strcmp(z,"-pagecache")==0 ){
-      int n, sz;
-      sz = (int)integerValue(cmdline_option_value(argc,argv,++i));
+      sqlite3_int64 n, sz;
+      sz = integerValue(cmdline_option_value(argc,argv,++i));
       if( sz>70000 ) sz = 70000;
       if( sz<0 ) sz = 0;
-      n = (int)integerValue(cmdline_option_value(argc,argv,++i));
+      n = integerValue(cmdline_option_value(argc,argv,++i));
+      if( sz>0 && n>0 && 0xffffffffffffLL/sz<n ){
+        n = 0xffffffffffffLL/sz;
+      }
       sqlite3_config(SQLITE_CONFIG_PAGECACHE,
                     (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n);
       data.shellFlgs |= SHFLG_Pagecache;
@@ -18796,6 +21027,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
 #endif
     }else if( strcmp(z,"-readonly")==0 ){
       data.openMode = SHELL_OPEN_READONLY;
+    }else if( strcmp(z,"-nofollow")==0 ){
+      data.openFlags = SQLITE_OPEN_NOFOLLOW;
 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_HAVE_ZLIB)
     }else if( strncmp(z, "-A",2)==0 ){
       /* All remaining command-line arguments are passed to the ".archive"
@@ -18804,6 +21037,8 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
 #endif
     }else if( strcmp(z, "-memtrace")==0 ){
       sqlite3MemTraceActivate(stderr);
+    }else if( strcmp(z,"-bail")==0 ){
+      bail_on_error = 1;
     }
   }
   verify_uninitialized();
@@ -18878,10 +21113,20 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       data.mode = MODE_List;
     }else if( strcmp(z,"-quote")==0 ){
       data.mode = MODE_Quote;
+      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Comma);
+      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
     }else if( strcmp(z,"-line")==0 ){
       data.mode = MODE_Line;
     }else if( strcmp(z,"-column")==0 ){
       data.mode = MODE_Column;
+    }else if( strcmp(z,"-json")==0 ){
+      data.mode = MODE_Json;
+    }else if( strcmp(z,"-markdown")==0 ){
+      data.mode = MODE_Markdown;
+    }else if( strcmp(z,"-table")==0 ){
+      data.mode = MODE_Table;
+    }else if( strcmp(z,"-box")==0 ){
+      data.mode = MODE_Box;
     }else if( strcmp(z,"-csv")==0 ){
       data.mode = MODE_Csv;
       memcpy(data.colSeparator,",",2);
@@ -18899,12 +21144,16 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
 #endif
     }else if( strcmp(z,"-readonly")==0 ){
       data.openMode = SHELL_OPEN_READONLY;
+    }else if( strcmp(z,"-nofollow")==0 ){
+      data.openFlags |= SQLITE_OPEN_NOFOLLOW;
     }else if( strcmp(z,"-ascii")==0 ){
       data.mode = MODE_Ascii;
-      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
-                       SEP_Unit);
-      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator,
-                       SEP_Record);
+      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit);
+      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record);
+    }else if( strcmp(z,"-tabs")==0 ){
+      data.mode = MODE_List;
+      sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Tab);
+      sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Row);
     }else if( strcmp(z,"-separator")==0 ){
       sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator,
                        "%s",cmdline_option_value(argc,argv,++i));
@@ -18936,7 +21185,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       */
       ShellSetFlag(&data, SHFLG_Backslash);
     }else if( strcmp(z,"-bail")==0 ){
-      bail_on_error = 1;
+      /* No-op.  The bail_on_error flag should already be set. */
     }else if( strcmp(z,"-version")==0 ){
       printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
       return 0;
@@ -19024,20 +21273,25 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
     for(i=0; i<nCmd; i++){
       if( azCmd[i][0]=='.' ){
         rc = do_meta_command(azCmd[i], &data);
-        if( rc ) return rc==2 ? 0 : rc;
+        if( rc ){
+          free(azCmd);
+          return rc==2 ? 0 : rc;
+        }
       }else{
         open_db(&data, 0);
         rc = shell_exec(&data, azCmd[i], &zErrMsg);
-        if( zErrMsg!=0 ){
-          utf8_printf(stderr,"Error: %s\n", zErrMsg);
+        if( zErrMsg || rc ){
+          if( zErrMsg!=0 ){
+            utf8_printf(stderr,"Error: %s\n", zErrMsg);
+          }else{
+            utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
+          }
+          sqlite3_free(zErrMsg);
+          free(azCmd);
           return rc!=0 ? rc : 1;
-        }else if( rc!=0 ){
-          utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]);
-          return rc;
         }
       }
     }
-    free(azCmd);
   }else{
     /* Run commands received from standard input
     */
@@ -19083,6 +21337,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
       rc = process_input(&data);
     }
   }
+  free(azCmd);
   set_table_name(&data, 0);
   if( data.db ){
     session_close_all(&data);
@@ -19097,6 +21352,7 @@ int SQLITE_CDECL wmain(int argc, wchar_t **wargv){
   for(i=0; i<argcToFree; i++) free(argvToFree[i]);
   free(argvToFree);
 #endif
+  free(data.colWidth);
   /* Clear the global data structure so that valgrind will detect memory
   ** leaks */
   memset(&data, 0, sizeof(data));
@@ -21,7 +21,7 @@ proc is_without_rowid {tname} {
   db eval "PRAGMA index_list = '$t'" o {
     if {$o(origin) == "pk"} {
       set n $o(name)
-      if {0==[db one { SELECT count(*) FROM sqlite_master WHERE name=$n }]} {
+      if {0==[db one { SELECT count(*) FROM sqlite_schema WHERE name=$n }]} {
         return 1
       }
     }
@@ -165,7 +165,7 @@ if {![db exists {SELECT 1 FROM pragma_compile_options
   exit 1
 }
 
-db eval {SELECT count(*) FROM sqlite_master}
+db eval {SELECT count(*) FROM sqlite_schema}
 set pageSize [expr {wide([db one {PRAGMA page_size}])}]
 
 if {$flags(-pageinfo)} {
@@ -250,8 +250,8 @@ db eval {DROP TABLE temp.stat}
 set isCompressed 0
 set compressOverhead 0
 set depth 0
-set sql { SELECT name, tbl_name FROM sqlite_master WHERE rootpage>0 }
-foreach {name tblname} [concat sqlite_master sqlite_master [db eval $sql]] {
+set sql { SELECT name, tbl_name FROM sqlite_schema WHERE rootpage>0 }
+foreach {name tblname} [concat sqlite_schema sqlite_schema [db eval $sql]] {
 
   set is_index [expr {$name!=$tblname}]
   set is_without_rowid [is_without_rowid $name]
@@ -565,7 +565,7 @@ proc autovacuum_overhead {filePages pageSize} {
 # nautoindex:    Number of indices created automatically.
 # nmanindex:     Number of indices created manually.
 # user_payload:  Number of bytes of payload in table btrees 
-#                (not including sqlite_master)
+#                (not including sqlite_schema)
 # user_percent:  $user_payload as a percentage of total file size.
 
 ### The following, setting $file_bytes based on the actual size of the file
@@ -592,15 +592,18 @@ set free_percent2 [percent $free_pgcnt2 $file_pgcnt]
 
 set file_pgcnt2 [expr {$inuse_pgcnt+$free_pgcnt2+$av_pgcnt}]
 
-set ntable [db eval {SELECT count(*)+1 FROM sqlite_master WHERE type='table'}]
-set nindex [db eval {SELECT count(*) FROM sqlite_master WHERE type='index'}]
-set sql {SELECT count(*) FROM sqlite_master WHERE name LIKE 'sqlite_autoindex%'}
+# Account for the lockbyte page
+if {$file_pgcnt2*$pageSize>1073742335} {incr file_pgcnt2}
+
+set ntable [db eval {SELECT count(*)+1 FROM sqlite_schema WHERE type='table'}]
+set nindex [db eval {SELECT count(*) FROM sqlite_schema WHERE type='index'}]
+set sql {SELECT count(*) FROM sqlite_schema WHERE name LIKE 'sqlite_autoindex%'}
 set nautoindex [db eval $sql]
 set nmanindex [expr {$nindex-$nautoindex}]
 
 # set total_payload [mem eval "SELECT sum(payload) FROM space_used"]
 set user_payload [mem one {SELECT int(sum(payload)) FROM space_used
-     WHERE NOT is_index AND name NOT LIKE 'sqlite_master'}]
+     WHERE NOT is_index AND name NOT LIKE 'sqlite_schema'}]
 set user_percent [percent $user_payload $file_bytes]
 
 # Output the summary statistics calculated above.
similarity index 91%
rename from pkgs/sqlite3.30.1.2/compat/sqlite3/sqlite3.c
rename to pkgs/sqlite3.34.0/compat/sqlite3/sqlite3.c
index bfe199e..d7595db 100644 (file)
@@ -1,6 +1,6 @@
 /******************************************************************************
 ** This file is an amalgamation of many separate C source files from SQLite
-** version 3.30.1.  By combining all the individual C code files into this
+** version 3.34.0.  By combining all the individual C code files into this
 ** single large file, the entire code can be compiled as a single translation
 ** unit.  This allows many compilers to do optimizations that would not be
 ** possible if the files were compiled separately.  Performance improvements
@@ -62,7 +62,7 @@
 #define CTIMEOPT_VAL2(opt) CTIMEOPT_VAL2_(opt)
 
 /*
-** An array of names of all compile-time options.  This array should 
+** An array of names of all compile-time options.  This array should
 ** be sorted A-Z.
 **
 ** This array looks large, but in a typical installation actually uses
@@ -71,8 +71,8 @@
 */
 static const char * const sqlite3azCompileOpt[] = {
 
-/* 
-** BEGIN CODE GENERATED BY tool/mkctime.tcl 
+/*
+** BEGIN CODE GENERATED BY tool/mkctime.tcl
 */
 #if SQLITE_32BIT_ROWID
   "32BIT_ROWID",
@@ -218,6 +218,9 @@ static const char * const sqlite3azCompileOpt[] = {
 #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
   "ENABLE_BATCH_ATOMIC_WRITE",
 #endif
+#if SQLITE_ENABLE_BYTECODE_VTAB
+  "ENABLE_BYTECODE_VTAB",
+#endif
 #if SQLITE_ENABLE_CEROD
   "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
 #endif
@@ -380,9 +383,6 @@ static const char * const sqlite3azCompileOpt[] = {
 #if SQLITE_FTS5_NO_WITHOUT_ROWID
   "FTS5_NO_WITHOUT_ROWID",
 #endif
-#if SQLITE_HAS_CODEC
-  "HAS_CODEC",
-#endif
 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
   "HAVE_ISNAN",
 #endif
@@ -539,9 +539,6 @@ static const char * const sqlite3azCompileOpt[] = {
 #if SQLITE_OMIT_BLOB_LITERAL
   "OMIT_BLOB_LITERAL",
 #endif
-#if SQLITE_OMIT_BTREECOUNT
-  "OMIT_BTREECOUNT",
-#endif
 #if SQLITE_OMIT_CAST
   "OMIT_CAST",
 #endif
@@ -777,8 +774,8 @@ static const char * const sqlite3azCompileOpt[] = {
 #if SQLITE_ZERO_MALLOC
   "ZERO_MALLOC",
 #endif
-/* 
-** END CODE GENERATED BY tool/mkctime.tcl 
+/*
+** END CODE GENERATED BY tool/mkctime.tcl
 */
 };
 
@@ -828,10 +825,10 @@ SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
 **
 **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
 **                                  that would be harmless and undetectable
-**                                  if it did occur.  
+**                                  if it did occur.
 **
 ** In all cases, the special comment must be enclosed in the usual
-** slash-asterisk...asterisk-slash comment marks, with no spaces between the 
+** slash-asterisk...asterisk-slash comment marks, with no spaces between the
 ** asterisks and the comment text.
 */
 
@@ -1004,6 +1001,15 @@ SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
 #endif
 
 /*
+** Macro to disable warnings about missing "break" at the end of a "case".
+*/
+#if GCC_VERSION>=7000000
+# define deliberate_fall_through __attribute__((fallthrough));
+#else
+# define deliberate_fall_through
+#endif
+
+/*
 ** For MinGW, check to see if we can include the header file containing its
 ** version information, among other things.  Normally, this internal MinGW
 ** header file would [only] be included automatically by other MinGW header
@@ -1151,7 +1157,7 @@ extern "C" {
 ** be held constant and Z will be incremented or else Y will be incremented
 ** and Z will be reset to zero.
 **
-** Since [version 3.6.18] ([dateof:3.6.18]), 
+** Since [version 3.6.18] ([dateof:3.6.18]),
 ** SQLite source code has been stored in the
 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
@@ -1166,9 +1172,9 @@ extern "C" {
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.30.1.2"
-#define SQLITE_VERSION_NUMBER 3030001
-#define SQLITE_SOURCE_ID      "2019-10-10 20:19:45 18db032d058f1436ce3dea84081f4ee5a0f2259ad97301d43c426bc7f3df1b0b"
+#define SQLITE_VERSION        "3.34.0"
+#define SQLITE_VERSION_NUMBER 3034000
+#define SQLITE_SOURCE_ID      "2020-12-01 16:14:00 a26b6597e3ae272231b96f9982c3bcc17ddec2f2b6eb4df06a224b91089fed5b"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
@@ -1194,8 +1200,8 @@ extern "C" {
 ** function is provided for use in DLLs since DLL users usually do not have
 ** direct access to string constants within the DLL.  ^The
 ** sqlite3_libversion_number() function returns an integer equal to
-** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns 
-** a pointer to a string constant whose value is the same as the 
+** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns
+** a pointer to a string constant whose value is the same as the
 ** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
 ** using an edited copy of [the amalgamation], then the last four characters
 ** of the hash might be different from [SQLITE_SOURCE_ID].)^
@@ -1210,20 +1216,20 @@ SQLITE_API int sqlite3_libversion_number(void);
 /*
 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
 **
-** ^The sqlite3_compileoption_used() function returns 0 or 1 
-** indicating whether the specified option was defined at 
-** compile time.  ^The SQLITE_ prefix may be omitted from the 
-** option name passed to sqlite3_compileoption_used().  
+** ^The sqlite3_compileoption_used() function returns 0 or 1
+** indicating whether the specified option was defined at
+** compile time.  ^The SQLITE_ prefix may be omitted from the
+** option name passed to sqlite3_compileoption_used().
 **
 ** ^The sqlite3_compileoption_get() function allows iterating
 ** over the list of options that were defined at compile time by
 ** returning the N-th compile time option string.  ^If N is out of range,
-** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
-** prefix is omitted from any strings returned by 
+** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
+** prefix is omitted from any strings returned by
 ** sqlite3_compileoption_get().
 **
 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
-** and sqlite3_compileoption_get() may be omitted by specifying the 
+** and sqlite3_compileoption_get() may be omitted by specifying the
 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
 **
 ** See also: SQL functions [sqlite_compileoption_used()] and
@@ -1247,7 +1253,7 @@ SQLITE_API const char *sqlite3_compileoption_get(int N);
 ** SQLite can be compiled with or without mutexes.  When
 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
 ** are enabled and SQLite is threadsafe.  When the
-** [SQLITE_THREADSAFE] macro is 0, 
+** [SQLITE_THREADSAFE] macro is 0,
 ** the mutexes are omitted.  Without the mutexes, it is not safe
 ** to use SQLite concurrently from more than one thread.
 **
@@ -1304,14 +1310,14 @@ typedef struct sqlite3 sqlite3;
 **
 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
-** sqlite3_uint64 and sqlite_uint64 types can store integer values 
+** sqlite3_uint64 and sqlite_uint64 types can store integer values
 ** between 0 and +18446744073709551615 inclusive.
 */
 #ifdef SQLITE_INT64_TYPE
   typedef SQLITE_INT64_TYPE sqlite_int64;
 # ifdef SQLITE_UINT64_TYPE
     typedef SQLITE_UINT64_TYPE sqlite_uint64;
-# else  
+# else
     typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
 # endif
 #elif defined(_MSC_VER) || defined(__BORLANDC__)
@@ -1342,26 +1348,22 @@ typedef sqlite_uint64 sqlite3_uint64;
 ** the [sqlite3] object is successfully destroyed and all associated
 ** resources are deallocated.
 **
-** ^If the database connection is associated with unfinalized prepared
-** statements or unfinished sqlite3_backup objects then sqlite3_close()
-** will leave the database connection open and return [SQLITE_BUSY].
-** ^If sqlite3_close_v2() is called with unfinalized prepared statements
-** and/or unfinished sqlite3_backups, then the database connection becomes
-** an unusable "zombie" which will automatically be deallocated when the
-** last prepared statement is finalized or the last sqlite3_backup is
-** finished.  The sqlite3_close_v2() interface is intended for use with
-** host languages that are garbage collected, and where the order in which
-** destructors are called is arbitrary.
-**
-** Applications should [sqlite3_finalize | finalize] all [prepared statements],
-** [sqlite3_blob_close | close] all [BLOB handles], and 
+** Ideally, applications should [sqlite3_finalize | finalize] all
+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
-** with the [sqlite3] object prior to attempting to close the object.  ^If
-** sqlite3_close_v2() is called on a [database connection] that still has
-** outstanding [prepared statements], [BLOB handles], and/or
-** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
-** of resources is deferred until all [prepared statements], [BLOB handles],
-** and [sqlite3_backup] objects are also destroyed.
+** with the [sqlite3] object prior to attempting to close the object.
+** ^If the database connection is associated with unfinalized prepared
+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
+** sqlite3_close() will leave the database connection open and return
+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
+** connection immediately, it marks the database connection as an unusable
+** "zombie" and makes arrangements to automatically deallocate the database
+** connection after all prepared statements are finalized, all BLOB handles
+** are closed, and all backups have finished. The sqlite3_close_v2() interface
+** is intended for use with host languages that are garbage collected, and
+** where the order in which destructors are called is arbitrary.
 **
 ** ^If an [sqlite3] object is destroyed while a transaction is open,
 ** the transaction is automatically rolled back.
@@ -1391,7 +1393,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);
 ** The sqlite3_exec() interface is a convenience wrapper around
 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
 ** that allows an application to run multiple statements of SQL
-** without having to use a lot of C code. 
+** without having to use a lot of C code.
 **
 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
 ** semicolon-separate SQL statements passed into its 2nd argument,
@@ -1431,7 +1433,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);
 ** from [sqlite3_column_name()].
 **
 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
-** to an empty string, or a pointer that contains only whitespace and/or 
+** to an empty string, or a pointer that contains only whitespace and/or
 ** SQL comments, then no SQL statements are evaluated and the database
 ** is not changed.
 **
@@ -1550,17 +1552,22 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
 #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
 #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
+#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))
+#define SQLITE_IOERR_CORRUPTFS         (SQLITE_IOERR | (33<<8))
 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
 #define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
+#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
 #define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
+#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))
 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
 #define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
+#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
@@ -1578,11 +1585,13 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
+#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
 #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
+#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))
 
 /*
 ** CAPI3REF: Flags For File Open Operations
@@ -1605,14 +1614,18 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
-#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
+#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */
 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
+#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
 
 /* Reserved:                         0x00F00000 */
+/* Legacy compatibility: */
+#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
+
 
 /*
 ** CAPI3REF: Device Characteristics
@@ -1709,7 +1722,7 @@ SQLITE_API int sqlite3_exec(
 /*
 ** CAPI3REF: OS Interface Open File Handle
 **
-** An [sqlite3_file] object represents an open file in the 
+** An [sqlite3_file] object represents an open file in the
 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
 ** implementations will
 ** want to subclass this object by appending additional fields
@@ -1731,7 +1744,7 @@ struct sqlite3_file {
 ** This object defines the methods used to perform various operations
 ** against the open file represented by the [sqlite3_file] object.
 **
-** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
@@ -1881,7 +1894,7 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
 ** extends and truncates the database file in chunks of a size specified
-** by the user. The fourth argument to [sqlite3_file_control()] should 
+** by the user. The fourth argument to [sqlite3_file_control()] should
 ** point to an integer (type int) containing the new chunk-size to use
 ** for the nominated database. Allocating database file space in large
 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
@@ -1904,24 +1917,24 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_SYNC]]
 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
 ** sent to the VFS immediately before the xSync method is invoked on a
-** database file descriptor. Or, if the xSync method is not invoked 
-** because the user has configured SQLite with 
-** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
+** database file descriptor. Or, if the xSync method is not invoked
+** because the user has configured SQLite with
+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
 ** of the xSync method. In most cases, the pointer argument passed with
 ** this file-control is NULL. However, if the database file is being synced
 ** as part of a multi-database commit, the argument points to a nul-terminated
-** string containing the transactions master-journal file name. VFSes that 
-** do not need this signal should silently ignore this opcode. Applications 
-** should not call [sqlite3_file_control()] with this opcode as doing so may 
-** disrupt the operation of the specialized VFSes that do require it.  
+** string containing the transactions super-journal file name. VFSes that
+** do not need this signal should silently ignore this opcode. Applications
+** should not call [sqlite3_file_control()] with this opcode as doing so may
+** disrupt the operation of the specialized VFSes that do require it.
 **
 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
 ** and sent to the VFS after a transaction has been committed immediately
 ** but before the database is unlocked. VFSes that do not need this signal
 ** should silently ignore this opcode. Applications should not call
-** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
-** operation of the specialized VFSes that do require it.  
+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
+** operation of the specialized VFSes that do require it.
 **
 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
@@ -1969,13 +1982,13 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
 ** a write transaction to indicate that, unless it is rolled back for some
-** reason, the entire database file will be overwritten by the current 
+** reason, the entire database file will be overwritten by the current
 ** transaction. This is used by VACUUM operations.
 **
 ** <li>[[SQLITE_FCNTL_VFSNAME]]
 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
-** final bottom-level VFS are written into memory obtained from 
+** final bottom-level VFS are written into memory obtained from
 ** [sqlite3_malloc()] and the result is stored in the char* variable
 ** that the fourth parameter of [sqlite3_file_control()] points to.
 ** The caller is responsible for freeing the memory when done.  As with
@@ -1994,7 +2007,7 @@ struct sqlite3_io_methods {
 ** upper-most shim only.
 **
 ** <li>[[SQLITE_FCNTL_PRAGMA]]
-** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
 ** file control is sent to the open [sqlite3_file] object corresponding
 ** to the database file to which the pragma statement refers. ^The argument
 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
@@ -2005,7 +2018,7 @@ struct sqlite3_io_methods {
 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
 ** or the equivalent and that string will become the result of the pragma or
 ** the error message if the pragma fails. ^If the
-** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
 ** file control returns [SQLITE_OK], then the parser assumes that the
 ** VFS has handled the PRAGMA itself and the parser generates a no-op
@@ -2022,16 +2035,16 @@ struct sqlite3_io_methods {
 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
 ** file-control may be invoked by SQLite on the database file handle
 ** shortly after it is opened in order to provide a custom VFS with access
-** to the connections busy-handler callback. The argument is of type (void **)
+** to the connection's busy-handler callback. The argument is of type (void**)
 ** - an array of two (void *) values. The first (void *) actually points
-** to a function of type (int (*)(void *)). In order to invoke the connections
+** to a function of type (int (*)(void *)). In order to invoke the connection's
 ** busy-handler, this function should be invoked with the second (void *) in
 ** the array as the only argument. If it returns non-zero, then the operation
 ** should be retried. If it returns zero, the custom VFS should abandon the
 ** current operation.
 **
 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
-** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
 ** to have SQLite generate a
 ** temporary filename using the same algorithm that is followed to generate
 ** temporary filenames for TEMP tables and other internal uses.  The
@@ -2045,7 +2058,7 @@ struct sqlite3_io_methods {
 ** The argument is a pointer to a value of type sqlite3_int64 that
 ** is an advisory maximum number of bytes in the file to memory map.  The
 ** pointer is overwritten with the old value.  The limit is not changed if
-** the value originally pointed to is negative, and so the current limit 
+** the value originally pointed to is negative, and so the current limit
 ** can be queried by passing in a pointer to a negative number.  This
 ** file-control is used internally to implement [PRAGMA mmap_size].
 **
@@ -2089,7 +2102,7 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_RBU]]
 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
 ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
-** this opcode.  
+** this opcode.
 **
 ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
 ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
@@ -2106,7 +2119,7 @@ struct sqlite3_io_methods {
 **
 ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
 ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to 
+** operations since the previous successful call to
 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
 ** This file control returns [SQLITE_OK] if and only if the writes were
 ** all performed successfully and have been committed to persistent storage.
@@ -2118,7 +2131,7 @@ struct sqlite3_io_methods {
 **
 ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
 ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to 
+** operations since the previous successful call to
 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
 ** ^This file control takes the file descriptor out of batch write mode
 ** so that all subsequent write operations are independent.
@@ -2126,10 +2139,12 @@ struct sqlite3_io_methods {
 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
 **
 ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
-** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
-** a file lock using the xLock or xShmLock methods of the VFS to wait
-** for up to M milliseconds before failing, where M is the single 
-** unsigned integer parameter.
+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
+** to block for up to M milliseconds before failing when attempting to
+** obtain a file lock using the xLock or xShmLock methods of the VFS.
+** The parameter is a pointer to a 32-bit signed integer that contains
+** the value that M is to be set to. Before returning, the 32-bit signed
+** integer is overwritten with the previous value of M.
 **
 ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
 ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
@@ -2144,12 +2159,23 @@ struct sqlite3_io_methods {
 ** not provide a mechanism to detect changes to MAIN only.  Also, the
 ** [sqlite3_total_changes()] interface responds to internal changes only and
 ** omits changes made by other database connections.  The
-** [PRAGMA data_version] command provide a mechanism to detect changes to
+** [PRAGMA data_version] command provides a mechanism to detect changes to
 ** a single attached database that occur due to other database connections,
 ** but omits changes implemented by the database connection on which it is
 ** called.  This file control is the only mechanism to detect changes that
 ** happen either internally or externally and that are associated with
 ** a particular attached database.
+**
+** <li>[[SQLITE_FCNTL_CKPT_START]]
+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
+** in wal mode before the client starts to copy pages from the wal
+** file to the database file.
+**
+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
+** in wal mode after the client has finished copying pages from the wal
+** file to the database file, but before the *-shm file is updated to
+** record the fact that the pages have been checkpointed.
 ** </ul>
 */
 #define SQLITE_FCNTL_LOCKSTATE               1
@@ -2187,6 +2213,9 @@ struct sqlite3_io_methods {
 #define SQLITE_FCNTL_LOCK_TIMEOUT           34
 #define SQLITE_FCNTL_DATA_VERSION           35
 #define SQLITE_FCNTL_SIZE_LIMIT             36
+#define SQLITE_FCNTL_CKPT_DONE              37
+#define SQLITE_FCNTL_RESERVE_BYTES          38
+#define SQLITE_FCNTL_CKPT_START             39
 
 /* deprecated names */
 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
@@ -2232,10 +2261,10 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields
 ** may be appended to the sqlite3_vfs object and the iVersion value
 ** may increase again in future versions of SQLite.
-** Note that the structure
-** of the sqlite3_vfs object changes in the transition from
+** Note that due to an oversight, the structure
+** of the sqlite3_vfs object changed in the transition from
 ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
-** and yet the iVersion field was not modified.
+** and yet the iVersion field was not increased.
 **
 ** The szOsFile field is the size of the subclassed [sqlite3_file]
 ** structure used by this VFS.  mxPathname is the maximum length of
@@ -2270,14 +2299,14 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** the [sqlite3_file] can safely store a pointer to the
 ** filename if it needs to remember the filename for some reason.
 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
-** must invent its own temporary name for the file.  ^Whenever the 
+** must invent its own temporary name for the file.  ^Whenever the
 ** xFilename parameter is NULL it will also be the case that the
 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
 **
 ** The flags argument to xOpen() includes all bits set in
 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
 ** or [sqlite3_open16()] is used, then flags includes at least
-** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
+** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
 ** If xOpen() opens a file read-only then it sets *pOutFlags to
 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
 **
@@ -2291,7 +2320,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
-** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
+** <li>  [SQLITE_OPEN_SUPER_JOURNAL]
 ** <li>  [SQLITE_OPEN_WAL]
 ** </ul>)^
 **
@@ -2319,14 +2348,14 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
-** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
+** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
 ** be created, and that it is an error if it already exists.
-** It is <i>not</i> used to indicate the file should be opened 
+** It is <i>not</i> used to indicate the file should be opened
 ** for exclusive access.
 **
 ** ^At least szOsFile bytes of memory are allocated by SQLite
-** to hold the  [sqlite3_file] structure passed as the third
+** to hold the [sqlite3_file] structure passed as the third
 ** argument to xOpen.  The xOpen method does not have to
 ** allocate the structure; it should just fill it in.  Note that
 ** the xOpen method must set the sqlite3_file.pMethods to either
@@ -2346,7 +2375,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** non-zero error code if there is an I/O error or if the name of
 ** the file given in the second argument is illegal.  If SQLITE_OK
 ** is returned, then non-zero or zero is written into *pResOut to indicate
-** whether or not the file is accessible.  
+** whether or not the file is accessible.
 **
 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
 ** output buffer xFullPathname.  The exact size of the output buffer
@@ -2366,16 +2395,16 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** method returns a Julian Day Number for the current date and time as
 ** a floating point value.
 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
-** Day Number multiplied by 86400000 (the number of milliseconds in 
-** a 24-hour day).  
+** Day Number multiplied by 86400000 (the number of milliseconds in
+** a 24-hour day).
 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
-** date and time if that method is available (if iVersion is 2 or 
+** date and time if that method is available (if iVersion is 2 or
 ** greater and the function pointer is not NULL) and will fall back
 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
 **
 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
 ** are not used by the SQLite core.  These optional interfaces are provided
-** by some VFSes to facilitate testing of the VFS code. By overriding 
+** by some VFSes to facilitate testing of the VFS code. By overriding
 ** system calls with functions under its control, a test program can
 ** simulate faults and error conditions that would otherwise be difficult
 ** or impossible to induce.  The set of system calls that can be overridden
@@ -2422,7 +2451,7 @@ struct sqlite3_vfs {
   /*
   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
   ** New fields may be appended in future versions.  The iVersion
-  ** value will increment whenever this happens. 
+  ** value will increment whenever this happens.
   */
 };
 
@@ -2466,7 +2495,7 @@ struct sqlite3_vfs {
 ** </ul>
 **
 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
-** was given on the corresponding lock.  
+** was given on the corresponding lock.
 **
 ** The xShmLock method can transition between unlocked and SHARED or
 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
@@ -2611,7 +2640,7 @@ SQLITE_API int sqlite3_config(int, ...);
 ** [database connection] (specified in the first argument).
 **
 ** The second argument to sqlite3_db_config(D,V,...)  is the
-** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
+** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
 ** that indicates what aspect of the [database connection] is being configured.
 ** Subsequent arguments vary depending on the configuration verb.
 **
@@ -2629,7 +2658,7 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
 ** This object is used in only one place in the SQLite interface.
 ** A pointer to an instance of this object is the argument to
 ** [sqlite3_config()] when the configuration option is
-** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
+** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
 ** By creating an instance of this object
 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
 ** during configuration, an application can specify an alternative
@@ -2659,17 +2688,17 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
 ** allocators round up memory allocations at least to the next multiple
 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
 ** Every memory allocation request coming in through [sqlite3_malloc()]
-** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
+** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
 ** that causes the corresponding memory allocation to fail.
 **
 ** The xInit method initializes the memory allocator.  For example,
-** it might allocate any require mutexes or initialize internal data
+** it might allocate any required mutexes or initialize internal data
 ** structures.  The xShutdown method is invoked (indirectly) by
 ** [sqlite3_shutdown()] and should deallocate any resources acquired
 ** by xInit.  The pAppData pointer is used as the only parameter to
 ** xInit and xShutdown.
 **
-** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
+** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
 ** the xInit method, so the xInit method need not be threadsafe.  The
 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
 ** not need to be threadsafe either.  For all other methods, SQLite
@@ -2717,7 +2746,7 @@ struct sqlite3_mem_methods {
 ** by a single thread.   ^If SQLite is compiled with
 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 ** it is not possible to change the [threading mode] from its default
-** value of Single-thread and so [sqlite3_config()] will return 
+** value of Single-thread and so [sqlite3_config()] will return
 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
 ** configuration option.</dd>
 **
@@ -2752,7 +2781,7 @@ struct sqlite3_mem_methods {
 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
 **
 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
-** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
+** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
 ** The argument specifies
 ** alternative low-level memory allocation routines to be used in place of
@@ -2785,6 +2814,7 @@ struct sqlite3_mem_methods {
 ** memory allocation statistics. ^(When memory allocation statistics are
 ** disabled, the following SQLite interfaces become non-operational:
 **   <ul>
+**   <li> [sqlite3_hard_heap_limit64()]
 **   <li> [sqlite3_memory_used()]
 **   <li> [sqlite3_memory_highwater()]
 **   <li> [sqlite3_soft_heap_limit64()]
@@ -2802,8 +2832,8 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
 ** that SQLite can use for the database page cache with the default page
-** cache implementation.  
-** This configuration option is a no-op if an application-define page
+** cache implementation.
+** This configuration option is a no-op if an application-defined page
 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
@@ -2830,7 +2860,7 @@ struct sqlite3_mem_methods {
 ** additional cache line. </dd>
 **
 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
-** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
+** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
 ** that SQLite will use for all of its dynamic memory allocation needs
 ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
@@ -2885,7 +2915,7 @@ struct sqlite3_mem_methods {
 ** configuration on individual connections.)^ </dd>
 **
 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
-** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
+** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
 ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
 ** the interface to a custom page cache implementation.)^
 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
@@ -2899,7 +2929,7 @@ struct sqlite3_mem_methods {
 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
 ** global [error log].
 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
-** function with a call signature of void(*)(void*,int,const char*), 
+** function with a call signature of void(*)(void*,int,const char*),
 ** and a pointer to void. ^If the function pointer is not NULL, it is
 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
@@ -3008,7 +3038,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
-** becomes the [statement journal] spill-to-disk threshold.  
+** becomes the [statement journal] spill-to-disk threshold.
 ** [Statement journals] are held in memory until their size (in bytes)
 ** exceeds this threshold, at which point they are written to disk.
 ** Or if the threshold is -1, statement journals are always held
@@ -3030,7 +3060,7 @@ struct sqlite3_mem_methods {
 ** than the configured sorter-reference size threshold - then a reference
 ** is stored in each sorted record and the required column values loaded
 ** from the database as records are returned in sorted order. The default
-** value for this option is to never use this optimization. Specifying a 
+** value for this option is to never use this optimization. Specifying a
 ** negative value for this option restores the default behaviour.
 ** This option is only available if SQLite is compiled with the
 ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
@@ -3058,7 +3088,7 @@ struct sqlite3_mem_methods {
 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
-/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
+/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
@@ -3093,7 +3123,7 @@ struct sqlite3_mem_methods {
 ** <dl>
 ** [[SQLITE_DBCONFIG_LOOKASIDE]]
 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
-** <dd> ^This option takes three additional arguments that determine the 
+** <dd> ^This option takes three additional arguments that determine the
 ** [lookaside memory allocator] configuration for the [database connection].
 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
 ** pointer to a memory buffer to use for lookaside memory.
@@ -3111,7 +3141,7 @@ struct sqlite3_mem_methods {
 ** when the "current value" returned by
 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
 ** Any attempt to change the lookaside memory configuration when lookaside
-** memory is in use leaves the configuration unchanged and returns 
+** memory is in use leaves the configuration unchanged and returns
 ** [SQLITE_BUSY].)^</dd>
 **
 ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
@@ -3188,11 +3218,11 @@ struct sqlite3_mem_methods {
 ** until after the database connection closes.
 ** </dd>
 **
-** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] 
+** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
 ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
-** <dd> Usually, when a database in wal mode is closed or detached from a 
-** database handle, SQLite checks if this will mean that there are now no 
-** connections at all to the database. If so, it performs a checkpoint 
+** <dd> Usually, when a database in wal mode is closed or detached from a
+** database handle, SQLite checks if this will mean that there are now no
+** connections at all to the database. If so, it performs a checkpoint
 ** operation before closing the connection. This option may be used to
 ** override this behaviour. The first parameter passed to this operation
 ** is an integer - positive to disable checkpoints-on-close, or zero (the
@@ -3211,7 +3241,7 @@ struct sqlite3_mem_methods {
 ** slower.  But the QPSG has the advantage of more predictable behavior.  With
 ** the QPSG active, SQLite will always use the same query plan in the field as
 ** was used during testing in the lab.
-** The first argument to this setting is an integer which is 0 to disable 
+** The first argument to this setting is an integer which is 0 to disable
 ** the QPSG, positive to enable QPSG, or negative to leave the setting
 ** unchanged. The second parameter is a pointer to an integer into which
 ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
@@ -3219,15 +3249,15 @@ struct sqlite3_mem_methods {
 ** </dd>
 **
 ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
-** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not 
+** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
 ** include output for any operations performed by trigger programs. This
 ** option is used to set or clear (the default) a flag that governs this
 ** behavior. The first parameter passed to this operation is an integer -
 ** positive to enable output for trigger programs, or zero to disable it,
 ** or negative to leave the setting unchanged.
-** The second parameter is a pointer to an integer into which is written 
-** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
-** it is not disabled, 1 if it is.  
+** The second parameter is a pointer to an integer into which is written
+** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
+** it is not disabled, 1 if it is.
 ** </dd>
 **
 ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
@@ -3241,7 +3271,7 @@ struct sqlite3_mem_methods {
 **      database, or calling sqlite3_table_column_metadata(), ignoring any
 **      errors.  This step is only necessary if the application desires to keep
 **      the database in WAL mode after the reset if it was in WAL mode before
-**      the reset.  
+**      the reset.
 ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
 ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
 ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
@@ -3253,7 +3283,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
 ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
 ** "defensive" flag for a database connection.  When the defensive
-** flag is enabled, language features that allow ordinary SQL to 
+** flag is enabled, language features that allow ordinary SQL to
 ** deliberately corrupt the database file are disabled.  The disabled
 ** features include but are not limited to the following:
 ** <ul>
@@ -3268,7 +3298,7 @@ struct sqlite3_mem_methods {
 ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
 ** "writable_schema" flag. This has the same effect and is logically equivalent
 ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
-** The first argument to this setting is an integer which is 0 to disable 
+** The first argument to this setting is an integer which is 0 to disable
 ** the writable_schema, positive to enable writable_schema, or negative to
 ** leave the setting unchanged. The second parameter is a pointer to an
 ** integer into which is written 0 or 1 to indicate whether the writable_schema
@@ -3288,7 +3318,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_DBCONFIG_DQS_DML]]
 ** <dt>SQLITE_DBCONFIG_DQS_DML</td>
 ** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
-** the legacy [double-quoted string literal] misfeature for DML statement
+** the legacy [double-quoted string literal] misfeature for DML statements
 ** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
 ** default value of this setting is determined by the [-DSQLITE_DQS]
 ** compile-time option.
@@ -3302,6 +3332,48 @@ struct sqlite3_mem_methods {
 ** default value of this setting is determined by the [-DSQLITE_DQS]
 ** compile-time option.
 ** </dd>
+**
+** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
+** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
+** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
+** assume that database schemas are untainted by malicious content.
+** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
+** takes additional defensive steps to protect the application from harm
+** including:
+** <ul>
+** <li> Prohibit the use of SQL functions inside triggers, views,
+** CHECK constraints, DEFAULT clauses, expression indexes,
+** partial indexes, or generated columns
+** unless those functions are tagged with [SQLITE_INNOCUOUS].
+** <li> Prohibit the use of virtual tables inside of triggers or views
+** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
+** </ul>
+** This setting defaults to "on" for legacy compatibility, however
+** all applications are advised to turn it off if possible. This setting
+** can also be controlled using the [PRAGMA trusted_schema] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
+** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
+** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
+** the legacy file format flag.  When activated, this flag causes all newly
+** created database file to have a schema format version number (the 4-byte
+** integer found at offset 44 into the database header) of 1.  This in turn
+** means that the resulting database file will be readable and writable by
+** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
+** newly created databases are generally not understandable by SQLite versions
+** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
+** is now scarcely any need to generated database files that are compatible
+** all the way back to version 3.0.0, and so this setting is of little
+** practical use, but is provided so that SQLite can continue to claim the
+** ability to generate new database files that are compatible with  version
+** 3.0.0.
+** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
+** the [VACUUM] command will fail with an obscure error when attempting to
+** process a table with generated columns and a descending index.  This is
+** not considered a bug since SQLite versions 3.3.0 and earlier do not support
+** either generated columns or decending indexes.
+** </dd>
 ** </dl>
 */
 #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
@@ -3320,7 +3392,9 @@ struct sqlite3_mem_methods {
 #define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
 #define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
 #define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
-#define SQLITE_DBCONFIG_MAX                   1015 /* Largest DBCONFIG */
+#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
+#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */
+#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */
 
 /*
 ** CAPI3REF: Enable Or Disable Extended Result Codes
@@ -3347,8 +3421,8 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
 ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
 ** the most recent successful [INSERT] into a rowid table or [virtual table]
 ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
-** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred 
-** on the database connection D, then sqlite3_last_insert_rowid(D) returns 
+** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
+** on the database connection D, then sqlite3_last_insert_rowid(D) returns
 ** zero.
 **
 ** As well as being set automatically as rows are inserted into database
@@ -3358,15 +3432,15 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
 ** Some virtual table implementations may INSERT rows into rowid tables as
 ** part of committing a transaction (e.g. to flush data accumulated in memory
 ** to disk). In this case subsequent calls to this function return the rowid
-** associated with these internal INSERT operations, which leads to 
+** associated with these internal INSERT operations, which leads to
 ** unintuitive results. Virtual table implementations that do write to rowid
-** tables in this way can avoid this problem by restoring the original 
-** rowid value using [sqlite3_set_last_insert_rowid()] before returning 
+** tables in this way can avoid this problem by restoring the original
+** rowid value using [sqlite3_set_last_insert_rowid()] before returning
 ** control to the user.
 **
-** ^(If an [INSERT] occurs within a trigger then this routine will 
-** return the [rowid] of the inserted row as long as the trigger is 
-** running. Once the trigger program ends, the value returned 
+** ^(If an [INSERT] occurs within a trigger then this routine will
+** return the [rowid] of the inserted row as long as the trigger is
+** running. Once the trigger program ends, the value returned
 ** by this routine reverts to what it was before the trigger was fired.)^
 **
 ** ^An [INSERT] that fails due to a constraint violation is not a
@@ -3399,7 +3473,7 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
 ** METHOD: sqlite3
 **
 ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
-** set the value returned by calling sqlite3_last_insert_rowid(D) to R 
+** set the value returned by calling sqlite3_last_insert_rowid(D) to R
 ** without inserting a row into the database.
 */
 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
@@ -3415,37 +3489,37 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** returned by this function.
 **
 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
-** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
+** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
-** 
-** Changes to a view that are intercepted by 
-** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
-** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
-** DELETE statement run on a view is always zero. Only changes made to real 
+**
+** Changes to a view that are intercepted by
+** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
+** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
+** DELETE statement run on a view is always zero. Only changes made to real
 ** tables are counted.
 **
 ** Things are more complicated if the sqlite3_changes() function is
 ** executed while a trigger program is running. This may happen if the
 ** program uses the [changes() SQL function], or if some other callback
 ** function invokes sqlite3_changes() directly. Essentially:
-** 
+**
 ** <ul>
 **   <li> ^(Before entering a trigger program the value returned by
-**        sqlite3_changes() function is saved. After the trigger program 
+**        sqlite3_changes() function is saved. After the trigger program
 **        has finished, the original value is restored.)^
-** 
-**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
-**        statement sets the value returned by sqlite3_changes() 
-**        upon completion as normal. Of course, this value will not include 
-**        any changes performed by sub-triggers, as the sqlite3_changes() 
+**
+**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
+**        statement sets the value returned by sqlite3_changes()
+**        upon completion as normal. Of course, this value will not include
+**        any changes performed by sub-triggers, as the sqlite3_changes()
 **        value will be saved and restored after each sub-trigger has run.)^
 ** </ul>
-** 
+**
 ** ^This means that if the changes() SQL function (or similar) is used
-** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
+** by the first INSERT, UPDATE or DELETE statement within a trigger, it
 ** returns the value as set when the calling statement began executing.
-** ^If it is used by the second or subsequent such statement within a trigger 
-** program, the value returned reflects the number of rows modified by the 
+** ^If it is used by the second or subsequent such statement within a trigger
+** program, the value returned reflects the number of rows modified by the
 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
 **
 ** If a separate thread makes changes on the same database connection
@@ -3473,10 +3547,10 @@ SQLITE_API sqlite3_uint64 sqlite3_changes(sqlite3*);
 ** since the database connection was opened, including those executed as
 ** part of trigger programs. ^Executing any other type of SQL statement
 ** does not affect the value returned by sqlite3_total_changes().
-** 
+**
 ** ^Changes made as part of [foreign key actions] are included in the
 ** count, but those made as part of REPLACE constraint resolution are
-** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
+** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
 ** are not counted.
 **
 ** The [sqlite3_total_changes(D)] interface only reports the number
@@ -3485,7 +3559,7 @@ SQLITE_API sqlite3_uint64 sqlite3_changes(sqlite3*);
 ** To detect changes against a database file from other database
 ** connections use the [PRAGMA data_version] command or the
 ** [SQLITE_FCNTL_DATA_VERSION] [file control].
-** 
+**
 ** If a separate thread makes changes on the same database connection
 ** while [sqlite3_total_changes()] is running then the value
 ** returned is unpredictable and not meaningful.
@@ -3529,8 +3603,8 @@ SQLITE_API sqlite3_uint64 sqlite3_total_changes(sqlite3*);
 **
 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
-** that are started after the sqlite3_interrupt() call and before the 
-** running statements reaches zero are interrupted as if they had been
+** that are started after the sqlite3_interrupt() call and before the
+** running statement count reaches zero are interrupted as if they had been
 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
 ** that are started after the running statement count reaches zero are
 ** not effected by the sqlite3_interrupt().
@@ -3561,7 +3635,7 @@ SQLITE_API void sqlite3_interrupt(sqlite3*);
 ** ^These routines do not parse the SQL statements thus
 ** will not detect syntactically incorrect SQL.
 **
-** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
+** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
 ** automatically by sqlite3_complete16().  If that initialization fails,
 ** then the return value from sqlite3_complete16() will be non-zero
@@ -3606,7 +3680,7 @@ SQLITE_API int sqlite3_complete16(const void *sql);
 ** The presence of a busy handler does not guarantee that it will be invoked
 ** when there is lock contention. ^If SQLite determines that invoking the busy
 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
-** to the application instead of invoking the 
+** to the application instead of invoking the
 ** busy handler.
 ** Consider a scenario where one process is holding a read lock that
 ** it is trying to promote to a reserved lock and
@@ -3631,7 +3705,7 @@ SQLITE_API int sqlite3_complete16(const void *sql);
 ** database connection that invoked the busy handler.  In other words,
 ** the busy handler is not reentrant.  Any such actions
 ** result in undefined behavior.
-** 
+**
 ** A busy handler must not close the database connection
 ** or [prepared statement] that invoked the busy handler.
 */
@@ -3698,9 +3772,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
 **        Cindy       | 21
 ** </pre></blockquote>
 **
-** There are two column (M==2) and three rows (N==3).  Thus the
+** There are two columns (M==2) and three rows (N==3).  Thus the
 ** result table has 8 entries.  Suppose the result table is stored
-** in an array names azResult.  Then azResult holds this content:
+** in an array named azResult.  Then azResult holds this content:
 **
 ** <blockquote><pre>
 **        azResult&#91;0] = "Name";
@@ -3749,7 +3823,7 @@ SQLITE_API void sqlite3_free_table(char **result);
 ** These routines are work-alikes of the "printf()" family of functions
 ** from the standard C library.
 ** These routines understand most of the common formatting options from
-** the standard library printf() 
+** the standard library printf()
 ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
 ** See the [built-in printf()] documentation for details.
 **
@@ -3793,7 +3867,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
 **
 ** The SQLite core uses these three routines for all of its own
 ** internal memory allocation needs. "Core" in the previous sentence
-** does not include operating-system specific VFS implementation.  The
+** does not include operating-system specific [VFS] implementation.  The
 ** Windows VFS uses native malloc() and free() for some operations.
 **
 ** ^The sqlite3_malloc() routine returns a pointer to a block
@@ -3854,19 +3928,6 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
 ** option is used.
 **
-** In SQLite version 3.5.0 and 3.5.1, it was possible to define
-** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
-** implementation of these routines to be omitted.  That capability
-** is no longer provided.  Only built-in memory allocators can be used.
-**
-** Prior to SQLite version 3.7.10, the Windows OS interface layer called
-** the system malloc() and free() directly when converting
-** filenames between the UTF-8 encoding used by SQLite
-** and whatever filename encoding is used by the particular Windows
-** installation.  Memory allocation errors were detected, but
-** they were reported back as [SQLITE_CANTOPEN] or
-** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
-**
 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
 ** must be either NULL or else pointers obtained from a prior
 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
@@ -3915,7 +3976,7 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
 ** select random [ROWID | ROWIDs] when inserting new records into a table that
 ** already uses the largest possible [ROWID].  The PRNG is also used for
-** the build-in random() and randomblob() SQL functions.  This interface allows
+** the built-in random() and randomblob() SQL functions.  This interface allows
 ** applications to access the same PRNG for other purposes.
 **
 ** ^A call to this routine stores N bytes of randomness into buffer P.
@@ -3958,7 +4019,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P);
 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
 ** authorizer will fail with an error message explaining that
-** access is denied. 
+** access is denied.
 **
 ** ^The first parameter to the authorizer callback is a copy of the third
 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
@@ -4011,7 +4072,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P);
 ** database connections for the meaning of "modify" in this paragraph.
 **
 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
-** statement might be re-prepared during [sqlite3_step()] due to a 
+** statement might be re-prepared during [sqlite3_step()] due to a
 ** schema change.  Hence, the application should ensure that the
 ** correct authorizer callback remains in place during the [sqlite3_step()].
 **
@@ -4159,7 +4220,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 ** execution of the prepared statement, such as at the start of each
 ** trigger subprogram. ^The P argument is a pointer to the
 ** [prepared statement]. ^The X argument is a pointer to a string which
-** is the unexpanded SQL text of the prepared statement or an SQL comment 
+** is the unexpanded SQL text of the prepared statement or an SQL comment
 ** that indicates the invocation of a trigger.  ^The callback can compute
 ** the same text that would have been returned by the legacy [sqlite3_trace()]
 ** interface by using the X argument when X begins with "--" and invoking
@@ -4175,7 +4236,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 **
 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
-** statement generates a single row of result.  
+** statement generates a single row of result.
 ** ^The P argument is a pointer to the [prepared statement] and the
 ** X argument is unused.
 **
@@ -4202,10 +4263,10 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 ** M argument should be the bitwise OR-ed combination of
 ** zero or more [SQLITE_TRACE] constants.
 **
-** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides 
+** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
 **
-** ^The X callback is invoked whenever any of the events identified by 
+** ^The X callback is invoked whenever any of the events identified by
 ** mask M occur.  ^The integer return value from the callback is currently
 ** ignored, though this may change in future releases.  Callback
 ** implementations should return zero to ensure future compatibility.
@@ -4237,8 +4298,8 @@ SQLITE_API int sqlite3_trace_v2(
 ** database connection D.  An example use for this
 ** interface is to keep a GUI updated during a large query.
 **
-** ^The parameter P is passed through as the only parameter to the 
-** callback function X.  ^The parameter N is the approximate number of 
+** ^The parameter P is passed through as the only parameter to the
+** callback function X.  ^The parameter N is the approximate number of
 ** [virtual machine instructions] that are evaluated between successive
 ** invocations of the callback X.  ^If N is less than one then the progress
 ** handler is disabled.
@@ -4265,7 +4326,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** CAPI3REF: Opening A New Database Connection
 ** CONSTRUCTOR: sqlite3
 **
-** ^These routines open an SQLite database file as specified by the 
+** ^These routines open an SQLite database file as specified by the
 ** filename argument. ^The filename argument is interpreted as UTF-8 for
 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
@@ -4289,10 +4350,8 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** The sqlite3_open_v2() interface works like sqlite3_open()
 ** except that it accepts two additional parameters for additional control
 ** over the new database connection.  ^(The flags parameter to
-** sqlite3_open_v2() can take one of
-** the following three values, optionally combined with the 
-** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
-** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
+** sqlite3_open_v2() must include, at a minimum, one of the following
+** three flag combinations:)^
 **
 ** <dl>
 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
@@ -4310,23 +4369,51 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** sqlite3_open() and sqlite3_open16().</dd>)^
 ** </dl>
 **
+** In addition to the required flags, the following optional flags are
+** also supported:
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_URI]</dt>
+** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
+** <dd>The database will be opened as an in-memory database.  The database
+** is named by the "filename" argument for the purposes of cache-sharing,
+** if shared cache mode is enabled, but the "filename" is otherwise ignored.
+** </dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
+** <dd>The new database connection will use the "multi-thread"
+** [threading mode].)^  This means that separate threads are allowed
+** to use SQLite at the same time, as long as each thread is using
+** a different [database connection].
+**
+** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
+** <dd>The new database connection will use the "serialized"
+** [threading mode].)^  This means the multiple threads can safely
+** attempt to use the same database connection at the same time.
+** (Mutexes will block any actual concurrency, but in this mode
+** there is no harm in trying.)
+**
+** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
+** <dd>The database is opened [shared cache] enabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
+** <dd>The database is opened [shared cache] disabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
+** <dd>The database filename is not allowed to be a symbolic link</dd>
+** </dl>)^
+**
 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
-** combinations shown above optionally combined with other
+** required combinations shown above optionally combined with other
 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
 ** then the behavior is undefined.
 **
-** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
-** opens in the multi-thread [threading mode] as long as the single-thread
-** mode has not been set at compile-time or start-time.  ^If the
-** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
-** in the serialized [threading mode] unless single-thread was
-** previously selected at compile-time or start-time.
-** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
-** eligible to use [shared cache mode], regardless of whether or not shared
-** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
-** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
-** participate in [shared cache mode] even if it is enabled.
-**
 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
 ** [sqlite3_vfs] object that defines the operating system interface that
 ** the new database connection should use.  ^If the fourth parameter is
@@ -4358,17 +4445,17 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** information.
 **
 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
-** authority, then it must be either an empty string or the string 
-** "localhost". ^If the authority is not an empty string or "localhost", an 
-** error is returned to the caller. ^The fragment component of a URI, if 
+** authority, then it must be either an empty string or the string
+** "localhost". ^If the authority is not an empty string or "localhost", an
+** error is returned to the caller. ^The fragment component of a URI, if
 ** present, is ignored.
 **
 ** ^SQLite uses the path component of the URI as the name of the disk file
-** which contains the database. ^If the path begins with a '/' character, 
-** then it is interpreted as an absolute path. ^If the path does not begin 
+** which contains the database. ^If the path begins with a '/' character,
+** then it is interpreted as an absolute path. ^If the path does not begin
 ** with a '/' (meaning that the authority section is omitted from the URI)
-** then the path is interpreted as a relative path. 
-** ^(On windows, the first component of an absolute path 
+** then the path is interpreted as a relative path.
+** ^(On windows, the first component of an absolute path
 ** is a drive specification (e.g. "C:").)^
 **
 ** [[core URI query parameters]]
@@ -4388,13 +4475,13 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **
 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
 **     "rwc", or "memory". Attempting to set it to any other value is
-**     an error)^. 
-**     ^If "ro" is specified, then the database is opened for read-only 
-**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
-**     third argument to sqlite3_open_v2(). ^If the mode option is set to 
-**     "rw", then the database is opened for read-write (but not create) 
-**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
-**     been set. ^Value "rwc" is equivalent to setting both 
+**     an error)^.
+**     ^If "ro" is specified, then the database is opened for read-only
+**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
+**     third argument to sqlite3_open_v2(). ^If the mode option is set to
+**     "rw", then the database is opened for read-write (but not create)
+**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
+**     been set. ^Value "rwc" is equivalent to setting both
 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
 **     set to "memory" then a pure [in-memory database] that never reads
 **     or writes from disk is used. ^It is an error to specify a value for
@@ -4404,7 +4491,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
 **     "private". ^Setting it to "shared" is equivalent to setting the
 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
-**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
+**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
 **     a URI filename, its value overrides any behavior requested by setting
@@ -4430,7 +4517,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **     property on a database file that does in fact change can result
 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
 **     See also: [SQLITE_IOCAP_IMMUTABLE].
-**       
+**
 ** </ul>
 **
 ** ^Specifying an unknown parameter in the query component of a URI is not an
@@ -4442,36 +4529,36 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **
 ** <table border="1" align=center cellpadding=5>
 ** <tr><th> URI filenames <th> Results
-** <tr><td> file:data.db <td> 
+** <tr><td> file:data.db <td>
 **          Open the file "data.db" in the current directory.
 ** <tr><td> file:/home/fred/data.db<br>
-**          file:///home/fred/data.db <br> 
-**          file://localhost/home/fred/data.db <br> <td> 
+**          file:///home/fred/data.db <br>
+**          file://localhost/home/fred/data.db <br> <td>
 **          Open the database file "/home/fred/data.db".
-** <tr><td> file://darkstar/home/fred/data.db <td> 
+** <tr><td> file://darkstar/home/fred/data.db <td>
 **          An error. "darkstar" is not a recognized authority.
-** <tr><td style="white-space:nowrap"> 
+** <tr><td style="white-space:nowrap">
 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
-**          C:. Note that the %20 escaping in this example is not strictly 
+**          C:. Note that the %20 escaping in this example is not strictly
 **          necessary - space characters can be used literally
 **          in URI filenames.
-** <tr><td> file:data.db?mode=ro&cache=private <td> 
+** <tr><td> file:data.db?mode=ro&cache=private <td>
 **          Open file "data.db" in the current directory for read-only access.
 **          Regardless of whether or not shared-cache mode is enabled by
 **          default, use a private cache.
 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
 **          that uses dot-files in place of posix advisory locking.
-** <tr><td> file:data.db?mode=readonly <td> 
+** <tr><td> file:data.db?mode=readonly <td>
 **          An error. "readonly" is not a valid option for the "mode" parameter.
 ** </table>
 **
 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
 ** query components of a URI. A hexadecimal escape sequence consists of a
-** percent sign - "%" - followed by exactly two hexadecimal digits 
+** percent sign - "%" - followed by exactly two hexadecimal digits
 ** specifying an octet value. ^Before the path or query components of a
-** URI filename are interpreted, they are encoded using UTF-8 and all 
+** URI filename are interpreted, they are encoded using UTF-8 and all
 ** hexadecimal escape sequences replaced by a single byte containing the
 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
 ** the results are undefined.
@@ -4506,17 +4593,27 @@ SQLITE_API int sqlite3_open_v2(
 /*
 ** CAPI3REF: Obtain Values For URI Parameters
 **
-** These are utility routines, useful to VFS implementations, that check
-** to see if a database file was a URI that contained a specific query 
+** These are utility routines, useful to [VFS|custom VFS implementations],
+** that check if a database file was a URI that contained a specific query
 ** parameter, and if so obtains the value of that query parameter.
 **
-** If F is the database filename pointer passed into the xOpen() method of 
-** a VFS implementation when the flags parameter to xOpen() has one or 
-** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
-** P is the name of the query parameter, then
+** The first parameter to these interfaces (hereafter referred to
+** as F) must be one of:
+** <ul>
+** <li> A database filename pointer created by the SQLite core and
+** passed into the xOpen() method of a VFS implemention, or
+** <li> A filename obtained from [sqlite3_db_filename()], or
+** <li> A new filename constructed using [sqlite3_create_filename()].
+** </ul>
+** If the F parameter is not one of the above, then the behavior is
+** undefined and probably undesirable.  Older versions of SQLite were
+** more tolerant of invalid F parameters than newer versions.
+**
+** If F is a suitable filename (as described in the previous paragraph)
+** and if P is the name of the query parameter, then
 ** sqlite3_uri_parameter(F,P) returns the value of the P
-** parameter if it exists or a NULL pointer if P does not appear as a 
-** query parameter on F.  If P is a query parameter of F
+** parameter if it exists or a NULL pointer if P does not appear as a
+** query parameter on F.  If P is a query parameter of F and it
 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
 ** a pointer to an empty string.
 **
@@ -4524,41 +4621,160 @@ SQLITE_API int sqlite3_open_v2(
 ** parameter and returns true (1) or false (0) according to the value
 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
 ** value of query parameter P is one of "yes", "true", or "on" in any
-** case or if the value begins with a non-zero number.  The 
+** case or if the value begins with a non-zero number.  The
 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
 ** query parameter P is one of "no", "false", or "off" in any case or
 ** if the value begins with a numeric zero.  If P is not a query
-** parameter on F or if the value of P is does not match any of the
+** parameter on F or if the value of P does not match any of the
 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
 **
 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
 ** 64-bit signed integer and returns that integer, or D if P does not
 ** exist.  If the value of P is something other than an integer, then
 ** zero is returned.
-** 
+**
+** The sqlite3_uri_key(F,N) returns a pointer to the name (not
+** the value) of the N-th query parameter for filename F, or a NULL
+** pointer if N is less than zero or greater than the number of query
+** parameters minus 1.  The N value is zero-based so N should be 0 to obtain
+** the name of the first query parameter, 1 for the second parameter, and
+** so forth.
+**
 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
-** is not a database file pathname pointer that SQLite passed into the xOpen
-** VFS method, then the behavior of this routine is undefined and probably
-** undesirable.
+** is not a database file pathname pointer that the SQLite core passed
+** into the xOpen VFS method, then the behavior of this routine is undefined
+** and probably undesirable.
+**
+** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
+** parameter can also be the name of a rollback journal file or WAL file
+** in addition to the main database file.  Prior to version 3.31.0, these
+** routines would only work if F was the name of the main database file.
+** When the F parameter is the name of the rollback journal or WAL file,
+** it has access to all the same query parameters as were found on the
+** main database file.
 **
 ** See the [URI filename] documentation for additional information.
 */
 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
+
+/*
+** CAPI3REF:  Translate filenames
+**
+** These routines are available to [VFS|custom VFS implementations] for
+** translating filenames between the main database file, the journal file,
+** and the WAL file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
+** returns the name of the corresponding database file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, or if F is a database filename
+** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
+** returns the name of the corresponding rollback journal file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** that was passed by the SQLite core into the VFS, or if F is a database
+** filename obtained from [sqlite3_db_filename()], then
+** sqlite3_filename_wal(F) returns the name of the corresponding
+** WAL file.
+**
+** In all of the above, if F is not the name of a database, journal or WAL
+** filename passed into the VFS from the SQLite core and F is not the
+** return value from [sqlite3_db_filename()], then the result is
+** undefined and is likely a memory access violation.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char*);
+SQLITE_API const char *sqlite3_filename_journal(const char*);
+SQLITE_API const char *sqlite3_filename_wal(const char*);
+
+/*
+** CAPI3REF:  Database File Corresponding To A Journal
+**
+** ^If X is the name of a rollback or WAL-mode journal file that is
+** passed into the xOpen method of [sqlite3_vfs], then
+** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
+** object that represents the main database file.
+**
+** This routine is intended for use in custom [VFS] implementations
+** only.  It is not a general-purpose interface.
+** The argument sqlite3_file_object(X) must be a filename pointer that
+** has been passed into [sqlite3_vfs].xOpen method where the
+** flags parameter to xOpen contains one of the bits
+** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use
+** of this routine results in undefined and probably undesirable
+** behavior.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
 
+/*
+** CAPI3REF: Create and Destroy VFS Filenames
+**
+** These interfces are provided for use by [VFS shim] implementations and
+** are not useful outside of that context.
+**
+** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
+** database filename D with corresponding journal file J and WAL file W and
+** with N URI parameters key/values pairs in the array P.  The result from
+** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
+** is safe to pass to routines like:
+** <ul>
+** <li> [sqlite3_uri_parameter()],
+** <li> [sqlite3_uri_boolean()],
+** <li> [sqlite3_uri_int64()],
+** <li> [sqlite3_uri_key()],
+** <li> [sqlite3_filename_database()],
+** <li> [sqlite3_filename_journal()], or
+** <li> [sqlite3_filename_wal()].
+** </ul>
+** If a memory allocation error occurs, sqlite3_create_filename() might
+** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)
+** must be released by a corresponding call to sqlite3_free_filename(Y).
+**
+** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
+** of 2*N pointers to strings.  Each pair of pointers in this array corresponds
+** to a key and value for a query parameter.  The P parameter may be a NULL
+** pointer if N is zero.  None of the 2*N pointers in the P array may be
+** NULL pointers and key pointers should not be empty strings.
+** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
+** be NULL pointers, though they can be empty strings.
+**
+** The sqlite3_free_filename(Y) routine releases a memory allocation
+** previously obtained from sqlite3_create_filename().  Invoking
+** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
+**
+** If the Y parameter to sqlite3_free_filename(Y) is anything other
+** than a NULL pointer or a pointer previously acquired from
+** sqlite3_create_filename(), then bad things such as heap
+** corruption or segfaults may occur. The value Y should not be
+** used again after sqlite3_free_filename(Y) has been called.  This means
+** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
+** then the corresponding [sqlite3_module.xClose() method should also be
+** invoked prior to calling sqlite3_free_filename(Y).
+*/
+SQLITE_API char *sqlite3_create_filename(
+  const char *zDatabase,
+  const char *zJournal,
+  const char *zWal,
+  int nParam,
+  const char **azParam
+);
+SQLITE_API void sqlite3_free_filename(char*);
 
 /*
 ** CAPI3REF: Error Codes And Messages
 ** METHOD: sqlite3
 **
-** ^If the most recent sqlite3_* API call associated with 
+** ^If the most recent sqlite3_* API call associated with
 ** [database connection] D failed, then the sqlite3_errcode(D) interface
 ** returns the numeric [result code] or [extended result code] for that
 ** API call.
 ** ^The sqlite3_extended_errcode()
-** interface is the same except that it always returns the 
+** interface is the same except that it always returns the
 ** [extended result code] even when extended result codes are
 ** disabled.
 **
@@ -4615,7 +4831,7 @@ SQLITE_API const char *sqlite3_errstr(int);
 ** has been compiled into binary form and is ready to be evaluated.
 **
 ** Think of each SQL statement as a separate computer program.  The
-** original SQL text is source code.  A prepared statement object 
+** original SQL text is source code.  A prepared statement object
 ** is the compiled object code.  All SQL must be converted into a
 ** prepared statement before it can be run.
 **
@@ -4645,7 +4861,7 @@ typedef struct sqlite3_stmt sqlite3_stmt;
 ** new limit for that construct.)^
 **
 ** ^If the new limit is a negative number, the limit is unchanged.
-** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
 ** [limits | hard upper bound]
 ** set at compile-time by a C preprocessor macro called
 ** [limits | SQLITE_MAX_<i>NAME</i>].
@@ -4653,7 +4869,7 @@ typedef struct sqlite3_stmt sqlite3_stmt;
 ** ^Attempts to increase a limit above its hard upper bound are
 ** silently truncated to the hard upper bound.
 **
-** ^Regardless of whether or not the limit was changed, the 
+** ^Regardless of whether or not the limit was changed, the
 ** [sqlite3_limit()] interface returns the prior value of the limit.
 ** ^Hence, to find the current value of a limit without changing it,
 ** simply invoke this interface with the third parameter set to -1.
@@ -4758,7 +4974,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
 ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
 ** that the prepared statement will be retained for a long time and
 ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
-** and [sqlite3_prepare16_v3()] assume that the prepared statement will 
+** and [sqlite3_prepare16_v3()] assume that the prepared statement will
 ** be used just once or at most a few times and then destroyed using
 ** [sqlite3_finalize()] relatively soon. The current implementation acts
 ** on this hint by avoiding the use of [lookaside memory] so as not to
@@ -4865,12 +5081,12 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
 ** </li>
 **
 ** <li>
-** ^If the specific value bound to [parameter | host parameter] in the 
+** ^If the specific value bound to a [parameter | host parameter] in the
 ** WHERE clause might influence the choice of query plan for a statement,
-** then the statement will be automatically recompiled, as if there had been 
-** a schema change, on the first  [sqlite3_step()] call following any change
-** to the [sqlite3_bind_text | bindings] of that [parameter]. 
-** ^The specific value of WHERE-clause [parameter] might influence the 
+** then the statement will be automatically recompiled, as if there had been
+** a schema change, on the first [sqlite3_step()] call following any change
+** to the [sqlite3_bind_text | bindings] of that [parameter].
+** ^The specific value of a WHERE-clause [parameter] might influence the
 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
 ** or [GLOB] operator or if the parameter is compared to an indexed column
 ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
@@ -4979,8 +5195,8 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** the content of the database file.
 **
 ** Note that [application-defined SQL functions] or
-** [virtual tables] might change the database indirectly as a side effect.  
-** ^(For example, if an application defines a function "eval()" that 
+** [virtual tables] might change the database indirectly as a side effect.
+** ^(For example, if an application defines a function "eval()" that
 ** calls [sqlite3_exec()], then the following SQL statement would
 ** change the database file through side-effects:
 **
@@ -4994,10 +5210,10 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
 ** since the statements themselves do not actually modify the database but
-** rather they control the timing of when other statements modify the 
+** rather they control the timing of when other statements modify the
 ** database.  ^The [ATTACH] and [DETACH] statements also cause
 ** sqlite3_stmt_readonly() to return true since, while those statements
-** change the configuration of a database connection, they do not make 
+** change the configuration of a database connection, they do not make
 ** changes to the content of the database files on disk.
 ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
@@ -5023,18 +5239,18 @@ SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
 ** METHOD: sqlite3_stmt
 **
 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
-** [prepared statement] S has been stepped at least once using 
+** [prepared statement] S has been stepped at least once using
 ** [sqlite3_step(S)] but has neither run to completion (returned
 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
-** interface returns false if S is a NULL pointer.  If S is not a 
+** interface returns false if S is a NULL pointer.  If S is not a
 ** NULL pointer and is not a pointer to a valid [prepared statement]
 ** object, then the behavior is undefined and probably undesirable.
 **
 ** This interface can be used in combination [sqlite3_next_stmt()]
-** to locate all prepared statements associated with a database 
+** to locate all prepared statements associated with a database
 ** connection that are in need of being reset.  This can be used,
-** for example, in diagnostic routines to search for prepared 
+** for example, in diagnostic routines to search for prepared
 ** statements that are holding a transaction open.
 */
 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
@@ -5053,7 +5269,7 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 ** will accept either a protected or an unprotected sqlite3_value.
 ** Every interface that accepts sqlite3_value arguments specifies
 ** whether or not it requires a protected sqlite3_value.  The
-** [sqlite3_value_dup()] interface can be used to construct a new 
+** [sqlite3_value_dup()] interface can be used to construct a new
 ** protected sqlite3_value from an unprotected sqlite3_value.
 **
 ** The terms "protected" and "unprotected" refer to whether or not
@@ -5061,7 +5277,7 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 ** sqlite3_value object but no mutex is held for an unprotected
 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
-** or if SQLite is run in one of reduced mutex modes 
+** or if SQLite is run in one of reduced mutex modes
 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
 ** then there is no distinction between protected and unprotected
 ** sqlite3_value objects and they can be used interchangeably.  However,
@@ -5130,12 +5346,30 @@ typedef struct sqlite3_context sqlite3_context;
 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
 ** for "?NNN" parameters is the value of NNN.
 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
-** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
+** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
 **
 ** ^The third argument is the value to bind to the parameter.
 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
 ** is ignored and the end result is the same as sqlite3_bind_null().
+** ^If the third parameter to sqlite3_bind_text() is not NULL, then
+** it should be a pointer to well-formed UTF8 text.
+** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
+** it should be a pointer to well-formed UTF16 text.
+** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
+** it should be a pointer to a well-formed unicode string that is
+** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
+** otherwise.
+**
+** [[byte-order determination rules]] ^The byte-order of
+** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
+** found in first character, which is removed, or in the absence of a BOM
+** the byte order is the native byte order of the host
+** machine for sqlite3_bind_text16() or the byte order specified in
+** the 6th parameter for sqlite3_bind_text64().)^
+** ^If UTF16 input text contains invalid unicode
+** characters, then SQLite might change those invalid characters
+** into the unicode replacement character: U+FFFD.
 **
 ** ^(In those routines that have a fourth argument, its value is the
 ** number of bytes in the parameter.  To be clear: the value is the
@@ -5149,7 +5383,7 @@ typedef struct sqlite3_context sqlite3_context;
 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
 ** that parameter must be the byte offset
 ** where the NUL terminator would occur assuming the string were NUL
-** terminated.  If any NUL characters occur at byte offsets less than 
+** terminated.  If any NUL characters occurs at byte offsets less than
 ** the value of the fourth parameter then the resulting string value will
 ** contain embedded NULs.  The result of expressions involving strings
 ** with embedded NULs is undefined.
@@ -5311,7 +5545,7 @@ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
 ** METHOD: sqlite3_stmt
 **
 ** ^Return the number of columns in the result set returned by the
-** [prepared statement]. ^If this routine returns 0, that means the 
+** [prepared statement]. ^If this routine returns 0, that means the
 ** [prepared statement] returns no data (for example an [UPDATE]).
 ** ^However, just because this routine returns a positive number does not
 ** mean that one or more rows of data will be returned.  ^A SELECT statement
@@ -5379,7 +5613,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
 **
 ** ^If the Nth column returned by the statement is an expression or
 ** subquery and is not a column value, then all of these functions return
-** NULL.  ^These routine might also return NULL if a memory allocation error
+** NULL.  ^These routines might also return NULL if a memory allocation error
 ** occurs.  ^Otherwise, they return the name of the attached database, table,
 ** or column that query result column was extracted from.
 **
@@ -5389,10 +5623,6 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
 ** ^These APIs are only available if the library was compiled with the
 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
 **
-** If two or more threads call one or more of these routines against the same
-** prepared statement and column at the same time then the results are
-** undefined.
-**
 ** If two or more threads call one or more
 ** [sqlite3_column_database_name | column metadata interfaces]
 ** for the same [prepared statement] and result column
@@ -5497,7 +5727,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
 ** For all versions of SQLite up to and including 3.6.23.1, a call to
 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
 ** other than [SQLITE_ROW] before any subsequent invocation of
-** sqlite3_step().  Failure to reset the prepared statement using 
+** sqlite3_step().  Failure to reset the prepared statement using
 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
 ** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
 ** sqlite3_step() began
@@ -5529,7 +5759,7 @@ SQLITE_API int sqlite3_step(sqlite3_stmt*);
 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
 ** current row of the result set of [prepared statement] P.
 ** ^If prepared statement P does not have results ready to return
-** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
+** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
 ** interfaces) then sqlite3_data_count(P) returns 0.
 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
@@ -5588,7 +5818,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
 ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
 ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
-** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an 
+** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
 ** [sqlite3_value|unprotected sqlite3_value] object.
 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
 ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
@@ -5636,7 +5866,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** The return value of sqlite3_column_type() can be used to decide which
 ** of the first six interface should be used to extract the column value.
 ** The value returned by sqlite3_column_type() is only meaningful if no
-** automatic type conversions have occurred for the value in question.  
+** automatic type conversions have occurred for the value in question.
 ** After a type conversion, the result of calling sqlite3_column_type()
 ** is undefined, though harmless.  Future
 ** versions of SQLite may change the behavior of sqlite3_column_type()
@@ -5664,7 +5894,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** the number of bytes in that string.
 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
 **
-** ^The values returned by [sqlite3_column_bytes()] and 
+** ^The values returned by [sqlite3_column_bytes()] and
 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
 ** of the string.  ^For clarity: the values returned by
 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
@@ -5683,7 +5913,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
 ** Hence, the sqlite3_column_value() interface
-** is normally only useful within the implementation of 
+** is normally only useful within the implementation of
 ** [application-defined SQL functions] or [virtual tables], not within
 ** top-level application code.
 **
@@ -5853,15 +6083,13 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 /*
 ** CAPI3REF: Create Or Redefine SQL Functions
 ** KEYWORDS: {function creation routines}
-** KEYWORDS: {application-defined SQL function}
-** KEYWORDS: {application-defined SQL functions}
 ** METHOD: sqlite3
 **
 ** ^These functions (collectively known as "function creation routines")
 ** are used to add SQL functions or aggregates or to redefine the behavior
 ** of existing SQL functions or aggregates. The only differences between
-** the three "sqlite3_create_function*" routines are the text encoding 
-** expected for the second parameter (the name of the function being 
+** the three "sqlite3_create_function*" routines are the text encoding
+** expected for the second parameter (the name of the function being
 ** created) and the presence or absence of a destructor callback for
 ** the application data pointer. Function sqlite3_create_window_function()
 ** is similar, but allows the user to supply the extra callback functions
@@ -5875,7 +6103,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** ^The second parameter is the name of the SQL function to be created or
 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
 ** representation, exclusive of the zero-terminator.  ^Note that the name
-** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
 ** ^Any attempt to create a function with a longer name
 ** will result in [SQLITE_MISUSE] being returned.
 **
@@ -5890,7 +6118,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** ^The fourth parameter, eTextRep, specifies what
 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
 ** its parameters.  The application should set this parameter to
-** [SQLITE_UTF16LE] if the function implementation invokes 
+** [SQLITE_UTF16LE] if the function implementation invokes
 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
 ** implementation invokes [sqlite3_value_text16be()] on an input, or
 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
@@ -5910,9 +6138,20 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 **
 ** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
 ** flag, which if present prevents the function from being invoked from
-** within VIEWs or TRIGGERs.  For security reasons, the [SQLITE_DIRECTONLY]
-** flag is recommended for any application-defined SQL function that has
-** side-effects.
+** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
+** index expressions, or the WHERE clause of partial indexes.
+**
+** <span style="background-color:#ffff90;">
+** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
+** all application-defined SQL functions that do not need to be
+** used inside of triggers, view, CHECK constraints, or other elements of
+** the database schema.  This flags is especially recommended for SQL
+** functions that have side effects or reveal internal application state.
+** Without this flag, an attacker might be able to modify the schema of
+** a database file to include invocations of the function with parameters
+** chosen by the attacker, which the application will then execute when
+** the database file is opened and read.
+** </span>
 **
 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
 ** function can gain access to this pointer using [sqlite3_user_data()].)^
@@ -5927,21 +6166,21 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** SQL function or aggregate, pass NULL pointers for all three function
 ** callbacks.
 **
-** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue 
+** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
 ** and xInverse) passed to sqlite3_create_window_function are pointers to
 ** C-language callbacks that implement the new function. xStep and xFinal
 ** must both be non-NULL. xValue and xInverse may either both be NULL, in
-** which case a regular aggregate function is created, or must both be 
+** which case a regular aggregate function is created, or must both be
 ** non-NULL, in which case the new function may be used as either an aggregate
 ** or aggregate window function. More details regarding the implementation
-** of aggregate window functions are 
+** of aggregate window functions are
 ** [user-defined window functions|available here].
 **
 ** ^(If the final parameter to sqlite3_create_function_v2() or
 ** sqlite3_create_window_function() is not NULL, then it is destructor for
-** the application data pointer. The destructor is invoked when the function 
-** is deleted, either by being overloaded or when the database connection 
-** closes.)^ ^The destructor is also invoked if the call to 
+** the application data pointer. The destructor is invoked when the function
+** is deleted, either by being overloaded or when the database connection
+** closes.)^ ^The destructor is also invoked if the call to
 ** sqlite3_create_function_v2() fails.  ^When the destructor callback is
 ** invoked, it is passed a single argument which is a copy of the application
 ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
@@ -5954,7 +6193,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** nArg parameter is a better match than a function implementation with
 ** a negative nArg.  ^A function where the preferred text encoding
 ** matches the database encoding is a better
-** match than a function where the encoding is different.  
+** match than a function where the encoding is different.
 ** ^A function where the encoding difference is between UTF16le and UTF16be
 ** is a closer match than a function where the encoding difference is
 ** between UTF8 and UTF16.
@@ -6026,23 +6265,58 @@ SQLITE_API int sqlite3_create_window_function(
 /*
 ** CAPI3REF: Function Flags
 **
-** These constants may be ORed together with the 
+** These constants may be ORed together with the
 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
 ** [sqlite3_create_function_v2()].
 **
-** The SQLITE_DETERMINISTIC flag means that the new function will always
-** maps the same inputs into the same output.  The abs() function is
-** deterministic, for example, but randomblob() is not.
+** <dl>
+** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
+** The SQLITE_DETERMINISTIC flag means that the new function always gives
+** the same output when the input parameters are the same.
+** The [abs|abs() function] is deterministic, for example, but
+** [randomblob|randomblob()] is not.  Functions must
+** be deterministic in order to be used in certain contexts such as
+** with the WHERE clause of [partial indexes] or in [generated columns].
+** SQLite might also optimize deterministic functions by factoring them
+** out of inner loops.
+** </dd>
 **
+** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
 ** The SQLITE_DIRECTONLY flag means that the function may only be invoked
-** from top-level SQL, and cannot be used in VIEWs or TRIGGERs.  This is
-** a security feature which is recommended for all 
-** [application-defined SQL functions] that have side-effects.  This flag 
-** prevents an attacker from adding triggers and views to a schema then 
-** tricking a high-privilege application into causing unintended side-effects
-** while performing ordinary queries.
+** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], or [generated columns].
+** The SQLITE_DIRECTONLY flags is a security feature which is recommended
+** for all [application-defined SQL functions], and especially for functions
+** that have side-effects or that could potentially leak sensitive
+** information.
+** </dd>
+**
+** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
+** The SQLITE_INNOCUOUS flag means that the function is unlikely
+** to cause problems even if misused.  An innocuous function should have
+** no side effects and should not depend on any values other than its
+** input parameters. The [abs|abs() function] is an example of an
+** innocuous function.
+** The [load_extension() SQL function] is not innocuous because of its
+** side effects.
+** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
+** exactly the same.  The [random|random() function] is an example of a
+** function that is innocuous but not deterministic.
+** <p>Some heightened security settings
+** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
+** disable the use of SQL functions inside views and triggers and in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], and [generated columns] unless
+** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions
+** are innocuous.  Developers are advised to avoid using the
+** SQLITE_INNOCUOUS flag for application-defined functions unless the
+** function has been carefully audited and found to be free of potentially
+** security-adverse side-effects and information-leaks.
+** </dd>
 **
+** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
 ** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
 ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
 ** Specifying this flag makes no difference for scalar or aggregate user
@@ -6050,17 +6324,20 @@ SQLITE_API int sqlite3_create_window_function(
 ** function, then any sub-types belonging to arguments passed to the window
 ** function may be discarded before the window function is called (i.e.
 ** sqlite3_value_subtype() will always return 0).
+** </dd>
+** </dl>
 */
 #define SQLITE_DETERMINISTIC    0x000000800
 #define SQLITE_DIRECTONLY       0x000080000
 #define SQLITE_SUBTYPE          0x000100000
+#define SQLITE_INNOCUOUS        0x000200000
 
 /*
 ** CAPI3REF: Deprecated Functions
 ** DEPRECATED
 **
 ** These functions are [deprecated].  In order to maintain
-** backwards compatibility with older code, these functions continue 
+** backwards compatibility with older code, these functions continue
 ** to be supported.  However, new applications should avoid
 ** the use of these functions.  To encourage programmers to avoid
 ** these functions, we will not explain what they do.
@@ -6112,8 +6389,8 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 **
 ** These routines extract type, size, and content information from
 ** [protected sqlite3_value] objects.  Protected sqlite3_value objects
-** are used to pass parameter information into implementation of
-** [application-defined SQL functions] and [virtual tables].
+** are used to pass parameter information into the functions that
+** implement [application-defined SQL functions] and [virtual tables].
 **
 ** These routines work only with [protected sqlite3_value] objects.
 ** Any attempt to use these routines on an [unprotected sqlite3_value]
@@ -6128,11 +6405,11 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
 ** extract UTF-16 strings as big-endian and little-endian respectively.
 **
-** ^If [sqlite3_value] object V was initialized 
+** ^If [sqlite3_value] object V was initialized
 ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
 ** and if X and Y are strings that compare equal according to strcmp(X,Y),
 ** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
-** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() 
+** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
 **
 ** ^(The sqlite3_value_type(V) interface returns the
@@ -6170,7 +6447,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
 ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
 ** interfaces.  ^If X comes from an SQL literal value, or a table column,
-** and expression, then sqlite3_value_frombind(X) returns zero.
+** or an expression, then sqlite3_value_frombind(X) returns zero.
 **
 ** Please pay particular attention to the fact that the pointer returned
 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
@@ -6255,9 +6532,9 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);
 ** Implementations of aggregate SQL functions use this
 ** routine to allocate memory for storing their state.
 **
-** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
-** for a particular aggregate function, SQLite
-** allocates N of memory, zeroes out that memory, and returns a pointer
+** ^The first time the sqlite3_aggregate_context(C,N) routine is called
+** for a particular aggregate function, SQLite allocates
+** N bytes of memory, zeroes out that memory, and returns a pointer
 ** to the new memory. ^On second and subsequent calls to
 ** sqlite3_aggregate_context() for the same aggregate function instance,
 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
@@ -6268,19 +6545,19 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);
 ** In those cases, sqlite3_aggregate_context() might be called for the
 ** first time from within xFinal().)^
 **
-** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
+** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
 ** when first called if N is less than or equal to zero or if a memory
 ** allocate error occurs.
 **
 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
 ** determined by the N parameter on first successful call.  Changing the
-** value of N in subsequent call to sqlite3_aggregate_context() within
+** value of N in any subsequent call to sqlite3_aggregate_context() within
 ** the same aggregate function instance will not resize the memory
 ** allocation.)^  Within the xFinal callback, it is customary to set
-** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
+** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
 ** pointless memory allocations occur.
 **
-** ^SQLite automatically frees the memory allocated by 
+** ^SQLite automatically frees the memory allocated by
 ** sqlite3_aggregate_context() when the aggregate query concludes.
 **
 ** The first parameter must be a copy of the
@@ -6330,7 +6607,7 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
 ** some circumstances the associated metadata may be preserved.  An example
 ** of where this might be useful is in a regular-expression matching
 ** function. The compiled version of the regular expression can be stored as
-** metadata associated with the pattern string.  
+** metadata associated with the pattern string.
 ** Then as long as the pattern string remains the same,
 ** the compiled regular expression can be reused on multiple
 ** invocations of the same function.
@@ -6356,10 +6633,10 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
 **      SQL statement)^, or
 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
 **       parameter)^, or
-** <li> ^(during the original sqlite3_set_auxdata() call when a memory 
+** <li> ^(during the original sqlite3_set_auxdata() call when a memory
 **      allocation error occurs.)^ </ul>
 **
-** Note the last bullet in particular.  The destructor X in 
+** Note the last bullet in particular.  The destructor X in
 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
 ** should be called near the end of the function implementation and the
@@ -6431,8 +6708,9 @@ typedef void (*sqlite3_destructor_type)(void*);
 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
 ** as the text of an error message.  ^SQLite interprets the error
 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
-** interprets the string from sqlite3_result_error16() as UTF-16 in native
-** byte order.  ^If the third parameter to sqlite3_result_error()
+** interprets the string from sqlite3_result_error16() as UTF-16 using
+** the same [byte-order determination rules] as [sqlite3_bind_text16()].
+** ^If the third parameter to sqlite3_result_error()
 ** or sqlite3_result_error16() is negative then SQLite takes as the error
 ** message all text up through the first zero character.
 ** ^If the third parameter to sqlite3_result_error() or
@@ -6500,6 +6778,25 @@ typedef void (*sqlite3_destructor_type)(void*);
 ** then SQLite makes a copy of the result into space obtained
 ** from [sqlite3_malloc()] before it returns.
 **
+** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
+** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
+** when the encoding is not UTF8, if the input UTF16 begins with a
+** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
+** string and the rest of the string is interpreted according to the
+** byte-order specified by the BOM.  ^The byte-order specified by
+** the BOM at the beginning of the text overrides the byte-order
+** specified by the interface procedure.  ^So, for example, if
+** sqlite3_result_text16le() is invoked with text that begins
+** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
+** first two bytes of input are skipped and the remaining input
+** is interpreted as UTF16BE text.
+**
+** ^For UTF16 input text to the sqlite3_result_text16(),
+** sqlite3_result_text16be(), sqlite3_result_text16le(), and
+** sqlite3_result_text64() routines, if the text contains invalid
+** UTF16 characters, the invalid characters might be converted
+** into the unicode replacement character, U+FFFD.
+**
 ** ^The sqlite3_result_value() interface sets the result of
 ** the application-defined function to be a copy of the
 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
@@ -6512,7 +6809,7 @@ typedef void (*sqlite3_destructor_type)(void*);
 **
 ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
 ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
-** also associates the host-language pointer P or type T with that 
+** also associates the host-language pointer P or type T with that
 ** NULL value such that the pointer can be retrieved within an
 ** [application-defined SQL function] using [sqlite3_value_pointer()].
 ** ^If the D parameter is not NULL, then it is a pointer to a destructor
@@ -6567,8 +6864,8 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
 ** METHOD: sqlite3_context
 **
 ** The sqlite3_result_subtype(C,T) function causes the subtype of
-** the result from the [application-defined SQL function] with 
-** [sqlite3_context] C to be the value T.  Only the lower 8 bits 
+** the result from the [application-defined SQL function] with
+** [sqlite3_context] C to be the value T.  Only the lower 8 bits
 ** of the subtype T are preserved in current versions of SQLite;
 ** higher order bits are discarded.
 ** The number of subtype bytes preserved by SQLite might increase
@@ -6598,7 +6895,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** <li> [SQLITE_UTF16_ALIGNED].
 ** </ul>)^
 ** ^The eTextRep argument determines the encoding of strings passed
-** to the collating function callback, xCallback.
+** to the collating function callback, xCompare.
 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
 ** force strings to be UTF16 with native byte order.
 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
@@ -6607,18 +6904,19 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** ^The fourth argument, pArg, is an application data pointer that is passed
 ** through as the first argument to the collating function callback.
 **
-** ^The fifth argument, xCallback, is a pointer to the collating function.
+** ^The fifth argument, xCompare, is a pointer to the collating function.
 ** ^Multiple collating functions can be registered using the same name but
 ** with different eTextRep parameters and SQLite will use whichever
 ** function requires the least amount of data transformation.
-** ^If the xCallback argument is NULL then the collating function is
+** ^If the xCompare argument is NULL then the collating function is
 ** deleted.  ^When all collating functions having the same name are deleted,
 ** that collation is no longer usable.
 **
-** ^The collating function callback is invoked with a copy of the pArg 
+** ^The collating function callback is invoked with a copy of the pArg
 ** application data pointer and with two strings in the encoding specified
-** by the eTextRep argument.  The collating function must return an
-** integer that is negative, zero, or positive
+** by the eTextRep argument.  The two integer parameters to the collating
+** function callback are the length of the two strings, in bytes. The collating
+** function must return an integer that is negative, zero, or positive
 ** if the first string is less than, equal to, or greater than the second,
 ** respectively.  A collating function must always return the same answer
 ** given the same inputs.  If two or more collating functions are registered
@@ -6635,7 +6933,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** </ol>
 **
 ** If a collating function fails any of the above constraints and that
-** collating function is  registered and used, then the behavior of SQLite
+** collating function is registered and used, then the behavior of SQLite
 ** is undefined.
 **
 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
@@ -6645,36 +6943,36 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** calls to the collation creation functions or when the
 ** [database connection] is closed using [sqlite3_close()].
 **
-** ^The xDestroy callback is <u>not</u> called if the 
+** ^The xDestroy callback is <u>not</u> called if the
 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
-** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
+** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
 ** check the return code and dispose of the application data pointer
 ** themselves rather than expecting SQLite to deal with it for them.
-** This is different from every other SQLite interface.  The inconsistency 
-** is unfortunate but cannot be changed without breaking backwards 
+** This is different from every other SQLite interface.  The inconsistency
+** is unfortunate but cannot be changed without breaking backwards
 ** compatibility.
 **
 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
 */
 SQLITE_API int sqlite3_create_collation(
-  sqlite3*, 
-  const char *zName, 
-  int eTextRep, 
+  sqlite3*,
+  const char *zName,
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*)
 );
 SQLITE_API int sqlite3_create_collation_v2(
-  sqlite3*, 
-  const char *zName, 
-  int eTextRep, 
+  sqlite3*,
+  const char *zName,
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*),
   void(*xDestroy)(void*)
 );
 SQLITE_API int sqlite3_create_collation16(
-  sqlite3*, 
+  sqlite3*,
   const void *zName,
-  int eTextRep, 
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*)
 );
@@ -6707,64 +7005,19 @@ SQLITE_API int sqlite3_create_collation16(
 ** [sqlite3_create_collation_v2()].
 */
 SQLITE_API int sqlite3_collation_needed(
-  sqlite3*, 
-  void*, 
+  sqlite3*,
+  void*,
   void(*)(void*,sqlite3*,int eTextRep,const char*)
 );
 SQLITE_API int sqlite3_collation_needed16(
-  sqlite3*, 
+  sqlite3*,
   void*,
   void(*)(void*,sqlite3*,int eTextRep,const void*)
 );
 
-#ifdef SQLITE_HAS_CODEC
-/*
-** Specify the key for an encrypted database.  This routine should be
-** called right after sqlite3_open().
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_key(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const void *pKey, int nKey     /* The key */
-);
-SQLITE_API int sqlite3_key_v2(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const char *zDbName,           /* Name of the database */
-  const void *pKey, int nKey     /* The key */
-);
-
-/*
-** Change the key on an open database.  If the current database is not
-** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
-** database is decrypted.
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_rekey(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const void *pKey, int nKey     /* The new key */
-);
-SQLITE_API int sqlite3_rekey_v2(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const char *zDbName,           /* Name of the database */
-  const void *pKey, int nKey     /* The new key */
-);
-
-/*
-** Specify the activation key for a SEE database.  Unless 
-** activated, none of the SEE routines will work.
-*/
-SQLITE_API void sqlite3_activate_see(
-  const char *zPassPhrase        /* Activation phrase */
-);
-#endif
-
 #ifdef SQLITE_ENABLE_CEROD
 /*
-** Specify the activation key for a CEROD database.  Unless 
+** Specify the activation key for a CEROD database.  Unless
 ** activated, none of the CEROD routines will work.
 */
 SQLITE_API void sqlite3_activate_cerod(
@@ -6820,7 +7073,7 @@ SQLITE_API int sqlite3_sleep(int);
 ** ^The [temp_store_directory pragma] may modify this variable and cause
 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 ** the [temp_store_directory pragma] always assumes that any string
-** that this variable points to is held in memory obtained from 
+** that this variable points to is held in memory obtained from
 ** [sqlite3_malloc] and the pragma may attempt to free that memory
 ** using [sqlite3_free].
 ** Hence, if this variable is modified directly, either it should be
@@ -6877,7 +7130,7 @@ char *sqlite3_temp_directory;
 ** ^The [data_store_directory pragma] may modify this variable and cause
 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 ** the [data_store_directory pragma] always assumes that any string
-** that this variable points to is held in memory obtained from 
+** that this variable points to is held in memory obtained from
 ** [sqlite3_malloc] and the pragma may attempt to free that memory
 ** using [sqlite3_free].
 ** Hence, if this variable is modified directly, either it should be
@@ -6962,16 +7215,31 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
 ** CAPI3REF: Return The Filename For A Database Connection
 ** METHOD: sqlite3
 **
-** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
-** associated with database N of connection D.  ^The main database file
-** has the name "main".  If there is no attached database N on the database
+** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
+** associated with database N of connection D.
+** ^If there is no attached database N on the database
 ** connection D, or if database N is a temporary or in-memory database, then
 ** this function will return either a NULL pointer or an empty string.
 **
+** ^The string value returned by this routine is owned and managed by
+** the database connection.  ^The value will be valid until the database N
+** is [DETACH]-ed or until the database connection closes.
+**
 ** ^The filename returned by this function is the output of the
 ** xFullPathname method of the [VFS].  ^In other words, the filename
 ** will be an absolute pathname, even if the filename used
 ** to open the database originally was a URI or relative pathname.
+**
+** If the filename pointer returned by this routine is not NULL, then it
+** can be used as the filename input parameter to these routines:
+** <ul>
+** <li> [sqlite3_uri_parameter()]
+** <li> [sqlite3_uri_boolean()]
+** <li> [sqlite3_uri_int64()]
+** <li> [sqlite3_filename_database()]
+** <li> [sqlite3_filename_journal()]
+** <li> [sqlite3_filename_wal()]
+** </ul>
 */
 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
 
@@ -6986,6 +7254,57 @@ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
 
 /*
+** CAPI3REF: Determine the transaction state of a database
+** METHOD: sqlite3
+**
+** ^The sqlite3_txn_state(D,S) interface returns the current
+** [transaction state] of schema S in database connection D.  ^If S is NULL,
+** then the highest transaction state of any schema on database connection D
+** is returned.  Transaction states are (in order of lowest to highest):
+** <ol>
+** <li value="0"> SQLITE_TXN_NONE
+** <li value="1"> SQLITE_TXN_READ
+** <li value="2"> SQLITE_TXN_WRITE
+** </ol>
+** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
+** a valid schema, then -1 is returned.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
+
+/*
+** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+** KEYWORDS: {transaction state}
+**
+** These constants define the current transaction state of a database file.
+** ^The [sqlite3_txn_state(D,S)] interface returns one of these
+** constants in order to describe the transaction state of schema S
+** in [database connection] D.
+**
+** <dl>
+** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
+** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
+** pending.</dd>
+**
+** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
+** <dd>The SQLITE_TXN_READ state means that the database is currently
+** in a read transaction.  Content has been read from the database file
+** but nothing in the database file has changed.  The transaction state
+** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
+** no other conflicting concurrent write transactions.  The transaction
+** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
+** [COMMIT].</dd>
+**
+** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
+** <dd>The SQLITE_TXN_WRITE state means that the database is currently
+** in a write transaction.  Content has been written to the database file
+** but has not yet committed.  The transaction state will change to
+** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
+*/
+#define SQLITE_TXN_NONE  0
+#define SQLITE_TXN_READ  1
+#define SQLITE_TXN_WRITE 2
+
+/*
 ** CAPI3REF: Find the next prepared statement
 ** METHOD: sqlite3
 **
@@ -7075,7 +7394,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 ** ^In the case of an update, this is the [rowid] after the update takes place.
 **
 ** ^(The update hook is not invoked when internal system tables are
-** modified (i.e. sqlite_master and sqlite_sequence).)^
+** modified (i.e. sqlite_sequence).)^
 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
 **
 ** ^In the current implementation, the update hook
@@ -7101,7 +7420,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 ** and [sqlite3_preupdate_hook()] interfaces.
 */
 SQLITE_API void *sqlite3_update_hook(
-  sqlite3*, 
+  sqlite3*,
   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   void*
 );
@@ -7115,25 +7434,29 @@ SQLITE_API void *sqlite3_update_hook(
 ** and disabled if the argument is false.)^
 **
 ** ^Cache sharing is enabled and disabled for an entire process.
-** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). 
+** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
 ** In prior versions of SQLite,
 ** sharing was enabled or disabled for each thread separately.
 **
 ** ^(The cache sharing mode set by this interface effects all subsequent
 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
-** Existing database connections continue use the sharing mode
+** Existing database connections continue to use the sharing mode
 ** that was in effect at the time they were opened.)^
 **
 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
 ** successfully.  An [error code] is returned otherwise.)^
 **
-** ^Shared cache is disabled by default. But this might change in
-** future releases of SQLite.  Applications that care about shared
-** cache setting should set it explicitly.
+** ^Shared cache is disabled by default. It is recommended that it stay
+** that way.  In other words, do not use this routine.  This interface
+** continues to be provided for historical compatibility, but its use is
+** discouraged.  Any use of shared cache is discouraged.  If shared cache
+** must be used, it is recommended that shared cache only be enabled for
+** individual database connections using the [sqlite3_open_v2()] interface
+** with the [SQLITE_OPEN_SHAREDCACHE] flag.
 **
 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
-** and will always return SQLITE_MISUSE. On those systems, 
-** shared cache mode should be enabled per-database connection via 
+** and will always return SQLITE_MISUSE. On those systems,
+** shared cache mode should be enabled per-database connection via
 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
 **
 ** This interface is threadsafe on processors where writing a
@@ -7176,6 +7499,9 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 /*
 ** CAPI3REF: Impose A Limit On Heap Size
 **
+** These interfaces impose limits on the amount of heap memory that will be
+** by all database connections within a single process.
+**
 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
 ** soft limit on the amount of heap memory that may be allocated by SQLite.
 ** ^SQLite strives to keep heap memory utilization below the soft heap
@@ -7183,23 +7509,44 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 ** as heap memory usages approaches the limit.
 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
 ** below the limit, it will exceed the limit rather than generate
-** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
+** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
 ** is advisory only.
 **
-** ^The return value from sqlite3_soft_heap_limit64() is the size of
-** the soft heap limit prior to the call, or negative in the case of an
-** error.  ^If the argument N is negative
-** then no change is made to the soft heap limit.  Hence, the current
-** size of the soft heap limit can be determined by invoking
-** sqlite3_soft_heap_limit64() with a negative argument.
-**
-** ^If the argument N is zero then the soft heap limit is disabled.
+** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
+** N bytes on the amount of memory that will be allocated.  ^The
+** sqlite3_hard_heap_limit64(N) interface is similar to
+** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
+** when the hard heap limit is reached.
 **
-** ^(The soft heap limit is not enforced in the current implementation
+** ^The return value from both sqlite3_soft_heap_limit64() and
+** sqlite3_hard_heap_limit64() is the size of
+** the heap limit prior to the call, or negative in the case of an
+** error.  ^If the argument N is negative
+** then no change is made to the heap limit.  Hence, the current
+** size of heap limits can be determined by invoking
+** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
+**
+** ^Setting the heap limits to zero disables the heap limiter mechanism.
+**
+** ^The soft heap limit may not be greater than the hard heap limit.
+** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
+** is invoked with a value of N that is greater than the hard heap limit,
+** the the soft heap limit is set to the value of the hard heap limit.
+** ^The soft heap limit is automatically enabled whenever the hard heap
+** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
+** the soft heap limit is outside the range of 1..N, then the soft heap
+** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the
+** hard heap limit is enabled makes the soft heap limit equal to the
+** hard heap limit.
+**
+** The memory allocation limits can also be adjusted using
+** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
+**
+** ^(The heap limits are not enforced in the current implementation
 ** if one or more of following conditions are true:
 **
 ** <ul>
-** <li> The soft heap limit is set to zero.
+** <li> The limit value is set to zero.
 ** <li> Memory accounting is disabled using a combination of the
 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
@@ -7210,21 +7557,11 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 **      from the heap.
 ** </ul>)^
 **
-** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), 
-** the soft heap limit is enforced
-** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
-** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
-** the soft heap limit is enforced on every memory allocation.  Without
-** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
-** when memory is allocated by the page cache.  Testing suggests that because
-** the page cache is the predominate memory user in SQLite, most
-** applications will achieve adequate soft heap limit enforcement without
-** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
-**
-** The circumstances under which SQLite will enforce the soft heap limit may
+** The circumstances under which SQLite will enforce the heap limits may
 ** changes in future releases of SQLite.
 */
 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
 
 /*
 ** CAPI3REF: Deprecated Soft Heap Limit Interface
@@ -7249,7 +7586,7 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
 ** the final five arguments with appropriate values if the specified
 ** column exists.  ^The sqlite3_table_column_metadata() interface returns
-** SQLITE_ERROR and if the specified column does not exist.
+** SQLITE_ERROR if the specified column does not exist.
 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
 ** NULL pointer, then this routine simply checks for the existence of the
 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
@@ -7289,7 +7626,7 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
 **
 ** ^If the specified table is actually a view, an [error code] is returned.
 **
-** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
+** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
 ** is not a [WITHOUT ROWID] table and an
 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
 ** parameters are set for the explicitly declared column. ^(If there is no
@@ -7355,7 +7692,7 @@ SQLITE_API int sqlite3_table_column_metadata(
 ** prior to calling this API,
 ** otherwise an error will be returned.
 **
-** <b>Security warning:</b> It is recommended that the 
+** <b>Security warning:</b> It is recommended that the
 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
 ** interface.  The use of the [sqlite3_enable_load_extension()] interface
 ** should be avoided.  This will keep the SQL function [load_extension()]
@@ -7391,7 +7728,7 @@ SQLITE_API int sqlite3_load_extension(
 ** to enable or disable only the C-API.)^
 **
 ** <b>Security warning:</b> It is recommended that extension loading
-** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
+** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
 ** rather than this interface, so the [load_extension()] SQL function
 ** remains disabled. This will prevent SQL injections from giving attackers
 ** access to extension loading capabilities.
@@ -7442,7 +7779,7 @@ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
 ** initialization routine X that was registered using a prior call to
 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
-** routine returns 1 if initialization routine X was successfully 
+** routine returns 1 if initialization routine X was successfully
 ** unregistered and it returns 0 if X was not on the list of initialization
 ** routines.
 */
@@ -7477,8 +7814,8 @@ typedef struct sqlite3_module sqlite3_module;
 ** CAPI3REF: Virtual Table Object
 ** KEYWORDS: sqlite3_module {virtual table module}
 **
-** This structure, sometimes called a "virtual table module", 
-** defines the implementation of a [virtual tables].  
+** This structure, sometimes called a "virtual table module",
+** defines the implementation of a [virtual table].
 ** This structure consists mostly of methods for the module.
 **
 ** ^A virtual table module is created by filling in a persistent
@@ -7517,7 +7854,7 @@ struct sqlite3_module {
                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
                        void **ppArg);
   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
-  /* The methods above are in version 1 of the sqlite_module object. Those 
+  /* The methods above are in version 1 of the sqlite_module object. Those
   ** below are for version 2 and greater. */
   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
   int (*xRelease)(sqlite3_vtab *pVTab, int);
@@ -7567,7 +7904,7 @@ struct sqlite3_module {
 ** required by SQLite. If the table has at least 64 columns and any column
 ** to the right of the first 63 is required, then bit 63 of colUsed is also
 ** set. In other words, column iCol may be required if the expression
-** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to 
+** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
 ** non-zero.
 **
 ** The [xBestIndex] method must fill aConstraintUsage[] with information
@@ -7575,7 +7912,13 @@ struct sqlite3_module {
 ** the right-hand side of the corresponding aConstraint[] is evaluated
 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
 ** is true, then the constraint is assumed to be fully handled by the
-** virtual table and is not checked again by SQLite.)^
+** virtual table and might not be checked again by the byte code.)^ ^(The
+** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
+** is left in its default setting of false, the constraint will always be
+** checked separately in byte code.  If the omit flag is change to true, then
+** the constraint may or may not be checked in byte code.  In other words,
+** when the omit flag is true there is no guarantee that the constraint will
+** not be checked again using byte code.)^
 **
 ** ^The idxNum and idxPtr values are recorded and passed into the
 ** [xFilter] method.
@@ -7588,17 +7931,17 @@ struct sqlite3_module {
 **
 ** ^The estimatedCost value is an estimate of the cost of a particular
 ** strategy. A cost of N indicates that the cost of the strategy is similar
-** to a linear scan of an SQLite table with N rows. A cost of log(N) 
+** to a linear scan of an SQLite table with N rows. A cost of log(N)
 ** indicates that the expense of the operation is similar to that of a
 ** binary search on a unique indexed field of an SQLite table with N rows.
 **
 ** ^The estimatedRows value is an estimate of the number of rows that
 ** will be returned by the strategy.
 **
-** The xBestIndex method may optionally populate the idxFlags field with a 
+** The xBestIndex method may optionally populate the idxFlags field with a
 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
-** assumes that the strategy may visit at most one row. 
+** assumes that the strategy may visit at most one row.
 **
 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
 ** SQLite also assumes that if a call to the xUpdate() method is made as
@@ -7611,14 +7954,14 @@ struct sqlite3_module {
 ** the xUpdate method are automatically rolled back by SQLite.
 **
 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
-** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). 
+** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
 ** If a virtual table extension is
-** used with an SQLite version earlier than 3.8.2, the results of attempting 
-** to read or write the estimatedRows field are undefined (but are likely 
-** to included crashing the application). The estimatedRows field should
+** used with an SQLite version earlier than 3.8.2, the results of attempting
+** to read or write the estimatedRows field are undefined (but are likely
+** to include crashing the application). The estimatedRows field should
 ** therefore only be used if [sqlite3_libversion_number()] returns a
 ** value greater than or equal to 3008002. Similarly, the idxFlags field
-** was added for [version 3.9.0] ([dateof:3.9.0]). 
+** was added for [version 3.9.0] ([dateof:3.9.0]).
 ** It may therefore only be used if
 ** sqlite3_libversion_number() returns a value greater than or equal to
 ** 3009000.
@@ -7658,7 +8001,7 @@ struct sqlite3_index_info {
 /*
 ** CAPI3REF: Virtual Table Scan Flags
 **
-** Virtual table implementations are allowed to set the 
+** Virtual table implementations are allowed to set the
 ** [sqlite3_index_info].idxFlags field to some combination of
 ** these bits.
 */
@@ -7667,7 +8010,7 @@ struct sqlite3_index_info {
 /*
 ** CAPI3REF: Virtual Table Constraint Operator Codes
 **
-** These macros defined the allowed values for the
+** These macros define the allowed values for the
 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
 ** an operator that is part of a constraint term in the wHERE clause of
 ** a query that uses a [virtual table].
@@ -7698,7 +8041,7 @@ struct sqlite3_index_info {
 ** preexisting [virtual table] for the module.
 **
 ** ^The module name is registered on the [database connection] specified
-** by the first parameter.  ^The name of the module is given by the 
+** by the first parameter.  ^The name of the module is given by the
 ** second parameter.  ^The third parameter is a pointer to
 ** the implementation of the [virtual table module].   ^The fourth
 ** parameter is an arbitrary client data pointer that is passed through
@@ -7813,7 +8156,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
 ** METHOD: sqlite3
 **
 ** ^(Virtual tables can provide alternative implementations of functions
-** using the [xFindFunction] method of the [virtual table module].  
+** using the [xFindFunction] method of the [virtual table module].
 ** But global versions of those functions
 ** must exist in order to be overloaded.)^
 **
@@ -7864,7 +8207,7 @@ typedef struct sqlite3_blob sqlite3_blob;
 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
 ** </pre>)^
 **
-** ^(Parameter zDb is not the filename that contains the database, but 
+** ^(Parameter zDb is not the filename that contains the database, but
 ** rather the symbolic name of the database. For attached databases, this is
 ** the name that appears after the AS keyword in the [ATTACH] statement.
 ** For the main database file, the database name is "main". For TEMP
@@ -7877,28 +8220,28 @@ typedef struct sqlite3_blob sqlite3_blob;
 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
-** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
+** the API is not misused, it is always safe to call [sqlite3_blob_close()]
 ** on *ppBlob after this function it returns.
 **
 ** This function fails with SQLITE_ERROR if any of the following are true:
 ** <ul>
-**   <li> ^(Database zDb does not exist)^, 
-**   <li> ^(Table zTable does not exist within database zDb)^, 
-**   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
+**   <li> ^(Database zDb does not exist)^,
+**   <li> ^(Table zTable does not exist within database zDb)^,
+**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
 **   <li> ^(Column zColumn does not exist)^,
 **   <li> ^(Row iRow is not present in the table)^,
 **   <li> ^(The specified column of row iRow contains a value that is not
 **         a TEXT or BLOB value)^,
-**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
+**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
 **         constraint and the blob is being opened for read/write access)^,
-**   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
+**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
 **         column zColumn is part of a [child key] definition and the blob is
 **         being opened for read/write access)^.
 ** </ul>
 **
-** ^Unless it returns SQLITE_MISUSE, this function sets the 
-** [database connection] error code and message accessible via 
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
+** ^Unless it returns SQLITE_MISUSE, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
 **
 ** A BLOB referenced by sqlite3_blob_open() may be read using the
 ** [sqlite3_blob_read()] interface and modified by using
@@ -7924,7 +8267,7 @@ typedef struct sqlite3_blob sqlite3_blob;
 ** blob.
 **
 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
-** and the built-in [zeroblob] SQL function may be used to create a 
+** and the built-in [zeroblob] SQL function may be used to create a
 ** zero-filled blob to read or write using the incremental-blob interface.
 **
 ** To avoid a resource leak, every open [BLOB handle] should eventually
@@ -7974,7 +8317,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
 ** DESTRUCTOR: sqlite3_blob
 **
 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
-** unconditionally.  Even if this routine returns an error code, the 
+** unconditionally.  Even if this routine returns an error code, the
 ** handle is still closed.)^
 **
 ** ^If the blob handle being closed was opened for read-write access, and if
@@ -7984,10 +8327,10 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
 ** code is returned and the transaction rolled back.
 **
 ** Calling this function with an argument that is not a NULL pointer or an
-** open blob handle results in undefined behaviour. ^Calling this routine 
-** with a null pointer (such as would be returned by a failed call to 
+** open blob handle results in undefined behaviour. ^Calling this routine
+** with a null pointer (such as would be returned by a failed call to
 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
-** is passed a valid open blob handle, the values returned by the 
+** is passed a valid open blob handle, the values returned by the
 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
 */
 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
@@ -7996,7 +8339,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
 ** CAPI3REF: Return The Size Of An Open BLOB
 ** METHOD: sqlite3_blob
 **
-** ^Returns the size in bytes of the BLOB accessible via the 
+** ^Returns the size in bytes of the BLOB accessible via the
 ** successfully opened [BLOB handle] in its only argument.  ^The
 ** incremental blob I/O routines can only read or overwriting existing
 ** blob content; they cannot change the size of a blob.
@@ -8047,9 +8390,9 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
 **
 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
-** ^Unless SQLITE_MISUSE is returned, this function sets the 
-** [database connection] error code and message accessible via 
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
+** ^Unless SQLITE_MISUSE is returned, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
 **
 ** ^If the [BLOB handle] passed as the first argument was not opened for
 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
@@ -8058,9 +8401,9 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
 ** This function may only modify the contents of the BLOB; it is
 ** not possible to increase the size of a BLOB using this API.
 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
-** [SQLITE_ERROR] is returned and no data is written. The size of the 
-** BLOB (and hence the maximum value of N+iOffset) can be determined 
-** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
+** [SQLITE_ERROR] is returned and no data is written. The size of the
+** BLOB (and hence the maximum value of N+iOffset) can be determined
+** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
 ** than zero [SQLITE_ERROR] is returned and no data is written.
 **
 ** ^An attempt to write to an expired [BLOB handle] fails with an
@@ -8154,7 +8497,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
 ** <ul>
 ** <li>  SQLITE_MUTEX_FAST
 ** <li>  SQLITE_MUTEX_RECURSIVE
-** <li>  SQLITE_MUTEX_STATIC_MASTER
+** <li>  SQLITE_MUTEX_STATIC_MAIN
 ** <li>  SQLITE_MUTEX_STATIC_MEM
 ** <li>  SQLITE_MUTEX_STATIC_OPEN
 ** <li>  SQLITE_MUTEX_STATIC_PRNG
@@ -8212,7 +8555,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
 ** ^(Some systems (for example, Windows 95) do not support the operation
 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
 ** will always return SQLITE_BUSY. The SQLite core only ever uses
-** sqlite3_mutex_try() as an optimization so this is acceptable 
+** sqlite3_mutex_try() as an optimization so this is acceptable
 ** behavior.)^
 **
 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
@@ -8277,7 +8620,7 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
 ** The only difference is that the public sqlite3_XXX functions enumerated
 ** above silently ignore any invocations that pass a NULL pointer instead
 ** of a valid mutex handle. The implementations of the methods defined
-** by this structure are not required to handle this case, the results
+** by this structure are not required to handle this case. The results
 ** of passing a NULL pointer instead of a valid mutex handle are undefined
 ** (i.e. it is acceptable to provide an implementation that segfaults if
 ** it is passed a NULL pointer).
@@ -8356,7 +8699,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
 */
 #define SQLITE_MUTEX_FAST             0
 #define SQLITE_MUTEX_RECURSIVE        1
-#define SQLITE_MUTEX_STATIC_MASTER    2
+#define SQLITE_MUTEX_STATIC_MAIN      2
 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
@@ -8371,11 +8714,15 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
 #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
 #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
 
+/* Legacy compatibility: */
+#define SQLITE_MUTEX_STATIC_MASTER    2
+
+
 /*
 ** CAPI3REF: Retrieve the mutex for a database connection
 ** METHOD: sqlite3
 **
-** ^This interface returns a pointer the [sqlite3_mutex] object that 
+** ^This interface returns a pointer the [sqlite3_mutex] object that
 ** serializes access to the [database connection] given in the argument
 ** when the [threading mode] is Serialized.
 ** ^If the [threading mode] is Single-thread or Multi-thread then this
@@ -8402,7 +8749,7 @@ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
 ** method becomes the return value of this routine.
 **
 ** A few opcodes for [sqlite3_file_control()] are handled directly
-** by the SQLite core and never invoke the 
+** by the SQLite core and never invoke the
 ** sqlite3_io_methods.xFileControl method.
 ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
 ** a pointer to the underlying [sqlite3_file] object to be written into
@@ -8466,7 +8813,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_PENDING_BYTE            11
 #define SQLITE_TESTCTRL_ASSERT                  12
 #define SQLITE_TESTCTRL_ALWAYS                  13
-#define SQLITE_TESTCTRL_RESERVE                 14
+#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */
 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
 #define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */
 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
@@ -8484,12 +8831,14 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_RESULT_INTREAL          27
 #define SQLITE_TESTCTRL_PRNG_SEED               28
 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
-#define SQLITE_TESTCTRL_LAST                    29  /* Largest TESTCTRL */
+#define SQLITE_TESTCTRL_SEEK_COUNT              30
+#define SQLITE_TESTCTRL_TRACEFLAGS              31
+#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
 
 /*
 ** CAPI3REF: SQL Keyword Checking
 **
-** These routines provide access to the set of SQL language keywords 
+** These routines provide access to the set of SQL language keywords
 ** recognized by SQLite.  Applications can uses these routines to determine
 ** whether or not a specific identifier needs to be escaped (for example,
 ** by enclosing in double-quotes) so as not to confuse the parser.
@@ -8561,14 +8910,14 @@ typedef struct sqlite3_str sqlite3_str;
 **
 ** ^The [sqlite3_str_new(D)] interface allocates and initializes
 ** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
-** [sqlite3_str_new()] must be freed by a subsequent call to 
+** [sqlite3_str_new()] must be freed by a subsequent call to
 ** [sqlite3_str_finish(X)].
 **
 ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
 ** valid [sqlite3_str] object, though in the event of an out-of-memory
 ** error the returned object might be a special singleton that will
-** silently reject new text, always return SQLITE_NOMEM from 
-** [sqlite3_str_errcode()], always return 0 for 
+** silently reject new text, always return SQLITE_NOMEM from
+** [sqlite3_str_errcode()], always return 0 for
 ** [sqlite3_str_length()], and always return NULL from
 ** [sqlite3_str_finish(X)].  It is always safe to use the value
 ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
@@ -8604,9 +8953,9 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
 ** These interfaces add content to an sqlite3_str object previously obtained
 ** from [sqlite3_str_new()].
 **
-** ^The [sqlite3_str_appendf(X,F,...)] and 
+** ^The [sqlite3_str_appendf(X,F,...)] and
 ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
-** functionality of SQLite to append formatted text onto the end of 
+** functionality of SQLite to append formatted text onto the end of
 ** [sqlite3_str] object X.
 **
 ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
@@ -8623,7 +8972,7 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
 ** ^This method can be used, for example, to add whitespace indentation.
 **
 ** ^The [sqlite3_str_reset(X)] method resets the string under construction
-** inside [sqlite3_str] object X back to zero bytes in length.  
+** inside [sqlite3_str] object X back to zero bytes in length.
 **
 ** These methods do not return a result code.  ^If an error occurs, that fact
 ** is recorded in the [sqlite3_str] object and can be recovered by a
@@ -8725,7 +9074,7 @@ SQLITE_API int sqlite3_status64(
 ** <dd>This parameter records the largest memory allocation request
 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
 ** internal equivalents).  Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.  
+** *pHighwater parameter to [sqlite3_status()] is of interest.
 ** The value written into the *pCurrent parameter is undefined.</dd>)^
 **
 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
@@ -8734,11 +9083,11 @@ SQLITE_API int sqlite3_status64(
 **
 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
 ** <dd>This parameter returns the number of pages used out of the
-** [pagecache memory allocator] that was configured using 
+** [pagecache memory allocator] that was configured using
 ** [SQLITE_CONFIG_PAGECACHE].  The
 ** value returned is in pages, not in bytes.</dd>)^
 **
-** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
+** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
 ** <dd>This parameter returns the number of bytes of page cache
 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
@@ -8750,8 +9099,8 @@ SQLITE_API int sqlite3_status64(
 **
 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
 ** <dd>This parameter records the largest memory allocation request
-** handed to [pagecache memory allocator].  Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.  
+** handed to the [pagecache memory allocator].  Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
 ** The value written into the *pCurrent parameter is undefined.</dd>)^
 **
 ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
@@ -8764,7 +9113,7 @@ SQLITE_API int sqlite3_status64(
 ** <dd>No longer used.</dd>
 **
 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
-** <dd>The *pHighwater parameter records the deepest parser stack. 
+** <dd>The *pHighwater parameter records the deepest parser stack.
 ** The *pCurrent value is undefined.  The *pHighwater value is only
 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
 ** </dl>
@@ -8786,12 +9135,12 @@ SQLITE_API int sqlite3_status64(
 ** CAPI3REF: Database Connection Status
 ** METHOD: sqlite3
 **
-** ^This interface is used to retrieve runtime status information 
+** ^This interface is used to retrieve runtime status information
 ** about a single [database connection].  ^The first argument is the
 ** database connection object to be interrogated.  ^The second argument
 ** is an integer constant, taken from the set of
 ** [SQLITE_DBSTATUS options], that
-** determines the parameter to interrogate.  The set of 
+** determines the parameter to interrogate.  The set of
 ** [SQLITE_DBSTATUS options] is likely
 ** to grow in future releases of SQLite.
 **
@@ -8826,7 +9175,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** checked out.</dd>)^
 **
 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
-** <dd>This parameter returns the number malloc attempts that were 
+** <dd>This parameter returns the number of malloc attempts that were
 ** satisfied using lookaside memory. Only the high-water value is meaningful;
 ** the current value is always zero.)^
 **
@@ -8851,7 +9200,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** memory used by all pager caches associated with the database connection.)^
 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
 **
-** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] 
+** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
 ** pager cache is shared between two or more connections the bytes of heap
@@ -8866,7 +9215,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
 ** <dd>This parameter returns the approximate number of bytes of heap
 ** memory used to store the schema for all databases associated
-** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
+** with the connection - main, temp, and any [ATTACH]-ed databases.)^
 ** ^The full amount of memory used by the schemas is reported, even if the
 ** schema memory is shared with other database connections due to
 ** [shared cache mode] being enabled.
@@ -8881,13 +9230,13 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 **
 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
 ** <dd>This parameter returns the number of pager cache hits that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
 ** is always 0.
 ** </dd>
 **
 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
 ** <dd>This parameter returns the number of pager cache misses that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
 ** is always 0.
 ** </dd>
 **
@@ -8908,7 +9257,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** cache overflowing. Transactions are more efficient if they are written
 ** to disk all at once. When pages spill mid-transaction, that introduces
 ** additional overhead. This parameter can be used help identify
-** inefficiencies that can be resolve by increasing the cache size.
+** inefficiencies that can be resolved by increasing the cache size.
 ** </dd>
 **
 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
@@ -8945,7 +9294,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** statements.  For example, if the number of table steps greatly exceeds
 ** the number of table searches or result rows, that would tend to indicate
 ** that the prepared statement is using a full table scan rather than
-** an index.  
+** an index.
 **
 ** ^(This interface is used to retrieve and reset counter values from
 ** a [prepared statement].  The first argument is the prepared statement
@@ -8972,7 +9321,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
 ** <dd>^This is the number of times that SQLite has stepped forward in
 ** a table as part of a full table scan.  Large numbers for this counter
-** may indicate opportunities for performance improvement through 
+** may indicate opportunities for performance improvement through
 ** careful use of indices.</dd>
 **
 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
@@ -8990,14 +9339,14 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
 ** <dd>^This is the number of virtual machine operations executed
 ** by the prepared statement if that number is less than or equal
-** to 2147483647.  The number of virtual machine operations can be 
+** to 2147483647.  The number of virtual machine operations can be
 ** used as a proxy for the total work done by the prepared statement.
 ** If the number of virtual machine operations exceeds 2147483647
 ** then the value returned by this statement status code is undefined.
 **
 ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
 ** <dd>^This is the number of times that the prepare statement has been
-** automatically regenerated due to schema changes or change to 
+** automatically regenerated due to schema changes or changes to
 ** [bound parameters] that might affect the query plan.
 **
 ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
@@ -9057,15 +9406,15 @@ struct sqlite3_pcache_page {
 ** KEYWORDS: {page cache}
 **
 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
-** register an alternative page cache implementation by passing in an 
+** register an alternative page cache implementation by passing in an
 ** instance of the sqlite3_pcache_methods2 structure.)^
-** In many applications, most of the heap memory allocated by 
+** In many applications, most of the heap memory allocated by
 ** SQLite is used for the page cache.
-** By implementing a 
+** By implementing a
 ** custom page cache using this API, an application can better control
-** the amount of memory consumed by SQLite, the way in which 
-** that memory is allocated and released, and the policies used to 
-** determine exactly which parts of a database file are cached and for 
+** the amount of memory consumed by SQLite, the way in which
+** that memory is allocated and released, and the policies used to
+** determine exactly which parts of a database file are cached and for
 ** how long.
 **
 ** The alternative page cache mechanism is an
@@ -9078,19 +9427,19 @@ struct sqlite3_pcache_page {
 ** [sqlite3_config()] returns.)^
 **
 ** [[the xInit() page cache method]]
-** ^(The xInit() method is called once for each effective 
+** ^(The xInit() method is called once for each effective
 ** call to [sqlite3_initialize()])^
 ** (usually only once during the lifetime of the process). ^(The xInit()
 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
-** The intent of the xInit() method is to set up global data structures 
-** required by the custom page cache implementation. 
-** ^(If the xInit() method is NULL, then the 
+** The intent of the xInit() method is to set up global data structures
+** required by the custom page cache implementation.
+** ^(If the xInit() method is NULL, then the
 ** built-in default page cache is used instead of the application defined
 ** page cache.)^
 **
 ** [[the xShutdown() page cache method]]
 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
-** It can be used to clean up 
+** It can be used to clean up
 ** any outstanding resources before process shutdown, if required.
 ** ^The xShutdown() method may be NULL.
 **
@@ -9109,7 +9458,7 @@ struct sqlite3_pcache_page {
 ** though this is not guaranteed. ^The
 ** first parameter, szPage, is the size in bytes of the pages that must
 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
-** second parameter szExtra is a number of bytes of extra storage 
+** second parameter szExtra is a number of bytes of extra storage
 ** associated with each page cache entry.  ^The szExtra parameter will
 ** a number less than 250.  SQLite will use the
 ** extra szExtra bytes on each page to store metadata about the underlying
@@ -9122,7 +9471,7 @@ struct sqlite3_pcache_page {
 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
 ** never invoke xUnpin() except to deliberately delete a page.
 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
-** false will always have the "discard" flag set to true.  
+** false will always have the "discard" flag set to true.
 ** ^Hence, a cache created with bPurgeable false will
 ** never contain any unpinned pages.
 **
@@ -9137,12 +9486,12 @@ struct sqlite3_pcache_page {
 ** [[the xPagecount() page cache methods]]
 ** The xPagecount() method must return the number of pages currently
 ** stored in the cache, both pinned and unpinned.
-** 
+**
 ** [[the xFetch() page cache methods]]
-** The xFetch() method locates a page in the cache and returns a pointer to 
+** The xFetch() method locates a page in the cache and returns a pointer to
 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
 ** The pBuf element of the returned sqlite3_pcache_page object will be a
-** pointer to a buffer of szPage bytes used to store the content of a 
+** pointer to a buffer of szPage bytes used to store the content of a
 ** single database page.  The pExtra element of sqlite3_pcache_page will be
 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
 ** for each entry in the page cache.
@@ -9168,7 +9517,7 @@ struct sqlite3_pcache_page {
 **
 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
-** failed.)^  In between the to xFetch() calls, SQLite may
+** failed.)^  In between the xFetch() calls, SQLite may
 ** attempt to unpin one or more cache pages by spilling the content of
 ** pinned pages to disk and synching the operating system disk cache.
 **
@@ -9181,8 +9530,8 @@ struct sqlite3_pcache_page {
 ** page cache implementation. ^The page cache implementation
 ** may choose to evict unpinned pages at any time.
 **
-** The cache must not perform any reference counting. A single 
-** call to xUnpin() unpins the page regardless of the number of prior calls 
+** The cache must not perform any reference counting. A single
+** call to xUnpin() unpins the page regardless of the number of prior calls
 ** to xFetch().
 **
 ** [[the xRekey() page cache methods]]
@@ -9222,7 +9571,7 @@ struct sqlite3_pcache_methods2 {
   int (*xPagecount)(sqlite3_pcache*);
   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
-  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
+  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
       unsigned oldKey, unsigned newKey);
   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   void (*xDestroy)(sqlite3_pcache*);
@@ -9267,7 +9616,7 @@ typedef struct sqlite3_backup sqlite3_backup;
 **
 ** The backup API copies the content of one database into another.
 ** It is useful either for creating backups of databases or
-** for copying in-memory databases to or from persistent files. 
+** for copying in-memory databases to or from persistent files.
 **
 ** See Also: [Using the SQLite Online Backup API]
 **
@@ -9278,36 +9627,36 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** ^Thus, the backup may be performed on a live source database without
 ** preventing other database connections from
 ** reading or writing to the source database while the backup is underway.
-** 
-** ^(To perform a backup operation: 
+**
+** ^(To perform a backup operation:
 **   <ol>
 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
-**         backup, 
-**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
+**         backup,
+**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
 **         the data between the two databases, and finally
-**     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
-**         associated with the backup operation. 
+**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
+**         associated with the backup operation.
 **   </ol>)^
 ** There should be exactly one call to sqlite3_backup_finish() for each
 ** successful call to sqlite3_backup_init().
 **
 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
 **
-** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
-** [database connection] associated with the destination database 
+** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
+** [database connection] associated with the destination database
 ** and the database name, respectively.
 ** ^The database name is "main" for the main database, "temp" for the
 ** temporary database, or the name specified after the AS keyword in
 ** an [ATTACH] statement for an attached database.
-** ^The S and M arguments passed to 
+** ^The S and M arguments passed to
 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
 ** and database name of the source database, respectively.
 ** ^The source and destination [database connections] (parameters S and D)
 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
 ** an error.
 **
-** ^A call to sqlite3_backup_init() will fail, returning NULL, if 
-** there is already a read or read-write transaction open on the 
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
+** there is already a read or read-write transaction open on the
 ** destination database.
 **
 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
@@ -9319,14 +9668,14 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
 ** [sqlite3_backup] object.
 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
-** sqlite3_backup_finish() functions to perform the specified backup 
+** sqlite3_backup_finish() functions to perform the specified backup
 ** operation.
 **
 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
 **
-** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
+** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
 ** the source and destination databases specified by [sqlite3_backup] object B.
-** ^If N is negative, all remaining source pages are copied. 
+** ^If N is negative, all remaining source pages are copied.
 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
 ** are still more pages to be copied, then the function returns [SQLITE_OK].
 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
@@ -9348,8 +9697,8 @@ typedef struct sqlite3_backup sqlite3_backup;
 **
 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
 ** the [sqlite3_busy_handler | busy-handler function]
-** is invoked (if one is specified). ^If the 
-** busy-handler returns non-zero before the lock is available, then 
+** is invoked (if one is specified). ^If the
+** busy-handler returns non-zero before the lock is available, then
 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
 ** sqlite3_backup_step() can be retried later. ^If the source
 ** [database connection]
@@ -9357,15 +9706,15 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
-** [SQLITE_READONLY] is returned, then 
-** there is no point in retrying the call to sqlite3_backup_step(). These 
-** errors are considered fatal.)^  The application must accept 
-** that the backup operation has failed and pass the backup operation handle 
+** [SQLITE_READONLY] is returned, then
+** there is no point in retrying the call to sqlite3_backup_step(). These
+** errors are considered fatal.)^  The application must accept
+** that the backup operation has failed and pass the backup operation handle
 ** to the sqlite3_backup_finish() to release associated resources.
 **
 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
-** on the destination file. ^The exclusive lock is not released until either 
-** sqlite3_backup_finish() is called or the backup operation is complete 
+** on the destination file. ^The exclusive lock is not released until either
+** sqlite3_backup_finish() is called or the backup operation is complete
 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
 ** lasts for the duration of the sqlite3_backup_step() call.
@@ -9374,18 +9723,18 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** through the backup process.  ^If the source database is modified by an
 ** external process or via a database connection other than the one being
 ** used by the backup operation, then the backup will be automatically
-** restarted by the next call to sqlite3_backup_step(). ^If the source 
+** restarted by the next call to sqlite3_backup_step(). ^If the source
 ** database is modified by the using the same database connection as is used
 ** by the backup operation, then the backup database is automatically
 ** updated at the same time.
 **
 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
 **
-** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
+** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
 ** application wishes to abandon the backup operation, the application
 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
 ** ^The sqlite3_backup_finish() interfaces releases all
-** resources associated with the [sqlite3_backup] object. 
+** resources associated with the [sqlite3_backup] object.
 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
 ** active write-transaction on the destination database is rolled back.
 ** The [sqlite3_backup] object is invalid
@@ -9425,8 +9774,8 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** connections, then the source database connection may be used concurrently
 ** from within other threads.
 **
-** However, the application must guarantee that the destination 
-** [database connection] is not passed to any other API (by any thread) after 
+** However, the application must guarantee that the destination
+** [database connection] is not passed to any other API (by any thread) after
 ** sqlite3_backup_init() is called and before the corresponding call to
 ** sqlite3_backup_finish().  SQLite does not currently check to see
 ** if the application incorrectly accesses the destination [database connection]
@@ -9437,11 +9786,11 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** If running in [shared cache mode], the application must
 ** guarantee that the shared cache used by the destination database
 ** is not accessed while the backup is running. In practice this means
-** that the application must guarantee that the disk file being 
+** that the application must guarantee that the disk file being
 ** backed up to is not accessed by any connection within the process,
 ** not just the specific connection that was passed to sqlite3_backup_init().
 **
-** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
+** The [sqlite3_backup] object itself is partially threadsafe. Multiple
 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
 ** APIs are not strictly speaking threadsafe. If they are invoked at the
@@ -9466,8 +9815,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** ^When running in shared-cache mode, a database operation may fail with
 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
 ** individual tables within the shared-cache cannot be obtained. See
-** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
-** ^This API may be used to register a callback that SQLite will invoke 
+** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
+** ^This API may be used to register a callback that SQLite will invoke
 ** when the connection currently holding the required lock relinquishes it.
 ** ^This API is only available if the library was compiled with the
 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
@@ -9475,18 +9824,18 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** See Also: [Using the SQLite Unlock Notification Feature].
 **
 ** ^Shared-cache locks are released when a database connection concludes
-** its current transaction, either by committing it or rolling it back. 
+** its current transaction, either by committing it or rolling it back.
 **
 ** ^When a connection (known as the blocked connection) fails to obtain a
 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
 ** identity of the database connection (the blocking connection) that
-** has locked the required resource is stored internally. ^After an 
+** has locked the required resource is stored internally. ^After an
 ** application receives an SQLITE_LOCKED error, it may call the
-** sqlite3_unlock_notify() method with the blocked connection handle as 
+** sqlite3_unlock_notify() method with the blocked connection handle as
 ** the first argument to register for a callback that will be invoked
 ** when the blocking connections current transaction is concluded. ^The
 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
-** call that concludes the blocking connections transaction.
+** call that concludes the blocking connection's transaction.
 **
 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
 ** there is a chance that the blocking connection will have already
@@ -9496,15 +9845,15 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** ^If the blocked connection is attempting to obtain a write-lock on a
 ** shared-cache table, and more than one other connection currently holds
-** a read-lock on the same table, then SQLite arbitrarily selects one of 
+** a read-lock on the same table, then SQLite arbitrarily selects one of
 ** the other connections to use as the blocking connection.
 **
-** ^(There may be at most one unlock-notify callback registered by a 
+** ^(There may be at most one unlock-notify callback registered by a
 ** blocked connection. If sqlite3_unlock_notify() is called when the
 ** blocked connection already has a registered unlock-notify callback,
 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
 ** called with a NULL pointer as its second argument, then any existing
-** unlock-notify callback is canceled. ^The blocked connections 
+** unlock-notify callback is canceled. ^The blocked connections
 ** unlock-notify callback may also be canceled by closing the blocked
 ** connection using [sqlite3_close()].
 **
@@ -9517,25 +9866,25 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** <b>Callback Invocation Details</b>
 **
-** When an unlock-notify callback is registered, the application provides a 
+** When an unlock-notify callback is registered, the application provides a
 ** single void* pointer that is passed to the callback when it is invoked.
 ** However, the signature of the callback function allows SQLite to pass
 ** it an array of void* context pointers. The first argument passed to
 ** an unlock-notify callback is a pointer to an array of void* pointers,
 ** and the second is the number of entries in the array.
 **
-** When a blocking connections transaction is concluded, there may be
+** When a blocking connection's transaction is concluded, there may be
 ** more than one blocked connection that has registered for an unlock-notify
 ** callback. ^If two or more such blocked connections have specified the
 ** same callback function, then instead of invoking the callback function
 ** multiple times, it is invoked once with the set of void* context pointers
 ** specified by the blocked connections bundled together into an array.
-** This gives the application an opportunity to prioritize any actions 
+** This gives the application an opportunity to prioritize any actions
 ** related to the set of unblocked database connections.
 **
 ** <b>Deadlock Detection</b>
 **
-** Assuming that after registering for an unlock-notify callback a 
+** Assuming that after registering for an unlock-notify callback a
 ** database waits for the callback to be issued before taking any further
 ** action (a reasonable assumption), then using this API may cause the
 ** application to deadlock. For example, if connection X is waiting for
@@ -9558,7 +9907,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** <b>The "DROP TABLE" Exception</b>
 **
-** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
+** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
 ** always appropriate to call sqlite3_unlock_notify(). There is however,
 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
 ** SQLite checks if there are any currently executing SELECT statements
@@ -9571,7 +9920,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** One way around this problem is to check the extended error code returned
 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
-** the special "DROP TABLE/INDEX" case, the extended error code is just 
+** the special "DROP TABLE/INDEX" case, the extended error code is just
 ** SQLITE_LOCKED.)^
 */
 SQLITE_API int sqlite3_unlock_notify(
@@ -9662,8 +10011,8 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
 ** is invoked each time data is committed to a database in wal mode.
 **
-** ^(The callback is invoked by SQLite after the commit has taken place and 
-** the associated write-lock on the database released)^, so the implementation 
+** ^(The callback is invoked by SQLite after the commit has taken place and
+** the associated write-lock on the database released)^, so the implementation
 ** may read, write or [checkpoint] the database as required.
 **
 ** ^The first parameter passed to the callback function when it is invoked
@@ -9682,7 +10031,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** that does not correspond to any valid SQLite error code, the results
 ** are undefined.
 **
-** A single database handle may have at most a single write-ahead log callback 
+** A single database handle may have at most a single write-ahead log callback
 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
 ** previously registered write-ahead log callback. ^Note that the
 ** [sqlite3_wal_autocheckpoint()] interface and the
@@ -9690,7 +10039,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** overwrite any prior [sqlite3_wal_hook()] settings.
 */
 SQLITE_API void *sqlite3_wal_hook(
-  sqlite3*, 
+  sqlite3*,
   int(*)(void *,sqlite3*,const char*,int),
   void*
 );
@@ -9703,7 +10052,7 @@ SQLITE_API void *sqlite3_wal_hook(
 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
 ** to automatically [checkpoint]
 ** after committing a transaction if there are N or
-** more frames in the [write-ahead log] file.  ^Passing zero or 
+** more frames in the [write-ahead log] file.  ^Passing zero or
 ** a negative value as the nFrame parameter disables automatic
 ** checkpoints entirely.
 **
@@ -9733,7 +10082,7 @@ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
 **
-** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
+** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
 ** [write-ahead log] for database X on [database connection] D to be
 ** transferred into the database file and for the write-ahead log to
 ** be reset.  See the [checkpointing] documentation for addition
@@ -9759,10 +10108,10 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 **
 ** <dl>
 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
-**   ^Checkpoint as many frames as possible without waiting for any database 
-**   readers or writers to finish, then sync the database file if all frames 
+**   ^Checkpoint as many frames as possible without waiting for any database
+**   readers or writers to finish, then sync the database file if all frames
 **   in the log were checkpointed. ^The [busy-handler callback]
-**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
+**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
 **   ^On the other hand, passive mode might leave the checkpoint unfinished
 **   if there are concurrent readers or writers.
 **
@@ -9776,9 +10125,9 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 **
 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
 **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
-**   that after checkpointing the log file it blocks (calls the 
+**   that after checkpointing the log file it blocks (calls the
 **   [busy-handler callback])
-**   until all readers are reading from the database file only. ^This ensures 
+**   until all readers are reading from the database file only. ^This ensures
 **   that the next writer will restart the log file from the beginning.
 **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
 **   database writer attempts while it is pending, but does not impede readers.
@@ -9800,31 +10149,31 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
 **
 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
-** any other process is running a checkpoint operation at the same time, the 
-** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
+** any other process is running a checkpoint operation at the same time, the
+** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
 ** busy-handler configured, it will not be invoked in this case.
 **
-** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
+** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
 ** obtained immediately, and a busy-handler is configured, it is invoked and
 ** the writer lock retried until either the busy-handler returns 0 or the lock
 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
 ** database readers as described above. ^If the busy-handler returns 0 before
 ** the writer lock is obtained or while waiting for database readers, the
-** checkpoint operation proceeds from that point in the same way as 
-** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
+** checkpoint operation proceeds from that point in the same way as
+** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
 **
 ** ^If parameter zDb is NULL or points to a zero length string, then the
-** specified operation is attempted on all WAL databases [attached] to 
+** specified operation is attempted on all WAL databases [attached] to
 ** [database connection] db.  In this case the
-** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
-** an SQLITE_BUSY error is encountered when processing one or more of the 
-** attached WAL databases, the operation is still attempted on any remaining 
-** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
-** error occurs while processing an attached database, processing is abandoned 
-** and the error code is returned to the caller immediately. ^If no error 
-** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
+** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
+** an SQLITE_BUSY error is encountered when processing one or more of the
+** attached WAL databases, the operation is still attempted on any remaining
+** attached databases and SQLITE_BUSY is returned at the end. ^If any other
+** error occurs while processing an attached database, processing is abandoned
+** and the error code is returned to the caller immediately. ^If no error
+** (SQLITE_BUSY or otherwise) is encountered while processing the attached
 ** databases, SQLITE_OK is returned.
 **
 ** ^If database zDb is the name of an attached database that is not in WAL
@@ -9872,14 +10221,20 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(
 ** If this interface is invoked outside the context of an xConnect or
 ** xCreate virtual table method then the behavior is undefined.
 **
-** At present, there is only one option that may be configured using
-** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
-** may be added in the future.
+** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
+** [database connection] in which the virtual table is being created and
+** which is passed in as the first argument to the [xConnect] or [xCreate]
+** method that is invoking sqlite3_vtab_config().  The C parameter is one
+** of the [virtual table configuration options].  The presence and meaning
+** of parameters after C depend on which [virtual table configuration option]
+** is used.
 */
 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 
 /*
 ** CAPI3REF: Virtual Table Configuration Options
+** KEYWORDS: {virtual table configuration options}
+** KEYWORDS: {virtual table configuration option}
 **
 ** These macros define the various options to the
 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
@@ -9887,7 +10242,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 **
 ** <dl>
 ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
-** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
+** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
 ** <dd>Calls of the form
 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
 ** where X is an integer.  If X is zero, then the [virtual table] whose
@@ -9901,24 +10256,46 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 ** If X is non-zero, then the virtual table implementation guarantees
 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
 ** any modifications to internal or persistent data structures have been made.
-** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
+** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
 ** is able to roll back a statement or database transaction, and abandon
-** or continue processing the current SQL statement as appropriate. 
+** or continue processing the current SQL statement as appropriate.
 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
 ** had been ABORT.
 **
 ** Virtual table implementations that are required to handle OR REPLACE
-** must do so within the [xUpdate] method. If a call to the 
-** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
-** CONFLICT policy is REPLACE, the virtual table implementation should 
+** must do so within the [xUpdate] method. If a call to the
+** [sqlite3_vtab_on_conflict()] function indicates that the current ON
+** CONFLICT policy is REPLACE, the virtual table implementation should
 ** silently replace the appropriate rows within the xUpdate callback and
 ** return SQLITE_OK. Or, if this is not possible, it may return
-** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
+** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
 ** constraint handling.
+** </dd>
+**
+** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** prohibits that virtual table from being used from within triggers and
+** views.
+** </dd>
+**
+** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** identify that virtual table as being safe to use from within triggers
+** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
+** virtual table can do no serious harm even if it is controlled by a
+** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
+** flag unless absolutely necessary.
+** </dd>
 ** </dl>
 */
 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
+#define SQLITE_VTAB_INNOCUOUS          2
+#define SQLITE_VTAB_DIRECTONLY         3
 
 /*
 ** CAPI3REF: Determine The Virtual Table Conflict Policy
@@ -9936,10 +10313,11 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
 ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
 **
 ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
-** method of a [virtual table], then it returns true if and only if the
+** method of a [virtual table], then it might return true if the
 ** column is being fetched as part of an UPDATE operation during which the
-** column value will not change.  Applications might use this to substitute
-** a return value that is less expensive to compute and that the corresponding
+** column value will not change.  The virtual table implementation can use
+** this hint as permission to substitute a return value that is less
+** expensive to compute and that the corresponding
 ** [xUpdate] method understands as a "no-change" value.
 **
 ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
@@ -9948,6 +10326,12 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
 ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
 ** In that case, [sqlite3_value_nochange(X)] will return true for the
 ** same column in the [xUpdate] method.
+**
+** The sqlite3_vtab_nochange() routine is an optimization.  Virtual table
+** implementations should continue to give a correct answer even if the
+** sqlite3_vtab_nochange() interface were to always return false.  In the
+** current implementation, the sqlite3_vtab_nochange() interface does always
+** returns false for the enhanced [UPDATE FROM] statement.
 */
 SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 
@@ -9955,12 +10339,12 @@ SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
 **
 ** This function may only be called from within a call to the [xBestIndex]
-** method of a [virtual table]. 
+** method of a [virtual table].
 **
 ** The first argument must be the sqlite3_index_info object that is the
 ** first parameter to the xBestIndex() method. The second argument must be
 ** an index into the aConstraint[] array belonging to the sqlite3_index_info
-** structure passed to xBestIndex. This function returns a pointer to a buffer 
+** structure passed to xBestIndex. This function returns a pointer to a buffer
 ** containing the name of the collation sequence for the corresponding
 ** constraint.
 */
@@ -9998,15 +10382,15 @@ SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_
 **
 ** <dl>
 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
-** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
 ** set to the total number of times that the X-th loop has run.</dd>
 **
 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
-** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
 **
 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
-** <dd>^The "double" variable pointed to by the T parameter will be set to the
+** <dd>^The "double" variable pointed to by the V parameter will be set to the
 ** query planner's estimate for the average number of rows output from each
 ** iteration of the X-th loop.  If the query planner's estimates was accurate,
 ** then this value will approximate the quotient NVISIT/NLOOP and the
@@ -10014,17 +10398,17 @@ SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_
 ** be the NLOOP value for the current loop.
 **
 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
-** <dd>^The "const char *" variable pointed to by the T parameter will be set
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
 ** to a zero-terminated UTF-8 string containing the name of the index or table
 ** used for the X-th loop.
 **
 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
-** <dd>^The "const char *" variable pointed to by the T parameter will be set
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
 ** description for the X-th loop.
 **
 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
-** <dd>^The "int" variable pointed to by the T parameter will be set to the
+** <dd>^The "int" variable pointed to by the V parameter will be set to the
 ** "select-id" for the X-th loop.  The select-id identifies which query or
 ** subquery the loop is part of.  The main query has a select-id of zero.
 ** The select-id is the same value as is output in the first column
@@ -10074,7 +10458,7 @@ SQLITE_API int sqlite3_stmt_scanstatus(
   int idx,                  /* Index of loop to report on */
   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
   void *pOut                /* Result written here */
-);     
+);
 
 /*
 ** CAPI3REF: Zero Scan-Status Counters
@@ -10089,18 +10473,19 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
 
 /*
 ** CAPI3REF: Flush caches to disk mid-transaction
+** METHOD: sqlite3
 **
 ** ^If a write-transaction is open on [database connection] D when the
 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
-** pages in the pager-cache that are not currently in use are written out 
+** pages in the pager-cache that are not currently in use are written out
 ** to disk. A dirty page may be in use if a database cursor created by an
 ** active SQL statement is reading from it, or if it is page 1 of a database
 ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
 ** interface flushes caches for all schemas - "main", "temp", and
 ** any [attached] databases.
 **
-** ^If this function needs to obtain extra database locks before dirty pages 
-** can be flushed to disk, it does so. ^If those locks cannot be obtained 
+** ^If this function needs to obtain extra database locks before dirty pages
+** can be flushed to disk, it does so. ^If those locks cannot be obtained
 ** immediately and there is a busy-handler callback configured, it is invoked
 ** in the usual manner. ^If the required lock still cannot be obtained, then
 ** the database is skipped and an attempt made to flush any dirty pages
@@ -10121,6 +10506,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 
 /*
 ** CAPI3REF: The pre-update hook.
+** METHOD: sqlite3
 **
 ** ^These interfaces are only available if SQLite is compiled using the
 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
@@ -10138,7 +10524,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 **
 ** ^The preupdate hook only fires for changes to real database tables; the
 ** preupdate hook is not invoked for changes to [virtual tables] or to
-** system tables like sqlite_master or sqlite_stat1.
+** system tables like sqlite_sequence or sqlite_stat1.
 **
 ** ^The second parameter to the preupdate callback is a pointer to
 ** the [database connection] that registered the preupdate hook.
@@ -10147,21 +10533,21 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 ** kind of update operation that is about to occur.
 ** ^(The fourth parameter to the preupdate callback is the name of the
 ** database within the database connection that is being modified.  This
-** will be "main" for the main database or "temp" for TEMP tables or 
+** will be "main" for the main database or "temp" for TEMP tables or
 ** the name given after the AS keyword in the [ATTACH] statement for attached
 ** databases.)^
 ** ^The fifth parameter to the preupdate callback is the name of the
 ** table that is being modified.
 **
 ** For an UPDATE or DELETE operation on a [rowid table], the sixth
-** parameter passed to the preupdate callback is the initial [rowid] of the 
+** parameter passed to the preupdate callback is the initial [rowid] of the
 ** row being modified or deleted. For an INSERT operation on a rowid table,
-** or any operation on a WITHOUT ROWID table, the value of the sixth 
+** or any operation on a WITHOUT ROWID table, the value of the sixth
 ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
 ** seventh parameter is the final rowid value of the row being inserted
 ** or updated. The value of the seventh parameter passed to the callback
 ** function is not defined for operations on WITHOUT ROWID tables, or for
-** INSERT operations on rowid tables.
+** DELETE operations on rowid tables.
 **
 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
@@ -10195,7 +10581,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 **
 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
 ** callback was invoked as a result of a direct insert, update, or delete
-** operation; or 1 for inserts, updates, or deletes invoked by top-level 
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
 ** triggers; or 2 for changes resulting from triggers called by top-level
 ** triggers; and so forth.
 **
@@ -10223,13 +10609,14 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
 
 /*
 ** CAPI3REF: Low-level system error code
+** METHOD: sqlite3
 **
 ** ^Attempt to return the underlying operating system error code or error
 ** number that caused the most recent I/O error or failure to open a file.
 ** The return value is OS-dependent.  For example, on unix systems, after
 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
 ** called to get back the underlying "errno" that caused the problem, such
-** as ENOSPC, EAUTH, EISDIR, and so forth.  
+** as ENOSPC, EAUTH, EISDIR, and so forth.
 */
 SQLITE_API int sqlite3_system_errno(sqlite3*);
 
@@ -10267,12 +10654,12 @@ typedef struct sqlite3_snapshot {
 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
 ** If there is not already a read-transaction open on schema S when
-** this function is called, one is opened automatically. 
+** this function is called, one is opened automatically.
 **
 ** The following must be true for this function to succeed. If any of
 ** the following statements are false when sqlite3_snapshot_get() is
 ** called, SQLITE_ERROR is returned. The final value of *P is undefined
-** in this case. 
+** in this case.
 **
 ** <ul>
 **   <li> The database handle must not be in [autocommit mode].
@@ -10284,13 +10671,13 @@ typedef struct sqlite3_snapshot {
 **
 **   <li> One or more transactions must have been written to the current wal
 **        file since it was created on disk (by any connection). This means
-**        that a snapshot cannot be taken on a wal mode database with no wal 
+**        that a snapshot cannot be taken on a wal mode database with no wal
 **        file immediately after it is first opened. At least one transaction
 **        must be written to it first.
 ** </ul>
 **
 ** This function may also return SQLITE_NOMEM.  If it is called with the
-** database handle in autocommit mode but fails for some other reason, 
+** database handle in autocommit mode but fails for some other reason,
 ** whether or not a read transaction is opened on schema S is undefined.
 **
 ** The [sqlite3_snapshot] object returned from a successful call to
@@ -10310,38 +10697,38 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
 ** CAPI3REF: Start a read transaction on an historical snapshot
 ** METHOD: sqlite3_snapshot
 **
-** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read 
-** transaction or upgrades an existing one for schema S of 
-** [database connection] D such that the read transaction refers to 
-** historical [snapshot] P, rather than the most recent change to the 
-** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK 
+** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
+** transaction or upgrades an existing one for schema S of
+** [database connection] D such that the read transaction refers to
+** historical [snapshot] P, rather than the most recent change to the
+** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
 ** on success or an appropriate [error code] if it fails.
 **
-** ^In order to succeed, the database connection must not be in 
+** ^In order to succeed, the database connection must not be in
 ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
 ** is already a read transaction open on schema S, then the database handle
 ** must have no active statements (SELECT statements that have been passed
-** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). 
+** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
 ** SQLITE_ERROR is returned if either of these conditions is violated, or
 ** if schema S does not exist, or if the snapshot object is invalid.
 **
 ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
-** snapshot has been overwritten by a [checkpoint]. In this case 
+** snapshot has been overwritten by a [checkpoint]. In this case
 ** SQLITE_ERROR_SNAPSHOT is returned.
 **
-** If there is already a read transaction open when this function is 
+** If there is already a read transaction open when this function is
 ** invoked, then the same read transaction remains open (on the same
 ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
 ** is returned. If another error code - for example SQLITE_PROTOCOL or an
 ** SQLITE_IOERR error code - is returned, then the final state of the
-** read transaction is undefined. If SQLITE_OK is returned, then the 
+** read transaction is undefined. If SQLITE_OK is returned, then the
 ** read transaction is now open on database snapshot P.
 **
 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
 ** database connection D does not know that the database file for
 ** schema S is in [WAL mode].  A database connection might not know
 ** that the database file is in [WAL mode] if there has been no prior
-** I/O on that database connection, or if the database entered [WAL mode] 
+** I/O on that database connection, or if the database entered [WAL mode]
 ** after the most recent I/O on the database connection.)^
 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
 ** database connection in order to make it ready to use snapshots.)
@@ -10373,17 +10760,17 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
 ** METHOD: sqlite3_snapshot
 **
 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
-** of two valid snapshot handles. 
+** of two valid snapshot handles.
 **
-** If the two snapshot handles are not associated with the same database 
-** file, the result of the comparison is undefined. 
+** If the two snapshot handles are not associated with the same database
+** file, the result of the comparison is undefined.
 **
 ** Additionally, the result of the comparison is only valid if both of the
 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
 ** last time the wal file was deleted. The wal file is deleted when the
 ** database is changed back to rollback mode or when the number of database
-** clients drops to zero. If either snapshot handle was obtained before the 
-** wal file was last deleted, the value returned by this function 
+** clients drops to zero. If either snapshot handle was obtained before the
+** wal file was last deleted, the value returned by this function
 ** is undefined.
 **
 ** Otherwise, this API returns a negative value if P1 refers to an older
@@ -10448,7 +10835,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
 ** representation of the database will usually only exist if there has
 ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
 ** values of D and S.
-** The size of the database is written into *P even if the 
+** The size of the database is written into *P even if the
 ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
 ** of the database exists.
 **
@@ -10485,7 +10872,7 @@ SQLITE_API unsigned char *sqlite3_serialize(
 /*
 ** CAPI3REF: Deserialize a database
 **
-** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the 
+** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
 ** [database connection] D to disconnect from database S and then
 ** reopen S as an in-memory database based on the serialization contained
 ** in P.  The serialized database P is N bytes in size.  M is the size of
@@ -10504,7 +10891,7 @@ SQLITE_API unsigned char *sqlite3_serialize(
 ** database is currently in a read transaction or is involved in a backup
 ** operation.
 **
-** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the 
+** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
 ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
 ** [sqlite3_free()] is invoked on argument P prior to returning.
 **
@@ -10619,7 +11006,7 @@ struct sqlite3_rtree_geometry {
 };
 
 /*
-** Register a 2nd-generation geometry callback named zScore that can be 
+** Register a 2nd-generation geometry callback named zScore that can be
 ** used as part of an R-Tree geometry query as follows:
 **
 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
@@ -10634,7 +11021,7 @@ SQLITE_API int sqlite3_rtree_query_callback(
 
 
 /*
-** A pointer to a structure of the following type is passed as the 
+** A pointer to a structure of the following type is passed as the
 ** argument to scored geometry callback registered using
 ** sqlite3_rtree_query_callback().
 **
@@ -10729,7 +11116,7 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
 ** is not possible for an application to register a pre-update hook on a
 ** database handle that has one or more session objects attached. Nor is
 ** it possible to create a session object attached to a database handle for
-** which a pre-update hook is already defined. The results of attempting 
+** which a pre-update hook is already defined. The results of attempting
 ** either of these things are undefined.
 **
 ** The session object will be used to create changesets for tables in
@@ -10747,13 +11134,13 @@ SQLITE_API int sqlite3session_create(
 ** CAPI3REF: Delete A Session Object
 ** DESTRUCTOR: sqlite3_session
 **
-** Delete a session object previously allocated using 
+** Delete a session object previously allocated using
 ** [sqlite3session_create()]. Once a session object has been deleted, the
 ** results of attempting to use pSession with any other session module
 ** function are undefined.
 **
 ** Session objects must be deleted before the database handle to which they
-** are attached is closed. Refer to the documentation for 
+** are attached is closed. Refer to the documentation for
 ** [sqlite3session_create()] for details.
 */
 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
@@ -10771,10 +11158,10 @@ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
 ** the eventual changesets.
 **
 ** Passing zero to this function disables the session. Passing a value
-** greater than zero enables it. Passing a value less than zero is a 
+** greater than zero enables it. Passing a value less than zero is a
 ** no-op, and may be used to query the current state of the session.
 **
-** The return value indicates the final state of the session object: 0 if 
+** The return value indicates the final state of the session object: 0 if
 ** the session is disabled, or 1 if it is enabled.
 */
 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
@@ -10789,7 +11176,7 @@ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 ** <ul>
 **   <li> The session object "indirect" flag is set when the change is
 **        made, or
-**   <li> The change is made by an SQL trigger or foreign key action 
+**   <li> The change is made by an SQL trigger or foreign key action
 **        instead of directly as a result of a users SQL statement.
 ** </ul>
 **
@@ -10801,10 +11188,10 @@ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 ** flag.  If the second argument passed to this function is zero, then the
 ** indirect flag is cleared. If it is greater than zero, the indirect flag
 ** is set. Passing a value less than zero does not modify the current value
-** of the indirect flag, and may be used to query the current state of the 
+** of the indirect flag, and may be used to query the current state of the
 ** indirect flag for the specified session object.
 **
-** The return value indicates the final state of the indirect flag: 0 if 
+** The return value indicates the final state of the indirect flag: 0 if
 ** it is clear, or 1 if it is set.
 */
 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
@@ -10814,20 +11201,20 @@ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect)
 ** METHOD: sqlite3_session
 **
 ** If argument zTab is not NULL, then it is the name of a table to attach
-** to the session object passed as the first argument. All subsequent changes 
-** made to the table while the session object is enabled will be recorded. See 
+** to the session object passed as the first argument. All subsequent changes
+** made to the table while the session object is enabled will be recorded. See
 ** documentation for [sqlite3session_changeset()] for further details.
 **
 ** Or, if argument zTab is NULL, then changes are recorded for all tables
-** in the database. If additional tables are added to the database (by 
-** executing "CREATE TABLE" statements) after this call is made, changes for 
+** in the database. If additional tables are added to the database (by
+** executing "CREATE TABLE" statements) after this call is made, changes for
 ** the new tables are also recorded.
 **
 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
-** defined as part of their CREATE TABLE statement. It does not matter if the 
+** defined as part of their CREATE TABLE statement. It does not matter if the
 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
 ** KEY may consist of a single column, or may be a composite key.
-** 
+**
 ** It is not an error if the named table does not exist in the database. Nor
 ** is it an error if the named table does not have a PRIMARY KEY. However,
 ** no changes will be recorded in either of these scenarios.
@@ -10835,29 +11222,29 @@ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect)
 ** Changes are not recorded for individual rows that have NULL values stored
 ** in one or more of their PRIMARY KEY columns.
 **
-** SQLITE_OK is returned if the call completes without error. Or, if an error 
+** SQLITE_OK is returned if the call completes without error. Or, if an error
 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
 **
 ** <h3>Special sqlite_stat1 Handling</h3>
 **
-** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to 
+** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
 ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
 **  <pre>
-**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)  
+**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)
 **  </pre>
 **
-** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are 
-** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes 
+** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
+** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
 ** are recorded for rows for which (idx IS NULL) is true. However, for such
 ** rows a zero-length blob (SQL value X'') is stored in the changeset or
 ** patchset instead of a NULL value. This allows such changesets to be
 ** manipulated by legacy implementations of sqlite3changeset_invert(),
 ** concat() and similar.
 **
-** The sqlite3changeset_apply() function automatically converts the 
+** The sqlite3changeset_apply() function automatically converts the
 ** zero-length blob back to a NULL value when updating the sqlite_stat1
 ** table. However, if the application calls sqlite3changeset_new(),
-** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset 
+** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
 ** iterator directly (including on a changeset iterator passed to a
 ** conflict-handler callback) then the X'' value is returned. The application
 ** must translate X'' to NULL itself if required.
@@ -10876,10 +11263,10 @@ SQLITE_API int sqlite3session_attach(
 ** CAPI3REF: Set a table filter on a Session Object.
 ** METHOD: sqlite3_session
 **
-** The second argument (xFilter) is the "filter callback". For changes to rows 
+** The second argument (xFilter) is the "filter callback". For changes to rows
 ** in tables that are not attached to the Session object, the filter is called
-** to determine whether changes to the table's rows should be tracked or not. 
-** If xFilter returns 0, changes is not tracked. Note that once a table is 
+** to determine whether changes to the table's rows should be tracked or not.
+** If xFilter returns 0, changes are not tracked. Note that once a table is
 ** attached, xFilter will not be called again.
 */
 SQLITE_API void sqlite3session_table_filter(
@@ -10895,9 +11282,9 @@ SQLITE_API void sqlite3session_table_filter(
 ** CAPI3REF: Generate A Changeset From A Session Object
 ** METHOD: sqlite3_session
 **
-** Obtain a changeset containing changes to the tables attached to the 
-** session object passed as the first argument. If successful, 
-** set *ppChangeset to point to a buffer containing the changeset 
+** Obtain a changeset containing changes to the tables attached to the
+** session object passed as the first argument. If successful,
+** set *ppChangeset to point to a buffer containing the changeset
 ** and *pnChangeset to the size of the changeset in bytes before returning
 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
 ** zero and return an SQLite error code.
@@ -10912,7 +11299,7 @@ SQLITE_API void sqlite3session_table_filter(
 ** modifies the values of primary key columns. If such a change is made, it
 ** is represented in a changeset as a DELETE followed by an INSERT.
 **
-** Changes are not recorded for rows that have NULL values stored in one or 
+** Changes are not recorded for rows that have NULL values stored in one or
 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
 ** no corresponding change is present in the changesets returned by this
 ** function. If an existing row with one or more NULL values stored in
@@ -10965,14 +11352,14 @@ SQLITE_API void sqlite3session_table_filter(
 ** <ul>
 **   <li> For each record generated by an insert, the database is queried
 **        for a row with a matching primary key. If one is found, an INSERT
-**        change is added to the changeset. If no such row is found, no change 
+**        change is added to the changeset. If no such row is found, no change
 **        is added to the changeset.
 **
-**   <li> For each record generated by an update or delete, the database is 
+**   <li> For each record generated by an update or delete, the database is
 **        queried for a row with a matching primary key. If such a row is
 **        found and one or more of the non-primary key fields have been
-**        modified from their original values, an UPDATE change is added to 
-**        the changeset. Or, if no such row is found in the table, a DELETE 
+**        modified from their original values, an UPDATE change is added to
+**        the changeset. Or, if no such row is found in the table, a DELETE
 **        change is added to the changeset. If there is a row with a matching
 **        primary key in the database, but all fields contain their original
 **        values, no change is added to the changeset.
@@ -10980,7 +11367,7 @@ SQLITE_API void sqlite3session_table_filter(
 **
 ** This means, amongst other things, that if a row is inserted and then later
 ** deleted while a session object is active, neither the insert nor the delete
-** will be present in the changeset. Or if a row is deleted and then later a 
+** will be present in the changeset. Or if a row is deleted and then later a
 ** row with the same primary key values inserted while a session object is
 ** active, the resulting changeset will contain an UPDATE change instead of
 ** a DELETE and an INSERT.
@@ -10989,10 +11376,10 @@ SQLITE_API void sqlite3session_table_filter(
 ** it does not accumulate records when rows are inserted, updated or deleted.
 ** This may appear to have some counter-intuitive effects if a single row
 ** is written to more than once during a session. For example, if a row
-** is inserted while a session object is enabled, then later deleted while 
+** is inserted while a session object is enabled, then later deleted while
 ** the same session object is disabled, no INSERT record will appear in the
 ** changeset, even though the delete took place while the session was disabled.
-** Or, if one field of a row is updated while a session is disabled, and 
+** Or, if one field of a row is updated while a session is disabled, and
 ** another field of the same row is updated while the session is enabled, the
 ** resulting changeset will contain an UPDATE change that updates both fields.
 */
@@ -11013,7 +11400,7 @@ SQLITE_API int sqlite3session_changeset(
 ** an error).
 **
 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
-** attached to the same database handle as the session object that contains 
+** attached to the same database handle as the session object that contains
 ** a table compatible with the table attached to the session by this function.
 ** A table is considered compatible if it:
 **
@@ -11029,33 +11416,33 @@ SQLITE_API int sqlite3session_changeset(
 ** APIs, tables without PRIMARY KEYs are simply ignored.
 **
 ** This function adds a set of changes to the session object that could be
-** used to update the table in database zFrom (call this the "from-table") 
-** so that its content is the same as the table attached to the session 
+** used to update the table in database zFrom (call this the "from-table")
+** so that its content is the same as the table attached to the session
 ** object (call this the "to-table"). Specifically:
 **
 ** <ul>
-**   <li> For each row (primary key) that exists in the to-table but not in 
+**   <li> For each row (primary key) that exists in the to-table but not in
 **     the from-table, an INSERT record is added to the session object.
 **
-**   <li> For each row (primary key) that exists in the to-table but not in 
+**   <li> For each row (primary key) that exists in the to-table but not in
 **     the from-table, a DELETE record is added to the session object.
 **
-**   <li> For each row (primary key) that exists in both tables, but features 
+**   <li> For each row (primary key) that exists in both tables, but features
 **     different non-PK values in each, an UPDATE record is added to the
-**     session.  
+**     session.
 ** </ul>
 **
 ** To clarify, if this function is called and then a changeset constructed
-** using [sqlite3session_changeset()], then after applying that changeset to 
-** database zFrom the contents of the two compatible tables would be 
+** using [sqlite3session_changeset()], then after applying that changeset to
+** database zFrom the contents of the two compatible tables would be
 ** identical.
 **
 ** It an error if database zFrom does not exist or does not contain the
 ** required compatible table.
 **
-** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
+** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
-** may be set to point to a buffer containing an English language error 
+** may be set to point to a buffer containing an English language error
 ** message. It is the responsibility of the caller to free this buffer using
 ** sqlite3_free().
 */
@@ -11074,19 +11461,19 @@ SQLITE_API int sqlite3session_diff(
 ** The differences between a patchset and a changeset are that:
 **
 ** <ul>
-**   <li> DELETE records consist of the primary key fields only. The 
+**   <li> DELETE records consist of the primary key fields only. The
 **        original values of other fields are omitted.
-**   <li> The original values of any modified fields are omitted from 
+**   <li> The original values of any modified fields are omitted from
 **        UPDATE records.
 ** </ul>
 **
-** A patchset blob may be used with up to date versions of all 
-** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), 
+** A patchset blob may be used with up to date versions of all
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
 ** attempting to use a patchset blob with old versions of the
-** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. 
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
 **
-** Because the non-primary key "old.*" fields are omitted, no 
+** Because the non-primary key "old.*" fields are omitted, no
 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
 ** in the same way as for changesets.
@@ -11105,22 +11492,22 @@ SQLITE_API int sqlite3session_patchset(
 /*
 ** CAPI3REF: Test if a changeset has recorded any changes.
 **
-** Return non-zero if no changes to attached tables have been recorded by 
-** the session object passed as the first argument. Otherwise, if one or 
+** Return non-zero if no changes to attached tables have been recorded by
+** the session object passed as the first argument. Otherwise, if one or
 ** more changes have been recorded, return zero.
 **
 ** Even if this function returns zero, it is possible that calling
 ** [sqlite3session_changeset()] on the session handle may still return a
-** changeset that contains no changes. This can happen when a row in 
-** an attached table is modified and then later on the original values 
+** changeset that contains no changes. This can happen when a row in
+** an attached table is modified and then later on the original values
 ** are restored. However, if this function returns non-zero, then it is
-** guaranteed that a call to sqlite3session_changeset() will return a 
+** guaranteed that a call to sqlite3session_changeset() will return a
 ** changeset containing zero changes.
 */
 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 
 /*
-** CAPI3REF: Create An Iterator To Traverse A Changeset 
+** CAPI3REF: Create An Iterator To Traverse A Changeset
 ** CONSTRUCTOR: sqlite3_changeset_iter
 **
 ** Create an iterator used to iterate through the contents of a changeset.
@@ -11128,7 +11515,7 @@ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
 ** SQLite error code is returned.
 **
-** The following functions can be used to advance and query a changeset 
+** The following functions can be used to advance and query a changeset
 ** iterator created by this function:
 **
 ** <ul>
@@ -11145,12 +11532,12 @@ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 **
 ** Assuming the changeset blob was created by one of the
 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
-** [sqlite3changeset_invert()] functions, all changes within the changeset 
-** that apply to a single table are grouped together. This means that when 
-** an application iterates through a changeset using an iterator created by 
-** this function, all changes that relate to a single table are visited 
-** consecutively. There is no chance that the iterator will visit a change 
-** the applies to table X, then one for table Y, and then later on visit 
+** [sqlite3changeset_invert()] functions, all changes within the changeset
+** that apply to a single table are grouped together. This means that when
+** an application iterates through a changeset using an iterator created by
+** this function, all changes that relate to a single table are visited
+** consecutively. There is no chance that the iterator will visit a change
+** the applies to table X, then one for table Y, and then later on visit
 ** another change for table X.
 **
 ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
@@ -11190,7 +11577,7 @@ SQLITE_API int sqlite3changeset_start_v2(
 ** CAPI3REF: Advance A Changeset Iterator
 ** METHOD: sqlite3_changeset_iter
 **
-** This function may only be used with iterators created by function
+** This function may only be used with iterators created by the function
 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
 ** is returned and the call has no effect.
@@ -11201,12 +11588,12 @@ SQLITE_API int sqlite3changeset_start_v2(
 ** point to the first change in the changeset. Each subsequent call advances
 ** the iterator to point to the next change in the changeset (if any). If
 ** no error occurs and the iterator points to a valid change after a call
-** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. 
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
 ** Otherwise, if all changes in the changeset have already been visited,
 ** SQLITE_DONE is returned.
 **
-** If an error occurs, an SQLite error code is returned. Possible error 
-** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or 
+** If an error occurs, an SQLite error code is returned. Possible error
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
 ** SQLITE_NOMEM.
 */
 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
@@ -11224,14 +11611,14 @@ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
 ** If argument pzTab is not NULL, then *pzTab is set to point to a
 ** nul-terminated utf-8 encoded string containing the name of the table
 ** affected by the current change. The buffer remains valid until either
-** sqlite3changeset_next() is called on the iterator or until the 
-** conflict-handler function returns. If pnCol is not NULL, then *pnCol is 
+** sqlite3changeset_next() is called on the iterator or until the
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
 ** set to the number of columns in the table affected by the change. If
 ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
 ** is an indirect change, or false (0) otherwise. See the documentation for
 ** [sqlite3session_indirect()] for a description of direct and indirect
-** changes. Finally, if pOp is not NULL, then *pOp is set to one of 
-** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the 
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
 ** type of change that the iterator currently points to.
 **
 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
@@ -11285,7 +11672,7 @@ SQLITE_API int sqlite3changeset_pk(
 ** The pIter argument passed to this function may either be an iterator
 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
 ** Furthermore, it may only be called if the type of change that the iterator
 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
@@ -11295,9 +11682,9 @@ SQLITE_API int sqlite3changeset_pk(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of 
+** sqlite3_value object containing the iVal'th value from the vector of
 ** original row values stored as part of the UPDATE or DELETE change and
-** returns SQLITE_OK. The name of the function comes from the fact that this 
+** returns SQLITE_OK. The name of the function comes from the fact that this
 ** is similar to the "old.*" columns available to update or delete triggers.
 **
 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
@@ -11316,7 +11703,7 @@ SQLITE_API int sqlite3changeset_old(
 ** The pIter argument passed to this function may either be an iterator
 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
 ** Furthermore, it may only be called if the type of change that the iterator
 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
@@ -11326,12 +11713,12 @@ SQLITE_API int sqlite3changeset_old(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of 
+** sqlite3_value object containing the iVal'th value from the vector of
 ** new row values stored as part of the UPDATE or INSERT change and
 ** returns SQLITE_OK. If the change is an UPDATE and does not include
-** a new value for the requested column, *ppValue is set to NULL and 
-** SQLITE_OK returned. The name of the function comes from the fact that 
-** this is similar to the "new.*" columns available to update or delete 
+** a new value for the requested column, *ppValue is set to NULL and
+** SQLITE_OK returned. The name of the function comes from the fact that
+** this is similar to the "new.*" columns available to update or delete
 ** triggers.
 **
 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
@@ -11358,7 +11745,7 @@ SQLITE_API int sqlite3changeset_new(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the 
+** sqlite3_value object containing the iVal'th value from the
 ** "conflicting row" associated with the current conflict-handler callback
 ** and returns SQLITE_OK.
 **
@@ -11402,7 +11789,7 @@ SQLITE_API int sqlite3changeset_fk_conflicts(
 ** call has no effect.
 **
 ** If an error was encountered within a call to an sqlite3changeset_xxx()
-** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an 
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
 ** to that error is returned by this function. Otherwise, SQLITE_OK is
 ** returned. This is to allow the following pattern (pseudo-code):
@@ -11414,7 +11801,7 @@ SQLITE_API int sqlite3changeset_fk_conflicts(
 **   }
 **   rc = sqlite3changeset_finalize();
 **   if( rc!=SQLITE_OK ){
-**     // An error has occurred 
+**     // An error has occurred
 **   }
 ** </pre>
 */
@@ -11442,7 +11829,7 @@ SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
 ** zeroed and an SQLite error code returned.
 **
 ** It is the responsibility of the caller to eventually call sqlite3_free()
-** on the *ppOut pointer to free the buffer allocation following a successful 
+** on the *ppOut pointer to free the buffer allocation following a successful
 ** call to this function.
 **
 ** WARNING/TODO: This function currently assumes that the input is a valid
@@ -11456,11 +11843,11 @@ SQLITE_API int sqlite3changeset_invert(
 /*
 ** CAPI3REF: Concatenate Two Changeset Objects
 **
-** This function is used to concatenate two changesets, A and B, into a 
+** This function is used to concatenate two changesets, A and B, into a
 ** single changeset. The result is a changeset equivalent to applying
-** changeset A followed by changeset B. 
+** changeset A followed by changeset B.
 **
-** This function combines the two input changesets using an 
+** This function combines the two input changesets using an
 ** sqlite3_changegroup object. Calling it produces similar results as the
 ** following code fragment:
 **
@@ -11492,7 +11879,7 @@ SQLITE_API int sqlite3changeset_concat(
 /*
 ** CAPI3REF: Changegroup Handle
 **
-** A changegroup is an object used to combine two or more 
+** A changegroup is an object used to combine two or more
 ** [changesets] or [patchsets]
 */
 typedef struct sqlite3_changegroup sqlite3_changegroup;
@@ -11508,7 +11895,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 **
 ** If successful, this function returns SQLITE_OK and populates (*pp) with
 ** a pointer to a new sqlite3_changegroup object before returning. The caller
-** should eventually free the returned object using a call to 
+** should eventually free the returned object using a call to
 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
 **
@@ -11520,7 +11907,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 **   <li> Zero or more changesets (or patchsets) are added to the object
 **        by calling sqlite3changegroup_add().
 **
-**   <li> The result of combining all input changesets together is obtained 
+**   <li> The result of combining all input changesets together is obtained
 **        by the application via a call to sqlite3changegroup_output().
 **
 **   <li> The object is deleted using a call to sqlite3changegroup_delete().
@@ -11529,7 +11916,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 ** Any number of calls to add() and output() may be made between the calls to
 ** new() and delete(), and in any order.
 **
-** As well as the regular sqlite3changegroup_add() and 
+** As well as the regular sqlite3changegroup_add() and
 ** sqlite3changegroup_output() functions, also available are the streaming
 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
 */
@@ -11540,7 +11927,7 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 ** METHOD: sqlite3_changegroup
 **
 ** Add all changes within the changeset (or patchset) in buffer pData (size
-** nData bytes) to the changegroup. 
+** nData bytes) to the changegroup.
 **
 ** If the buffer contains a patchset, then all prior calls to this function
 ** on the same changegroup object must also have specified patchsets. Or, if
@@ -11567,7 +11954,7 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 **       changeset was recorded immediately after the changesets already
 **       added to the changegroup.
 **   <tr><td>INSERT <td>UPDATE <td>
-**       The INSERT change remains in the changegroup. The values in the 
+**       The INSERT change remains in the changegroup. The values in the
 **       INSERT change are modified as if the row was inserted by the
 **       existing change and then updated according to the new change.
 **   <tr><td>INSERT <td>DELETE <td>
@@ -11578,17 +11965,17 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 **       changeset was recorded immediately after the changesets already
 **       added to the changegroup.
 **   <tr><td>UPDATE <td>UPDATE <td>
-**       The existing UPDATE remains within the changegroup. It is amended 
-**       so that the accompanying values are as if the row was updated once 
+**       The existing UPDATE remains within the changegroup. It is amended
+**       so that the accompanying values are as if the row was updated once
 **       by the existing change and then again by the new change.
 **   <tr><td>UPDATE <td>DELETE <td>
 **       The existing UPDATE is replaced by the new DELETE within the
 **       changegroup.
 **   <tr><td>DELETE <td>INSERT <td>
 **       If one or more of the column values in the row inserted by the
-**       new change differ from those in the row deleted by the existing 
+**       new change differ from those in the row deleted by the existing
 **       change, the existing DELETE is replaced by an UPDATE within the
-**       changegroup. Otherwise, if the inserted row is exactly the same 
+**       changegroup. Otherwise, if the inserted row is exactly the same
 **       as the deleted row, the existing DELETE is simply discarded.
 **   <tr><td>DELETE <td>UPDATE <td>
 **       The new change is ignored. This case does not occur if the new
@@ -11606,8 +11993,8 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
 ** returned. Or, if an out-of-memory condition occurs during processing, this
-** function returns SQLITE_NOMEM. In all cases, if an error occurs the
-** final contents of the changegroup is undefined.
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
+** of the final contents of the changegroup is undefined.
 **
 ** If no error occurs, SQLITE_OK is returned.
 */
@@ -11633,7 +12020,7 @@ SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pDa
 **
 ** If an error occurs, an SQLite error code is returned and the output
 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
-** is returned and the output variables are set to the size of and a 
+** is returned and the output variables are set to the size of and a
 ** pointer to the output buffer, respectively. In this case it is the
 ** responsibility of the caller to eventually free the buffer using a
 ** call to sqlite3_free().
@@ -11655,7 +12042,7 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **
 ** Apply a changeset or patchset to a database. These functions attempt to
 ** update the "main" database attached to handle db with the changes found in
-** the changeset passed via the second and third arguments. 
+** the changeset passed via the second and third arguments.
 **
 ** The fourth argument (xFilter) passed to these functions is the "filter
 ** callback". If it is not NULL, then for each table affected by at least one
@@ -11666,16 +12053,16 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** Otherwise, if the return value is non-zero or the xFilter argument to
 ** is NULL, all changes related to the table are attempted.
 **
-** For each table that is not excluded by the filter callback, this function 
-** tests that the target database contains a compatible table. A table is 
+** For each table that is not excluded by the filter callback, this function
+** tests that the target database contains a compatible table. A table is
 ** considered compatible if all of the following are true:
 **
 ** <ul>
-**   <li> The table has the same name as the name recorded in the 
+**   <li> The table has the same name as the name recorded in the
 **        changeset, and
-**   <li> The table has at least as many columns as recorded in the 
+**   <li> The table has at least as many columns as recorded in the
 **        changeset, and
-**   <li> The table has primary key columns in the same position as 
+**   <li> The table has primary key columns in the same position as
 **        recorded in the changeset.
 ** </ul>
 **
@@ -11684,11 +12071,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
 ** one such warning is issued for each table in the changeset.
 **
-** For each change for which there is a compatible table, an attempt is made 
-** to modify the table contents according to the UPDATE, INSERT or DELETE 
-** change. If a change cannot be applied cleanly, the conflict handler 
-** function passed as the fifth argument to sqlite3changeset_apply() may be 
-** invoked. A description of exactly when the conflict handler is invoked for 
+** For each change for which there is a compatible table, an attempt is made
+** to modify the table contents according to the UPDATE, INSERT or DELETE
+** change. If a change cannot be applied cleanly, the conflict handler
+** function passed as the fifth argument to sqlite3changeset_apply() may be
+** invoked. A description of exactly when the conflict handler is invoked for
 ** each type of change is below.
 **
 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
@@ -11696,23 +12083,23 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** argument are undefined.
 **
 ** Each time the conflict handler function is invoked, it must return one
-** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or 
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
 ** if the second argument passed to the conflict handler is either
 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
 ** returns an illegal value, any changes already made are rolled back and
-** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different 
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
 ** actions are taken by sqlite3changeset_apply() depending on the value
 ** returned by each invocation of the conflict-handler function. Refer to
-** the documentation for the three 
+** the documentation for the three
 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
 **
 ** <dl>
 ** <dt>DELETE Changes<dd>
-**   For each DELETE change, the function checks if the target database 
-**   contains a row with the same primary key value (or values) as the 
-**   original row values stored in the changeset. If it does, and the values 
-**   stored in all non-primary key columns also match the values stored in 
+**   For each DELETE change, the function checks if the target database
+**   contains a row with the same primary key value (or values) as the
+**   original row values stored in the changeset. If it does, and the values
+**   stored in all non-primary key columns also match the values stored in
 **   the changeset the row is deleted from the target database.
 **
 **   If a row with matching primary key values is found, but one or more of
@@ -11741,22 +12128,22 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **   database table, the trailing fields are populated with their default
 **   values.
 **
-**   If the attempt to insert the row fails because the database already 
+**   If the attempt to insert the row fails because the database already
 **   contains a row with the same primary key values, the conflict handler
-**   function is invoked with the second argument set to 
+**   function is invoked with the second argument set to
 **   [SQLITE_CHANGESET_CONFLICT].
 **
 **   If the attempt to insert the row fails because of some other constraint
-**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is 
+**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
 **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
-**   This includes the case where the INSERT operation is re-attempted because 
-**   an earlier call to the conflict handler function returned 
+**   This includes the case where the INSERT operation is re-attempted because
+**   an earlier call to the conflict handler function returned
 **   [SQLITE_CHANGESET_REPLACE].
 **
 ** <dt>UPDATE Changes<dd>
-**   For each UPDATE change, the function checks if the target database 
-**   contains a row with the same primary key value (or values) as the 
-**   original row values stored in the changeset. If it does, and the values 
+**   For each UPDATE change, the function checks if the target database
+**   contains a row with the same primary key value (or values) as the
+**   original row values stored in the changeset. If it does, and the values
 **   stored in all modified non-primary key columns also match the values
 **   stored in the changeset the row is updated within the target database.
 **
@@ -11772,28 +12159,28 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 **   passed as the second argument.
 **
-**   If the UPDATE operation is attempted, but SQLite returns 
-**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with 
+**   If the UPDATE operation is attempted, but SQLite returns
+**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
 **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
-**   This includes the case where the UPDATE operation is attempted after 
+**   This includes the case where the UPDATE operation is attempted after
 **   an earlier call to the conflict handler function returned
-**   [SQLITE_CHANGESET_REPLACE].  
+**   [SQLITE_CHANGESET_REPLACE].
 ** </dl>
 **
 ** It is safe to execute SQL statements, including those that write to the
 ** table that the callback related to, from within the xConflict callback.
-** This can be used to further customize the applications conflict
+** This can be used to further customize the application's conflict
 ** resolution strategy.
 **
 ** All changes made by these functions are enclosed in a savepoint transaction.
 ** If any other error (aside from a constraint failure when attempting to
 ** write to the target database) occurs, then the savepoint transaction is
-** rolled back, restoring the target database to its original state, and an 
+** rolled back, restoring the target database to its original state, and an
 ** SQLite error code returned.
 **
 ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
 ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
-** may set (*ppRebase) to point to a "rebase" that may be used with the 
+** may set (*ppRebase) to point to a "rebase" that may be used with the
 ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
 ** is set to the size of the buffer in bytes. It is the responsibility of the
 ** caller to eventually free any such buffer using sqlite3_free(). The buffer
@@ -11854,7 +12241,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   SAVEPOINT is committed if the changeset or patchset is successfully
 **   applied, or rolled back if an error occurs. Specifying this flag
 **   causes the sessions module to omit this savepoint. In this case, if the
-**   caller has an open transaction or savepoint when apply_v2() is called, 
+**   caller has an open transaction or savepoint when apply_v2() is called,
 **   it may revert the partially applied changeset by rolling it back.
 **
 ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
@@ -11865,7 +12252,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
 #define SQLITE_CHANGESETAPPLY_INVERT        0x0002
 
-/* 
+/*
 ** CAPI3REF: Constants Passed To The Conflict Handler
 **
 ** Values that may be passed as the second argument to a conflict-handler.
@@ -11874,32 +12261,32 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** <dt>SQLITE_CHANGESET_DATA<dd>
 **   The conflict handler is invoked with CHANGESET_DATA as the second argument
 **   when processing a DELETE or UPDATE change if a row with the required
-**   PRIMARY KEY fields is present in the database, but one or more other 
-**   (non primary-key) fields modified by the update do not contain the 
+**   PRIMARY KEY fields is present in the database, but one or more other
+**   (non primary-key) fields modified by the update do not contain the
 **   expected "before" values.
-** 
+**
 **   The conflicting row, in this case, is the database row with the matching
 **   primary key.
-** 
+**
 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
 **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
 **   argument when processing a DELETE or UPDATE change if a row with the
 **   required PRIMARY KEY fields is not present in the database.
-** 
+**
 **   There is no conflicting row in this case. The results of invoking the
 **   sqlite3changeset_conflict() API are undefined.
-** 
+**
 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
 **   CHANGESET_CONFLICT is passed as the second argument to the conflict
-**   handler while processing an INSERT change if the operation would result 
+**   handler while processing an INSERT change if the operation would result
 **   in duplicate primary key values.
-** 
+**
 **   The conflicting row in this case is the database row with the matching
 **   primary key.
 **
 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
 **   If foreign key handling is enabled, and applying a changeset leaves the
-**   database in a state containing foreign key violations, the conflict 
+**   database in a state containing foreign key violations, the conflict
 **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
 **   exactly once before the changeset is committed. If the conflict handler
 **   returns CHANGESET_OMIT, the changes, including those that caused the
@@ -11909,12 +12296,12 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   No current or conflicting row information is provided. The only function
 **   it is possible to call on the supplied sqlite3_changeset_iter handle
 **   is sqlite3changeset_fk_conflicts().
-** 
+**
 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
-**   If any other constraint violation occurs while applying a change (i.e. 
-**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is 
+**   If any other constraint violation occurs while applying a change (i.e.
+**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
 **   invoked with CHANGESET_CONSTRAINT as the second argument.
-** 
+**
 **   There is no conflicting row in this case. The results of invoking the
 **   sqlite3changeset_conflict() API are undefined.
 **
@@ -11926,7 +12313,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESET_CONSTRAINT  4
 #define SQLITE_CHANGESET_FOREIGN_KEY 5
 
-/* 
+/*
 ** CAPI3REF: Constants Returned By The Conflict Handler
 **
 ** A conflict handler callback must return one of the following three values.
@@ -11934,13 +12321,13 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** <dl>
 ** <dt>SQLITE_CHANGESET_OMIT<dd>
 **   If a conflict handler returns this value no special action is taken. The
-**   change that caused the conflict is not applied. The session module 
+**   change that caused the conflict is not applied. The session module
 **   continues to the next change in the changeset.
 **
 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
 **   This value may only be returned if the second argument to the conflict
 **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
-**   is not the case, any changes applied so far are rolled back and the 
+**   is not the case, any changes applied so far are rolled back and the
 **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
 **
 **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
@@ -11953,7 +12340,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   the original row is restored to the database before continuing.
 **
 ** <dt>SQLITE_CHANGESET_ABORT<dd>
-**   If this value is returned, any changes applied so far are rolled back 
+**   If this value is returned, any changes applied so far are rolled back
 **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
 ** </dl>
 */
@@ -11961,20 +12348,20 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESET_REPLACE    1
 #define SQLITE_CHANGESET_ABORT      2
 
-/* 
+/*
 ** CAPI3REF: Rebasing changesets
 ** EXPERIMENTAL
 **
 ** Suppose there is a site hosting a database in state S0. And that
 ** modifications are made that move that database to state S1 and a
 ** changeset recorded (the "local" changeset). Then, a changeset based
-** on S0 is received from another site (the "remote" changeset) and 
-** applied to the database. The database is then in state 
+** on S0 is received from another site (the "remote" changeset) and
+** applied to the database. The database is then in state
 ** (S1+"remote"), where the exact state depends on any conflict
 ** resolution decisions (OMIT or REPLACE) made while applying "remote".
-** Rebasing a changeset is to update it to take those conflict 
+** Rebasing a changeset is to update it to take those conflict
 ** resolution decisions into account, so that the same conflicts
-** do not have to be resolved elsewhere in the network. 
+** do not have to be resolved elsewhere in the network.
 **
 ** For example, if both the local and remote changesets contain an
 ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
@@ -11993,7 +12380,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **
 ** <dl>
 ** <dt>Local INSERT<dd>
-**   This may only conflict with a remote INSERT. If the conflict 
+**   This may only conflict with a remote INSERT. If the conflict
 **   resolution was OMIT, then add an UPDATE change to the rebased
 **   changeset. Or, if the conflict resolution was REPLACE, add
 **   nothing to the rebased changeset.
@@ -12017,12 +12404,12 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   the old.* values are rebased using the new.* values in the remote
 **   change. Or, if the resolution is REPLACE, then the change is copied
 **   into the rebased changeset with updates to columns also updated by
-**   the conflicting remote UPDATE removed. If this means no columns would 
+**   the conflicting remote UPDATE removed. If this means no columns would
 **   be updated, the change is omitted.
 ** </dl>
 **
-** A local change may be rebased against multiple remote changes 
-** simultaneously. If a single key is modified by multiple remote 
+** A local change may be rebased against multiple remote changes
+** simultaneously. If a single key is modified by multiple remote
 ** changesets, they are combined as follows before the local changeset
 ** is rebased:
 **
@@ -12035,10 +12422,10 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **         of the OMIT resolutions.
 ** </ul>
 **
-** Note that conflict resolutions from multiple remote changesets are 
-** combined on a per-field basis, not per-row. This means that in the 
-** case of multiple remote UPDATE operations, some fields of a single 
-** local change may be rebased for REPLACE while others are rebased for 
+** Note that conflict resolutions from multiple remote changesets are
+** combined on a per-field basis, not per-row. This means that in the
+** case of multiple remote UPDATE operations, some fields of a single
+** local change may be rebased for REPLACE while others are rebased for
 ** OMIT.
 **
 ** In order to rebase a local changeset, the remote changeset must first
@@ -12046,7 +12433,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** the buffer of rebase information captured. Then:
 **
 ** <ol>
-**   <li> An sqlite3_rebaser object is created by calling 
+**   <li> An sqlite3_rebaser object is created by calling
 **        sqlite3rebaser_create().
 **   <li> The new object is configured with the rebase buffer obtained from
 **        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
@@ -12067,8 +12454,8 @@ typedef struct sqlite3_rebaser sqlite3_rebaser;
 **
 ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
 ** point to the new object and return SQLITE_OK. Otherwise, if an error
-** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) 
-** to NULL. 
+** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
+** to NULL.
 */
 SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
 
@@ -12082,9 +12469,9 @@ SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
 ** sqlite3changeset_apply_v2().
 */
 SQLITE_API int sqlite3rebaser_configure(
-  sqlite3_rebaser*, 
+  sqlite3_rebaser*,
   int nRebase, const void *pRebase
-); 
+);
 
 /*
 ** CAPI3REF: Rebase a changeset
@@ -12092,9 +12479,9 @@ SQLITE_API int sqlite3rebaser_configure(
 **
 ** Argument pIn must point to a buffer containing a changeset nIn bytes
 ** in size. This function allocates and populates a buffer with a copy
-** of the changeset rebased rebased according to the configuration of the
+** of the changeset rebased according to the configuration of the
 ** rebaser object passed as the first argument. If successful, (*ppOut)
-** is set to point to the new buffer containing the rebased changeset and 
+** is set to point to the new buffer containing the rebased changeset and
 ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
 ** responsibility of the caller to eventually free the new buffer using
 ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
@@ -12102,8 +12489,8 @@ SQLITE_API int sqlite3rebaser_configure(
 */
 SQLITE_API int sqlite3rebaser_rebase(
   sqlite3_rebaser*,
-  int nIn, const void *pIn, 
-  int *pnOut, void **ppOut 
+  int nIn, const void *pIn,
+  int *pnOut, void **ppOut
 );
 
 /*
@@ -12114,30 +12501,30 @@ SQLITE_API int sqlite3rebaser_rebase(
 ** should be one call to this function for each successful invocation
 ** of sqlite3rebaser_create().
 */
-SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); 
+SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 
 /*
 ** CAPI3REF: Streaming Versions of API functions.
 **
-** The six streaming API xxx_strm() functions serve similar purposes to the 
+** The six streaming API xxx_strm() functions serve similar purposes to the
 ** corresponding non-streaming API functions:
 **
 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
-**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] 
-**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] 
-**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] 
-**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] 
-**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] 
-**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] 
-**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] 
+**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
+**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
+**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
+**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
+**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
+**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
+**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
 ** </table>
 **
 ** Non-streaming functions that accept changesets (or patchsets) as input
-** require that the entire changeset be stored in a single buffer in memory. 
-** Similarly, those that return a changeset or patchset do so by returning 
-** a pointer to a single large buffer allocated using sqlite3_malloc(). 
-** Normally this is convenient. However, if an application running in a 
+** require that the entire changeset be stored in a single buffer in memory.
+** Similarly, those that return a changeset or patchset do so by returning
+** a pointer to a single large buffer allocated using sqlite3_malloc().
+** Normally this is convenient. However, if an application running in a
 ** low-memory environment is required to handle very large changesets, the
 ** large contiguous memory allocations required can become onerous.
 **
@@ -12159,12 +12546,12 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 **  </pre>
 **
 ** Each time the xInput callback is invoked by the sessions module, the first
-** argument passed is a copy of the supplied pIn context pointer. The second 
-** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no 
-** error occurs the xInput method should copy up to (*pnData) bytes of data 
-** into the buffer and set (*pnData) to the actual number of bytes copied 
-** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) 
-** should be set to zero to indicate this. Or, if an error occurs, an SQLite 
+** argument passed is a copy of the supplied pIn context pointer. The second
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
+** error occurs the xInput method should copy up to (*pnData) bytes of data
+** into the buffer and set (*pnData) to the actual number of bytes copied
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
 ** error code should be returned. In all cases, if an xInput callback returns
 ** an error, all processing is abandoned and the streaming API function
 ** returns a copy of the error code to the caller.
@@ -12172,7 +12559,7 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
 ** invoked by the sessions module at any point during the lifetime of the
 ** iterator. If such an xInput callback returns an error, the iterator enters
-** an error state, whereby all subsequent calls to iterator functions 
+** an error state, whereby all subsequent calls to iterator functions
 ** immediately fail with the same error code as returned by xInput.
 **
 ** Similarly, streaming API functions that return changesets (or patchsets)
@@ -12202,7 +12589,7 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 ** is immediately abandoned and the streaming API function returns a copy
 ** of the xOutput error code to the application.
 **
-** The sessions module never invokes an xOutput callback with the third 
+** The sessions module never invokes an xOutput callback with the third
 ** parameter set to a value less than or equal to zero. Other than this,
 ** no guarantees are made as to the size of the chunks of data returned.
 */
@@ -12273,12 +12660,12 @@ SQLITE_API int sqlite3session_patchset_strm(
   int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 );
-SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, 
+SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
     int (*xInput)(void *pIn, void *pData, int *pnData),
     void *pIn
 );
 SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
-    int (*xOutput)(void *pOut, const void *pData, int nData), 
+    int (*xOutput)(void *pOut, const void *pData, int nData),
     void *pOut
 );
 SQLITE_API int sqlite3rebaser_rebase_strm(
@@ -12293,16 +12680,16 @@ SQLITE_API int sqlite3rebaser_rebase_strm(
 ** CAPI3REF: Configure global parameters
 **
 ** The sqlite3session_config() interface is used to make global configuration
-** changes to the sessions module in order to tune it to the specific needs 
+** changes to the sessions module in order to tune it to the specific needs
 ** of the application.
 **
 ** The sqlite3session_config() interface is not threadsafe. If it is invoked
 ** while any other thread is inside any other sessions method then the
 ** results are undefined. Furthermore, if it is invoked after any sessions
-** related objects have been created, the results are also undefined. 
+** related objects have been created, the results are also undefined.
 **
 ** The first argument to the sqlite3session_config() function must be one
-** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The 
+** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
 ** interpretation of the (void*) value passed as the second parameter and
 ** the effect of calling this function depends on the value of the first
 ** parameter.
@@ -12352,7 +12739,7 @@ SQLITE_API int sqlite3session_config(int op, void *pArg);
 **
 ******************************************************************************
 **
-** Interfaces to extend FTS5. Using the interfaces defined in this file, 
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
 ** FTS5 may be extended with:
 **
 **     * custom tokenizers, and
@@ -12396,19 +12783,19 @@ struct Fts5PhraseIter {
 ** EXTENSION API FUNCTIONS
 **
 ** xUserData(pFts):
-**   Return a copy of the context pointer the extension function was 
+**   Return a copy of the context pointer the extension function was
 **   registered with.
 **
 ** xColumnTotalSize(pFts, iCol, pnToken):
 **   If parameter iCol is less than zero, set output variable *pnToken
 **   to the total number of tokens in the FTS5 table. Or, if iCol is
 **   non-negative but less than the number of columns in the table, return
-**   the total number of tokens in column iCol, considering all rows in 
+**   the total number of tokens in column iCol, considering all rows in
 **   the FTS5 table.
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 ** xColumnCount(pFts):
@@ -12422,7 +12809,7 @@ struct Fts5PhraseIter {
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 **   This function may be quite inefficient if used with an FTS5 table
@@ -12449,8 +12836,8 @@ struct Fts5PhraseIter {
 **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always returns 0.
 **
 ** xInst:
@@ -12465,7 +12852,7 @@ struct Fts5PhraseIter {
 **   code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. 
+**   "detail=none" or "detail=column" option.
 **
 ** xRowid:
 **   Returns the rowid of the current row.
@@ -12481,11 +12868,11 @@ struct Fts5PhraseIter {
 **
 **   with $p set to a phrase equivalent to the phrase iPhrase of the
 **   current query is executed. Any column filter that applies to
-**   phrase iPhrase of the current query is included in $p. For each 
-**   row visited, the callback function passed as the fourth argument 
-**   is invoked. The context and API objects passed to the callback 
+**   phrase iPhrase of the current query is included in $p. For each
+**   row visited, the callback function passed as the fourth argument
+**   is invoked. The context and API objects passed to the callback
 **   function may be used to access the properties of each matched row.
-**   Invoking Api.xUserData() returns a copy of the pointer passed as 
+**   Invoking Api.xUserData() returns a copy of the pointer passed as
 **   the third argument to pUserData.
 **
 **   If the callback function returns any value other than SQLITE_OK, the
@@ -12500,14 +12887,14 @@ struct Fts5PhraseIter {
 **
 ** xSetAuxdata(pFts5, pAux, xDelete)
 **
-**   Save the pointer passed as the second argument as the extension function
+**   Save the pointer passed as the second argument as the extension function's
 **   "auxiliary data". The pointer may then be retrieved by the current or any
 **   future invocation of the same fts5 extension function made as part of
 **   the same MATCH query using the xGetAuxdata() API.
 **
 **   Each extension function is allocated a single auxiliary data slot for
-**   each FTS query (MATCH expression). If the extension function is invoked 
-**   more than once for a single FTS query, then all invocations share a 
+**   each FTS query (MATCH expression). If the extension function is invoked
+**   more than once for a single FTS query, then all invocations share a
 **   single auxiliary data context.
 **
 **   If there is already an auxiliary data pointer when this function is
@@ -12526,7 +12913,7 @@ struct Fts5PhraseIter {
 **
 ** xGetAuxdata(pFts5, bClear)
 **
-**   Returns the current auxiliary data pointer for the fts5 extension 
+**   Returns the current auxiliary data pointer for the fts5 extension
 **   function. See the xSetAuxdata() method for details.
 **
 **   If the bClear argument is non-zero, then the auxiliary data is cleared
@@ -12546,7 +12933,7 @@ struct Fts5PhraseIter {
 **   method, to iterate through all instances of a single query phrase within
 **   the current row. This is the same information as is accessible via the
 **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
-**   to use, this API may be faster under some circumstances. To iterate 
+**   to use, this API may be faster under some circumstances. To iterate
 **   through instances of phrase iPhrase, use the following code:
 **
 **       Fts5PhraseIter iter;
@@ -12564,8 +12951,8 @@ struct Fts5PhraseIter {
 **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always iterates
 **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
 **
@@ -12589,16 +12976,16 @@ struct Fts5PhraseIter {
 **       }
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" option. If the FTS5 table is created with either 
-**   "detail=none" "content=" option (i.e. if it is a contentless table), 
-**   then this API always iterates through an empty set (all calls to 
+**   "detail=none" option. If the FTS5 table is created with either
+**   "detail=none" "content=" option (i.e. if it is a contentless table),
+**   then this API always iterates through an empty set (all calls to
 **   xPhraseFirstColumn() set iCol to -1).
 **
 **   The information accessed using this API and its companion
 **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
 **   (or xInst/xInstCount). The chief advantage of this API is that it is
 **   significantly more efficient than those alternatives when used with
-**   "detail=column" tables.  
+**   "detail=column" tables.
 **
 ** xPhraseNextColumn()
 **   See xPhraseFirstColumn above.
@@ -12612,7 +12999,7 @@ struct Fts5ExtensionApi {
   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
 
-  int (*xTokenize)(Fts5Context*, 
+  int (*xTokenize)(Fts5Context*,
     const char *pText, int nText, /* Text to tokenize */
     void *pCtx,                   /* Context passed to xToken() */
     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
@@ -12641,15 +13028,15 @@ struct Fts5ExtensionApi {
   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
 };
 
-/* 
+/*
 ** CUSTOM AUXILIARY FUNCTIONS
 *************************************************************************/
 
 /*************************************************************************
 ** CUSTOM TOKENIZERS
 **
-** Applications may also register custom tokenizer types. A tokenizer 
-** is registered by providing fts5 with a populated instance of the 
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
 ** following structure. All structure methods must be defined, setting
 ** any member of the fts5_tokenizer struct to NULL leads to undefined
 ** behaviour. The structure methods are expected to function as follows:
@@ -12660,16 +13047,16 @@ struct Fts5ExtensionApi {
 **
 **   The first argument passed to this function is a copy of the (void*)
 **   pointer provided by the application when the fts5_tokenizer object
-**   was registered with FTS5 (the third argument to xCreateTokenizer()). 
+**   was registered with FTS5 (the third argument to xCreateTokenizer()).
 **   The second and third arguments are an array of nul-terminated strings
 **   containing the tokenizer arguments, if any, specified following the
 **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
 **   to create the FTS5 table.
 **
-**   The final argument is an output variable. If successful, (*ppOut) 
+**   The final argument is an output variable. If successful, (*ppOut)
 **   should be set to point to the new tokenizer handle and SQLITE_OK
 **   returned. If an error occurs, some value other than SQLITE_OK should
-**   be returned. In this case, fts5 assumes that the final value of *ppOut 
+**   be returned. In this case, fts5 assumes that the final value of *ppOut
 **   is undefined.
 **
 ** xDelete:
@@ -12678,7 +13065,7 @@ struct Fts5ExtensionApi {
 **   be invoked exactly once for each successful call to xCreate().
 **
 ** xTokenize:
-**   This function is expected to tokenize the nText byte string indicated 
+**   This function is expected to tokenize the nText byte string indicated
 **   by argument pText. pText may or may not be nul-terminated. The first
 **   argument passed to this function is a pointer to an Fts5Tokenizer object
 **   returned by an earlier call to xCreate().
@@ -12692,8 +13079,8 @@ struct Fts5ExtensionApi {
 **            determine the set of tokens to add to (or delete from) the
 **            FTS index.
 **
-**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
-**            against the FTS index. The tokenizer is being called to tokenize 
+**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+**            against the FTS index. The tokenizer is being called to tokenize
 **            a bareword or quoted string specified as part of the query.
 **
 **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
@@ -12701,10 +13088,10 @@ struct Fts5ExtensionApi {
 **            followed by a "*" character, indicating that the last token
 **            returned by the tokenizer will be treated as a token prefix.
 **
-**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
+**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
 **            satisfy an fts5_api.xTokenize() request made by an auxiliary
 **            function. Or an fts5_api.xColumnSize() request made by the same
-**            on a columnsize=0 database.  
+**            on a columnsize=0 database.
 **   </ul>
 **
 **   For each token in the input string, the supplied callback xToken() must
@@ -12716,10 +13103,10 @@ struct Fts5ExtensionApi {
 **   which the token is derived within the input.
 **
 **   The second argument passed to the xToken() callback ("tflags") should
-**   normally be set to 0. The exception is if the tokenizer supports 
+**   normally be set to 0. The exception is if the tokenizer supports
 **   synonyms. In this case see the discussion below for details.
 **
-**   FTS5 assumes the xToken() callback is invoked for each token in the 
+**   FTS5 assumes the xToken() callback is invoked for each token in the
 **   order that they occur within the input text.
 **
 **   If an xToken() callback returns any value other than SQLITE_OK, then
@@ -12733,7 +13120,7 @@ struct Fts5ExtensionApi {
 ** SYNONYM SUPPORT
 **
 **   Custom tokenizers may also support synonyms. Consider a case in which a
-**   user wishes to query for a phrase such as "first place". Using the 
+**   user wishes to query for a phrase such as "first place". Using the
 **   built-in tokenizers, the FTS5 query 'first + place' will match instances
 **   of "first place" within the document set, but not alternative forms
 **   such as "1st place". In some applications, it would be better to match
@@ -12742,8 +13129,8 @@ struct Fts5ExtensionApi {
 **
 **   There are several ways to approach this in FTS5:
 **
-**   <ol><li> By mapping all synonyms to a single token. In this case, the 
-**            In the above example, this means that the tokenizer returns the
+**   <ol><li> By mapping all synonyms to a single token. In this case, using
+**            the above example, this means that the tokenizer returns the
 **            same token for inputs "first" and "1st". Say that token is in
 **            fact "first", so that when the user inserts the document "I won
 **            1st place" entries are added to the index for tokens "i", "won",
@@ -12753,34 +13140,34 @@ struct Fts5ExtensionApi {
 **
 **       <li> By querying the index for all synonyms of each query term
 **            separately. In this case, when tokenizing query text, the
-**            tokenizer may provide multiple synonyms for a single term 
-**            within the document. FTS5 then queries the index for each 
+**            tokenizer may provide multiple synonyms for a single term
+**            within the document. FTS5 then queries the index for each
 **            synonym individually. For example, faced with the query:
 **
 **   <codeblock>
 **     ... MATCH 'first place'</codeblock>
 **
 **            the tokenizer offers both "1st" and "first" as synonyms for the
-**            first token in the MATCH query and FTS5 effectively runs a query 
+**            first token in the MATCH query and FTS5 effectively runs a query
 **            similar to:
 **
 **   <codeblock>
 **     ... MATCH '(first OR 1st) place'</codeblock>
 **
 **            except that, for the purposes of auxiliary functions, the query
-**            still appears to contain just two phrases - "(first OR 1st)" 
+**            still appears to contain just two phrases - "(first OR 1st)"
 **            being treated as a single phrase.
 **
 **       <li> By adding multiple synonyms for a single term to the FTS index.
 **            Using this method, when tokenizing document text, the tokenizer
-**            provides multiple synonyms for each token. So that when a 
+**            provides multiple synonyms for each token. So that when a
 **            document such as "I won first place" is tokenized, entries are
 **            added to the FTS index for "i", "won", "first", "1st" and
 **            "place".
 **
 **            This way, even if the tokenizer does not provide synonyms
 **            when tokenizing query text (it should not - to do so would be
-**            inefficient), it doesn't matter if the user queries for 
+**            inefficient), it doesn't matter if the user queries for
 **            'first + place' or '1st + place', as there are entries in the
 **            FTS index corresponding to both forms of the first token.
 **   </ol>
@@ -12801,11 +13188,11 @@ struct Fts5ExtensionApi {
 **
 **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
 **   xToken() is called. Multiple synonyms may be specified for a single token
-**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
+**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
 **   There is no limit to the number of synonyms that may be provided for a
 **   single token.
 **
-**   In many cases, method (1) above is the best approach. It does not add 
+**   In many cases, method (1) above is the best approach. It does not add
 **   extra data to the FTS index or require FTS5 to query for multiple terms,
 **   so it is efficient in terms of disk space and query speed. However, it
 **   does not support prefix queries very well. If, as suggested above, the
@@ -12817,18 +13204,18 @@ struct Fts5ExtensionApi {
 **   will not match documents that contain the token "1st" (as the tokenizer
 **   will probably not map "1s" to any prefix of "first").
 **
-**   For full prefix support, method (3) may be preferred. In this case, 
+**   For full prefix support, method (3) may be preferred. In this case,
 **   because the index contains entries for both "first" and "1st", prefix
 **   queries such as 'fi*' or '1s*' will match correctly. However, because
 **   extra entries are added to the FTS index, this method uses more space
 **   within the database.
 **
 **   Method (2) offers a midpoint between (1) and (3). Using this method,
-**   a query such as '1s*' will match documents that contain the literal 
+**   a query such as '1s*' will match documents that contain the literal
 **   token "1st", but not "first" (assuming the tokenizer is not able to
 **   provide synonyms for prefixes). However, a non-prefix query like '1st'
 **   will match against "1st" and "first". This method does not require
-**   extra disk space, as no extra entries are added to the FTS index. 
+**   extra disk space, as no extra entries are added to the FTS index.
 **   On the other hand, it may require more CPU cycles to run MATCH queries,
 **   as separate queries of the FTS index are required for each synonym.
 **
@@ -12842,10 +13229,10 @@ typedef struct fts5_tokenizer fts5_tokenizer;
 struct fts5_tokenizer {
   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
   void (*xDelete)(Fts5Tokenizer*);
-  int (*xTokenize)(Fts5Tokenizer*, 
+  int (*xTokenize)(Fts5Tokenizer*,
       void *pCtx,
       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
-      const char *pText, int nText, 
+      const char *pText, int nText,
       int (*xToken)(
         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
         int tflags,         /* Mask of FTS5_TOKEN_* flags */
@@ -12942,7 +13329,7 @@ struct fts5_api {
 **    May you share freely, never taking more than you give.
 **
 *************************************************************************
-** 
+**
 ** This file defines various limits of what SQLite can process.
 */
 
@@ -12990,14 +13377,10 @@ struct fts5_api {
 #endif
 
 /*
-** The maximum depth of an expression tree. This is limited to 
-** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
-** want to place more severe limits on the complexity of an 
-** expression.
-**
-** A value of 0 used to mean that the limit was not enforced.
-** But that is no longer true.  The limit is now strictly enforced
-** at all times.
+** The maximum depth of an expression tree. This is limited to
+** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
+** want to place more severe limits on the complexity of an
+** expression. A value of 0 means that there is no limit.
 */
 #ifndef SQLITE_MAX_EXPR_DEPTH
 # define SQLITE_MAX_EXPR_DEPTH 1000
@@ -13064,9 +13447,12 @@ struct fts5_api {
 
 /*
 ** The maximum value of a ?nnn wildcard that the parser will accept.
+** If the value exceeds 32767 then extra space is required for the Expr
+** structure.  But otherwise, we believe that the number can be as large
+** as a signed 32-bit integer can hold.
 */
 #ifndef SQLITE_MAX_VARIABLE_NUMBER
-# define SQLITE_MAX_VARIABLE_NUMBER 999
+# define SQLITE_MAX_VARIABLE_NUMBER 32766
 #endif
 
 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
@@ -13074,10 +13460,10 @@ struct fts5_api {
 **
 ** Earlier versions of SQLite allowed the user to change this value at
 ** compile time. This is no longer permitted, on the grounds that it creates
-** a library that is technically incompatible with an SQLite library 
-** compiled with a different limit. If a process operating on a database 
-** with a page-size of 65536 bytes crashes, then an instance of SQLite 
-** compiled with the default page-size limit will not be able to rollback 
+** a library that is technically incompatible with an SQLite library
+** compiled with a different limit. If a process operating on a database
+** with a page-size of 65536 bytes crashes, then an instance of SQLite
+** compiled with the default page-size limit will not be able to rollback
 ** the aborted transaction. This could lead to database corruption.
 */
 #ifdef SQLITE_MAX_PAGE_SIZE
@@ -13136,7 +13522,7 @@ struct fts5_api {
 ** Maximum depth of recursion for triggers.
 **
 ** A value of 1 means that a trigger program will not be able to itself
-** fire any triggers. A value of 0 means that no trigger programs at all 
+** fire any triggers. A value of 0 means that no trigger programs at all
 ** may be executed.
 */
 #ifndef SQLITE_MAX_TRIGGER_DEPTH
@@ -13163,6 +13549,21 @@ struct fts5_api {
 #endif
 
 /*
+** WAL mode depends on atomic aligned 32-bit loads and stores in a few
+** places.  The following macros try to make this explicit.
+*/
+#ifndef __has_extension
+# define __has_extension(x) 0     /* compatibility with non-clang compilers */
+#endif
+#if GCC_VERSION>=4007000 || __has_extension(c_atomic)
+# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
+# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
+#else
+# define AtomicLoad(PTR)       (*(PTR))
+# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
+#endif
+
+/*
 ** Include standard header files as necessary
 */
 #ifdef HAVE_STDINT_H
@@ -13423,6 +13824,26 @@ SQLITE_PRIVATE   void sqlite3Coverage(int);
 #endif
 
 /*
+** The harmless(X) macro indicates that expression X is usually false
+** but can be true without causing any problems, but we don't know of
+** any way to cause X to be true.
+**
+** In debugging and testing builds, this macro will abort if X is ever
+** true.  In this way, developers are alerted to a possible test case
+** that causes X to be true.  If a harmless macro ever fails, that is
+** an opportunity to change the macro into a testcase() and add a new
+** test case to the test suite.
+**
+** For normal production builds, harmless(X) is a no-op, since it does
+** not matter whether expression X is true or false.
+*/
+#ifdef SQLITE_DEBUG
+# define harmless(X)  assert(!(X));
+#else
+# define harmless(X)
+#endif
+
+/*
 ** Some conditionals are optimizations only.  In other words, if the
 ** conditionals are replaced with a constant 1 (true) or 0 (false) then
 ** the correct answer is still obtained, though perhaps not as quickly.
@@ -13541,7 +13962,7 @@ typedef struct HashElem HashElem;
 ** element pointed to plus the next _ht.count-1 elements in the list.
 **
 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
-** by a linear search of the global list.  For small tables, the 
+** by a linear search of the global list.  For small tables, the
 ** Hash.ht table is never allocated because if there are few elements
 ** in the table, it is faster to do a linear search than to manage
 ** the hash table.
@@ -13556,7 +13977,7 @@ struct Hash {
   } *ht;
 };
 
-/* Each element in the hash table is an instance of the following 
+/* Each element in the hash table is an instance of the following
 ** structure.  All elements are stored on a single doubly-linked list.
 **
 ** Again, this structure is intended to be opaque, but it can't really
@@ -13699,90 +14120,92 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 #define TK_GROUPS                          92
 #define TK_OTHERS                          93
 #define TK_TIES                            94
-#define TK_REINDEX                         95
-#define TK_RENAME                          96
-#define TK_CTIME_KW                        97
-#define TK_ANY                             98
-#define TK_BITAND                          99
-#define TK_BITOR                          100
-#define TK_LSHIFT                         101
-#define TK_RSHIFT                         102
-#define TK_PLUS                           103
-#define TK_MINUS                          104
-#define TK_STAR                           105
-#define TK_SLASH                          106
-#define TK_REM                            107
-#define TK_CONCAT                         108
-#define TK_COLLATE                        109
-#define TK_BITNOT                         110
-#define TK_ON                             111
-#define TK_INDEXED                        112
-#define TK_STRING                         113
-#define TK_JOIN_KW                        114
-#define TK_CONSTRAINT                     115
-#define TK_DEFAULT                        116
-#define TK_NULL                           117
-#define TK_PRIMARY                        118
-#define TK_UNIQUE                         119
-#define TK_CHECK                          120
-#define TK_REFERENCES                     121
-#define TK_AUTOINCR                       122
-#define TK_INSERT                         123
-#define TK_DELETE                         124
-#define TK_UPDATE                         125
-#define TK_SET                            126
-#define TK_DEFERRABLE                     127
-#define TK_FOREIGN                        128
-#define TK_DROP                           129
-#define TK_UNION                          130
-#define TK_ALL                            131
-#define TK_EXCEPT                         132
-#define TK_INTERSECT                      133
-#define TK_SELECT                         134
-#define TK_VALUES                         135
-#define TK_DISTINCT                       136
-#define TK_DOT                            137
-#define TK_FROM                           138
-#define TK_JOIN                           139
-#define TK_USING                          140
-#define TK_ORDER                          141
-#define TK_GROUP                          142
-#define TK_HAVING                         143
-#define TK_LIMIT                          144
-#define TK_WHERE                          145
-#define TK_INTO                           146
-#define TK_NOTHING                        147
-#define TK_FLOAT                          148
-#define TK_BLOB                           149
-#define TK_INTEGER                        150
-#define TK_VARIABLE                       151
-#define TK_CASE                           152
-#define TK_WHEN                           153
-#define TK_THEN                           154
-#define TK_ELSE                           155
-#define TK_INDEX                          156
-#define TK_ALTER                          157
-#define TK_ADD                            158
-#define TK_WINDOW                         159
-#define TK_OVER                           160
-#define TK_FILTER                         161
-#define TK_COLUMN                         162
-#define TK_AGG_FUNCTION                   163
-#define TK_AGG_COLUMN                     164
-#define TK_TRUEFALSE                      165
-#define TK_ISNOT                          166
-#define TK_FUNCTION                       167
-#define TK_UMINUS                         168
-#define TK_UPLUS                          169
-#define TK_TRUTH                          170
-#define TK_REGISTER                       171
-#define TK_VECTOR                         172
-#define TK_SELECT_COLUMN                  173
-#define TK_IF_NULL_ROW                    174
-#define TK_ASTERISK                       175
-#define TK_SPAN                           176
-#define TK_SPACE                          177
-#define TK_ILLEGAL                        178
+#define TK_GENERATED                       95
+#define TK_ALWAYS                          96
+#define TK_REINDEX                         97
+#define TK_RENAME                          98
+#define TK_CTIME_KW                        99
+#define TK_ANY                            100
+#define TK_BITAND                         101
+#define TK_BITOR                          102
+#define TK_LSHIFT                         103
+#define TK_RSHIFT                         104
+#define TK_PLUS                           105
+#define TK_MINUS                          106
+#define TK_STAR                           107
+#define TK_SLASH                          108
+#define TK_REM                            109
+#define TK_CONCAT                         110
+#define TK_COLLATE                        111
+#define TK_BITNOT                         112
+#define TK_ON                             113
+#define TK_INDEXED                        114
+#define TK_STRING                         115
+#define TK_JOIN_KW                        116
+#define TK_CONSTRAINT                     117
+#define TK_DEFAULT                        118
+#define TK_NULL                           119
+#define TK_PRIMARY                        120
+#define TK_UNIQUE                         121
+#define TK_CHECK                          122
+#define TK_REFERENCES                     123
+#define TK_AUTOINCR                       124
+#define TK_INSERT                         125
+#define TK_DELETE                         126
+#define TK_UPDATE                         127
+#define TK_SET                            128
+#define TK_DEFERRABLE                     129
+#define TK_FOREIGN                        130
+#define TK_DROP                           131
+#define TK_UNION                          132
+#define TK_ALL                            133
+#define TK_EXCEPT                         134
+#define TK_INTERSECT                      135
+#define TK_SELECT                         136
+#define TK_VALUES                         137
+#define TK_DISTINCT                       138
+#define TK_DOT                            139
+#define TK_FROM                           140
+#define TK_JOIN                           141
+#define TK_USING                          142
+#define TK_ORDER                          143
+#define TK_GROUP                          144
+#define TK_HAVING                         145
+#define TK_LIMIT                          146
+#define TK_WHERE                          147
+#define TK_INTO                           148
+#define TK_NOTHING                        149
+#define TK_FLOAT                          150
+#define TK_BLOB                           151
+#define TK_INTEGER                        152
+#define TK_VARIABLE                       153
+#define TK_CASE                           154
+#define TK_WHEN                           155
+#define TK_THEN                           156
+#define TK_ELSE                           157
+#define TK_INDEX                          158
+#define TK_ALTER                          159
+#define TK_ADD                            160
+#define TK_WINDOW                         161
+#define TK_OVER                           162
+#define TK_FILTER                         163
+#define TK_COLUMN                         164
+#define TK_AGG_FUNCTION                   165
+#define TK_AGG_COLUMN                     166
+#define TK_TRUEFALSE                      167
+#define TK_ISNOT                          168
+#define TK_FUNCTION                       169
+#define TK_UMINUS                         170
+#define TK_UPLUS                          171
+#define TK_TRUTH                          172
+#define TK_REGISTER                       173
+#define TK_VECTOR                         174
+#define TK_SELECT_COLUMN                  175
+#define TK_IF_NULL_ROW                    176
+#define TK_ASTERISK                       177
+#define TK_SPAN                           178
+#define TK_SPACE                          179
+#define TK_ILLEGAL                        180
 
 /************** End of parse.h ***********************************************/
 /************** Continuing where we left off in sqliteInt.h ******************/
@@ -13908,7 +14331,7 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*);
 #endif
 
 /*
-** The compile-time options SQLITE_MMAP_READWRITE and 
+** The compile-time options SQLITE_MMAP_READWRITE and
 ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
 ** You must choose one or the other (or neither) but not both.
 */
@@ -14130,6 +14553,7 @@ typedef INT16_TYPE LogEst;
 ** compilers.
 */
 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
+#define LARGEST_UINT64 (0xffffffff|(((u64)0xffffffff)<<32))
 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
 
 /*
@@ -14203,13 +14627,37 @@ typedef INT16_TYPE LogEst;
 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
 ** the Select query generator tracing logic is turned on.
 */
-#if defined(SQLITE_ENABLE_SELECTTRACE)
+#if !defined(SQLITE_AMALGAMATION)
+SQLITE_PRIVATE u32 sqlite3SelectTrace;
+#endif
+#if defined(SQLITE_DEBUG) \
+    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_SELECTTRACE))
 # define SELECTTRACE_ENABLED 1
+# define SELECTTRACE(K,P,S,X)  \
+  if(sqlite3SelectTrace&(K))   \
+    sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
+    sqlite3DebugPrintf X
 #else
+# define SELECTTRACE(K,P,S,X)
 # define SELECTTRACE_ENABLED 0
 #endif
 
 /*
+** Macros for "wheretrace"
+*/
+#if defined(SQLITE_DEBUG) \
+    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
+# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
+# define WHERETRACE_ENABLED 1
+#else
+# define WHERETRACE(K,X)
+#endif
+#if !defined(SQLITE_AMAGAMATION) && defined(WHERETRACE_ENABLED)
+SQLITE_PRIVATE u32 sqlite3WhereTrace;
+#endif
+
+
+/*
 ** An instance of the following structure is used to store the busy-handler
 ** callback for a given sqlite handle.
 **
@@ -14223,26 +14671,27 @@ struct BusyHandler {
   int (*xBusyHandler)(void *,int);  /* The busy callback */
   void *pBusyArg;                   /* First arg to busy callback */
   int nBusy;                        /* Incremented with each busy call */
-  u8 bExtraFileArg;                 /* Include sqlite3_file as callback arg */
 };
 
 /*
-** Name of the master database table.  The master database table
-** is a special table that holds the names and attributes of all
-** user tables and indices.
+** Name of table that holds the database schema.
 */
-#define MASTER_NAME       "sqlite_master"
-#define TEMP_MASTER_NAME  "sqlite_temp_master"
+#define DFLT_SCHEMA_TABLE          "sqlite_master"
+#define DFLT_TEMP_SCHEMA_TABLE     "sqlite_temp_master"
+#define ALT_SCHEMA_TABLE           "sqlite_schema"
+#define ALT_TEMP_SCHEMA_TABLE      "sqlite_temp_schema"
+
 
 /*
-** The root-page of the master database table.
+** The root-page of the schema table.
 */
-#define MASTER_ROOT       1
+#define SCHEMA_ROOT    1
 
 /*
-** The name of the schema table.
+** The name of the schema table.  The name is different for TEMP.
 */
-#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
+#define SCHEMA_TABLE(x) \
+    ((!OMIT_TEMPDB)&&(x==1)?DFLT_TEMP_SCHEMA_TABLE:DFLT_SCHEMA_TABLE)
 
 /*
 ** A convenience macro that returns the number of elements in
@@ -14263,7 +14712,7 @@ struct BusyHandler {
 ** pointer will work here as long as it is distinct from SQLITE_STATIC
 ** and SQLITE_TRANSIENT.
 */
-#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
+#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3OomFault)
 
 /*
 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
@@ -14386,6 +14835,7 @@ typedef struct With With;
 ** A bit in a Bitmask
 */
 #define MASKBIT(n)   (((Bitmask)1)<<(n))
+#define MASKBIT64(n) (((u64)1)<<(n))
 #define MASKBIT32(n) (((unsigned int)1)<<(n))
 #define ALLBITS      ((Bitmask)-1)
 
@@ -14402,6 +14852,253 @@ typedef int VList;
 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
 ** pointer types (i.e. FuncDef) defined above.
 */
+/************** Include pager.h in the middle of sqliteInt.h *****************/
+/************** Begin file pager.h *******************************************/
+/*
+** 2001 September 15
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+** This header file defines the interface that the sqlite page cache
+** subsystem.  The page cache subsystem reads and writes a file a page
+** at a time and provides a journal for rollback.
+*/
+
+#ifndef SQLITE_PAGER_H
+#define SQLITE_PAGER_H
+
+/*
+** Default maximum size for persistent journal files. A negative
+** value means no limit. This value may be overridden using the
+** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
+*/
+#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
+  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
+#endif
+
+/*
+** The type used to represent a page number.  The first page in a file
+** is called page 1.  0 is used to represent "not a page".
+*/
+typedef u32 Pgno;
+
+/*
+** Each open file is managed by a separate instance of the "Pager" structure.
+*/
+typedef struct Pager Pager;
+
+/*
+** Handle type for pages.
+*/
+typedef struct PgHdr DbPage;
+
+/*
+** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
+** reserved for working around a windows/posix incompatibility). It is
+** used in the journal to signify that the remainder of the journal file
+** is devoted to storing a super-journal name - there are no more pages to
+** roll back. See comments for function writeSuperJournal() in pager.c
+** for details.
+*/
+#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
+
+/*
+** Allowed values for the flags parameter to sqlite3PagerOpen().
+**
+** NOTE: These values must match the corresponding BTREE_ values in btree.h.
+*/
+#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
+#define PAGER_MEMORY        0x0002    /* In-memory database */
+
+/*
+** Valid values for the second argument to sqlite3PagerLockingMode().
+*/
+#define PAGER_LOCKINGMODE_QUERY      -1
+#define PAGER_LOCKINGMODE_NORMAL      0
+#define PAGER_LOCKINGMODE_EXCLUSIVE   1
+
+/*
+** Numeric constants that encode the journalmode.
+**
+** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
+** are exposed in the API via the "PRAGMA journal_mode" command and
+** therefore cannot be changed without a compatibility break.
+*/
+#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
+#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
+#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
+#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
+#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
+#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
+#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
+
+/*
+** Flags that make up the mask passed to sqlite3PagerGet().
+*/
+#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
+#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
+
+/*
+** Flags for sqlite3PagerSetFlags()
+**
+** Value constraints (enforced via assert()):
+**    PAGER_FULLFSYNC      == SQLITE_FullFSync
+**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
+**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
+*/
+#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
+#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
+#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
+#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
+#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
+#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
+#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
+#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
+#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
+
+/*
+** The remainder of this file contains the declarations of the functions
+** that make up the Pager sub-system API. See source code comments for
+** a detailed description of each routine.
+*/
+
+/* Open and close a Pager connection. */
+SQLITE_PRIVATE int sqlite3PagerOpen(
+  sqlite3_vfs*,
+  Pager **ppPager,
+  const char*,
+  int,
+  int,
+  int,
+  void(*)(DbPage*)
+);
+SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
+SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
+
+/* Functions used to configure a Pager object. */
+SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
+SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
+SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager*, Pgno);
+SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
+SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
+SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
+SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
+SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
+SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
+SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
+SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
+SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
+SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
+SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
+SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
+
+/* Functions used to obtain and release page references. */
+SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
+SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
+SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
+
+/* Operations on page references. */
+SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
+SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
+SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
+SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
+SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
+SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
+
+/* Functions used to manage pager transactions and savepoints. */
+SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
+SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zSuper, int);
+SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
+SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper);
+SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
+SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
+SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
+SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
+SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
+
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
+SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
+SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
+SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
+SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
+# ifdef SQLITE_ENABLE_SNAPSHOT
+SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
+SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
+SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
+SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);
+# endif
+#endif
+
+#if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
+SQLITE_PRIVATE   int sqlite3PagerWalWriteLock(Pager*, int);
+SQLITE_PRIVATE   void sqlite3PagerWalDb(Pager*, sqlite3*);
+#else
+# define sqlite3PagerWalWriteLock(y,z) SQLITE_OK
+# define sqlite3PagerWalDb(x,y)
+#endif
+
+#ifdef SQLITE_DIRECT_OVERFLOW_READ
+SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
+#endif
+
+#ifdef SQLITE_ENABLE_ZIPVFS
+SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
+#endif
+
+/* Functions used to query pager state and configuration. */
+SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
+SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
+#endif
+SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
+SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);
+SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
+SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
+SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
+SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
+SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
+SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
+SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
+SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
+
+/* Functions used to truncate the database file. */
+SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
+
+SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
+
+/* Functions to support testing and debugging. */
+#if !defined(NDEBUG) || defined(SQLITE_TEST)
+SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
+SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
+#endif
+#ifdef SQLITE_TEST
+SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
+SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
+  void disable_simulated_io_errors(void);
+  void enable_simulated_io_errors(void);
+#else
+# define disable_simulated_io_errors()
+# define enable_simulated_io_errors()
+#endif
+
+#endif /* SQLITE_PAGER_H */
+
+/************** End of pager.h ***********************************************/
+/************** Continuing where we left off in sqliteInt.h ******************/
 /************** Include btree.h in the middle of sqliteInt.h *****************/
 /************** Begin file btree.h *******************************************/
 /*
@@ -14477,30 +15174,38 @@ SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
-SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
+SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree*,Pgno);
+SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree*);
 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);
 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char*);
 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
-SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
-SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
-SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
+SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, Pgno*, int flags);
+SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree*);
 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
+
 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
 #ifndef SQLITE_OMIT_SHARED_CACHE
 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
 #endif
+
+/* Savepoints are named, nestable SQL transactions mostly implemented */
+/* in vdbe.c and pager.c See https://sqlite.org/lang_savepoint.html */
 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
 
+/* "Checkpoint" only refers to WAL. See https://sqlite.org/wal.html#ckpt */
+#ifndef SQLITE_OMIT_WAL
+SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
+#endif
+
 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
@@ -14532,7 +15237,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
 
 /*
 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
-** should be one of the following values. The integer values are assigned 
+** should be one of the following values. The integer values are assigned
 ** to constants so that the offset of the corresponding field in an
 ** SQLite database header may be found using the following formula:
 **
@@ -14603,7 +15308,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
 #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
 #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
 
-/* 
+/*
 ** Flags passed as the third argument to sqlite3BtreeCursor().
 **
 ** For read-only cursors the wrFlag argument is always zero. For read-write
@@ -14631,7 +15336,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
 
 SQLITE_PRIVATE int sqlite3BtreeCursor(
   Btree*,                              /* BTree containing table to open */
-  int iTable,                          /* Index of root page */
+  Pgno iTable,                         /* Index of root page */
   int wrFlag,                          /* 1 for writing.  0 for read-only */
   struct KeyInfo*,                     /* First argument to compare function */
   BtCursor *pCursor                    /* Space to write cursor structure */
@@ -14671,7 +15376,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
 ** The nMem field might be zero, indicating that no decomposition is available.
 **
 ** Table btrees (used for rowid tables) contain an integer rowid used as
-** the key and passed in the nKey field.  The pKey field is zero.  
+** the key and passed in the nKey field.  The pKey field is zero.
 ** pData,nData hold the content of the new entry.  nZero extra zero bytes
 ** are appended to the end of the content when constructing the entry.
 ** The aMem,nMem fields are uninitialized for table btrees.
@@ -14690,7 +15395,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
 **
 ** This object is used to pass information into sqlite3BtreeInsert().  The
 ** same information used to be passed as five separate parameters.  But placing
-** the information into this object helps to keep the interface more 
+** the information into this object helps to keep the interface more
 ** organized and understandable, and it also helps the resulting code to
 ** run a little faster by using fewer registers for parameter passing.
 */
@@ -14712,6 +15417,8 @@ SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
 SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);
+SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
 SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
 #endif
@@ -14720,7 +15427,7 @@ SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
 SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
 
-SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
+SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(sqlite3*,Btree*,Pgno*aRoot,int nRoot,int,int*);
 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
 
@@ -14735,14 +15442,18 @@ SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
 
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree*);
+#else
+# define sqlite3BtreeSeekCount(X) 0
+#endif
+
 #ifndef NDEBUG
 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
 #endif
 SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
 
-#ifndef SQLITE_OMIT_BTREECOUNT
-SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
-#endif
+SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
 
 #ifdef SQLITE_TEST
 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
@@ -14765,7 +15476,7 @@ SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
 SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
 #else
-# define sqlite3BtreeEnter(X) 
+# define sqlite3BtreeEnter(X)
 # define sqlite3BtreeEnterAll(X)
 # define sqlite3BtreeSharable(X) 0
 # define sqlite3BtreeEnterCursor(X)
@@ -14859,7 +15570,7 @@ struct VdbeOp {
     Mem *pMem;             /* Used when p4type is P4_MEM */
     VTable *pVtab;         /* Used when p4type is P4_VTAB */
     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
-    int *ai;               /* Used when p4type is P4_INTARRAY */
+    u32 *ai;               /* Used when p4type is P4_INTARRAY */
     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
     Table *pTab;           /* Used when p4type is P4_TABLE */
 #ifdef SQLITE_ENABLE_CURSOR_HINTS
@@ -14939,7 +15650,7 @@ typedef struct VdbeOpList VdbeOpList;
 #define P5_ConstraintFK      4
 
 /*
-** The Vdbe.aColName array contains 5n Mem structures, where n is the 
+** The Vdbe.aColName array contains 5n Mem structures, where n is the
 ** number of columns of data returned by the statement.
 */
 #define COLNAME_NAME     0
@@ -14998,30 +15709,30 @@ typedef struct VdbeOpList VdbeOpList;
 #define OP_SeekLE         23 /* jump, synopsis: key=r[P3@P4]               */
 #define OP_SeekGE         24 /* jump, synopsis: key=r[P3@P4]               */
 #define OP_SeekGT         25 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IfNoHope       26 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_NoConflict     27 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_NotFound       28 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_Found          29 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_SeekRowid      30 /* jump, synopsis: intkey=r[P3]               */
-#define OP_NotExists      31 /* jump, synopsis: intkey=r[P3]               */
-#define OP_Last           32 /* jump                                       */
-#define OP_IfSmaller      33 /* jump                                       */
-#define OP_SorterSort     34 /* jump                                       */
-#define OP_Sort           35 /* jump                                       */
-#define OP_Rewind         36 /* jump                                       */
-#define OP_IdxLE          37 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxGT          38 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxLT          39 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_IdxGE          40 /* jump, synopsis: key=r[P3@P4]               */
-#define OP_RowSetRead     41 /* jump, synopsis: r[P3]=rowset(P1)           */
-#define OP_RowSetTest     42 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
+#define OP_IfNotOpen      26 /* jump, synopsis: if( !csr[P1] ) goto P2     */
+#define OP_IfNoHope       27 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_NoConflict     28 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_NotFound       29 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_Found          30 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_SeekRowid      31 /* jump, synopsis: intkey=r[P3]               */
+#define OP_NotExists      32 /* jump, synopsis: intkey=r[P3]               */
+#define OP_Last           33 /* jump                                       */
+#define OP_IfSmaller      34 /* jump                                       */
+#define OP_SorterSort     35 /* jump                                       */
+#define OP_Sort           36 /* jump                                       */
+#define OP_Rewind         37 /* jump                                       */
+#define OP_IdxLE          38 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxGT          39 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxLT          40 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_IdxGE          41 /* jump, synopsis: key=r[P3@P4]               */
+#define OP_RowSetRead     42 /* jump, synopsis: r[P3]=rowset(P1)           */
 #define OP_Or             43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
 #define OP_And            44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
-#define OP_Program        45 /* jump                                       */
-#define OP_FkIfZero       46 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
-#define OP_IfPos          47 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
-#define OP_IfNotZero      48 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
-#define OP_DecrJumpZero   49 /* jump, synopsis: if (--r[P1])==0 goto P2    */
+#define OP_RowSetTest     45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
+#define OP_Program        46 /* jump                                       */
+#define OP_FkIfZero       47 /* jump, synopsis: if fkctr[P1]==0 goto P2    */
+#define OP_IfPos          48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
+#define OP_IfNotZero      49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
 #define OP_IsNull         50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
 #define OP_NotNull        51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
 #define OP_Ne             52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
@@ -15031,67 +15742,67 @@ typedef struct VdbeOpList VdbeOpList;
 #define OP_Lt             56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
 #define OP_Ge             57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
 #define OP_ElseNotEq      58 /* jump, same as TK_ESCAPE                    */
-#define OP_IncrVacuum     59 /* jump                                       */
-#define OP_VNext          60 /* jump                                       */
-#define OP_Init           61 /* jump, synopsis: Start at P2                */
-#define OP_PureFunc0      62
-#define OP_Function0      63 /* synopsis: r[P3]=func(r[P2@P5])             */
-#define OP_PureFunc       64
-#define OP_Function       65 /* synopsis: r[P3]=func(r[P2@P5])             */
-#define OP_Return         66
-#define OP_EndCoroutine   67
-#define OP_HaltIfNull     68 /* synopsis: if r[P3]=null halt               */
-#define OP_Halt           69
-#define OP_Integer        70 /* synopsis: r[P2]=P1                         */
-#define OP_Int64          71 /* synopsis: r[P2]=P4                         */
-#define OP_String         72 /* synopsis: r[P2]='P4' (len=P1)              */
-#define OP_Null           73 /* synopsis: r[P2..P3]=NULL                   */
-#define OP_SoftNull       74 /* synopsis: r[P1]=NULL                       */
-#define OP_Blob           75 /* synopsis: r[P2]=P4 (len=P1)                */
-#define OP_Variable       76 /* synopsis: r[P2]=parameter(P1,P4)           */
-#define OP_Move           77 /* synopsis: r[P2@P3]=r[P1@P3]                */
-#define OP_Copy           78 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
-#define OP_SCopy          79 /* synopsis: r[P2]=r[P1]                      */
-#define OP_IntCopy        80 /* synopsis: r[P2]=r[P1]                      */
-#define OP_ResultRow      81 /* synopsis: output=r[P1@P2]                  */
-#define OP_CollSeq        82
-#define OP_AddImm         83 /* synopsis: r[P1]=r[P1]+P2                   */
-#define OP_RealAffinity   84
-#define OP_Cast           85 /* synopsis: affinity(r[P1])                  */
-#define OP_Permutation    86
-#define OP_Compare        87 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
-#define OP_IsTrue         88 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
-#define OP_Offset         89 /* synopsis: r[P3] = sqlite_offset(P1)        */
-#define OP_Column         90 /* synopsis: r[P3]=PX                         */
-#define OP_Affinity       91 /* synopsis: affinity(r[P1@P2])               */
-#define OP_MakeRecord     92 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
-#define OP_Count          93 /* synopsis: r[P2]=count()                    */
-#define OP_ReadCookie     94
-#define OP_SetCookie      95
-#define OP_ReopenIdx      96 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenRead       97 /* synopsis: root=P2 iDb=P3                   */
-#define OP_OpenWrite      98 /* synopsis: root=P2 iDb=P3                   */
-#define OP_BitAnd         99 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
-#define OP_BitOr         100 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
-#define OP_ShiftLeft     101 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
-#define OP_ShiftRight    102 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
-#define OP_Add           103 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
-#define OP_Subtract      104 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
-#define OP_Multiply      105 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
-#define OP_Divide        106 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
-#define OP_Remainder     107 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
-#define OP_Concat        108 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
-#define OP_OpenDup       109
-#define OP_BitNot        110 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
-#define OP_OpenAutoindex 111 /* synopsis: nColumn=P2                       */
-#define OP_OpenEphemeral 112 /* synopsis: nColumn=P2                       */
-#define OP_String8       113 /* same as TK_STRING, synopsis: r[P2]='P4'    */
-#define OP_SorterOpen    114
-#define OP_SequenceTest  115 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
-#define OP_OpenPseudo    116 /* synopsis: P3 columns in r[P2]              */
-#define OP_Close         117
-#define OP_ColumnsUsed   118
-#define OP_SeekHit       119 /* synopsis: seekHit=P2                       */
+#define OP_DecrJumpZero   59 /* jump, synopsis: if (--r[P1])==0 goto P2    */
+#define OP_IncrVacuum     60 /* jump                                       */
+#define OP_VNext          61 /* jump                                       */
+#define OP_Init           62 /* jump, synopsis: Start at P2                */
+#define OP_PureFunc       63 /* synopsis: r[P3]=func(r[P2@NP])             */
+#define OP_Function       64 /* synopsis: r[P3]=func(r[P2@NP])             */
+#define OP_Return         65
+#define OP_EndCoroutine   66
+#define OP_HaltIfNull     67 /* synopsis: if r[P3]=null halt               */
+#define OP_Halt           68
+#define OP_Integer        69 /* synopsis: r[P2]=P1                         */
+#define OP_Int64          70 /* synopsis: r[P2]=P4                         */
+#define OP_String         71 /* synopsis: r[P2]='P4' (len=P1)              */
+#define OP_Null           72 /* synopsis: r[P2..P3]=NULL                   */
+#define OP_SoftNull       73 /* synopsis: r[P1]=NULL                       */
+#define OP_Blob           74 /* synopsis: r[P2]=P4 (len=P1)                */
+#define OP_Variable       75 /* synopsis: r[P2]=parameter(P1,P4)           */
+#define OP_Move           76 /* synopsis: r[P2@P3]=r[P1@P3]                */
+#define OP_Copy           77 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
+#define OP_SCopy          78 /* synopsis: r[P2]=r[P1]                      */
+#define OP_IntCopy        79 /* synopsis: r[P2]=r[P1]                      */
+#define OP_ResultRow      80 /* synopsis: output=r[P1@P2]                  */
+#define OP_CollSeq        81
+#define OP_AddImm         82 /* synopsis: r[P1]=r[P1]+P2                   */
+#define OP_RealAffinity   83
+#define OP_Cast           84 /* synopsis: affinity(r[P1])                  */
+#define OP_Permutation    85
+#define OP_Compare        86 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
+#define OP_IsTrue         87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
+#define OP_Offset         88 /* synopsis: r[P3] = sqlite_offset(P1)        */
+#define OP_Column         89 /* synopsis: r[P3]=PX                         */
+#define OP_Affinity       90 /* synopsis: affinity(r[P1@P2])               */
+#define OP_MakeRecord     91 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
+#define OP_Count          92 /* synopsis: r[P2]=count()                    */
+#define OP_ReadCookie     93
+#define OP_SetCookie      94
+#define OP_ReopenIdx      95 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenRead       96 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenWrite      97 /* synopsis: root=P2 iDb=P3                   */
+#define OP_OpenDup        98
+#define OP_OpenAutoindex  99 /* synopsis: nColumn=P2                       */
+#define OP_OpenEphemeral 100 /* synopsis: nColumn=P2                       */
+#define OP_BitAnd        101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
+#define OP_BitOr         102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
+#define OP_ShiftLeft     103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
+#define OP_ShiftRight    104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
+#define OP_Add           105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
+#define OP_Subtract      106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
+#define OP_Multiply      107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
+#define OP_Divide        108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
+#define OP_Remainder     109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
+#define OP_Concat        110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
+#define OP_SorterOpen    111
+#define OP_BitNot        112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
+#define OP_SequenceTest  113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
+#define OP_OpenPseudo    114 /* synopsis: P3 columns in r[P2]              */
+#define OP_String8       115 /* same as TK_STRING, synopsis: r[P2]='P4'    */
+#define OP_Close         116
+#define OP_ColumnsUsed   117
+#define OP_SeekScan      118 /* synopsis: Scan-ahead up to P1 rows         */
+#define OP_SeekHit       119 /* synopsis: set P2<=seekHit<=P3              */
 #define OP_Sequence      120 /* synopsis: r[P2]=cursor[P1].ctr++           */
 #define OP_NewRowid      121 /* synopsis: r[P2]=rowid                      */
 #define OP_Insert        122 /* synopsis: intkey=r[P3] data=r[P2]          */
@@ -15103,48 +15814,52 @@ typedef struct VdbeOpList VdbeOpList;
 #define OP_Rowid         128 /* synopsis: r[P2]=rowid                      */
 #define OP_NullRow       129
 #define OP_SeekEnd       130
-#define OP_SorterInsert  131 /* synopsis: key=r[P2]                        */
-#define OP_IdxInsert     132 /* synopsis: key=r[P2]                        */
+#define OP_IdxInsert     131 /* synopsis: key=r[P2]                        */
+#define OP_SorterInsert  132 /* synopsis: key=r[P2]                        */
 #define OP_IdxDelete     133 /* synopsis: key=r[P2@P3]                     */
 #define OP_DeferredSeek  134 /* synopsis: Move P3 to P1.rowid if needed    */
 #define OP_IdxRowid      135 /* synopsis: r[P2]=rowid                      */
-#define OP_Destroy       136
-#define OP_Clear         137
-#define OP_ResetSorter   138
-#define OP_CreateBtree   139 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
-#define OP_SqlExec       140
-#define OP_ParseSchema   141
-#define OP_LoadAnalysis  142
-#define OP_DropTable     143
-#define OP_DropIndex     144
-#define OP_DropTrigger   145
-#define OP_IntegrityCk   146
-#define OP_RowSetAdd     147 /* synopsis: rowset(P1)=r[P2]                 */
-#define OP_Real          148 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
+#define OP_FinishSeek    136
+#define OP_Destroy       137
+#define OP_Clear         138
+#define OP_ResetSorter   139
+#define OP_CreateBtree   140 /* synopsis: r[P2]=root iDb=P1 flags=P3       */
+#define OP_SqlExec       141
+#define OP_ParseSchema   142
+#define OP_LoadAnalysis  143
+#define OP_DropTable     144
+#define OP_DropIndex     145
+#define OP_DropTrigger   146
+#define OP_IntegrityCk   147
+#define OP_RowSetAdd     148 /* synopsis: rowset(P1)=r[P2]                 */
 #define OP_Param         149
-#define OP_FkCounter     150 /* synopsis: fkctr[P1]+=P2                    */
-#define OP_MemMax        151 /* synopsis: r[P1]=max(r[P1],r[P2])           */
-#define OP_OffsetLimit   152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
-#define OP_AggInverse    153 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
-#define OP_AggStep       154 /* synopsis: accum=r[P3] step(r[P2@P5])       */
-#define OP_AggStep1      155 /* synopsis: accum=r[P3] step(r[P2@P5])       */
-#define OP_AggValue      156 /* synopsis: r[P3]=value N=P2                 */
-#define OP_AggFinal      157 /* synopsis: accum=r[P1] N=P2                 */
-#define OP_Expire        158
-#define OP_TableLock     159 /* synopsis: iDb=P1 root=P2 write=P3          */
-#define OP_VBegin        160
-#define OP_VCreate       161
-#define OP_VDestroy      162
-#define OP_VOpen         163
-#define OP_VColumn       164 /* synopsis: r[P3]=vcolumn(P2)                */
-#define OP_VRename       165
-#define OP_Pagecount     166
-#define OP_MaxPgcnt      167
-#define OP_Trace         168
-#define OP_CursorHint    169
-#define OP_Noop          170
-#define OP_Explain       171
-#define OP_Abortable     172
+#define OP_Real          150 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
+#define OP_FkCounter     151 /* synopsis: fkctr[P1]+=P2                    */
+#define OP_MemMax        152 /* synopsis: r[P1]=max(r[P1],r[P2])           */
+#define OP_OffsetLimit   153 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
+#define OP_AggInverse    154 /* synopsis: accum=r[P3] inverse(r[P2@P5])    */
+#define OP_AggStep       155 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggStep1      156 /* synopsis: accum=r[P3] step(r[P2@P5])       */
+#define OP_AggValue      157 /* synopsis: r[P3]=value N=P2                 */
+#define OP_AggFinal      158 /* synopsis: accum=r[P1] N=P2                 */
+#define OP_Expire        159
+#define OP_CursorLock    160
+#define OP_CursorUnlock  161
+#define OP_TableLock     162 /* synopsis: iDb=P1 root=P2 write=P3          */
+#define OP_VBegin        163
+#define OP_VCreate       164
+#define OP_VDestroy      165
+#define OP_VOpen         166
+#define OP_VColumn       167 /* synopsis: r[P3]=vcolumn(P2)                */
+#define OP_VRename       168
+#define OP_Pagecount     169
+#define OP_MaxPgcnt      170
+#define OP_Trace         171
+#define OP_CursorHint    172
+#define OP_ReleaseReg    173 /* synopsis: release r[P1@P2] mask P3         */
+#define OP_Noop          174
+#define OP_Explain       175
+#define OP_Abortable     176
 
 /* Properties such as "out2" or "jump" that are specified in
 ** comments following the "case" for each opcode in the vdbe.c
@@ -15160,25 +15875,26 @@ typedef struct VdbeOpList VdbeOpList;
 /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
 /*   8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
 /*  16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
-/*  24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
-/*  32 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
-/*  40 */ 0x01, 0x23, 0x0b, 0x26, 0x26, 0x01, 0x01, 0x03,\
+/*  24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\
+/*  32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
+/*  40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
 /*  48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
-/*  56 */ 0x0b, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,\
-/*  64 */ 0x00, 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10,\
-/*  72 */ 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10,\
-/*  80 */ 0x10, 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00,\
-/*  88 */ 0x12, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
-/*  96 */ 0x00, 0x00, 0x00, 0x26, 0x26, 0x26, 0x26, 0x26,\
-/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12, 0x00,\
-/* 112 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/*  56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\
+/*  64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\
+/*  72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\
+/*  80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\
+/*  88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
+/*  96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\
+/* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
+/* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
 /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
 /* 128 */ 0x10, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
-/* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
-/* 144 */ 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00, 0x04,\
-/* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
-/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
-/* 168 */ 0x00, 0x00, 0x00, 0x00, 0x00,}
+/* 136 */ 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,\
+/* 144 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x10, 0x00,\
+/* 152 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 168 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
+/* 176 */ 0x00,}
 
 /* The sqlite3P2Values() routine is able to run faster if it knows
 ** the value of the largest JUMP opcode.  The smaller the maximum
@@ -15186,7 +15902,7 @@ typedef struct VdbeOpList VdbeOpList;
 ** generated this include file strives to group all JUMP opcodes
 ** together near the beginning of the list.
 */
-#define SQLITE_MX_JUMP_OPCODE  61  /* Maximum JUMP opcode */
+#define SQLITE_MX_JUMP_OPCODE  62  /* Maximum JUMP opcode */
 
 /************** End of opcodes.h *********************************************/
 /************** Continuing where we left off in vdbe.h ***********************/
@@ -15202,6 +15918,7 @@ typedef struct VdbeOpList VdbeOpList;
 ** for a description of what each of these routines does.
 */
 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
+SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);
 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
@@ -15212,6 +15929,7 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
+SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
 SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
 SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
@@ -15251,8 +15969,14 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
+SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
+#ifdef SQLITE_DEBUG
+SQLITE_PRIVATE   void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
+#else
+# define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
+#endif
 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
 SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
@@ -15301,11 +16025,13 @@ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
 
-#ifndef SQLITE_OMIT_TRIGGER
 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
-#endif
+SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);
 
 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);
+#endif
 
 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
 ** each VDBE opcode.
@@ -15410,257 +16136,6 @@ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
 
 /************** End of vdbe.h ************************************************/
 /************** Continuing where we left off in sqliteInt.h ******************/
-/************** Include pager.h in the middle of sqliteInt.h *****************/
-/************** Begin file pager.h *******************************************/
-/*
-** 2001 September 15
-**
-** The author disclaims copyright to this source code.  In place of
-** a legal notice, here is a blessing:
-**
-**    May you do good and not evil.
-**    May you find forgiveness for yourself and forgive others.
-**    May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This header file defines the interface that the sqlite page cache
-** subsystem.  The page cache subsystem reads and writes a file a page
-** at a time and provides a journal for rollback.
-*/
-
-#ifndef SQLITE_PAGER_H
-#define SQLITE_PAGER_H
-
-/*
-** Default maximum size for persistent journal files. A negative 
-** value means no limit. This value may be overridden using the 
-** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
-*/
-#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
-  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
-#endif
-
-/*
-** The type used to represent a page number.  The first page in a file
-** is called page 1.  0 is used to represent "not a page".
-*/
-typedef u32 Pgno;
-
-/*
-** Each open file is managed by a separate instance of the "Pager" structure.
-*/
-typedef struct Pager Pager;
-
-/*
-** Handle type for pages.
-*/
-typedef struct PgHdr DbPage;
-
-/*
-** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
-** reserved for working around a windows/posix incompatibility). It is
-** used in the journal to signify that the remainder of the journal file 
-** is devoted to storing a master journal name - there are no more pages to
-** roll back. See comments for function writeMasterJournal() in pager.c 
-** for details.
-*/
-#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
-
-/*
-** Allowed values for the flags parameter to sqlite3PagerOpen().
-**
-** NOTE: These values must match the corresponding BTREE_ values in btree.h.
-*/
-#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
-#define PAGER_MEMORY        0x0002    /* In-memory database */
-
-/*
-** Valid values for the second argument to sqlite3PagerLockingMode().
-*/
-#define PAGER_LOCKINGMODE_QUERY      -1
-#define PAGER_LOCKINGMODE_NORMAL      0
-#define PAGER_LOCKINGMODE_EXCLUSIVE   1
-
-/*
-** Numeric constants that encode the journalmode.
-**
-** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
-** are exposed in the API via the "PRAGMA journal_mode" command and
-** therefore cannot be changed without a compatibility break.
-*/
-#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
-#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
-#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
-#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
-#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
-#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
-#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
-
-/*
-** Flags that make up the mask passed to sqlite3PagerGet().
-*/
-#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
-#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
-
-/*
-** Flags for sqlite3PagerSetFlags()
-**
-** Value constraints (enforced via assert()):
-**    PAGER_FULLFSYNC      == SQLITE_FullFSync
-**    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
-**    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
-*/
-#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
-#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
-#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
-#define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
-#define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
-#define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
-#define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
-#define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
-#define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
-
-/*
-** The remainder of this file contains the declarations of the functions
-** that make up the Pager sub-system API. See source code comments for 
-** a detailed description of each routine.
-*/
-
-/* Open and close a Pager connection. */ 
-SQLITE_PRIVATE int sqlite3PagerOpen(
-  sqlite3_vfs*,
-  Pager **ppPager,
-  const char*,
-  int,
-  int,
-  int,
-  void(*)(DbPage*)
-);
-SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
-SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
-
-/* Functions used to configure a Pager object. */
-SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
-SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
-#ifdef SQLITE_HAS_CODEC
-SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
-#endif
-SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
-SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
-SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
-SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
-SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
-SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
-SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
-SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
-SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
-SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
-SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
-SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
-
-/* Functions used to obtain and release page references. */ 
-SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
-SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
-SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
-
-/* Operations on page references. */
-SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
-SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
-SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
-SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
-SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
-SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
-
-/* Functions used to manage pager transactions and savepoints. */
-SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
-SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
-SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
-SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
-SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
-SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
-SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
-SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
-SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
-
-#ifndef SQLITE_OMIT_WAL
-SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
-SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
-SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
-SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
-SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
-# ifdef SQLITE_ENABLE_SNAPSHOT
-SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
-SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
-SQLITE_PRIVATE   int sqlite3PagerSnapshotRecover(Pager *pPager);
-SQLITE_PRIVATE   int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
-SQLITE_PRIVATE   void sqlite3PagerSnapshotUnlock(Pager *pPager);
-# endif
-#endif
-
-#ifdef SQLITE_DIRECT_OVERFLOW_READ
-SQLITE_PRIVATE   int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
-#endif
-
-#ifdef SQLITE_ENABLE_ZIPVFS
-SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
-#endif
-
-/* Functions used to query pager state and configuration. */
-SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
-SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
-#ifdef SQLITE_DEBUG
-SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
-#endif
-SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
-SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
-SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
-SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
-SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
-SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
-SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
-SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
-SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
-SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
-SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
-#else
-# define sqlite3PagerResetLockTimeout(X)
-#endif
-
-/* Functions used to truncate the database file. */
-SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
-
-SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
-
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
-SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
-#endif
-
-/* Functions to support testing and debugging. */
-#if !defined(NDEBUG) || defined(SQLITE_TEST)
-SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
-SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
-#endif
-#ifdef SQLITE_TEST
-SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
-SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
-  void disable_simulated_io_errors(void);
-  void enable_simulated_io_errors(void);
-#else
-# define disable_simulated_io_errors()
-# define enable_simulated_io_errors()
-#endif
-
-#endif /* SQLITE_PAGER_H */
-
-/************** End of pager.h ***********************************************/
-/************** Continuing where we left off in sqliteInt.h ******************/
 /************** Include pcache.h in the middle of sqliteInt.h ****************/
 /************** Begin file pcache.h ******************************************/
 /*
@@ -15675,7 +16150,7 @@ SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
 **
 *************************************************************************
 ** This header file defines the interface that the sqlite page cache
-** subsystem. 
+** subsystem.
 */
 
 #ifndef _PCACHE_H_
@@ -15701,7 +16176,7 @@ struct PgHdr {
   u16 flags;                     /* PGHDR flags defined below */
 
   /**********************************************************************
-  ** Elements above, except pCache, are public.  All that follow are 
+  ** Elements above, except pCache, are public.  All that follow are
   ** private to pcache.c and should not be accessed by other modules.
   ** pCache is grouped with the public elements for efficiency.
   */
@@ -15754,7 +16229,7 @@ SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
 SQLITE_PRIVATE int sqlite3PcacheSize(void);
 
 /* One release per successful fetch.  Page is pinned until released.
-** Reference counted. 
+** Reference counted.
 */
 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
@@ -15798,7 +16273,7 @@ SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
 
 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
 /* Iterate through all dirty pages currently stored in the cache. This
-** interface is only available if SQLITE_CHECK_PAGES is defined when the 
+** interface is only available if SQLITE_CHECK_PAGES is defined when the
 ** library is built.
 */
 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
@@ -15973,10 +16448,10 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
 ** Mcafee started using SQLite in their anti-virus product and it
 ** started putting files with the "sqlite" name in the c:/temp folder.
-** This annoyed many windows users.  Those users would then do a 
+** This annoyed many windows users.  Those users would then do a
 ** Google search for "sqlite", find the telephone numbers of the
 ** developers and call to wake them up at night and complain.
-** For this reason, the default name prefix is changed to be "sqlite" 
+** For this reason, the default name prefix is changed to be "sqlite"
 ** spelled backwards.  So the temp files are still identified, but
 ** anybody smart enough to figure out the code is also likely smart
 ** enough to know that calling the developer will not help get rid
@@ -16017,9 +16492,9 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 ** UnlockFile().
 **
 ** LockFile() prevents not just writing but also reading by other processes.
-** A SHARED_LOCK is obtained by locking a single randomly-chosen 
-** byte out of a specific range of bytes. The lock byte is obtained at 
-** random so two separate readers can probably access the file at the 
+** A SHARED_LOCK is obtained by locking a single randomly-chosen
+** byte out of a specific range of bytes. The lock byte is obtained at
+** random so two separate readers can probably access the file at the
 ** same time, unless they are unlucky and choose the same lock byte.
 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
@@ -16038,7 +16513,7 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 ** The following #defines specify the range of bytes used for locking.
 ** SHARED_SIZE is the number of bytes available in the pool from which
 ** a random byte is selected for a shared lock.  The pool of bytes for
-** shared locks begins at SHARED_FIRST. 
+** shared locks begins at SHARED_FIRST.
 **
 ** The same locking strategy and
 ** byte ranges are used for Unix.  This leaves open the possibility of having
@@ -16054,7 +16529,7 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 ** that all locks will fit on a single page even at the minimum page size.
 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
 ** is set high so that we don't have to allocate an unused page except
-** for very large databases.  But one should test the page skipping logic 
+** for very large databases.  But one should test the page skipping logic
 ** by setting PENDING_BYTE low and running the entire regression suite.
 **
 ** Changing the value of PENDING_BYTE results in a subtly incompatible
@@ -16078,8 +16553,8 @@ SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
 */
 SQLITE_PRIVATE int sqlite3OsInit(void);
 
-/* 
-** Functions for accessing sqlite3_file methods 
+/*
+** Functions for accessing sqlite3_file methods
 */
 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
@@ -16105,8 +16580,8 @@ SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
 
 
-/* 
-** Functions for accessing sqlite3_vfs methods 
+/*
+** Functions for accessing sqlite3_vfs methods
 */
 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
@@ -16124,7 +16599,7 @@ SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
 
 /*
-** Convenience functions for opening and closing files using 
+** Convenience functions for opening and closing files using
 ** sqlite3_malloc() to obtain space for the file-handle structure.
 */
 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
@@ -16194,9 +16669,9 @@ SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
 */
 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
 #define sqlite3_mutex_free(X)
-#define sqlite3_mutex_enter(X)    
+#define sqlite3_mutex_enter(X)
 #define sqlite3_mutex_try(X)      SQLITE_OK
-#define sqlite3_mutex_leave(X)    
+#define sqlite3_mutex_leave(X)
 #define sqlite3_mutex_held(X)     ((void)(X),1)
 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
@@ -16309,7 +16784,6 @@ struct Schema {
 */
 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
-#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
 #define DB_ResetWanted     0x0008  /* Reset the schema when nSchemaLock==0 */
 
 /*
@@ -16337,15 +16811,47 @@ struct Schema {
 ** is shared by multiple database connections.  Therefore, while parsing
 ** schema information, the Lookaside.bEnabled flag is cleared so that
 ** lookaside allocations are not used to construct the schema objects.
+**
+** New lookaside allocations are only allowed if bDisable==0.  When
+** bDisable is greater than zero, sz is set to zero which effectively
+** disables lookaside without adding a new test for the bDisable flag
+** in a performance-critical path.  sz should be set by to szTrue whenever
+** bDisable changes back to zero.
+**
+** Lookaside buffers are initially held on the pInit list.  As they are
+** used and freed, they are added back to the pFree list.  New allocations
+** come off of pFree first, then pInit as a fallback.  This dual-list
+** allows use to compute a high-water mark - the maximum number of allocations
+** outstanding at any point in the past - by subtracting the number of
+** allocations on the pInit list from the total number of allocations.
+**
+** Enhancement on 2019-12-12:  Two-size-lookaside
+** The default lookaside configuration is 100 slots of 1200 bytes each.
+** The larger slot sizes are important for performance, but they waste
+** a lot of space, as most lookaside allocations are less than 128 bytes.
+** The two-size-lookaside enhancement breaks up the lookaside allocation
+** into two pools:  One of 128-byte slots and the other of the default size
+** (1200-byte) slots.   Allocations are filled from the small-pool first,
+** failing over to the full-size pool if that does not work.  Thus more
+** lookaside slots are available while also using less memory.
+** This enhancement can be omitted by compiling with
+** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
 */
 struct Lookaside {
   u32 bDisable;           /* Only operate the lookaside when zero */
   u16 sz;                 /* Size of each buffer in bytes */
+  u16 szTrue;             /* True value of sz, even if disabled */
   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
   u32 nSlot;              /* Number of lookaside slots allocated */
   u32 anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
   LookasideSlot *pInit;   /* List of buffers not previously used */
   LookasideSlot *pFree;   /* List of available buffers */
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+  LookasideSlot *pSmallInit; /* List of small buffers not prediously used */
+  LookasideSlot *pSmallFree; /* List of available small buffers */
+  void *pMiddle;          /* First byte past end of full-size buffers and
+                          ** the first byte of LOOKASIDE_SMALL buffers */
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
   void *pStart;           /* First byte of available memory space */
   void *pEnd;             /* First byte past end of available space */
 };
@@ -16353,6 +16859,17 @@ struct LookasideSlot {
   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
 };
 
+#define DisableLookaside  db->lookaside.bDisable++;db->lookaside.sz=0
+#define EnableLookaside   db->lookaside.bDisable--;\
+   db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
+
+/* Size of the smaller allocations in two-size lookside */
+#ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+#  define LOOKASIDE_SMALL           0
+#else
+#  define LOOKASIDE_SMALL         128
+#endif
+
 /*
 ** A hash table for built-in function definitions.  (Application-defined
 ** functions use a regular table table from hash.h.)
@@ -16424,7 +16941,7 @@ SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
 struct sqlite3 {
   sqlite3_vfs *pVfs;            /* OS Interface */
   struct Vdbe *pVdbe;           /* List of active virtual machines */
-  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
+  CollSeq *pDfltColl;           /* BINARY collseq for the database encoding */
   sqlite3_mutex *mutex;         /* Connection mutex */
   Db *aDb;                      /* All backends */
   int nDb;                      /* Number of backends currently in use */
@@ -16458,7 +16975,7 @@ struct sqlite3 {
   int aLimit[SQLITE_N_LIMIT];   /* Limits */
   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
   struct sqlite3InitInfo {      /* Information used during initialization */
-    int newTnum;                /* Rootpage of table being initialized */
+    Pgno newTnum;               /* Rootpage of table being initialized */
     u8 iDb;                     /* Which db file is being initialized */
     u8 busy;                    /* TRUE if currently initializing */
     unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
@@ -16473,7 +16990,10 @@ struct sqlite3 {
   int nVDestroy;                /* Number of active OP_VDestroy operations */
   int nExtension;               /* Number of loaded extensions */
   void **aExtension;            /* Array of shared library handles */
-  int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
+  union {
+    void (*xLegacy)(void*,const char*);     /* Legacy trace function */
+    int (*xV2)(u32,void*,void*,void*);      /* V2 Trace function */
+  } trace;
   void *pTraceArg;                          /* Argument to the trace function */
 #ifndef SQLITE_OMIT_DEPRECATED
   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
@@ -16527,6 +17047,7 @@ struct sqlite3 {
   BusyHandler busyHandler;      /* Busy callback */
   Db aDbStatic[2];              /* Static space for the 2 default backends */
   Savepoint *pSavepoint;        /* List of active savepoints */
+  int nAnalysisLimit;           /* Number of index rows to ANALYZE */
   int busyTimeout;              /* Busy handler timeout, in msec */
   int nSavepoint;               /* Number of non-transaction savepoints */
   int nStatement;               /* Number of nested statement-transactions  */
@@ -16534,7 +17055,7 @@ struct sqlite3 {
   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
   size_t *pnBytesFreed;         /* If not NULL, increment this in DbFree() */
 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
-  /* The following variables are all protected by the STATIC_MASTER
+  /* The following variables are all protected by the STATIC_MAIN
   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
   **
   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
@@ -16562,6 +17083,13 @@ struct sqlite3 {
 #define ENC(db)        ((db)->enc)
 
 /*
+** A u64 constant where the lower 32 bits are all zeros.  Only the
+** upper 32 bits are included in the argument.  Necessary because some
+** C-compilers still do not accept LL integer literals.
+*/
+#define HI(X)  ((u64)(X)<<32)
+
+/*
 ** Possible values for the sqlite3.flags.
 **
 ** Value constraints (enforced via assert()):
@@ -16569,16 +17097,15 @@ struct sqlite3 {
 **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
 **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
 */
-#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_MASTER */
+#define SQLITE_WriteSchema    0x00000001  /* OK to update SQLITE_SCHEMA */
 #define SQLITE_LegacyFileFmt  0x00000002  /* Create new databases in format 1 */
 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
 #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
 #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
 #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
-#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
-                                          /*   DELETE, or UPDATE and return */
-                                          /*   the count using a callback. */
+#define SQLITE_TrustedSchema  0x00000080  /* Allow unsafe functions and
+                                          ** vtabs in the schema definition */
 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
                                           /*   result set is empty */
 #define SQLITE_IgnoreChecks   0x00000200  /* Do not enforce check constraints */
@@ -16604,9 +17131,11 @@ struct sqlite3 {
 #define SQLITE_DqsDDL         0x20000000  /* dbl-quoted strings allowed in DDL*/
 #define SQLITE_DqsDML         0x40000000  /* dbl-quoted strings allowed in DML*/
 #define SQLITE_EnableView     0x80000000  /* Enable the use of views */
+#define SQLITE_CountRows      HI(0x00001) /* Count rows changed by INSERT, */
+                                          /*   DELETE, or UPDATE and return */
+                                          /*   the count using a callback. */
 
 /* Flags used only if debugging */
-#define HI(X)  ((u64)(X)<<32)
 #ifdef SQLITE_DEBUG
 #define SQLITE_SqlTrace       HI(0x0100000) /* Debug print SQL as it executes */
 #define SQLITE_VdbeListing    HI(0x0200000) /* Debug listings of VDBE progs */
@@ -16624,6 +17153,8 @@ struct sqlite3 {
 #define DBFLAG_Vacuum         0x0004  /* Currently in a VACUUM */
 #define DBFLAG_VacuumInto     0x0008  /* Currently running VACUUM INTO */
 #define DBFLAG_SchemaKnownOk  0x0010  /* Schema is known to be valid */
+#define DBFLAG_InternalFunc   0x0020  /* Allow use of internal functions */
+#define DBFLAG_EncodingFixed  0x0040  /* No longer possible to change enc. */
 
 /*
 ** Bits of the sqlite3.dbOptFlags field that are used by the
@@ -16731,6 +17262,7 @@ struct FuncDestructor {
 **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
 **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
 **     SQLITE_FUNC_DIRECT    ==  SQLITE_DIRECTONLY from the API
+**     SQLITE_FUNC_UNSAFE    ==  SQLITE_INNOCUOUS
 **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
 */
 #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
@@ -16741,18 +17273,29 @@ struct FuncDestructor {
 #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
 #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
 #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
-#define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
+/*                           0x0200 -- available for reuse */
 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
 #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
 #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
                                     ** single query - might change over time */
-#define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
+#define SQLITE_FUNC_TEST     0x4000 /* Built-in testing functions */
 #define SQLITE_FUNC_OFFSET   0x8000 /* Built-in sqlite_offset() function */
 #define SQLITE_FUNC_WINDOW   0x00010000 /* Built-in window-only function */
 #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
 #define SQLITE_FUNC_DIRECT   0x00080000 /* Not for use in TRIGGERs or VIEWs */
 #define SQLITE_FUNC_SUBTYPE  0x00100000 /* Result likely to have sub-type */
+#define SQLITE_FUNC_UNSAFE   0x00200000 /* Function has side effects */
+#define SQLITE_FUNC_INLINE   0x00400000 /* Functions implemented in-line */
+
+/* Identifier numbers for each in-line function */
+#define INLINEFUNC_coalesce             0
+#define INLINEFUNC_implies_nonnull_row  1
+#define INLINEFUNC_expr_implies_expr    2
+#define INLINEFUNC_expr_compare         3
+#define INLINEFUNC_affinity             4
+#define INLINEFUNC_iif                  5
+#define INLINEFUNC_unlikely            99  /* Default case */
 
 /*
 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
@@ -16768,6 +17311,22 @@ struct FuncDestructor {
 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
 **
+**   SFUNCTION(zName, nArg, iArg, bNC, xFunc)
+**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
+**     adds the SQLITE_DIRECTONLY flag.
+**
+**   INLINE_FUNC(zName, nArg, iFuncId, mFlags)
+**     zName is the name of a function that is implemented by in-line
+**     byte code rather than by the usual callbacks. The iFuncId
+**     parameter determines the function id.  The mFlags parameter is
+**     optional SQLITE_FUNC_ flags for this function.
+**
+**   TEST_FUNC(zName, nArg, iFuncId, mFlags)
+**     zName is the name of a test-only function implemented by in-line
+**     byte code rather than by the usual callbacks. The iFuncId
+**     parameter determines the function id.  The mFlags parameter is
+**     optional SQLITE_FUNC_ flags for this function.
+**
 **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
 **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
@@ -16778,7 +17337,7 @@ struct FuncDestructor {
 **   PURE_DATE(zName, nArg, iArg, bNC, xFunc)
 **     Used for "pure" date/time functions, this macro is like DFUNCTION
 **     except that it does set the SQLITE_FUNC_CONSTANT flags.  iArg is
-**     ignored and the user-data for these functions is set to an 
+**     ignored and the user-data for these functions is set to an
 **     arbitrary non-NULL pointer.  The bNC parameter is not used.
 **
 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
@@ -16807,6 +17366,16 @@ struct FuncDestructor {
 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
+  {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
+   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
+#define INLINE_FUNC(zName, nArg, iArg, mFlags) \
+  {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
+   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
+#define TEST_FUNC(zName, nArg, iArg, mFlags) \
+  {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
+         SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
+   SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
    0, 0, xFunc, 0, 0, 0, #zName, {0} }
@@ -16822,12 +17391,6 @@ struct FuncDestructor {
 #define LIKEFUNC(zName, nArg, arg, flags) \
   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
    (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
-#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue) \
-  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
-   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,0,#zName, {0}}
-#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
-  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
-   SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xFinal,0,#zName, {0}}
 #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
@@ -16873,26 +17436,46 @@ struct Module {
 };
 
 /*
-** information about each column of an SQL table is held in an instance
-** of this structure.
+** Information about each column of an SQL table is held in an instance
+** of the Column structure, in the Table.aCol[] array.
+**
+** Definitions:
+**
+**   "table column index"     This is the index of the column in the
+**                            Table.aCol[] array, and also the index of
+**                            the column in the original CREATE TABLE stmt.
+**
+**   "storage column index"   This is the index of the column in the
+**                            record BLOB generated by the OP_MakeRecord
+**                            opcode.  The storage column index is less than
+**                            or equal to the table column index.  It is
+**                            equal if and only if there are no VIRTUAL
+**                            columns to the left.
 */
 struct Column {
   char *zName;     /* Name of this column, \000, then the type */
-  Expr *pDflt;     /* Default value of this column */
+  Expr *pDflt;     /* Default value or GENERATED ALWAYS AS value */
   char *zColl;     /* Collating sequence.  If NULL, use the default */
   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
   char affinity;   /* One of the SQLITE_AFF_... values */
   u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
-  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
+  u8 hName;        /* Column name hash for faster lookup */
+  u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
 };
 
 /* Allowed values for Column.colFlags:
 */
-#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
-#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
-#define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
-#define COLFLAG_UNIQUE   0x0008    /* Column def contains "UNIQUE" or "PK" */
+#define COLFLAG_PRIMKEY   0x0001   /* Column is part of the primary key */
+#define COLFLAG_HIDDEN    0x0002   /* A hidden column in a virtual table */
+#define COLFLAG_HASTYPE   0x0004   /* Type name follows column name */
+#define COLFLAG_UNIQUE    0x0008   /* Column def contains "UNIQUE" or "PK" */
 #define COLFLAG_SORTERREF 0x0010   /* Use sorter-refs with this column */
+#define COLFLAG_VIRTUAL   0x0020   /* GENERATED ALWAYS AS ... VIRTUAL */
+#define COLFLAG_STORED    0x0040   /* GENERATED ALWAYS AS ... STORED */
+#define COLFLAG_NOTAVAIL  0x0080   /* STORED column not yet calculated */
+#define COLFLAG_BUSY      0x0100   /* Blocks recursion on GENERATED columns */
+#define COLFLAG_GENERATED 0x0060   /* Combo: _STORED, _VIRTUAL */
+#define COLFLAG_NOINSERT  0x0062   /* Combo: _HIDDEN, _STORED, _VIRTUAL */
 
 /*
 ** A "Collating Sequence" is defined by an instance of the following
@@ -17010,10 +17593,17 @@ struct VTable {
   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
   int nRef;                 /* Number of pointers to this structure */
   u8 bConstraint;           /* True if constraints are supported */
+  u8 eVtabRisk;             /* Riskiness of allowing hacker access */
   int iSavepoint;           /* Depth of the SAVEPOINT stack */
   VTable *pNext;            /* Next in linked list (see above) */
 };
 
+/* Allowed values for VTable.eVtabRisk
+*/
+#define SQLITE_VTABRISK_Low          0
+#define SQLITE_VTABRISK_Normal       1
+#define SQLITE_VTABRISK_High         2
+
 /*
 ** The schema for each SQL table and view is represented in memory
 ** by an instance of the following structure.
@@ -17027,11 +17617,12 @@ struct Table {
   char *zColAff;       /* String defining the affinity of each column */
   ExprList *pCheck;    /* All CHECK constraints */
                        /*   ... also used as column name list in a VIEW */
-  int tnum;            /* Root BTree page for this table */
+  Pgno tnum;           /* Root BTree page for this table */
   u32 nTabRef;         /* Number of pointers to this Table */
   u32 tabFlags;        /* Mask of TF_* values */
   i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
   i16 nCol;            /* Number of columns in this table */
+  i16 nNVCol;          /* Number of columns that are not VIRTUAL */
   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
   LogEst szTabRow;     /* Estimated size of each table row in bytes */
 #ifdef SQLITE_ENABLE_COSTMULT
@@ -17058,20 +17649,29 @@ struct Table {
 ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
 ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
 ** the TF_OOOHidden attribute would apply in this case.  Such tables require
-** special handling during INSERT processing.
+** special handling during INSERT processing. The "OOO" means "Out Of Order".
+**
+** Constraints:
+**
+**         TF_HasVirtual == COLFLAG_Virtual
+**         TF_HasStored  == COLFLAG_Stored
 */
 #define TF_Readonly        0x0001    /* Read-only system table */
 #define TF_Ephemeral       0x0002    /* An ephemeral table */
 #define TF_HasPrimaryKey   0x0004    /* Table has a primary key */
 #define TF_Autoincrement   0x0008    /* Integer primary key is autoincrement */
 #define TF_HasStat1        0x0010    /* nRowLogEst set from sqlite_stat1 */
-#define TF_WithoutRowid    0x0020    /* No rowid.  PRIMARY KEY is the key */
-#define TF_NoVisibleRowid  0x0040    /* No user-visible "rowid" column */
-#define TF_OOOHidden       0x0080    /* Out-of-Order hidden columns */
+#define TF_HasVirtual      0x0020    /* Has one or more VIRTUAL columns */
+#define TF_HasStored       0x0040    /* Has one or more STORED columns */
+#define TF_HasGenerated    0x0060    /* Combo: HasVirtual + HasStored */
+#define TF_WithoutRowid    0x0080    /* No rowid.  PRIMARY KEY is the key */
 #define TF_StatsUsed       0x0100    /* Query planner decisions affected by
                                      ** Index.aiRowLogEst[] values */
-#define TF_HasNotNull      0x0200    /* Contains NOT NULL constraints */
-#define TF_Shadow          0x0400    /* True for a shadow table */
+#define TF_NoVisibleRowid  0x0200    /* No user-visible "rowid" column */
+#define TF_OOOHidden       0x0400    /* Out-of-Order hidden columns */
+#define TF_HasNotNull      0x0800    /* Contains NOT NULL constraints */
+#define TF_Shadow          0x1000    /* True for a shadow table */
+#define TF_HasStat4        0x2000    /* STAT4 info available for this table */
 
 /*
 ** Test to see whether or not a table is a virtual table.  This is
@@ -17080,8 +17680,11 @@ struct Table {
 */
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 #  define IsVirtual(X)      ((X)->nModuleArg)
+#  define ExprIsVtab(X)  \
+              ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg)
 #else
 #  define IsVirtual(X)      0
+#  define ExprIsVtab(X)     0
 #endif
 
 /*
@@ -17289,7 +17892,7 @@ struct UnpackedRecord {
 ** element.
 **
 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
-** generate VDBE code (as opposed to parsing one read from an sqlite_master
+** generate VDBE code (as opposed to parsing one read from an sqlite_schema
 ** table as part of parsing an existing database schema), transient instances
 ** of this structure may be created. In this case the Index.tnum variable is
 ** used to store the address of a VDBE instruction, not a database page
@@ -17308,7 +17911,7 @@ struct Index {
   const char **azColl;     /* Array of collation sequence names for index */
   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
   ExprList *aColExpr;      /* Column expressions */
-  int tnum;                /* DB Page containing root of this index */
+  Pgno tnum;               /* DB Page containing root of this index */
   LogEst szIdxRow;         /* Estimated average row size in bytes */
   u16 nKeyCol;             /* Number of columns forming the key */
   u16 nColumn;             /* Number of columns stored in the index */
@@ -17322,6 +17925,7 @@ struct Index {
   unsigned hasStat1:1;     /* aiRowLogEst values come from sqlite_stat1 */
   unsigned bNoQuery:1;     /* Do not use this index to optimize queries */
   unsigned bAscKeyBug:1;   /* True if the bba7b69f9849b5bf bug applies */
+  unsigned bHasVCol:1;     /* Index references one or more VIRTUAL columns */
 #ifdef SQLITE_ENABLE_STAT4
   int nSample;             /* Number of elements in aSample[] */
   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
@@ -17392,7 +17996,7 @@ struct Token {
 ** code for a SELECT that contains aggregate functions.
 **
 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
-** pointer to this structure.  The Expr.iColumn field is the index in
+** pointer to this structure.  The Expr.iAgg field is the index in
 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
 ** code for that node.
 **
@@ -17412,23 +18016,25 @@ struct AggInfo {
   ExprList *pGroupBy;     /* The group by clause */
   struct AggInfo_col {    /* For each column used in source tables */
     Table *pTab;             /* Source table */
+    Expr *pCExpr;            /* The original expression */
     int iTable;              /* Cursor number of the source table */
-    int iColumn;             /* Column number within the source table */
-    int iSorterColumn;       /* Column number in the sorting index */
     int iMem;                /* Memory location that acts as accumulator */
-    Expr *pExpr;             /* The original expression */
+    i16 iColumn;             /* Column number within the source table */
+    i16 iSorterColumn;       /* Column number in the sorting index */
   } *aCol;
   int nColumn;            /* Number of used entries in aCol[] */
   int nAccumulator;       /* Number of columns that show through to the output.
                           ** Additional columns are used only as parameters to
                           ** aggregate functions */
   struct AggInfo_func {   /* For each aggregate function */
-    Expr *pExpr;             /* Expression encoding the function */
+    Expr *pFExpr;            /* Expression encoding the function */
     FuncDef *pFunc;          /* The aggregate function implementation */
     int iMem;                /* Memory location that acts as accumulator */
     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
   } *aFunc;
   int nFunc;              /* Number of entries in aFunc[] */
+  u32 selId;              /* Select to which this AggInfo belongs */
+  AggInfo *pNext;         /* Next in list of them all */
 };
 
 /*
@@ -17438,10 +18044,10 @@ struct AggInfo {
 ** it uses less memory in the Expr object, which is a big memory user
 ** in systems with lots of prepared statements.  And few applications
 ** need more than about 10 or 20 variables.  But some extreme users want
-** to have prepared statements with over 32767 variables, and for them
+** to have prepared statements with over 32766 variables, and for them
 ** the option is available (at compile-time).
 */
-#if SQLITE_MAX_VARIABLE_NUMBER<=32767
+#if SQLITE_MAX_VARIABLE_NUMBER<32767
 typedef i16 ynVar;
 #else
 typedef int ynVar;
@@ -17513,6 +18119,13 @@ typedef int ynVar;
 struct Expr {
   u8 op;                 /* Operation performed by this node */
   char affExpr;          /* affinity, or RAISE type */
+  u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op
+                         ** TK_COLUMN: the value of p5 for OP_Column
+                         ** TK_AGG_FUNCTION: nesting depth
+                         ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
+#ifdef SQLITE_DEBUG
+  u8 vvaFlags;           /* Verification flags. */
+#endif
   u32 flags;             /* Various flags.  EP_* See below */
   union {
     char *zToken;          /* Token value. Zero terminated and dequoted */
@@ -17551,9 +18164,6 @@ struct Expr {
                          ** TK_SELECT_COLUMN: column of the result vector */
   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
-  u8 op2;                /* TK_REGISTER/TK_TRUTH: original value of Expr.op
-                         ** TK_COLUMN: the value of p5 for OP_Column
-                         ** TK_AGG_FUNCTION: nesting depth */
   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
   union {
     Table *pTab;           /* TK_COLUMN: Table containing column. Can be NULL
@@ -17582,7 +18192,7 @@ struct Expr {
 #define EP_DblQuoted  0x000040 /* token.z was originally in "..." */
 #define EP_InfixFunc  0x000080 /* True for an infix function: LIKE, GLOB, etc */
 #define EP_Collate    0x000100 /* Tree contains a TK_COLLATE operator */
-  /*                  0x000200 Available for reuse */
+#define EP_Commuted   0x000200 /* Comparison operator has been commuted */
 #define EP_IntValue   0x000400 /* Integer value contained in u.iValue */
 #define EP_xIsSelect  0x000800 /* x.pSelect is valid (otherwise x.pList is) */
 #define EP_Skip       0x001000 /* Operator does not contribute to affinity */
@@ -17590,7 +18200,7 @@ struct Expr {
 #define EP_TokenOnly  0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
 #define EP_Win        0x008000 /* Contains window functions */
 #define EP_MemToken   0x010000 /* Need to sqlite3DbFree() Expr.zToken */
-#define EP_NoReduce   0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
+#define EP_IfNullRow  0x020000 /* The TK_IF_NULL_ROW opcode */
 #define EP_Unlikely   0x040000 /* unlikely() or likelihood() function */
 #define EP_ConstFunc  0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
 #define EP_CanBeNull  0x100000 /* Can be null despite NOT NULL constraint */
@@ -17603,7 +18213,8 @@ struct Expr {
 #define EP_Static    0x8000000 /* Held in memory not obtained from malloc() */
 #define EP_IsTrue   0x10000000 /* Always has boolean value of TRUE */
 #define EP_IsFalse  0x20000000 /* Always has boolean value of FALSE */
-#define EP_Indirect 0x40000000 /* Contained within a TRIGGER or a VIEW */
+#define EP_FromDDL  0x40000000 /* Originates from sqlite_schema */
+               /*   0x80000000 // Available */
 
 /*
 ** The EP_Propagate mask is a set of properties that automatically propagate
@@ -17622,14 +18233,24 @@ struct Expr {
 #define ExprAlwaysTrue(E)   (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
 #define ExprAlwaysFalse(E)  (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
 
+
+/* Flags for use with Expr.vvaFlags
+*/
+#define EP_NoReduce   0x01  /* Cannot EXPRDUP_REDUCE this Expr */
+#define EP_Immutable  0x02  /* Do not change this Expr node */
+
 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
 ** and Accreditation only.  It works like ExprSetProperty() during VVA
 ** processes but is a no-op for delivery.
 */
 #ifdef SQLITE_DEBUG
-# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
+# define ExprSetVVAProperty(E,P)   (E)->vvaFlags|=(P)
+# define ExprHasVVAProperty(E,P)   (((E)->vvaFlags&(P))!=0)
+# define ExprClearVVAProperties(E) (E)->vvaFlags = 0
 #else
 # define ExprSetVVAProperty(E,P)
+# define ExprHasVVAProperty(E,P)   0
+# define ExprClearVVAProperties(E)
 #endif
 
 /*
@@ -17667,23 +18288,28 @@ struct Expr {
 ** also be used as the argument to a function, in which case the a.zName
 ** field is not used.
 **
-** By default the Expr.zSpan field holds a human-readable description of
-** the expression that is used in the generation of error messages and
-** column labels.  In this case, Expr.zSpan is typically the text of a
-** column expression as it exists in a SELECT statement.  However, if
-** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
-** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
-** form is used for name resolution with nested FROM clauses.
+** In order to try to keep memory usage down, the Expr.a.zEName field
+** is used for multiple purposes:
+**
+**     eEName          Usage
+**    ----------       -------------------------
+**    ENAME_NAME       (1) the AS of result set column
+**                     (2) COLUMN= of an UPDATE
+**
+**    ENAME_TAB        DB.TABLE.NAME used to resolve names
+**                     of subqueries
+**
+**    ENAME_SPAN       Text of the original result set
+**                     expression.
 */
 struct ExprList {
   int nExpr;             /* Number of expressions on the list */
   struct ExprList_item { /* For each expression in the list */
     Expr *pExpr;            /* The parse tree for this expression */
-    char *zName;            /* Token associated with this expression */
-    char *zSpan;            /* Original text of the expression */
+    char *zEName;           /* Token associated with this expression */
     u8 sortFlags;           /* Mask of KEYINFO_ORDER_* flags */
+    unsigned eEName :2;     /* Meaning of zEName */
     unsigned done :1;       /* A flag to indicate when processing is finished */
-    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
     unsigned reusable :1;   /* Constant expression is reusable */
     unsigned bSorterRef :1; /* Defer evaluation until after sorting */
     unsigned bNulls: 1;     /* True if explicit "NULLS FIRST/LAST" */
@@ -17698,6 +18324,13 @@ struct ExprList {
 };
 
 /*
+** Allowed values for Expr.a.eEName
+*/
+#define ENAME_NAME  0       /* The AS clause of a result set */
+#define ENAME_SPAN  1       /* Complete text of the result set expression */
+#define ENAME_TAB   2       /* "DB.TABLE.NAME" for the result set */
+
+/*
 ** An instance of this structure can hold a simple list of identifiers,
 ** such as the list "a,b,c" in the following statements:
 **
@@ -17760,6 +18393,7 @@ struct SrcList {
       unsigned isCorrelated :1;  /* True if sub-query is correlated */
       unsigned viaCoroutine :1;  /* Implemented as a co-routine */
       unsigned isRecursive :1;   /* True for recursive reference in WITH */
+      unsigned fromDDL :1;       /* Comes from sqlite_schema */
     } fg;
     int iCursor;      /* The VDBE cursor number used to access this table */
     Expr *pOn;        /* The ON clause of a join */
@@ -17804,9 +18438,9 @@ struct SrcList {
 #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
 #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
 #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
-#define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
+                        /*     0x0400    not currently used */
 #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
-#define WHERE_SEEK_UNIQ_TABLE  0x1000 /* Do not defer seeks if unique */
+                        /*     0x1000    not currently used */
                         /*     0x2000    not currently used */
 #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
                         /*     0x8000    not currently used */
@@ -17863,21 +18497,24 @@ struct NameContext {
 **    NC_HasWin    == EP_Win
 **
 */
-#define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
-#define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
-#define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
-#define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
-#define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
-#define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
-#define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
-#define NC_UEList    0x0080  /* True if uNC.pEList is used */
-#define NC_UAggInfo  0x0100  /* True if uNC.pAggInfo is used */
-#define NC_UUpsert   0x0200  /* True if uNC.pUpsert is used */
-#define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
-#define NC_Complex   0x2000  /* True if a function or subquery seen */
-#define NC_AllowWin  0x4000  /* Window functions are allowed here */
-#define NC_HasWin    0x8000  /* One or more window functions seen */
-#define NC_IsDDL    0x10000  /* Resolving names in a CREATE statement */
+#define NC_AllowAgg  0x00001  /* Aggregate functions are allowed here */
+#define NC_PartIdx   0x00002  /* True if resolving a partial index WHERE */
+#define NC_IsCheck   0x00004  /* True if resolving a CHECK constraint */
+#define NC_GenCol    0x00008  /* True for a GENERATED ALWAYS AS clause */
+#define NC_HasAgg    0x00010  /* One or more aggregate functions seen */
+#define NC_IdxExpr   0x00020  /* True if resolving columns of CREATE INDEX */
+#define NC_SelfRef   0x0002e  /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
+#define NC_VarSelect 0x00040  /* A correlated subquery has been seen */
+#define NC_UEList    0x00080  /* True if uNC.pEList is used */
+#define NC_UAggInfo  0x00100  /* True if uNC.pAggInfo is used */
+#define NC_UUpsert   0x00200  /* True if uNC.pUpsert is used */
+#define NC_MinMaxAgg 0x01000  /* min/max aggregates seen.  See note above */
+#define NC_Complex   0x02000  /* True if a function or subquery seen */
+#define NC_AllowWin  0x04000  /* Window functions are allowed here */
+#define NC_HasWin    0x08000  /* One or more window functions seen */
+#define NC_IsDDL     0x10000  /* Resolving names in a CREATE statement */
+#define NC_InAggFunc 0x20000  /* True if analyzing arguments to an agg func */
+#define NC_FromDDL   0x40000  /* SQL text comes from sqlite_schema */
 
 /*
 ** An instance of the following object describes a single ON CONFLICT
@@ -17888,7 +18525,7 @@ struct NameContext {
 ** conflict-target clause.)  The pUpsertTargetWhere is the optional
 ** WHERE clause used to identify partial unique indexes.
 **
-** pUpsertSet is the list of column=expr terms of the UPDATE statement. 
+** pUpsertSet is the list of column=expr terms of the UPDATE statement.
 ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING.  The
 ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
 ** WHERE clause is omitted.
@@ -17927,13 +18564,13 @@ struct Upsert {
 ** sequences for the ORDER BY clause.
 */
 struct Select {
-  ExprList *pEList;      /* The fields of the result */
   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
   LogEst nSelectRow;     /* Estimated number of result rows */
   u32 selFlags;          /* Various SF_* values */
   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
   u32 selId;             /* Unique identifier number for this SELECT */
   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
+  ExprList *pEList;      /* The fields of the result */
   SrcList *pSrc;         /* The FROM clause */
   Expr *pWhere;          /* The WHERE clause */
   ExprList *pGroupBy;    /* The GROUP BY clause */
@@ -17958,26 +18595,30 @@ struct Select {
 **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
 **     SF_FixedLimit == WHERE_USE_LIMIT
 */
-#define SF_Distinct       0x00001  /* Output should be DISTINCT */
-#define SF_All            0x00002  /* Includes the ALL keyword */
-#define SF_Resolved       0x00004  /* Identifiers have been resolved */
-#define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
-#define SF_HasAgg         0x00010  /* Contains aggregate functions */
-#define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
-#define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
-#define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
-#define SF_Compound       0x00100  /* Part of a compound query */
-#define SF_Values         0x00200  /* Synthesized from VALUES clause */
-#define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
-#define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
-#define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
-#define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
-#define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
-#define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
-#define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
-#define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
-#define SF_ComplexResult  0x40000  /* Result contains subquery or function */
-#define SF_WhereBegin     0x80000  /* Really a WhereBegin() call.  Debug Only */
+#define SF_Distinct      0x0000001 /* Output should be DISTINCT */
+#define SF_All           0x0000002 /* Includes the ALL keyword */
+#define SF_Resolved      0x0000004 /* Identifiers have been resolved */
+#define SF_Aggregate     0x0000008 /* Contains agg functions or a GROUP BY */
+#define SF_HasAgg        0x0000010 /* Contains aggregate functions */
+#define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
+#define SF_Expanded      0x0000040 /* sqlite3SelectExpand() called on this */
+#define SF_HasTypeInfo   0x0000080 /* FROM subqueries have Table metadata */
+#define SF_Compound      0x0000100 /* Part of a compound query */
+#define SF_Values        0x0000200 /* Synthesized from VALUES clause */
+#define SF_MultiValue    0x0000400 /* Single VALUES term with multiple rows */
+#define SF_NestedFrom    0x0000800 /* Part of a parenthesized FROM clause */
+#define SF_MinMaxAgg     0x0001000 /* Aggregate containing min() or max() */
+#define SF_Recursive     0x0002000 /* The recursive part of a recursive CTE */
+#define SF_FixedLimit    0x0004000 /* nSelectRow set by a constant LIMIT */
+#define SF_MaybeConvert  0x0008000 /* Need convertCompoundSelectToSubquery() */
+#define SF_Converted     0x0010000 /* By convertCompoundSelectToSubquery() */
+#define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
+#define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
+#define SF_WhereBegin    0x0080000 /* Really a WhereBegin() call.  Debug Only */
+#define SF_WinRewrite    0x0100000 /* Window function rewrite accomplished */
+#define SF_View          0x0200000 /* SELECT statement is a view */
+#define SF_NoopOrderBy   0x0400000 /* ORDER BY is ignored for this query */
+#define SF_UpdateFrom    0x0800000 /* Statement is an UPDATE...FROM */
 
 /*
 ** The results of a SELECT can be distributed in several ways, as defined
@@ -17996,9 +18637,6 @@ struct Select {
 **                     statements within triggers whose only purpose is
 **                     the side-effects of functions.
 **
-** All of the above are free to ignore their ORDER BY clause. Those that
-** follow must honor the ORDER BY clause.
-**
 **     SRT_Output      Generate a row of output (using the OP_ResultRow
 **                     opcode) for each row in the result set.
 **
@@ -18042,18 +18680,31 @@ struct Select {
 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
 **                     the same record has never been stored before.  The
 **                     index at pDest->iSDParm+1 hold all prior stores.
+**
+**     SRT_Upfrom      Store results in the temporary table already opened by
+**                     pDest->iSDParm. If (pDest->iSDParm<0), then the temp
+**                     table is an intkey table - in this case the first
+**                     column returned by the SELECT is used as the integer
+**                     key. If (pDest->iSDParm>0), then the table is an index
+**                     table. (pDest->iSDParm) is the number of key columns in
+**                     each index record in this case.
 */
 #define SRT_Union        1  /* Store result as keys in an index */
 #define SRT_Except       2  /* Remove result from a UNION index */
 #define SRT_Exists       3  /* Store 1 if the result is not empty */
 #define SRT_Discard      4  /* Do not save the results anywhere */
-#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
-#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
+#define SRT_DistFifo     5  /* Like SRT_Fifo, but unique results only */
+#define SRT_DistQueue    6  /* Like SRT_Queue, but unique results only */
+
+/* The DISTINCT clause is ignored for all of the above.  Not that
+** IgnorableDistinct() implies IgnorableOrderby() */
+#define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
+
 #define SRT_Queue        7  /* Store result in an queue */
-#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
+#define SRT_Fifo         8  /* Store result as data with an automatic rowid */
 
 /* The ORDER BY clause is ignored for all of the above */
-#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
+#define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
 
 #define SRT_Output       9  /* Output each row of result */
 #define SRT_Mem         10  /* Store result in a memory cell */
@@ -18061,14 +18712,16 @@ struct Select {
 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
 #define SRT_Coroutine   13  /* Generate a single row of result */
 #define SRT_Table       14  /* Store result as data with an automatic rowid */
+#define SRT_Upfrom      15  /* Store result as data with rowid */
 
 /*
 ** An instance of this object describes where to put of the results of
 ** a SELECT statement.
 */
 struct SelectDest {
-  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
+  u8 eDest;            /* How to dispose of the results.  One of SRT_* above. */
   int iSDParm;         /* A parameter used by the eDest disposal method */
+  int iSDParm2;        /* A second parameter for the eDest disposal method */
   int iSdst;           /* Base register where results are written */
   int nSdst;           /* Number of registers allocated */
   char *zAffSdst;      /* Affinity used when eDest==SRT_Set */
@@ -18198,6 +18851,7 @@ struct Parse {
   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
   Table *pTriggerTab;  /* Table triggers are being coded for */
   Parse *pParentParse; /* Parent parser if this parser is nested */
+  AggInfo *pAggList;   /* List of all AggInfo objects */
   int addrCrTab;       /* Address of OP_CreateBtree opcode on CREATE TABLE */
   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
   u32 oldmask;         /* Mask of old.* columns referenced */
@@ -18227,9 +18881,7 @@ struct Parse {
   ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
   u8 explain;               /* True if the EXPLAIN flag is found on the query */
-#if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
   u8 eParseMode;            /* PARSE_MODE_XXX constant */
-#endif
 #ifndef SQLITE_OMIT_VIRTUALTABLE
   int nVtabLock;            /* Number of virtual tables to lock */
 #endif
@@ -18261,8 +18913,8 @@ struct Parse {
 
 #define PARSE_MODE_NORMAL        0
 #define PARSE_MODE_DECLARE_VTAB  1
-#define PARSE_MODE_RENAME_COLUMN 2
-#define PARSE_MODE_RENAME_TABLE  3
+#define PARSE_MODE_RENAME        2
+#define PARSE_MODE_UNMAP         3
 
 /*
 ** Sizes and pointers of various parts of the Parse object.
@@ -18284,7 +18936,7 @@ struct Parse {
 #if defined(SQLITE_OMIT_ALTERTABLE)
   #define IN_RENAME_OBJECT 0
 #else
-  #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME_COLUMN)
+  #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
 #endif
 
 #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
@@ -18417,6 +19069,7 @@ struct TriggerStep {
   Trigger *pTrig;      /* The trigger that this step is a part of */
   Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
   char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
+  SrcList *pFrom;      /* FROM clause for UPDATE statement (if any) */
   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
   ExprList *pExprList; /* SET clause for UPDATE */
   IdList *pIdList;     /* Column names for INSERT */
@@ -18435,7 +19088,7 @@ typedef struct DbFixer DbFixer;
 struct DbFixer {
   Parse *pParse;      /* The parsing context.  Error messages written here */
   Schema *pSchema;    /* Fix items to this schema */
-  int bVarOnly;       /* Check for variable references only */
+  u8 bTemp;           /* True for TEMP schema entries */
   const char *zDb;    /* Make sure all objects are contained in this database */
   const char *zType;  /* Type of the container - used for error messages */
   const Token *pName; /* Name of the container - used for error messages */
@@ -18472,6 +19125,7 @@ typedef struct {
   int rc;             /* Result code stored here */
   u32 mInitFlags;     /* Flags controlling error messages */
   u32 nInitRow;       /* Number of rows processed */
+  Pgno mxPage;        /* Maximum page number.  0 for no limit. */
 } InitData;
 
 /*
@@ -18557,7 +19211,6 @@ struct Sqlite3Config {
   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
   int bLocaltimeFault;              /* True to fail localtime() calls */
 #endif
-  int bInternalFunctions;           /* Internal SQL functions are visible */
   int iOnceResetThreshold;          /* When to reset OP_Once counters */
   u32 szSorterRef;                  /* Min size in bytes to use sorter-refs */
   unsigned int iPrngSeed;           /* Alternative fixed seed for the PRNG */
@@ -18590,7 +19243,7 @@ struct Walker {
   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
   int walkerDepth;                          /* Number of subqueries */
-  u8 eCode;                                 /* A small processing code */
+  u16 eCode;                                /* A small processing code */
   union {                                   /* Extra data for callback */
     NameContext *pNC;                         /* Naming context */
     int n;                                    /* A counter */
@@ -18606,6 +19259,8 @@ struct Walker {
     struct WindowRewrite *pRewrite;           /* Window rewrite context */
     struct WhereConst *pConst;                /* WHERE clause constants */
     struct RenameCtx *pRename;                /* RENAME COLUMN context */
+    struct Table *pTab;                       /* Table of generated column */
+    struct SrcList_item *pSrcItem;            /* A single FROM clause item */
   } u;
 };
 
@@ -18618,6 +19273,9 @@ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
 SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
 SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
 SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
+SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
+SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
+
 #ifdef SQLITE_DEBUG
 SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
 #endif
@@ -18719,7 +19377,7 @@ SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*,
 SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
 SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
 SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int);
-SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Window*);
+SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
 SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
 SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
 SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
@@ -18762,13 +19420,16 @@ SQLITE_PRIVATE int sqlite3CantopenError(int);
 #ifdef SQLITE_DEBUG
 SQLITE_PRIVATE   int sqlite3NomemError(int);
 SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
-SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
-# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
 #else
 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
+#endif
+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
+SQLITE_PRIVATE   int sqlite3CorruptPgnoError(int,Pgno);
+# define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
+#else
 # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
 #endif
 
@@ -18988,6 +19649,7 @@ SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
 SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
 SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
+SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);
 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
 SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
@@ -19014,9 +19676,16 @@ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
 SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
 SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);
 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
-SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
+SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *, int);
 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
-SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
+SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);
+#ifdef SQLITE_OMIT_GENERATED_COLUMNS
+# define sqlite3TableColumnToStorage(T,X) (X)  /* No-op pass-through */
+# define sqlite3StorageColumnToTable(T,X) (X)  /* No-op pass-through */
+#else
+SQLITE_PRIVATE   i16 sqlite3TableColumnToStorage(Table*, i16);
+SQLITE_PRIVATE   i16 sqlite3StorageColumnToTable(Table*, i16);
+#endif
 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
 #if SQLITE_ENABLE_HIDDEN_COLUMNS
 SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
@@ -19026,17 +19695,14 @@ SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
-SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
+SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*, const char*, const char*);
 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
+SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
                     sqlite3_vfs**,char**,char **);
-#ifdef SQLITE_HAS_CODEC
-SQLITE_PRIVATE   int sqlite3CodecQueryParameters(sqlite3*,const char*,const char*);
-#else
-# define sqlite3CodecQueryParameters(A,B,C) 0
-#endif
+#define sqlite3CodecQueryParameters(A,B,C) 0
 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
 
 #ifdef SQLITE_UNTESTABLE
@@ -19086,10 +19752,14 @@ SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
 # define sqlite3AutoincrementEnd(X)
 #endif
 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+SQLITE_PRIVATE   void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
+#endif
 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
 SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2);
 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
                                       Token*, Select*, Expr*, IdList*);
@@ -19130,17 +19800,20 @@ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
 #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
 #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
 #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
+SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
 SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int);
+#endif
 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
-SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
+SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
-SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
@@ -19165,6 +19838,7 @@ SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
 SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
+SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker*,Parse*);
 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
 SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
@@ -19182,6 +19856,7 @@ SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
+SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);
 SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
 SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
@@ -19254,13 +19929,14 @@ SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
                                         Select*,u8,Upsert*,
                                         const char*,const char*);
-SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
-                                        const char*,const char*);
+SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,SrcList*,ExprList*,
+                                        Expr*, u8, const char*,const char*);
 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
                                         const char*,const char*);
 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
+SQLITE_PRIVATE   SrcList *sqlite3TriggerStepSrc(Parse*, TriggerStep*);
 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
 #else
@@ -19274,9 +19950,11 @@ SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Tab
 # define sqlite3ParseToplevel(p) p
 # define sqlite3IsToplevel(p) 1
 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
+# define sqlite3TriggerStepSrc(A,B) 0
 #endif
 
 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
+SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);
 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
 #ifndef SQLITE_OMIT_AUTHORIZATION
@@ -19291,6 +19969,7 @@ SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int)
 # define sqlite3AuthContextPush(a,b,c)
 # define sqlite3AuthContextPop(a)  ((void)(a))
 #endif
+SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
@@ -19300,8 +19979,10 @@ SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
+SQLITE_PRIVATE void sqlite3Int64ToText(i64,char*);
 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
+SQLITE_PRIVATE int sqlite3GetUInt32(const char*, u32*);
 SQLITE_PRIVATE int sqlite3Atoi(const char*);
 #ifndef SQLITE_OMIT_UTF16
 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
@@ -19339,6 +20020,8 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
 */
 #define getVarint32(A,B)  \
   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
+#define getVarint32NR(A,B) \
+  B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
 #define putVarint32(A,B)  \
   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
   sqlite3PutVarint((A),(B)))
@@ -19348,10 +20031,10 @@ SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
 
 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
-SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
-SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
+SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
+SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
 SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
-SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
+SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
@@ -19374,9 +20057,10 @@ SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
 SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
-SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
-SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
-SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
+SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
+SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
+SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
+SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
@@ -19421,11 +20105,11 @@ SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
 #ifndef SQLITE_OMIT_WSD
 SQLITE_PRIVATE int sqlite3PendingByte;
 #endif
-#endif
+#endif /* SQLITE_AMALGAMATION */
 #ifdef VDBE_PROFILE
 SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
 #endif
-SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
+SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, Pgno, Pgno);
 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
@@ -19437,7 +20121,14 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
 SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
-SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
+SQLITE_PRIVATE int sqlite3MatchEName(
+  const struct ExprList_item*,
+  const char*,
+  const char*,
+  const char*
+);
+SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
+SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
 SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
@@ -19453,7 +20144,7 @@ SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
 SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
-SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
+SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
@@ -19476,10 +20167,10 @@ SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
 #endif
 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
   void (*)(sqlite3_context*,int,sqlite3_value **),
-  void (*)(sqlite3_context*,int,sqlite3_value **), 
+  void (*)(sqlite3_context*,int,sqlite3_value **),
   void (*)(sqlite3_context*),
   void (*)(sqlite3_context*),
-  void (*)(sqlite3_context*,int,sqlite3_value **), 
+  void (*)(sqlite3_context*,int,sqlite3_value **),
   FuncDestructor *pDestructor
 );
 SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
@@ -19532,7 +20223,7 @@ SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
 #endif
 
 #ifndef SQLITE_OMIT_SHARED_CACHE
-SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
+SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, Pgno, u8, const char *);
 #else
   #define sqlite3TableLock(v,w,x,y,z)
 #endif
@@ -19575,6 +20266,14 @@ SQLITE_PRIVATE    Module *sqlite3VtabCreateModule(
    );
 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
 #endif
+SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+SQLITE_PRIVATE   int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
+SQLITE_PRIVATE   int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
+#else
+# define sqlite3ShadowTableName(A,B) 0
+# define sqlite3IsShadowTableOf(A,B,C) 0
+#endif
 SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
 SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
@@ -19596,7 +20295,8 @@ SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
 #endif
 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
-SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
+SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
+SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
 #ifndef SQLITE_OMIT_WAL
@@ -19830,7 +20530,7 @@ SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
 /* #include "sqliteInt.h" */
 
 /* An array to map all upper-case characters into their corresponding
-** lower-case character. 
+** lower-case character.
 **
 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
 ** handle case conversions for the UTF character set since the tables
@@ -19897,12 +20597,11 @@ SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
 ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
 ** array. tolower() is used more often than toupper() by SQLite.
 **
-** Bit 0x40 is set if the character is non-alphanumeric and can be used in an 
+** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
 ** non-ASCII UTF character. Hence the test for whether or not a character is
 ** part of an identifier is 0x46.
 */
-#ifdef SQLITE_ASCII
 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
@@ -19940,7 +20639,6 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
 };
-#endif
 
 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
 ** compatibility for legacy applications, the URI filename capability is
@@ -19952,16 +20650,9 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
 ** disabled. The default value may be changed by compiling with the
 ** SQLITE_USE_URI symbol defined.
-**
-** URI filenames are enabled by default if SQLITE_HAS_CODEC is
-** enabled.
 */
 #ifndef SQLITE_USE_URI
-# ifdef SQLITE_HAS_CODEC
-#  define SQLITE_USE_URI 1
-# else
-#  define SQLITE_USE_URI 0
-# endif
+# define SQLITE_USE_URI 0
 #endif
 
 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
@@ -19971,7 +20662,7 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 #if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
 #else
-# if !SQLITE_ALLOW_COVERING_INDEX_SCAN 
+# if !SQLITE_ALLOW_COVERING_INDEX_SCAN
 #   error "Compile-time disabling of covering index scan using the\
  -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
  Contact SQLite developers if this is a problem for you, and\
@@ -19994,7 +20685,7 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
 ** setting.)
 */
-#ifndef SQLITE_STMTJRNL_SPILL 
+#ifndef SQLITE_STMTJRNL_SPILL
 # define SQLITE_STMTJRNL_SPILL (64*1024)
 #endif
 
@@ -20005,9 +20696,18 @@ SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
 ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
 ** or at run-time for an individual database connection using
 ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
+**
+** With the two-size-lookaside enhancement, less lookaside is required.
+** The default configuration of 1200,40 actually provides 30 1200-byte slots
+** and 93 128-byte slots, which is more lookaside than is available
+** using the older 1200,100 configuration without two-size-lookaside.
 */
 #ifndef SQLITE_DEFAULT_LOOKASIDE
-# define SQLITE_DEFAULT_LOOKASIDE 1200,100
+# ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+#   define SQLITE_DEFAULT_LOOKASIDE 1200,100  /* 120KB of memory */
+# else
+#   define SQLITE_DEFAULT_LOOKASIDE 1200,40   /* 48KB of memory */
+# endif
 #endif
 
 
@@ -20074,7 +20774,6 @@ SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
    0,                         /* xTestCallback */
    0,                         /* bLocaltimeFault */
 #endif
-   0,                         /* bInternalFunctions */
    0x7ffffffe,                /* iOnceResetThreshold */
    SQLITE_DEFAULT_SORTERREF_SIZE,   /* szSorterRef */
    0,                         /* iPrngSeed */
@@ -20117,12 +20816,19 @@ SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
 #endif
 
+/*
+** Tracing flags set by SQLITE_TESTCTRL_TRACEFLAGS.
+*/
+#ifdef WHERETRACE_ENABLED /* 0x20800 */
+SQLITE_PRIVATE u32 sqlite3WhereTrace = 0;
+#endif
+
 /* #include "opcodes.h" */
 /*
 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
 ** created by mkopcodeh.awk during compilation.  Data is obtained
 ** from the comments following the "case OP_xxxx:" statements in
-** the vdbe.c file.  
+** the vdbe.c file.
 */
 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
 
@@ -20184,7 +20890,8 @@ SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
 ** "explain" P4 display logic is enabled.
 */
 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
-     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
+     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
+     || defined(SQLITE_ENABLE_BYTECODE_VTAB)
 # define VDBE_DISPLAY_P4 1
 #else
 # define VDBE_DISPLAY_P4 0
@@ -20238,10 +20945,10 @@ struct VdbeCursor {
   Bool isEphemeral:1;     /* True for an ephemeral table */
   Bool useRandomRowid:1;  /* Generate new record numbers semi-randomly */
   Bool isOrdered:1;       /* True if the table is not BTREE_UNORDERED */
-  Bool seekHit:1;         /* See the OP_SeekHit and OP_IfNoHope opcodes */
+  u16 seekHit;            /* See the OP_SeekHit and OP_IfNoHope opcodes */
   Btree *pBtx;            /* Separate file holding temporary table */
   i64 seqCount;           /* Sequence counter */
-  int *aAltMap;           /* Mapping from table to index column numbers */
+  u32 *aAltMap;           /* Mapping from table to index column numbers */
 
   /* Cached OP_Column parse information is only valid if cacheStatus matches
   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
@@ -20293,7 +21000,7 @@ struct VdbeCursor {
 ** When a sub-program is executed (OP_Program), a structure of this type
 ** is allocated to store the current value of the program counter, as
 ** well as the current memory cell array and various other frame specific
-** values stored in the Vdbe struct. When the sub-program is finished, 
+** values stored in the Vdbe struct. When the sub-program is finished,
 ** these values are copied back to the Vdbe from the VdbeFrame structure,
 ** restoring the state of the VM to as it was before the sub-program
 ** began executing.
@@ -20390,7 +21097,7 @@ struct sqlite3_value {
 ** If the MEM_Str flag is set then Mem.z points at a string representation.
 ** Usually this is encoded in the same unicode encoding as the main
 ** database (see below for exceptions). If the MEM_Term flag is also
-** set, then the string is nul terminated. The MEM_Int and MEM_Real 
+** set, then the string is nul terminated. The MEM_Int and MEM_Real
 ** flags may coexist with the MEM_Str flag.
 */
 #define MEM_Null      0x0001   /* Value is NULL (or a pointer) */
@@ -20451,7 +21158,7 @@ struct sqlite3_value {
 #endif
 
 /*
-** Each auxiliary data pointer stored by a user defined function 
+** Each auxiliary data pointer stored by a user defined function
 ** implementation calling sqlite3_set_auxdata() is stored in an instance
 ** of this structure. All such structures associated with a single VM
 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
@@ -20571,9 +21278,9 @@ struct Vdbe {
   u8 errorAction;         /* Recovery action to do in case of an error */
   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
   u8 prepFlags;           /* SQLITE_PREPARE_* flags */
+  u8 doingRerun;          /* True if rerunning after an auto-reprepare */
   bft expired:2;          /* 1: recompile VM immediately  2: when convenient */
   bft explain:2;          /* True if EXPLAIN present on SQL command */
-  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
   bft changeCntOn:1;      /* True to update the change-counter */
   bft runOnlyOnce:1;      /* Automatically expire on reset */
   bft usesStmtJournal:1;  /* True if uses a statement journal */
@@ -20611,7 +21318,7 @@ struct Vdbe {
 #define VDBE_MAGIC_DEAD     0x5606c3c8    /* The VDBE has been deallocated */
 
 /*
-** Structure used to store the context required by the 
+** Structure used to store the context required by the
 ** sqlite3_preupdate_*() API functions.
 */
 struct PreUpdate {
@@ -20626,7 +21333,7 @@ struct PreUpdate {
   i64 iKey1;                      /* First key value passed to hook */
   i64 iKey2;                      /* Second key value passed to hook */
   Mem *aNew;                      /* Array of new.* values */
-  Table *pTab;                    /* Schema object being upated */          
+  Table *pTab;                    /* Schema object being upated */
   Index *pPk;                     /* PK index if pTab is WITHOUT ROWID */
 };
 
@@ -20636,7 +21343,8 @@ struct PreUpdate {
 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
 void sqliteVdbePopStack(Vdbe*,int);
-SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
+SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);
+SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, u32*);
 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
@@ -20648,7 +21356,14 @@ int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
-#ifndef SQLITE_OMIT_EXPLAIN
+#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
+SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
+SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
+#endif
+#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
+SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
+#endif
+#if !defined(SQLITE_OMIT_EXPLAIN)
 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
 #endif
 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
@@ -20682,14 +21397,15 @@ SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
-SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
+SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);
 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
 #ifndef SQLITE_OMIT_WINDOWFUNC
 SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
 #endif
-#ifndef SQLITE_OMIT_EXPLAIN
+#if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
 #endif
 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
@@ -20723,7 +21439,7 @@ SQLITE_PRIVATE   void sqlite3VdbeAssertAbortable(Vdbe*);
 # define sqlite3VdbeAssertAbortable(V)
 #endif
 
-#if !defined(SQLITE_OMIT_SHARED_CACHE) 
+#if !defined(SQLITE_OMIT_SHARED_CACHE)
 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
 #else
 # define sqlite3VdbeEnter(X)
@@ -20748,7 +21464,7 @@ SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
 
 #ifdef SQLITE_DEBUG
 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
-SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
+SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
 #endif
 #ifndef SQLITE_OMIT_UTF16
 SQLITE_PRIVATE   int sqlite3VdbeMemTranslate(Mem*, u8);
@@ -20931,6 +21647,10 @@ static u32 countLookasideSlots(LookasideSlot *p){
 SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
   u32 nInit = countLookasideSlots(db->lookaside.pInit);
   u32 nFree = countLookasideSlots(db->lookaside.pFree);
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+  nInit += countLookasideSlots(db->lookaside.pSmallInit);
+  nFree += countLookasideSlots(db->lookaside.pSmallFree);
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
   if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
   return db->lookaside.nSlot - (nInit+nFree);
 }
@@ -20963,6 +21683,15 @@ SQLITE_API int sqlite3_db_status(
           db->lookaside.pInit = db->lookaside.pFree;
           db->lookaside.pFree = 0;
         }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+        p = db->lookaside.pSmallFree;
+        if( p ){
+          while( p->pNext ) p = p->pNext;
+          p->pNext = db->lookaside.pSmallInit;
+          db->lookaside.pSmallInit = db->lookaside.pSmallFree;
+          db->lookaside.pSmallFree = 0;
+        }
+#endif
       }
       break;
     }
@@ -20983,7 +21712,7 @@ SQLITE_API int sqlite3_db_status(
       break;
     }
 
-    /* 
+    /*
     ** Return an approximation for the amount of memory currently used
     ** by all pagers associated with the given database connection.  The
     ** highwater mark is meaningless and is returned as zero.
@@ -21027,7 +21756,7 @@ SQLITE_API int sqlite3_db_status(
           HashElem *p;
 
           nByte += sqlite3GlobalConfig.m2.xRoundup(sizeof(HashElem)) * (
-              pSchema->tblHash.count 
+              pSchema->tblHash.count
             + pSchema->trigHash.count
             + pSchema->idxHash.count
             + pSchema->fkeyHash.count
@@ -21077,12 +21806,12 @@ SQLITE_API int sqlite3_db_status(
 
     /*
     ** Set *pCurrent to the total cache hits or misses encountered by all
-    ** pagers the database handle is connected to. *pHighwater is always set 
+    ** pagers the database handle is connected to. *pHighwater is always set
     ** to zero.
     */
     case SQLITE_DBSTATUS_CACHE_SPILL:
       op = SQLITE_DBSTATUS_CACHE_WRITE+1;
-      /* Fall through into the next case */
+      /* no break */ deliberate_fall_through
     case SQLITE_DBSTATUS_CACHE_HIT:
     case SQLITE_DBSTATUS_CACHE_MISS:
     case SQLITE_DBSTATUS_CACHE_WRITE:{
@@ -21136,7 +21865,7 @@ SQLITE_API int sqlite3_db_status(
 **
 *************************************************************************
 ** This file contains the C functions that implement date and time
-** functions for SQLite.  
+** functions for SQLite.
 **
 ** There is only one exported symbol in this file - the function
 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
@@ -21145,7 +21874,7 @@ SQLITE_API int sqlite3_db_status(
 ** SQLite processes all times and dates as julian day numbers.  The
 ** dates and times are stored as the number of days since noon
 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
-** calendar system. 
+** calendar system.
 **
 ** 1970-01-01 00:00:00 is JD 2440587.5
 ** 2000-01-01 00:00:00 is JD 2451544.5
@@ -21493,7 +22222,7 @@ static void setRawDateNumber(DateTime *p, double r){
 ** The following are acceptable forms for the input string:
 **
 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
-**      DDDD.DD 
+**      DDDD.DD
 **      now
 **
 ** In the first form, the +/-HH:MM is always optional.  The fractional
@@ -21503,8 +22232,8 @@ static void setRawDateNumber(DateTime *p, double r){
 ** as there is a year and date.
 */
 static int parseDateOrTime(
-  sqlite3_context *context, 
-  const char *zDate, 
+  sqlite3_context *context,
+  const char *zDate,
   DateTime *p
 ){
   double r;
@@ -21525,7 +22254,7 @@ static int parseDateOrTime(
 ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
 ** for DateTime.iJD.
 **
-** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with 
+** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
 ** such a large integer literal, so we have to encode it.
 */
 #define INT_464269060799999  ((((i64)0x1a640)<<32)|0x1072fdff)
@@ -21607,14 +22336,14 @@ static void clearYMD_HMS_TZ(DateTime *p){
 #ifndef SQLITE_OMIT_LOCALTIME
 /*
 ** On recent Windows platforms, the localtime_s() function is available
-** as part of the "Secure CRT". It is essentially equivalent to 
-** localtime_r() available under most POSIX platforms, except that the 
+** as part of the "Secure CRT". It is essentially equivalent to
+** localtime_r() available under most POSIX platforms, except that the
 ** order of the parameters is reversed.
 **
 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
 **
 ** If the user has not indicated to use localtime_r() or localtime_s()
-** already, check for an MSVC build environment that provides 
+** already, check for an MSVC build environment that provides
 ** localtime_s().
 */
 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
@@ -21641,7 +22370,7 @@ static int osLocaltime(time_t *t, struct tm *pTm){
 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
   struct tm *pX;
 #if SQLITE_THREADSAFE>0
-  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
   sqlite3_mutex_enter(mutex);
   pX = localtime(t);
@@ -21670,7 +22399,7 @@ static int osLocaltime(time_t *t, struct tm *pTm){
 /*
 ** Compute the difference (in milliseconds) between localtime and UTC
 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
-** return this value and set *pRc to SQLITE_OK. 
+** return this value and set *pRc to SQLITE_OK.
 **
 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
 ** is undefined in this case.
@@ -21758,12 +22487,12 @@ static const struct {
   double rLimit;      /* Maximum NNN value for this transform */
   double rXform;      /* Constant used for this transform */
 } aXformType[] = {
-  { 0, 6, "second", 464269060800.0, 1000.0                      },
-  { 0, 6, "minute", 7737817680.0,   60000.0                     },
-  { 0, 4, "hour",   128963628.0,    3600000.0                   },
-  { 0, 3, "day",    5373485.0,      86400000.0                  },
-  { 1, 5, "month",  176546.0,       2592000000.0                },
-  { 2, 4, "year",   14713.0,        31536000000.0               },
+  { 0, 6, "second", 464269060800.0, 1000.0         },
+  { 0, 6, "minute", 7737817680.0,   60000.0        },
+  { 0, 4, "hour",   128963628.0,    3600000.0      },
+  { 0, 3, "day",    5373485.0,      86400000.0     },
+  { 1, 5, "month",  176546.0,       2592000000.0   },
+  { 2, 4, "year",   14713.0,        31536000000.0  },
 };
 
 /*
@@ -21825,7 +22554,7 @@ static int parseModifier(
         r = p->s*1000.0 + 210866760000000.0;
         if( r>=0.0 && r<464269060800000.0 ){
           clearYMD_HMS_TZ(p);
-          p->iJD = (sqlite3_int64)r;
+          p->iJD = (sqlite3_int64)(r + 0.5);
           p->validJD = 1;
           p->rawS = 0;
           rc = 0;
@@ -22008,9 +22737,9 @@ static int parseModifier(
 ** then assume a default value of "now" for argv[0].
 */
 static int isDate(
-  sqlite3_context *context, 
-  int argc, 
-  sqlite3_value **argv, 
+  sqlite3_context *context,
+  int argc,
+  sqlite3_value **argv,
   DateTime *p
 ){
   int i, n;
@@ -22249,8 +22978,8 @@ static void strftimeFunc(
         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
         case 's': {
-          sqlite3_snprintf(30,&z[j],"%lld",
-                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
+          i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
+          sqlite3Int64ToText(iS, &z[j]);
           j += sqlite3Strlen30(&z[j]);
           break;
         }
@@ -22348,10 +23077,10 @@ static void currentTimeFunc(
 #if HAVE_GMTIME_R
   pTm = gmtime_r(&t, &sNow);
 #else
-  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
+  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
   pTm = gmtime(&t);
   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
-  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
+  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
 #endif
   if( pTm ){
     strftime(zBuf, 20, zFormat, &sNow);
@@ -22604,7 +23333,7 @@ SQLITE_PRIVATE int sqlite3OsOpen(
   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   ** reaching the VFS. */
-  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
+  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
   assert( rc==SQLITE_OK || pFile->pMethods==0 );
   return rc;
 }
@@ -22655,7 +23384,7 @@ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufO
   }else{
     return pVfs->xRandomness(pVfs, nByte, zBufOut);
   }
-  
+
 }
 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
   return pVfs->xSleep(pVfs, nMicro);
@@ -22742,7 +23471,7 @@ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
   if( rc ) return 0;
 #endif
 #if SQLITE_THREADSAFE
-  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
   sqlite3_mutex_enter(mutex);
   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
@@ -22757,7 +23486,7 @@ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
 ** Unlink a VFS from the linked list
 */
 static void vfsUnlink(sqlite3_vfs *pVfs){
-  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
+  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) );
   if( pVfs==0 ){
     /* No-op */
   }else if( vfsList==pVfs ){
@@ -22788,7 +23517,7 @@ SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
   if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
 #endif
 
-  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
+  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
   sqlite3_mutex_enter(mutex);
   vfsUnlink(pVfs);
   if( makeDflt || vfsList==0 ){
@@ -22812,7 +23541,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
   int rc = sqlite3_initialize();
   if( rc ) return rc;
 #endif
-  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
+  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
   sqlite3_mutex_enter(mutex);
   vfsUnlink(pVfs);
   sqlite3_mutex_leave(mutex);
@@ -22833,17 +23562,17 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
 **
 *************************************************************************
 **
-** This file contains code to support the concept of "benign" 
+** This file contains code to support the concept of "benign"
 ** malloc failures (when the xMalloc() or xRealloc() method of the
 ** sqlite3_mem_methods structure fails to allocate a block of memory
-** and returns 0). 
+** and returns 0).
 **
 ** Most malloc failures are non-benign. After they occur, SQLite
 ** abandons the current operation and returns an error code (usually
 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
-** fatal. For example, if a malloc fails while resizing a hash table, this 
-** is completely recoverable simply by not carrying out the resize. The 
-** hash table will continue to function normally.  So a malloc failure 
+** fatal. For example, if a malloc fails while resizing a hash table, this
+** is completely recoverable simply by not carrying out the resize. The
+** hash table will continue to function normally.  So a malloc failure
 ** during a hash table resize is a benign fault.
 */
 
@@ -23045,7 +23774,7 @@ static malloc_zone_t* _sqliteZone_;
 #else /* if not __APPLE__ */
 
 /*
-** Use standard C library malloc and free on non-Apple systems.  
+** Use standard C library malloc and free on non-Apple systems.
 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
 */
 #define SQLITE_MALLOC(x)             malloc(x)
@@ -23228,7 +23957,7 @@ static int sqlite3MemInit(void *NotUsed){
     /* defer MT decisions to system malloc */
     _sqliteZone_ = malloc_default_zone();
   }else{
-    /* only 1 core, use our own zone to contention over global locks, 
+    /* only 1 core, use our own zone to contention over global locks,
     ** e.g. we have our own dedicated locks */
     _sqliteZone_ = malloc_create_zone(4096, 0);
     malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
@@ -23352,7 +24081,7 @@ struct MemBlockHdr {
 ** when this module is combined with other in the amalgamation.
 */
 static struct {
-  
+
   /*
   ** Mutex to control access to the memory allocation subsystem.
   */
@@ -23363,7 +24092,7 @@ static struct {
   */
   struct MemBlockHdr *pFirst;
   struct MemBlockHdr *pLast;
-  
+
   /*
   ** The number of levels of backtrace to save in new allocations.
   */
@@ -23376,7 +24105,7 @@ static struct {
   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
   char zTitle[100];  /* The title text */
 
-  /* 
+  /*
   ** sqlite3MallocDisallow() increments the following counter.
   ** sqlite3MallocAllow() decrements it.
   */
@@ -23438,7 +24167,7 @@ static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
   pU8 = (u8*)pAllocation;
   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
   /* This checks any of the "extra" bytes allocated due
-  ** to rounding up to an 8 byte boundary to ensure 
+  ** to rounding up to an 8 byte boundary to ensure
   ** they haven't been overwritten.
   */
   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
@@ -23568,7 +24297,7 @@ static void *sqlite3MemMalloc(size_t nByte){
     p = (void*)pInt;
   }
   sqlite3_mutex_leave(mem.mutex);
-  return p; 
+  return p;
 }
 
 /*
@@ -23578,7 +24307,7 @@ static void sqlite3MemFree(void *pPrior){
   struct MemBlockHdr *pHdr;
   void **pBt;
   char *z;
-  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
+  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
        || mem.mutex!=0 );
   pHdr = sqlite3MemsysGetHeader(pPrior);
   pBt = (void**)pHdr;
@@ -23604,15 +24333,15 @@ static void sqlite3MemFree(void *pPrior){
   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
   free(z);
-  sqlite3_mutex_leave(mem.mutex);  
+  sqlite3_mutex_leave(mem.mutex);
 }
 
 /*
 ** Change the size of an existing memory allocation.
 **
 ** For this debugging implementation, we *always* make a copy of the
-** allocation into a new place in memory.  In this way, if the 
-** higher level code is using pointer to the old allocation, it is 
+** allocation into a new place in memory.  In this way, if the
+** higher level code is using pointer to the old allocation, it is
 ** much more likely to break and we are much more liking to find
 ** the error.
 */
@@ -23655,7 +24384,7 @@ SQLITE_PRIVATE void sqlite3MemSetDefault(void){
 ** Set the "type" of an allocation.
 */
 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
-  if( p && sqlite3GlobalConfig.m2.xMalloc==sqlite3MemMalloc ){
+  if( p && sqlite3GlobalConfig.m2.xFree==sqlite3MemFree ){
     struct MemBlockHdr *pHdr;
     pHdr = sqlite3MemsysGetHeader(p);
     assert( pHdr->iForeGuard==FOREGUARD );
@@ -23674,7 +24403,7 @@ SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
 */
 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
   int rc = 1;
-  if( p && sqlite3GlobalConfig.m2.xMalloc==sqlite3MemMalloc ){
+  if( p && sqlite3GlobalConfig.m2.xFree==sqlite3MemFree ){
     struct MemBlockHdr *pHdr;
     pHdr = sqlite3MemsysGetHeader(p);
     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
@@ -23696,7 +24425,7 @@ SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
 */
 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
   int rc = 1;
-  if( p && sqlite3GlobalConfig.m2.xMalloc==sqlite3MemMalloc ){
+  if( p && sqlite3GlobalConfig.m2.xFree==sqlite3MemFree ){
     struct MemBlockHdr *pHdr;
     pHdr = sqlite3MemsysGetHeader(p);
     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
@@ -23746,7 +24475,7 @@ SQLITE_PRIVATE void sqlite3MemdebugSync(){
 }
 
 /*
-** Open the file indicated and write a log of all unfreed memory 
+** Open the file indicated and write a log of all unfreed memory
 ** allocations into that log.
 */
 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
@@ -23763,7 +24492,7 @@ SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
     char *z = (char*)pHdr;
     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
-    fprintf(out, "**** %llu bytes at %p from %s ****\n", 
+    fprintf(out, "**** %llu bytes at %p from %s ****\n",
             (u64)pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
     if( pHdr->nBacktrace ){
       fflush(out);
@@ -23776,7 +24505,7 @@ SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
   fprintf(out, "COUNTS:\n");
   for(i=0; i<NCSIZE-1; i++){
     if( mem.nAlloc[i] ){
-      fprintf(out, "   %5d: %10d %10d %10d\n", 
+      fprintf(out, "   %5d: %10d %10d %10d\n",
             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
     }
   }
@@ -23817,12 +24546,12 @@ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 **
 *************************************************************************
 ** This file contains the C functions that implement a memory
-** allocation subsystem for use by SQLite. 
+** allocation subsystem for use by SQLite.
 **
 ** This version of the memory allocation subsystem omits all
 ** use of malloc(). The SQLite user supplies a block of memory
 ** before calling sqlite3_initialize() from which allocations
-** are made and returned by the xMalloc() and xRealloc() 
+** are made and returned by the xMalloc() and xRealloc()
 ** implementations. Once sqlite3_initialize() has been called,
 ** the amount of memory available to SQLite is fixed and cannot
 ** be changed.
@@ -23853,8 +24582,8 @@ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 #define N_HASH  61
 
 /*
-** A memory allocation (also called a "chunk") consists of two or 
-** more blocks where each block is 8 bytes.  The first 8 bytes are 
+** A memory allocation (also called a "chunk") consists of two or
+** more blocks where each block is 8 bytes.  The first 8 bytes are
 ** a header that is not returned to the user.
 **
 ** A chunk is two or more blocks that is either checked out or
@@ -23877,10 +24606,10 @@ SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
 **
 ** The second block of free chunks is of the form u.list.  The
 ** two fields form a double-linked list of chunks of related sizes.
-** Pointers to the head of the list are stored in mem3.aiSmall[] 
+** Pointers to the head of the list are stored in mem3.aiSmall[]
 ** for smaller chunks and mem3.aiHash[] for larger chunks.
 **
-** The second block of a chunk is user data if the chunk is checked 
+** The second block of a chunk is user data if the chunk is checked
 ** out.  If a chunk is checked out, the user data may extend into
 ** the u.hdr.prevSize value of the following chunk.
 */
@@ -23916,28 +24645,28 @@ static SQLITE_WSD struct Mem3Global {
   ** True if we are evaluating an out-of-memory callback.
   */
   int alarmBusy;
-  
+
   /*
   ** Mutex to control access to the memory allocation subsystem.
   */
   sqlite3_mutex *mutex;
-  
+
   /*
   ** The minimum amount of free space that we have seen.
   */
-  u32 mnMaster;
+  u32 mnKeyBlk;
 
   /*
-  ** iMaster is the index of the master chunk.  Most new allocations
-  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
-  ** of the current master.  iMaster is 0 if there is not master chunk.
-  ** The master chunk is not in either the aiHash[] or aiSmall[].
+  ** iKeyBlk is the index of the key chunk.  Most new allocations
+  ** occur off of this chunk.  szKeyBlk is the size (in Mem3Blocks)
+  ** of the current key chunk.  iKeyBlk is 0 if there is no key chunk.
+  ** The key chunk is not in either the aiHash[] or aiSmall[].
   */
-  u32 iMaster;
-  u32 szMaster;
+  u32 iKeyBlk;
+  u32 szKeyBlk;
 
   /*
-  ** Array of lists of free blocks according to the block size 
+  ** Array of lists of free blocks according to the block size
   ** for smaller chunks, or a hash on the block size for larger
   ** chunks.
   */
@@ -23968,7 +24697,7 @@ static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
 }
 
 /*
-** Unlink the chunk at index i from 
+** Unlink the chunk at index i from
 ** whatever list is currently a member of.
 */
 static void memsys3Unlink(u32 i){
@@ -24054,8 +24783,8 @@ static void memsys3OutOfMemory(size_t nByte){
 
 
 /*
-** Chunk i is a free chunk that has been unlinked.  Adjust its 
-** size parameters for check-out and return a pointer to the 
+** Chunk i is a free chunk that has been unlinked.  Adjust its
+** size parameters for check-out and return a pointer to the
 ** user portion of the chunk.
 */
 static void *memsys3Checkout(u32 i, u32 nBlock){
@@ -24072,34 +24801,34 @@ static void *memsys3Checkout(u32 i, u32 nBlock){
 }
 
 /*
-** Carve a piece off of the end of the mem3.iMaster free chunk.
-** Return a pointer to the new allocation.  Or, if the master chunk
+** Carve a piece off of the end of the mem3.iKeyBlk free chunk.
+** Return a pointer to the new allocation.  Or, if the key chunk
 ** is not large enough, return 0.
 */
-static void *memsys3FromMaster(u32 nBlock){
+static void *memsys3FromKeyBlk(u32 nBlock){
   assert( sqlite3_mutex_held(mem3.mutex) );
-  assert( mem3.szMaster>=nBlock );
-  if( nBlock>=mem3.szMaster-1 ){
-    /* Use the entire master */
-    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
-    mem3.iMaster = 0;
-    mem3.szMaster = 0;
-    mem3.mnMaster = 0;
+  assert( mem3.szKeyBlk>=nBlock );
+  if( nBlock>=mem3.szKeyBlk-1 ){
+    /* Use the entire key chunk */
+    void *p = memsys3Checkout(mem3.iKeyBlk, mem3.szKeyBlk);
+    mem3.iKeyBlk = 0;
+    mem3.szKeyBlk = 0;
+    mem3.mnKeyBlk = 0;
     return p;
   }else{
-    /* Split the master block.  Return the tail. */
+    /* Split the key block.  Return the tail. */
     u32 newi, x;
-    newi = mem3.iMaster + mem3.szMaster - nBlock;
-    assert( newi > mem3.iMaster+1 );
-    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
-    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
+    newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock;
+    assert( newi > mem3.iKeyBlk+1 );
+    mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock;
+    mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2;
     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
-    mem3.szMaster -= nBlock;
-    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
-    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
-    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
-    if( mem3.szMaster < mem3.mnMaster ){
-      mem3.mnMaster = mem3.szMaster;
+    mem3.szKeyBlk -= nBlock;
+    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk;
+    x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+    mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+    if( mem3.szKeyBlk < mem3.mnKeyBlk ){
+      mem3.mnKeyBlk = mem3.szKeyBlk;
     }
     return (void*)&mem3.aPool[newi];
   }
@@ -24108,18 +24837,18 @@ static void *memsys3FromMaster(u32 nBlock){
 /*
 ** *pRoot is the head of a list of free chunks of the same size
 ** or same size hash.  In other words, *pRoot is an entry in either
-** mem3.aiSmall[] or mem3.aiHash[].  
+** mem3.aiSmall[] or mem3.aiHash[].
 **
 ** This routine examines all entries on the given list and tries
-** to coalesce each entries with adjacent free chunks.  
+** to coalesce each entries with adjacent free chunks.
 **
-** If it sees a chunk that is larger than mem3.iMaster, it replaces 
-** the current mem3.iMaster with the new larger chunk.  In order for
-** this mem3.iMaster replacement to work, the master chunk must be
+** If it sees a chunk that is larger than mem3.iKeyBlk, it replaces
+** the current mem3.iKeyBlk with the new larger chunk.  In order for
+** this mem3.iKeyBlk replacement to work, the key chunk must be
 ** linked into the hash tables.  That is not the normal state of
-** affairs, of course.  The calling routine must link the master
+** affairs, of course.  The calling routine must link the key
 ** chunk before invoking this routine, then must unlink the (possibly
-** changed) master chunk once this routine has finished.
+** changed) key chunk once this routine has finished.
 */
 static void memsys3Merge(u32 *pRoot){
   u32 iNext, prev, size, i, x;
@@ -24146,9 +24875,9 @@ static void memsys3Merge(u32 *pRoot){
     }else{
       size /= 4;
     }
-    if( size>mem3.szMaster ){
-      mem3.iMaster = i;
-      mem3.szMaster = size;
+    if( size>mem3.szKeyBlk ){
+      mem3.iKeyBlk = i;
+      mem3.szKeyBlk = size;
     }
   }
 }
@@ -24197,26 +24926,26 @@ static void *memsys3MallocUnsafe(size_t nByte){
 
   /* STEP 2:
   ** Try to satisfy the allocation by carving a piece off of the end
-  ** of the master chunk.  This step usually works if step 1 fails.
+  ** of the key chunk.  This step usually works if step 1 fails.
   */
-  if( mem3.szMaster>=nBlock ){
-    return memsys3FromMaster(nBlock);
+  if( mem3.szKeyBlk>=nBlock ){
+    return memsys3FromKeyBlk(nBlock);
   }
 
 
-  /* STEP 3:  
+  /* STEP 3:
   ** Loop through the entire memory pool.  Coalesce adjacent free
-  ** chunks.  Recompute the master chunk as the largest free chunk.
+  ** chunks.  Recompute the key chunk as the largest free chunk.
   ** Then try again to satisfy the allocation by carving a piece off
-  ** of the end of the master chunk.  This step happens very
+  ** of the end of the key chunk.  This step happens very
   ** rarely (we hope!)
   */
   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
     memsys3OutOfMemory(toFree);
-    if( mem3.iMaster ){
-      memsys3Link(mem3.iMaster);
-      mem3.iMaster = 0;
-      mem3.szMaster = 0;
+    if( mem3.iKeyBlk ){
+      memsys3Link(mem3.iKeyBlk);
+      mem3.iKeyBlk = 0;
+      mem3.szKeyBlk = 0;
     }
     for(i=0; i<N_HASH; i++){
       memsys3Merge(&mem3.aiHash[i]);
@@ -24224,10 +24953,10 @@ static void *memsys3MallocUnsafe(size_t nByte){
     for(i=0; i<MX_SMALL-1; i++){
       memsys3Merge(&mem3.aiSmall[i]);
     }
-    if( mem3.szMaster ){
-      memsys3Unlink(mem3.iMaster);
-      if( mem3.szMaster>=nBlock ){
-        return memsys3FromMaster(nBlock);
+    if( mem3.szKeyBlk ){
+      memsys3Unlink(mem3.iKeyBlk);
+      if( mem3.szKeyBlk>=nBlock ){
+        return memsys3FromKeyBlk(nBlock);
       }
     }
   }
@@ -24257,23 +24986,23 @@ static void memsys3FreeUnsafe(void *pOld){
   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
   memsys3Link(i);
 
-  /* Try to expand the master using the newly freed chunk */
-  if( mem3.iMaster ){
-    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
-      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
-      mem3.iMaster -= size;
-      mem3.szMaster += size;
-      memsys3Unlink(mem3.iMaster);
-      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
-      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
-      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
+  /* Try to expand the key using the newly freed chunk */
+  if( mem3.iKeyBlk ){
+    while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){
+      size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize;
+      mem3.iKeyBlk -= size;
+      mem3.szKeyBlk += size;
+      memsys3Unlink(mem3.iKeyBlk);
+      x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+      mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+      mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
     }
-    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
-    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
-      memsys3Unlink(mem3.iMaster+mem3.szMaster);
-      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
-      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
-      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
+    x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
+    while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){
+      memsys3Unlink(mem3.iKeyBlk+mem3.szKeyBlk);
+      mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4;
+      mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
+      mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
     }
   }
 }
@@ -24311,7 +25040,7 @@ static void *memsys3Malloc(size_t nBytes){
   memsys3Enter();
   p = memsys3MallocUnsafe(nBytes);
   memsys3Leave();
-  return (void*)p; 
+  return (void*)p;
 }
 
 /*
@@ -24369,11 +25098,11 @@ static int memsys3Init(void *NotUsed){
   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
 
-  /* Initialize the master block. */
-  mem3.szMaster = mem3.nPool;
-  mem3.mnMaster = mem3.szMaster;
-  mem3.iMaster = 1;
-  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
+  /* Initialize the key block. */
+  mem3.szKeyBlk = mem3.nPool;
+  mem3.mnKeyBlk = mem3.szKeyBlk;
+  mem3.iKeyBlk = 1;
+  mem3.aPool[0].u.hdr.size4x = (mem3.szKeyBlk<<2) + 2;
   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
 
@@ -24392,7 +25121,7 @@ static void memsys3Shutdown(void *NotUsed){
 
 
 /*
-** Open the file indicated and write a log of all unfreed memory 
+** Open the file indicated and write a log of all unfreed memory
 ** allocations into that log.
 */
 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
@@ -24433,7 +25162,7 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
     }else{
       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
-                  i==mem3.iMaster ? " **master**" : "");
+                  i==mem3.iKeyBlk ? " **key**" : "");
     }
   }
   for(i=0; i<MX_SMALL-1; i++){
@@ -24443,7 +25172,7 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
       fprintf(out, " %p(%d)", &mem3.aPool[j],
               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
     }
-    fprintf(out, "\n"); 
+    fprintf(out, "\n");
   }
   for(i=0; i<N_HASH; i++){
     if( mem3.aiHash[i]==0 ) continue;
@@ -24452,11 +25181,11 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
       fprintf(out, " %p(%d)", &mem3.aPool[j],
               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
     }
-    fprintf(out, "\n"); 
+    fprintf(out, "\n");
   }
-  fprintf(out, "master=%d\n", mem3.iMaster);
-  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
-  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
+  fprintf(out, "key=%d\n", mem3.iKeyBlk);
+  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8);
+  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8);
   sqlite3_mutex_leave(mem3.mutex);
   if( out==stdout ){
     fflush(stdout);
@@ -24467,7 +25196,7 @@ SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
 #endif
 
 /*
-** This routine is the only routine in this file with external 
+** This routine is the only routine in this file with external
 ** linkage.
 **
 ** Populate the low-level memory allocation function pointers in
@@ -24507,12 +25236,12 @@ SQLITE_PRIVATE const sqlite3_mem_methods2 *sqlite3MemGetMemsys3(void){
 **
 *************************************************************************
 ** This file contains the C functions that implement a memory
-** allocation subsystem for use by SQLite. 
+** allocation subsystem for use by SQLite.
 **
 ** This version of the memory allocation subsystem omits all
 ** use of malloc(). The application gives SQLite a block of memory
 ** before calling sqlite3_initialize() from which allocations
-** are made and returned by the xMalloc() and xRealloc() 
+** are made and returned by the xMalloc() and xRealloc()
 ** implementations. Once sqlite3_initialize() has been called,
 ** the amount of memory available to SQLite is fixed and cannot
 ** be changed.
@@ -24532,12 +25261,12 @@ SQLITE_PRIVATE const sqlite3_mem_methods2 *sqlite3MemGetMemsys3(void){
 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
 ** Concerning Dynamic Storage Allocation". Journal of the Association for
 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
-** 
+**
 ** Let n be the size of the largest allocation divided by the minimum
 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
 ** be the maximum amount of memory ever outstanding at one time.  Let
 ** N be the total amount of memory available for allocation.  Robson
-** proved that this memory allocator will never breakdown due to 
+** proved that this memory allocator will never breakdown due to
 ** fragmentation as long as the following constraint holds:
 **
 **      N >=  M*(1 + log2(n)/2) - n + 1
@@ -24548,7 +25277,7 @@ SQLITE_PRIVATE const sqlite3_mem_methods2 *sqlite3MemGetMemsys3(void){
 /* #include "sqliteInt.h" */
 
 /*
-** This version of the memory allocator is used only when 
+** This version of the memory allocator is used only when
 ** SQLITE_ENABLE_MEMSYS5 is defined.
 */
 #ifdef SQLITE_ENABLE_MEMSYS5
@@ -24593,7 +25322,7 @@ static SQLITE_WSD struct Mem5Global {
   int szAtom;      /* Smallest possible allocation in bytes */
   int nBlock;      /* Number of szAtom sized blocks in zPool */
   u8 *zPool;       /* Memory available to be allocated */
-  
+
   /*
   ** Mutex to control access to the memory allocation subsystem.
   */
@@ -24612,7 +25341,7 @@ static SQLITE_WSD struct Mem5Global {
   u32 maxCount;       /* Maximum instantaneous currentCount */
   size_t maxRequest;  /* Largest allocation (exclusive of internal frag) */
 #endif
-  
+
   /*
   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
@@ -24791,7 +25520,7 @@ static void memsys5FreeUnsafe(void *pOld){
   u32 size, iLogsize;
   int iBlock;
 
-  /* Set iBlock to the index of the block pointed to by pOld in 
+  /* Set iBlock to the index of the block pointed to by pOld in
   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
   */
   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
@@ -24860,7 +25589,7 @@ static void *memsys5Malloc(size_t nBytes){
     p = memsys5MallocUnsafe(nBytes);
     memsys5Leave();
   }
-  return (void*)p; 
+  return (void*)p;
 }
 
 /*
@@ -24873,14 +25602,14 @@ static void memsys5Free(void *pPrior){
   assert( pPrior!=0 );
   memsys5Enter();
   memsys5FreeUnsafe(pPrior);
-  memsys5Leave();  
+  memsys5Leave();
 }
 
 /*
 ** Change the size of an existing memory allocation.
 **
 ** The outer layer memory allocator prevents this routine from
-** being called with pPrior==0.  
+** being called with pPrior==0.
 **
 ** nBytes is always a value obtained from a prior call to
 ** memsys5Round().  Hence nBytes is always a non-negative power
@@ -25012,7 +25741,7 @@ static void memsys5Shutdown(void *NotUsed){
 
 #ifdef SQLITE_TEST
 /*
-** Open the file indicated and write a log of all unfreed memory 
+** Open the file indicated and write a log of all unfreed memory
 ** allocations into that log.
 */
 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
@@ -25054,7 +25783,7 @@ SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
 #endif
 
 /*
-** This routine is the only routine in this file with external 
+** This routine is the only routine in this file with external
 ** linkage. It returns a pointer to a static sqlite3_mem_methods
 ** struct populated with the memsys5 methods.
 */
@@ -25109,7 +25838,7 @@ static SQLITE_WSD int mutexIsInit = 0;
 /*
 ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
 ** the implementation of a wrapper around the system default mutex
-** implementation (sqlite3DefaultMutex()). 
+** implementation (sqlite3DefaultMutex()).
 **
 ** Most calls are passed directly through to the underlying default
 ** mutex implementation. Except, if a mutex is configured by calling
@@ -25120,7 +25849,7 @@ static SQLITE_WSD int mutexIsInit = 0;
 ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
 */
 
-/* 
+/*
 ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
 ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
 ** allocated by the system mutex implementation. Variable iType is usually set
@@ -25137,9 +25866,9 @@ struct CheckMutex {
 
 #define SQLITE_MUTEX_WARNONCONTENTION  (-1)
 
-/* 
+/*
 ** Pointer to real mutex methods object used by the CheckMutex
-** implementation. Set by checkMutexInit(). 
+** implementation. Set by checkMutexInit().
 */
 static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
 
@@ -25155,13 +25884,13 @@ static int checkMutexNotheld(sqlite3_mutex *p){
 /*
 ** Initialize and deinitialize the mutex subsystem.
 */
-static int checkMutexInit(void){ 
+static int checkMutexInit(void){
   pGlobalMutexMethods = sqlite3DefaultMutex();
-  return SQLITE_OK; 
+  return SQLITE_OK;
 }
-static int checkMutexEnd(void){ 
+static int checkMutexEnd(void){
   pGlobalMutexMethods = 0;
-  return SQLITE_OK; 
+  return SQLITE_OK;
 }
 
 /*
@@ -25235,7 +25964,7 @@ static void checkMutexEnter(sqlite3_mutex *p){
     if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
       return;
     }
-    sqlite3_log(SQLITE_MISUSE, 
+    sqlite3_log(SQLITE_MISUSE,
         "illegal multi-threaded access to database connection"
     );
   }
@@ -25294,11 +26023,11 @@ SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
 /*
 ** Initialize the mutex system.
 */
-SQLITE_PRIVATE int sqlite3MutexInit(void){ 
+SQLITE_PRIVATE int sqlite3MutexInit(void){
   int rc = SQLITE_OK;
   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
     /* If the xMutexAlloc method has not been set, then the user did not
-    ** install a mutex implementation via sqlite3_config() prior to 
+    ** install a mutex implementation via sqlite3_config() prior to
     ** sqlite3_initialize() being called. This block copies pointers to
     ** the default implementation into the sqlite3GlobalConfig structure.
     */
@@ -25332,6 +26061,7 @@ SQLITE_PRIVATE int sqlite3MutexInit(void){
   GLOBAL(int, mutexIsInit) = 1;
 #endif
 
+  sqlite3MemoryBarrier();
   return rc;
 }
 
@@ -25409,7 +26139,7 @@ SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
 
 /*
 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
-** entered by the same thread.  The behavior is undefined if the mutex 
+** entered by the same thread.  The behavior is undefined if the mutex
 ** is not currently entered. If a NULL pointer is passed as an argument
 ** this function is a no-op.
 */
@@ -25478,9 +26208,9 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
 */
 static int noopMutexInit(void){ return SQLITE_OK; }
 static int noopMutexEnd(void){ return SQLITE_OK; }
-static sqlite3_mutex *noopMutexAlloc(int id){ 
+static sqlite3_mutex *noopMutexAlloc(int id){
   UNUSED_PARAMETER(id);
-  return (sqlite3_mutex*)8; 
+  return (sqlite3_mutex*)8;
 }
 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
@@ -25545,7 +26275,7 @@ static int debugMutexEnd(void){ return SQLITE_OK; }
 /*
 ** The sqlite3_mutex_alloc() routine allocates a new
 ** mutex and returns a pointer to it.  If it returns NULL
-** that means that a mutex could not be allocated. 
+** that means that a mutex could not be allocated.
 */
 static sqlite3_mutex *debugMutexAlloc(int id){
   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
@@ -25723,7 +26453,7 @@ struct sqlite3_mutex {
 ** there might be race conditions that can cause these routines to
 ** deliver incorrect results.  In particular, if pthread_equal() is
 ** not an atomic operation, then these routines might delivery
-** incorrect results.  On most platforms, pthread_equal() is a 
+** incorrect results.  On most platforms, pthread_equal() is a
 ** comparison of two integers and is therefore atomic.  But we are
 ** told that HPUX is not such a platform.  If so, then these routines
 ** will not always work correctly on HPUX.
@@ -25771,7 +26501,7 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; }
 ** <ul>
 ** <li>  SQLITE_MUTEX_FAST
 ** <li>  SQLITE_MUTEX_RECURSIVE
-** <li>  SQLITE_MUTEX_STATIC_MASTER
+** <li>  SQLITE_MUTEX_STATIC_MAIN
 ** <li>  SQLITE_MUTEX_STATIC_MEM
 ** <li>  SQLITE_MUTEX_STATIC_OPEN
 ** <li>  SQLITE_MUTEX_STATIC_PRNG
@@ -25805,7 +26535,7 @@ static int pthreadMutexEnd(void){ return SQLITE_OK; }
 **
 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
-** returns a different mutex on every call.  But for the static 
+** returns a different mutex on every call.  But for the static
 ** mutex types, the same mutex is returned on every call that has
 ** the same type number.
 */
@@ -25916,7 +26646,7 @@ static void pthreadMutexEnter(sqlite3_mutex *p){
   ** is atomic - that it cannot be deceived into thinking self
   ** and p->owner are equal if p->owner changes between two values
   ** that are not equal to self while the comparison is taking place.
-  ** This implementation also assumes a coherent cache - that 
+  ** This implementation also assumes a coherent cache - that
   ** separate processes cannot read different values from the same
   ** address at the same time.  If either of these two conditions
   ** are not met, then the mutexes will fail and problems will result.
@@ -25959,7 +26689,7 @@ static int pthreadMutexTry(sqlite3_mutex *p){
   ** is atomic - that it cannot be deceived into thinking self
   ** and p->owner are equal if p->owner changes between two values
   ** that are not equal to self while the comparison is taking place.
-  ** This implementation also assumes a coherent cache - that 
+  ** This implementation also assumes a coherent cache - that
   ** separate processes cannot read different values from the same
   ** address at the same time.  If either of these two conditions
   ** are not met, then the mutexes will fail and problems will result.
@@ -26131,7 +26861,7 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 ******************************************************************************
 **
 ** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 class CPUs.
+** counters for x86 and x86_64 class CPUs.
 */
 #ifndef SQLITE_HWTIME_H
 #define SQLITE_HWTIME_H
@@ -26142,8 +26872,9 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 ** processor and returns that value.  This can be used for high-res
 ** profiling.
 */
-#if (defined(__GNUC__) || defined(_MSC_VER)) && \
-      (defined(i386) || defined(__i386__) || defined(_M_IX86))
+#if !defined(__STRICT_ANSI__) && \
+    (defined(__GNUC__) || defined(_MSC_VER)) && \
+    (defined(i386) || defined(__i386__) || defined(_M_IX86))
 
   #if defined(__GNUC__)
 
@@ -26164,15 +26895,15 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 
   #endif
 
-#elif (defined(__GNUC__) && defined(__x86_64__))
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long val;
       __asm__ __volatile__ ("rdtsc" : "=A" (val));
       return val;
   }
-#elif (defined(__GNUC__) && defined(__ppc__))
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long long retval;
@@ -26189,14 +26920,13 @@ SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
 
 #else
 
-  #error Need implementation of sqlite3Hwtime() for your platform.
-
   /*
-  ** To compile without implementing sqlite3Hwtime() for your platform,
-  ** you can remove the above #error and use the following
-  ** stub function.  You will lose timing support for many
-  ** of the debugging and testing utilities, but it should at
-  ** least compile and run.
+  ** asm() is needed for hardware timing support.  Without asm(),
+  ** disable the sqlite3Hwtime() routine.
+  **
+  ** sqlite3Hwtime() is only used for some obscure debugging
+  ** and analysis configurations, not in any deliverable, so this
+  ** should not be a great loss.
   */
 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 
@@ -26517,7 +27247,7 @@ static int winMutexEnd(void){
 ** <ul>
 ** <li>  SQLITE_MUTEX_FAST
 ** <li>  SQLITE_MUTEX_RECURSIVE
-** <li>  SQLITE_MUTEX_STATIC_MASTER
+** <li>  SQLITE_MUTEX_STATIC_MAIN
 ** <li>  SQLITE_MUTEX_STATIC_MEM
 ** <li>  SQLITE_MUTEX_STATIC_OPEN
 ** <li>  SQLITE_MUTEX_STATIC_PRNG
@@ -26781,18 +27511,26 @@ SQLITE_API int sqlite3_release_memory(int n){
 }
 
 /*
+** Default value of the hard heap limit.  0 means "no limit".
+*/
+#ifndef SQLITE_MAX_MEMORY
+# define SQLITE_MAX_MEMORY 0
+#endif
+
+/*
 ** State information local to the memory allocation subsystem.
 */
 static SQLITE_WSD struct Mem0Global {
   sqlite3_mutex *mutex;         /* Mutex to serialize access */
   size_t alarmThreshold;        /* The soft heap limit */
+  size_t hardLimit;             /* The hard upper bound on memory */
 
   /*
   ** True if heap is nearly "full" where "full" is defined by the
   ** sqlite3_soft_heap_limit() setting.
   */
   int nearlyFull;
-} mem0 = { 0, 0, 0 };
+} mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
 
 #define mem0 GLOBAL(struct Mem0Global, mem0)
 
@@ -26822,8 +27560,15 @@ SQLITE_API int sqlite3_memory_alarm(
 #endif
 
 /*
-** Set the soft heap-size limit for the library. Passing a zero or 
-** negative value indicates no limit.
+** Set the soft heap-size limit for the library.  An argument of
+** zero disables the limit.  A negative argument is a no-op used to
+** obtain the return value.
+**
+** The return value is the value of the heap limit just before this
+** interface was called.
+**
+** If the hard heap limit is enabled, then the soft heap limit cannot
+** be disabled nor raised above the hard heap limit.
 */
 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   size_t priorLimit;
@@ -26838,9 +27583,12 @@ SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
     sqlite3_mutex_leave(mem0.mutex);
     return priorLimit;
   }
+  if( mem0.hardLimit!=0 && (n>(sqlite3_int64)mem0.hardLimit || n==0) ){
+    n = mem0.hardLimit;
+  }
   mem0.alarmThreshold = n;
   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
-  mem0.nearlyFull = (n>0 && (size_t)n<=nUsed);
+  AtomicStore(&mem0.nearlyFull, n>0 && (size_t)n<=nUsed);
   sqlite3_mutex_leave(mem0.mutex);
 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   if( sqlite3_memory_used() > n ) sqlite3PcacheReleaseMemory(sqlite3_memory_used() - n);
@@ -26856,6 +27604,37 @@ SQLITE_API void sqlite3_soft_heap_limit(int n){
 #endif
 
 /*
+** Set the hard heap-size limit for the library. An argument of zero
+** disables the hard heap limit.  A negative argument is a no-op used
+** to obtain the return value without affecting the hard heap limit.
+**
+** The return value is the value of the hard heap limit just prior to
+** calling this interface.
+**
+** Setting the hard heap limit will also activate the soft heap limit
+** and constrain the soft heap limit to be no more than the hard heap
+** limit.
+*/
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
+  size_t priorLimit;
+#ifndef SQLITE_OMIT_AUTOINIT
+  int rc = sqlite3_initialize();
+  if( rc ) return -1;
+#endif
+  sqlite3_mutex_enter(mem0.mutex);
+  priorLimit = mem0.hardLimit;
+  if( n>=0 ){
+    mem0.hardLimit = n;
+    if( n<(sqlite3_int64)mem0.alarmThreshold || mem0.alarmThreshold==0 ){
+      mem0.alarmThreshold = n;
+    }
+  }
+  sqlite3_mutex_leave(mem0.mutex);
+  return priorLimit;
+}
+
+
+/*
 ** Initialize the memory allocation subsystem.
 */
 SQLITE_PRIVATE int sqlite3MallocInit(void){
@@ -26881,7 +27660,7 @@ SQLITE_PRIVATE int sqlite3MallocInit(void){
 ** sqlite3_soft_heap_limit().
 */
 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
-  return mem0.nearlyFull;
+  return AtomicLoad(&mem0.nearlyFull);
 }
 
 /*
@@ -26915,7 +27694,7 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
 }
 
 /*
-** Trigger the alarm 
+** Trigger the alarm
 */
 static void sqlite3MallocAlarm(size_t nByte){
   if( mem0.alarmThreshold<=0 ) return;
@@ -26943,21 +27722,21 @@ static void mallocWithAlarm(size_t n, void **pp){
   ** following xRoundup() call. */
   nFull = sqlite3GlobalConfig.m2.xRoundup(n);
 
-#ifdef SQLITE_MAX_MEMORY
-  if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
-    *pp = 0;
-    return;
-  }
-#endif
-
   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
   if( mem0.alarmThreshold>0 ){
     size_t nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
     if( (nUsed + nFull >= mem0.alarmThreshold) || (nUsed + nFull < nUsed) ){
-      mem0.nearlyFull = 1;
+      AtomicStore(&mem0.nearlyFull, 1);
       sqlite3MallocAlarm(nFull);
+      if( mem0.hardLimit ){
+        nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
+        if( nUsed >= mem0.hardLimit - nFull ){
+          *pp = 0;
+          return;
+        }
+      }
     }else{
-      mem0.nearlyFull = 0;
+      AtomicStore(&mem0.nearlyFull, 0);
     }
   }
   p = sqlite3GlobalConfig.m2.xMalloc(nFull);
@@ -27044,10 +27823,17 @@ SQLITE_PRIVATE size_t sqlite3MallocSize(void *p){
   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
   return sqlite3GlobalConfig.m2.xSize(p);
 }
+static int lookasideMallocSize(sqlite3 *db, void *p){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+  return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
+#else
+  return db->lookaside.szTrue;
+#endif
+}
 SQLITE_PRIVATE size_t sqlite3DbMallocSize(sqlite3 *db, void *p){
   assert( p!=0 );
-  if( db==0 || !isLookaside(db,p) ){
 #ifdef SQLITE_DEBUG
+  if( db==0 || !isLookaside(db,p) ){
     if( db==0 ){
       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
@@ -27055,12 +27841,23 @@ SQLITE_PRIVATE size_t sqlite3DbMallocSize(sqlite3 *db, void *p){
       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
     }
+  }
 #endif
-    return sqlite3GlobalConfig.m2.xSize(p);
-  }else{
-    assert( sqlite3_mutex_held(db->mutex) );
-    return db->lookaside.sz;
+  if( db ){
+    if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
+        assert( sqlite3_mutex_held(db->mutex) );
+        return LOOKASIDE_SMALL;
+      }
+#endif
+      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
+        assert( sqlite3_mutex_held(db->mutex) );
+        return db->lookaside.szTrue;
+      }
+    }
   }
+  return sqlite3GlobalConfig.m2.xSize(p);
 }
 SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
@@ -27107,15 +27904,27 @@ SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
       measureAllocationSize(db, p);
       return;
     }
-    if( isLookaside(db, p) ){
-      LookasideSlot *pBuf = (LookasideSlot*)p;
+    if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+      if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
+        LookasideSlot *pBuf = (LookasideSlot*)p;
 #ifdef SQLITE_DEBUG
-      /* Trash all content in the buffer being freed */
-      memset(p, 0xaa, db->lookaside.sz);
+        memset(p, 0xaa, LOOKASIDE_SMALL);  /* Trash freed content */
 #endif
-      pBuf->pNext = db->lookaside.pFree;
-      db->lookaside.pFree = pBuf;
-      return;
+        pBuf->pNext = db->lookaside.pSmallFree;
+        db->lookaside.pSmallFree = pBuf;
+        return;
+      }
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+      if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
+        LookasideSlot *pBuf = (LookasideSlot*)p;
+#ifdef SQLITE_DEBUG
+        memset(p, 0xaa, db->lookaside.szTrue);  /* Trash freed content */
+#endif
+        pBuf->pNext = db->lookaside.pFree;
+        db->lookaside.pFree = pBuf;
+        return;
+      }
     }
   }
   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
@@ -27152,17 +27961,24 @@ SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, size_t nBytes){
   if( nOld==nNew ){
     pNew = pOld;
   }else if( sqlite3GlobalConfig.bMemstat ){
+    sqlite3_int64 nUsed;
     sqlite3_mutex_enter(mem0.mutex);
-    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, nBytes);
-    if( nNew > nOld && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew >=
-          mem0.alarmThreshold+nOld ){
+    sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
+    if( nNew > nOld && (nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)) + nNew >=
+          mem0.alarmThreshold + nOld ){
       sqlite3MallocAlarm(nNew - nOld);
+      if( mem0.hardLimit>0 && nUsed + nOld >= mem0.hardLimit - nNew ){
+        sqlite3_mutex_leave(mem0.mutex);
+        return 0;
+      }
     }
     pNew = sqlite3GlobalConfig.m2.xRealloc(pOld, nNew);
+#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
     if( pNew==0 && mem0.alarmThreshold>0 ){
       sqlite3MallocAlarm(nBytes);
       pNew = sqlite3GlobalConfig.m2.xRealloc(pOld, nNew);
     }
+#endif
     if( pNew ){
       nNew = sqlite3MallocSize(pNew);
       sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, nOld);
@@ -27204,7 +28020,7 @@ SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
 
 /*
 ** Allocate and zero memory.
-*/ 
+*/
 SQLITE_PRIVATE void *sqlite3MallocZero(size_t n){
   void *p = sqlite3Malloc(n);
   if( p ){
@@ -27234,13 +28050,13 @@ static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, size_t n){
   assert( db!=0 );
   p = sqlite3Malloc(n);
   if( !p ) sqlite3OomFault(db);
-  sqlite3MemdebugSetType(p, 
+  sqlite3MemdebugSetType(p,
          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
   return p;
 }
 
 /*
-** Allocate memory, either lookaside (if possible) or heap.  
+** Allocate memory, either lookaside (if possible) or heap.
 ** If the allocation fails, set the mallocFailed flag in
 ** the connection pointer.
 **
@@ -27274,23 +28090,37 @@ SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
   assert( db!=0 );
   assert( sqlite3_mutex_held(db->mutex) );
   assert( db->pnBytesFreed==0 );
-  if( db->lookaside.bDisable==0 ){
-    assert( db->mallocFailed==0 );
-    if( n>db->lookaside.sz ){
+  if( n>db->lookaside.sz ){
+    if( !db->lookaside.bDisable ){
       db->lookaside.anStat[1]++;
-    }else if( (pBuf = db->lookaside.pFree)!=0 ){
-      db->lookaside.pFree = pBuf->pNext;
+    }else if( db->mallocFailed ){
+      return 0;
+    }
+    return dbMallocRawFinish(db, n);
+  }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+  if( n<=LOOKASIDE_SMALL ){
+    if( (pBuf = db->lookaside.pSmallFree)!=0 ){
+      db->lookaside.pSmallFree = pBuf->pNext;
       db->lookaside.anStat[0]++;
       return (void*)pBuf;
-    }else if( (pBuf = db->lookaside.pInit)!=0 ){
-      db->lookaside.pInit = pBuf->pNext;
+    }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
+      db->lookaside.pSmallInit = pBuf->pNext;
       db->lookaside.anStat[0]++;
       return (void*)pBuf;
-    }else{
-      db->lookaside.anStat[2]++;
     }
-  }else if( db->mallocFailed ){
-    return 0;
+  }
+#endif
+  if( (pBuf = db->lookaside.pFree)!=0 ){
+    db->lookaside.pFree = pBuf->pNext;
+    db->lookaside.anStat[0]++;
+    return (void*)pBuf;
+  }else if( (pBuf = db->lookaside.pInit)!=0 ){
+    db->lookaside.pInit = pBuf->pNext;
+    db->lookaside.anStat[0]++;
+    return (void*)pBuf;
+  }else{
+    db->lookaside.anStat[2]++;
   }
 #else
   assert( db!=0 );
@@ -27314,7 +28144,16 @@ SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, size_t n){
   assert( db!=0 );
   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
   assert( sqlite3_mutex_held(db->mutex) );
-  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
+  if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+    if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
+      if( n<=LOOKASIDE_SMALL ) return p;
+    }else
+#endif
+    if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
+      if( n<=db->lookaside.szTrue ) return p;
+    }
+  }
   return dbReallocFinish(db, p, n);
 }
 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, size_t n){
@@ -27325,14 +28164,14 @@ static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, size_t n){
     if( isLookaside(db, p) ){
       pNew = sqlite3DbMallocRawNN(db, n);
       if( pNew ){
-        memcpy(pNew, p, db->lookaside.sz);
+        memcpy(pNew, p, lookasideMallocSize(db, p));
         sqlite3DbFree(db, p);
       }
     }else{
       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
-      pNew = sqlite3_realloc64(p, n);
+      pNew = sqlite3Realloc(p, n);
       if( !pNew ){
         sqlite3OomFault(db);
       }
@@ -27357,9 +28196,9 @@ SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, size_t n){
 }
 
 /*
-** Make a copy of a string in memory obtained from sqliteMalloc(). These 
+** Make a copy of a string in memory obtained from sqliteMalloc(). These
 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
-** is because when memory debugging is turned on, these two functions are 
+** is because when memory debugging is turned on, these two functions are
 ** called via macros that record the current file and line number in the
 ** ThreadData structure.
 */
@@ -27379,11 +28218,9 @@ SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, size_t n){
   char *zNew;
   assert( db!=0 );
-  if( z==0 ){
-    return 0;
-  }
+  assert( z!=0 || n==0 );
   assert( (n&0x7fffffff)==n );
-  zNew = sqlite3DbMallocRawNN(db, n+1);
+  zNew = z ? sqlite3DbMallocRawNN(db, n+1) : 0;
   if( zNew ){
     memcpy(zNew, z, n);
     zNew[n] = 0;
@@ -27422,9 +28259,9 @@ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
     db->mallocFailed = 1;
     if( db->nVdbeExec>0 ){
-      db->u1.isInterrupted = 1;
+      AtomicStore(&db->u1.isInterrupted, 1);
     }
-    db->lookaside.bDisable++;
+    DisableLookaside;
     if( db->pParse ){
       db->pParse->rc = SQLITE_NOMEM_BKPT;
     }
@@ -27441,42 +28278,45 @@ SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
 SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
   if( db->mallocFailed && db->nVdbeExec==0 ){
     db->mallocFailed = 0;
-    db->u1.isInterrupted = 0;
+    AtomicStore(&db->u1.isInterrupted, 0);
     assert( db->lookaside.bDisable>0 );
-    db->lookaside.bDisable--;
+    EnableLookaside;
   }
 }
 
 /*
-** Take actions at the end of an API call to indicate an OOM error
+** Take actions at the end of an API call to deal with error codes.
 */
-static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
-  sqlite3OomClear(db);
-  sqlite3Error(db, SQLITE_NOMEM);
-  return SQLITE_NOMEM_BKPT;
+static SQLITE_NOINLINE int apiHandleError(sqlite3 *db, int rc){
+  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
+    sqlite3OomClear(db);
+    sqlite3Error(db, SQLITE_NOMEM);
+    return SQLITE_NOMEM_BKPT;
+  }
+  return rc & db->errMask;
 }
 
 /*
-** This function must be called before exiting any API function (i.e. 
+** This function must be called before exiting any API function (i.e.
 ** returning control to the user) that has called sqlite3_malloc or
 ** sqlite3_realloc.
 **
 ** The returned value is normally a copy of the second argument to this
 ** function. However, if a malloc() failure has occurred since the previous
-** invocation SQLITE_NOMEM is returned instead. 
+** invocation SQLITE_NOMEM is returned instead.
 **
 ** If an OOM as occurred, then the connection error-code (the value
 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
 */
 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
   /* If the db handle must hold the connection handle mutex here.
-  ** Otherwise the read (and possible write) of db->mallocFailed 
+  ** Otherwise the read (and possible write) of db->mallocFailed
   ** is unsafe, as is the call to sqlite3Error().
   */
   assert( db!=0 );
   assert( sqlite3_mutex_held(db->mutex) );
-  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
-    return apiOomError(db);
+  if( db->mallocFailed || rc ){
+    return apiHandleError(db, rc);
   }
   return rc & db->errMask;
 }
@@ -27485,7 +28325,7 @@ SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
 /************** Begin file printf.c ******************************************/
 /*
 ** The "printf" code that follows dates from the 1980's.  It is in
-** the public domain. 
+** the public domain.
 **
 **************************************************************************
 **
@@ -27680,6 +28520,13 @@ static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
 
 /*
+** Hard limit on the precision of floating-point conversions.
+*/
+#ifndef SQLITE_PRINTF_PRECISION_LIMIT
+# define SQLITE_FP_PRECISION_LIMIT 100000000
+#endif
+
+/*
 ** Render a string given by "fmt" into the StrAccum object.
 */
 SQLITE_API void sqlite3_str_vappendf(
@@ -27720,7 +28567,7 @@ SQLITE_API void sqlite3_str_vappendf(
   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
   char buf[etBUFSIZE];       /* Conversion buffer */
 
-  /* pAccum never starts out with an empty buffer that was obtained from 
+  /* pAccum never starts out with an empty buffer that was obtained from
   ** malloc().  This precondition is required by the mprintf("%z...")
   ** optimization. */
   assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
@@ -27879,15 +28726,17 @@ SQLITE_API void sqlite3_str_vappendf(
     **   xtype                       The class of the conversion.
     **   infop                       Pointer to the appropriate info struct.
     */
+    assert( width>=0 );
+    assert( precision>=(-1) );
     switch( xtype ){
       case etPOINTER:
         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
                      sizeof(char*)==sizeof(long int) ? 1 : 0;
-        /* Fall through into the next case */
+        /* no break */ deliberate_fall_through
       case etORDINAL:
-      case etRADIX:      
+      case etRADIX:
         cThousand = 0;
-        /* Fall through into the next case */
+        /* no break */ deliberate_fall_through
       case etDECIMAL:
         if( infop->flags & FLAG_SIGNED ){
           i64 v;
@@ -27903,11 +28752,10 @@ SQLITE_API void sqlite3_str_vappendf(
             v = va_arg(ap,int);
           }
           if( v<0 ){
-            if( v==SMALLEST_INT64 ){
-              longvalue = ((u64)1)<<63;
-            }else{
-              longvalue = -v;
-            }
+            testcase( v==SMALLEST_INT64 );
+            testcase( v==(-1) );
+            longvalue = ~v;
+            longvalue++;
             prefix = '-';
           }else{
             longvalue = v;
@@ -28002,6 +28850,11 @@ SQLITE_API void sqlite3_str_vappendf(
         length = 0;
 #else
         if( precision<0 ) precision = 6;         /* Set default precision */
+#ifdef SQLITE_FP_PRECISION_LIMIT
+        if( precision>SQLITE_FP_PRECISION_LIMIT ){
+          precision = SQLITE_FP_PRECISION_LIMIT;
+        }
+#endif
         if( realvalue<0.0 ){
           realvalue = -realvalue;
           prefix = '-';
@@ -28284,7 +29137,7 @@ SQLITE_API void sqlite3_str_vappendf(
         }
         isnull = escarg==0;
         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
-        /* For %q, %Q, and %w, the precision is the number of byte (or
+        /* For %q, %Q, and %w, the precision is the number of bytes (or
         ** characters if the ! flags is present) to use from the input.
         ** Because of the extra quoting characters inserted, the number
         ** of output characters may be larger than the precision.
@@ -28640,7 +29493,7 @@ SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
   char zBase[SQLITE_PRINT_BUF_SIZE];
   StrAccum acc;
 
-#ifdef SQLITE_ENABLE_API_ARMOR  
+#ifdef SQLITE_ENABLE_API_ARMOR
   if( zFormat==0 ){
     (void)SQLITE_MISUSE_BKPT;
     return 0;
@@ -28753,7 +29606,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
   va_list ap;
   StrAccum acc;
-  char zBuf[500];
+  char zBuf[SQLITE_PRINT_BUF_SIZE*10];
   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
   va_start(ap,zFormat);
   sqlite3_str_vappendf(&acc, zFormat, ap);
@@ -28799,7 +29652,7 @@ SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
 **
 ** This file contains C code to implement the TreeView debugging routines.
 ** These routines print a parse tree to standard output for debugging and
-** analysis. 
+** analysis.
 **
 ** The interfaces in this file is only available when compiling
 ** with SQLITE_DEBUG.
@@ -28853,7 +29706,7 @@ static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
     va_start(ap, zFormat);
     sqlite3_str_vappendf(&acc, zFormat, ap);
     va_end(ap);
-    assert( acc.nChar>0 );
+    assert( acc.nChar>0 || acc.accError );
     sqlite3_str_append(&acc, "\n", 1);
   }
   sqlite3StrAccumFinish(&acc);
@@ -28893,7 +29746,7 @@ SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 m
         char cSep = '(';
         int j;
         for(j=0; j<pCte->pCols->nExpr; j++){
-          sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
+          sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
           cSep = ',';
         }
         sqlite3_str_appendf(&x, ")");
@@ -28918,15 +29771,15 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc)
     StrAccum x;
     char zLine[100];
     sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
-    sqlite3_str_appendf(&x, "{%d,*}", pItem->iCursor);
+    sqlite3_str_appendf(&x, "{%d:*}", pItem->iCursor);
     if( pItem->zDatabase ){
       sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
     }else if( pItem->zName ){
       sqlite3_str_appendf(&x, " %s", pItem->zName);
     }
     if( pItem->pTab ){
-      sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p",
-           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab);
+      sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
+           pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
     }
     if( pItem->zAlias ){
       sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
@@ -28934,8 +29787,11 @@ SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc)
     if( pItem->fg.jointype & JT_LEFT ){
       sqlite3_str_appendf(&x, " LEFT-JOIN");
     }
+    if( pItem->fg.fromDDL ){
+      sqlite3_str_appendf(&x, " DDL");
+    }
     sqlite3StrAccumFinish(&x);
-    sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); 
+    sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
     if( pItem->pSelect ){
       sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
     }
@@ -28955,7 +29811,7 @@ SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 m
   if( p==0 ){
     sqlite3TreeViewLine(pView, "nil-SELECT");
     return;
-  } 
+  }
   pView = sqlite3TreeViewPush(pView, moreToFollow);
   if( p->pWith ){
     sqlite3TreeViewWith(pView, p->pWith, 1);
@@ -29182,22 +30038,28 @@ SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin,
 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
   const char *zBinOp = 0;   /* Binary operator */
   const char *zUniOp = 0;   /* Unary operator */
-  char zFlgs[60];
+  char zFlgs[200];
   pView = sqlite3TreeViewPush(pView, moreToFollow);
   if( pExpr==0 ){
     sqlite3TreeViewLine(pView, "nil");
     sqlite3TreeViewPop(pView);
     return;
   }
-  if( pExpr->flags || pExpr->affExpr ){
+  if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){
+    StrAccum x;
+    sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);
+    sqlite3_str_appendf(&x, " fg.af=%x.%c",
+      pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
     if( ExprHasProperty(pExpr, EP_FromJoin) ){
-      sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  fg.af=%x.%c iRJT=%d",
-                       pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n',
-                       pExpr->iRightJoinTable);
-    }else{
-      sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  fg.af=%x.%c",
-                       pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
+      sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable);
+    }
+    if( ExprHasProperty(pExpr, EP_FromDDL) ){
+      sqlite3_str_appendf(&x, " DDL");
     }
+    if( ExprHasVVAProperty(pExpr, EP_Immutable) ){
+      sqlite3_str_appendf(&x, " IMMUTABLE");
+    }
+    sqlite3StrAccumFinish(&x);
   }else{
     zFlgs[0] = 0;
   }
@@ -29210,10 +30072,18 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     case TK_COLUMN: {
       if( pExpr->iTable<0 ){
         /* This only happens when coding check constraints */
-        sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
+        char zOp2[16];
+        if( pExpr->op2 ){
+          sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
+        }else{
+          zOp2[0] = 0;
+        }
+        sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
+                                    pExpr->iColumn, zFlgs, zOp2);
       }else{
-        sqlite3TreeViewLine(pView, "{%d:%d}%s",
-                             pExpr->iTable, pExpr->iColumn, zFlgs);
+        sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
+                        pExpr->iTable, pExpr->iColumn,
+                        pExpr->y.pTab, zFlgs);
       }
       if( ExprHasProperty(pExpr, EP_FixedCol) ){
         sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
@@ -29295,6 +30165,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
     case TK_CONCAT:  zBinOp = "CONCAT"; break;
     case TK_DOT:     zBinOp = "DOT";    break;
+    case TK_LIMIT:   zBinOp = "LIMIT";  break;
 
     case TK_UMINUS:  zUniOp = "UMINUS"; break;
     case TK_UPLUS:   zUniOp = "UPLUS";  break;
@@ -29345,14 +30216,27 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       }else{
         pFarg = pExpr->x.pList;
 #ifndef SQLITE_OMIT_WINDOWFUNC
-        pWin = pExpr->y.pWin;
+        pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
 #else
         pWin = 0;
-#endif 
+#endif
       }
       if( pExpr->op==TK_AGG_FUNCTION ){
-        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s",
-                             pExpr->op2, pExpr->u.zToken, zFlgs);
+        sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s agg=%d[%d]/%p",
+                             pExpr->op2, pExpr->u.zToken, zFlgs,
+                             pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0,
+                             pExpr->iAgg, pExpr->pAggInfo);
+      }else if( pExpr->op2!=0 ){
+        const char *zOp2;
+        char zBuf[8];
+        sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
+        zOp2 = zBuf;
+        if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
+        if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
+        if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
+        if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
+        sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s",
+                            pExpr->u.zToken, zFlgs, zOp2);
       }else{
         sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
       }
@@ -29373,7 +30257,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       break;
     }
     case TK_SELECT: {
-      sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
+      sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
       break;
     }
@@ -29418,7 +30302,7 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       ** is set to the column of the pseudo-table to read, or to -1 to
       ** read the rowid field.
       */
-      sqlite3TreeViewLine(pView, "%s(%d)", 
+      sqlite3TreeViewLine(pView, "%s(%d)",
           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
       break;
     }
@@ -29448,7 +30332,9 @@ SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 m
       break;
     }
     case TK_VECTOR: {
-      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
+      char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
+      sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
+      sqlite3_free(z);
       break;
     }
     case TK_SELECT_COLUMN: {
@@ -29494,8 +30380,9 @@ SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
     sqlite3TreeViewLine(pView, "%s", zLabel);
     for(i=0; i<pList->nExpr; i++){
       int j = pList->a[i].u.x.iOrderByCol;
-      char *zName = pList->a[i].zName;
+      char *zName = pList->a[i].zEName;
       int moreToFollow = i<pList->nExpr - 1;
+      if( pList->a[i].eEName!=ENAME_NAME ) zName = 0;
       if( j || zName ){
         sqlite3TreeViewPush(pView, moreToFollow);
         moreToFollow = 0;
@@ -29737,13 +30624,13 @@ SQLITE_PRIVATE int sqlite3ThreadCreate(
   memset(p, 0, sizeof(*p));
   p->xTask = xTask;
   p->pIn = pIn;
-  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
+  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
   ** function that returns SQLITE_ERROR when passed the argument 200, that
-  ** forces worker threads to run sequentially and deterministically 
+  ** forces worker threads to run sequentially and deterministically
   ** for testing purposes. */
   if( sqlite3FaultSim(200) ){
     rc = 1;
-  }else{    
+  }else{
     rc = pthread_create(&p->tid, 0, xTask, pIn);
   }
   if( rc ){
@@ -29825,9 +30712,9 @@ SQLITE_PRIVATE int sqlite3ThreadCreate(
   *ppThread = 0;
   p = sqlite3Malloc(sizeof(*p));
   if( p==0 ) return SQLITE_NOMEM_BKPT;
-  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
+  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
   ** function that returns SQLITE_ERROR when passed the argument 200, that
-  ** forces worker threads to run sequentially and deterministically 
+  ** forces worker threads to run sequentially and deterministically
   ** (via the sqlite3FaultSim() term of the conditional) for testing
   ** purposes. */
   if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
@@ -29954,7 +30841,7 @@ SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
 **    May you share freely, never taking more than you give.
 **
 *************************************************************************
-** This file contains routines used to translate between UTF-8, 
+** This file contains routines used to translate between UTF-8,
 ** UTF-16, UTF-16BE, and UTF-16LE.
 **
 ** Notes on UTF-8:
@@ -30050,26 +30937,6 @@ static const unsigned char sqlite3Utf8Trans1[] = {
   }                                                                 \
 }
 
-#define READ_UTF16LE(zIn, TERM, c){                                   \
-  c = (*zIn++);                                                       \
-  c += ((*zIn++)<<8);                                                 \
-  if( c>=0xD800 && c<0xE000 && TERM ){                                \
-    int c2 = (*zIn++);                                                \
-    c2 += ((*zIn++)<<8);                                              \
-    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
-  }                                                                   \
-}
-
-#define READ_UTF16BE(zIn, TERM, c){                                   \
-  c = ((*zIn++)<<8);                                                  \
-  c += (*zIn++);                                                      \
-  if( c>=0xD800 && c<0xE000 && TERM ){                                \
-    int c2 = ((*zIn++)<<8);                                           \
-    c2 += (*zIn++);                                                   \
-    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
-  }                                                                   \
-}
-
 /*
 ** Translate a single UTF-8 character.  Return the unicode value.
 **
@@ -30135,7 +31002,7 @@ SQLITE_PRIVATE u32 sqlite3Utf8Read(
 /*
 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
-*/ 
+*/
 /* #define TRANSLATE_TRACE 1 */
 
 #ifndef SQLITE_OMIT_UTF16
@@ -30160,13 +31027,15 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired
 
 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   {
-    char zBuf[100];
-    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
-    fprintf(stderr, "INPUT:  %s\n", zBuf);
+    StrAccum acc;
+    char zBuf[1000];
+    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+    sqlite3VdbeMemPrettyPrint(pMem, &acc);
+    fprintf(stderr, "INPUT:  %s\n", sqlite3StrAccumFinish(&acc));
   }
 #endif
 
-  /* If the translation is between UTF-16 little and big endian, then 
+  /* If the translation is between UTF-16 little and big endian, then
   ** all that is required is to swap the byte order. This case is handled
   ** differently from the others.
   */
@@ -30244,13 +31113,59 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired
     if( pMem->enc==SQLITE_UTF16LE ){
       /* UTF-16 Little-endian -> UTF-8 */
       while( zIn<zTerm ){
-        READ_UTF16LE(zIn, zIn<zTerm, c); 
+        c = *(zIn++);
+        c += (*(zIn++))<<8;
+        if( c>=0xd800 && c<0xe000 ){
+#ifdef SQLITE_REPLACE_INVALID_UTF
+          if( c>=0xdc00 || zIn>=zTerm ){
+            c = 0xfffd;
+          }else{
+            int c2 = *(zIn++);
+            c2 += (*(zIn++))<<8;
+            if( c2<0xdc00 || c2>=0xe000 ){
+              zIn -= 2;
+              c = 0xfffd;
+            }else{
+              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
+            }
+          }
+#else
+          if( zIn<zTerm ){
+            int c2 = (*zIn++);
+            c2 += ((*zIn++)<<8);
+            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
+          }
+#endif
+        }
         WRITE_UTF8(z, c);
       }
     }else{
       /* UTF-16 Big-endian -> UTF-8 */
       while( zIn<zTerm ){
-        READ_UTF16BE(zIn, zIn<zTerm, c); 
+        c = (*(zIn++))<<8;
+        c += *(zIn++);
+        if( c>=0xd800 && c<0xe000 ){
+#ifdef SQLITE_REPLACE_INVALID_UTF
+          if( c>=0xdc00 || zIn>=zTerm ){
+            c = 0xfffd;
+          }else{
+            int c2 = (*(zIn++))<<8;
+            c2 += *(zIn++);
+            if( c2<0xdc00 || c2>=0xe000 ){
+              zIn -= 2;
+              c = 0xfffd;
+            }else{
+              c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
+            }
+          }
+#else
+          if( zIn<zTerm ){
+            int c2 = ((*zIn++)<<8);
+            c2 += (*zIn++);
+            c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
+          }
+#endif
+        }
         WRITE_UTF8(z, c);
       }
     }
@@ -30259,9 +31174,9 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired
   *z = 0;
   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
 
-  c = pMem->flags;
+  c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
   sqlite3VdbeMemRelease(pMem);
-  pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
+  pMem->flags = c;
   pMem->enc = desiredEnc;
   pMem->z = (char*)zOut;
   pMem->zMalloc = pMem->z;
@@ -30270,9 +31185,11 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desired
 translate_out:
 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   {
-    char zBuf[100];
-    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
-    fprintf(stderr, "OUTPUT: %s\n", zBuf);
+    StrAccum acc;
+    char zBuf[1000];
+    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+    sqlite3VdbeMemPrettyPrint(pMem, &acc);
+    fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
   }
 #endif
   return SQLITE_OK;
@@ -30281,7 +31198,7 @@ translate_out:
 
 #ifndef SQLITE_OMIT_UTF16
 /*
-** This routine checks for a byte-order mark at the beginning of the 
+** This routine checks for a byte-order mark at the beginning of the
 ** UTF-16 string stored in *pMem. If one is present, it is removed and
 ** the encoding of the Mem adjusted. This routine does not do any
 ** byte-swapping, it just sets Mem.enc appropriately.
@@ -30304,7 +31221,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
       bom = SQLITE_UTF16LE;
     }
   }
-  
+
   if( bom ){
     rc = sqlite3VdbeMemMakeWriteable(pMem);
     if( rc==SQLITE_OK ){
@@ -30324,7 +31241,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
 ** return the number of unicode characters in pZ up to (but not including)
 ** the first 0x00 byte. If nByte is not less than zero, return the
-** number of unicode characters in the first nByte of pZ (or up to 
+** number of unicode characters in the first nByte of pZ (or up to
 ** the first 0x00, whichever comes first).
 */
 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
@@ -30344,7 +31261,7 @@ SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
   return r;
 }
 
-/* This test function is not currently used by the automated test-suite. 
+/* This test function is not currently used by the automated test-suite.
 ** Hence it is only available in debug builds.
 */
 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
@@ -30406,19 +31323,16 @@ SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
   int c;
   unsigned char const *z = zIn;
   int n = 0;
-  
-  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
-    while( n<nChar ){
-      READ_UTF16BE(z, 1, c);
-      n++;
-    }
-  }else{
-    while( n<nChar ){
-      READ_UTF16LE(z, 1, c);
-      n++;
-    }
+
+  if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
+  while( n<nChar ){
+    c = z[0];
+    z += 2;
+    if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
+    n++;
   }
-  return (int)(z-(unsigned char const *)zIn);
+  return (int)(z-(unsigned char const *)zIn)
+              - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
 }
 
 #if defined(SQLITE_TEST)
@@ -30448,30 +31362,6 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
     assert( c==t );
     assert( (z-zBuf)==n );
   }
-  for(i=0; i<0x00110000; i++){
-    if( i>=0xD800 && i<0xE000 ) continue;
-    z = zBuf;
-    WRITE_UTF16LE(z, i);
-    n = (int)(z-zBuf);
-    assert( n>0 && n<=4 );
-    z[0] = 0;
-    z = zBuf;
-    READ_UTF16LE(z, 1, c);
-    assert( c==i );
-    assert( (z-zBuf)==n );
-  }
-  for(i=0; i<0x00110000; i++){
-    if( i>=0xD800 && i<0xE000 ) continue;
-    z = zBuf;
-    WRITE_UTF16BE(z, i);
-    n = (int)(z-zBuf);
-    assert( n>0 && n<=4 );
-    z[0] = 0;
-    z = zBuf;
-    READ_UTF16BE(z, 1, c);
-    assert( c==i );
-    assert( (z-zBuf)==n );
-  }
 }
 #endif /* SQLITE_TEST */
 #endif /* SQLITE_OMIT_UTF16 */
@@ -30497,7 +31387,9 @@ SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
 */
 /* #include "sqliteInt.h" */
 /* #include <stdarg.h> */
+#ifndef SQLITE_OMIT_FLOATING_POINT
 #include <math.h>
+#endif
 
 /*
 ** Routine needed to support the testcase() macro.
@@ -30511,7 +31403,7 @@ SQLITE_PRIVATE void sqlite3Coverage(int x){
 
 /*
 ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
-** or to bypass normal error detection during testing in order to let 
+** or to bypass normal error detection during testing in order to let
 ** execute proceed futher downstream.
 **
 ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0).  The
@@ -30560,7 +31452,7 @@ SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
 }
 
 /*
-** Return the declared type of a column.  Or return zDflt if the column 
+** Return the declared type of a column.  Or return zDflt if the column
 ** has no declared type.
 **
 ** The column type is an extra string stored after the zero-terminator on
@@ -30672,6 +31564,7 @@ SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
     sqlite3DbFree(db, pParse->zErrMsg);
     pParse->zErrMsg = zMsg;
     pParse->rc = SQLITE_ERROR;
+    pParse->pWith = 0;
   }
 }
 
@@ -30795,6 +31688,19 @@ SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
 }
 
 /*
+** Compute an 8-bit hash on a string that is insensitive to case differences
+*/
+SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){
+  u8 h = 0;
+  if( z==0 ) return 0;
+  while( z[0] ){
+    h += UpperToLower[(unsigned char)z[0]];
+    z++;
+  }
+  return h;
+}
+
+/*
 ** Compute 10 to the E-th power.  Examples:  E==1 results in 10.
 ** E==2 results in 100.  E==50 results in 1.0e50.
 **
@@ -30829,7 +31735,7 @@ static LONGDOUBLE_TYPE sqlite3Pow10(int E){
     if( E==0 ) break;
     x *= x;
   }
-  return r; 
+  return r;
 #endif
 }
 
@@ -30846,7 +31752,7 @@ static LONGDOUBLE_TYPE sqlite3Pow10(int E){
 **      1          =>  The input string is a pure integer
 **      2 or more  =>  The input has a decimal point or eNNN clause
 **      0 or less  =>  The input string is not a valid number
-**     -1          =>  Not a valid number, but has a valid prefix which 
+**     -1          =>  Not a valid number, but has a valid prefix which
 **                     includes a decimal point and/or an eNNN clause
 **
 ** Valid numbers are in one of these formats:
@@ -30862,10 +31768,13 @@ static LONGDOUBLE_TYPE sqlite3Pow10(int E){
 ** returns FALSE but it still converts the prefix and writes the result
 ** into *pResult.
 */
+#if defined(_MSC_VER)
+#pragma warning(disable : 4756)
+#endif
 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
 #ifndef SQLITE_OMIT_FLOATING_POINT
   int incr;
-  const char *zEnd = z + length;
+  const char *zEnd;
   /* sign * significand * (10 ^ (esign * exponent)) */
   int sign = 1;    /* sign of significand */
   i64 s = 0;       /* significand */
@@ -30879,12 +31788,15 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en
 
   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
   *pResult = 0.0;   /* Default return value, in case of an error */
+  if( length==0 ) return 0;
 
   if( enc==SQLITE_UTF8 ){
     incr = 1;
+    zEnd = z + length;
   }else{
     int i;
     incr = 2;
+    length &= ~1;
     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
     testcase( enc==SQLITE_UTF16LE );
     testcase( enc==SQLITE_UTF16BE );
@@ -30941,7 +31853,7 @@ SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 en
     eValid = 0;
     eType++;
 
-    /* This branch is needed to avoid a (harmless) buffer overread.  The 
+    /* This branch is needed to avoid a (harmless) buffer overread.  The
     ** special comment alerts the mutation tester that the correct answer
     ** is obtained even if the branch is omitted */
     if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
@@ -31049,6 +31961,33 @@ do_atof_calc:
   return !sqlite3Atoi64(z, pResult, length, enc);
 #endif /* SQLITE_OMIT_FLOATING_POINT */
 }
+#if defined(_MSC_VER)
+#pragma warning(default : 4756)
+#endif
+
+/*
+** Render an signed 64-bit integer as text.  Store the result in zOut[].
+**
+** The caller must ensure that zOut[] is at least 21 bytes in size.
+*/
+SQLITE_PRIVATE void sqlite3Int64ToText(i64 v, char *zOut){
+  int i;
+  u64 x;
+  char zTemp[22];
+  if( v<0 ){
+    x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
+  }else{
+    x = v;
+  }
+  i = sizeof(zTemp)-2;
+  zTemp[sizeof(zTemp)-1] = 0;
+  do{
+    zTemp[i--] = (x%10) + '0';
+    x = x/10;
+  }while( x );
+  if( v<0 ) zTemp[i--] = '-';
+  memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
+}
 
 /*
 ** Compare the 19-character string zNum against the text representation
@@ -31112,6 +32051,7 @@ SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc
     incr = 1;
   }else{
     incr = 2;
+    length &= ~1;
     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
     nonNum = i<length;
@@ -31290,11 +32230,29 @@ SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
 */
 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
   int x = 0;
-  if( z ) sqlite3GetInt32(z, &x);
+  sqlite3GetInt32(z, &x);
   return x;
 }
 
 /*
+** Try to convert z into an unsigned 32-bit integer.  Return true on
+** success and false if there is an error.
+**
+** Only decimal notation is accepted.
+*/
+SQLITE_PRIVATE int sqlite3GetUInt32(const char *z, u32 *pI){
+  u64 v = 0;
+  int i;
+  for(i=0; sqlite3Isdigit(z[i]); i++){
+    v = v*10 + z[i] - '0';
+    if( v>4294967296LL ){ *pI = 0; return 0; }
+  }
+  if( i==0 || z[i]!=0 ){ *pI = 0; return 0; }
+  *pI = (u32)v;
+  return 1;
+}
+
+/*
 ** The variable-length integer encoding is as follows:
 **
 ** KEY:
@@ -31334,7 +32292,7 @@ static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
       v >>= 7;
     }
     return 9;
-  }    
+  }
   n = 0;
   do{
     buf[n++] = (u8)((v & 0x7f) | 0x80);
@@ -31534,8 +32492,8 @@ SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
 ** integer, then set *v to 0xffffffff.
 **
-** A MACRO version, getVarint32, is provided which inlines the 
-** single-byte case.  All code should use the MACRO version as 
+** A MACRO version, getVarint32, is provided which inlines the
+** single-byte case.  All code should use the MACRO version as
 ** this function assumes the single-byte case has already been handled.
 */
 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
@@ -31596,8 +32554,7 @@ SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
     u64 v64;
     u8 n;
 
-    p -= 2;
-    n = sqlite3GetVarint(p, &v64);
+    n = sqlite3GetVarint(p-2, &v64);
     assert( n>3 && n<=9 );
     if( (v64 & SQLITE_MAX_U32)!=v64 ){
       *v = 0xffffffff;
@@ -31724,7 +32681,7 @@ SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
   return (u8)(h & 0xf);
 }
 
-#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
+#if !defined(SQLITE_OMIT_BLOB_LITERAL)
 /*
 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
 ** value.  Return a pointer to its binary value.  Space to hold the
@@ -31745,7 +32702,7 @@ SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
   }
   return zBlob;
 }
-#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
+#endif /* !SQLITE_OMIT_BLOB_LITERAL */
 
 /*
 ** Log an error that is an API call on a connection pointer that should
@@ -31753,7 +32710,7 @@ SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
 */
 static void logBadConnection(const char *zType){
-  sqlite3_log(SQLITE_MISUSE, 
+  sqlite3_log(SQLITE_MISUSE,
      "API call with %s database connection pointer",
      zType
   );
@@ -31827,7 +32784,7 @@ SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
   }
   *pA += iB;
-  return 0; 
+  return 0;
 #endif
 }
 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
@@ -31868,7 +32825,7 @@ SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
 }
 
 /*
-** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
+** Compute the absolute value of a 32-bit signed integer, of possible.  Or
 ** if the integer has a value of -2147483648, return +2147483647
 */
 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
@@ -31908,11 +32865,11 @@ SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
 }
 #endif
 
-/* 
+/*
 ** Find (an approximate) sum of two LogEst values.  This computation is
 ** not a simple "+" operator because LogEst is stored as a logarithmic
 ** value.
-** 
+**
 */
 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
   static const unsigned char x[] = {
@@ -32026,8 +32983,8 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 ** Conceptually:
 **
 **    struct VList {
-**      int nAlloc;   // Number of allocated slots 
-**      int nUsed;    // Number of used slots 
+**      int nAlloc;   // Number of allocated slots
+**      int nUsed;    // Number of used slots
 **      struct VListEntry {
 **        int iValue;    // Value for this entry
 **        int nSlot;     // Slots used by this entry
@@ -32036,7 +32993,7 @@ SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
 **    }
 **
 ** During code generation, pointers to the variable names within the
-** VList are taken.  When that happens, nAlloc is set to zero as an 
+** VList are taken.  When that happens, nAlloc is set to zero as an
 ** indication that the VList may never again be enlarged, since the
 ** accompanying realloc() would invalidate the pointers.
 */
@@ -32227,7 +33184,7 @@ static int rehash(Hash *pH, unsigned int new_size){
 
   /* The inability to allocates space for a larger hash table is
   ** a performance hit but it is not a fatal error.  So mark the
-  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
+  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
   ** only zeroes the requested number of bytes whereas this module will
   ** use the actual amount of space allocated for the hash table (which
@@ -32279,7 +33236,7 @@ static HashElem *findElementWithHash(
   if( pHash ) *pHash = h;
   while( count-- ){
     assert( elem!=0 );
-    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
+    if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
       return elem;
     }
     elem = elem->next;
@@ -32297,7 +33254,7 @@ static void removeElementGivenHash(
 ){
   struct _ht *pEntry;
   if( elem->prev ){
-    elem->prev->next = elem->next; 
+    elem->prev->next = elem->next;
   }else{
     pH->first = elem->next;
   }
@@ -32419,30 +33376,30 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /*  23 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
     /*  24 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
     /*  25 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
-    /*  26 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
-    /*  27 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
-    /*  28 */ "NotFound"         OpHelp("key=r[P3@P4]"),
-    /*  29 */ "Found"            OpHelp("key=r[P3@P4]"),
-    /*  30 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
-    /*  31 */ "NotExists"        OpHelp("intkey=r[P3]"),
-    /*  32 */ "Last"             OpHelp(""),
-    /*  33 */ "IfSmaller"        OpHelp(""),
-    /*  34 */ "SorterSort"       OpHelp(""),
-    /*  35 */ "Sort"             OpHelp(""),
-    /*  36 */ "Rewind"           OpHelp(""),
-    /*  37 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
-    /*  38 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
-    /*  39 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
-    /*  40 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
-    /*  41 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
-    /*  42 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
+    /*  26 */ "IfNotOpen"        OpHelp("if( !csr[P1] ) goto P2"),
+    /*  27 */ "IfNoHope"         OpHelp("key=r[P3@P4]"),
+    /*  28 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
+    /*  29 */ "NotFound"         OpHelp("key=r[P3@P4]"),
+    /*  30 */ "Found"            OpHelp("key=r[P3@P4]"),
+    /*  31 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
+    /*  32 */ "NotExists"        OpHelp("intkey=r[P3]"),
+    /*  33 */ "Last"             OpHelp(""),
+    /*  34 */ "IfSmaller"        OpHelp(""),
+    /*  35 */ "SorterSort"       OpHelp(""),
+    /*  36 */ "Sort"             OpHelp(""),
+    /*  37 */ "Rewind"           OpHelp(""),
+    /*  38 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
+    /*  39 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
+    /*  40 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
+    /*  41 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
+    /*  42 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
     /*  43 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
     /*  44 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
-    /*  45 */ "Program"          OpHelp(""),
-    /*  46 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
-    /*  47 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
-    /*  48 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
-    /*  49 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
+    /*  45 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
+    /*  46 */ "Program"          OpHelp(""),
+    /*  47 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
+    /*  48 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
+    /*  49 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
     /*  50 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
     /*  51 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
     /*  52 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
@@ -32452,67 +33409,67 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /*  56 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
     /*  57 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
     /*  58 */ "ElseNotEq"        OpHelp(""),
-    /*  59 */ "IncrVacuum"       OpHelp(""),
-    /*  60 */ "VNext"            OpHelp(""),
-    /*  61 */ "Init"             OpHelp("Start at P2"),
-    /*  62 */ "PureFunc0"        OpHelp(""),
-    /*  63 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
-    /*  64 */ "PureFunc"         OpHelp(""),
-    /*  65 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
-    /*  66 */ "Return"           OpHelp(""),
-    /*  67 */ "EndCoroutine"     OpHelp(""),
-    /*  68 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
-    /*  69 */ "Halt"             OpHelp(""),
-    /*  70 */ "Integer"          OpHelp("r[P2]=P1"),
-    /*  71 */ "Int64"            OpHelp("r[P2]=P4"),
-    /*  72 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
-    /*  73 */ "Null"             OpHelp("r[P2..P3]=NULL"),
-    /*  74 */ "SoftNull"         OpHelp("r[P1]=NULL"),
-    /*  75 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
-    /*  76 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
-    /*  77 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
-    /*  78 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
-    /*  79 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
-    /*  80 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
-    /*  81 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
-    /*  82 */ "CollSeq"          OpHelp(""),
-    /*  83 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
-    /*  84 */ "RealAffinity"     OpHelp(""),
-    /*  85 */ "Cast"             OpHelp("affinity(r[P1])"),
-    /*  86 */ "Permutation"      OpHelp(""),
-    /*  87 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
-    /*  88 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
-    /*  89 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
-    /*  90 */ "Column"           OpHelp("r[P3]=PX"),
-    /*  91 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
-    /*  92 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
-    /*  93 */ "Count"            OpHelp("r[P2]=count()"),
-    /*  94 */ "ReadCookie"       OpHelp(""),
-    /*  95 */ "SetCookie"        OpHelp(""),
-    /*  96 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
-    /*  97 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
-    /*  98 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
-    /*  99 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
-    /* 100 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
-    /* 101 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
-    /* 102 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
-    /* 103 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
-    /* 104 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
-    /* 105 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
-    /* 106 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
-    /* 107 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
-    /* 108 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
-    /* 109 */ "OpenDup"          OpHelp(""),
-    /* 110 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
-    /* 111 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
-    /* 112 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
-    /* 113 */ "String8"          OpHelp("r[P2]='P4'"),
-    /* 114 */ "SorterOpen"       OpHelp(""),
-    /* 115 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
-    /* 116 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
-    /* 117 */ "Close"            OpHelp(""),
-    /* 118 */ "ColumnsUsed"      OpHelp(""),
-    /* 119 */ "SeekHit"          OpHelp("seekHit=P2"),
+    /*  59 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
+    /*  60 */ "IncrVacuum"       OpHelp(""),
+    /*  61 */ "VNext"            OpHelp(""),
+    /*  62 */ "Init"             OpHelp("Start at P2"),
+    /*  63 */ "PureFunc"         OpHelp("r[P3]=func(r[P2@NP])"),
+    /*  64 */ "Function"         OpHelp("r[P3]=func(r[P2@NP])"),
+    /*  65 */ "Return"           OpHelp(""),
+    /*  66 */ "EndCoroutine"     OpHelp(""),
+    /*  67 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
+    /*  68 */ "Halt"             OpHelp(""),
+    /*  69 */ "Integer"          OpHelp("r[P2]=P1"),
+    /*  70 */ "Int64"            OpHelp("r[P2]=P4"),
+    /*  71 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
+    /*  72 */ "Null"             OpHelp("r[P2..P3]=NULL"),
+    /*  73 */ "SoftNull"         OpHelp("r[P1]=NULL"),
+    /*  74 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
+    /*  75 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
+    /*  76 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
+    /*  77 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
+    /*  78 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
+    /*  79 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
+    /*  80 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
+    /*  81 */ "CollSeq"          OpHelp(""),
+    /*  82 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
+    /*  83 */ "RealAffinity"     OpHelp(""),
+    /*  84 */ "Cast"             OpHelp("affinity(r[P1])"),
+    /*  85 */ "Permutation"      OpHelp(""),
+    /*  86 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
+    /*  87 */ "IsTrue"           OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
+    /*  88 */ "Offset"           OpHelp("r[P3] = sqlite_offset(P1)"),
+    /*  89 */ "Column"           OpHelp("r[P3]=PX"),
+    /*  90 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
+    /*  91 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
+    /*  92 */ "Count"            OpHelp("r[P2]=count()"),
+    /*  93 */ "ReadCookie"       OpHelp(""),
+    /*  94 */ "SetCookie"        OpHelp(""),
+    /*  95 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
+    /*  96 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
+    /*  97 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
+    /*  98 */ "OpenDup"          OpHelp(""),
+    /*  99 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
+    /* 100 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
+    /* 101 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
+    /* 102 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
+    /* 103 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
+    /* 104 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
+    /* 105 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
+    /* 106 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
+    /* 107 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
+    /* 108 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
+    /* 109 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
+    /* 110 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
+    /* 111 */ "SorterOpen"       OpHelp(""),
+    /* 112 */ "BitNot"           OpHelp("r[P2]= ~r[P1]"),
+    /* 113 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
+    /* 114 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
+    /* 115 */ "String8"          OpHelp("r[P2]='P4'"),
+    /* 116 */ "Close"            OpHelp(""),
+    /* 117 */ "ColumnsUsed"      OpHelp(""),
+    /* 118 */ "SeekScan"         OpHelp("Scan-ahead up to P1 rows"),
+    /* 119 */ "SeekHit"          OpHelp("set P2<=seekHit<=P3"),
     /* 120 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
     /* 121 */ "NewRowid"         OpHelp("r[P2]=rowid"),
     /* 122 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
@@ -32524,48 +33481,52 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
     /* 128 */ "Rowid"            OpHelp("r[P2]=rowid"),
     /* 129 */ "NullRow"          OpHelp(""),
     /* 130 */ "SeekEnd"          OpHelp(""),
-    /* 131 */ "SorterInsert"     OpHelp("key=r[P2]"),
-    /* 132 */ "IdxInsert"        OpHelp("key=r[P2]"),
+    /* 131 */ "IdxInsert"        OpHelp("key=r[P2]"),
+    /* 132 */ "SorterInsert"     OpHelp("key=r[P2]"),
     /* 133 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
     /* 134 */ "DeferredSeek"     OpHelp("Move P3 to P1.rowid if needed"),
     /* 135 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
-    /* 136 */ "Destroy"          OpHelp(""),
-    /* 137 */ "Clear"            OpHelp(""),
-    /* 138 */ "ResetSorter"      OpHelp(""),
-    /* 139 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
-    /* 140 */ "SqlExec"          OpHelp(""),
-    /* 141 */ "ParseSchema"      OpHelp(""),
-    /* 142 */ "LoadAnalysis"     OpHelp(""),
-    /* 143 */ "DropTable"        OpHelp(""),
-    /* 144 */ "DropIndex"        OpHelp(""),
-    /* 145 */ "DropTrigger"      OpHelp(""),
-    /* 146 */ "IntegrityCk"      OpHelp(""),
-    /* 147 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
-    /* 148 */ "Real"             OpHelp("r[P2]=P4"),
+    /* 136 */ "FinishSeek"       OpHelp(""),
+    /* 137 */ "Destroy"          OpHelp(""),
+    /* 138 */ "Clear"            OpHelp(""),
+    /* 139 */ "ResetSorter"      OpHelp(""),
+    /* 140 */ "CreateBtree"      OpHelp("r[P2]=root iDb=P1 flags=P3"),
+    /* 141 */ "SqlExec"          OpHelp(""),
+    /* 142 */ "ParseSchema"      OpHelp(""),
+    /* 143 */ "LoadAnalysis"     OpHelp(""),
+    /* 144 */ "DropTable"        OpHelp(""),
+    /* 145 */ "DropIndex"        OpHelp(""),
+    /* 146 */ "DropTrigger"      OpHelp(""),
+    /* 147 */ "IntegrityCk"      OpHelp(""),
+    /* 148 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
     /* 149 */ "Param"            OpHelp(""),
-    /* 150 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
-    /* 151 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
-    /* 152 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
-    /* 153 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
-    /* 154 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
-    /* 155 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
-    /* 156 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
-    /* 157 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
-    /* 158 */ "Expire"           OpHelp(""),
-    /* 159 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
-    /* 160 */ "VBegin"           OpHelp(""),
-    /* 161 */ "VCreate"          OpHelp(""),
-    /* 162 */ "VDestroy"         OpHelp(""),
-    /* 163 */ "VOpen"            OpHelp(""),
-    /* 164 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
-    /* 165 */ "VRename"          OpHelp(""),
-    /* 166 */ "Pagecount"        OpHelp(""),
-    /* 167 */ "MaxPgcnt"         OpHelp(""),
-    /* 168 */ "Trace"            OpHelp(""),
-    /* 169 */ "CursorHint"       OpHelp(""),
-    /* 170 */ "Noop"             OpHelp(""),
-    /* 171 */ "Explain"          OpHelp(""),
-    /* 172 */ "Abortable"        OpHelp(""),
+    /* 150 */ "Real"             OpHelp("r[P2]=P4"),
+    /* 151 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
+    /* 152 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
+    /* 153 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
+    /* 154 */ "AggInverse"       OpHelp("accum=r[P3] inverse(r[P2@P5])"),
+    /* 155 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 156 */ "AggStep1"         OpHelp("accum=r[P3] step(r[P2@P5])"),
+    /* 157 */ "AggValue"         OpHelp("r[P3]=value N=P2"),
+    /* 158 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
+    /* 159 */ "Expire"           OpHelp(""),
+    /* 160 */ "CursorLock"       OpHelp(""),
+    /* 161 */ "CursorUnlock"     OpHelp(""),
+    /* 162 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
+    /* 163 */ "VBegin"           OpHelp(""),
+    /* 164 */ "VCreate"          OpHelp(""),
+    /* 165 */ "VDestroy"         OpHelp(""),
+    /* 166 */ "VOpen"            OpHelp(""),
+    /* 167 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
+    /* 168 */ "VRename"          OpHelp(""),
+    /* 169 */ "Pagecount"        OpHelp(""),
+    /* 170 */ "MaxPgcnt"         OpHelp(""),
+    /* 171 */ "Trace"            OpHelp(""),
+    /* 172 */ "CursorHint"       OpHelp(""),
+    /* 173 */ "ReleaseReg"       OpHelp("release r[P1@P2] mask P3"),
+    /* 174 */ "Noop"             OpHelp(""),
+    /* 175 */ "Explain"          OpHelp(""),
+    /* 176 */ "Abortable"        OpHelp(""),
   };
   return azName[i];
 }
@@ -32636,7 +33597,7 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
 ** selection of the appropriate locking style based on the filesystem
-** where the database is located.  
+** where the database is located.
 */
 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 #  if defined(__APPLE__)
@@ -32697,7 +33658,8 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
                             (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
 #    if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
-         && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
+        && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))\
+        && (!defined(TARGET_OS_MACCATALYST) || (TARGET_OS_MACCATALYST==0))
 #      undef HAVE_GETHOSTUUID
 #      define HAVE_GETHOSTUUID 1
 #    else
@@ -32762,7 +33724,7 @@ SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
 #define osGetpid(X) (pid_t)getpid()
 
 /*
-** Only set the lastErrno if the error code is a real error and not 
+** Only set the lastErrno if the error code is a real error and not
 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
 */
 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
@@ -32830,7 +33792,7 @@ struct unixFile {
   ** whenever any part of the database changes.  An assertion fault will
   ** occur if a file is updated without also updating the transaction
   ** counter.  This test is made to avoid new problems similar to the
-  ** one described by ticket #3584. 
+  ** one described by ticket #3584.
   */
   unsigned char transCntrChng;   /* True if the transaction counter changed */
   unsigned char dbUpdate;        /* True if any part of database file changed */
@@ -32839,7 +33801,7 @@ struct unixFile {
 #endif
 
 #ifdef SQLITE_TEST
-  /* In test mode, increase the size of this structure a bit so that 
+  /* In test mode, increase the size of this structure a bit so that
   ** it is larger than the struct CrashFile defined in test6.c.
   */
   char aPadding[32];
@@ -32929,7 +33891,7 @@ static pid_t randomnessPid = 0;
 ******************************************************************************
 **
 ** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 class CPUs.
+** counters for x86 and x86_64 class CPUs.
 */
 #ifndef SQLITE_HWTIME_H
 #define SQLITE_HWTIME_H
@@ -32940,8 +33902,9 @@ static pid_t randomnessPid = 0;
 ** processor and returns that value.  This can be used for high-res
 ** profiling.
 */
-#if (defined(__GNUC__) || defined(_MSC_VER)) && \
-      (defined(i386) || defined(__i386__) || defined(_M_IX86))
+#if !defined(__STRICT_ANSI__) && \
+    (defined(__GNUC__) || defined(_MSC_VER)) && \
+    (defined(i386) || defined(__i386__) || defined(_M_IX86))
 
   #if defined(__GNUC__)
 
@@ -32962,15 +33925,15 @@ static pid_t randomnessPid = 0;
 
   #endif
 
-#elif (defined(__GNUC__) && defined(__x86_64__))
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long val;
       __asm__ __volatile__ ("rdtsc" : "=A" (val));
       return val;
   }
-#elif (defined(__GNUC__) && defined(__ppc__))
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long long retval;
@@ -32987,14 +33950,13 @@ static pid_t randomnessPid = 0;
 
 #else
 
-  #error Need implementation of sqlite3Hwtime() for your platform.
-
   /*
-  ** To compile without implementing sqlite3Hwtime() for your platform,
-  ** you can remove the above #error and use the following
-  ** stub function.  You will lose timing support for many
-  ** of the debugging and testing utilities, but it should at
-  ** least compile and run.
+  ** asm() is needed for hardware timing support.  Without asm(),
+  ** disable the sqlite3Hwtime() routine.
+  **
+  ** sqlite3Hwtime() is only used for some obscure debugging
+  ** and analysis configurations, not in any deliverable, so this
+  ** should not be a great loss.
   */
 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 
@@ -33183,7 +34145,7 @@ static struct unix_syscall {
 #ifdef __DJGPP__
   { "fstat",        0,                 0  },
 #define osFstat(a,b,c)    0
-#else     
+#else
   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
 #endif
@@ -33421,7 +34383,7 @@ static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
 
 /*
 ** Do not accept any file descriptor less than this value, in order to avoid
-** opening database file using file descriptors that are commonly used for 
+** opening database file using file descriptors that are commonly used for
 ** standard input, output, and error.
 */
 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
@@ -33460,17 +34422,17 @@ static int robust_open(const char *z, int f, mode_t m){
     }
     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
     osClose(fd);
-    sqlite3_log(SQLITE_WARNING, 
+    sqlite3_log(SQLITE_WARNING,
                 "attempt to open \"%s\" as file descriptor %d", z, fd);
     fd = -1;
-    if( osOpen("/dev/null", f, m)<0 ) break;
+    if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
   }
   if( fd>=0 ){
     if( m!=0 ){
       struct stat statbuf;
-      if( osFstat(fd, &statbuf)==0 
+      if( osFstat(fd, &statbuf)==0
        && statbuf.st_size==0
-       && (statbuf.st_mode&0777)!=m 
+       && (statbuf.st_mode&0777)!=m
       ){
         osFchmod(fd, m);
       }
@@ -33485,11 +34447,11 @@ static int robust_open(const char *z, int f, mode_t m){
 /*
 ** Helper functions to obtain and relinquish the global mutex. The
 ** global mutex is used to protect the unixInodeInfo and
-** vxworksFileId objects used by this file, all of which may be 
+** vxworksFileId objects used by this file, all of which may be
 ** shared by multiple threads.
 **
-** Function unixMutexHeld() is used to assert() that the global mutex 
-** is held when required. This function is only used as part of assert() 
+** Function unixMutexHeld() is used to assert() that the global mutex
+** is held when required. This function is only used as part of assert()
 ** statements. e.g.
 **
 **   unixEnterMutex()
@@ -33611,7 +34573,7 @@ static int lockTrace(int fd, int op, struct flock *p){
 static int robust_ftruncate(int h, sqlite3_int64 sz){
   int rc;
 #ifdef __ANDROID__
-  /* On Android, ftruncate() always uses 32-bit offsets, even if 
+  /* On Android, ftruncate() always uses 32-bit offsets, even if
   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
   ** truncate a file to any size larger than 2GiB. Silently ignore any
   ** such attempts.  */
@@ -33627,32 +34589,32 @@ static int robust_ftruncate(int h, sqlite3_int64 sz){
 ** This routine translates a standard POSIX errno code into something
 ** useful to the clients of the sqlite3 functions.  Specifically, it is
 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
-** and a variety of "please close the file descriptor NOW" errors into 
+** and a variety of "please close the file descriptor NOW" errors into
 ** SQLITE_IOERR
-** 
+**
 ** Errors during initialization of locks, or file system support for locks,
 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
 */
 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
-  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
-          (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
+  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
+          (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
           (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
           (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
   switch (posixError) {
-  case EACCES: 
+  case EACCES:
   case EAGAIN:
   case ETIMEDOUT:
   case EBUSY:
   case EINTR:
-  case ENOLCK:  
-    /* random NFS retry error, unless during file system support 
+  case ENOLCK:
+    /* random NFS retry error, unless during file system support
      * introspection, in which it actually means what it says */
     return SQLITE_BUSY;
-    
-  case EPERM: 
+
+  case EPERM:
     return SQLITE_PERM;
-    
-  default: 
+
+  default:
     return sqliteIOErr;
   }
 }
@@ -33667,7 +34629,7 @@ static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
 **
 ** A pointer to an instance of the following structure can be used as a
 ** unique file ID in VxWorks.  Each instance of this structure contains
-** a copy of the canonical filename.  There is also a reference count.  
+** a copy of the canonical filename.  There is also a reference count.
 ** The structure is reclaimed when the number of pointers to it drops to
 ** zero.
 **
@@ -33683,7 +34645,7 @@ struct vxworksFileId {
 };
 
 #if OS_VXWORKS
-/* 
+/*
 ** All unique filenames are held on a linked list headed by this
 ** variable:
 */
@@ -33755,7 +34717,7 @@ static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
   */
   unixEnterMutex();
   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
-    if( pCandidate->nName==n 
+    if( pCandidate->nName==n
      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
     ){
        sqlite3_free(pNew);
@@ -33848,7 +34810,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){
 ** cnt>0 means there are cnt shared locks on the file.
 **
 ** Any attempt to lock or unlock a file first checks the locking
-** structure.  The fcntl() system call is only invoked to set a 
+** structure.  The fcntl() system call is only invoked to set a
 ** POSIX lock if the internal lock structure transitions between
 ** a locked and an unlocked state.
 **
@@ -33881,7 +34843,7 @@ static void vxworksReleaseFileId(struct vxworksFileId *pId){
 **
 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
 ** was dropped beginning with version 3.7.0.  SQLite will still work with
-** LinuxThreads provided that (1) there is no more than one connection 
+** LinuxThreads provided that (1) there is no more than one connection
 ** per database file in the same process and (2) database connections
 ** do not move across threads.
 */
@@ -33898,7 +34860,7 @@ struct unixFileId {
   /* We are told that some versions of Android contain a bug that
   ** sizes ino_t at only 32-bits instead of 64-bits. (See
   ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
-  ** To work around this, always allocate 64-bits for the inode number.  
+  ** To work around this, always allocate 64-bits for the inode number.
   ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
   ** but that should not be a big deal. */
   /* WAS:  ino_t ino;   */
@@ -33986,7 +34948,7 @@ int unixFileMutexNotheld(unixFile *pFile){
 ** strerror_r().
 **
 ** The first argument passed to the macro should be the error code that
-** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
+** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
 ** The two subsequent arguments should be the name of the OS function that
 ** failed (e.g. "unlink", "open") and the associated file-system path,
 ** if any.
@@ -34004,7 +34966,7 @@ static int unixLogErrorAtLine(
   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
   ** the strerror() function to obtain the human-readable error message
   ** equivalent to errno. Otherwise, use strerror_r().
-  */ 
+  */
 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
   char aErr[80];
   memset(aErr, 0, sizeof(aErr));
@@ -34012,18 +34974,18 @@ static int unixLogErrorAtLine(
 
   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
   ** assume that the system provides the GNU version of strerror_r() that
-  ** returns a pointer to a buffer containing the error message. That pointer 
-  ** may point to aErr[], or it may point to some static storage somewhere. 
-  ** Otherwise, assume that the system provides the POSIX version of 
+  ** returns a pointer to a buffer containing the error message. That pointer
+  ** may point to aErr[], or it may point to some static storage somewhere.
+  ** Otherwise, assume that the system provides the POSIX version of
   ** strerror_r(), which always writes an error message into aErr[].
   **
   ** If the code incorrectly assumes that it is the POSIX version that is
   ** available, the error message will often be an empty string. Not a
-  ** huge problem. Incorrectly concluding that the GNU version is available 
+  ** huge problem. Incorrectly concluding that the GNU version is available
   ** could lead to a segfault though.
   */
 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
-  zErr = 
+  zErr =
 # endif
   strerror_r(iErrno, aErr, sizeof(aErr)-1);
 
@@ -34074,7 +35036,7 @@ static void storeLastErrno(unixFile *pFile, int error){
 
 /*
 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
-*/ 
+*/
 static void closePendingFds(unixFile *pFile){
   unixInodeInfo *pInode = pFile->pInode;
   UnixUnusedFd *p;
@@ -34229,7 +35191,7 @@ static int fileHasMoved(unixFile *pFile){
 #else
   struct stat buf;
   return pFile->pInode!=0 &&
-      (osStat(pFile->zPath, &buf)!=0 
+      (osStat(pFile->zPath, &buf)!=0
          || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
 #endif
 }
@@ -34310,7 +35272,7 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
     }
   }
 #endif
-  
+
   sqlite3_mutex_leave(pFile->pInode->pLockMutex);
   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
 
@@ -34318,6 +35280,9 @@ static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
   return rc;
 }
 
+/* Forward declaration*/
+static int unixSleep(sqlite3_vfs*,int);
+
 /*
 ** Set a posix-advisory-lock.
 **
@@ -34339,16 +35304,17 @@ static int osSetPosixAdvisoryLock(
   struct flock *pLock,  /* The description of the lock */
   unixFile *pFile       /* Structure holding timeout value */
 ){
+  int tm = pFile->iBusyTimeout;
   int rc = osFcntl(h,F_SETLK,pLock);
-  while( rc<0 && pFile->iBusyTimeout>0 ){
+  while( rc<0 && tm>0 ){
     /* On systems that support some kind of blocking file lock with a timeout,
     ** make appropriate changes here to invoke that blocking file lock.  On
     ** generic posix, however, there is no such API.  So we simply try the
     ** lock once every millisecond until either the timeout expires, or until
     ** the lock is obtained. */
-    usleep(1000);
+    unixSleep(0,1000);
     rc = osFcntl(h,F_SETLK,pLock);
-    pFile->iBusyTimeout--;
+    tm--;
   }
   return rc;
 }
@@ -34356,7 +35322,7 @@ static int osSetPosixAdvisoryLock(
 
 
 /*
-** Attempt to set a system-lock on the file pFile.  The lock is 
+** Attempt to set a system-lock on the file pFile.  The lock is
 ** described by pLock.
 **
 ** If the pFile was opened read/write from unix-excl, then the only lock
@@ -34448,7 +35414,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
   **
   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
   ** A RESERVED lock is implemented by grabbing a write-lock on the
-  ** 'reserved byte'. 
+  ** 'reserved byte'.
   **
   ** A process may only obtain a PENDING lock after it has obtained a
   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
@@ -34462,7 +35428,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
   ** implemented by obtaining a write-lock on the entire 'shared byte
   ** range'. Since all other locks require a read-lock on one of the bytes
   ** within this range, this ensures that no other locks are held on the
-  ** database. 
+  ** database.
   */
   int rc = SQLITE_OK;
   unixFile *pFile = (unixFile*)id;
@@ -34503,7 +35469,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
   /* If some thread using this PID has a lock via a different unixFile*
   ** handle that precludes the requested lock, return BUSY.
   */
-  if( (pFile->eFileLock!=pInode->eFileLock && 
+  if( (pFile->eFileLock!=pInode->eFileLock &&
           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
   ){
     rc = SQLITE_BUSY;
@@ -34514,7 +35480,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
   ** has a SHARED or RESERVED lock, then increment reference counts and
   ** return SQLITE_OK.
   */
-  if( eFileLock==SHARED_LOCK && 
+  if( eFileLock==SHARED_LOCK &&
       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
     assert( eFileLock==SHARED_LOCK );
     assert( pFile->eFileLock==0 );
@@ -34532,7 +35498,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
   */
   lock.l_len = 1L;
   lock.l_whence = SEEK_SET;
-  if( eFileLock==SHARED_LOCK 
+  if( eFileLock==SHARED_LOCK
       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   ){
     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
@@ -34571,7 +35537,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
       /* This could happen with a network mount */
       tErrno = errno;
-      rc = SQLITE_IOERR_UNLOCK; 
+      rc = SQLITE_IOERR_UNLOCK;
     }
 
     if( rc ){
@@ -34613,7 +35579,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
       }
     }
   }
-  
+
 
 #ifdef SQLITE_DEBUG
   /* Set up the transaction-counter change checking flags when
@@ -34642,7 +35608,7 @@ static int unixLock(sqlite3_file *id, int eFileLock){
 
 end_lock:
   sqlite3_mutex_leave(pInode->pLockMutex);
-  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
+  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
       rc==SQLITE_OK ? "ok" : "failed"));
   return rc;
 }
@@ -34667,11 +35633,11 @@ static void setPendingFd(unixFile *pFile){
 **
 ** If the locking level of the file descriptor is already at or below
 ** the requested locking level, this routine is a no-op.
-** 
+**
 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
 ** the byte range is divided into 2 parts and the first part is unlocked then
-** set to a read lock, then the other part is simply unlocked.  This works 
-** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
+** set to a read lock, then the other part is simply unlocked.  This works
+** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
 ** remove the write lock on a region when a read lock is set.
 */
 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
@@ -34709,7 +35675,7 @@ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
 
     /* downgrading to a shared lock on NFS involves clearing the write lock
     ** before establishing the readlock - to avoid a race condition we downgrade
-    ** the lock in 2 blocks, so that part of the range will be covered by a 
+    ** the lock in 2 blocks, so that part of the range will be covered by a
     ** write lock until the rest is covered by a read lock:
     **  1:   [WWWWW]
     **  2:   [....W]
@@ -34725,7 +35691,7 @@ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
       if( handleNFSUnlock ){
         int tErrno;               /* Error code from system call errors */
         off_t divSize = SHARED_SIZE - 1;
-        
+
         lock.l_type = F_UNLCK;
         lock.l_whence = SEEK_SET;
         lock.l_start = SHARED_FIRST;
@@ -34767,11 +35733,11 @@ static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
         lock.l_len = SHARED_SIZE;
         if( unixFileLock(pFile, &lock) ){
           /* In theory, the call to unixFileLock() cannot fail because another
-          ** process is holding an incompatible lock. If it does, this 
+          ** process is holding an incompatible lock. If it does, this
           ** indicates that the other process is not following the locking
           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
-          ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
-          ** an assert to fail). */ 
+          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
+          ** an assert to fail). */
           rc = SQLITE_IOERR_RDLOCK;
           storeLastErrno(pFile, errno);
           goto end_unlock;
@@ -34847,7 +35813,7 @@ static void unixUnmapfile(unixFile *pFd);
 #endif
 
 /*
-** This function performs the parts of the "close file" operation 
+** This function performs the parts of the "close file" operation
 ** common to all locking schemes. It closes the directory and file
 ** handles, if they are valid, and sets all fields of the unixFile
 ** structure to 0.
@@ -34910,13 +35876,14 @@ static int unixClose(sqlite3_file *id){
   if( pInode->nLock ){
     /* If there are outstanding locks, do not actually close the file just
     ** yet because that would clear those locks.  Instead, add the file
-    ** descriptor to pInode->pUnused list.  It will be automatically closed 
+    ** descriptor to pInode->pUnused list.  It will be automatically closed
     ** when the last lock is cleared.
     */
     setPendingFd(pFile);
   }
   sqlite3_mutex_leave(pInode->pLockMutex);
   releaseInodeInfo(pFile);
+  assert( pFile->pShm==0 );
   rc = closeUnixFile(id);
   unixLeaveMutex();
   return rc;
@@ -35010,7 +35977,7 @@ static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
   unixFile *pFile = (unixFile*)id;
 
   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-  
+
   assert( pFile );
   reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
@@ -35064,7 +36031,7 @@ static int dotlockLock(sqlite3_file *id, int eFileLock) {
 #endif
     return SQLITE_OK;
   }
-  
+
   /* grab an exclusive lock */
   rc = osMkdir(zLockFile, 0777);
   if( rc<0 ){
@@ -35079,8 +36046,8 @@ static int dotlockLock(sqlite3_file *id, int eFileLock) {
       }
     }
     return rc;
-  } 
-  
+  }
+
   /* got it, set the type and return ok */
   pFile->eFileLock = eFileLock;
   return rc;
@@ -35104,7 +36071,7 @@ static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
            pFile->eFileLock, osGetpid(0)));
   assert( eFileLock<=SHARED_LOCK );
-  
+
   /* no-op if possible */
   if( pFile->eFileLock==eFileLock ){
     return SQLITE_OK;
@@ -35117,7 +36084,7 @@ static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
     pFile->eFileLock = SHARED_LOCK;
     return SQLITE_OK;
   }
-  
+
   /* To fully unlock the database, delete the lock file */
   assert( eFileLock==NO_LOCK );
   rc = osRmdir(zLockFile);
@@ -35129,7 +36096,7 @@ static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
       rc = SQLITE_IOERR_UNLOCK;
       storeLastErrno(pFile, tErrno);
     }
-    return rc; 
+    return rc;
   }
   pFile->eFileLock = NO_LOCK;
   return SQLITE_OK;
@@ -35176,7 +36143,7 @@ static int robust_flock(int fd, int op){
 #else
 # define robust_flock(a,b) flock(a,b)
 #endif
-     
+
 
 /*
 ** This routine checks if there is a RESERVED lock held on the specified
@@ -35188,16 +36155,16 @@ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
   int rc = SQLITE_OK;
   int reserved = 0;
   unixFile *pFile = (unixFile*)id;
-  
+
   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-  
+
   assert( pFile );
-  
+
   /* Check if a thread in this process holds such a lock */
   if( pFile->eFileLock>SHARED_LOCK ){
     reserved = 1;
   }
-  
+
   /* Otherwise see if some other process holds it. */
   if( !reserved ){
     /* attempt to get the lock */
@@ -35208,7 +36175,7 @@ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
       if ( lrc ) {
         int tErrno = errno;
         /* unlock failed with an error */
-        lrc = SQLITE_IOERR_UNLOCK; 
+        lrc = SQLITE_IOERR_UNLOCK;
         storeLastErrno(pFile, tErrno);
         rc = lrc;
       }
@@ -35216,7 +36183,7 @@ static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
       int tErrno = errno;
       reserved = 1;
       /* someone else might have it reserved */
-      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
+      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
       if( IS_LOCK_ERROR(lrc) ){
         storeLastErrno(pFile, tErrno);
         rc = lrc;
@@ -35270,15 +36237,15 @@ static int flockLock(sqlite3_file *id, int eFileLock) {
 
   assert( pFile );
 
-  /* if we already have a lock, it is exclusive.  
+  /* if we already have a lock, it is exclusive.
   ** Just adjust level and punt on outta here. */
   if (pFile->eFileLock > NO_LOCK) {
     pFile->eFileLock = eFileLock;
     return SQLITE_OK;
   }
-  
+
   /* grab an exclusive lock */
-  
+
   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
     int tErrno = errno;
     /* didn't get, must be busy */
@@ -35290,7 +36257,7 @@ static int flockLock(sqlite3_file *id, int eFileLock) {
     /* got it, set the type and return ok */
     pFile->eFileLock = eFileLock;
   }
-  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
+  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
            rc==SQLITE_OK ? "ok" : "failed"));
 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
   if( (rc & 0xff) == SQLITE_IOERR ){
@@ -35310,23 +36277,23 @@ static int flockLock(sqlite3_file *id, int eFileLock) {
 */
 static int flockUnlock(sqlite3_file *id, int eFileLock) {
   unixFile *pFile = (unixFile*)id;
-  
+
   assert( pFile );
   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
            pFile->eFileLock, osGetpid(0)));
   assert( eFileLock<=SHARED_LOCK );
-  
+
   /* no-op if possible */
   if( pFile->eFileLock==eFileLock ){
     return SQLITE_OK;
   }
-  
+
   /* shared can just be set because we always have an exclusive */
   if (eFileLock==SHARED_LOCK) {
     pFile->eFileLock = eFileLock;
     return SQLITE_OK;
   }
-  
+
   /* no, really, unlock. */
   if( robust_flock(pFile->h, LOCK_UN) ){
 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
@@ -35377,14 +36344,14 @@ static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
   unixFile *pFile = (unixFile*)id;
 
   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-  
+
   assert( pFile );
 
   /* Check if a thread in this process holds such a lock */
   if( pFile->eFileLock>SHARED_LOCK ){
     reserved = 1;
   }
-  
+
   /* Otherwise see if some other process holds it. */
   if( !reserved ){
     sem_t *pSem = pFile->pInode->pSem;
@@ -35443,14 +36410,14 @@ static int semXLock(sqlite3_file *id, int eFileLock) {
   sem_t *pSem = pFile->pInode->pSem;
   int rc = SQLITE_OK;
 
-  /* if we already have a lock, it is exclusive.  
+  /* if we already have a lock, it is exclusive.
   ** Just adjust level and punt on outta here. */
   if (pFile->eFileLock > NO_LOCK) {
     pFile->eFileLock = eFileLock;
     rc = SQLITE_OK;
     goto sem_end_lock;
   }
-  
+
   /* lock semaphore now but bail out when already locked. */
   if( sem_trywait(pSem)==-1 ){
     rc = SQLITE_BUSY;
@@ -35480,18 +36447,18 @@ static int semXUnlock(sqlite3_file *id, int eFileLock) {
   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
            pFile->eFileLock, osGetpid(0)));
   assert( eFileLock<=SHARED_LOCK );
-  
+
   /* no-op if possible */
   if( pFile->eFileLock==eFileLock ){
     return SQLITE_OK;
   }
-  
+
   /* shared can just be set because we always have an exclusive */
   if (eFileLock==SHARED_LOCK) {
     pFile->eFileLock = eFileLock;
     return SQLITE_OK;
   }
-  
+
   /* no, really unlock. */
   if ( sem_post(pSem)==-1 ) {
     int rc, tErrno = errno;
@@ -35499,7 +36466,7 @@ static int semXUnlock(sqlite3_file *id, int eFileLock) {
     if( IS_LOCK_ERROR(rc) ){
       storeLastErrno(pFile, tErrno);
     }
-    return rc; 
+    return rc;
   }
   pFile->eFileLock = NO_LOCK;
   return SQLITE_OK;
@@ -35565,7 +36532,7 @@ struct ByteRangeLockPB2
 /*
 ** This is a utility for setting or clearing a bit-range lock on an
 ** AFP filesystem.
-** 
+**
 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
 */
 static int afpSetLock(
@@ -35577,14 +36544,14 @@ static int afpSetLock(
 ){
   struct ByteRangeLockPB2 pb;
   int err;
-  
+
   pb.unLockFlag = setLockFlag ? 0 : 1;
   pb.startEndFlag = 0;
   pb.offset = offset;
-  pb.length = length; 
+  pb.length = length;
   pb.fd = pFile->h;
-  
-  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
+
+  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
     offset, length));
   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
@@ -35619,9 +36586,9 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   int reserved = 0;
   unixFile *pFile = (unixFile*)id;
   afpLockingContext *context;
-  
+
   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
-  
+
   assert( pFile );
   context = (afpLockingContext *) pFile->lockingContext;
   if( context->reserved ){
@@ -35633,12 +36600,12 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
   if( pFile->pInode->eFileLock>SHARED_LOCK ){
     reserved = 1;
   }
-  
+
   /* Otherwise see if some other process holds it.
    */
   if( !reserved ){
     /* lock the RESERVED byte */
-    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
+    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
     if( SQLITE_OK==lrc ){
       /* if we succeeded in taking the reserved lock, unlock it to restore
       ** the original state */
@@ -35651,10 +36618,10 @@ static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
       rc=lrc;
     }
   }
-  
+
   sqlite3_mutex_leave(pFile->pInode->pLockMutex);
   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
-  
+
   *pResOut = reserved;
   return rc;
 }
@@ -35688,7 +36655,7 @@ static int afpLock(sqlite3_file *id, int eFileLock){
   unixFile *pFile = (unixFile*)id;
   unixInodeInfo *pInode = pFile->pInode;
   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
-  
+
   assert( pFile );
   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
@@ -35712,7 +36679,7 @@ static int afpLock(sqlite3_file *id, int eFileLock){
   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
   assert( eFileLock!=PENDING_LOCK );
   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
-  
+
   /* This mutex is needed because pFile->pInode is shared across threads
   */
   pInode = pFile->pInode;
@@ -35721,18 +36688,18 @@ static int afpLock(sqlite3_file *id, int eFileLock){
   /* If some thread using this PID has a lock via a different unixFile*
   ** handle that precludes the requested lock, return BUSY.
   */
-  if( (pFile->eFileLock!=pInode->eFileLock && 
+  if( (pFile->eFileLock!=pInode->eFileLock &&
        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
      ){
     rc = SQLITE_BUSY;
     goto afp_end_lock;
   }
-  
+
   /* If a SHARED lock is requested, and some thread using this PID already
   ** has a SHARED or RESERVED lock, then increment reference counts and
   ** return SQLITE_OK.
   */
-  if( eFileLock==SHARED_LOCK && 
+  if( eFileLock==SHARED_LOCK &&
      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
     assert( eFileLock==SHARED_LOCK );
     assert( pFile->eFileLock==0 );
@@ -35742,12 +36709,12 @@ static int afpLock(sqlite3_file *id, int eFileLock){
     pInode->nLock++;
     goto afp_end_lock;
   }
-    
+
   /* A PENDING lock is needed before acquiring a SHARED lock and before
   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
   ** be released.
   */
-  if( eFileLock==SHARED_LOCK 
+  if( eFileLock==SHARED_LOCK
       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
   ){
     int failed;
@@ -35757,30 +36724,30 @@ static int afpLock(sqlite3_file *id, int eFileLock){
       goto afp_end_lock;
     }
   }
-  
+
   /* If control gets to this point, then actually go ahead and make
   ** operating system calls for the specified lock.
   */
   if( eFileLock==SHARED_LOCK ){
     int lrc1, lrc2, lrc1Errno = 0;
     long lk, mask;
-    
+
     assert( pInode->nShared==0 );
     assert( pInode->eFileLock==0 );
-        
+
     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
     /* Now get the read-lock SHARED_LOCK */
     /* note that the quality of the randomness doesn't matter that much */
-    lk = random(); 
+    lk = random();
     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
-    lrc1 = afpSetLock(context->dbPath, pFile, 
+    lrc1 = afpSetLock(context->dbPath, pFile,
           SHARED_FIRST+pInode->sharedByte, 1, 1);
     if( IS_LOCK_ERROR(lrc1) ){
       lrc1Errno = pFile->lastErrno;
     }
     /* Drop the temporary PENDING lock */
     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
-    
+
     if( IS_LOCK_ERROR(lrc1) ) {
       storeLastErrno(pFile, lrc1Errno);
       rc = lrc1;
@@ -35815,34 +36782,34 @@ static int afpLock(sqlite3_file *id, int eFileLock){
     }
     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
       /* Acquire an EXCLUSIVE lock */
-        
-      /* Remove the shared lock before trying the range.  we'll need to 
+
+      /* Remove the shared lock before trying the range.  we'll need to
       ** reestablish the shared lock if we can't get the  afpUnlock
       */
       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
                          pInode->sharedByte, 1, 0)) ){
         int failed2 = SQLITE_OK;
         /* now attemmpt to get the exclusive lock range */
-        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
+        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
                                SHARED_SIZE, 1);
-        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
+        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
           ** a critical I/O error
           */
-          rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 : 
+          rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
                SQLITE_IOERR_LOCK;
           goto afp_end_lock;
-        } 
+        }
       }else{
-        rc = failed; 
+        rc = failed;
       }
     }
     if( failed ){
       rc = failed;
     }
   }
-  
+
   if( rc==SQLITE_OK ){
     pFile->eFileLock = eFileLock;
     pInode->eFileLock = eFileLock;
@@ -35850,10 +36817,10 @@ static int afpLock(sqlite3_file *id, int eFileLock){
     pFile->eFileLock = PENDING_LOCK;
     pInode->eFileLock = PENDING_LOCK;
   }
-  
+
 afp_end_lock:
   sqlite3_mutex_leave(pInode->pLockMutex);
-  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
+  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
          rc==SQLITE_OK ? "ok" : "failed"));
   return rc;
 }
@@ -35892,7 +36859,7 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
     SimulateIOErrorBenign(1);
     SimulateIOError( h=(-1) )
     SimulateIOErrorBenign(0);
-    
+
 #ifdef SQLITE_DEBUG
     /* When reducing a lock such that other processes can start
     ** reading the database file again, make sure that the
@@ -35907,7 +36874,7 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
            || pFile->transCntrChng==1 );
     pFile->inNormalWrite = 0;
 #endif
-    
+
     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
@@ -35920,11 +36887,11 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
     }
     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
-    } 
+    }
     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
-      if( !rc ){ 
-        context->reserved = 0; 
+      if( !rc ){
+        context->reserved = 0;
       }
     }
     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
@@ -35957,7 +36924,7 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
       if( pInode->nLock==0 ) closePendingFds(pFile);
     }
   }
-  
+
   sqlite3_mutex_leave(pInode->pLockMutex);
   if( rc==SQLITE_OK ){
     pFile->eFileLock = eFileLock;
@@ -35966,7 +36933,7 @@ static int afpUnlock(sqlite3_file *id, int eFileLock) {
 }
 
 /*
-** Close a file & cleanup AFP specific locking context 
+** Close a file & cleanup AFP specific locking context
 */
 static int afpClose(sqlite3_file *id) {
   int rc = SQLITE_OK;
@@ -36024,7 +36991,7 @@ static int nfsUnlock(sqlite3_file *id, int eFileLock){
 /*
 ** The code above is the NFS lock implementation.  The code is specific
 ** to MacOSX and does not work on other unix platforms.  No alternative
-** is available.  
+** is available.
 **
 ********************* End of the NFS lock implementation **********************
 ******************************************************************************/
@@ -36032,7 +36999,7 @@ static int nfsUnlock(sqlite3_file *id, int eFileLock){
 /******************************************************************************
 **************** Non-locking sqlite3_file methods *****************************
 **
-** The next division contains implementations for all methods of the 
+** The next division contains implementations for all methods of the
 ** sqlite3_file object other than the locking methods.  The locking
 ** methods were defined in divisions above (one locking method per
 ** division).  Those methods that are common to all locking modes
@@ -36040,7 +37007,7 @@ static int nfsUnlock(sqlite3_file *id, int eFileLock){
 */
 
 /*
-** Seek to the offset passed as the second argument, then read cnt 
+** Seek to the offset passed as the second argument, then read cnt
 ** bytes into pBuf. Return the number of bytes actually read.
 **
 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
@@ -36102,8 +37069,8 @@ static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
 ** wrong.
 */
 static int unixRead(
-  sqlite3_file *id, 
-  void *pBuf, 
+  sqlite3_file *id,
+  void *pBuf,
   int amt,
   sqlite3_int64 offset
 ){
@@ -36113,12 +37080,12 @@ static int unixRead(
   assert( offset>=0 );
   assert( amt>0 );
 
-  /* If this is a database file (not a journal, master-journal or temp
+  /* If this is a database file (not a journal, super-journal or temp
   ** file), the bytes in the locking range should never be read or written. */
 #if 0
   assert( pFile->pPreallocatedUnused==0
        || offset>=PENDING_BYTE+512
-       || offset+amt<=PENDING_BYTE 
+       || offset+amt<=PENDING_BYTE
   );
 #endif
 
@@ -36143,7 +37110,24 @@ static int unixRead(
   if( got==amt ){
     return SQLITE_OK;
   }else if( got<0 ){
-    /* lastErrno set by seekAndRead */
+    /* pFile->lastErrno has been set by seekAndRead().
+    ** Usually we return SQLITE_IOERR_READ here, though for some
+    ** kinds of errors we return SQLITE_IOERR_CORRUPTFS.  The
+    ** SQLITE_IOERR_CORRUPTFS will be converted into SQLITE_CORRUPT
+    ** prior to returning to the application by the sqlite3ApiExit()
+    ** routine.
+    */
+    switch( pFile->lastErrno ){
+      case ERANGE:
+      case EIO:
+#ifdef ENXIO
+      case ENXIO:
+#endif
+#ifdef EDEVERR
+      case EDEVERR:
+#endif
+        return SQLITE_IOERR_CORRUPTFS;
+    }
     return SQLITE_IOERR_READ;
   }else{
     storeLastErrno(pFile, 0);   /* not a system error */
@@ -36156,7 +37140,7 @@ static int unixRead(
 /*
 ** Attempt to seek the file-descriptor passed as the first argument to
 ** absolute offset iOff, then attempt to write nBuf bytes of data from
-** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
+** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
 ** return the actual number of bytes written (which may be less than
 ** nBuf).
 */
@@ -36216,22 +37200,22 @@ static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
 ** or some other error code on failure.
 */
 static int unixWrite(
-  sqlite3_file *id, 
-  const void *pBuf, 
+  sqlite3_file *id,
+  const void *pBuf,
   int amt,
-  sqlite3_int64 offset 
+  sqlite3_int64 offset
 ){
   unixFile *pFile = (unixFile*)id;
   int wrote = 0;
   assert( id );
   assert( amt>0 );
 
-  /* If this is a database file (not a journal, master-journal or temp
+  /* If this is a database file (not a journal, super-journal or temp
   ** file), the bytes in the locking range should never be read or written. */
 #if 0
   assert( pFile->pPreallocatedUnused==0
        || offset>=PENDING_BYTE+512
-       || offset+amt<=PENDING_BYTE 
+       || offset+amt<=PENDING_BYTE
   );
 #endif
 
@@ -36273,7 +37257,7 @@ static int unixWrite(
     }
   }
 #endif
+
   while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
     amt -= wrote;
     offset += wrote;
@@ -36343,8 +37327,8 @@ SQLITE_API int sqlite3_fullsync_count = 0;
 **
 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
 ** The idea behind dataOnly is that it should only write the file content
-** to disk, not the inode.  We only set dataOnly if the file size is 
-** unchanged since the file size is part of the inode.  However, 
+** to disk, not the inode.  We only set dataOnly if the file size is
+** unchanged since the file size is part of the inode.  However,
 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
 ** file size has changed.  The only real difference between fdatasync()
 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
@@ -36358,7 +37342,7 @@ static int full_fsync(int fd, int fullSync, int dataOnly){
   int rc;
 
   /* The following "ifdef/elif/else/" block has the same structure as
-  ** the one below. It is replicated here solely to avoid cluttering 
+  ** the one below. It is replicated here solely to avoid cluttering
   ** up the real code with the UNUSED_PARAMETER() macros.
   */
 #ifdef SQLITE_NO_SYNC
@@ -36372,7 +37356,7 @@ static int full_fsync(int fd, int fullSync, int dataOnly){
   UNUSED_PARAMETER(dataOnly);
 #endif
 
-  /* Record the number of times that we do a normal fsync() and 
+  /* Record the number of times that we do a normal fsync() and
   ** FULLSYNC.  This is used during testing to verify that this procedure
   ** gets called with the correct arguments.
   */
@@ -36398,11 +37382,11 @@ static int full_fsync(int fd, int fullSync, int dataOnly){
     rc = 1;
   }
   /* If the FULLFSYNC failed, fall back to attempting an fsync().
-  ** It shouldn't be possible for fullfsync to fail on the local 
+  ** It shouldn't be possible for fullfsync to fail on the local
   ** file system (on OSX), so failure indicates that FULLFSYNC
-  ** isn't supported for this file system. So, attempt an fsync 
-  ** and (for now) ignore the overhead of a superfluous fcntl call.  
-  ** It'd be better to detect fullfsync support once and avoid 
+  ** isn't supported for this file system. So, attempt an fsync
+  ** and (for now) ignore the overhead of a superfluous fcntl call.
+  ** It'd be better to detect fullfsync support once and avoid
   ** the fcntl call every time sync is called.
   */
   if( rc ) rc = fsync(fd);
@@ -36412,7 +37396,7 @@ static int full_fsync(int fd, int fullSync, int dataOnly){
   ** so currently we default to the macro that redefines fdatasync to fsync
   */
   rc = fsync(fd);
-#else 
+#else
   rc = fdatasync(fd);
 #if OS_VXWORKS
   if( rc==-1 && errno==ENOTSUP ){
@@ -36573,7 +37557,7 @@ static int unixTruncate(sqlite3_file *id, i64 nByte){
 #if SQLITE_MAX_MMAP_SIZE>0
     /* If the file was just truncated to a size smaller than the currently
     ** mapped region, reduce the effective mapping size as well. SQLite will
-    ** use read() and write() to access data beyond this point from now on.  
+    ** use read() and write() to access data beyond this point from now on.
     */
     if( nByte<pFile->mmapSize ){
       pFile->mmapSize = nByte;
@@ -36619,8 +37603,8 @@ static int unixFileSize(sqlite3_file *id, i64 *pSize){
 static int proxyFileControl(sqlite3_file*,int,void*);
 #endif
 
-/* 
-** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
+/*
+** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
 ** file-control operation.  Enlarge the database to nBytes in size
 ** (rounded up to the next chunk-size).  If the database is already
 ** nBytes or larger, this routine is a no-op.
@@ -36629,7 +37613,7 @@ static int fcntlSizeHint(unixFile *pFile, i64 nByte){
   if( pFile->szChunk>0 ){
     i64 nSize;                    /* Required file size */
     struct stat buf;              /* Used to hold return values of fstat() */
-   
+
     if( osFstat(pFile->h, &buf) ){
       return SQLITE_IOERR_FSTAT;
     }
@@ -36638,8 +37622,8 @@ static int fcntlSizeHint(unixFile *pFile, i64 nByte){
     if( nSize>(i64)buf.st_size ){
 
 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
-      /* The code below is handling the return value of osFallocate() 
-      ** correctly. posix_fallocate() is defined to "returns zero on success, 
+      /* The code below is handling the return value of osFallocate()
+      ** correctly. posix_fallocate() is defined to "returns zero on success,
       ** or an error number on  failure". See the manpage for details. */
       int err;
       do{
@@ -36647,7 +37631,7 @@ static int fcntlSizeHint(unixFile *pFile, i64 nByte){
       }while( err==EINTR );
       if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
 #else
-      /* If the OS does not have posix_fallocate(), fake it. Write a 
+      /* If the OS does not have posix_fallocate(), fake it. Write a
       ** single byte to the last byte in each block that falls entirely
       ** within the extended region. Then, if required, a single byte
       ** at offset (nSize-1), to set the size of the file correctly.
@@ -36773,7 +37757,9 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){
     }
 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
     case SQLITE_FCNTL_LOCK_TIMEOUT: {
+      int iOld = pFile->iBusyTimeout;
       pFile->iBusyTimeout = *(int*)pArg;
+      *(int*)pArg = iOld;
       return SQLITE_OK;
     }
 #endif
@@ -36826,9 +37812,9 @@ static int unixFileControl(sqlite3_file *id, int op, void *pArg){
 
 /*
 ** If pFd->sectorSize is non-zero when this function is called, it is a
-** no-op. Otherwise, the values of pFd->sectorSize and 
-** pFd->deviceCharacteristics are set according to the file-system 
-** characteristics. 
+** no-op. Otherwise, the values of pFd->sectorSize and
+** pFd->deviceCharacteristics are set according to the file-system
+** characteristics.
 **
 ** There are two versions of this function. One for QNX and one for all
 ** other systems.
@@ -36862,7 +37848,7 @@ static void setDeviceCharacteristics(unixFile *pFd){
 static void setDeviceCharacteristics(unixFile *pFile){
   if( pFile->sectorSize == 0 ){
     struct statvfs fsInfo;
-       
+
     /* Set defaults for non-supported filesystems */
     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
     pFile->deviceCharacteristics = 0;
@@ -36971,7 +37957,7 @@ static int unixDeviceCharacteristics(sqlite3_file *id){
 /*
 ** Return the system page size.
 **
-** This function should not be called directly by other code in this file. 
+** This function should not be called directly by other code in this file.
 ** Instead, it should be called via macro osGetpagesize().
 */
 static int unixGetpagesize(void){
@@ -36989,7 +37975,7 @@ static int unixGetpagesize(void){
 #ifndef SQLITE_OMIT_WAL
 
 /*
-** Object used to represent an shared memory buffer.  
+** Object used to represent an shared memory buffer.
 **
 ** When multiple threads all reference the same wal-index, each thread
 ** has its own unixShm object, but they all point to a single instance
@@ -37009,7 +37995,7 @@ static int unixGetpagesize(void){
 **      nRef
 **
 ** The following fields are read-only after the object is created:
-** 
+**
 **      hShm
 **      zFilename
 **
@@ -37029,6 +38015,7 @@ struct unixShmNode {
   char **apRegion;           /* Array of mapped shared-memory regions */
   int nRef;                  /* Number of unixShm objects pointing to this */
   unixShm *pFirst;           /* All unixShm objects pointing to this */
+  int aLock[SQLITE_SHM_NLOCK];  /* # shared locks on slot, -1==excl lock */
 #ifdef SQLITE_DEBUG
   u8 exclMask;               /* Mask of exclusive locks held */
   u8 sharedMask;             /* Mask of shared locks held */
@@ -37092,13 +38079,20 @@ static int unixShmSystemLock(
   assert( n>=1 && n<=SQLITE_SHM_NLOCK );
 
   if( pShmNode->hShm>=0 ){
+    int res;
     /* Initialize the locking parameters */
     f.l_type = lockType;
     f.l_whence = SEEK_SET;
     f.l_start = ofst;
     f.l_len = n;
-    rc = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
-    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
+    res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
+    if( res==-1 ){
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+      rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
+#else
+      rc = SQLITE_BUSY;
+#endif
+    }
   }
 
   /* Update the global lock state and do debug tracing */
@@ -37136,7 +38130,7 @@ static int unixShmSystemLock(
   }
 #endif
 
-  return rc;        
+  return rc;
 }
 
 /*
@@ -37192,7 +38186,7 @@ static void unixShmPurge(unixFile *pFd){
 ** take it now. Return SQLITE_OK if successful, or an SQLite error
 ** code otherwise.
 **
-** If the DMS cannot be locked because this is a readonly_shm=1 
+** If the DMS cannot be locked because this is a readonly_shm=1
 ** connection and no other process already holds a lock, return
 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
 */
@@ -37203,7 +38197,7 @@ static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
   /* Use F_GETLK to determine the locks other processes are holding
   ** on the DMS byte. If it indicates that another process is holding
   ** a SHARED lock, then this process may also take a SHARED lock
-  ** and proceed with opening the *-shm file. 
+  ** and proceed with opening the *-shm file.
   **
   ** Or, if no other process is holding any lock, then this process
   ** is the first to open it. In this case take an EXCLUSIVE lock on the
@@ -37251,20 +38245,20 @@ static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
 }
 
 /*
-** Open a shared-memory area associated with open database file pDbFd.  
+** Open a shared-memory area associated with open database file pDbFd.
 ** This particular implementation uses mmapped files.
 **
 ** The file used to implement shared-memory is in the same directory
 ** as the open database file and has the same name as the open database
 ** file with the "-shm" suffix added.  For example, if the database file
 ** is "/home/user1/config.db" then the file that is created and mmapped
-** for shared memory will be called "/home/user1/config.db-shm".  
+** for shared memory will be called "/home/user1/config.db-shm".
 **
 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
 ** some other tmpfs mount. But if a file in a different directory
 ** from the database file is used, then differing access permissions
 ** or a chroot() might cause two different processes on the same
-** database to end up using different files for shared memory - 
+** database to end up using different files for shared memory -
 ** meaning that their memory would not really be shared - resulting
 ** in database corruption.  Nevertheless, this tmpfs file usage
 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
@@ -37334,7 +38328,7 @@ static int unixOpenSharedMemory(unixFile *pDbFd){
     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
     zShm = pShmNode->zFilename = (char*)&pShmNode[1];
 #ifdef SQLITE_SHM_DIRECTORY
-    sqlite3_snprintf(nShmFilename, zShm, 
+    sqlite3_snprintf(nShmFilename, zShm,
                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
                      (u32)sStat.st_ino, (u32)sStat.st_dev);
 #else
@@ -37354,10 +38348,12 @@ static int unixOpenSharedMemory(unixFile *pDbFd){
 
     if( pInode->bProcessLock==0 ){
       if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
-        pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT,(sStat.st_mode&0777));
+        pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
+                                     (sStat.st_mode&0777));
       }
       if( pShmNode->hShm<0 ){
-        pShmNode->hShm = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
+        pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
+                                     (sStat.st_mode&0777));
         if( pShmNode->hShm<0 ){
           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
           goto shm_open_err;
@@ -37407,22 +38403,22 @@ shm_open_err:
 }
 
 /*
-** This function is called to obtain a pointer to region iRegion of the 
-** shared-memory associated with the database file fd. Shared-memory regions 
-** are numbered starting from zero. Each shared-memory region is szRegion 
+** This function is called to obtain a pointer to region iRegion of the
+** shared-memory associated with the database file fd. Shared-memory regions
+** are numbered starting from zero. Each shared-memory region is szRegion
 ** bytes in size.
 **
 ** If an error occurs, an error code is returned and *pp is set to NULL.
 **
 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
 ** region has not been allocated (by any client, including one running in a
-** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
-** bExtend is non-zero and the requested shared-memory region has not yet 
+** separate process), then *pp is set to NULL and SQLITE_OK returned. If
+** bExtend is non-zero and the requested shared-memory region has not yet
 ** been allocated, it is allocated by this function.
 **
 ** If the shared-memory region has already been allocated or is allocated by
-** this call as described above, then it is mapped into this processes 
-** address space (if it is not already), *pp is set to point to the mapped 
+** this call as described above, then it is mapped into this processes
+** address space (if it is not already), *pp is set to point to the mapped
 ** memory and SQLITE_OK returned.
 */
 static int unixShmMap(
@@ -37477,7 +38473,7 @@ static int unixShmMap(
         rc = SQLITE_IOERR_SHMSIZE;
         goto shmpage_out;
       }
-  
+
       if( sStat.st_size<nByte ){
         /* The requested memory region does not exist. If bExtend is set to
         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
@@ -37526,7 +38522,7 @@ static int unixShmMap(
       void *pMem;
       if( pShmNode->hShm>=0 ){
         pMem = osMmap(0, nMap,
-            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
+            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
             MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
         );
         if( pMem==MAP_FAILED ){
@@ -37561,6 +38557,38 @@ shmpage_out:
 }
 
 /*
+** Check that the pShmNode->aLock[] array comports with the locking bitmasks
+** held by each client. Return true if it does, or false otherwise. This
+** is to be used in an assert(). e.g.
+**
+**     assert( assertLockingArrayOk(pShmNode) );
+*/
+#ifdef SQLITE_DEBUG
+static int assertLockingArrayOk(unixShmNode *pShmNode){
+  unixShm *pX;
+  int aLock[SQLITE_SHM_NLOCK];
+  assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
+
+  memset(aLock, 0, sizeof(aLock));
+  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
+    int i;
+    for(i=0; i<SQLITE_SHM_NLOCK; i++){
+      if( pX->exclMask & (1<<i) ){
+        assert( aLock[i]==0 );
+        aLock[i] = -1;
+      }else if( pX->sharedMask & (1<<i) ){
+        assert( aLock[i]>=0 );
+        aLock[i]++;
+      }
+    }
+  }
+
+  assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
+  return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
+}
+#endif
+
+/*
 ** Change the lock state for a shared-memory segment.
 **
 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
@@ -37576,10 +38604,10 @@ static int unixShmLock(
 ){
   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
-  unixShm *pX;                          /* For looping over all siblings */
   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
   int rc = SQLITE_OK;                   /* Result code */
   u16 mask;                             /* Mask of locks to take or release */
+  int *aLock = pShmNode->aLock;
 
   assert( pShmNode==pDbFd->pInode->pShmNode );
   assert( pShmNode->pInode==pDbFd->pInode );
@@ -37593,81 +38621,101 @@ static int unixShmLock(
   assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
   assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
 
+  /* Check that, if this to be a blocking lock, no locks that occur later
+  ** in the following list than the lock being obtained are already held:
+  **
+  **   1. Checkpointer lock (ofst==1).
+  **   2. Write lock (ofst==0).
+  **   3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
+  **
+  ** In other words, if this is a blocking lock, none of the locks that
+  ** occur later in the above list than the lock being obtained may be
+  ** held.
+  **
+  ** It is not permitted to block on the RECOVER lock.
+  */
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
+         (ofst!=2)                                   /* not RECOVER */
+      && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
+      && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
+      && (ofst<3  || (p->exclMask|p->sharedMask)<(1<<ofst))
+  ));
+#endif
+
   mask = (1<<(ofst+n)) - (1<<ofst);
   assert( n>1 || mask==(1<<ofst) );
   sqlite3_mutex_enter(pShmNode->pShmMutex);
+  assert( assertLockingArrayOk(pShmNode) );
   if( flags & SQLITE_SHM_UNLOCK ){
-    u16 allMask = 0; /* Mask of locks held by siblings */
-
-    /* See if any siblings hold this same lock */
-    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
-      if( pX==p ) continue;
-      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
-      allMask |= pX->sharedMask;
-    }
+    if( (p->exclMask|p->sharedMask) & mask ){
+      int ii;
+      int bUnlock = 1;
 
-    /* Unlock the system-level locks */
-    if( (mask & allMask)==0 ){
-      rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
-    }else{
-      rc = SQLITE_OK;
-    }
+      for(ii=ofst; ii<ofst+n; ii++){
+        if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
+          bUnlock = 0;
+        }
+      }
 
-    /* Undo the local locks */
-    if( rc==SQLITE_OK ){
-      p->exclMask &= ~mask;
-      p->sharedMask &= ~mask;
-    } 
-  }else if( flags & SQLITE_SHM_SHARED ){
-    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
+      if( bUnlock ){
+        rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
+        if( rc==SQLITE_OK ){
+          memset(&aLock[ofst], 0, sizeof(int)*n);
+        }
+      }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
+        assert( n==1 && aLock[ofst]>1 );
+        aLock[ofst]--;
+      }
 
-    /* Find out which shared locks are already held by sibling connections.
-    ** If any sibling already holds an exclusive lock, go ahead and return
-    ** SQLITE_BUSY.
-    */
-    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
-      if( (pX->exclMask & mask)!=0 ){
-        rc = SQLITE_BUSY;
-        break;
+      /* Undo the local locks */
+      if( rc==SQLITE_OK ){
+        p->exclMask &= ~mask;
+        p->sharedMask &= ~mask;
       }
-      allShared |= pX->sharedMask;
     }
-
-    /* Get shared locks at the system level, if necessary */
-    if( rc==SQLITE_OK ){
-      if( (allShared & mask)==0 ){
+  }else if( flags & SQLITE_SHM_SHARED ){
+    assert( n==1 );
+    assert( (p->exclMask & (1<<ofst))==0 );
+    if( (p->sharedMask & mask)==0 ){
+      if( aLock[ofst]<0 ){
+        rc = SQLITE_BUSY;
+      }else if( aLock[ofst]==0 ){
         rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
-      }else{
-        rc = SQLITE_OK;
       }
-    }
 
-    /* Get the local shared locks */
-    if( rc==SQLITE_OK ){
-      p->sharedMask |= mask;
+      /* Get the local shared locks */
+      if( rc==SQLITE_OK ){
+        p->sharedMask |= mask;
+        aLock[ofst]++;
+      }
     }
   }else{
     /* Make sure no sibling connections hold locks that will block this
-    ** lock.  If any do, return SQLITE_BUSY right away.
-    */
-    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
-      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
+    ** lock.  If any do, return SQLITE_BUSY right away.  */
+    int ii;
+    for(ii=ofst; ii<ofst+n; ii++){
+      assert( (p->sharedMask & mask)==0 );
+      if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
         rc = SQLITE_BUSY;
         break;
       }
     }
-  
-    /* Get the exclusive locks at the system level.  Then if successful
-    ** also mark the local connection as being locked.
-    */
+
+    /* Get the exclusive locks at the system level. Then if successful
+    ** also update the in-memory values. */
     if( rc==SQLITE_OK ){
       rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
       if( rc==SQLITE_OK ){
         assert( (p->sharedMask & mask)==0 );
         p->exclMask |= mask;
+        for(ii=ofst; ii<ofst+n; ii++){
+          aLock[ii] = -1;
+        }
       }
     }
   }
+  assert( assertLockingArrayOk(pShmNode) );
   sqlite3_mutex_leave(pShmNode->pShmMutex);
   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
            p->id, osGetpid(0), p->sharedMask, p->exclMask));
@@ -37675,7 +38723,7 @@ static int unixShmLock(
 }
 
 /*
-** Implement a memory barrier or memory fence on shared memory.  
+** Implement a memory barrier or memory fence on shared memory.
 **
 ** All loads and stores begun before the barrier must complete before
 ** any load or store begun after the barrier.
@@ -37685,15 +38733,15 @@ static void unixShmBarrier(
 ){
   UNUSED_PARAMETER(fd);
   sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
-  assert( fd->pMethods->xLock==nolockLock 
-       || unixFileMutexNotheld((unixFile*)fd) 
+  assert( fd->pMethods->xLock==nolockLock
+       || unixFileMutexNotheld((unixFile*)fd)
   );
   unixEnterMutex();               /* Also mutex, for redundancy */
   unixLeaveMutex();
 }
 
 /*
-** Close a connection to shared-memory.  Delete the underlying 
+** Close a connection to shared-memory.  Delete the underlying
 ** storage if deleteFlag is true.
 **
 ** If there is no shared memory associated with the connection then this
@@ -37767,7 +38815,7 @@ static void unixUnmapfile(unixFile *pFd){
 }
 
 /*
-** Attempt to set the size of the memory mapping maintained by file 
+** Attempt to set the size of the memory mapping maintained by file
 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
 **
 ** If successful, this function sets the following variables:
@@ -37859,14 +38907,14 @@ static void unixRemapfile(
 
 /*
 ** Memory map or remap the file opened by file-descriptor pFd (if the file
-** is already mapped, the existing mapping is replaced by the new). Or, if 
-** there already exists a mapping for this file, and there are still 
+** is already mapped, the existing mapping is replaced by the new). Or, if
+** there already exists a mapping for this file, and there are still
 ** outstanding xFetch() references to it, this function is a no-op.
 **
-** If parameter nByte is non-negative, then it is the requested size of 
-** the mapping to create. Otherwise, if nByte is less than zero, then the 
+** If parameter nByte is non-negative, then it is the requested size of
+** the mapping to create. Otherwise, if nByte is less than zero, then the
 ** requested size is the size of the file on disk. The actual size of the
-** created mapping is either the requested size or the value configured 
+** created mapping is either the requested size or the value configured
 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
 **
 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
@@ -37907,7 +38955,7 @@ static int unixMapfile(unixFile *pFd, i64 nMap){
 ** Finally, if an error does occur, return an SQLite error code. The final
 ** value of *pp is undefined in this case.
 **
-** If this function does return a pointer, the caller must eventually 
+** If this function does return a pointer, the caller must eventually
 ** release the reference by calling unixUnfetch().
 */
 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
@@ -37932,13 +38980,13 @@ static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
 }
 
 /*
-** If the third argument is non-NULL, then this function releases a 
+** If the third argument is non-NULL, then this function releases a
 ** reference obtained by an earlier call to unixFetch(). The second
 ** argument passed to this function must be the same as the corresponding
-** argument that was passed to the unixFetch() invocation. 
+** argument that was passed to the unixFetch() invocation.
 **
-** Or, if the third argument is NULL, then this function is being called 
-** to inform the VFS layer that, according to POSIX, any existing mapping 
+** Or, if the third argument is NULL, then this function is being called
+** to inform the VFS layer that, according to POSIX, any existing mapping
 ** may now be invalid and should be unmapped.
 */
 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
@@ -37946,7 +38994,7 @@ static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
   UNUSED_PARAMETER(iOff);
 
-  /* If p==0 (unmap the entire file) then there must be no outstanding 
+  /* If p==0 (unmap the entire file) then there must be no outstanding
   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
   ** then there must be at least one outstanding.  */
   assert( (p==0)==(pFd->nFetchOut==0) );
@@ -38167,8 +39215,8 @@ IOMETHODS(
 #endif
 
 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
-/* 
-** This "finder" function attempts to determine the best locking strategy 
+/*
+** This "finder" function attempts to determine the best locking strategy
 ** for the database file "filePath".  It then returns the sqlite3_io_methods
 ** object that implements that strategy.
 **
@@ -38210,8 +39258,8 @@ static const sqlite3_io_methods *autolockIoFinderImpl(
   }
 
   /* Default case. Handles, amongst others, "nfs".
-  ** Test byte-range lock using fcntl(). If the call succeeds, 
-  ** assume that the file-system supports POSIX style locks. 
+  ** Test byte-range lock using fcntl(). If the call succeeds,
+  ** assume that the file-system supports POSIX style locks.
   */
   lockInfo.l_len = 1;
   lockInfo.l_start = 0;
@@ -38227,7 +39275,7 @@ static const sqlite3_io_methods *autolockIoFinderImpl(
     return &dotlockIoMethods;
   }
 }
-static const sqlite3_io_methods 
+static const sqlite3_io_methods
   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
 
 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
@@ -38263,7 +39311,7 @@ static const sqlite3_io_methods *vxworksIoFinderImpl(
     return &semIoMethods;
   }
 }
-static const sqlite3_io_methods 
+static const sqlite3_io_methods
   *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
 
 #endif /* OS_VXWORKS */
@@ -38391,14 +39439,14 @@ static int fillInUnixFile(
         robust_close(pNew, h, __LINE__);
         h = -1;
       }
-      unixLeaveMutex();        
+      unixLeaveMutex();
     }
   }
 #endif
 
   else if( pLockingStyle == &dotlockIoMethods ){
     /* Dotfile locking uses the file path so it needs to be included in
-    ** the dotlockLockingContext 
+    ** the dotlockLockingContext
     */
     char *zLockFile;
     int nFilename;
@@ -38445,7 +39493,7 @@ static int fillInUnixFile(
     }
   }
 #endif
-  
+
   storeLastErrno(pNew, 0);
 #if OS_VXWORKS
   if( rc!=SQLITE_OK ){
@@ -38458,7 +39506,7 @@ static int fillInUnixFile(
   if( rc!=SQLITE_OK ){
     if( h>=0 ) robust_close(pNew, h, __LINE__);
   }else{
-    pNew->pMethod = pLockingStyle;
+    pId->pMethods = pLockingStyle;
     OpenCounter(+1);
     verifyDbFile(pNew);
   }
@@ -38513,7 +39561,7 @@ static int unixGetTempname(int nBuf, char *zBuf){
 
   /* It's odd to simulate an io-error here, but really this is just
   ** using the io-error infrastructure to test that SQLite handles this
-  ** function failing. 
+  ** function failing.
   */
   zBuf[0] = 0;
   SimulateIOError( return SQLITE_IOERR );
@@ -38542,8 +39590,8 @@ static int proxyTransformUnixFile(unixFile*, const char*);
 #endif
 
 /*
-** Search for an unused file descriptor that was opened on the database 
-** file (not a journal or master-journal file) identified by pathname
+** Search for an unused file descriptor that was opened on the database
+** file (not a journal or super-journal file) identified by pathname
 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
 ** argument to this function.
 **
@@ -38551,7 +39599,7 @@ static int proxyTransformUnixFile(unixFile*, const char*);
 ** but the associated file descriptor could not be closed because some
 ** other file descriptor open on the same file is holding a file-lock.
 ** Refer to comments in the unixClose() function and the lengthy comment
-** describing "Posix Advisory Locking" at the start of this file for 
+** describing "Posix Advisory Locking" at the start of this file for
 ** further details. Also, ticket #4018.
 **
 ** If a suitable file descriptor is found, then it is returned. If no
@@ -38562,8 +39610,8 @@ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
 
   /* Do not search for an unused file descriptor on vxworks. Not because
   ** vxworks would not benefit from the change (it might, we're not sure),
-  ** but because no way to test it is currently available. It is better 
-  ** not to risk breaking vxworks support for the sake of such an obscure 
+  ** but because no way to test it is currently available. It is better
+  ** not to risk breaking vxworks support for the sake of such an obscure
   ** feature.  */
 #if !OS_VXWORKS
   struct stat sStat;                   /* Results of stat() call */
@@ -38605,7 +39653,7 @@ static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
 }
 
 /*
-** Find the mode, uid and gid of file zFile. 
+** Find the mode, uid and gid of file zFile.
 */
 static int getFileMode(
   const char *zFile,              /* File name */
@@ -38629,16 +39677,16 @@ static int getFileMode(
 ** This function is called by unixOpen() to determine the unix permissions
 ** to create new files with. If no error occurs, then SQLITE_OK is returned
 ** and a value suitable for passing as the third argument to open(2) is
-** written to *pMode. If an IO error occurs, an SQLite error code is 
+** written to *pMode. If an IO error occurs, an SQLite error code is
 ** returned and the value of *pMode is not modified.
 **
 ** In most cases, this routine sets *pMode to 0, which will become
 ** an indication to robust_open() to create the file using
 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
-** But if the file being opened is a WAL or regular journal file, then 
-** this function queries the file-system for the permissions on the 
-** corresponding database file and sets *pMode to this value. Whenever 
-** possible, WAL and journal files are created using the same permissions 
+** But if the file being opened is a WAL or regular journal file, then
+** this function queries the file-system for the permissions on the
+** corresponding database file and sets *pMode to this value. Whenever
+** possible, WAL and journal files are created using the same permissions
 ** as the associated database file.
 **
 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
@@ -38670,14 +39718,14 @@ static int findCreateFileMode(
     **   "<path to db>-journalNN"
     **   "<path to db>-walNN"
     **
-    ** where NN is a decimal number. The NN naming schemes are 
+    ** where NN is a decimal number. The NN naming schemes are
     ** used by the test_multiplex.c module.
     */
-    nDb = sqlite3Strlen30(zPath) - 1; 
+    nDb = sqlite3Strlen30(zPath) - 1;
     while( zPath[nDb]!='-' ){
       /* In normal operation, the journal file name will always contain
       ** a '-' character.  However in 8+3 filename mode, or if a corrupt
-      ** rollback journal specifies a master journal with a goofy name, then
+      ** rollback journal specifies a super-journal with a goofy name, then
       ** the '-' might be missing. */
       if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
       nDb--;
@@ -38703,7 +39751,7 @@ static int findCreateFileMode(
 
 /*
 ** Open the file zPath.
-** 
+**
 ** Previously, the SQLite OS layer used three functions in place of this
 ** one:
 **
@@ -38714,13 +39762,13 @@ static int findCreateFileMode(
 ** These calls correspond to the following combinations of flags:
 **
 **     ReadWrite() ->     (READWRITE | CREATE)
-**     ReadOnly()  ->     (READONLY) 
+**     ReadOnly()  ->     (READONLY)
 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
 **
 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
 ** true, the file was configured to be automatically deleted when the
-** file handle closed. To achieve the same effect using this new 
-** interface, add the DELETEONCLOSE flag to those specified above for 
+** file handle closed. To achieve the same effect using this new
+** interface, add the DELETEONCLOSE flag to those specified above for
 ** OpenExclusive().
 */
 static int unixOpen(
@@ -38733,7 +39781,7 @@ static int unixOpen(
   unixFile *p = (unixFile *)pFile;
   int fd = -1;                   /* File descriptor returned by open() */
   int openFlags = 0;             /* Flags to pass to open() */
-  int eType = flags&0xFFFFFF00;  /* Type of file to open */
+  int eType = flags&0x0FFF00;  /* Type of file to open */
   int noLock;                    /* True to omit locking primitives */
   int rc = SQLITE_OK;            /* Function Return Code */
   int ctrlFlags = 0;             /* UNIXFILE_* flags */
@@ -38750,13 +39798,13 @@ static int unixOpen(
   struct statfs fsInfo;
 #endif
 
-  /* If creating a master or main-file journal, this function will open
+  /* If creating a super- or main-file journal, this function will open
   ** a file-descriptor on the directory too. The first time unixSync()
   ** is called the directory file descriptor will be fsync()ed and close()d.
   */
   int isNewJrnl = (isCreate && (
-        eType==SQLITE_OPEN_MASTER_JOURNAL 
-     || eType==SQLITE_OPEN_MAIN_JOURNAL 
+        eType==SQLITE_OPEN_SUPER_JOURNAL
+     || eType==SQLITE_OPEN_MAIN_JOURNAL
      || eType==SQLITE_OPEN_WAL
   ));
 
@@ -38766,9 +39814,9 @@ static int unixOpen(
   char zTmpname[MAX_PATHNAME+2];
   const char *zName = zPath;
 
-  /* Check the following statements are true: 
+  /* Check the following statements are true:
   **
-  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
+  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
   **   (b) if CREATE is set, then READWRITE must also be set, and
   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
@@ -38778,17 +39826,17 @@ static int unixOpen(
   assert(isExclusive==0 || isCreate);
   assert(isDelete==0 || isCreate);
 
-  /* The main DB, main journal, WAL file and master journal are never 
+  /* The main DB, main journal, WAL file and super-journal are never
   ** automatically deleted. Nor are they ever temporary files.  */
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
-  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
+  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 
   /* Assert that the upper layer has set one of the "file-type" flags. */
-  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
-       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
-       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
+  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
+       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
+       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_SUPER_JOURNAL
        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   );
 
@@ -38837,13 +39885,13 @@ static int unixOpen(
 
   /* Determine the value of the flags parameter passed to POSIX function
   ** open(). These must be calculated even if open() is not called, as
-  ** they may be stored as part of the file handle and used by the 
+  ** they may be stored as part of the file handle and used by the
   ** 'conch file' locking functions later on.  */
   if( isReadonly )  openFlags |= O_RDONLY;
   if( isReadWrite ) openFlags |= O_RDWR;
   if( isCreate )    openFlags |= O_CREAT;
   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
-  openFlags |= (O_LARGEFILE|O_BINARY);
+  openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
 
   if( fd<0 ){
     mode_t openMode;              /* Permissions to create file with */
@@ -38902,7 +39950,7 @@ static int unixOpen(
 
   if( p->pPreallocatedUnused ){
     p->pPreallocatedUnused->fd = fd;
-    p->pPreallocatedUnused->flags = 
+    p->pPreallocatedUnused->flags =
                           flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
   }
 
@@ -38924,7 +39972,7 @@ static int unixOpen(
     p->openFlags = openFlags;
   }
 #endif
-  
+
 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
   if( fstatfs(fd, &fsInfo) == -1 ){
     storeLastErrno(p, errno);
@@ -38955,7 +40003,7 @@ static int unixOpen(
     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
     int useProxy = 0;
 
-    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
+    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
     ** never use proxy, NULL means use proxy for non-local files only.  */
     if( envforce!=NULL ){
       useProxy = atoi(envforce)>0;
@@ -38967,9 +40015,9 @@ static int unixOpen(
       if( rc==SQLITE_OK ){
         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
         if( rc!=SQLITE_OK ){
-          /* Use unixClose to clean up the resources added in fillInUnixFile 
-          ** and clear all the structure's references.  Specifically, 
-          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
+          /* Use unixClose to clean up the resources added in fillInUnixFile
+          ** and clear all the structure's references.  Specifically,
+          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
           */
           unixClose(pFile);
           return rc;
@@ -38979,9 +40027,9 @@ static int unixOpen(
     }
   }
 #endif
-  
-  assert( zPath==0 || zPath[0]=='/' 
-      || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL 
+
+  assert( zPath==0 || zPath[0]=='/'
+      || eType==SQLITE_OPEN_SUPER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
   );
   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
 
@@ -39061,7 +40109,8 @@ static int unixAccess(
 
   if( flags==SQLITE_ACCESS_EXISTS ){
     struct stat buf;
-    *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
+    *pResOut = 0==osStat(zPath, &buf) &&
+                (!S_ISREG(buf.st_mode) || buf.st_size>0);
   }else{
     *pResOut = osAccess(zPath, W_OK|R_OK)==0;
   }
@@ -39069,7 +40118,26 @@ static int unixAccess(
 }
 
 /*
+** If the last component of the pathname in z[0]..z[j-1] is something
+** other than ".." then back it out and return true.  If the last
+** component is empty or if it is ".." then return false.
+*/
+static int unixBackupDir(const char *z, int *pJ){
+  int j = *pJ;
+  int i;
+  if( j<=0 ) return 0;
+  for(i=j-1; ALWAYS(i>0) && z[i-1]!='/'; i--){}
+  if( z[i]=='.' && i==j-2 && z[i+1]=='.' ) return 0;
+  *pJ = i-1;
+  return 1;
+}
+
+/*
+** Convert a relative pathname into a full pathname.  Also
+** simplify the pathname as follows:
 **
+**    Remove all instances of /./
+**    Remove all isntances of /X/../ for any X
 */
 static int mkFullPathname(
   const char *zPath,              /* Input path */
@@ -39078,6 +40146,7 @@ static int mkFullPathname(
 ){
   int nPath = sqlite3Strlen30(zPath);
   int iOff = 0;
+  int i, j;
   if( zPath[0]!='/' ){
     if( osGetcwd(zOut, nOut-2)==0 ){
       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
@@ -39092,15 +40161,50 @@ static int mkFullPathname(
     return SQLITE_CANTOPEN_BKPT;
   }
   sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
+
+  /* Remove duplicate '/' characters.  Except, two // at the beginning
+  ** of a pathname is allowed since this is important on windows. */
+  for(i=j=1; zOut[i]; i++){
+    zOut[j++] = zOut[i];
+    while( zOut[i]=='/' && zOut[i+1]=='/' ) i++;
+  }
+  zOut[j] = 0;
+
+  assert( zOut[0]=='/' );
+  for(i=j=0; zOut[i]; i++){
+    if( zOut[i]=='/' ){
+      /* Skip over internal "/." directory components */
+      if( zOut[i+1]=='.' && zOut[i+2]=='/' ){
+        i += 1;
+        continue;
+      }
+
+      /* If this is a "/.." directory component then back out the
+      ** previous term of the directory if it is something other than "..".
+      */
+      if( zOut[i+1]=='.'
+       && zOut[i+2]=='.'
+       && zOut[i+3]=='/'
+       && unixBackupDir(zOut, &j)
+      ){
+        i += 2;
+        continue;
+      }
+    }
+    if( ALWAYS(j>=0) ) zOut[j] = zOut[i];
+    j++;
+  }
+  if( NEVER(j==0) ) zOut[j++] = '/';
+  zOut[j] = 0;
   return SQLITE_OK;
 }
 
 /*
 ** Turn a relative pathname into a full pathname. The relative path
 ** is stored as a nul-terminated string in the buffer pointed to by
-** zPath. 
+** zPath.
 **
-** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
+** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
 ** this buffer before returning.
 */
@@ -39115,7 +40219,7 @@ static int unixFullPathname(
 #else
   int rc = SQLITE_OK;
   int nByte;
-  int nLink = 1;                /* Number of symbolic links followed so far */
+  int nLink = 0;                /* Number of symbolic links followed so far */
   const char *zIn = zPath;      /* Input path for each iteration of loop */
   char *zDel = 0;
 
@@ -39144,10 +40248,11 @@ static int unixFullPathname(
     }
 
     if( bLink ){
+      nLink++;
       if( zDel==0 ){
         zDel = sqlite3Malloc(nOut);
         if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
-      }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
+      }else if( nLink>=SQLITE_MAX_SYMLINKS ){
         rc = SQLITE_CANTOPEN_BKPT;
       }
 
@@ -39183,6 +40288,7 @@ static int unixFullPathname(
   }while( rc==SQLITE_OK );
 
   sqlite3_free(zDel);
+  if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
   return rc;
 #endif   /* HAVE_READLINK && HAVE_LSTAT */
 }
@@ -39217,7 +40323,7 @@ static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
   unixLeaveMutex();
 }
 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
-  /* 
+  /*
   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
   ** cast into a pointer to a function.  And yet the library dlsym() routine
   ** returns a void* which is really a pointer to a function.  So how do we
@@ -39227,7 +40333,7 @@ static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
   ** parameters void* and const char* and returning a pointer to a function.
   ** We initialize x by assigning it a pointer to the dlsym() function.
   ** (That assignment requires a cast.)  Then we call the function that
-  ** x points to.  
+  ** x points to.
   **
   ** This work-around is unlikely to work correctly on any system where
   ** you really cannot cast a function pointer into void*.  But then, on the
@@ -39270,7 +40376,7 @@ static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
   ** tests repeatable.
   */
   memset(zBuf, 0, nBuf);
-  randomnessPid = osGetpid(0);  
+  randomnessPid = osGetpid(0);
 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
   {
     int fd, got;
@@ -39310,7 +40416,8 @@ static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
   UNUSED_PARAMETER(NotUsed);
   return microseconds;
 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
-  usleep(microseconds);
+  if( microseconds>=1000000 ) sleep(microseconds/1000000);
+  if( microseconds%1000000 ) usleep(microseconds%1000000);
   UNUSED_PARAMETER(NotUsed);
   return microseconds;
 #else
@@ -39341,7 +40448,7 @@ SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1
 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
 ** proleptic Gregorian calendar.
 **
-** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
+** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
 ** cannot be found.
 */
 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
@@ -39448,7 +40555,7 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 ** To address the performance and cache coherency issues, proxy file locking
 ** changes the way database access is controlled by limiting access to a
 ** single host at a time and moving file locks off of the database file
-** and onto a proxy file on the local file system.  
+** and onto a proxy file on the local file system.
 **
 **
 ** Using proxy locks
@@ -39474,19 +40581,19 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 ** actual proxy file name is generated from the name and path of the
 ** database file.  For example:
 **
-**       For database path "/Users/me/foo.db" 
+**       For database path "/Users/me/foo.db"
 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
 **
 ** Once a lock proxy is configured for a database connection, it can not
 ** be removed, however it may be switched to a different proxy path via
 ** the above APIs (assuming the conch file is not being held by another
-** connection or process). 
+** connection or process).
 **
 **
 ** How proxy locking works
 ** -----------------------
 **
-** Proxy file locking relies primarily on two new supporting files: 
+** Proxy file locking relies primarily on two new supporting files:
 **
 **   *  conch file to limit access to the database file to a single host
 **      at a time
@@ -39513,11 +40620,11 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 ** host (the conch ensures that they all use the same local lock file).
 **
 ** Requesting the lock proxy does not immediately take the conch, it is
-** only taken when the first request to lock database file is made.  
+** only taken when the first request to lock database file is made.
 ** This matches the semantics of the traditional locking behavior, where
 ** opening a connection to a database file does not take a lock on it.
-** The shared lock and an open file descriptor are maintained until 
-** the connection to the database is closed. 
+** The shared lock and an open file descriptor are maintained until
+** the connection to the database is closed.
 **
 ** The proxy file and the lock file are never deleted so they only need
 ** to be created the first time they are used.
@@ -39531,7 +40638,7 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 **       automatically configured for proxy locking, lock files are
 **       named automatically using the same logic as
 **       PRAGMA lock_proxy_file=":auto:"
-**    
+**
 **  SQLITE_PROXY_DEBUG
 **
 **       Enables the logging of error messages during host id file
@@ -39546,8 +40653,8 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 **
 **       Permissions to use when creating a directory for storing the
 **       lock proxy files, only used when LOCKPROXYDIR is not set.
-**    
-**    
+**
+**
 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
 ** force proxy locking to be used for every database file opened, and 0
@@ -39557,12 +40664,12 @@ static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
 */
 
 /*
-** Proxy locking is only available on MacOSX 
+** Proxy locking is only available on MacOSX
 */
 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
 
 /*
-** The proxyLockingContext has the path and file structures for the remote 
+** The proxyLockingContext has the path and file structures for the remote
 ** and local proxy files in it
 */
 typedef struct proxyLockingContext proxyLockingContext;
@@ -39578,10 +40685,10 @@ struct proxyLockingContext {
   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
 };
 
-/* 
-** The proxy lock file path for the database at dbPath is written into lPath, 
+/*
+** The proxy lock file path for the database at dbPath is written into lPath,
 ** which must point to valid, writable memory large enough for a maxLen length
-** file path. 
+** file path.
 */
 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   int len;
@@ -39598,7 +40705,7 @@ static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
                lPath, errno, osGetpid(0)));
       return SQLITE_IOERR_LOCK;
     }
-    len = strlcat(lPath, "sqliteplocks", maxLen);    
+    len = strlcat(lPath, "sqliteplocks", maxLen);
   }
 # else
   len = strlcpy(lPath, "/tmp/", maxLen);
@@ -39608,7 +40715,7 @@ static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   if( lPath[len-1]!='/' ){
     len = strlcat(lPath, "/", maxLen);
   }
-  
+
   /* transform the db path to a unique cache name */
   dbLen = (int)strlen(dbPath);
   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
@@ -39621,14 +40728,14 @@ static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
   return SQLITE_OK;
 }
 
-/* 
+/*
  ** Creates the lock file and any missing directories in lockPath
  */
 static int proxyCreateLockPath(const char *lockPath){
   int i, len;
   char buf[MAXPATHLEN];
   int start = 0;
-  
+
   assert(lockPath!=NULL);
   /* try to create all the intermediate directories */
   len = (int)strlen(lockPath);
@@ -39636,7 +40743,7 @@ static int proxyCreateLockPath(const char *lockPath){
   for( i=1; i<len; i++ ){
     if( lockPath[i] == '/' && (i - start > 0) ){
       /* only mkdir if leaf dir != "." or "/" or ".." */
-      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
+      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
         buf[i]='\0';
         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
@@ -39672,7 +40779,7 @@ static int proxyCreateUnixFile(
   int fd = -1;
   unixFile *pNew;
   int rc = SQLITE_OK;
-  int openFlags = O_RDWR | O_CREAT;
+  int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
   sqlite3_vfs dummyVfs;
   int terrno = 0;
   UnixUnusedFd *pUnused = NULL;
@@ -39702,7 +40809,7 @@ static int proxyCreateUnixFile(
     }
   }
   if( fd<0 ){
-    openFlags = O_RDONLY;
+    openFlags = O_RDONLY | O_NOFOLLOW;
     fd = robust_open(path, openFlags, 0);
     terrno = errno;
   }
@@ -39713,13 +40820,13 @@ static int proxyCreateUnixFile(
     switch (terrno) {
       case EACCES:
         return SQLITE_PERM;
-      case EIO: 
+      case EIO:
         return SQLITE_IOERR_LOCK; /* even though it is the conch */
       default:
         return SQLITE_CANTOPEN_BKPT;
     }
   }
-  
+
   pNew = (unixFile *)sqlite3Malloc(sizeof(*pNew));
   if( pNew==NULL ){
     rc = SQLITE_NOMEM_BKPT;
@@ -39733,13 +40840,13 @@ static int proxyCreateUnixFile(
   pUnused->fd = fd;
   pUnused->flags = openFlags;
   pNew->pPreallocatedUnused = pUnused;
-  
+
   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
   if( rc==SQLITE_OK ){
     *ppFile = pNew;
     return SQLITE_OK;
   }
-end_create_proxy:    
+end_create_proxy:
   robust_close(pNew, fd, __LINE__);
   sqlite3_free(pNew);
   sqlite3_free(pUnused);
@@ -39758,7 +40865,7 @@ SQLITE_API int sqlite3_hostid_num = 0;
 extern int gethostuuid(uuid_t id, const struct timespec *wait);
 #endif
 
-/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
+/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
 ** bytes of writable memory.
 */
 static int proxyGetHostID(unsigned char *pHostID, int *pError){
@@ -39784,7 +40891,7 @@ static int proxyGetHostID(unsigned char *pHostID, int *pError){
     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
   }
 #endif
-  
+
   return SQLITE_OK;
 }
 
@@ -39795,14 +40902,14 @@ static int proxyGetHostID(unsigned char *pHostID, int *pError){
 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
 
-/* 
-** Takes an open conch file, copies the contents to a new path and then moves 
+/*
+** Takes an open conch file, copies the contents to a new path and then moves
 ** it back.  The newly created file's file descriptor is assigned to the
-** conch file structure and finally the original conch file descriptor is 
+** conch file structure and finally the original conch file descriptor is
 ** closed.  Returns zero if successful.
 */
 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
-  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
+  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   unixFile *conchFile = pCtx->conchFile;
   char tPath[MAXPATHLEN];
   char buf[PROXY_MAXCONCHLEN];
@@ -39816,7 +40923,7 @@ static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
 
   /* create a new path by replace the trailing '-conch' with '-break' */
   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
-  if( pathLen>MAXPATHLEN || pathLen<6 || 
+  if( pathLen>MAXPATHLEN || pathLen<6 ||
      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
     goto end_breaklock;
@@ -39828,7 +40935,7 @@ static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
     goto end_breaklock;
   }
   /* write it out to the temporary break file */
-  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
+  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
   if( fd<0 ){
     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
     goto end_breaklock;
@@ -39858,24 +40965,24 @@ end_breaklock:
   return rc;
 }
 
-/* Take the requested lock on the conch file and break a stale lock if the 
+/* Take the requested lock on the conch file and break a stale lock if the
 ** host id matches.
 */
 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
-  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
+  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
   unixFile *conchFile = pCtx->conchFile;
   int rc = SQLITE_OK;
   int nTries = 0;
   struct timespec conchModTime;
-  
+
   memset(&conchModTime, 0, sizeof(conchModTime));
   do {
     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
     nTries ++;
     if( rc==SQLITE_BUSY ){
       /* If the lock failed (busy):
-       * 1st try: get the mod time of the conch, wait 0.5s and try again. 
-       * 2nd try: fail if the mod time changed or host id is different, wait 
+       * 1st try: get the mod time of the conch, wait 0.5s and try again.
+       * 2nd try: fail if the mod time changed or host id is different, wait
        *           10 sec and try again
        * 3rd try: break the lock unless the mod time has changed.
        */
@@ -39884,20 +40991,20 @@ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
         storeLastErrno(pFile, errno);
         return SQLITE_IOERR_LOCK;
       }
-      
+
       if( nTries==1 ){
         conchModTime = buf.st_mtimespec;
-        usleep(500000); /* wait 0.5 sec and try the lock again*/
-        continue;  
+        unixSleep(0,500000); /* wait 0.5 sec and try the lock again*/
+        continue;
       }
 
       assert( nTries>1 );
-      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
+      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
         return SQLITE_BUSY;
       }
-      
-      if( nTries==2 ){  
+
+      if( nTries==2 ){
         char tBuf[PROXY_MAXCONCHLEN];
         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
         if( len<0 ){
@@ -39913,10 +41020,10 @@ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
           /* don't break the lock on short read or a version mismatch */
           return SQLITE_BUSY;
         }
-        usleep(10000000); /* wait 10 sec and try the lock again */
-        continue; 
+        unixSleep(0,10000000); /* wait 10 sec and try the lock again */
+        continue;
       }
-      
+
       assert( nTries==3 );
       if( 0==proxyBreakConchLock(pFile, myHostID) ){
         rc = SQLITE_OK;
@@ -39929,19 +41036,19 @@ static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
       }
     }
   } while( rc==SQLITE_BUSY && nTries<3 );
-  
+
   return rc;
 }
 
-/* Takes the conch by taking a shared lock and read the contents conch, if 
-** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
-** lockPath means that the lockPath in the conch file will be used if the 
-** host IDs match, or a new lock path will be generated automatically 
+/* Takes the conch by taking a shared lock and read the contents conch, if
+** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
+** lockPath means that the lockPath in the conch file will be used if the
+** host IDs match, or a new lock path will be generated automatically
 ** and written to the conch file.
 */
 static int proxyTakeConch(unixFile *pFile){
-  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
-  
+  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
+
   if( pCtx->conchHeld!=0 ){
     return SQLITE_OK;
   }else{
@@ -39957,7 +41064,7 @@ static int proxyTakeConch(unixFile *pFile){
     int readLen = 0;
     int tryOldLockPath = 0;
     int forceNewLockPath = 0;
-    
+
     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
              osGetpid(0)));
@@ -39978,21 +41085,21 @@ static int proxyTakeConch(unixFile *pFile){
       storeLastErrno(pFile, conchFile->lastErrno);
       rc = SQLITE_IOERR_READ;
       goto end_takeconch;
-    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
+    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
              readBuf[0]!=(char)PROXY_CONCHVERSION ){
-      /* a short read or version format mismatch means we need to create a new 
-      ** conch file. 
+      /* a short read or version format mismatch means we need to create a new
+      ** conch file.
       */
       createConch = 1;
     }
     /* if the host id matches and the lock path already exists in the conch
-    ** we'll try to use the path there, if we can't open that path, we'll 
-    ** retry with a new auto-generated path 
+    ** we'll try to use the path there, if we can't open that path, we'll
+    ** retry with a new auto-generated path
     */
     do { /* in case we need to try again for an :auto: named lock file */
 
       if( !createConch && !forceNewLockPath ){
-        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
+        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
                                   PROXY_HOSTIDLEN);
         /* if the conch has data compare the contents */
         if( !pCtx->lockProxyPath ){
@@ -40001,7 +41108,7 @@ static int proxyTakeConch(unixFile *pFile){
            */
           if( hostIdMatch ){
             size_t pathLen = (readLen - PROXY_PATHINDEX);
-            
+
             if( pathLen>=MAXPATHLEN ){
               pathLen=MAXPATHLEN-1;
             }
@@ -40017,23 +41124,23 @@ static int proxyTakeConch(unixFile *pFile){
                            readLen-PROXY_PATHINDEX)
         ){
           /* conch host and lock path match */
-          goto end_takeconch; 
+          goto end_takeconch;
         }
       }
-      
+
       /* if the conch isn't writable and doesn't match, we can't take it */
       if( (conchFile->openFlags&O_RDWR) == 0 ){
         rc = SQLITE_BUSY;
         goto end_takeconch;
       }
-      
+
       /* either the conch didn't match or we need to create a new one */
       if( !pCtx->lockProxyPath ){
         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
         tempLockPath = lockPath;
         /* create a copy of the lock path _only_ if the conch is taken */
       }
-      
+
       /* update conch with host and path (this will fail if other process
       ** has a shared lock already), if the host id matches, use the big
       ** stick.
@@ -40044,7 +41151,7 @@ static int proxyTakeConch(unixFile *pFile){
           /* We are trying for an exclusive lock but another thread in this
            ** same process is still holding a shared lock. */
           rc = SQLITE_BUSY;
-        } else {          
+        } else {
           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
         }
       }else{
@@ -40053,7 +41160,7 @@ static int proxyTakeConch(unixFile *pFile){
       if( rc==SQLITE_OK ){
         char writeBuffer[PROXY_MAXCONCHLEN];
         int writeSize = 0;
-        
+
         writeBuffer[0] = (char)PROXY_CONCHVERSION;
         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
         if( pCtx->lockProxyPath!=NULL ){
@@ -40066,8 +41173,8 @@ static int proxyTakeConch(unixFile *pFile){
         robust_ftruncate(conchFile->h, writeSize);
         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
         full_fsync(conchFile->h,0,0);
-        /* If we created a new conch file (not just updated the contents of a 
-         ** valid conch file), try to match the permissions of the database 
+        /* If we created a new conch file (not just updated the contents of a
+         ** valid conch file), try to match the permissions of the database
          */
         if( rc==SQLITE_OK && createConch ){
           struct stat buf;
@@ -40091,14 +41198,14 @@ static int proxyTakeConch(unixFile *pFile){
             }
           }else{
             int code = errno;
-            fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
+            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
                     err, code, strerror(code));
 #endif
           }
         }
       }
       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
-      
+
     end_takeconch:
       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
       if( rc==SQLITE_OK && pFile->openFlags ){
@@ -40121,7 +41228,7 @@ static int proxyTakeConch(unixFile *pFile){
         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
           /* we couldn't create the proxy lock file with the old lock file path
-           ** so try again via auto-naming 
+           ** so try again via auto-naming
            */
           forceNewLockPath = 1;
           tryOldLockPath = 0;
@@ -40141,7 +41248,7 @@ static int proxyTakeConch(unixFile *pFile){
       }
       if( rc==SQLITE_OK ){
         pCtx->conchHeld = 1;
-        
+
         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
           afpLockingContext *afpCtx;
           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
@@ -40153,7 +41260,7 @@ static int proxyTakeConch(unixFile *pFile){
       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
                rc==SQLITE_OK?"ok":"failed"));
       return rc;
-    } while (1); /* in case we need to retry the :auto: lock file - 
+    } while (1); /* in case we need to retry the :auto: lock file -
                  ** we should never get here except via the 'continue' call. */
   }
 }
@@ -40169,7 +41276,7 @@ static int proxyReleaseConch(unixFile *pFile){
   pCtx = (proxyLockingContext *)pFile->lockingContext;
   conchFile = pCtx->conchFile;
   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
-           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
+           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
            osGetpid(0)));
   if( pCtx->conchHeld>0 ){
     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
@@ -40197,13 +41304,13 @@ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
   char *conchPath;              /* buffer in which to construct conch name */
 
   /* Allocate space for the conch filename and initialize the name to
-  ** the name of the original database file. */  
+  ** the name of the original database file. */
   *pConchPath = conchPath = (char *)sqlite3Malloc(len + 8);
   if( conchPath==0 ){
     return SQLITE_NOMEM_BKPT;
   }
   memcpy(conchPath, dbPath, len+1);
-  
+
   /* now insert a "." before the last / character */
   for( i=(len-1); i>=0; i-- ){
     if( conchPath[i]=='/' ){
@@ -40226,7 +41333,7 @@ static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
 
 
 /* Takes a fully configured proxy locking-style unix file and switches
-** the local lock file path 
+** the local lock file path
 */
 static int switchLockProxyPath(unixFile *pFile, const char *path) {
   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
@@ -40235,7 +41342,7 @@ static int switchLockProxyPath(unixFile *pFile, const char *path) {
 
   if( pFile->eFileLock!=NO_LOCK ){
     return SQLITE_BUSY;
-  }  
+  }
 
   /* nothing to do if the path is NULL, :auto: or matches the existing path */
   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
@@ -40253,7 +41360,7 @@ static int switchLockProxyPath(unixFile *pFile, const char *path) {
     sqlite3_free(oldPath);
     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
   }
-  
+
   return rc;
 }
 
@@ -40267,7 +41374,7 @@ static int switchLockProxyPath(unixFile *pFile, const char *path) {
 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
 #if defined(__APPLE__)
   if( pFile->pMethod == &afpIoMethods ){
-    /* afp style keeps a reference to the db path in the filePath field 
+    /* afp style keeps a reference to the db path in the filePath field
     ** of the struct */
     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
@@ -40288,9 +41395,9 @@ static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
 }
 
 /*
-** Takes an already filled in unix file and alters it so all file locking 
+** Takes an already filled in unix file and alters it so all file locking
 ** will be performed on the local proxy lock file.  The following fields
-** are preserved in the locking context so that they can be restored and 
+** are preserved in the locking context so that they can be restored and
 ** the unix structure properly cleaned up at close time:
 **  ->lockingContext
 **  ->pMethod
@@ -40300,7 +41407,7 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
   char *lockPath=NULL;
   int rc = SQLITE_OK;
-  
+
   if( pFile->eFileLock!=NO_LOCK ){
     return SQLITE_BUSY;
   }
@@ -40310,7 +41417,7 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
   }else{
     lockPath=(char *)path;
   }
-  
+
   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
            (lockPath ? lockPath : ":auto:"), osGetpid(0)));
 
@@ -40344,7 +41451,7 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
         rc = SQLITE_OK;
       }
     }
-  }  
+  }
   if( rc==SQLITE_OK && lockPath ){
     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
   }
@@ -40356,7 +41463,7 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
     }
   }
   if( rc==SQLITE_OK ){
-    /* all memory is allocated, proxys are created and assigned, 
+    /* all memory is allocated, proxys are created and assigned,
     ** switch the locking context and pMethod then return.
     */
     pCtx->oldLockingContext = pFile->lockingContext;
@@ -40364,12 +41471,12 @@ static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
     pCtx->pOldMethod = pFile->pMethod;
     pFile->pMethod = &proxyIoMethods;
   }else{
-    if( pCtx->conchFile ){ 
+    if( pCtx->conchFile ){
       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
       sqlite3_free(pCtx->conchFile);
     }
     sqlite3DbFree(0, pCtx->lockProxyPath);
-    sqlite3_free(pCtx->conchFilePath); 
+    sqlite3_free(pCtx->conchFilePath);
     sqlite3_free(pCtx);
   }
   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
@@ -40407,7 +41514,7 @@ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
         if( isProxyStyle ){
           /* turn off proxy locking - not supported.  If support is added for
           ** switching proxy locking mode off then it will need to fail if
-          ** the journal mode is WAL mode. 
+          ** the journal mode is WAL mode.
           */
           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
         }else{
@@ -40417,9 +41524,9 @@ static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
       }else{
         const char *proxyPath = (const char *)pArg;
         if( isProxyStyle ){
-          proxyLockingContext *pCtx = 
+          proxyLockingContext *pCtx =
             (proxyLockingContext*)pFile->lockingContext;
-          if( !strcmp(pArg, ":auto:") 
+          if( !strcmp(pArg, ":auto:")
            || (pCtx->lockProxyPath &&
                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
           ){
@@ -40544,7 +41651,7 @@ static int proxyClose(sqlite3_file *id) {
     unixFile *lockProxy = pCtx->lockProxy;
     unixFile *conchFile = pCtx->conchFile;
     int rc = SQLITE_OK;
-    
+
     if( lockProxy ){
       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
       if( rc ) return rc;
@@ -40581,7 +41688,7 @@ static int proxyClose(sqlite3_file *id) {
 ** The proxy locking style is intended for use with AFP filesystems.
 ** And since AFP is only supported on MacOSX, the proxy locking is also
 ** restricted to MacOSX.
-** 
+**
 **
 ******************* End of the proxy lock implementation **********************
 ******************************************************************************/
@@ -40605,9 +41712,9 @@ static
 #endif
 SQLITE_API int sqlite3_os_unix_init(void){
 #else
-SQLITE_API int sqlite3_os_init(void){ 
+SQLITE_API int sqlite3_os_init(void){
 #endif
-  /* 
+  /*
   ** The following macro defines an initializer for an sqlite3_vfs object.
   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
   ** to the "finder" function.  (pAppData is a pointer to a pointer because
@@ -40623,7 +41730,7 @@ SQLITE_API int sqlite3_os_init(void){
   **
   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
   ** object.  But the "autolockIoFinder" available on MacOSX does a little
-  ** more than that; it looks at the filesystem type that hosts the 
+  ** more than that; it looks at the filesystem type that hosts the
   ** database file and tries to choose an locking method appropriate for
   ** that filesystem time.
   */
@@ -40707,7 +41814,7 @@ SQLITE_API int sqlite3_os_init(void){
     sqlite3_vfs_register(&aVfs[i], i==0);
   }
   unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
-  return SQLITE_OK; 
+  return SQLITE_OK;
 }
 
 #undef aSyscall
@@ -40719,12 +41826,12 @@ SQLITE_API int sqlite3_os_init(void){
 ** to release dynamically allocated objects.  But not on unix.
 ** This routine is a no-op for unix.
 */
-SQLITE_API int sqlite3_os_end(void){ 
+SQLITE_API int sqlite3_os_end(void){
   unixBigLock = 0;
-  return SQLITE_OK; 
+  return SQLITE_OK;
 }
 #endif /* !SQLITE_OS_WIN */
+
 #endif /* SQLITE_OS_UNIX */
 
 /************** End of os_unix.c *********************************************/
@@ -40807,7 +41914,7 @@ SQLITE_API int sqlite3_os_end(void){
 ******************************************************************************
 **
 ** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 class CPUs.
+** counters for x86 and x86_64 class CPUs.
 */
 #ifndef SQLITE_HWTIME_H
 #define SQLITE_HWTIME_H
@@ -40818,8 +41925,9 @@ SQLITE_API int sqlite3_os_end(void){
 ** processor and returns that value.  This can be used for high-res
 ** profiling.
 */
-#if (defined(__GNUC__) || defined(_MSC_VER)) && \
-      (defined(i386) || defined(__i386__) || defined(_M_IX86))
+#if !defined(__STRICT_ANSI__) && \
+    (defined(__GNUC__) || defined(_MSC_VER)) && \
+    (defined(i386) || defined(__i386__) || defined(_M_IX86))
 
   #if defined(__GNUC__)
 
@@ -40840,15 +41948,15 @@ SQLITE_API int sqlite3_os_end(void){
 
   #endif
 
-#elif (defined(__GNUC__) && defined(__x86_64__))
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long val;
       __asm__ __volatile__ ("rdtsc" : "=A" (val));
       return val;
   }
-#elif (defined(__GNUC__) && defined(__ppc__))
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long long retval;
@@ -40865,14 +41973,13 @@ SQLITE_API int sqlite3_os_end(void){
 
 #else
 
-  #error Need implementation of sqlite3Hwtime() for your platform.
-
   /*
-  ** To compile without implementing sqlite3Hwtime() for your platform,
-  ** you can remove the above #error and use the following
-  ** stub function.  You will lose timing support for many
-  ** of the debugging and testing utilities, but it should at
-  ** least compile and run.
+  ** asm() is needed for hardware timing support.  Without asm(),
+  ** disable the sqlite3Hwtime() routine.
+  **
+  ** sqlite3Hwtime() is only used for some obscure debugging
+  ** and analysis configurations, not in any deliverable, so this
+  ** should not be a great loss.
   */
 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 
@@ -42223,17 +43330,17 @@ SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
 */
 SQLITE_API int sqlite3_win32_reset_heap(){
   int rc;
-  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
+  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; ) /* The main static mutex */
   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
-  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
+  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
-  sqlite3_mutex_enter(pMaster);
+  sqlite3_mutex_enter(pMainMtx);
   sqlite3_mutex_enter(pMem);
   winMemAssertMagic();
   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
     /*
     ** At this point, there should be no outstanding memory allocations on
-    ** the heap.  Also, since both the master and memsys locks are currently
+    ** the heap.  Also, since both the main and memsys locks are currently
     ** being held by us, no other function (i.e. from another thread) should
     ** be able to even access the heap.  Attempt to destroy and recreate our
     ** isolated Win32 native heap now.
@@ -42256,7 +43363,7 @@ SQLITE_API int sqlite3_win32_reset_heap(){
     rc = SQLITE_BUSY;
   }
   sqlite3_mutex_leave(pMem);
-  sqlite3_mutex_leave(pMaster);
+  sqlite3_mutex_leave(pMainMtx);
   return rc;
 }
 #endif /* SQLITE_WIN32_MALLOC */
@@ -44432,6 +45539,7 @@ static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
 /* Forward references to VFS helper methods used for temporary files */
 static int winGetTempname(sqlite3_vfs *, char **);
 static int winIsDir(const void *);
+static BOOL winIsLongPathPrefix(const char *);
 static BOOL winIsDriveLetterAndColon(const char *);
 
 /*
@@ -45980,7 +47088,7 @@ static int winOpen(
 
 #ifndef NDEBUG
   int isOpenJournal = (isCreate && (
-        eType==SQLITE_OPEN_MASTER_JOURNAL
+        eType==SQLITE_OPEN_SUPER_JOURNAL
      || eType==SQLITE_OPEN_MAIN_JOURNAL
      || eType==SQLITE_OPEN_WAL
   ));
@@ -46001,17 +47109,17 @@ static int winOpen(
   assert(isExclusive==0 || isCreate);
   assert(isDelete==0 || isCreate);
 
-  /* The main DB, main journal, WAL file and master journal are never
+  /* The main DB, main journal, WAL file and super-journal are never
   ** automatically deleted. Nor are they ever temporary files.  */
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
-  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
+  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_SUPER_JOURNAL );
   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
 
   /* Assert that the upper layer has set one of the "file-type" flags. */
   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
-       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
+       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_SUPER_JOURNAL
        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
   );
 
@@ -46083,7 +47191,11 @@ static int winOpen(
     dwCreationDisposition = OPEN_EXISTING;
   }
 
-  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
+  if( 0==sqlite3_uri_boolean(zName, "exclusive", 0) ){
+    dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
+  }else{
+    dwShareMode = 0;
+  }
 
   if( isDelete ){
 #if SQLITE_OS_WINCE
@@ -46223,13 +47335,15 @@ static int winOpen(
   }
 
   sqlite3_free(zTmpname);
-  pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
+  id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
   pFile->pVfs = pVfs;
   pFile->h = h;
   if( isReadonly ){
     pFile->ctrlFlags |= WINFILE_RDONLY;
   }
-  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
+  if( (flags & SQLITE_OPEN_MAIN_DB)
+   && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE)
+  ){
     pFile->ctrlFlags |= WINFILE_PSOW;
   }
   pFile->lastErrno = NO_ERROR;
@@ -46440,6 +47554,17 @@ static int winAccess(
 }
 
 /*
+** Returns non-zero if the specified path name starts with the "long path"
+** prefix.
+*/
+static BOOL winIsLongPathPrefix(
+  const char *zPathname
+){
+  return ( zPathname[0]=='\\' && zPathname[1]=='\\'
+        && zPathname[2]=='?'  && zPathname[3]=='\\' );
+}
+
+/*
 ** Returns non-zero if the specified path name starts with a drive letter
 ** followed by a colon character.
 */
@@ -46505,10 +47630,11 @@ static int winFullPathname(
   char *zOut;
 #endif
 
-  /* If this path name begins with "/X:", where "X" is any alphabetic
-  ** character, discard the initial "/" from the pathname.
+  /* If this path name begins with "/X:" or "\\?\", where "X" is any
+  ** alphabetic character, discard the initial "/" from the pathname.
   */
-  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
+  if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)
+       || winIsLongPathPrefix(zRelative+1)) ){
     zRelative++;
   }
 
@@ -47208,7 +48334,7 @@ static sqlite3_vfs memdb_vfs = {
   1024,                        /* mxPathname */
   0,                           /* pNext */
   "memdb",                     /* zName */
-  0,                           /* pAppData (set when registered) */ 
+  0,                           /* pAppData (set when registered) */
   memdbOpen,                   /* xOpen */
   0, /* memdbDelete, */        /* xDelete */
   memdbAccess,                 /* xAccess */
@@ -47233,7 +48359,7 @@ static const sqlite3_io_methods memdb_io_methods = {
   memdbSync,                       /* xSync */
   memdbFileSize,                   /* xFileSize */
   memdbLock,                       /* xLock */
-  memdbLock,                       /* xUnlock - same as xLock in this case */ 
+  memdbLock,                       /* xUnlock - same as xLock in this case */
   0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
   memdbFileControl,                /* xFileControl */
   0, /* memdbSectorSize,*/         /* xSectorSize */
@@ -47252,11 +48378,14 @@ static const sqlite3_io_methods memdb_io_methods = {
 ** Close an memdb-file.
 **
 ** The pData pointer is owned by the application, so there is nothing
-** to free.
+** to free.  Unless the SQLITE_DESERIALIZE_FREEONCLOSE flag is set,
+** in which case we own the pData pointer and need to free it.
 */
 static int memdbClose(sqlite3_file *pFile){
   MemFile *p = (MemFile *)pFile;
-  if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
+  if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
+    sqlite3_free(p->aData);
+  }
   return SQLITE_OK;
 }
 
@@ -47264,9 +48393,9 @@ static int memdbClose(sqlite3_file *pFile){
 ** Read data from an memdb-file.
 */
 static int memdbRead(
-  sqlite3_file *pFile, 
-  void *zBuf, 
-  int iAmt, 
+  sqlite3_file *pFile,
+  void *zBuf,
+  int iAmt,
   sqlite_int64 iOfst
 ){
   MemFile *p = (MemFile *)pFile;
@@ -47292,7 +48421,7 @@ static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
   }
   newSz *= 2;
   if( newSz>p->szMax ) newSz = p->szMax;
-  pNew = sqlite3_realloc64(p->aData, newSz);
+  pNew = sqlite3Realloc(p->aData, newSz);
   if( pNew==0 ) return SQLITE_NOMEM;
   p->aData = pNew;
   p->szAlloc = newSz;
@@ -47334,7 +48463,7 @@ static int memdbWrite(
 static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
   MemFile *p = (MemFile *)pFile;
   if( NEVER(size>p->sz) ) return SQLITE_FULL;
-  p->sz = size; 
+  p->sz = size;
   return SQLITE_OK;
 }
 
@@ -47359,7 +48488,7 @@ static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
 */
 static int memdbLock(sqlite3_file *pFile, int eLock){
   MemFile *p = (MemFile *)pFile;
-  if( eLock>SQLITE_LOCK_SHARED 
+  if( eLock>SQLITE_LOCK_SHARED
    && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
   ){
     return SQLITE_READONLY;
@@ -47417,7 +48546,7 @@ static int memdbSectorSize(sqlite3_file *pFile){
 ** Return the device characteristic flags supported by an memdb-file.
 */
 static int memdbDeviceCharacteristics(sqlite3_file *pFile){
-  return SQLITE_IOCAP_ATOMIC | 
+  return SQLITE_IOCAP_ATOMIC |
          SQLITE_IOCAP_POWERSAFE_OVERWRITE |
          SQLITE_IOCAP_SAFE_APPEND |
          SQLITE_IOCAP_SEQUENTIAL;
@@ -47465,12 +48594,12 @@ static int memdbOpen(
   p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
   assert( pOutFlags!=0 );  /* True because flags==SQLITE_OPEN_MAIN_DB */
   *pOutFlags = flags | SQLITE_OPEN_MEMORY;
-  p->base.pMethods = &memdb_io_methods;
+  pFile->pMethods = &memdb_io_methods;
   p->szMax = sqlite3GlobalConfig.mxMemdbSize;
   return SQLITE_OK;
 }
 
-#if 0 /* Only used to delete rollback journals, master journals, and WAL
+#if 0 /* Only used to delete rollback journals, super-journals, and WAL
       ** files, none of which exist in memdb.  So this routine is never used */
 /*
 ** Delete the file located at zPath. If the dirSync argument is true,
@@ -47489,9 +48618,9 @@ static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 ** With memdb, no files ever exist on disk.  So always return false.
 */
 static int memdbAccess(
-  sqlite3_vfs *pVfs, 
-  const char *zPath, 
-  int flags, 
+  sqlite3_vfs *pVfs,
+  const char *zPath,
+  int flags,
   int *pResOut
 ){
   *pResOut = 0;
@@ -47504,9 +48633,9 @@ static int memdbAccess(
 ** of at least (INST_MAX_PATHNAME+1) bytes.
 */
 static int memdbFullPathname(
-  sqlite3_vfs *pVfs, 
-  const char *zPath, 
-  int nOut, 
+  sqlite3_vfs *pVfs,
+  const char *zPath,
+  int nOut,
   char *zOut
 ){
   sqlite3_snprintf(nOut, zOut, "%s", zPath);
@@ -47522,7 +48651,7 @@ static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 
 /*
 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
-** utf-8 string describing the most recent error encountered associated 
+** utf-8 string describing the most recent error encountered associated
 ** with dynamic libraries.
 */
 static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
@@ -47544,7 +48673,7 @@ static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
 }
 
 /*
-** Populate the buffer pointed to by zBufOut with nByte bytes of 
+** Populate the buffer pointed to by zBufOut with nByte bytes of
 ** random data.
 */
 static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
@@ -47552,7 +48681,7 @@ static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 }
 
 /*
-** Sleep for nMicro microseconds. Return the number of microseconds 
+** Sleep for nMicro microseconds. Return the number of microseconds
 ** actually slept.
 */
 static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
@@ -47658,7 +48787,7 @@ SQLITE_API unsigned char *sqlite3_serialize(
           }else{
             memset(pTo, 0, szPage);
           }
-          sqlite3PagerUnref(pPage);       
+          sqlite3PagerUnref(pPage);
         }
       }
     }
@@ -47697,10 +48826,14 @@ SQLITE_API int sqlite3_deserialize(
   if( iDb<0 ){
     rc = SQLITE_ERROR;
     goto end_deserialize;
-  }    
+  }
   zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
-  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
-  sqlite3_free(zSql);
+  if( zSql==0 ){
+    rc = SQLITE_NOMEM;
+  }else{
+    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
+    sqlite3_free(zSql);
+  }
   if( rc ) goto end_deserialize;
   db->init.iDb = (u8)iDb;
   db->init.reopenMemdb = 1;
@@ -47715,6 +48848,7 @@ SQLITE_API int sqlite3_deserialize(
     rc = SQLITE_ERROR;
   }else{
     p->aData = pData;
+    pData = 0;
     p->sz = szDb;
     p->szAlloc = szBuf;
     p->szMax = szBuf;
@@ -47727,11 +48861,14 @@ SQLITE_API int sqlite3_deserialize(
 
 end_deserialize:
   sqlite3_finalize(pStmt);
+  if( pData && (mFlags & SQLITE_DESERIALIZE_FREEONCLOSE)!=0 ){
+    sqlite3_free(pData);
+  }
   sqlite3_mutex_leave(db->mutex);
   return rc;
 }
 
-/* 
+/*
 ** This routine is called when the extension is loaded.
 ** Register the new VFS.
 */
@@ -47739,10 +48876,11 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){
   sqlite3_vfs *pLower = sqlite3_vfs_find(0);
   int sz = pLower->szOsFile;
   memdb_vfs.pAppData = pLower;
-  /* In all known configurations of SQLite, the size of a default
-  ** sqlite3_file is greater than the size of a memdb sqlite3_file.
-  ** Should that ever change, remove the following NEVER() */
-  if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
+  /* The following conditional can only be true when compiled for
+  ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0.  We always leave
+  ** it in, to be safe, but it is marked as NO_TEST since there
+  ** is no way to reach it under most builds. */
+  if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/
   memdb_vfs.szOsFile = sz;
   return sqlite3_vfs_register(&memdb_vfs, 0);
 }
@@ -47769,8 +48907,8 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){
 ** property.  Usually only a few pages are meet either condition.
 ** So the bitmap is usually sparse and has low cardinality.
 ** But sometimes (for example when during a DROP of a large table) most
-** or all of the pages in a database can get journalled.  In those cases, 
-** the bitmap becomes dense with high cardinality.  The algorithm needs 
+** or all of the pages in a database can get journalled.  In those cases,
+** the bitmap becomes dense with high cardinality.  The algorithm needs
 ** to handle both cases well.
 **
 ** The size of the bitmap is fixed when the object is created.
@@ -47791,13 +48929,13 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){
 /* Size of the Bitvec structure in bytes. */
 #define BITVEC_SZ        512
 
-/* Round the union size down to the nearest pointer boundary, since that's how 
+/* Round the union size down to the nearest pointer boundary, since that's how
 ** it will be aligned within the Bitvec struct. */
 #define BITVEC_USIZE \
     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
 
-/* Type of the array "element" for the bitmap representation. 
-** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
+/* Type of the array "element" for the bitmap representation.
+** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
 ** Setting this to the "natural word" size of your CPU may improve
 ** performance. */
 #define BITVEC_TELEM     u8
@@ -47810,12 +48948,12 @@ SQLITE_PRIVATE int sqlite3MemdbInit(void){
 
 /* Number of u32 values in hash table. */
 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
-/* Maximum number of entries in hash table before 
+/* Maximum number of entries in hash table before
 ** sub-dividing and re-hashing. */
 #define BITVEC_MXHASH    (BITVEC_NINT/2)
 /* Hashing function for the aHash representation.
-** Empirical testing showed that the *37 multiplier 
-** (an arbitrary prime)in the hash function provided 
+** Empirical testing showed that the *37 multiplier
+** (an arbitrary prime)in the hash function provided
 ** no fewer collisions than the no-op *1. */
 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
 
@@ -47861,7 +48999,7 @@ struct Bitvec {
 
 /*
 ** Create a new bitmap object able to handle bits between 0 and iSize,
-** inclusive.  Return a pointer to the new object.  Return NULL if 
+** inclusive.  Return a pointer to the new object.  Return NULL if
 ** malloc fails.
 */
 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
@@ -48117,7 +49255,7 @@ SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
         break;
       }
       case 3:
-      case 4: 
+      case 4:
       default: {
         nx = 2;
         sqlite3_randomness(sizeof(i), &i);
@@ -48197,7 +49335,7 @@ bitvec_end:
 **
 **   The PCache.pSynced variable is used to optimize searching for a dirty
 **   page to eject from the cache mid-transaction. It is better to eject
-**   a page that does not require a journal sync than one that does. 
+**   a page that does not require a journal sync than one that does.
 **   Therefore, pSynced is maintained so that it *almost* always points
 **   to either the oldest page in the pDirty/pDirtyTail list that has a
 **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
@@ -48238,7 +49376,7 @@ struct PCache {
     sqlite3_pcache_page *pLower;
     PgHdr *pPg;
     unsigned char *a;
-  
+
     if( sqlite3PcacheTrace<2 ) return;
     if( pCache->pCache==0 ) return;
     N = sqlite3PcachePagecount(pCache);
@@ -48330,12 +49468,12 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
     assert( pPage->pDirtyPrev || pPage==p->pDirty );
-  
+
     /* Update the PCache1.pSynced variable if necessary. */
     if( p->pSynced==pPage ){
       p->pSynced = pPage->pDirtyPrev;
     }
-  
+
     if( pPage->pDirtyNext ){
       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
     }else{
@@ -48345,7 +49483,7 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
     if( pPage->pDirtyPrev ){
       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
     }else{
-      /* If there are now no dirty pages in the cache, set eCreate to 2. 
+      /* If there are now no dirty pages in the cache, set eCreate to 2.
       ** This is an optimization that allows sqlite3PcacheFetch() to skip
       ** searching for a dirty page to eject from the cache when it might
       ** otherwise have to.  */
@@ -48374,11 +49512,11 @@ static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
     p->pDirty = pPage;
 
     /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
-    ** pSynced to point to it. Checking the NEED_SYNC flag is an 
+    ** pSynced to point to it. Checking the NEED_SYNC flag is an
     ** optimization, as if pSynced points to a page with the NEED_SYNC
-    ** flag set sqlite3PcacheFetchStress() searches through all newer 
+    ** flag set sqlite3PcacheFetchStress() searches through all newer
     ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
-    if( !p->pSynced 
+    if( !p->pSynced
      && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
     ){
       p->pSynced = pPage;
@@ -48419,7 +49557,7 @@ static int numberOfCachePages(PCache *p){
 
 /*************************************************** General Interfaces ******
 **
-** Initialize and shutdown the page cache subsystem. Neither of these 
+** Initialize and shutdown the page cache subsystem. Neither of these
 ** functions are threadsafe.
 */
 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
@@ -48446,8 +49584,8 @@ SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
 
 /*
 ** Create a new PCache object. Storage space to hold the object
-** has already been allocated and is passed in as the p pointer. 
-** The caller discovers how much space needs to be allocated by 
+** has already been allocated and is passed in as the p pointer.
+** The caller discovers how much space needs to be allocated by
 ** calling sqlite3PcacheSize().
 **
 ** szExtra is some extra space allocated for each page.  The first
@@ -48559,7 +49697,7 @@ SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
 /*
 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
 ** page because no clean pages are available for reuse and the cache
-** size limit has been reached, then this routine can be invoked to 
+** size limit has been reached, then this routine can be invoked to
 ** try harder to allocate a page.  This routine might invoke the stress
 ** callback to spill dirty pages to the journal.  It will then try to
 ** allocate the new page and will only fail to allocate a new page on
@@ -48576,17 +49714,17 @@ SQLITE_PRIVATE int sqlite3PcacheFetchStress(
   if( pCache->eCreate==2 ) return 0;
 
   if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
-    /* Find a dirty page to write-out and recycle. First try to find a 
+    /* Find a dirty page to write-out and recycle. First try to find a
     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
-    ** cleared), but if that is not possible settle for any other 
+    ** cleared), but if that is not possible settle for any other
     ** unreferenced dirty page.
     **
     ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
     ** flag is currently referenced, then the following may leave pSynced
     ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
     ** cleared). This is Ok, as pSynced is just an optimization.  */
-    for(pPg=pCache->pSynced; 
-        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
+    for(pPg=pCache->pSynced;
+        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
         pPg=pPg->pDirtyPrev
     );
     pCache->pSynced = pPg;
@@ -48596,7 +49734,7 @@ SQLITE_PRIVATE int sqlite3PcacheFetchStress(
     if( pPg ){
       int rc;
 #ifdef SQLITE_LOG_CACHE_SPILL
-      sqlite3_log(SQLITE_FULL, 
+      sqlite3_log(SQLITE_FULL,
                   "spill page %d making room for %d - cache used: %d/%d",
                   pPg->pgno, pgno,
                   sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
@@ -48781,7 +49919,7 @@ SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
 }
 
 /*
-** Change the page number of page p to newPgno. 
+** Change the page number of page p to newPgno.
 */
 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   PCache *pCache = p->pCache;
@@ -48844,7 +49982,7 @@ SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
 }
 
-/* 
+/*
 ** Discard the contents of the cache.
 */
 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
@@ -48935,7 +50073,7 @@ SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
   return pcacheSortDirtyList(pCache->pDirty);
 }
 
-/* 
+/*
 ** Return the total number of references to all pages held by the cache.
 **
 ** This is not the total number of pages referenced, but the sum of the
@@ -48952,7 +50090,7 @@ SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
   return p->nRef;
 }
 
-/* 
+/*
 ** Return the total number of pages in the cache.
 */
 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
@@ -48994,7 +50132,7 @@ SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
     p->szSpill = mxPage;
   }
   res = numberOfCachePages(p);
-  if( res<p->szSpill ) res = p->szSpill; 
+  if( res<p->szSpill ) res = p->szSpill;
   return res;
 }
 
@@ -49025,7 +50163,7 @@ SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
 }
 
 #ifdef SQLITE_DIRECT_OVERFLOW_READ
-/* 
+/*
 ** Return true if there are one or more dirty pages in the cache. Else false.
 */
 SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
@@ -49114,7 +50252,7 @@ SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHd
 **
 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
 ** that is allocated when the page cache is created.  The size of the local
-** bulk allocation can be adjusted using 
+** bulk allocation can be adjusted using
 **
 **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
 **
@@ -49139,16 +50277,16 @@ typedef struct PgFreeslot PgFreeslot;
 typedef struct PGroup PGroup;
 
 /*
-** Each cache entry is represented by an instance of the following 
+** Each cache entry is represented by an instance of the following
 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
-** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
+** PgHdr1.pCache->szPage bytes is allocated directly before this structure
 ** in memory.
 **
 ** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
-** but causes a 2-byte gap in the structure for most architectures (since 
+** but causes a 2-byte gap in the structure for most architectures (since
 ** pointers must be either 4 or 8-byte aligned). As this structure is located
 ** in memory directly after the associated page data, if the database is
-** corrupt, code at the b-tree layer may overread the page buffer and 
+** corrupt, code at the b-tree layer may overread the page buffer and
 ** read part of this structure before the corruption is detected. This
 ** can cause a valgrind error if the unitialized gap is accessed. Using u16
 ** ensures there is no such gap, and therefore no bytes of unitialized memory
@@ -49173,7 +50311,7 @@ struct PgHdr1 {
 #define PAGE_IS_PINNED(p)    ((p)->pLruNext==0)
 #define PAGE_IS_UNPINNED(p)  ((p)->pLruNext!=0)
 
-/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
+/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
 ** of one or more PCaches that are able to recycle each other's unpinned
 ** pages when they are under memory pressure.  A PGroup is an instance of
 ** the following object.
@@ -49209,13 +50347,13 @@ struct PGroup {
 ** temporary or transient database) has a single page cache which
 ** is an instance of this object.
 **
-** Pointers to structures of this type are cast and returned as 
+** Pointers to structures of this type are cast and returned as
 ** opaque sqlite3_pcache* handles.
 */
 struct PCache1 {
   /* Cache configuration parameters. Page size (szPage) and the purgeable
   ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
-  ** cache is created and are never changed thereafter. nMax may be 
+  ** cache is created and are never changed thereafter. nMax may be
   ** modified at any time by a call to the pcache1Cachesize() method.
   ** The PGroup mutex must be held when accessing nMax.
   */
@@ -49263,7 +50401,7 @@ static SQLITE_WSD struct PCacheGlobal {
   */
   int isInit;                    /* True if initialized */
   int separateCache;             /* Use a new PGroup for each PCache */
-  int nInitPage;                 /* Initial bulk allocation size */   
+  int nInitPage;                 /* Initial bulk allocation size */
   size_t szSlot;                 /* Size of each free slot */
   int nSlot;                     /* The number of pcache slots */
   int nReserve;                  /* Try to keep nFreeSlot above this */
@@ -49304,7 +50442,7 @@ static SQLITE_WSD struct PCacheGlobal {
 
 
 /*
-** This function is called during initialization if a static buffer is 
+** This function is called during initialization if a static buffer is
 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
 ** enough to contain 'n' buffers of 'sz' bytes each.
@@ -49374,8 +50512,8 @@ static int pcache1InitBulk(PCache1 *pCache){
 
 /*
 ** Malloc function used within this file to allocate space from the buffer
-** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
-** such buffer exists or there is no space left in it, this function falls 
+** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
+** such buffer exists or there is no space left in it, this function falls
 ** back to sqlite3Malloc().
 **
 ** Multiple threads can run this routine at the same time.  Global variables
@@ -49482,7 +50620,7 @@ static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
   }else{
 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
     /* The group mutex must be released before pcache1Alloc() is called. This
-    ** is because it might call sqlite3_release_memory(), which assumes that 
+    ** is because it might call sqlite3_release_memory(), which assumes that
     ** this mutex is not held. */
     assert( pcache1.separateCache==0 );
     assert( pCache->pGroup==&pcache1.grp );
@@ -49499,13 +50637,15 @@ static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
     }
 #else
     pPg = pcache1Alloc(pCache->szAlloc);
-    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
 #endif
     if( benignMalloc ){ sqlite3EndBenignMalloc(); }
 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
     pcache1EnterMutex(pCache->pGroup);
 #endif
     if( pPg==0 ) return 0;
+#ifndef SQLITE_PCACHE_SEPARATE_HEADER
+    p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
+#endif
     p->page.pBuf = pPg;
     p->page.pExtra = &p[1];
     p->isBulkLocal = 0;
@@ -49621,7 +50761,7 @@ static void pcache1ResizeHash(PCache1 *p){
 }
 
 /*
-** This function is used internally to remove the page pPage from the 
+** This function is used internally to remove the page pPage from the
 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
 ** LRU list, then this function is a no-op.
 **
@@ -49646,7 +50786,7 @@ static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
 
 
 /*
-** Remove the page supplied as an argument from the hash table 
+** Remove the page supplied as an argument from the hash table
 ** (PCache1.apHash structure) that it is currently stored in.
 ** Also free the page if freePage is true.
 **
@@ -49689,8 +50829,8 @@ static void pcache1EnforceMaxPage(PCache1 *pCache){
 }
 
 /*
-** Discard all pages from cache pCache with a page number (key value) 
-** greater than or equal to iLimit. Any pinned pages that meet this 
+** Discard all pages from cache pCache with a page number (key value)
+** greater than or equal to iLimit. Any pinned pages that meet this
 ** criteria are unpinned before they are discarded.
 **
 ** The PCache mutex must be held when this function is called.
@@ -49722,7 +50862,7 @@ static void pcache1TruncateUnsafe(
     PgHdr1 **pp;
     PgHdr1 *pPage;
     assert( h<pCache->nHash );
-    pp = &pCache->apHash[h]; 
+    pp = &pCache->apHash[h];
     while( (pPage = *pp)!=0 ){
       if( pPage->iKey>=iLimit ){
         pCache->nPage--;
@@ -49761,7 +50901,7 @@ static int pcache1Init(void *NotUsed){
   **
   **   *  Use a unified cache in single-threaded applications that have
   **      configured a start-time buffer for use as page-cache memory using
-  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL 
+  **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
   **      pBuf argument.
   **
   **   *  Otherwise use separate caches (mode-1)
@@ -49796,7 +50936,7 @@ static int pcache1Init(void *NotUsed){
 
 /*
 ** Implementation of the sqlite3_pcache.xShutdown method.
-** Note that the static mutex allocated in xInit does 
+** Note that the static mutex allocated in xInit does
 ** not need to be freed.
 */
 static void pcache1Shutdown(void *NotUsed){
@@ -49859,7 +50999,7 @@ static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
 }
 
 /*
-** Implementation of the sqlite3_pcache.xCachesize method. 
+** Implementation of the sqlite3_pcache.xCachesize method.
 **
 ** Configure the cache_size limit for a cache.
 */
@@ -49878,7 +51018,7 @@ static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
 }
 
 /*
-** Implementation of the sqlite3_pcache.xShrink method. 
+** Implementation of the sqlite3_pcache.xShrink method.
 **
 ** Free up as much memory as possible.
 */
@@ -49897,7 +51037,7 @@ static void pcache1Shrink(sqlite3_pcache *p){
 }
 
 /*
-** Implementation of the sqlite3_pcache.xPagecount method. 
+** Implementation of the sqlite3_pcache.xPagecount method.
 */
 static int pcache1Pagecount(sqlite3_pcache *p){
   int n;
@@ -49918,8 +51058,8 @@ static int pcache1Pagecount(sqlite3_pcache *p){
 ** for these steps, the main pcache1Fetch() procedure can run faster.
 */
 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
-  PCache1 *pCache, 
-  unsigned int iKey, 
+  PCache1 *pCache,
+  unsigned int iKey,
   int createFlag
 ){
   unsigned int nPinned;
@@ -49961,8 +51101,8 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
     }
   }
 
-  /* Step 5. If a usable page buffer has still not been found, 
-  ** attempt to allocate a new one. 
+  /* Step 5. If a usable page buffer has still not been found,
+  ** attempt to allocate a new one.
   */
   if( !pPage ){
     pPage = pcache1AllocPage(pCache, createFlag==1);
@@ -49987,13 +51127,13 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 }
 
 /*
-** Implementation of the sqlite3_pcache.xFetch method. 
+** Implementation of the sqlite3_pcache.xFetch method.
 **
 ** Fetch a page by key value.
 **
 ** Whether or not a new page may be allocated by this function depends on
 ** the value of the createFlag argument.  0 means do not allocate a new
-** page.  1 means allocate a new page if space is easily available.  2 
+** page.  1 means allocate a new page if space is easily available.  2
 ** means to try really hard to allocate a new page.
 **
 ** For a non-purgeable cache (a cache used as the storage for an in-memory
@@ -50004,7 +51144,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 ** There are three different approaches to obtaining space for a page,
 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
 **
-**   1. Regardless of the value of createFlag, the cache is searched for a 
+**   1. Regardless of the value of createFlag, the cache is searched for a
 **      copy of the requested page. If one is found, it is returned.
 **
 **   2. If createFlag==0 and the page is not already in the cache, NULL is
@@ -50018,13 +51158,13 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 **           PCache1.nMax, or
 **
 **       (b) the number of pages pinned by the cache is greater than
-**           the sum of nMax for all purgeable caches, less the sum of 
+**           the sum of nMax for all purgeable caches, less the sum of
 **           nMin for all other purgeable caches, or
 **
 **   4. If none of the first three conditions apply and the cache is marked
 **      as purgeable, and if one of the following is true:
 **
-**       (a) The number of pages allocated for the cache is already 
+**       (a) The number of pages allocated for the cache is already
 **           PCache1.nMax, or
 **
 **       (b) The number of pages allocated for all purgeable caches is
@@ -50036,7 +51176,7 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 **
 **      then attempt to recycle a page from the LRU list. If it is the right
 **      size, return the recycled buffer. Otherwise, free the buffer and
-**      proceed to step 5. 
+**      proceed to step 5.
 **
 **   5. Otherwise, allocate and return a new page buffer.
 **
@@ -50046,8 +51186,8 @@ static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
 ** invokes the appropriate routine.
 */
 static PgHdr1 *pcache1FetchNoMutex(
-  sqlite3_pcache *p, 
-  unsigned int iKey, 
+  sqlite3_pcache *p,
+  unsigned int iKey,
   int createFlag
 ){
   PCache1 *pCache = (PCache1 *)p;
@@ -50076,8 +51216,8 @@ static PgHdr1 *pcache1FetchNoMutex(
 }
 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
 static PgHdr1 *pcache1FetchWithMutex(
-  sqlite3_pcache *p, 
-  unsigned int iKey, 
+  sqlite3_pcache *p,
+  unsigned int iKey,
   int createFlag
 ){
   PCache1 *pCache = (PCache1 *)p;
@@ -50091,8 +51231,8 @@ static PgHdr1 *pcache1FetchWithMutex(
 }
 #endif
 static sqlite3_pcache_page *pcache1Fetch(
-  sqlite3_pcache *p, 
-  unsigned int iKey, 
+  sqlite3_pcache *p,
+  unsigned int iKey,
   int createFlag
 ){
 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
@@ -50122,18 +51262,18 @@ static sqlite3_pcache_page *pcache1Fetch(
 ** Mark a page as unpinned (eligible for asynchronous recycling).
 */
 static void pcache1Unpin(
-  sqlite3_pcache *p, 
-  sqlite3_pcache_page *pPg, 
+  sqlite3_pcache *p,
+  sqlite3_pcache_page *pPg,
   int reuseUnlikely
 ){
   PCache1 *pCache = (PCache1 *)p;
   PgHdr1 *pPage = (PgHdr1 *)pPg;
   PGroup *pGroup = pCache->pGroup;
+
   assert( pPage->pCache==pCache );
   pcache1EnterMutex(pGroup);
 
-  /* It is an error to call this function if the page is already 
+  /* It is an error to call this function if the page is already
   ** part of the PGroup LRU list.
   */
   assert( pPage->pLruNext==0 );
@@ -50154,7 +51294,7 @@ static void pcache1Unpin(
 }
 
 /*
-** Implementation of the sqlite3_pcache.xRekey method. 
+** Implementation of the sqlite3_pcache.xRekey method.
 */
 static void pcache1Rekey(
   sqlite3_pcache *p,
@@ -50165,7 +51305,7 @@ static void pcache1Rekey(
   PCache1 *pCache = (PCache1 *)p;
   PgHdr1 *pPage = (PgHdr1 *)pPg;
   PgHdr1 **pp;
-  unsigned int h; 
+  unsigned int h;
   assert( pPage->iKey==iOld );
   assert( pPage->pCache==pCache );
 
@@ -50190,7 +51330,7 @@ static void pcache1Rekey(
 }
 
 /*
-** Implementation of the sqlite3_pcache.xTruncate method. 
+** Implementation of the sqlite3_pcache.xTruncate method.
 **
 ** Discard all unpinned pages in the cache with a page number equal to
 ** or greater than parameter iLimit. Any pinned pages with a page number
@@ -50207,7 +51347,7 @@ static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
 }
 
 /*
-** Implementation of the sqlite3_pcache.xDestroy method. 
+** Implementation of the sqlite3_pcache.xDestroy method.
 **
 ** Destroy a cache allocated using pcache1Create().
 */
@@ -50273,7 +51413,7 @@ SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
 ** by the current thread may be sqlite3_free()ed.
 **
 ** nReq is the number of bytes of memory required. Once this much has
-** been released, the function returns. The return value is the total number 
+** been released, the function returns. The return value is the total number
 ** of bytes of memory released.
 */
 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
@@ -50364,7 +51504,7 @@ SQLITE_PRIVATE void sqlite3PcacheStats(
 ** extracts the least value from the RowSet.
 **
 ** The INSERT primitive might allocate additional memory.  Memory is
-** allocated in chunks so most INSERTs do no allocation.  There is an 
+** allocated in chunks so most INSERTs do no allocation.  There is an
 ** upper bound on the size of allocated memory.  No memory is freed
 ** until DESTROY.
 **
@@ -50412,7 +51552,7 @@ SQLITE_PRIVATE void sqlite3PcacheStats(
 ** in the list, pLeft points to the tree, and v is unused.  The
 ** RowSet.pForest value points to the head of this forest list.
 */
-struct RowSetEntry {            
+struct RowSetEntry {
   i64 v;                        /* ROWID value for this entry */
   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
@@ -50506,7 +51646,7 @@ SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
 /*
 ** Allocate a new RowSetEntry object that is associated with the
 ** given RowSet.  Return a pointer to the new and completely uninitialized
-** objected.
+** object.
 **
 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
 ** routine returns NULL.
@@ -50564,7 +51704,7 @@ SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
 /*
 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
 **
-** The input lists are connected via pRight pointers and are 
+** The input lists are connected via pRight pointers and are
 ** assumed to each already be in sorted order.
 */
 static struct RowSetEntry *rowSetEntryMerge(
@@ -50601,7 +51741,7 @@ static struct RowSetEntry *rowSetEntryMerge(
 /*
 ** Sort all elements on the list of RowSetEntry objects into order of
 ** increasing v.
-*/ 
+*/
 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
   unsigned int i;
   struct RowSetEntry *pNext, *aBucket[40];
@@ -50674,7 +51814,7 @@ static struct RowSetEntry *rowSetNDeepTree(
   struct RowSetEntry *pLeft;     /* Left subtree */
   if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
     /* Prevent unnecessary deep recursion when we run out of entries */
-    return 0; 
+    return 0;
   }
   if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
     /* This branch causes a *balanced* tree to be generated.  A valid tree
@@ -50782,7 +51922,7 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64
     if( p ){
       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
-        /* Only sort the current set of entiries if they need it */
+        /* Only sort the current set of entries if they need it */
         p = rowSetEntrySort(p);
       }
       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
@@ -50844,7 +51984,7 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64
 **
 *************************************************************************
 ** This is the implementation of the page cache subsystem or "pager".
-** 
+**
 ** The pager is used to access a database disk file.  It implements
 ** atomic commit and rollback through the use of a journal file that
 ** is separate from the database file.  The pager also implements file
@@ -50867,8 +52007,8 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64
 **    May you share freely, never taking more than you give.
 **
 *************************************************************************
-** This header file defines the interface to the write-ahead logging 
-** system. Refer to the comments below and the header comment attached to 
+** This header file defines the interface to the write-ahead logging
+** system. Refer to the comments below and the header comment attached to
 ** the implementation of each function in log.c for further details.
 */
 
@@ -50907,8 +52047,8 @@ SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64
 
 #define WAL_SAVEPOINT_NDATA 4
 
-/* Connection to a write-ahead log (WAL) file. 
-** There is one object of this type for each pager. 
+/* Connection to a write-ahead log (WAL) file.
+** There is one object of this type for each pager.
 */
 typedef struct Wal Wal;
 
@@ -50919,7 +52059,7 @@ SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8
 /* Set the limiting size of a WAL file. */
 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
 
-/* Used by readers to open (lock) and close (unlock) a snapshot.  A 
+/* Used by readers to open (lock) and close (unlock) a snapshot.  A
 ** snapshot is like a read-transaction.  It is the state of the database
 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
 ** preserves the current state even if the other threads or processes
@@ -50954,7 +52094,7 @@ SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
 /* Write a frame or frames to the log. */
 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
 
-/* Copy pages from the log to the database file */ 
+/* Copy pages from the log to the database file */
 SQLITE_PRIVATE int sqlite3WalCheckpoint(
   Wal *pWal,                      /* Write-ahead log connection */
   sqlite3 *db,                    /* Check this handle's interrupt flag */
@@ -50982,7 +52122,7 @@ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
 
 /* Return true if the argument is non-NULL and the WAL module is using
 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
-** WAL module is using shared-memory, return false. 
+** WAL module is using shared-memory, return false.
 */
 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
 
@@ -51004,6 +52144,11 @@ SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
 /* Return the sqlite3_file object for the WAL file */
 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
 
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock);
+SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db);
+#endif
+
 #endif /* ifndef SQLITE_OMIT_WAL */
 #endif /* SQLITE_WAL_H */
 
@@ -51024,60 +52169,60 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
 **
 ** Definition:  A page of the database file is said to be "overwriteable" if
 ** one or more of the following are true about the page:
-** 
+**
 **     (a)  The original content of the page as it was at the beginning of
 **          the transaction has been written into the rollback journal and
 **          synced.
-** 
+**
 **     (b)  The page was a freelist leaf page at the start of the transaction.
-** 
+**
 **     (c)  The page number is greater than the largest page that existed in
 **          the database file at the start of the transaction.
-** 
+**
 ** (1) A page of the database file is never overwritten unless one of the
 **     following are true:
-** 
+**
 **     (a) The page and all other pages on the same sector are overwriteable.
-** 
+**
 **     (b) The atomic page write optimization is enabled, and the entire
 **         transaction other than the update of the transaction sequence
 **         number consists of a single page change.
-** 
+**
 ** (2) The content of a page written into the rollback journal exactly matches
 **     both the content in the database when the rollback journal was written
 **     and the content in the database at the beginning of the current
 **     transaction.
-** 
+**
 ** (3) Writes to the database file are an integer multiple of the page size
 **     in length and are aligned on a page boundary.
-** 
+**
 ** (4) Reads from the database file are either aligned on a page boundary and
 **     an integer multiple of the page size in length or are taken from the
 **     first 100 bytes of the database file.
-** 
+**
 ** (5) All writes to the database file are synced prior to the rollback journal
 **     being deleted, truncated, or zeroed.
-** 
-** (6) If a master journal file is used, then all writes to the database file
-**     are synced prior to the master journal being deleted.
-** 
+**
+** (6) If a super-journal file is used, then all writes to the database file
+**     are synced prior to the super-journal being deleted.
+**
 ** Definition: Two databases (or the same database at two points it time)
 ** are said to be "logically equivalent" if they give the same answer to
 ** all queries.  Note in particular the content of freelist leaf
 ** pages can be changed arbitrarily without affecting the logical equivalence
 ** of the database.
-** 
+**
 ** (7) At any time, if any subset, including the empty set and the total set,
-**     of the unsynced changes to a rollback journal are removed and the 
+**     of the unsynced changes to a rollback journal are removed and the
 **     journal is rolled back, the resulting database file will be logically
 **     equivalent to the database file at the beginning of the transaction.
-** 
+**
 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
 **     is called to restore the database file to the same size it was at
 **     the beginning of the transaction.  (In some VFSes, the xTruncate
 **     method is a no-op, but that does not change the fact the SQLite will
 **     invoke it.)
-** 
+**
 ** (9) Whenever the database file is modified, at least one bit in the range
 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
 **     the EXCLUSIVE lock, thus signaling other connections on the same
@@ -51110,7 +52255,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 
 /*
 ** The following two macros are used within the PAGERTRACE() macros above
-** to print out file-descriptors. 
+** to print out file-descriptors.
 **
 ** PAGERID() takes a pointer to a Pager struct as its argument. The
 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
@@ -51131,7 +52276,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **               |              |                |
 **               |              V                |
 **               |<-------WRITER_LOCKED------> ERROR
-**               |              |                ^  
+**               |              |                ^
 **               |              V                |
 **               |<------WRITER_CACHEMOD-------->|
 **               |              |                |
@@ -51143,7 +52288,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **
 ** List of state transitions and the C [function] that performs each:
-** 
+**
 **   OPEN              -> READER              [sqlite3PagerSharedLock]
 **   READER            -> OPEN                [pager_unlock]
 **
@@ -51155,7 +52300,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **   WRITER_***        -> ERROR               [pager_error]
 **   ERROR             -> OPEN                [pager_unlock]
-** 
+**
 **
 **  OPEN:
 **
@@ -51169,9 +52314,9 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **  READER:
 **
-**    In this state all the requirements for reading the database in 
+**    In this state all the requirements for reading the database in
 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
-**    was) in exclusive-locking mode, a user-level read transaction is 
+**    was) in exclusive-locking mode, a user-level read transaction is
 **    open. The database size is known in this state.
 **
 **    A connection running with locking_mode=normal enters this state when
@@ -51181,28 +52326,28 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **    this state even after the read-transaction is closed. The only way
 **    a locking_mode=exclusive connection can transition from READER to OPEN
 **    is via the ERROR state (see below).
-** 
+**
 **    * A read transaction may be active (but a write-transaction cannot).
 **    * A SHARED or greater lock is held on the database file.
-**    * The dbSize variable may be trusted (even if a user-level read 
+**    * The dbSize variable may be trusted (even if a user-level read
 **      transaction is not active). The dbOrigSize and dbFileSize variables
 **      may not be trusted at this point.
 **    * If the database is a WAL database, then the WAL connection is open.
-**    * Even if a read-transaction is not open, it is guaranteed that 
+**    * Even if a read-transaction is not open, it is guaranteed that
 **      there is no hot-journal in the file-system.
 **
 **  WRITER_LOCKED:
 **
 **    The pager moves to this state from READER when a write-transaction
-**    is first opened on the database. In WRITER_LOCKED state, all locks 
-**    required to start a write-transaction are held, but no actual 
+**    is first opened on the database. In WRITER_LOCKED state, all locks
+**    required to start a write-transaction are held, but no actual
 **    modifications to the cache or database have taken place.
 **
-**    In rollback mode, a RESERVED or (if the transaction was opened with 
+**    In rollback mode, a RESERVED or (if the transaction was opened with
 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
-**    moving to this state, but the journal file is not written to or opened 
-**    to in this state. If the transaction is committed or rolled back while 
-**    in WRITER_LOCKED state, all that is required is to unlock the database 
+**    moving to this state, but the journal file is not written to or opened
+**    to in this state. If the transaction is committed or rolled back while
+**    in WRITER_LOCKED state, all that is required is to unlock the database
 **    file.
 **
 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
@@ -51210,7 +52355,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **    is made to obtain an EXCLUSIVE lock on the database file.
 **
 **    * A write transaction is active.
-**    * If the connection is open in rollback-mode, a RESERVED or greater 
+**    * If the connection is open in rollback-mode, a RESERVED or greater
 **      lock is held on the database file.
 **    * If the connection is open in WAL-mode, a WAL write transaction
 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
@@ -51229,7 +52374,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **    * A write transaction is active.
 **    * A RESERVED or greater lock is held on the database file.
-**    * The journal file is open and the first header has been written 
+**    * The journal file is open and the first header has been written
 **      to it, but the header has not been synced to disk.
 **    * The contents of the page cache have been modified.
 **
@@ -51242,7 +52387,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **    * A write transaction is active.
 **    * An EXCLUSIVE or greater lock is held on the database file.
-**    * The journal file is open and the first header has been written 
+**    * The journal file is open and the first header has been written
 **      and synced to disk.
 **    * The contents of the page cache have been modified (and possibly
 **      written to disk).
@@ -51254,8 +52399,8 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
 **    state after the entire transaction has been successfully written into the
 **    database file. In this state the transaction may be committed simply
-**    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
-**    not possible to modify the database further. At this point, the upper 
+**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
+**    not possible to modify the database further. At this point, the upper
 **    layer must either commit or rollback the transaction.
 **
 **    * A write transaction is active.
@@ -51263,19 +52408,19 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **    * All writing and syncing of journal and database data has finished.
 **      If no error occurred, all that remains is to finalize the journal to
 **      commit the transaction. If an error did occur, the caller will need
-**      to rollback the transaction. 
+**      to rollback the transaction.
 **
 **  ERROR:
 **
 **    The ERROR state is entered when an IO or disk-full error (including
-**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
-**    difficult to be sure that the in-memory pager state (cache contents, 
+**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
+**    difficult to be sure that the in-memory pager state (cache contents,
 **    db size etc.) are consistent with the contents of the file-system.
 **
 **    Temporary pager files may enter the ERROR state, but in-memory pagers
 **    cannot.
 **
-**    For example, if an IO error occurs while performing a rollback, 
+**    For example, if an IO error occurs while performing a rollback,
 **    the contents of the page-cache may be left in an inconsistent state.
 **    At this point it would be dangerous to change back to READER state
 **    (as usually happens after a rollback). Any subsequent readers might
@@ -51285,13 +52430,13 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **    instead of READER following such an error.
 **
 **    Once it has entered the ERROR state, any attempt to use the pager
-**    to read or write data returns an error. Eventually, once all 
+**    to read or write data returns an error. Eventually, once all
 **    outstanding transactions have been abandoned, the pager is able to
-**    transition back to OPEN state, discarding the contents of the 
+**    transition back to OPEN state, discarding the contents of the
 **    page-cache and any other in-memory state at the same time. Everything
 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
 **    when a read-transaction is next opened on the pager (transitioning
-**    the pager into READER state). At that point the system has recovered 
+**    the pager into READER state). At that point the system has recovered
 **    from the error.
 **
 **    Specifically, the pager jumps into the ERROR state if:
@@ -51307,21 +52452,21 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **         memory.
 **
 **    In other cases, the error is returned to the b-tree layer. The b-tree
-**    layer then attempts a rollback operation. If the error condition 
+**    layer then attempts a rollback operation. If the error condition
 **    persists, the pager enters the ERROR state via condition (1) above.
 **
 **    Condition (3) is necessary because it can be triggered by a read-only
 **    statement executed within a transaction. In this case, if the error
 **    code were simply returned to the user, the b-tree layer would not
 **    automatically attempt a rollback, as it assumes that an error in a
-**    read-only statement cannot leave the pager in an internally inconsistent 
+**    read-only statement cannot leave the pager in an internally inconsistent
 **    state.
 **
 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
 **    * There are one or more outstanding references to pages (after the
 **      last reference is dropped the pager should move back to OPEN state).
 **    * The pager is not an in-memory pager.
-**    
+**
 **
 ** Notes:
 **
@@ -51331,7 +52476,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
 **     state. There are two exceptions: immediately after exclusive-mode has
-**     been turned on (and before any read or write transactions are 
+**     been turned on (and before any read or write transactions are
 **     executed), and when the pager is leaving the "error state".
 **
 **   * See also: assert_pager_state().
@@ -51345,7 +52490,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 #define PAGER_ERROR                 6
 
 /*
-** The Pager.eLock variable is almost always set to one of the 
+** The Pager.eLock variable is almost always set to one of the
 ** following locking-states, according to the lock currently held on
 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
 ** This variable is kept up to date as locks are taken and released by
@@ -51360,20 +52505,20 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 ** to a less exclusive (lower) value than the lock that is actually held
 ** at the system level, but it is never set to a more exclusive value.
 **
-** This is usually safe. If an xUnlock fails or appears to fail, there may 
+** This is usually safe. If an xUnlock fails or appears to fail, there may
 ** be a few redundant xLock() calls or a lock may be held for longer than
 ** required, but nothing really goes wrong.
 **
 ** The exception is when the database file is unlocked as the pager moves
-** from ERROR to OPEN state. At this point there may be a hot-journal file 
+** from ERROR to OPEN state. At this point there may be a hot-journal file
 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
 ** transition, by the same pager or any other). If the call to xUnlock()
 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
 ** can confuse the call to xCheckReservedLock() call made later as part
 ** of hot-journal detection.
 **
-** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
-** lock held by this process or any others". So xCheckReservedLock may 
+** xCheckReservedLock() is defined as returning true "if there is a RESERVED
+** lock held by this process or any others". So xCheckReservedLock may
 ** return true because the caller itself is holding an EXCLUSIVE lock (but
 ** doesn't know it because of a previous error in xUnlock). If this happens
 ** a hot-journal may be mistaken for a journal being created by an active
@@ -51384,32 +52529,18 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
 ** is only changed back to a real locking state after a successful call
 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
-** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
+** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
 ** lock on the database file before attempting to roll it back. See function
 ** PagerSharedLock() for more detail.
 **
-** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
+** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
 ** PAGER_OPEN state.
 */
 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
 
 /*
-** A macro used for invoking the codec if there is one
-*/
-#ifdef SQLITE_HAS_CODEC
-# define CODEC1(P,D,N,X,E) \
-    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
-# define CODEC2(P,D,N,X,E,O) \
-    if( P->xCodec==0 ){ O=(char*)D; }else \
-    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
-#else
-# define CODEC1(P,D,N,X,E)   /* NO-OP */
-# define CODEC2(P,D,N,X,E,O) O=(char*)D
-#endif
-
-/*
-** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
+** The maximum allowed sector size. 64KiB. If the xSectorsize() method
 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
 ** This could conceivably cause corruption following a power failure on
 ** such a system. This is currently an undocumented limit.
@@ -51425,7 +52556,7 @@ int sqlite3PagerTrace=1;  /* True to enable tracing */
 **
 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
 ** set to 0. If a journal-header is written into the main journal while
-** the savepoint is active, then iHdrOffset is set to the byte offset 
+** the savepoint is active, then iHdrOffset is set to the byte offset
 ** immediately following the last journal record written into the main
 ** journal before the journal-header. This is required during savepoint
 ** rollback (see pagerPlaybackSavepoint()).
@@ -51475,44 +52606,44 @@ struct PagerSavepoint {
 **
 ** changeCountDone
 **
-**   This boolean variable is used to make sure that the change-counter 
-**   (the 4-byte header field at byte offset 24 of the database file) is 
-**   not updated more often than necessary. 
+**   This boolean variable is used to make sure that the change-counter
+**   (the 4-byte header field at byte offset 24 of the database file) is
+**   not updated more often than necessary.
 **
-**   It is set to true when the change-counter field is updated, which 
+**   It is set to true when the change-counter field is updated, which
 **   can only happen if an exclusive lock is held on the database file.
-**   It is cleared (set to false) whenever an exclusive lock is 
+**   It is cleared (set to false) whenever an exclusive lock is
 **   relinquished on the database file. Each time a transaction is committed,
 **   The changeCountDone flag is inspected. If it is true, the work of
 **   updating the change-counter is omitted for the current transaction.
 **
-**   This mechanism means that when running in exclusive mode, a connection 
+**   This mechanism means that when running in exclusive mode, a connection
 **   need only update the change-counter once, for the first transaction
 **   committed.
 **
-** setMaster
+** setSuper
 **
 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
-**   (or may not) specify a master-journal name to be written into the 
+**   (or may not) specify a super-journal name to be written into the
 **   journal file before it is synced to disk.
 **
-**   Whether or not a journal file contains a master-journal pointer affects 
-**   the way in which the journal file is finalized after the transaction is 
+**   Whether or not a journal file contains a super-journal pointer affects
+**   the way in which the journal file is finalized after the transaction is
 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
-**   If a journal file does not contain a master-journal pointer, it is
+**   If a journal file does not contain a super-journal pointer, it is
 **   finalized by overwriting the first journal header with zeroes. If
-**   it does contain a master-journal pointer the journal file is finalized 
-**   by truncating it to zero bytes, just as if the connection were 
+**   it does contain a super-journal pointer the journal file is finalized
+**   by truncating it to zero bytes, just as if the connection were
 **   running in "journal_mode=truncate" mode.
 **
-**   Journal files that contain master journal pointers cannot be finalized
+**   Journal files that contain super-journal pointers cannot be finalized
 **   simply by overwriting the first journal-header with zeroes, as the
-**   master journal pointer could interfere with hot-journal rollback of any
+**   super-journal pointer could interfere with hot-journal rollback of any
 **   subsequently interrupted transaction that reuses the journal file.
 **
 **   The flag is cleared as soon as the journal file is finalized (either
 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
-**   journal file from being successfully finalized, the setMaster flag
+**   journal file from being successfully finalized, the setSuper flag
 **   is cleared anyway (and the pager will move to ERROR state).
 **
 ** doNotSpill
@@ -51528,12 +52659,12 @@ struct PagerSavepoint {
 **   to allocate a new page to prevent the journal file from being written
 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
 **   case is a user preference.
-** 
+**
 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
 **   pagerStress() is permitted, but syncing the journal file is not.
 **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
 **   is larger than the database page-size in order to prevent a journal sync
-**   from happening in between the journalling of two pages on the same sector. 
+**   from happening in between the journalling of two pages on the same sector.
 **
 ** subjInMemory
 **
@@ -51541,16 +52672,16 @@ struct PagerSavepoint {
 **   is opened as an in-memory journal file. If false, then in-memory
 **   sub-journals are only used for in-memory pager files.
 **
-**   This variable is updated by the upper layer each time a new 
+**   This variable is updated by the upper layer each time a new
 **   write-transaction is opened.
 **
 ** dbSize, dbOrigSize, dbFileSize
 **
 **   Variable dbSize is set to the number of pages in the database file.
 **   It is valid in PAGER_READER and higher states (all states except for
-**   OPEN and ERROR). 
+**   OPEN and ERROR).
 **
-**   dbSize is set based on the size of the database file, which may be 
+**   dbSize is set based on the size of the database file, which may be
 **   larger than the size of the database (the value stored at offset
 **   28 of the database header by the btree). If the size of the file
 **   is not an integer multiple of the page-size, the value stored in
@@ -51561,10 +52692,10 @@ struct PagerSavepoint {
 **
 **   During a write-transaction, if pages with page-numbers greater than
 **   dbSize are modified in the cache, dbSize is updated accordingly.
-**   Similarly, if the database is truncated using PagerTruncateImage(), 
+**   Similarly, if the database is truncated using PagerTruncateImage(),
 **   dbSize is updated.
 **
-**   Variables dbOrigSize and dbFileSize are valid in states 
+**   Variables dbOrigSize and dbFileSize are valid in states
 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
 **   variable at the start of the transaction. It is used during rollback,
 **   and to determine whether or not pages need to be journalled before
@@ -51573,12 +52704,12 @@ struct PagerSavepoint {
 **   Throughout a write-transaction, dbFileSize contains the size of
 **   the file on disk in pages. It is set to a copy of dbSize when the
 **   write-transaction is first opened, and updated when VFS calls are made
-**   to write or truncate the database file on disk. 
+**   to write or truncate the database file on disk.
 **
-**   The only reason the dbFileSize variable is required is to suppress 
-**   unnecessary calls to xTruncate() after committing a transaction. If, 
-**   when a transaction is committed, the dbFileSize variable indicates 
-**   that the database file is larger than the database image (Pager.dbSize), 
+**   The only reason the dbFileSize variable is required is to suppress
+**   unnecessary calls to xTruncate() after committing a transaction. If,
+**   when a transaction is committed, the dbFileSize variable indicates
+**   that the database file is larger than the database image (Pager.dbSize),
 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
 **   to measure the database file on disk, and then truncates it if required.
 **   dbFileSize is not used when rolling back a transaction. In this case
@@ -51589,20 +52720,20 @@ struct PagerSavepoint {
 ** dbHintSize
 **
 **   The dbHintSize variable is used to limit the number of calls made to
-**   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
+**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
 **
 **   dbHintSize is set to a copy of the dbSize variable when a
 **   write-transaction is opened (at the same time as dbFileSize and
 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
 **   dbHintSize is increased to the number of pages that correspond to the
-**   size-hint passed to the method call. See pager_write_pagelist() for 
+**   size-hint passed to the method call. See pager_write_pagelist() for
 **   details.
 **
 ** errCode
 **
 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
-**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
-**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
+**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
+**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
 **   sub-codes.
 **
 ** syncFlags, walSyncFlags
@@ -51644,7 +52775,7 @@ struct Pager {
   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
   u8 eLock;                   /* Current lock held on database file */
   u8 changeCountDone;         /* Set after incrementing the change-counter */
-  u8 setMaster;               /* True if a m-j name has been written to jrnl */
+  u8 setSuper;                /* Super-jrnl name is written into jrnl */
   u8 doNotSpill;              /* Do not spill the cache when non-zero */
   u8 subjInMemory;            /* True to use in-memory sub-journals */
   u8 bUseFetch;               /* True to use xFetch() */
@@ -51693,12 +52824,6 @@ struct Pager {
 #endif
   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
   int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
-#ifdef SQLITE_HAS_CODEC
-  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
-  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
-  void (*xCodecFree)(void*);             /* Destructor for the codec */
-  void *pCodec;               /* First argument to xCodec... methods */
-#endif
   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
   PCache *pPCache;            /* Pointer to page cache object */
 #ifndef SQLITE_OMIT_WAL
@@ -51709,7 +52834,7 @@ struct Pager {
 
 /*
 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
-** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
+** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
 ** or CACHE_WRITE to sqlite3_db_status().
 */
 #define PAGER_STAT_HIT   0
@@ -51767,7 +52892,7 @@ static const unsigned char aJournalMagic[] = {
 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
 
 /*
-** The journal header size for this pager. This is usually the same 
+** The journal header size for this pager. This is usually the same
 ** size as a single disk sector. See also setSectorSize().
 */
 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
@@ -51795,11 +52920,6 @@ static const unsigned char aJournalMagic[] = {
 #endif
 
 /*
-** The maximum legal page number is (2^31 - 1).
-*/
-#define PAGER_MAX_PGNO 2147483647
-
-/*
 ** The argument to this macro is a file descriptor (type sqlite3_file*).
 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
 **
@@ -51825,9 +52945,6 @@ static const unsigned char aJournalMagic[] = {
 SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
   if( pPager->fd->pMethods==0 ) return 0;
   if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
-#ifdef SQLITE_HAS_CODEC
-  if( pPager->xCodec!=0 ) return 0;
-#endif
 #ifndef SQLITE_OMIT_WAL
   if( pPager->pWal ){
     u32 iRead = 0;
@@ -51850,7 +52967,7 @@ SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
 # define pagerBeginReadTransaction(z) SQLITE_OK
 #endif
 
-#ifndef NDEBUG 
+#ifndef NDEBUG
 /*
 ** Usage:
 **
@@ -51879,25 +52996,25 @@ static int assert_pager_state(Pager *p){
   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
   assert( p->tempFile==0 || pPager->changeCountDone );
 
-  /* If the useJournal flag is clear, the journal-mode must be "OFF". 
+  /* If the useJournal flag is clear, the journal-mode must be "OFF".
   ** And if the journal-mode is "OFF", the journal file must not be open.
   */
   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
 
-  /* Check that MEMDB implies noSync. And an in-memory journal. Since 
-  ** this means an in-memory pager performs no IO at all, it cannot encounter 
-  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
-  ** a journal file. (although the in-memory journal implementation may 
-  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
-  ** is therefore not possible for an in-memory pager to enter the ERROR 
+  /* Check that MEMDB implies noSync. And an in-memory journal. Since
+  ** this means an in-memory pager performs no IO at all, it cannot encounter
+  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
+  ** a journal file. (although the in-memory journal implementation may
+  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
+  ** is therefore not possible for an in-memory pager to enter the ERROR
   ** state.
   */
   if( MEMDB ){
     assert( !isOpen(p->fd) );
     assert( p->noSync );
-    assert( p->journalMode==PAGER_JOURNALMODE_OFF 
-         || p->journalMode==PAGER_JOURNALMODE_MEMORY 
+    assert( p->journalMode==PAGER_JOURNALMODE_OFF
+         || p->journalMode==PAGER_JOURNALMODE_MEMORY
     );
     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
     assert( pagerUseWal(p)==0 );
@@ -51931,7 +53048,7 @@ static int assert_pager_state(Pager *p){
       assert( pPager->dbSize==pPager->dbOrigSize );
       assert( pPager->dbOrigSize==pPager->dbFileSize );
       assert( pPager->dbOrigSize==pPager->dbHintSize );
-      assert( pPager->setMaster==0 );
+      assert( pPager->setSuper==0 );
       break;
 
     case PAGER_WRITER_CACHEMOD:
@@ -51944,9 +53061,9 @@ static int assert_pager_state(Pager *p){
         ** to journal_mode=wal.
         */
         assert( p->eLock>=RESERVED_LOCK );
-        assert( isOpen(p->jfd) 
-             || p->journalMode==PAGER_JOURNALMODE_OFF 
-             || p->journalMode==PAGER_JOURNALMODE_WAL 
+        assert( isOpen(p->jfd)
+             || p->journalMode==PAGER_JOURNALMODE_OFF
+             || p->journalMode==PAGER_JOURNALMODE_WAL
         );
       }
       assert( pPager->dbOrigSize==pPager->dbFileSize );
@@ -51958,9 +53075,9 @@ static int assert_pager_state(Pager *p){
       assert( pPager->errCode==SQLITE_OK );
       assert( !pagerUseWal(pPager) );
       assert( p->eLock>=EXCLUSIVE_LOCK );
-      assert( isOpen(p->jfd) 
-           || p->journalMode==PAGER_JOURNALMODE_OFF 
-           || p->journalMode==PAGER_JOURNALMODE_WAL 
+      assert( isOpen(p->jfd)
+           || p->journalMode==PAGER_JOURNALMODE_OFF
+           || p->journalMode==PAGER_JOURNALMODE_WAL
            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
       );
       assert( pPager->dbOrigSize<=pPager->dbHintSize );
@@ -51970,9 +53087,9 @@ static int assert_pager_state(Pager *p){
       assert( p->eLock==EXCLUSIVE_LOCK );
       assert( pPager->errCode==SQLITE_OK );
       assert( !pagerUseWal(pPager) );
-      assert( isOpen(p->jfd) 
-           || p->journalMode==PAGER_JOURNALMODE_OFF 
-           || p->journalMode==PAGER_JOURNALMODE_WAL 
+      assert( isOpen(p->jfd)
+           || p->journalMode==PAGER_JOURNALMODE_OFF
+           || p->journalMode==PAGER_JOURNALMODE_WAL
            || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
       );
       break;
@@ -51991,7 +53108,7 @@ static int assert_pager_state(Pager *p){
 }
 #endif /* ifndef NDEBUG */
 
-#ifdef SQLITE_DEBUG 
+#ifdef SQLITE_DEBUG
 /*
 ** Return a pointer to a human readable string in a static buffer
 ** containing the state of the Pager object passed as an argument. This
@@ -52061,11 +53178,7 @@ static void setGetterMethod(Pager *pPager){
   if( pPager->errCode ){
     pPager->xGet = getPageError;
 #if SQLITE_MAX_MMAP_SIZE>0
-  }else if( USEFETCH(pPager)
-#ifdef SQLITE_HAS_CODEC
-   && pPager->xCodec==0
-#endif
-  ){
+  }else if( USEFETCH(pPager) ){
     pPager->xGet = getPageMMap;
 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
   }else{
@@ -52143,7 +53256,7 @@ static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
 **
 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
-** called, do not modify it. See the comment above the #define of 
+** called, do not modify it. See the comment above the #define of
 ** UNKNOWN_LOCK for an explanation of this.
 */
 static int pagerUnlockDb(Pager *pPager, int eLock){
@@ -52160,17 +53273,18 @@ static int pagerUnlockDb(Pager *pPager, int eLock){
     }
     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
   }
+  pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
   return rc;
 }
 
 /*
 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
-** Pager.eLock variable to the new locking state. 
+** Pager.eLock variable to the new locking state.
 **
-** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
-** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
-** See the comment above the #define of UNKNOWN_LOCK for an explanation 
+** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
+** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
+** See the comment above the #define of UNKNOWN_LOCK for an explanation
 ** of this.
 */
 static int pagerLockDb(Pager *pPager, int eLock){
@@ -52197,7 +53311,7 @@ static int pagerLockDb(Pager *pPager, int eLock){
 **  (b) the value returned by OsSectorSize() is less than or equal
 **      to the page size.
 **
-** If it can be used, then the value returned is the size of the journal 
+** If it can be used, then the value returned is the size of the journal
 ** file when it contains rollback data for exactly one page.
 **
 ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
@@ -52288,72 +53402,73 @@ static void checkPage(PgHdr *pPg){
 
 /*
 ** When this is called the journal file for pager pPager must be open.
-** This function attempts to read a master journal file name from the 
-** end of the file and, if successful, copies it into memory supplied 
-** by the caller. See comments above writeMasterJournal() for the format
-** used to store a master journal file name at the end of a journal file.
+** This function attempts to read a super-journal file name from the
+** end of the file and, if successful, copies it into memory supplied
+** by the caller. See comments above writeSuperJournal() for the format
+** used to store a super-journal file name at the end of a journal file.
 **
-** zMaster must point to a buffer of at least nMaster bytes allocated by
+** zSuper must point to a buffer of at least nSuper bytes allocated by
 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
-** enough space to write the master journal name). If the master journal
-** name in the journal is longer than nMaster bytes (including a
-** nul-terminator), then this is handled as if no master journal name
+** enough space to write the super-journal name). If the super-journal
+** name in the journal is longer than nSuper bytes (including a
+** nul-terminator), then this is handled as if no super-journal name
 ** were present in the journal.
 **
-** If a master journal file name is present at the end of the journal
-** file, then it is copied into the buffer pointed to by zMaster. A
-** nul-terminator byte is appended to the buffer following the master
-** journal file name.
+** If a super-journal file name is present at the end of the journal
+** file, then it is copied into the buffer pointed to by zSuper. A
+** nul-terminator byte is appended to the buffer following the
+** super-journal file name.
 **
-** If it is determined that no master journal file name is present 
-** zMaster[0] is set to 0 and SQLITE_OK returned.
+** If it is determined that no super-journal file name is present
+** zSuper[0] is set to 0 and SQLITE_OK returned.
 **
 ** If an error occurs while reading from the journal file, an SQLite
 ** error code is returned.
 */
-static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
+static int readSuperJournal(sqlite3_file *pJrnl, char *zSuper, u32 nSuper){
   int rc;                    /* Return code */
-  u32 len;                   /* Length in bytes of master journal name */
+  u32 len;                   /* Length in bytes of super-journal name */
   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
   u32 cksum;                 /* MJ checksum value read from journal */
   u32 u;                     /* Unsigned loop counter */
   unsigned char aMagic[8];   /* A buffer to hold the magic header */
-  zMaster[0] = '\0';
+  zSuper[0] = '\0';
 
   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
    || szJ<16
    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
-   || len>=nMaster 
+   || len>=nSuper
    || len>szJ-16
-   || len==0 
+   || len==0
    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
    || memcmp(aMagic, aJournalMagic, 8)
-   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
+   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
   ){
     return rc;
   }
 
-  /* See if the checksum matches the master journal name */
+  /* See if the checksum matches the super-journal name */
   for(u=0; u<len; u++){
-    cksum -= zMaster[u];
+    cksum -= zSuper[u];
   }
   if( cksum ){
     /* If the checksum doesn't add up, then one or more of the disk sectors
-    ** containing the master journal filename is corrupted. This means
+    ** containing the super-journal filename is corrupted. This means
     ** definitely roll back, so just return SQLITE_OK and report a (nul)
-    ** master-journal filename.
+    ** super-journal filename.
     */
     len = 0;
   }
-  zMaster[len] = '\0';
-   
+  zSuper[len] = '\0';
+  zSuper[len+1] = '\0';
+
   return SQLITE_OK;
 }
 
 /*
-** Return the offset of the sector boundary at or immediately 
-** following the value in pPager->journalOff, assuming a sector 
+** Return the offset of the sector boundary at or immediately
+** following the value in pPager->journalOff, assuming a sector
 ** size of pPager->sectorSize bytes.
 **
 ** i.e for a sector size of 512:
@@ -52364,7 +53479,7 @@ static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
 **   512                       512
 **   100                       512
 **   2000                      2048
-** 
+**
 */
 static i64 journalHdrOffset(Pager *pPager){
   i64 offset = 0;
@@ -52386,12 +53501,12 @@ static i64 journalHdrOffset(Pager *pPager){
 **
 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
-** zero the 28-byte header at the start of the journal file. In either case, 
-** if the pager is not in no-sync mode, sync the journal file immediately 
+** zero the 28-byte header at the start of the journal file. In either case,
+** if the pager is not in no-sync mode, sync the journal file immediately
 ** after writing or truncating it.
 **
 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
-** following the truncation or zeroing described above the size of the 
+** following the truncation or zeroing described above the size of the
 ** journal file in bytes is larger than this value, then truncate the
 ** journal file to Pager.journalSizeLimit bytes. The journal file does
 ** not need to be synced following this operation.
@@ -52417,8 +53532,8 @@ static int zeroJournalHdr(Pager *pPager, int doTruncate){
       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
     }
 
-    /* At this point the transaction is committed but the write lock 
-    ** is still held on the file. If there is a size limit configured for 
+    /* At this point the transaction is committed but the write lock
+    ** is still held on the file. If there is a size limit configured for
     ** the persistent journal and the journal file currently consumes more
     ** space than that limit allows for, truncate it now. There is no need
     ** to sync the file following this operation.
@@ -52446,7 +53561,7 @@ static int zeroJournalHdr(Pager *pPager, int doTruncate){
 ** - 4 bytes: Initial database page count.
 ** - 4 bytes: Sector size used by the process that wrote this journal.
 ** - 4 bytes: Database page size.
-** 
+**
 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
 */
 static int writeJournalHdr(Pager *pPager){
@@ -52462,8 +53577,8 @@ static int writeJournalHdr(Pager *pPager){
     nHeader = JOURNAL_HDR_SZ(pPager);
   }
 
-  /* If there are active savepoints and any of them were created 
-  ** since the most recent journal header was written, update the 
+  /* If there are active savepoints and any of them were created
+  ** since the most recent journal header was written, update the
   ** PagerSavepoint.iHdrOffset fields now.
   */
   for(ii=0; ii<pPager->nSavepoint; ii++){
@@ -52474,10 +53589,10 @@ static int writeJournalHdr(Pager *pPager){
 
   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
 
-  /* 
+  /*
   ** Write the nRec Field - the number of page records that follow this
   ** journal header. Normally, zero is written to this value at this time.
-  ** After the records are added to the journal (and the journal synced, 
+  ** After the records are added to the journal (and the journal synced,
   ** if in full-sync mode), the zero is overwritten with the true number
   ** of records (see syncJournal()).
   **
@@ -52496,7 +53611,7 @@ static int writeJournalHdr(Pager *pPager){
   */
   assert( isOpen(pPager->fd) || pPager->noSync );
   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
-   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
+   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
   ){
     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
@@ -52504,7 +53619,7 @@ static int writeJournalHdr(Pager *pPager){
     memset(zHeader, 0, sizeof(aJournalMagic)+4);
   }
 
-  /* The random check-hash initializer */ 
+  /* The random check-hash initializer */
   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
   /* The initial database size */
@@ -52523,23 +53638,23 @@ static int writeJournalHdr(Pager *pPager){
   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
          nHeader-(sizeof(aJournalMagic)+20));
 
-  /* In theory, it is only necessary to write the 28 bytes that the 
-  ** journal header consumes to the journal file here. Then increment the 
-  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
+  /* In theory, it is only necessary to write the 28 bytes that the
+  ** journal header consumes to the journal file here. Then increment the
+  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
   ** record is written to the following sector (leaving a gap in the file
   ** that will be implicitly filled in by the OS).
   **
-  ** However it has been discovered that on some systems this pattern can 
+  ** However it has been discovered that on some systems this pattern can
   ** be significantly slower than contiguously writing data to the file,
-  ** even if that means explicitly writing data to the block of 
+  ** even if that means explicitly writing data to the block of
   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
-  ** is done. 
+  ** is done.
   **
-  ** The loop is required here in case the sector-size is larger than the 
+  ** The loop is required here in case the sector-size is larger than the
   ** database page size. Since the zHeader buffer is only Pager.pageSize
   ** bytes in size, more than one call to sqlite3OsWrite() may be required
   ** to populate the entire journal header sector.
-  */ 
+  */
   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
@@ -52637,29 +53752,29 @@ static int readJournalHdr(
 
     /* Check that the values read from the page-size and sector-size fields
     ** are within range. To be 'in range', both values need to be a power
-    ** of two greater than or equal to 512 or 32, and not greater than their 
+    ** of two greater than or equal to 512 or 32, and not greater than their
     ** respective compile time maximum limits.
     */
     if( iPageSize<512                  || iSectorSize<32
      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
-     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
+     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
     ){
-      /* If the either the page-size or sector-size in the journal-header is 
-      ** invalid, then the process that wrote the journal-header must have 
-      ** crashed before the header was synced. In this case stop reading 
+      /* If the either the page-size or sector-size in the journal-header is
+      ** invalid, then the process that wrote the journal-header must have
+      ** crashed before the header was synced. In this case stop reading
       ** the journal file here.
       */
       return SQLITE_DONE;
     }
 
-    /* Update the page-size to match the value read from the journal. 
-    ** Use a testcase() macro to make sure that malloc failure within 
+    /* Update the page-size to match the value read from the journal.
+    ** Use a testcase() macro to make sure that malloc failure within
     ** PagerSetPagesize() is tested.
     */
     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
     testcase( rc!=SQLITE_OK );
 
-    /* Update the assumed sector-size to match the value used by 
+    /* Update the assumed sector-size to match the value used by
     ** the process that created this journal. If this journal was
     ** created by a process other than this one, then this routine
     ** is being called from within pager_playback(). The local value
@@ -52674,50 +53789,50 @@ static int readJournalHdr(
 
 
 /*
-** Write the supplied master journal name into the journal file for pager
-** pPager at the current location. The master journal name must be the last
+** Write the supplied super-journal name into the journal file for pager
+** pPager at the current location. The super-journal name must be the last
 ** thing written to a journal file. If the pager is in full-sync mode, the
 ** journal file descriptor is advanced to the next sector boundary before
 ** anything is written. The format is:
 **
 **   + 4 bytes: PAGER_MJ_PGNO.
-**   + N bytes: Master journal filename in utf-8.
-**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
-**   + 4 bytes: Master journal name checksum.
+**   + N bytes: super-journal filename in utf-8.
+**   + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
+**   + 4 bytes: super-journal name checksum.
 **   + 8 bytes: aJournalMagic[].
 **
-** The master journal page checksum is the sum of the bytes in the master
-** journal name, where each byte is interpreted as a signed 8-bit integer.
+** The super-journal page checksum is the sum of the bytes in thesuper-journal
+** name, where each byte is interpreted as a signed 8-bit integer.
 **
-** If zMaster is a NULL pointer (occurs for a single database transaction), 
+** If zSuper is a NULL pointer (occurs for a single database transaction),
 ** this call is a no-op.
 */
-static int writeMasterJournal(Pager *pPager, const char *zMaster){
+static int writeSuperJournal(Pager *pPager, const char *zSuper){
   int rc;                          /* Return code */
-  int nMaster;                     /* Length of string zMaster */
+  int nSuper;                      /* Length of string zSuper */
   i64 iHdrOff;                     /* Offset of header in journal file */
   i64 jrnlSize;                    /* Size of journal file on disk */
-  u32 cksum = 0;                   /* Checksum of string zMaster */
+  u32 cksum = 0;                   /* Checksum of string zSuper */
 
-  assert( pPager->setMaster==0 );
+  assert( pPager->setSuper==0 );
   assert( !pagerUseWal(pPager) );
 
-  if( !zMaster 
-   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
+  if( !zSuper
+   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
    || !isOpen(pPager->jfd)
   ){
     return SQLITE_OK;
   }
-  pPager->setMaster = 1;
+  pPager->setSuper = 1;
   assert( pPager->journalHdr <= pPager->journalOff );
 
-  /* Calculate the length in bytes and the checksum of zMaster */
-  for(nMaster=0; zMaster[nMaster]; nMaster++){
-    cksum += zMaster[nMaster];
+  /* Calculate the length in bytes and the checksum of zSuper */
+  for(nSuper=0; zSuper[nSuper]; nSuper++){
+    cksum += zSuper[nSuper];
   }
 
   /* If in full-sync mode, advance to the next disk sector before writing
-  ** the master journal name. This is in case the previous page written to
+  ** the super-journal name. This is in case the previous page written to
   ** the journal has already been synced.
   */
   if( pPager->fullSync ){
@@ -52725,30 +53840,30 @@ static int writeMasterJournal(Pager *pPager, const char *zMaster){
   }
   iHdrOff = pPager->journalOff;
 
-  /* Write the master journal data to the end of the journal file. If
+  /* Write the super-journal data to the end of the journal file. If
   ** an error occurs, return the error code to the caller.
   */
   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
-   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
-   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
-   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
+   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
+   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
+   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
-                                 iHdrOff+4+nMaster+8)))
+                                 iHdrOff+4+nSuper+8)))
   ){
     return rc;
   }
-  pPager->journalOff += (nMaster+20);
+  pPager->journalOff += (nSuper+20);
 
-  /* If the pager is in peristent-journal mode, then the physical 
-  ** journal-file may extend past the end of the master-journal name
-  ** and 8 bytes of magic data just written to the file. This is 
+  /* If the pager is in peristent-journal mode, then the physical
+  ** journal-file may extend past the end of the super-journal name
+  ** and 8 bytes of magic data just written to the file. This is
   ** dangerous because the code to rollback a hot-journal file
-  ** will not be able to find the master-journal name to determine 
-  ** whether or not the journal is hot. 
+  ** will not be able to find the super-journal name to determine
+  ** whether or not the journal is hot.
   **
-  ** Easiest thing to do in this scenario is to truncate the journal 
+  ** Easiest thing to do in this scenario is to truncate the journal
   ** file to the required size.
-  */ 
+  */
   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
    && jrnlSize>pPager->journalOff
   ){
@@ -52793,7 +53908,7 @@ static void releaseAllSavepoints(Pager *pPager){
 }
 
 /*
-** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
+** Set the bit number pgno in the PagerSavepoint.pInSavepoint
 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
 ** or SQLITE_NOMEM if a malloc failure occurs.
 */
@@ -52822,8 +53937,8 @@ static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
 ** closed (if it is open).
 **
-** If the pager is in ERROR state when this function is called, the 
-** contents of the pager cache are discarded before switching back to 
+** If the pager is in ERROR state when this function is called, the
+** contents of the pager cache are discarded before switching back to
 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
 ** or not, any journal file left in the file-system will be treated
 ** as a hot-journal and rolled back the next time a read-transaction
@@ -52831,9 +53946,9 @@ static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
 */
 static void pager_unlock(Pager *pPager){
 
-  assert( pPager->eState==PAGER_READER 
-       || pPager->eState==PAGER_OPEN 
-       || pPager->eState==PAGER_ERROR 
+  assert( pPager->eState==PAGER_READER
+       || pPager->eState==PAGER_OPEN
+       || pPager->eState==PAGER_ERROR
   );
 
   sqlite3BitvecDestroy(pPager->pInJournal);
@@ -52880,7 +53995,6 @@ static void pager_unlock(Pager *pPager){
     ** code is cleared and the cache reset in the block below.
     */
     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
-    pPager->changeCountDone = 0;
     pPager->eState = PAGER_OPEN;
   }
 
@@ -52905,23 +54019,23 @@ static void pager_unlock(Pager *pPager){
 
   pPager->journalOff = 0;
   pPager->journalHdr = 0;
-  pPager->setMaster = 0;
+  pPager->setSuper = 0;
 }
 
 /*
 ** This function is called whenever an IOERR or FULL error that requires
 ** the pager to transition into the ERROR state may ahve occurred.
-** The first argument is a pointer to the pager structure, the second 
-** the error-code about to be returned by a pager API function. The 
-** value returned is a copy of the second argument to this function. 
+** The first argument is a pointer to the pager structure, the second
+** the error-code about to be returned by a pager API function. The
+** value returned is a copy of the second argument to this function.
 **
 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
 ** IOERR sub-codes, the pager enters the ERROR state and the error code
 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
 ** all major API calls on the Pager will immediately return Pager.errCode.
 **
-** The ERROR state indicates that the contents of the pager-cache 
-** cannot be trusted. This state can be cleared by completely discarding 
+** The ERROR state indicates that the contents of the pager-cache
+** cannot be trusted. This state can be cleared by completely discarding
 ** the contents of the pager-cache. If a transaction was active when
 ** the persistent error occurred, then the rollback journal may need
 ** to be replayed to restore the contents of the database file (as if
@@ -52969,27 +54083,27 @@ static int pagerFlushOnCommit(Pager *pPager, int bCommit){
 }
 
 /*
-** This routine ends a transaction. A transaction is usually ended by 
-** either a COMMIT or a ROLLBACK operation. This routine may be called 
+** This routine ends a transaction. A transaction is usually ended by
+** either a COMMIT or a ROLLBACK operation. This routine may be called
 ** after rollback of a hot-journal, or if an error occurs while opening
 ** the journal file or writing the very first journal-header of a
 ** database transaction.
-** 
+**
 ** This routine is never called in PAGER_ERROR state. If it is called
 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
 ** exclusive than a RESERVED lock, it is a no-op.
 **
 ** Otherwise, any active savepoints are released.
 **
-** If the journal file is open, then it is "finalized". Once a journal 
-** file has been finalized it is not possible to use it to roll back a 
+** If the journal file is open, then it is "finalized". Once a journal
+** file has been finalized it is not possible to use it to roll back a
 ** transaction. Nor will it be considered to be a hot-journal by this
 ** or any other database connection. Exactly how a journal is finalized
 ** depends on whether or not the pager is running in exclusive mode and
 ** the current journal-mode (Pager.journalMode value), as follows:
 **
 **   journalMode==MEMORY
-**     Journal file descriptor is simply closed. This destroys an 
+**     Journal file descriptor is simply closed. This destroys an
 **     in-memory journal.
 **
 **   journalMode==TRUNCATE
@@ -53009,19 +54123,19 @@ static int pagerFlushOnCommit(Pager *pPager, int bCommit){
 **     journalMode==PERSIST is used instead.
 **
 ** After the journal is finalized, the pager moves to PAGER_READER state.
-** If running in non-exclusive rollback mode, the lock on the file is 
+** If running in non-exclusive rollback mode, the lock on the file is
 ** downgraded to a SHARED_LOCK.
 **
 ** SQLITE_OK is returned if no error occurs. If an error occurs during
 ** any of the IO operations to finalize the journal file or unlock the
-** database then the IO error code is returned to the user. If the 
+** database then the IO error code is returned to the user. If the
 ** operation to finalize the journal file fails, then the code still
 ** tries to unlock the database file if not in exclusive mode. If the
 ** unlock operation fails as well, then the first error code related
 ** to the first error encountered (the journal finalization one) is
 ** returned.
 */
-static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
+static int pager_end_transaction(Pager *pPager, int hasSuper, int bCommit){
   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
 
@@ -53033,9 +54147,9 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   **   1. After a successful hot-journal rollback, it is called with
   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
   **
-  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
+  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
   **      lock switches back to locking_mode=normal and then executes a
-  **      read-transaction, this function is called with eState==PAGER_READER 
+  **      read-transaction, this function is called with eState==PAGER_READER
   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
   */
   assert( assert_pager_state(pPager) );
@@ -53045,7 +54159,7 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   }
 
   releaseAllSavepoints(pPager);
-  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 
+  assert( isOpen(pPager->jfd) || pPager->pInJournal==0
       || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
   );
   if( isOpen(pPager->jfd) ){
@@ -53073,7 +54187,7 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
     ){
-      rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
+      rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
       pPager->journalOff = 0;
     }else{
       /* This branch may be executed with Pager.journalMode==MEMORY if
@@ -53083,9 +54197,9 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
       */
       int bDelete = !pPager->tempFile;
       assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
-      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
-           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
-           || pPager->journalMode==PAGER_JOURNALMODE_WAL 
+      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
+           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
+           || pPager->journalMode==PAGER_JOURNALMODE_WAL
       );
       sqlite3OsClose(pPager->jfd);
       if( bDelete ){
@@ -53118,8 +54232,8 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   }
 
   if( pagerUseWal(pPager) ){
-    /* Drop the WAL write-lock, if any. Also, if the connection was in 
-    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
+    /* Drop the WAL write-lock, if any. Also, if the connection was in
+    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
     ** lock held on the database file.
     */
     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
@@ -53127,7 +54241,7 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
     /* This branch is taken when committing a transaction in rollback-journal
     ** mode if the database file on disk is larger than the database image.
-    ** At this point the journal has been finalized and the transaction 
+    ** At this point the journal has been finalized and the transaction
     ** successfully committed, but the EXCLUSIVE lock is still held on the
     ** file. So it is safe to truncate the database file to its minimum
     ** required size.  */
@@ -53140,32 +54254,31 @@ static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   }
 
-  if( !pPager->exclusiveMode 
+  if( !pPager->exclusiveMode
    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
   ){
     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
-    pPager->changeCountDone = 0;
   }
   pPager->eState = PAGER_READER;
-  pPager->setMaster = 0;
+  pPager->setSuper = 0;
 
   return (rc==SQLITE_OK?rc2:rc);
 }
 
 /*
-** Execute a rollback if a transaction is active and unlock the 
-** database file. 
+** Execute a rollback if a transaction is active and unlock the
+** database file.
 **
-** If the pager has already entered the ERROR state, do not attempt 
+** If the pager has already entered the ERROR state, do not attempt
 ** the rollback at this time. Instead, pager_unlock() is called. The
 ** call to pager_unlock() will discard all in-memory pages, unlock
-** the database file and move the pager back to OPEN state. If this 
-** means that there is a hot-journal left in the file-system, the next 
-** connection to obtain a shared lock on the pager (which may be this one) 
+** the database file and move the pager back to OPEN state. If this
+** means that there is a hot-journal left in the file-system, the next
+** connection to obtain a shared lock on the pager (which may be this one)
 ** will roll it back.
 **
 ** If the pager has not already entered the ERROR state, but an IO or
-** malloc error occurs during a rollback, then this will itself cause 
+** malloc error occurs during a rollback, then this will itself cause
 ** the pager to enter the ERROR state. Which will be cleared by the
 ** call to pager_unlock(), as described above.
 */
@@ -53186,10 +54299,10 @@ static void pagerUnlockAndRollback(Pager *pPager){
 
 /*
 ** Parameter aData must point to a buffer of pPager->pageSize bytes
-** of data. Compute and return a checksum based ont the contents of the 
+** of data. Compute and return a checksum based ont the contents of the
 ** page of data and the current value of pPager->cksumInit.
 **
-** This is not a real checksum. It is really just the sum of the 
+** This is not a real checksum. It is really just the sum of the
 ** random initial value (pPager->cksumInit) and every 200th byte
 ** of the page data, starting with byte offset (pPager->pageSize%200).
 ** Each byte is interpreted as an 8-bit unsigned integer.
@@ -53197,8 +54310,8 @@ static void pagerUnlockAndRollback(Pager *pPager){
 ** Changing the formula used to compute this checksum results in an
 ** incompatible journal file format.
 **
-** If journal corruption occurs due to a power failure, the most likely 
-** scenario is that one end or the other of the record will be changed. 
+** If journal corruption occurs due to a power failure, the most likely
+** scenario is that one end or the other of the record will be changed.
 ** It is much less likely that the two ends of the journal record will be
 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
 ** though fast and simple, catches the mostly likely kind of corruption.
@@ -53214,41 +54327,12 @@ static u32 pager_cksum(Pager *pPager, const u8 *aData){
 }
 
 /*
-** Report the current page size and number of reserved bytes back
-** to the codec.
-*/
-#ifdef SQLITE_HAS_CODEC
-static void pagerReportSize(Pager *pPager){
-  if( pPager->xCodecSizeChng ){
-    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
-                           (int)pPager->nReserve);
-  }
-}
-#else
-# define pagerReportSize(X)     /* No-op if we do not support a codec */
-#endif
-
-#ifdef SQLITE_HAS_CODEC
-/*
-** Make sure the number of reserved bits is the same in the destination
-** pager as it is in the source.  This comes up when a VACUUM changes the
-** number of reserved bits to the "optimal" amount.
-*/
-SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
-  if( pDest->nReserve!=pSrc->nReserve ){
-    pDest->nReserve = pSrc->nReserve;
-    pagerReportSize(pDest);
-  }
-}
-#endif
-
-/*
 ** Read a single page from either the journal file (if isMainJrnl==1) or
 ** from the sub-journal (if isMainJrnl==0) and playback that page.
 ** The page begins at offset *pOffset into the file. The *pOffset
 ** value is increased to the start of the next page in the journal.
 **
-** The main rollback journal uses checksums - the statement journal does 
+** The main rollback journal uses checksums - the statement journal does
 ** not.
 **
 ** If the page number of the page record read from the (sub-)journal file
@@ -53268,7 +54352,7 @@ SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
 ** is successfully read from the (sub-)journal file but appears to be
 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
 ** two circumstances:
-** 
+**
 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
 **   * If the record is being rolled back from the main journal file
 **     and the checksum field does not match the record content.
@@ -53293,11 +54377,6 @@ static int pager_playback_one_page(
   char *aData;                  /* Temporary storage for the page */
   sqlite3_file *jfd;            /* The file descriptor for the journal file */
   int isSynced;                 /* True if journal page is synced */
-#ifdef SQLITE_HAS_CODEC
-  /* The jrnlEnc flag is true if Journal pages should be passed through
-  ** the codec.  It is false for pure in-memory journals. */
-  const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
-#endif
 
   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
@@ -53308,7 +54387,7 @@ static int pager_playback_one_page(
   assert( aData );         /* Temp storage must have already been allocated */
   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
 
-  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
+  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
   ** or savepoint rollback done at the request of the caller) or this is
   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
@@ -53360,7 +54439,6 @@ static int pager_playback_one_page(
   */
   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
     pPager->nReserve = ((u8*)aData)[20];
-    pagerReportSize(pPager);
   }
 
   /* If the pager is in CACHEMOD state, then there must be a copy of this
@@ -53375,7 +54453,7 @@ static int pager_playback_one_page(
   ** assert()able.
   **
   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
-  ** pager cache if it exists and the main file. The page is then marked 
+  ** pager cache if it exists and the main file. The page is then marked
   ** not dirty. Since this code is only executed in PAGER_OPEN state for
   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
   ** if the pager is in OPEN state.
@@ -53428,43 +54506,29 @@ static int pager_playback_one_page(
     ** is if the data was just read from an in-memory sub-journal. In that
     ** case it must be encrypted here before it is copied into the database
     ** file.  */
-#ifdef SQLITE_HAS_CODEC
-    if( !jrnlEnc ){
-      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
-      rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
-      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
-    }else
-#endif
     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
 
     if( pgno>pPager->dbFileSize ){
       pPager->dbFileSize = pgno;
     }
     if( pPager->pBackup ){
-#ifdef SQLITE_HAS_CODEC
-      if( jrnlEnc ){
-        CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
-        sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
-        CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
-      }else
-#endif
       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
     }
   }else if( !isMainJrnl && pPg==0 ){
     /* If this is a rollback of a savepoint and data was not written to
     ** the database and the page is not in-memory, there is a potential
-    ** problem. When the page is next fetched by the b-tree layer, it 
-    ** will be read from the database file, which may or may not be 
-    ** current. 
+    ** problem. When the page is next fetched by the b-tree layer, it
+    ** will be read from the database file, which may or may not be
+    ** current.
     **
     ** There are a couple of different ways this can happen. All are quite
-    ** obscure. When running in synchronous mode, this can only happen 
+    ** obscure. When running in synchronous mode, this can only happen
     ** if the page is on the free-list at the start of the transaction, then
     ** populated, then moved using sqlite3PagerMovepage().
     **
     ** The solution is to add an in-memory page to the cache containing
-    ** the data just read from the sub-journal. Mark the page as dirty 
-    ** and if the pager requires a journal-sync, then mark the page as 
+    ** the data just read from the sub-journal. Mark the page as dirty
+    ** and if the pager requires a journal-sync, then mark the page as
     ** requiring a journal-sync before it is written.
     */
     assert( isSavepnt );
@@ -53498,164 +54562,167 @@ static int pager_playback_one_page(
     if( pgno==1 ){
       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
     }
-
-    /* Decode the page just read from disk */
-#if SQLITE_HAS_CODEC
-    if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
-#endif
     sqlite3PcacheRelease(pPg);
   }
   return rc;
 }
 
 /*
-** Parameter zMaster is the name of a master journal file. A single journal
-** file that referred to the master journal file has just been rolled back.
-** This routine checks if it is possible to delete the master journal file,
+** Parameter zSuper is the name of a super-journal file. A single journal
+** file that referred to the super-journal file has just been rolled back.
+** This routine checks if it is possible to delete the super-journal file,
 ** and does so if it is.
 **
-** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
+** Argument zSuper may point to Pager.pTmpSpace. So that buffer is not
 ** available for use within this function.
 **
-** When a master journal file is created, it is populated with the names 
-** of all of its child journals, one after another, formatted as utf-8 
-** encoded text. The end of each child journal file is marked with a 
-** nul-terminator byte (0x00). i.e. the entire contents of a master journal
+** When a super-journal file is created, it is populated with the names
+** of all of its child journals, one after another, formatted as utf-8
+** encoded text. The end of each child journal file is marked with a
+** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
 ** file for a transaction involving two databases might be:
 **
 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
 **
-** A master journal file may only be deleted once all of its child 
+** A super-journal file may only be deleted once all of its child
 ** journals have been rolled back.
 **
-** This function reads the contents of the master-journal file into 
+** This function reads the contents of the super-journal file into
 ** memory and loops through each of the child journal names. For
 ** each child journal, it checks if:
 **
 **   * if the child journal exists, and if so
-**   * if the child journal contains a reference to master journal 
-**     file zMaster
+**   * if the child journal contains a reference to super-journal
+**     file zSuper
 **
 ** If a child journal can be found that matches both of the criteria
 ** above, this function returns without doing anything. Otherwise, if
-** no such child journal can be found, file zMaster is deleted from
+** no such child journal can be found, file zSuper is deleted from
 ** the file-system using sqlite3OsDelete().
 **
 ** If an IO error within this function, an error code is returned. This
 ** function allocates memory by calling sqlite3Malloc(). If an allocation
-** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
+** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
 ** occur, SQLITE_OK is returned.
 **
 ** TODO: This function allocates a single block of memory to load
-** the entire contents of the master journal file. This could be
-** a couple of kilobytes or so - potentially larger than the page 
+** the entire contents of the super-journal file. This could be
+** a couple of kilobytes or so - potentially larger than the page
 ** size.
 */
-static int pager_delmaster(Pager *pPager, const char *zMaster){
+static int pager_delsuper(Pager *pPager, const char *zSuper){
   sqlite3_vfs *pVfs = pPager->pVfs;
   int rc;                   /* Return code */
-  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
+  sqlite3_file *pSuper;     /* Malloc'd super-journal file descriptor */
   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
-  char *zMasterJournal = 0; /* Contents of master journal file */
-  i64 nMasterJournal;       /* Size of master journal file */
+  char *zSuperJournal = 0;  /* Contents of super-journal file */
+  i64 nSuperJournal;        /* Size of super-journal file */
   char *zJournal;           /* Pointer to one journal within MJ file */
-  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
-  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
+  char *zSuperPtr;          /* Space to hold super-journal filename */
+  char *zFree = 0;          /* Free this buffer */
+  int nSuperPtr;            /* Amount of space allocated to zSuperPtr[] */
 
-  /* Allocate space for both the pJournal and pMaster file descriptors.
-  ** If successful, open the master journal file for reading.
+  /* Allocate space for both the pJournal and pSuper file descriptors.
+  ** If successful, open the super-journal file for reading.
   */
-  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
-  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
-  if( !pMaster ){
+  pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
+  if( !pSuper ){
     rc = SQLITE_NOMEM_BKPT;
+    pJournal = 0;
   }else{
-    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
-    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
+    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
+    rc = sqlite3OsOpen(pVfs, zSuper, pSuper, flags, 0);
+    pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
   }
-  if( rc!=SQLITE_OK ) goto delmaster_out;
+  if( rc!=SQLITE_OK ) goto delsuper_out;
 
-  /* Load the entire master journal file into space obtained from
-  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
-  ** sufficient space (in zMasterPtr) to hold the names of master
-  ** journal files extracted from regular rollback-journals.
+  /* Load the entire super-journal file into space obtained from
+  ** sqlite3_malloc() and pointed to by zSuperJournal.   Also obtain
+  ** sufficient space (in zSuperPtr) to hold the names of super-journal
+  ** files extracted from regular rollback-journals.
   */
-  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
-  if( rc!=SQLITE_OK ) goto delmaster_out;
-  nMasterPtr = pVfs->mxPathname+1;
-  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
-  if( !zMasterJournal ){
+  rc = sqlite3OsFileSize(pSuper, &nSuperJournal);
+  if( rc!=SQLITE_OK ) goto delsuper_out;
+  nSuperPtr = pVfs->mxPathname+1;
+  zFree = sqlite3Malloc(4 + nSuperJournal + nSuperPtr + 2);
+  if( !zFree ){
     rc = SQLITE_NOMEM_BKPT;
-    goto delmaster_out;
-  }
-  zMasterPtr = &zMasterJournal[nMasterJournal+1];
-  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
-  if( rc!=SQLITE_OK ) goto delmaster_out;
-  zMasterJournal[nMasterJournal] = 0;
-
-  zJournal = zMasterJournal;
-  while( (zJournal-zMasterJournal)<nMasterJournal ){
+    goto delsuper_out;
+  }
+  zFree[0] = zFree[1] = zFree[2] = zFree[3] = 0;
+  zSuperJournal = &zFree[4];
+  zSuperPtr = &zSuperJournal[nSuperJournal+2];
+  rc = sqlite3OsRead(pSuper, zSuperJournal, (int)nSuperJournal, 0);
+  if( rc!=SQLITE_OK ) goto delsuper_out;
+  zSuperJournal[nSuperJournal] = 0;
+  zSuperJournal[nSuperJournal+1] = 0;
+
+  zJournal = zSuperJournal;
+  while( (zJournal-zSuperJournal)<nSuperJournal ){
     int exists;
     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
     if( rc!=SQLITE_OK ){
-      goto delmaster_out;
+      goto delsuper_out;
     }
     if( exists ){
-      /* One of the journals pointed to by the master journal exists.
-      ** Open it and check if it points at the master journal. If
-      ** so, return without deleting the master journal file.
+      /* One of the journals pointed to by the super-journal exists.
+      ** Open it and check if it points at the super-journal. If
+      ** so, return without deleting the super-journal file.
+      ** NB:  zJournal is really a MAIN_JOURNAL.  But call it a
+      ** SUPER_JOURNAL here so that the VFS will not send the zJournal
+      ** name into sqlite3_database_file_object().
       */
       int c;
-      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
+      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_SUPER_JOURNAL);
       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
       if( rc!=SQLITE_OK ){
-        goto delmaster_out;
+        goto delsuper_out;
       }
 
-      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
+      rc = readSuperJournal(pJournal, zSuperPtr, nSuperPtr);
       sqlite3OsClose(pJournal);
       if( rc!=SQLITE_OK ){
-        goto delmaster_out;
+        goto delsuper_out;
       }
 
-      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
+      c = zSuperPtr[0]!=0 && strcmp(zSuperPtr, zSuper)==0;
       if( c ){
-        /* We have a match. Do not delete the master journal file. */
-        goto delmaster_out;
+        /* We have a match. Do not delete the super-journal file. */
+        goto delsuper_out;
       }
     }
     zJournal += (sqlite3Strlen30(zJournal)+1);
   }
-  sqlite3OsClose(pMaster);
-  rc = sqlite3OsDelete(pVfs, zMaster, 0);
 
-delmaster_out:
-  sqlite3_free(zMasterJournal);
-  if( pMaster ){
-    sqlite3OsClose(pMaster);
+  sqlite3OsClose(pSuper);
+  rc = sqlite3OsDelete(pVfs, zSuper, 0);
+
+delsuper_out:
+  sqlite3_free(zFree);
+  if( pSuper ){
+    sqlite3OsClose(pSuper);
     assert( !isOpen(pJournal) );
-    sqlite3_free(pMaster);
+    sqlite3_free(pSuper);
   }
   return rc;
 }
 
 
 /*
-** This function is used to change the actual size of the database 
+** This function is used to change the actual size of the database
 ** file in the file-system. This only happens when committing a transaction,
 ** or rolling back a transaction (including rolling back a hot-journal).
 **
 ** If the main database file is not open, or the pager is not in either
-** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
-** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
+** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
+** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
 ** If the file on disk is currently larger than nPage pages, then use the VFS
 ** xTruncate() method to truncate it.
 **
-** Or, it might be the case that the file on disk is smaller than 
-** nPage pages. Some operating system implementations can get confused if 
-** you try to truncate a file to some size that is larger than it 
-** currently is, so detect this case and write a single zero byte to 
+** Or, it might be the case that the file on disk is smaller than
+** nPage pages. Some operating system implementations can get confused if
+** you try to truncate a file to some size that is larger than it
+** currently is, so detect this case and write a single zero byte to
 ** the end of the new file instead.
 **
 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
@@ -53665,9 +54732,9 @@ static int pager_truncate(Pager *pPager, Pgno nPage){
   int rc = SQLITE_OK;
   assert( pPager->eState!=PAGER_ERROR );
   assert( pPager->eState!=PAGER_READER );
-  
-  if( isOpen(pPager->fd) 
-   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
+
+  if( isOpen(pPager->fd)
+   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
   ){
     i64 currentSize, newSize;
     int szPage = pPager->pageSize;
@@ -53711,9 +54778,9 @@ SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
 /*
 ** Set the value of the Pager.sectorSize variable for the given
 ** pager based on the value returned by the xSectorSize method
-** of the open database file. The sector size will be used 
-** to determine the size and alignment of journal header and 
-** master journal pointers within created journal files.
+** of the open database file. The sector size will be used
+** to determine the size and alignment of journal header and
+** super-journal pointers within created journal files.
 **
 ** For temporary files the effective sector size is always 512 bytes.
 **
@@ -53735,7 +54802,7 @@ static void setSectorSize(Pager *pPager){
   assert( isOpen(pPager->fd) || pPager->tempFile );
 
   if( pPager->tempFile
-   || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
+   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
   ){
     /* Sector size doesn't matter for temporary files. Also, the file
@@ -53749,15 +54816,15 @@ static void setSectorSize(Pager *pPager){
 
 /*
 ** Playback the journal and thus restore the database file to
-** the state it was in before we started making changes.  
+** the state it was in before we started making changes.
 **
-** The journal file format is as follows: 
+** The journal file format is as follows:
 **
 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
 **  (2)  4 byte big-endian integer which is the number of valid page records
 **       in the journal.  If this value is 0xffffffff, then compute the
 **       number of page records from the journal size.
-**  (3)  4 byte big-endian integer which is the initial value for the 
+**  (3)  4 byte big-endian integer which is the initial value for the
 **       sanity checksum.
 **  (4)  4 byte integer which is the number of pages to truncate the
 **       database to during a rollback.
@@ -53786,7 +54853,7 @@ static void setSectorSize(Pager *pPager){
 ** from the file size.  This value is used when the user selects the
 ** no-sync option for the journal.  A power failure could lead to corruption
 ** in this case.  But for things like temporary table (which will be
-** deleted when the power is restored) we don't care.  
+** deleted when the power is restored) we don't care.
 **
 ** If the file opened as the journal file is not a well-formed
 ** journal file then all pages up to the first corrupted page are rolled
@@ -53798,7 +54865,7 @@ static void setSectorSize(Pager *pPager){
 ** and an error code is returned.
 **
 ** The isHot parameter indicates that we are trying to rollback a journal
-** that might be a hot journal.  Or, it could be that the journal is 
+** that might be a hot journal.  Or, it could be that the journal is
 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
 ** If the journal really is hot, reset the pager cache prior rolling
 ** back any content.  If the journal is merely persistent, no reset is
@@ -53812,7 +54879,7 @@ static int pager_playback(Pager *pPager, int isHot){
   Pgno mxPg = 0;           /* Size of the original file in pages */
   int rc;                  /* Result code of a subroutine */
   int res = 1;             /* Value returned by sqlite3OsAccess() */
-  char *zMaster = 0;       /* Name of master journal file if any */
+  char *zSuper = 0;        /* Name of super-journal file if any */
   int needPagerReset;      /* True to reset page prior to first page rollback */
   int nPlayback = 0;       /* Total number of pages restored from journal */
   u32 savedPageSize = pPager->pageSize;
@@ -53826,8 +54893,8 @@ static int pager_playback(Pager *pPager, int isHot){
     goto end_playback;
   }
 
-  /* Read the master journal name from the journal, if it is present.
-  ** If a master journal file name is specified, but the file is not
+  /* Read the super-journal name from the journal, if it is present.
+  ** If a super-journal file name is specified, but the file is not
   ** present on disk, then the journal is not hot and does not need to be
   ** played back.
   **
@@ -53837,21 +54904,21 @@ static int pager_playback(Pager *pPager, int isHot){
   ** mxPathname is 512, which is the same as the minimum allowable value
   ** for pageSize.
   */
-  zMaster = pPager->pTmpSpace;
-  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
-  if( rc==SQLITE_OK && zMaster[0] ){
-    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
+  zSuper = pPager->pTmpSpace;
+  rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
+  if( rc==SQLITE_OK && zSuper[0] ){
+    rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
   }
-  zMaster = 0;
+  zSuper = 0;
   if( rc!=SQLITE_OK || !res ){
     goto end_playback;
   }
   pPager->journalOff = 0;
   needPagerReset = isHot;
 
-  /* This loop terminates either when a readJournalHdr() or 
-  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
-  ** occurs. 
+  /* This loop terminates either when a readJournalHdr() or
+  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
+  ** occurs.
   */
   while( 1 ){
     /* Read the next journal header from the journal file.  If there are
@@ -53860,7 +54927,7 @@ static int pager_playback(Pager *pPager, int isHot){
     ** This indicates nothing more needs to be rolled back.
     */
     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
-    if( rc!=SQLITE_OK ){ 
+    if( rc!=SQLITE_OK ){
       if( rc==SQLITE_DONE ){
         rc = SQLITE_OK;
       }
@@ -53888,7 +54955,7 @@ static int pager_playback(Pager *pPager, int isHot){
     ** chunk of the journal contains zero pages to be rolled back.  But
     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
     ** the journal, it means that the journal might contain additional
-    ** pages that need to be rolled back and that the number of pages 
+    ** pages that need to be rolled back and that the number of pages
     ** should be computed based on the journal file size.
     */
     if( nRec==0 && !isHot &&
@@ -53907,7 +54974,7 @@ static int pager_playback(Pager *pPager, int isHot){
       pPager->dbSize = mxPg;
     }
 
-    /* Copy original pages out of the journal and back into the 
+    /* Copy original pages out of the journal and back into the
     ** database file and/or page cache.
     */
     for(u=0; u<nRec; u++){
@@ -53957,10 +55024,10 @@ end_playback:
   sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
 #endif
 
-  /* If this playback is happening automatically as a result of an IO or 
-  ** malloc error that occurred after the change-counter was updated but 
-  ** before the transaction was committed, then the change-counter 
-  ** modification may just have been reverted. If this happens in exclusive 
+  /* If this playback is happening automatically as a result of an IO or
+  ** malloc error that occurred after the change-counter was updated but
+  ** before the transaction was committed, then the change-counter
+  ** modification may just have been reverted. If this happens in exclusive
   ** mode, then subsequent transactions performed by the connection will not
   ** update the change-counter at all. This may lead to cache inconsistency
   ** problems for other processes at some point in the future. So, just
@@ -53969,8 +55036,12 @@ end_playback:
   pPager->changeCountDone = pPager->tempFile;
 
   if( rc==SQLITE_OK ){
-    zMaster = pPager->pTmpSpace;
-    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
+    /* Leave 4 bytes of space before the super-journal filename in memory.
+    ** This is because it may end up being passed to sqlite3OsOpen(), in
+    ** which case it requires 4 0x00 bytes in memory immediately before
+    ** the filename. */
+    zSuper = &pPager->pTmpSpace[4];
+    rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
     testcase( rc!=SQLITE_OK );
   }
   if( rc==SQLITE_OK
@@ -53979,14 +55050,16 @@ end_playback:
     rc = sqlite3PagerSync(pPager, 0);
   }
   if( rc==SQLITE_OK ){
-    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
+    rc = pager_end_transaction(pPager, zSuper[0]!='\0', 0);
     testcase( rc!=SQLITE_OK );
   }
-  if( rc==SQLITE_OK && zMaster[0] && res ){
-    /* If there was a master journal and this routine will return success,
-    ** see if it is possible to delete the master journal.
+  if( rc==SQLITE_OK && zSuper[0] && res ){
+    /* If there was a super-journal and this routine will return success,
+    ** see if it is possible to delete the super-journal.
     */
-    rc = pager_delmaster(pPager, zMaster);
+    assert( zSuper==&pPager->pTmpSpace[4] );
+    memset(&zSuper[-4], 0, 4);
+    rc = pager_delsuper(pPager, zSuper);
     testcase( rc!=SQLITE_OK );
   }
   if( isHot && nPlayback ){
@@ -54005,7 +55078,7 @@ end_playback:
 
 /*
 ** Read the content for page pPg out of the database file (or out of
-** the WAL if that is where the most recent copy if found) into 
+** the WAL if that is where the most recent copy if found) into
 ** pPg->pData. A shared lock or greater must be held on the database
 ** file before this function is called.
 **
@@ -54061,8 +55134,6 @@ static int readDbPage(PgHdr *pPg){
       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
     }
   }
-  CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
-
   PAGER_INCR(sqlite3_pager_readdb_count);
   PAGER_INCR(pPager->nRead);
   IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
@@ -54096,15 +55167,15 @@ static void pager_write_changecounter(PgHdr *pPg){
 
 #ifndef SQLITE_OMIT_WAL
 /*
-** This function is invoked once for each page that has already been 
+** This function is invoked once for each page that has already been
 ** written into the log file when a WAL transaction is rolled back.
-** Parameter iPg is the page number of said page. The pCtx argument 
+** Parameter iPg is the page number of said page. The pCtx argument
 ** is actually a pointer to the Pager structure.
 **
 ** If page iPg is present in the cache, and has no outstanding references,
 ** it is discarded. Otherwise, if there are one or more outstanding
 ** references, the page content is reloaded from the database. If the
-** attempt to reload content from the database is required and fails, 
+** attempt to reload content from the database is required and fails,
 ** return an SQLite error code. Otherwise, SQLITE_OK.
 */
 static int pagerUndoCallback(void *pCtx, Pgno iPg){
@@ -54130,7 +55201,7 @@ static int pagerUndoCallback(void *pCtx, Pgno iPg){
   ** updated as data is copied out of the rollback journal and into the
   ** database. This is not generally possible with a WAL database, as
   ** rollback involves simply truncating the log file. Therefore, if one
-  ** or more frames have already been written to the log (and therefore 
+  ** or more frames have already been written to the log (and therefore
   ** also copied into the backup databases) as part of this transaction,
   ** the backups must be restarted.
   */
@@ -54147,7 +55218,7 @@ static int pagerRollbackWal(Pager *pPager){
   PgHdr *pList;                   /* List of dirty pages to revert */
 
   /* For all pages in the cache that are currently dirty or have already
-  ** been written (but not committed) to the log file, do one of the 
+  ** been written (but not committed) to the log file, do one of the
   ** following:
   **
   **   + Discard the cached page (if refcount==0), or
@@ -54169,11 +55240,11 @@ static int pagerRollbackWal(Pager *pPager){
 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
 ** the contents of the list of pages headed by pList (connected by pDirty),
 ** this function notifies any active backup processes that the pages have
-** changed. 
+** changed.
 **
 ** The list of pages passed into this routine is always sorted by page number.
 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
-*/ 
+*/
 static int pagerWalFrames(
   Pager *pPager,                  /* Pager object */
   PgHdr *pList,                   /* List of frames to log */
@@ -54214,7 +55285,7 @@ static int pagerWalFrames(
   pPager->aStat[PAGER_STAT_WRITE] += nList;
 
   if( pList->pgno==1 ) pager_write_changecounter(pList);
-  rc = sqlite3WalFrames(pPager->pWal, 
+  rc = sqlite3WalFrames(pPager->pWal,
       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
   );
   if( rc==SQLITE_OK && pPager->pBackup ){
@@ -54329,9 +55400,9 @@ static int pagerPagecount(Pager *pPager, Pgno *pnPage){
 ** Return SQLITE_OK or an error code.
 **
 ** The caller must hold a SHARED lock on the database file to call this
-** function. Because an EXCLUSIVE lock on the db file is required to delete 
-** a WAL on a none-empty database, this ensures there is no race condition 
-** between the xAccess() below and an xDelete() being executed by some 
+** function. Because an EXCLUSIVE lock on the db file is required to delete
+** a WAL on a none-empty database, this ensures there is no race condition
+** between the xAccess() below and an xDelete() being executed by some
 ** other connection.
 */
 static int pagerOpenWalIfPresent(Pager *pPager){
@@ -54367,21 +55438,21 @@ static int pagerOpenWalIfPresent(Pager *pPager){
 
 /*
 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
-** the entire master journal file. The case pSavepoint==NULL occurs when 
-** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
+** the entire super-journal file. The case pSavepoint==NULL occurs when
+** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
 ** savepoint.
 **
-** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
+** When pSavepoint is not NULL (meaning a non-transaction savepoint is
 ** being rolled back), then the rollback consists of up to three stages,
 ** performed in the order specified:
 **
 **   * Pages are played back from the main journal starting at byte
-**     offset PagerSavepoint.iOffset and continuing to 
+**     offset PagerSavepoint.iOffset and continuing to
 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
 **     file if PagerSavepoint.iHdrOffset is zero.
 **
 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
-**     back starting from the journal header immediately following 
+**     back starting from the journal header immediately following
 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
 **
 **   * Pages are then played back from the sub-journal file, starting
@@ -54397,7 +55468,7 @@ static int pagerOpenWalIfPresent(Pager *pPager){
 ** journal file. There is no need for a bitvec in this case.
 **
 ** In either case, before playback commences the Pager.dbSize variable
-** is reset to the value that it held at the start of the savepoint 
+** is reset to the value that it held at the start of the savepoint
 ** (or transaction). No page with a page-number greater than this value
 ** is played back. If one is encountered it is simply skipped.
 */
@@ -54418,7 +55489,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
     }
   }
 
-  /* Set the database size back to the value it was before the savepoint 
+  /* Set the database size back to the value it was before the savepoint
   ** being reverted was opened.
   */
   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
@@ -54471,7 +55542,7 @@ static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
     ** test is related to ticket #2565.  See the discussion in the
     ** pager_playback() function for additional information.
     */
-    if( nJRec==0 
+    if( nJRec==0
      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
     ){
       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
@@ -54647,7 +55718,7 @@ SQLITE_PRIVATE void sqlite3PagerSetFlags(
 /*
 ** The following global variable is incremented whenever the library
 ** attempts to open a temporary file.  This information is used for
-** testing and analysis only.  
+** testing and analysis only.
 */
 #ifdef SQLITE_TEST
 SQLITE_API int sqlite3_opentemp_count = 0;
@@ -54656,8 +55727,8 @@ SQLITE_API int sqlite3_opentemp_count = 0;
 /*
 ** Open a temporary file.
 **
-** Write the file descriptor into *pFile. Return SQLITE_OK on success 
-** or some other error code if we fail. The OS will automatically 
+** Write the file descriptor into *pFile. Return SQLITE_OK on success
+** or some other error code if we fail. The OS will automatically
 ** delete the temporary file when it is closed.
 **
 ** The flags passed to the VFS layer xOpen() call are those specified
@@ -54689,9 +55760,9 @@ static int pagerOpentemp(
 /*
 ** Set the busy handler function.
 **
-** The pager invokes the busy-handler if sqlite3OsLock() returns 
+** The pager invokes the busy-handler if sqlite3OsLock() returns
 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
-** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
+** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
 ** lock. It does *not* invoke the busy handler when upgrading from
 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
 ** (which occurs during hot-journal rollback). Summary:
@@ -54703,7 +55774,7 @@ static int pagerOpentemp(
 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
 **
-** If the busy-handler callback returns non-zero, the lock is 
+** If the busy-handler callback returns non-zero, the lock is
 ** retried. If it returns zero, then the SQLITE_BUSY error is
 ** returned to the caller of the pager API function.
 */
@@ -54722,16 +55793,16 @@ SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
 }
 
 /*
-** Change the page size used by the Pager object. The new page size 
+** Change the page size used by the Pager object. The new page size
 ** is passed in *pPageSize.
 **
 ** If the pager is in the error state when this function is called, it
-** is a no-op. The value returned is the error state error code (i.e. 
+** is a no-op. The value returned is the error state error code (i.e.
 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
 **
 ** Otherwise, if all of the following are true:
 **
-**   * the new page size (value of *pPageSize) is valid (a power 
+**   * the new page size (value of *pPageSize) is valid (a power
 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
 **
 **   * there are no outstanding page references, and
@@ -54741,14 +55812,14 @@ SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
 **
 ** then the pager object page size is set to *pPageSize.
 **
-** If the page size is changed, then this function uses sqlite3PagerMalloc() 
-** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
-** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
+** If the page size is changed, then this function uses sqlite3PagerMalloc()
+** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
+** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
 ** In all other cases, SQLITE_OK is returned.
 **
 ** If the page size is not changed, either because one of the enumerated
 ** conditions above is not true, the pager was in error state when this
-** function was called, or because the memory allocation attempt failed, 
+** function was called, or because the memory allocation attempt failed,
 ** then *pPageSize is set to the old, retained page size before returning.
 */
 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
@@ -54758,7 +55829,7 @@ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nR
   ** function may be called from within PagerOpen(), before the state
   ** of the Pager object is internally consistent.
   **
-  ** At one point this function returned an error if the pager was in 
+  ** At one point this function returned an error if the pager was in
   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
   ** there is at least one outstanding page reference, this function
   ** is a no-op for that case anyhow.
@@ -54767,8 +55838,8 @@ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nR
   u32 pageSize = *pPageSize;
   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
   if( (pPager->memDb==0 || pPager->dbSize==0)
-   && sqlite3PcacheRefCount(pPager->pPCache)==0 
-   && pageSize && pageSize!=(u32)pPager->pageSize 
+   && sqlite3PcacheRefCount(pPager->pPCache)==0
+   && pageSize && pageSize!=(u32)pPager->pageSize
   ){
     char *pNew = NULL;             /* New temp space */
     i64 nByte = 0;
@@ -54806,7 +55877,6 @@ SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nR
     if( nReserve<0 ) nReserve = pPager->nReserve;
     assert( nReserve>=0 && nReserve<1000 );
     pPager->nReserve = (i16)nReserve;
-    pagerReportSize(pPager);
     pagerFixMaplimit(pPager);
   }
   return rc;
@@ -54825,13 +55895,13 @@ SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
 }
 
 /*
-** Attempt to set the maximum database page count if mxPage is positive. 
+** Attempt to set the maximum database page count if mxPage is positive.
 ** Make no changes if mxPage is zero or negative.  And never reduce the
 ** maximum page count below the current size of the database.
 **
 ** Regardless of mxPage, return the current maximum page count.
 */
-SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
+SQLITE_PRIVATE Pgno sqlite3PagerMaxPageCount(Pager *pPager, Pgno mxPage){
   if( mxPage>0 ){
     pPager->mxPgno = mxPage;
   }
@@ -54869,11 +55939,11 @@ void enable_simulated_io_errors(void){
 
 /*
 ** Read the first N bytes from the beginning of the file into memory
-** that pDest points to. 
+** that pDest points to.
 **
 ** If the pager was opened on a transient file (zFilename==""), or
 ** opened on a file less than N bytes in size, the output buffer is
-** zeroed and SQLITE_OK returned. The rationale for this is that this 
+** zeroed and SQLITE_OK returned. The rationale for this is that this
 ** function is used to read database headers, and a new transient or
 ** zero sized database has a header than consists entirely of zeroes.
 **
@@ -54906,7 +55976,7 @@ SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned cha
 ** This function may only be called when a read-transaction is open on
 ** the pager. It returns the total number of pages in the database.
 **
-** However, if the file is between 1 and <page-size> bytes in size, then 
+** However, if the file is between 1 and <page-size> bytes in size, then
 ** this is considered a 1 page file.
 */
 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
@@ -54921,19 +55991,19 @@ SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
 ** a similar or greater lock is already held, this function is a no-op
 ** (returning SQLITE_OK immediately).
 **
-** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
-** the busy callback if the lock is currently not available. Repeat 
-** until the busy callback returns false or until the attempt to 
+** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
+** the busy callback if the lock is currently not available. Repeat
+** until the busy callback returns false or until the attempt to
 ** obtain the lock succeeds.
 **
 ** Return SQLITE_OK on success and an error code if we cannot obtain
-** the lock. If the lock is obtained successfully, set the Pager.state 
+** the lock. If the lock is obtained successfully, set the Pager.state
 ** variable to locktype before returning.
 */
 static int pager_wait_on_lock(Pager *pPager, int locktype){
   int rc;                              /* Return code */
 
-  /* Check that this is either a no-op (because the requested lock is 
+  /* Check that this is either a no-op (because the requested lock is
   ** already held), or one of the transitions that the busy-handler
   ** may be invoked during, according to the comment above
   ** sqlite3PagerSetBusyhandler().
@@ -54950,10 +56020,10 @@ static int pager_wait_on_lock(Pager *pPager, int locktype){
 }
 
 /*
-** Function assertTruncateConstraint(pPager) checks that one of the 
+** Function assertTruncateConstraint(pPager) checks that one of the
 ** following is true for all dirty pages currently in the page-cache:
 **
-**   a) The page number is less than or equal to the size of the 
+**   a) The page number is less than or equal to the size of the
 **      current database image, in pages, OR
 **
 **   b) if the page content were written at this time, it would not
@@ -54966,9 +56036,9 @@ static int pager_wait_on_lock(Pager *pPager, int locktype){
 ** the database file. If a savepoint transaction were rolled back after
 ** this happened, the correct behavior would be to restore the current
 ** content of the page. However, since this content is not present in either
-** the database file or the portion of the rollback journal and 
+** the database file or the portion of the rollback journal and
 ** sub-journal rolled back the content could not be restored and the
-** database image would become corrupt. It is therefore fortunate that 
+** database image would become corrupt. It is therefore fortunate that
 ** this circumstance cannot arise.
 */
 #if defined(SQLITE_DEBUG)
@@ -54984,9 +56054,9 @@ static void assertTruncateConstraint(Pager *pPager){
 #endif
 
 /*
-** Truncate the in-memory database file image to nPage pages. This 
-** function does not actually modify the database file on disk. It 
-** just sets the internal state of the pager object so that the 
+** Truncate the in-memory database file image to nPage pages. This
+** function does not actually modify the database file on disk. It
+** just sets the internal state of the pager object so that the
 ** truncation will be done when the current transaction is committed.
 **
 ** This function is only called right before committing a transaction.
@@ -55001,11 +56071,11 @@ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
 
   /* At one point the code here called assertTruncateConstraint() to
   ** ensure that all pages being truncated away by this operation are,
-  ** if one or more savepoints are open, present in the savepoint 
+  ** if one or more savepoints are open, present in the savepoint
   ** journal so that they can be restored if the savepoint is rolled
   ** back. This is no longer necessary as this function is now only
-  ** called right before committing a transaction. So although the 
-  ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
+  ** called right before committing a transaction. So although the
+  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
   ** they cannot be rolled back. So the assertTruncateConstraint() call
   ** is no longer correct. */
 }
@@ -55017,12 +56087,12 @@ SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
 ** size of the journal file so that the pager_playback() routine knows
 ** that the entire journal file has been synced.
 **
-** Syncing a hot-journal to disk before attempting to roll it back ensures 
+** Syncing a hot-journal to disk before attempting to roll it back ensures
 ** that if a power-failure occurs during the rollback, the process that
 ** attempts rollback following system recovery sees the same journal
 ** content as this process.
 **
-** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
+** If everything goes as planned, SQLITE_OK is returned. Otherwise,
 ** an SQLite error code.
 */
 static int pagerSyncHotJournal(Pager *pPager){
@@ -55038,7 +56108,7 @@ static int pagerSyncHotJournal(Pager *pPager){
 
 #if SQLITE_MAX_MMAP_SIZE>0
 /*
-** Obtain a reference to a memory mapped page object for page number pgno. 
+** Obtain a reference to a memory mapped page object for page number pgno.
 ** The new object will use the pointer pData, obtained from xFetch().
 ** If successful, set *ppPage to point to the new page reference
 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
@@ -55054,7 +56124,7 @@ static int pagerAcquireMapPage(
   PgHdr **ppPage                  /* OUT: Acquired page object */
 ){
   PgHdr *p;                       /* Memory mapped page to return */
-  
+
   if( pPager->pMmapFreelist ){
     *ppPage = p = pPager->pMmapFreelist;
     pPager->pMmapFreelist = p->pDirty;
@@ -55088,7 +56158,7 @@ static int pagerAcquireMapPage(
 #endif
 
 /*
-** Release a reference to page pPg. pPg must have been returned by an 
+** Release a reference to page pPg. pPg must have been returned by an
 ** earlier call to pagerAcquireMapPage().
 */
 static void pagerReleaseMapPage(PgHdr *pPg){
@@ -55148,7 +56218,7 @@ static int databaseIsUnmoved(Pager *pPager){
 ** result in a coredump.
 **
 ** This function always succeeds. If a transaction is active an attempt
-** is made to roll it back. If an error occurs during the rollback 
+** is made to roll it back. If an error occurs during the rollback
 ** a hot journal may be left in the filesystem but no error is returned
 ** to the caller.
 */
@@ -55165,7 +56235,7 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
   {
     u8 *a = 0;
     assert( db || pPager->pWal==0 );
-    if( db && 0==(db->flags & SQLITE_NoCkptOnClose) 
+    if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
      && SQLITE_OK==databaseIsUnmoved(pPager)
     ){
       a = pTmp;
@@ -55179,8 +56249,8 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
     pager_unlock(pPager);
   }else{
     /* If it is open, sync the journal file before calling UnlockAndRollback.
-    ** If this is not done, then an unsynced portion of the open journal 
-    ** file may be played back into the database. If a power failure occurs 
+    ** If this is not done, then an unsynced portion of the open journal
+    ** file may be played back into the database. If a power failure occurs
     ** while this is happening, the database could become corrupt.
     **
     ** If an error occurs while trying to sync the journal, shift the pager
@@ -55202,11 +56272,6 @@ SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
   sqlite3OsClose(pPager->fd);
   sqlite3PageFree(pTmp);
   sqlite3PcacheClose(pPager->pPCache);
-
-#ifdef SQLITE_HAS_CODEC
-  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
-#endif
-
   assert( !pPager->aSavepoint && !pPager->pInJournal );
   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
 
@@ -55236,7 +56301,7 @@ SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 ** disk and can be restored in the event of a hot-journal rollback.
 **
 ** If the Pager.noSync flag is set, then this function is a no-op.
-** Otherwise, the actions required depend on the journal-mode and the 
+** Otherwise, the actions required depend on the journal-mode and the
 ** device characteristics of the file-system, as follows:
 **
 **   * If the journal file is an in-memory journal file, no action need
@@ -55248,7 +56313,7 @@ SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 **     been written following it. If the pager is operating in full-sync
 **     mode, then the journal file is synced before this field is updated.
 **
-**   * If the device does not support the SEQUENTIAL property, then 
+**   * If the device does not support the SEQUENTIAL property, then
 **     journal file is synced.
 **
 ** Or, in pseudo-code:
@@ -55257,11 +56322,11 @@ SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
 **     if( NOT SAFE_APPEND ){
 **       if( <full-sync mode> ) xSync(<journal file>);
 **       <update nRec field>
-**     } 
+**     }
 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
 **   }
 **
-** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
+** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
 ** page currently held in memory before returning SQLITE_OK. If an IO
 ** error is encountered, then the IO error code is returned to the caller.
 */
@@ -55289,10 +56354,10 @@ static int syncJournal(Pager *pPager, int newHdr){
         ** mode, then the journal file may at this point actually be larger
         ** than Pager.journalOff bytes. If the next thing in the journal
         ** file happens to be a journal-header (written as part of the
-        ** previous connection's transaction), and a crash or power-failure 
-        ** occurs after nRec is updated but before this connection writes 
-        ** anything else to the journal file (or commits/rolls back its 
-        ** transaction), then SQLite may become confused when doing the 
+        ** previous connection's transaction), and a crash or power-failure
+        ** occurs after nRec is updated but before this connection writes
+        ** anything else to the journal file (or commits/rolls back its
+        ** transaction), then SQLite may become confused when doing the
         ** hot-journal rollback following recovery. It may roll back all
         ** of this connections data, then proceed to rolling back the old,
         ** out-of-date data that follows it. Database corruption.
@@ -55302,7 +56367,7 @@ static int syncJournal(Pager *pPager, int newHdr){
         ** byte to the start of it to prevent it from being recognized.
         **
         ** Variable iNextHdrOffset is set to the offset at which this
-        ** problematic header will occur, if it exists. aMagic is used 
+        ** problematic header will occur, if it exists. aMagic is used
         ** as a temporary buffer to inspect the first couple of bytes of
         ** the potential journal header.
         */
@@ -55329,7 +56394,7 @@ static int syncJournal(Pager *pPager, int newHdr){
         ** it as a candidate for rollback.
         **
         ** This is not required if the persistent media supports the
-        ** SAFE_APPEND property. Because in this case it is not possible 
+        ** SAFE_APPEND property. Because in this case it is not possible
         ** for garbage data to be appended to the file, the nRec field
         ** is populated with 0xFFFFFFFF when the journal header is written
         ** and never needs to be updated.
@@ -55349,7 +56414,7 @@ static int syncJournal(Pager *pPager, int newHdr){
       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
         IOTRACE(("JSYNC %p\n", pPager))
-        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
+        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
         );
         if( rc!=SQLITE_OK ) return rc;
@@ -55366,8 +56431,8 @@ static int syncJournal(Pager *pPager, int newHdr){
     }
   }
 
-  /* Unless the pager is in noSync mode, the journal file was just 
-  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
+  /* Unless the pager is in noSync mode, the journal file was just
+  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
   ** all pages.
   */
   sqlite3PcacheClearSyncFlags(pPager->pPCache);
@@ -55387,9 +56452,9 @@ static int syncJournal(Pager *pPager, int newHdr){
 ** is called. Before writing anything to the database file, this lock
 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
 ** SQLITE_BUSY is returned and no data is written to the database file.
-** 
+**
 ** If the pager is a temp-file pager and the actual file-system file
-** is not yet open, it is created and opened before any data is 
+** is not yet open, it is created and opened before any data is
 ** written out.
 **
 ** Once the lock has been upgraded and, if necessary, the file opened,
@@ -55404,7 +56469,7 @@ static int syncJournal(Pager *pPager, int newHdr){
 ** in Pager.dbFileVers[] is updated to match the new value stored in
 ** the database file.
 **
-** If everything is successful, SQLITE_OK is returned. If an IO error 
+** If everything is successful, SQLITE_OK is returned. If an IO error
 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
 ** be obtained, SQLITE_BUSY is returned.
 */
@@ -55430,7 +56495,7 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
   ** file size will be.
   */
   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
-  if( rc==SQLITE_OK 
+  if( rc==SQLITE_OK
    && pPager->dbHintSize<pPager->dbSize
    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
   ){
@@ -55452,20 +56517,19 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
     */
     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
-      char *pData;                                   /* Data to write */    
+      char *pData;                                   /* Data to write */
 
       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
       if( pList->pgno==1 ) pager_write_changecounter(pList);
 
-      /* Encode the database */
-      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
+      pData = pList->pData;
 
       /* Write out the page data. */
       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
 
       /* If page 1 was just written, update Pager.dbFileVers to match
-      ** the value now stored in the database file. If writing this 
-      ** page caused the database file to grow, update dbFileSize. 
+      ** the value now stored in the database file. If writing this
+      ** page caused the database file to grow, update dbFileSize.
       */
       if( pgno==1 ){
         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
@@ -55493,18 +56557,18 @@ static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
 }
 
 /*
-** Ensure that the sub-journal file is open. If it is already open, this 
+** Ensure that the sub-journal file is open. If it is already open, this
 ** function is a no-op.
 **
-** SQLITE_OK is returned if everything goes according to plan. An 
-** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
+** SQLITE_OK is returned if everything goes according to plan. An
+** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
 ** fails.
 */
 static int openSubJournal(Pager *pPager){
   int rc = SQLITE_OK;
   if( !isOpen(pPager->sjfd) ){
-    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE 
-      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE 
+    const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
+      | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
       | SQLITE_OPEN_DELETEONCLOSE;
     int nStmtSpill = sqlite3Config.nStmtSpill;
     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
@@ -55516,13 +56580,13 @@ static int openSubJournal(Pager *pPager){
 }
 
 /*
-** Append a record of the current state of page pPg to the sub-journal. 
+** Append a record of the current state of page pPg to the sub-journal.
 **
 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
 ** for all open savepoints before returning.
 **
 ** This function returns SQLITE_OK if everything is successful, an IO
-** error code if the attempt to write to the sub-journal fails, or 
+** error code if the attempt to write to the sub-journal fails, or
 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
 ** bitvec.
 */
@@ -55535,9 +56599,9 @@ static int subjournalPage(PgHdr *pPg){
     assert( pPager->useJournal );
     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
-    assert( pagerUseWal(pPager) 
-         || pageInJournal(pPager, pPg) 
-         || pPg->pgno>pPager->dbOrigSize 
+    assert( pagerUseWal(pPager)
+         || pageInJournal(pPager, pPg)
+         || pPg->pgno>pPager->dbOrigSize
     );
     rc = openSubJournal(pPager);
 
@@ -55547,12 +56611,6 @@ static int subjournalPage(PgHdr *pPg){
       void *pData = pPg->pData;
       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
       char *pData2;
-
-#if SQLITE_HAS_CODEC   
-      if( !pPager->subjInMemory ){
-        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
-      }else
-#endif
       pData2 = pData;
       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
@@ -55580,14 +56638,14 @@ static int subjournalPageIfRequired(PgHdr *pPg){
 ** This function is called by the pcache layer when it has reached some
 ** soft memory limit. The first argument is a pointer to a Pager object
 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
-** database). The second argument is a reference to a page that is 
+** database). The second argument is a reference to a page that is
 ** currently dirty but has no outstanding references. The page
-** is always associated with the Pager object passed as the first 
+** is always associated with the Pager object passed as the first
 ** argument.
 **
 ** The job of this function is to make pPg clean by writing its contents
 ** out to the database file, if possible. This may involve syncing the
-** journal file. 
+** journal file.
 **
 ** If successful, sqlite3PcacheMakeClean() is called on the page and
 ** SQLITE_OK returned. If an IO error occurs while trying to make the
@@ -55612,7 +56670,7 @@ static int pagerStress(void *p, PgHdr *pPg){
   ** a rollback or by user request, respectively.
   **
   ** Spilling is also prohibited when in an error state since that could
-  ** lead to database corruption.   In the current implementation it 
+  ** lead to database corruption.   In the current implementation it
   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
   ** while in the error state, hence it is impossible for this routine to
   ** be called in the error state.  Nevertheless, we include a NEVER()
@@ -55633,26 +56691,26 @@ static int pagerStress(void *p, PgHdr *pPg){
   pPg->pDirty = 0;
   if( pagerUseWal(pPager) ){
     /* Write a single frame for this page to the log. */
-    rc = subjournalPageIfRequired(pPg); 
+    rc = subjournalPageIfRequired(pPg);
     if( rc==SQLITE_OK ){
       rc = pagerWalFrames(pPager, pPg, 0, 0);
     }
   }else{
-    
+
 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
     if( pPager->tempFile==0 ){
       rc = sqlite3JournalCreate(pPager->jfd);
       if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
     }
 #endif
-  
+
     /* Sync the journal file if required. */
-    if( pPg->flags&PGHDR_NEED_SYNC 
+    if( pPg->flags&PGHDR_NEED_SYNC
      || pPager->eState==PAGER_WRITER_CACHEMOD
     ){
       rc = syncJournal(pPager, 1);
     }
-  
+
     /* Write the contents of the page out to the database file. */
     if( rc==SQLITE_OK ){
       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
@@ -55666,7 +56724,7 @@ static int pagerStress(void *p, PgHdr *pPg){
     sqlite3PcacheMakeClean(pPg);
   }
 
-  return pager_error(pPager, rc); 
+  return pager_error(pPager, rc);
 }
 
 /*
@@ -55697,8 +56755,8 @@ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
 ** The zFilename argument is the path to the database file to open.
 ** If zFilename is NULL then a randomly-named temporary file is created
 ** and used as the file to be cached. Temporary files are be deleted
-** automatically when they are closed. If zFilename is ":memory:" then 
-** all information is held in cache. It is never written to disk. 
+** automatically when they are closed. If zFilename is ":memory:" then
+** all information is held in cache. It is never written to disk.
 ** This can be used to implement an in-memory database.
 **
 ** The nExtra parameter specifies the number of bytes of space allocated
@@ -55712,13 +56770,13 @@ SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
 ** of the PAGER_* flags.
 **
 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
-** of the xOpen() method of the supplied VFS when opening files. 
+** of the xOpen() method of the supplied VFS when opening files.
 **
-** If the pager object is allocated and the specified file opened 
+** If the pager object is allocated and the specified file opened
 ** successfully, SQLITE_OK is returned and *ppPager set to point to
 ** the new pager object. If an error occurs, *ppPager is set to NULL
 ** and error code returned. This function may return SQLITE_NOMEM
-** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
+** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
 ** various SQLITE_IO_XXX errors.
 */
 SQLITE_PRIVATE int sqlite3PagerOpen(
@@ -55748,7 +56806,8 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
   const char *zUri = 0;    /* URI args to copy */
-  int nUri = 0;            /* Number of bytes of URI args at *zUri */
+  int nUriByte = 1;        /* Number of bytes of URI args at *zUri */
+  int nUri = 0;            /* Number of URI parameters */
 
   /* Figure out how much space is required for each journal file-handle
   ** (there are two of them, the main journal and the sub-journal).  */
@@ -55782,14 +56841,24 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
     }
     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
+    if( rc!=SQLITE_OK ){
+      if( rc==SQLITE_OK_SYMLINK ){
+        if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){
+          rc = SQLITE_CANTOPEN_SYMLINK;
+        }else{
+          rc = SQLITE_OK;
+        }
+      }
+    }
     nPathname = sqlite3Strlen30(zPathname);
     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
     while( *z ){
-      z += sqlite3Strlen30(z)+1;
-      z += sqlite3Strlen30(z)+1;
+      z += strlen(z)+1;
+      z += strlen(z)+1;
+      nUri++;
     }
-    nUri = (int)(&z[1] - zUri);
-    assert( nUri>=0 );
+    nUriByte = (int)(&z[1] - zUri);
+    assert( nUriByte>=1 );
     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
       /* This branch is taken when the journal path required by
       ** the database being opened will be more than pVfs->mxPathname
@@ -55806,7 +56875,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
   }
 
   /* Allocate memory for the Pager structure, PCache object, the
-  ** three file descriptors, the database file name and the journal 
+  ** three file descriptors, the database file name and the journal
   ** file name. The layout in memory is as follows:
   **
   **     Pager object                    (sizeof(Pager) bytes)
@@ -55814,50 +56883,111 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
   **     Database file handle            (pVfs->szOsFile bytes)
   **     Sub-journal file handle         (journalFileSize bytes)
   **     Main journal file handle        (journalFileSize bytes)
+  **     Ptr back to the Pager           (sizeof(Pager*) bytes)
+  **     \0\0\0\0 database prefix        (4 bytes)
   **     Database file name              (nPathname+1 bytes)
-  **     Journal file name               (nPathname+8+1 bytes)
+  **     URI query parameters            (nUriByte bytes)
+  **     Journal filename                (nPathname+8+1 bytes)
+  **     WAL filename                    (nPathname+4+1 bytes)
+  **     \0\0\0 terminator               (3 bytes)
+  **
+  ** Some 3rd-party software, over which we have no control, depends on
+  ** the specific order of the filenames and the \0 separators between them
+  ** so that it can (for example) find the database filename given the WAL
+  ** filename without using the sqlite3_filename_database() API.  This is a
+  ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
+  ** software is in widespread use, so we try to avoid changing the filename
+  ** order and formatting if possible.  In particular, the details of the
+  ** filename format expected by 3rd-party software should be as follows:
+  **
+  **   - Main Database Path
+  **   - \0
+  **   - Multiple URI components consisting of:
+  **     - Key
+  **     - \0
+  **     - Value
+  **     - \0
+  **   - \0
+  **   - Journal Path
+  **   - \0
+  **   - WAL Path (zWALName)
+  **   - \0
+  **
+  ** The sqlite3_create_filename() interface and the databaseFilename() utility
+  ** that is used by sqlite3_filename_database() and kin also depend on the
+  ** specific formatting and order of the various filenames, so if the format
+  ** changes here, be sure to change it there as well.
   */
   pPtr = (u8 *)sqlite3MallocZero(
-    ROUND8(sizeof(*pPager)) +      /* Pager structure */
-    ROUND8(pcacheSize) +           /* PCache object */
-    ROUND8(pVfs->szOsFile) +       /* The main db file */
-    journalFileSize * 2 +          /* The two journal files */ 
-    nPathname + 1 + nUri +         /* zFilename */
-    nPathname + 8 + 2              /* zJournal */
+    ROUND8(sizeof(*pPager)) +            /* Pager structure */
+    ROUND8(pcacheSize) +                 /* PCache object */
+    ROUND8(pVfs->szOsFile) +             /* The main db file */
+    journalFileSize * 2 +                /* The two journal files */
+    sizeof(pPager) +                     /* Space to hold a pointer */
+    4 +                                  /* Database prefix */
+    nPathname + 1 +                      /* database filename */
+    nUriByte +                           /* query parameters */
+    nPathname + 8 + 1 +                  /* Journal filename */
 #ifndef SQLITE_OMIT_WAL
-    + nPathname + 4 + 2            /* zWal */
+    nPathname + 4 + 1 +                  /* WAL filename */
 #endif
+    3                                    /* Terminator */
   );
   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
   if( !pPtr ){
     sqlite3DbFree(0, zPathname);
     return SQLITE_NOMEM_BKPT;
   }
-  pPager =              (Pager*)(pPtr);
-  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
-  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
-  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
-  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
-  pPager->zFilename =    (char*)(pPtr += journalFileSize);
+  pPager = (Pager*)pPtr;                  pPtr += ROUND8(sizeof(*pPager));
+  pPager->pPCache = (PCache*)pPtr;        pPtr += ROUND8(pcacheSize);
+  pPager->fd = (sqlite3_file*)pPtr;       pPtr += ROUND8(pVfs->szOsFile);
+  pPager->sjfd = (sqlite3_file*)pPtr;     pPtr += journalFileSize;
+  pPager->jfd =  (sqlite3_file*)pPtr;     pPtr += journalFileSize;
   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
+  memcpy(pPtr, &pPager, sizeof(pPager));  pPtr += sizeof(pPager);
+
+  /* Fill in the Pager.zFilename and pPager.zQueryParam fields */
+                                          pPtr += 4;  /* Skip zero prefix */
+  pPager->zFilename = (char*)pPtr;
+  if( nPathname>0 ){
+    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname + 1;
+    if( zUri ){
+      memcpy(pPtr, zUri, nUriByte);       pPtr += nUriByte;
+    }else{
+                                          pPtr++;
+    }
+  }
+
+
+  /* Fill in Pager.zJournal */
+  if( nPathname>0 ){
+    pPager->zJournal = (char*)pPtr;
+    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
+    memcpy(pPtr, "-journal",8);           pPtr += 8 + 1;
+#ifdef SQLITE_ENABLE_8_3_NAMES
+    sqlite3FileSuffix3(zFilename,pPager->zJournal);
+    pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
+#endif
+  }else{
+    pPager->zJournal = 0;
+  }
 
-  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
-  if( zPathname ){
-    assert( nPathname>0 );
-    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
-    memcpy(pPager->zFilename, zPathname, nPathname);
-    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
-    memcpy(pPager->zJournal, zPathname, nPathname);
-    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
-    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
 #ifndef SQLITE_OMIT_WAL
-    pPager->zWal = &pPager->zJournal[nPathname+8+1];
-    memcpy(pPager->zWal, zPathname, nPathname);
-    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
-    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
+  /* Fill in Pager.zWal */
+  if( nPathname>0 ){
+    pPager->zWal = (char*)pPtr;
+    memcpy(pPtr, zPathname, nPathname);   pPtr += nPathname;
+    memcpy(pPtr, "-wal", 4);              pPtr += 4 + 1;
+#ifdef SQLITE_ENABLE_8_3_NAMES
+    sqlite3FileSuffix3(zFilename, pPager->zWal);
+    pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
 #endif
-    sqlite3DbFree(0, zPathname);
+  }else{
+    pPager->zWal = 0;
   }
+#endif
+
+  if( nPathname ) sqlite3DbFree(0, zPathname);
   pPager->pVfs = pVfs;
   pPager->vfsFlags = vfsFlags;
 
@@ -55906,9 +57036,9 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
         }
 #endif
       }
-      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
+      pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
-       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
+       || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
           vfsFlags |= SQLITE_OPEN_READONLY;
           goto act_like_temp_file;
       }
@@ -55923,7 +57053,7 @@ SQLITE_PRIVATE int sqlite3PagerOpen(
     ** disk and uses an in-memory rollback journal.
     **
     ** This branch also runs for files marked as immutable.
-    */ 
+    */
 act_like_temp_file:
     tempFile = 1;
     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
@@ -55932,7 +57062,7 @@ act_like_temp_file:
     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
   }
 
-  /* The following call to PagerSetPagesize() serves to set the value of 
+  /* The following call to PagerSetPagesize() serves to set the value of
   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
   */
   if( rc==SQLITE_OK ){
@@ -55972,10 +57102,10 @@ act_like_temp_file:
   /* pPager->state = PAGER_UNLOCK; */
   /* pPager->errMask = 0; */
   pPager->tempFile = (u8)tempFile;
-  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
+  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
-  pPager->exclusiveMode = (u8)tempFile; 
+  pPager->exclusiveMode = (u8)tempFile;
   pPager->changeCountDone = pPager->tempFile;
   pPager->memDb = (u8)memDb;
   pPager->readOnly = (u8)readOnly;
@@ -56015,12 +57145,25 @@ act_like_temp_file:
   return SQLITE_OK;
 }
 
+/*
+** Return the sqlite3_file for the main database given the name
+** of the corresonding WAL or Journal name as passed into
+** xOpen.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){
+  Pager *pPager;
+  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
+    zName--;
+  }
+  pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
+  return pPager->fd;
+}
 
 
 /*
 ** This function is called after transitioning from PAGER_UNLOCK to
 ** PAGER_SHARED state. It tests if there is a hot journal present in
-** the file-system for the given pager. A hot journal is one that 
+** the file-system for the given pager. A hot journal is one that
 ** needs to be played back. According to this function, a hot-journal
 ** file exists if the following criteria are met:
 **
@@ -56035,14 +57178,14 @@ act_like_temp_file:
 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
 ** is returned.
 **
-** This routine does not check if there is a master journal filename
-** at the end of the file. If there is, and that master journal file
+** This routine does not check if there is a super-journal filename
+** at the end of the file. If there is, and that super-journal file
 ** does not exist, then the journal file is not really hot. In this
 ** case this routine will return a false-positive. The pager_playback()
-** routine will discover that the journal file is not really hot and 
-** will not roll it back. 
+** routine will discover that the journal file is not really hot and
+** will not roll it back.
 **
-** If a hot-journal file is found to exist, *pExists is set to 1 and 
+** If a hot-journal file is found to exist, *pExists is set to 1 and
 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
 ** to determine whether or not a hot-journal file exists, the IO error
@@ -56070,7 +57213,7 @@ static int hasHotJournal(Pager *pPager, int *pExists){
     int locked = 0;             /* True if some process holds a RESERVED lock */
 
     /* Race condition here:  Another process might have been holding the
-    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
+    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
     ** call above, but then delete the journal and drop the lock before
     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
     ** is the case, this routine might think there is a hot journal when
@@ -56103,7 +57246,7 @@ static int hasHotJournal(Pager *pPager, int *pExists){
           /* The journal file exists and no other connection has a reserved
           ** or greater lock on the database file. Now check that there is
           ** at least one non-zero bytes at the start of the journal file.
-          ** If there is, then we consider this journal to be hot. If not, 
+          ** If there is, then we consider this journal to be hot. If not,
           ** it can be ignored.
           */
           if( !jrnlOpen ){
@@ -56153,7 +57296,7 @@ static int hasHotJournal(Pager *pPager, int *pExists){
 **      on the database file), then an attempt is made to obtain a
 **      SHARED lock on the database file. Immediately after obtaining
 **      the SHARED lock, the file-system is checked for a hot-journal,
-**      which is played back if present. Following any hot-journal 
+**      which is played back if present. Following any hot-journal
 **      rollback, the contents of the cache are validated by checking
 **      the 'change-counter' field of the database file header and
 **      discarded if they are found to be invalid.
@@ -56164,8 +57307,8 @@ static int hasHotJournal(Pager *pPager, int *pExists){
 **      the contents of the page cache and rolling back any open journal
 **      file.
 **
-** If everything is successful, SQLITE_OK is returned. If an IO error 
-** occurs while locking the database, checking for a hot-journal file or 
+** If everything is successful, SQLITE_OK is returned. If an IO error
+** occurs while locking the database, checking for a hot-journal file or
 ** rolling back a journal file, the IO error code is returned.
 */
 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
@@ -56173,7 +57316,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
 
   /* This routine is only called from b-tree and only when there are no
   ** outstanding pages. This implies that the pager state should either
-  ** be OPEN or READER. READER is only possible if the pager is or was in 
+  ** be OPEN or READER. READER is only possible if the pager is or was in
   ** exclusive access mode.  */
   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
   assert( assert_pager_state(pPager) );
@@ -56211,12 +57354,12 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
       ** important that a RESERVED lock is not obtained on the way to the
       ** EXCLUSIVE lock. If it were, another process might open the
       ** database file, detect the RESERVED lock, and conclude that the
-      ** database is safe to read while this process is still rolling the 
+      ** database is safe to read while this process is still rolling the
       ** hot-journal back.
-      ** 
+      **
       ** Because the intermediate RESERVED lock is not requested, any
-      ** other process attempting to access the database file will get to 
-      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
+      ** other process attempting to access the database file will get to
+      ** this point in the code and fail to obtain its own EXCLUSIVE lock
       ** on the database file.
       **
       ** Unless the pager is in locking_mode=exclusive mode, the lock is
@@ -56226,17 +57369,17 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
       if( rc!=SQLITE_OK ){
         goto failed;
       }
-      /* If it is not already open and the file exists on disk, open the 
-      ** journal for read/write access. Write access is required because 
-      ** in exclusive-access mode the file descriptor will be kept open 
-      ** and possibly used for a transaction later on. Also, write-access 
-      ** is usually required to finalize the journal in journal_mode=persist 
+
+      /* If it is not already open and the file exists on disk, open the
+      ** journal for read/write access. Write access is required because
+      ** in exclusive-access mode the file descriptor will be kept open
+      ** and possibly used for a transaction later on. Also, write-access
+      ** is usually required to finalize the journal in journal_mode=persist
       ** mode (and also for journal_mode=truncate on some systems).
       **
-      ** If the journal does not exist, it usually means that some 
-      ** other connection managed to get in and roll it back before 
-      ** this connection obtained the exclusive lock above. Or, it 
+      ** If the journal does not exist, it usually means that some
+      ** other connection managed to get in and roll it back before
+      ** this connection obtained the exclusive lock above. Or, it
       ** may mean that the pager was in the error-state when this
       ** function was called and the journal file does not exist.
       */
@@ -56257,7 +57400,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
           }
         }
       }
+
       /* Playback and delete the journal.  Drop the database write
       ** lock and reacquire the read lock. Purge the cache before
       ** playing back the hot-journal so that we don't end up with
@@ -56282,8 +57425,8 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
         ** pager_unlock() routine will be called before returning to unlock
         ** the file. If the unlock attempt fails, then Pager.eLock must be
-        ** set to UNKNOWN_LOCK (see the comment above the #define for 
-        ** UNKNOWN_LOCK above for an explanation). 
+        ** set to UNKNOWN_LOCK (see the comment above the #define for
+        ** UNKNOWN_LOCK above for an explanation).
         **
         ** In order to get pager_unlock() to do this, set Pager.eState to
         ** PAGER_ERROR now. This is not actually counted as a transition
@@ -56291,7 +57434,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
         ** since we know that the same call to pager_unlock() will very
         ** shortly transition the pager object to the OPEN state. Calling
         ** assert_pager_state() would fail now, as it should not be possible
-        ** to be in ERROR state when there are zero outstanding page 
+        ** to be in ERROR state when there are zero outstanding page
         ** references.
         */
         pager_error(pPager, rc);
@@ -56316,8 +57459,8 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
       ** a 32-bit counter that is incremented with each change.  The
       ** other bytes change randomly with each file change when
       ** a codec is in use.
-      ** 
-      ** There is a vanishingly small chance that a change will not be 
+      **
+      ** There is a vanishingly small chance that a change will not be
       ** detected.  The chance of an undetected change is so small that
       ** it can be neglected.
       */
@@ -56384,7 +57527,7 @@ SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
 ** the rollback journal, the unlock is not performed and there is
 ** nothing to rollback, so this routine is a no-op.
-*/ 
+*/
 static void pagerUnlockIfUnused(Pager *pPager){
   if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
     assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
@@ -56394,7 +57537,7 @@ static void pagerUnlockIfUnused(Pager *pPager){
 
 /*
 ** The page getter methods each try to acquire a reference to a
-** page with page number pgno. If the requested reference is 
+** page with page number pgno. If the requested reference is
 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
 **
 ** There are different implementations of the getter method depending
@@ -56404,22 +57547,22 @@ static void pagerUnlockIfUnused(Pager *pPager){
 **     getPageError()          --  Used if the pager is in an error state
 **     getPageMmap()           --  Used if memory-mapped I/O is enabled
 **
-** If the requested page is already in the cache, it is returned. 
+** If the requested page is already in the cache, it is returned.
 ** Otherwise, a new page object is allocated and populated with data
 ** read from the database file. In some cases, the pcache module may
 ** choose not to allocate a new page object and may reuse an existing
 ** object with no outstanding references.
 **
-** The extra data appended to a page is always initialized to zeros the 
-** first time a page is loaded into memory. If the page requested is 
+** The extra data appended to a page is always initialized to zeros the
+** first time a page is loaded into memory. If the page requested is
 ** already in the cache when this function is called, then the extra
 ** data is left as it was when the page object was last used.
 **
-** If the database image is smaller than the requested page or if 
-** the flags parameter contains the PAGER_GET_NOCONTENT bit and the 
-** requested page is not already stored in the cache, then no 
-** actual disk read occurs. In this case the memory image of the 
-** page is initialized to all zeros. 
+** If the database image is smaller than the requested page or if
+** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
+** requested page is not already stored in the cache, then no
+** actual disk read occurs. In this case the memory image of the
+** page is initialized to all zeros.
 **
 ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
 ** the contents of the page. This occurs in two scenarios:
@@ -56485,18 +57628,18 @@ static int getPageNormal(
   if( pPg->pPager && !noContent ){
     /* In this case the pcache already contains an initialized copy of
     ** the page. Return without further ado.  */
-    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
+    assert( pgno!=PAGER_MJ_PGNO(pPager) );
     pPager->aStat[PAGER_STAT_HIT]++;
     return SQLITE_OK;
 
   }else{
-    /* The pager cache has created a new page. Its content needs to 
+    /* The pager cache has created a new page. Its content needs to
     ** be initialized. But first some error checks:
     **
-    ** (1) The maximum page number is 2^31
+    ** (*) obsolete.  Was: maximum page number is 2^31
     ** (2) Never try to fetch the locking page
     */
-    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
+    if( pgno==PAGER_MJ_PGNO(pPager) ){
       rc = SQLITE_CORRUPT_BKPT;
       goto pager_acquire_err;
     }
@@ -56511,9 +57654,9 @@ static int getPageNormal(
       }
       if( noContent ){
         /* Failure to set the bits in the InJournal bit-vectors is benign.
-        ** It merely means that we might do some extra work to journal a 
-        ** page that does not need to be journaled.  Nevertheless, be sure 
-        ** to test the case where a malloc error occurs while trying to set 
+        ** It merely means that we might do some extra work to journal a
+        ** page that does not need to be journaled.  Nevertheless, be sure
+        ** to test the case where a malloc error occurs while trying to set
         ** a bit in a bit vector.
         */
         sqlite3BeginBenignMalloc();
@@ -56563,16 +57706,13 @@ static int getPageMMap(
 
   /* It is acceptable to use a read-only (mmap) page for any page except
   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
-  ** flag was specified by the caller. And so long as the db is not a 
+  ** flag was specified by the caller. And so long as the db is not a
   ** temporary or in-memory database.  */
   const int bMmapOk = (pgno>1
    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
   );
 
   assert( USEFETCH(pPager) );
-#ifdef SQLITE_HAS_CODEC
-  assert( pPager->xCodec==0 );
-#endif
 
   /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
   ** allows the compiler optimizer to reuse the results of the "pgno>1"
@@ -56595,7 +57735,7 @@ static int getPageMMap(
   }
   if( bMmapOk && iFrame==0 ){
     void *pData = 0;
-    rc = sqlite3OsFetch(pPager->fd, 
+    rc = sqlite3OsFetch(pPager->fd,
         (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
     );
     if( rc==SQLITE_OK && pData ){
@@ -56651,12 +57791,12 @@ SQLITE_PRIVATE int sqlite3PagerGet(
 /*
 ** Acquire a page if it is already in the in-memory cache.  Do
 ** not read the page from disk.  Return a pointer to the page,
-** or 0 if the page is not in cache. 
+** or 0 if the page is not in cache.
 **
 ** See also sqlite3PagerGet().  The difference between this routine
 ** and sqlite3PagerGet() is that _get() will go to the disk and read
 ** in the page if the page is not already in cache.  This routine
-** returns NULL if the page is not in cache or if a disk I/O error 
+** returns NULL if the page is not in cache or if a disk I/O error
 ** has ever happened.
 */
 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
@@ -56703,31 +57843,30 @@ SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
   assert( pPg->pgno==1 );
   assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
   pPager = pPg->pPager;
-  sqlite3PagerResetLockTimeout(pPager);
   sqlite3PcacheRelease(pPg);
   pagerUnlockIfUnused(pPager);
 }
 
 /*
 ** This function is called at the start of every write transaction.
-** There must already be a RESERVED or EXCLUSIVE lock on the database 
+** There must already be a RESERVED or EXCLUSIVE lock on the database
 ** file when this routine is called.
 **
 ** Open the journal file for pager pPager and write a journal header
 ** to the start of it. If there are active savepoints, open the sub-journal
-** as well. This function is only used when the journal file is being 
-** opened to write a rollback log for a transaction. It is not used 
+** as well. This function is only used when the journal file is being
+** opened to write a rollback log for a transaction. It is not used
 ** when opening a hot journal file to roll it back.
 **
 ** If the journal file is already open (as it may be in exclusive mode),
 ** then this function just writes a journal header to the start of the
-** already open file. 
+** already open file.
 **
 ** Whether or not the journal file is opened by this function, the
 ** Pager.pInJournal bitvec structure is allocated.
 **
-** Return SQLITE_OK if everything is successful. Otherwise, return 
-** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
+** Return SQLITE_OK if everything is successful. Otherwise, return
+** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
 ** an IO error code if opening or writing the journal file fails.
 */
 static int pager_open_journal(Pager *pPager){
@@ -56737,7 +57876,7 @@ static int pager_open_journal(Pager *pPager){
   assert( pPager->eState==PAGER_WRITER_LOCKED );
   assert( assert_pager_state(pPager) );
   assert( pPager->pInJournal==0 );
-  
+
   /* If already in the error state, this function is a no-op.  But on
   ** the other hand, this routine is never called if we are already in
   ** an error state. */
@@ -56748,7 +57887,7 @@ static int pager_open_journal(Pager *pPager){
     if( pPager->pInJournal==0 ){
       return SQLITE_NOMEM_BKPT;
     }
-  
+
     /* Open the journal file if it is not already open. */
     if( !isOpen(pPager->jfd) ){
       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
@@ -56764,7 +57903,7 @@ static int pager_open_journal(Pager *pPager){
           flags |= SQLITE_OPEN_MAIN_JOURNAL;
           nSpill = jrnlBufferSize(pPager);
         }
-          
+
         /* Verify that the database still has the same name as it did when
         ** it was originally opened. */
         rc = databaseIsUnmoved(pPager);
@@ -56776,16 +57915,16 @@ static int pager_open_journal(Pager *pPager){
       }
       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
     }
-  
-  
-    /* Write the first journal header to the journal file and open 
+
+
+    /* Write the first journal header to the journal file and open
     ** the sub-journal if necessary.
     */
     if( rc==SQLITE_OK ){
       /* TODO: Check if all of these are really required. */
       pPager->nRec = 0;
       pPager->journalOff = 0;
-      pPager->setMaster = 0;
+      pPager->setSuper = 0;
       pPager->journalHdr = 0;
       rc = writeJournalHdr(pPager);
     }
@@ -56803,12 +57942,12 @@ static int pager_open_journal(Pager *pPager){
 }
 
 /*
-** Begin a write-transaction on the specified pager object. If a 
+** Begin a write-transaction on the specified pager object. If a
 ** write-transaction has already been opened, this function is a no-op.
 **
 ** If the exFlag argument is false, then acquire at least a RESERVED
 ** lock on the database file. If exFlag is true, then acquire at least
-** an EXCLUSIVE lock. If such a lock is already held, no locking 
+** an EXCLUSIVE lock. If such a lock is already held, no locking
 ** functions need be called.
 **
 ** If the subjInMemory argument is non-zero, then any sub-journal opened
@@ -56816,7 +57955,7 @@ static int pager_open_journal(Pager *pPager){
 ** has no effect if the sub-journal is already opened (as it may be when
 ** running in exclusive mode) or if the transaction does not require a
 ** sub-journal. If the subjInMemory argument is zero, then any required
-** sub-journal is implemented in-memory if pPager is an in-memory database, 
+** sub-journal is implemented in-memory if pPager is an in-memory database,
 ** or using a temporary file otherwise.
 */
 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
@@ -56864,9 +58003,9 @@ SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory
       **
       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
       ** when it has an open transaction, but never to DBMOD or FINISHED.
-      ** This is because in those states the code to roll back savepoint 
-      ** transactions may copy data from the sub-journal into the database 
-      ** file as well as into the page cache. Which would be incorrect in 
+      ** This is because in those states the code to roll back savepoint
+      ** transactions may copy data from the sub-journal into the database
+      ** file as well as into the page cache. Which would be incorrect in
       ** WAL mode.
       */
       pPager->eState = PAGER_WRITER_LOCKED;
@@ -56901,7 +58040,7 @@ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
   assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
 
   assert( pPager->journalHdr<=pPager->journalOff );
-  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
+  pData2 = pPg->pData;
   cksum = pager_cksum(pPager, (u8*)pData2);
 
   /* Even if an IO or diskfull error occurs while journalling the
@@ -56920,11 +58059,11 @@ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
   rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
   if( rc!=SQLITE_OK ) return rc;
 
-  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
+  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
            pPager->journalOff, pPager->pageSize));
   PAGER_INCR(sqlite3_pager_writej_count);
   PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
-       PAGERID(pPager), pPg->pgno, 
+       PAGERID(pPager), pPg->pgno,
        ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
 
   pPager->journalOff += 8 + pPager->pageSize;
@@ -56939,9 +58078,9 @@ static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
 }
 
 /*
-** Mark a single data page as writeable. The page is written into the 
+** Mark a single data page as writeable. The page is written into the
 ** main journal or sub-journal as required. If the page is written into
-** one of the journals, the corresponding bit is set in the 
+** one of the journals, the corresponding bit is set in the
 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
 ** of any open savepoints as appropriate.
 */
@@ -56949,7 +58088,7 @@ static int pager_write(PgHdr *pPg){
   Pager *pPager = pPg->pPager;
   int rc = SQLITE_OK;
 
-  /* This routine is not called unless a write-transaction has already 
+  /* This routine is not called unless a write-transaction has already
   ** been started. The journal file may or may not be open at this point.
   ** It is never called in the ERROR state.
   */
@@ -56966,7 +58105,7 @@ static int pager_write(PgHdr *pPg){
   ** obtained the necessary locks to begin the write-transaction, but the
   ** rollback journal might not yet be open. Open it now if this is the case.
   **
-  ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
+  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
   ** an error might occur and the pager would end up in WRITER_LOCKED state
   ** with pages marked as dirty in the cache.
@@ -57011,7 +58150,7 @@ static int pager_write(PgHdr *pPg){
   ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
   */
   pPg->flags |= PGHDR_WRITEABLE;
-  
+
   /* If the statement journal is open and the page is not in it,
   ** then write the page into the statement journal.
   */
@@ -57095,7 +58234,7 @@ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
     }
   }
 
-  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
+  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
   ** starting at pg1, then it needs to be set for all of them. Because
   ** writing to any of these nPage pages may damage the others, the
   ** journal file must contain sync()ed copies of all of them
@@ -57118,9 +58257,9 @@ static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
 }
 
 /*
-** Mark a data page as writeable. This routine must be called before 
-** making changes to a page. The caller must check the return value 
-** of this function and be careful not to change any page data unless 
+** Mark a data page as writeable. This routine must be called before
+** making changes to a page. The caller must check the return value
+** of this function and be careful not to change any page data unless
 ** this routine returns SQLITE_OK.
 **
 ** The difference between this function and pager_write() is that this
@@ -57171,13 +58310,13 @@ SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
 ** on the given page is unused. The pager marks the page as clean so
 ** that it does not get written to disk.
 **
-** Tests show that this optimization can quadruple the speed of large 
+** Tests show that this optimization can quadruple the speed of large
 ** DELETE operations.
 **
 ** This optimization cannot be used with a temp-file, as the page may
 ** have been dirty at the start of the transaction. In that case, if
-** memory pressure forces page pPg out of the cache, the data does need 
-** to be written out to disk so that it may be read back in if the 
+** memory pressure forces page pPg out of the cache, the data does need
+** to be written out to disk so that it may be read back in if the
 ** current transaction is rolled back.
 */
 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
@@ -57193,17 +58332,17 @@ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
 }
 
 /*
-** This routine is called to increment the value of the database file 
-** change-counter, stored as a 4-byte big-endian integer starting at 
+** This routine is called to increment the value of the database file
+** change-counter, stored as a 4-byte big-endian integer starting at
 ** byte offset 24 of the pager file.  The secondary change counter at
 ** 92 is also updated, as is the SQLite version number at offset 96.
 **
 ** But this only happens if the pPager->changeCountDone flag is false.
 ** To avoid excess churning of page 1, the update only happens once.
-** See also the pager_write_changecounter() routine that does an 
+** See also the pager_write_changecounter() routine that does an
 ** unconditional update of the change counters.
 **
-** If the isDirectMode flag is zero, then this is done by calling 
+** If the isDirectMode flag is zero, then this is done by calling
 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
 ** page data. In this case the file will be updated when the current
 ** transaction is committed.
@@ -57211,7 +58350,7 @@ SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
 ** The isDirectMode flag may only be non-zero if the library was compiled
 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
 ** if isDirect is non-zero, then the database file is updated directly
-** by writing an updated version of page 1 using a call to the 
+** by writing an updated version of page 1 using a call to the
 ** sqlite3OsWrite() function.
 */
 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
@@ -57250,7 +58389,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
     assert( pPgHdr==0 || rc==SQLITE_OK );
 
     /* If page one was fetched successfully, and this function is not
-    ** operating in direct-mode, make page 1 writable.  When not in 
+    ** operating in direct-mode, make page 1 writable.  When not in
     ** direct mode, page 1 is always held in cache and hence the PagerGet()
     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
     */
@@ -57266,7 +58405,7 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
       if( DIRECT_MODE ){
         const void *zBuf;
         assert( pPager->dbFileSize>0 );
-        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
+        zBuf = pPgHdr->pData;
         if( rc==SQLITE_OK ){
           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
           pPager->aStat[PAGER_STAT_WRITE]++;
@@ -57297,9 +58436,9 @@ static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
 ** If successful, or if called on a pager for which it is a no-op, this
 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
 */
-SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
+SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zSuper){
   int rc = SQLITE_OK;
-  void *pArg = (void*)zMaster;
+  void *pArg = (void*)zSuper;
   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
   if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
   if( rc==SQLITE_OK && !pPager->noSync ){
@@ -57311,22 +58450,22 @@ SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
 
 /*
 ** This function may only be called while a write-transaction is active in
-** rollback. If the connection is in WAL mode, this call is a no-op. 
-** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
+** rollback. If the connection is in WAL mode, this call is a no-op.
+** Otherwise, if the connection does not already have an EXCLUSIVE lock on
 ** the database file, an attempt is made to obtain one.
 **
 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
-** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
+** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
 ** returned.
 */
 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
   int rc = pPager->errCode;
   assert( assert_pager_state(pPager) );
   if( rc==SQLITE_OK ){
-    assert( pPager->eState==PAGER_WRITER_CACHEMOD 
-         || pPager->eState==PAGER_WRITER_DBMOD 
-         || pPager->eState==PAGER_WRITER_LOCKED 
+    assert( pPager->eState==PAGER_WRITER_CACHEMOD
+         || pPager->eState==PAGER_WRITER_DBMOD
+         || pPager->eState==PAGER_WRITER_LOCKED
     );
     assert( assert_pager_state(pPager) );
     if( 0==pagerUseWal(pPager) ){
@@ -57337,24 +58476,24 @@ SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
 }
 
 /*
-** Sync the database file for the pager pPager. zMaster points to the name
-** of a master journal file that should be written into the individual
-** journal file. zMaster may be NULL, which is interpreted as no master
-** journal (a single database transaction).
+** Sync the database file for the pager pPager. zSuper points to the name
+** of a super-journal file that should be written into the individual
+** journal file. zSuper may be NULL, which is interpreted as no
+** super-journal (a single database transaction).
 **
 ** This routine ensures that:
 **
 **   * The database file change-counter is updated,
 **   * the journal is synced (unless the atomic-write optimization is used),
-**   * all dirty pages are written to the database file, 
+**   * all dirty pages are written to the database file,
 **   * the database file is truncated (if required), and
-**   * the database file synced. 
+**   * the database file synced.
 **
-** The only thing that remains to commit the transaction is to finalize 
-** (delete, truncate or zero the first part of) the journal file (or 
-** delete the master journal file if specified).
+** The only thing that remains to commit the transaction is to finalize
+** (delete, truncate or zero the first part of) the journal file (or
+** delete the super-journal file if specified).
 **
-** Note that if zMaster==NULL, this does not overwrite a previous value
+** Note that if zSuper==NULL, this does not overwrite a previous value
 ** passed to an sqlite3PagerCommitPhaseOne() call.
 **
 ** If the final parameter - noSync - is true, then the database file itself
@@ -57364,7 +58503,7 @@ SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
 */
 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   Pager *pPager,                  /* Pager object */
-  const char *zMaster,            /* If not NULL, the master journal name */
+  const char *zSuper,            /* If not NULL, the super-journal name */
   int noSync                      /* True to omit the xSync on the db file */
 ){
   int rc = SQLITE_OK;             /* Return code */
@@ -57382,8 +58521,8 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
   /* Provide the ability to easily simulate an I/O error during testing */
   if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
 
-  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
-      pPager->zFilename, zMaster, pPager->dbSize));
+  PAGERTRACE(("DATABASE SYNC: File=%s zSuper=%s nSize=%d\n",
+      pPager->zFilename, zSuper, pPager->dbSize));
 
   /* If no database changes have been made, return early. */
   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
@@ -57422,7 +58561,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       */
 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
       sqlite3_file *fd = pPager->fd;
-      int bBatch = zMaster==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
+      int bBatch = zSuper==0    /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
         && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
         && !pPager->noSync
         && sqlite3JournalIsInMemory(pPager->jfd);
@@ -57433,11 +58572,11 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
       /* The following block updates the change-counter. Exactly how it
       ** does this depends on whether or not the atomic-update optimization
-      ** was enabled at compile time, and if this transaction meets the 
-      ** runtime criteria to use the operation: 
+      ** was enabled at compile time, and if this transaction meets the
+      ** runtime criteria to use the operation:
       **
       **    * The file-system supports the atomic-write property for
-      **      blocks of size page-size, and 
+      **      blocks of size page-size, and
       **    * This commit is not part of a multi-file transaction, and
       **    * Exactly one page has been modified and store in the journal file.
       **
@@ -57447,7 +58586,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       ** is not applicable to this transaction, call sqlite3JournalCreate()
       ** to make sure the journal file has actually been created, then call
       ** pager_incr_changecounter() to update the change-counter in indirect
-      ** mode. 
+      ** mode.
       **
       ** Otherwise, if the optimization is both enabled and applicable,
       ** then call pager_incr_changecounter() to update the change-counter
@@ -57456,19 +58595,19 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       */
       if( bBatch==0 ){
         PgHdr *pPg;
-        assert( isOpen(pPager->jfd) 
-            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
-            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
+        assert( isOpen(pPager->jfd)
+            || pPager->journalMode==PAGER_JOURNALMODE_OFF
+            || pPager->journalMode==PAGER_JOURNALMODE_WAL
             );
-        if( !zMaster && isOpen(pPager->jfd) 
-         && pPager->journalOff==jrnlBufferSize(pPager) 
+        if( !zSuper && isOpen(pPager->jfd)
+         && pPager->journalOff==jrnlBufferSize(pPager)
          && pPager->dbSize>=pPager->dbOrigSize
          && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
         ){
-          /* Update the db file change counter via the direct-write method. The 
-          ** following call will modify the in-memory representation of page 1 
-          ** to include the updated change counter and then write page 1 
-          ** directly to the database file. Because of the atomic-write 
+          /* Update the db file change counter via the direct-write method. The
+          ** following call will modify the in-memory representation of page 1
+          ** to include the updated change counter and then write page 1
+          ** directly to the database file. Because of the atomic-write
           ** property of the host file-system, this is safe.
           */
           rc = pager_incr_changecounter(pPager, 1);
@@ -57481,7 +58620,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       }
 #else  /* SQLITE_ENABLE_ATOMIC_WRITE */
 #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
-      if( zMaster ){
+      if( zSuper ){
         rc = sqlite3JournalCreate(pPager->jfd);
         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
         assert( bBatch==0 );
@@ -57490,24 +58629,24 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       rc = pager_incr_changecounter(pPager, 0);
 #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
-  
-      /* Write the master journal name into the journal file. If a master 
-      ** journal file name has already been written to the journal file, 
-      ** or if zMaster is NULL (no master journal), then this call is a no-op.
+
+      /* Write the super-journal name into the journal file. If a
+      ** super-journal file name has already been written to the journal file,
+      ** or if zSuper is NULL (no super-journal), then this call is a no-op.
       */
-      rc = writeMasterJournal(pPager, zMaster);
+      rc = writeSuperJournal(pPager, zSuper);
       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
-  
+
       /* Sync the journal file and write all dirty pages to the database.
-      ** If the atomic-update optimization is being used, this sync will not 
+      ** If the atomic-update optimization is being used, this sync will not
       ** create the journal file or perform any real IO.
       **
       ** Because the change-counter page was just modified, unless the
       ** atomic-update optimization is used it is almost certain that the
       ** journal requires a sync here. However, in locking_mode=exclusive
-      ** on a system under memory pressure it is just possible that this is 
+      ** on a system under memory pressure it is just possible that this is
       ** not the case. In this case it is likely enough that the redundant
-      ** xSync() call will be changed to a no-op by the OS anyhow. 
+      ** xSync() call will be changed to a no-op by the OS anyhow.
       */
       rc = syncJournal(pPager, 0);
       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
@@ -57548,7 +58687,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
       }
       sqlite3PcacheCleanAll(pPager->pPCache);
 
-      /* If the file on disk is smaller than the database image, use 
+      /* If the file on disk is smaller than the database image, use
       ** pager_truncate to grow the file here. This can happen if the database
       ** image was extended as part of the current transaction and then the
       ** last page in the db image moved to the free-list. In this case the
@@ -57560,10 +58699,10 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
         rc = pager_truncate(pPager, nNew);
         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
       }
-  
+
       /* Finally, sync the database file. */
       if( !noSync ){
-        rc = sqlite3PagerSync(pPager, zMaster);
+        rc = sqlite3PagerSync(pPager, zSuper);
       }
       IOTRACE(("DBSYNC %p\n", pPager))
     }
@@ -57580,12 +58719,12 @@ commit_phase_one_exit:
 /*
 ** When this function is called, the database file has been completely
 ** updated to reflect the changes made by the current transaction and
-** synced to disk. The journal file still exists in the file-system 
+** synced to disk. The journal file still exists in the file-system
 ** though, and if a failure occurs at this point it will eventually
 ** be used as a hot-journal and the current transaction rolled back.
 **
-** This function finalizes the journal file, either by deleting, 
-** truncating or partially zeroing it, so that it cannot be used 
+** This function finalizes the journal file, either by deleting,
+** truncating or partially zeroing it, so that it cannot be used
 ** for hot-journal rollback. Once this is done the transaction is
 ** irrevocably committed.
 **
@@ -57599,6 +58738,7 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   ** But if (due to a coding error elsewhere in the system) it does get
   ** called, just return the same error code without doing anything. */
   if( NEVER(pPager->errCode) ) return pPager->errCode;
+  pPager->iDataVersion++;
 
   assert( pPager->eState==PAGER_WRITER_LOCKED
        || pPager->eState==PAGER_WRITER_FINISHED
@@ -57610,15 +58750,15 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   ** this transaction, the pager is running in exclusive-mode and is
   ** using persistent journals, then this function is a no-op.
   **
-  ** The start of the journal file currently contains a single journal 
+  ** The start of the journal file currently contains a single journal
   ** header with the nRec field set to 0. If such a journal is used as
   ** a hot-journal during hot-journal rollback, 0 changes will be made
-  ** to the database file. So there is no need to zero the journal 
+  ** to the database file. So there is no need to zero the journal
   ** header. Since the pager is in exclusive mode, there is no need
   ** to drop any locks either.
   */
-  if( pPager->eState==PAGER_WRITER_LOCKED 
-   && pPager->exclusiveMode 
+  if( pPager->eState==PAGER_WRITER_LOCKED
+   && pPager->exclusiveMode
    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
   ){
     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
@@ -57627,13 +58767,12 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
   }
 
   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
-  pPager->iDataVersion++;
-  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
+  rc = pager_end_transaction(pPager, pPager->setSuper, 1);
   return pager_error(pPager, rc);
 }
 
 /*
-** If a write transaction is open, then all changes made within the 
+** If a write transaction is open, then all changes made within the
 ** transaction are reverted and the current write-transaction is closed.
 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
 ** state if an error occurs.
@@ -57643,14 +58782,14 @@ SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
 **
 ** Otherwise, in rollback mode, this function performs two functions:
 **
-**   1) It rolls back the journal file, restoring all database file and 
+**   1) It rolls back the journal file, restoring all database file and
 **      in-memory cache pages to the state they were in when the transaction
 **      was opened, and
 **
 **   2) It finalizes the journal file, so that it is not used for hot
 **      rollback at any point in the future.
 **
-** Finalization of the journal file (task 2) is only performed if the 
+** Finalization of the journal file (task 2) is only performed if the
 ** rollback is successful.
 **
 ** In WAL mode, all cache-entries containing data modified within the
@@ -57663,7 +58802,7 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
 
   /* PagerRollback() is a no-op if called in READER or OPEN state. If
-  ** the pager is already in the ERROR state, the rollback is not 
+  ** the pager is already in the ERROR state, the rollback is not
   ** attempted here. Instead, the error code is returned to the caller.
   */
   assert( assert_pager_state(pPager) );
@@ -57673,13 +58812,13 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
   if( pagerUseWal(pPager) ){
     int rc2;
     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
-    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
+    rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
     if( rc==SQLITE_OK ) rc = rc2;
   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
     int eState = pPager->eState;
     rc = pager_end_transaction(pPager, 0, 0);
     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
-      /* This can happen using journal_mode=off. Move the pager to the error 
+      /* This can happen using journal_mode=off. Move the pager to the error
       ** state to indicate that the contents of the cache may not be trusted.
       ** Any active readers will get SQLITE_ABORT.
       */
@@ -57694,7 +58833,7 @@ SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
 
   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
-          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
+          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
           || rc==SQLITE_CANTOPEN
   );
 
@@ -57768,8 +58907,8 @@ SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
 ** it was added later.
 **
 ** Before returning, *pnVal is incremented by the
-** current cache hit or miss count, according to the value of eStat. If the 
-** reset parameter is non-zero, the cache hit or miss count is zeroed before 
+** current cache hit or miss count, according to the value of eStat. If the
+** reset parameter is non-zero, the cache hit or miss count is zeroed before
 ** returning.
 */
 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
@@ -57805,7 +58944,7 @@ SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
 ** to make up the difference. If the number of savepoints is already
 ** equal to nSavepoint, then this function is a no-op.
 **
-** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
+** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
 ** occurs while opening the sub-journal file, then an IO error code is
 ** returned. Otherwise, SQLITE_OK.
 */
@@ -57820,7 +58959,7 @@ static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
   assert( nSavepoint>nCurrent && pPager->useJournal );
 
   /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
-  ** if the allocation fails. Otherwise, zero the new portion in case a 
+  ** if the allocation fails. Otherwise, zero the new portion in case a
   ** malloc failure occurs while populating it in the for(...) loop below.
   */
   aNew = (PagerSavepoint *)sqlite3Realloc(
@@ -57868,7 +59007,7 @@ SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
 
 /*
 ** This function is called to rollback or release (commit) a savepoint.
-** The savepoint to release or rollback need not be the most recently 
+** The savepoint to release or rollback need not be the most recently
 ** created savepoint.
 **
 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
@@ -57876,29 +59015,29 @@ SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
 ** that have occurred since the specified savepoint was created.
 **
-** The savepoint to rollback or release is identified by parameter 
+** The savepoint to rollback or release is identified by parameter
 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
 ** (the first created). A value of (Pager.nSavepoint-1) means operate
 ** on the most recently created savepoint. If iSavepoint is greater than
 ** (Pager.nSavepoint-1), then this function is a no-op.
 **
 ** If a negative value is passed to this function, then the current
-** transaction is rolled back. This is different to calling 
+** transaction is rolled back. This is different to calling
 ** sqlite3PagerRollback() because this function does not terminate
-** the transaction or unlock the database, it just restores the 
-** contents of the database to its original state. 
+** the transaction or unlock the database, it just restores the
+** contents of the database to its original state.
 **
-** In any case, all savepoints with an index greater than iSavepoint 
+** In any case, all savepoints with an index greater than iSavepoint
 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
 ** then savepoint iSavepoint is also destroyed.
 **
 ** This function may return SQLITE_NOMEM if a memory allocation fails,
-** or an IO error code if an IO error occurs while rolling back a 
+** or an IO error code if an IO error occurs while rolling back a
 ** savepoint. If no errors occur, SQLITE_OK is returned.
-*/ 
+*/
 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
   int rc = pPager->errCode;
-  
+
 #ifdef SQLITE_ENABLE_ZIPVFS
   if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
 #endif
@@ -57911,7 +59050,7 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
     int nNew;          /* Number of remaining savepoints after this op. */
 
     /* Figure out how many savepoints will still be active after this
-    ** operation. Store this value in nNew. Then free resources associated 
+    ** operation. Store this value in nNew. Then free resources associated
     ** with any savepoints that are destroyed by this operation.
     */
     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
@@ -57920,7 +59059,7 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
     }
     pPager->nSavepoint = nNew;
 
-    /* If this is a release of the outermost savepoint, truncate 
+    /* If this is a release of the outermost savepoint, truncate
     ** the sub-journal to zero bytes in size. */
     if( op==SAVEPOINT_RELEASE ){
       if( nNew==0 && isOpen(pPager->sjfd) ){
@@ -57942,14 +59081,14 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
       assert(rc!=SQLITE_DONE);
     }
-    
+
 #ifdef SQLITE_ENABLE_ZIPVFS
-    /* If the cache has been modified but the savepoint cannot be rolled 
+    /* If the cache has been modified but the savepoint cannot be rolled
     ** back journal_mode=off, put the pager in the error state. This way,
     ** if the VFS used by this pager includes ZipVFS, the entire transaction
     ** can be rolled back at the ZipVFS level.  */
-    else if( 
-        pPager->journalMode==PAGER_JOURNALMODE_OFF 
+    else if(
+        pPager->journalMode==PAGER_JOURNALMODE_OFF
      && pPager->eState>=PAGER_WRITER_CACHEMOD
     ){
       pPager->errCode = SQLITE_ABORT;
@@ -57971,9 +59110,13 @@ SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
 ** behavior.  But when the Btree needs to know the filename for matching to
 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
 ** participate in shared-cache.
+**
+** The return value to this routine is always safe to use with
+** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.
 */
-SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
-  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
+SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){
+  static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
+  return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;
 }
 
 /*
@@ -57992,16 +59135,6 @@ SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
   return pPager->fd;
 }
 
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
-/*
-** Reset the lock timeout for pager.
-*/
-SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
-  int x = 0;
-  sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
-}
-#endif
-
 /*
 ** Return the file handle for the journal file (if it exists).
 ** This will be either the rollback journal or the WAL file.
@@ -58021,54 +59154,6 @@ SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
   return pPager->zJournal;
 }
 
-#ifdef SQLITE_HAS_CODEC
-/*
-** Set or retrieve the codec for this pager
-*/
-SQLITE_PRIVATE void sqlite3PagerSetCodec(
-  Pager *pPager,
-  void *(*xCodec)(void*,void*,Pgno,int),
-  void (*xCodecSizeChng)(void*,int,int),
-  void (*xCodecFree)(void*),
-  void *pCodec
-){
-  if( pPager->xCodecFree ){
-    pPager->xCodecFree(pPager->pCodec);
-  }else{
-    pager_reset(pPager);
-  }
-  pPager->xCodec = pPager->memDb ? 0 : xCodec;
-  pPager->xCodecSizeChng = xCodecSizeChng;
-  pPager->xCodecFree = xCodecFree;
-  pPager->pCodec = pCodec;
-  setGetterMethod(pPager);
-  pagerReportSize(pPager);
-}
-SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
-  return pPager->pCodec;
-}
-
-/*
-** This function is called by the wal module when writing page content
-** into the log file.
-**
-** This function returns a pointer to a buffer containing the encrypted
-** page content. If a malloc fails, this function may return NULL.
-*/
-SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
-  void *aData = 0;
-  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
-  return aData;
-}
-
-/*
-** Return the current pager state
-*/
-SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
-  return pPager->eState;
-}
-#endif /* SQLITE_HAS_CODEC */
-
 #ifndef SQLITE_OMIT_AUTOVACUUM
 /*
 ** Move the page pPg to location pgno in the file.
@@ -58088,8 +59173,8 @@ SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
 ** transaction is active).
 **
 ** If the fourth argument, isCommit, is non-zero, then this page is being
-** moved as part of a database reorganization just before the transaction 
-** is being committed. In this case, it is guaranteed that the database page 
+** moved as part of a database reorganization just before the transaction
+** is being committed. In this case, it is guaranteed that the database page
 ** pPg refers to will not be written to again within this transaction.
 **
 ** This function may return SQLITE_NOMEM or an IO error code if an error
@@ -58117,7 +59202,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
   }
 
   /* If the page being moved is dirty and has not been saved by the latest
-  ** savepoint, then save the current contents of the page into the 
+  ** savepoint, then save the current contents of the page into the
   ** sub-journal now. This is required to handle the following scenario:
   **
   **   BEGIN;
@@ -58140,7 +59225,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
     return rc;
   }
 
-  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
+  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
 
@@ -58148,7 +59233,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
   ** be written to, store pPg->pgno in local variable needSyncPgno.
   **
   ** If the isCommit flag is set, there is no need to remember that
-  ** the journal needs to be sync()ed before database page pPg->pgno 
+  ** the journal needs to be sync()ed before database page pPg->pgno
   ** can be written to. The caller has already promised not to write to it.
   */
   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
@@ -58159,8 +59244,8 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
   }
 
   /* If the cache contains a page with page-number pgno, remove it
-  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
-  ** page pgno before the 'move' operation, it needs to be retained 
+  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
+  ** page pgno before the 'move' operation, it needs to be retained
   ** for the page moved there.
   */
   pPg->flags &= ~PGHDR_NEED_SYNC;
@@ -58195,9 +59280,9 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
   }
 
   if( needSyncPgno ){
-    /* If needSyncPgno is non-zero, then the journal file needs to be 
+    /* If needSyncPgno is non-zero, then the journal file needs to be
     ** sync()ed before any data is written to database file page needSyncPgno.
-    ** Currently, no such page exists in the page-cache and the 
+    ** Currently, no such page exists in the page-cache and the
     ** "is journaled" bitvec flag has been set. This needs to be remedied by
     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
     ** flag.
@@ -58228,9 +59313,9 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, i
 #endif
 
 /*
-** The page handle passed as the first argument refers to a dirty page 
-** with a page number other than iNew. This function changes the page's 
-** page number to iNew and sets the value of the PgHdr.flags field to 
+** The page handle passed as the first argument refers to a dirty page
+** with a page number other than iNew. This function changes the page's
+** page number to iNew and sets the value of the PgHdr.flags field to
 ** the value passed as the third parameter.
 */
 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
@@ -58248,7 +59333,7 @@ SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
 }
 
 /*
-** Return a pointer to the Pager.nExtra bytes of "extra" space 
+** Return a pointer to the Pager.nExtra bytes of "extra" space
 ** allocated along with the specified page.
 */
 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
@@ -58257,7 +59342,7 @@ SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
 
 /*
 ** Get/set the locking-mode for this pager. Parameter eMode must be one
-** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
+** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
 ** the locking-mode is set to the value specified.
 **
@@ -58305,8 +59390,8 @@ SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
   assert(      eMode==PAGER_JOURNALMODE_DELETE
             || eMode==PAGER_JOURNALMODE_TRUNCATE
             || eMode==PAGER_JOURNALMODE_PERSIST
-            || eMode==PAGER_JOURNALMODE_OFF 
-            || eMode==PAGER_JOURNALMODE_WAL 
+            || eMode==PAGER_JOURNALMODE_OFF
+            || eMode==PAGER_JOURNALMODE_WAL
             || eMode==PAGER_JOURNALMODE_MEMORY );
 
   /* This routine is only called from the OP_JournalMode opcode, and
@@ -58463,7 +59548,6 @@ SQLITE_PRIVATE int sqlite3PagerCheckpoint(
         pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
         pnLog, pnCkpt
     );
-    sqlite3PagerResetLockTimeout(pPager);
   }
   return rc;
 }
@@ -58492,7 +59576,7 @@ static int pagerExclusiveLock(Pager *pPager){
   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
   if( rc!=SQLITE_OK ){
-    /* If the attempt to grab the exclusive lock failed, release the 
+    /* If the attempt to grab the exclusive lock failed, release the
     ** pending lock that may have been obtained instead.  */
     pagerUnlockDb(pPager, SHARED_LOCK);
   }
@@ -58501,7 +59585,7 @@ static int pagerExclusiveLock(Pager *pPager){
 }
 
 /*
-** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
+** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
 ** lock on the database file and use heap-memory to store the wal-index
 ** in. Otherwise, use the normal shared-memory.
@@ -58512,8 +59596,8 @@ static int pagerOpenWal(Pager *pPager){
   assert( pPager->pWal==0 && pPager->tempFile==0 );
   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
 
-  /* If the pager is already in exclusive-mode, the WAL module will use 
-  ** heap-memory for the wal-index instead of the VFS shared-memory 
+  /* If the pager is already in exclusive-mode, the WAL module will use
+  ** heap-memory for the wal-index instead of the VFS shared-memory
   ** implementation. Take the exclusive lock now, before opening the WAL
   ** file, to make sure this is safe.
   */
@@ -58521,7 +59605,7 @@ static int pagerOpenWal(Pager *pPager){
     rc = pagerExclusiveLock(pPager);
   }
 
-  /* Open the connection to the log file. If this operation fails, 
+  /* Open the connection to the log file. If this operation fails,
   ** (e.g. due to malloc() failure), return an error code.
   */
   if( rc==SQLITE_OK ){
@@ -58543,7 +59627,7 @@ static int pagerOpenWal(Pager *pPager){
 ** If the pager passed as the first argument is open on a real database
 ** file (not a temp file or an in-memory database), and the WAL file
 ** is not already open, make an attempt to open it now. If successful,
-** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
+** return SQLITE_OK. If an error occurs or the VFS used by the pager does
 ** not support the xShmXXX() methods, return an error code. *pbOpen is
 ** not modified in either case.
 **
@@ -58585,7 +59669,7 @@ SQLITE_PRIVATE int sqlite3PagerOpenWal(
 ** This function is called to close the connection to the log file prior
 ** to switching from WAL to rollback mode.
 **
-** Before closing the log file, this function attempts to take an 
+** Before closing the log file, this function attempts to take an
 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
 ** If successful, the EXCLUSIVE lock is not released before returning.
@@ -58611,7 +59695,7 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
       rc = pagerOpenWal(pPager);
     }
   }
-    
+
   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
   ** the database file, the log and log-summary files will be deleted.
   */
@@ -58628,6 +59712,32 @@ SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
   return rc;
 }
 
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+/*
+** If pager pPager is a wal-mode database not in exclusive locking mode,
+** invoke the sqlite3WalWriteLock() function on the associated Wal object
+** with the same db and bLock parameters as were passed to this function.
+** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
+*/
+SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){
+  int rc = SQLITE_OK;
+  if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
+    rc = sqlite3WalWriteLock(pPager->pWal, bLock);
+  }
+  return rc;
+}
+
+/*
+** Set the database handle used by the wal layer to determine if
+** blocking locks are required.
+*/
+SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){
+  if( pagerUseWal(pPager) ){
+    sqlite3WalDb(pPager->pWal, db);
+  }
+}
+#endif
+
 #ifdef SQLITE_ENABLE_SNAPSHOT
 /*
 ** If this is a WAL database, obtain a snapshot handle for the snapshot
@@ -58643,10 +59753,13 @@ SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppS
 
 /*
 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
-** read transaction is opened, attempt to read from the snapshot it 
+** read transaction is opened, attempt to read from the snapshot it
 ** identifies. If this is not a WAL database, return an error.
 */
-SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
+SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(
+  Pager *pPager,
+  sqlite3_snapshot *pSnapshot
+){
   int rc = SQLITE_OK;
   if( pPager->pWal ){
     sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
@@ -58657,7 +59770,7 @@ SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSn
 }
 
 /*
-** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this 
+** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
 ** is not a WAL database, return an error.
 */
 SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
@@ -58674,7 +59787,7 @@ SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
 ** The caller currently has a read transaction open on the database.
 ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
 ** this function takes a SHARED lock on the CHECKPOINTER slot and then
-** checks if the snapshot passed as the second argument is still 
+** checks if the snapshot passed as the second argument is still
 ** available. If so, SQLITE_OK is returned.
 **
 ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
@@ -58734,7 +59847,7 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 **
 *************************************************************************
 **
-** This file contains the implementation of a write-ahead log (WAL) used in 
+** This file contains the implementation of a write-ahead log (WAL) used in
 ** "journal_mode=WAL" mode.
 **
 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
@@ -58743,7 +59856,7 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** Each frame records the revised content of a single page from the
 ** database file.  All changes to the database are recorded by writing
 ** frames into the WAL.  Transactions commit when a frame is written that
-** contains a commit marker.  A single WAL can and usually does record 
+** contains a commit marker.  A single WAL can and usually does record
 ** multiple transactions.  Periodically, the content of the WAL is
 ** transferred back into the database file in an operation called a
 ** "checkpoint".
@@ -58769,11 +59882,11 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 **
 ** Immediately following the wal-header are zero or more frames. Each
 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
-** of page data. The frame-header is six big-endian 32-bit unsigned 
+** of page data. The frame-header is six big-endian 32-bit unsigned
 ** integer values, as follows:
 **
 **     0: Page number.
-**     4: For commit records, the size of the database image in pages 
+**     4: For commit records, the size of the database image in pages
 **        after the commit. For all other records, zero.
 **     8: Salt-1 (copied from the header)
 **    12: Salt-2 (copied from the header)
@@ -58799,7 +59912,7 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** the checksum.  The checksum is computed by interpreting the input as
 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
 ** algorithm used for the checksum is as follows:
-** 
+**
 **   for i from 0 to n-1 step 2:
 **     s0 += x[i] + s1;
 **     s1 += x[i+1] + s0;
@@ -58807,7 +59920,7 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 **
 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
 ** in reverse order (the largest fibonacci weight occurs on the first element
-** of the sequence being summed.)  The s1 value spans all 32-bit 
+** of the sequence being summed.)  The s1 value spans all 32-bit
 ** terms of the sequence whereas s0 omits the final term.
 **
 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
@@ -58840,19 +59953,19 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** multiple concurrent readers to view different versions of the database
 ** content simultaneously.
 **
-** The reader algorithm in the previous paragraphs works correctly, but 
+** The reader algorithm in the previous paragraphs works correctly, but
 ** because frames for page P can appear anywhere within the WAL, the
 ** reader has to scan the entire WAL looking for page P frames.  If the
 ** WAL is large (multiple megabytes is typical) that scan can be slow,
 ** and read performance suffers.  To overcome this problem, a separate
 ** data structure called the wal-index is maintained to expedite the
 ** search for frames of a particular page.
-** 
+**
 ** WAL-INDEX FORMAT
 **
 ** Conceptually, the wal-index is shared memory, though VFS implementations
 ** might choose to implement the wal-index using a mmapped file.  Because
-** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
+** the wal-index is shared memory, SQLite does not support journal_mode=WAL
 ** on a network filesystem.  All users of the database must be able to
 ** share memory.
 **
@@ -58870,28 +59983,28 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** byte order of the host computer.
 **
 ** The purpose of the wal-index is to answer this question quickly:  Given
-** a page number P and a maximum frame index M, return the index of the 
+** a page number P and a maximum frame index M, return the index of the
 ** last frame in the wal before frame M for page P in the WAL, or return
 ** NULL if there are no frames for page P in the WAL prior to M.
 **
 ** The wal-index consists of a header region, followed by an one or
-** more index blocks.  
+** more index blocks.
 **
 ** The wal-index header contains the total number of frames within the WAL
 ** in the mxFrame field.
 **
-** Each index block except for the first contains information on 
+** Each index block except for the first contains information on
 ** HASHTABLE_NPAGE frames. The first index block contains information on
-** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
+** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
 ** first index block are the same size as all other index blocks in the
 ** wal-index.
 **
 ** Each index block contains two sections, a page-mapping that contains the
-** database page number associated with each wal frame, and a hash-table 
+** database page number associated with each wal frame, and a hash-table
 ** that allows readers to query an index block for a specific page number.
 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
-** for the first index block) 32-bit page numbers. The first entry in the 
+** for the first index block) 32-bit page numbers. The first entry in the
 ** first index-block contains the database page number corresponding to the
 ** first frame in the WAL file. The first entry in the second index block
 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
@@ -58912,8 +60025,8 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 **
 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
-** hash table for each page number in the mapping section, so the hash 
-** table is never more than half full.  The expected number of collisions 
+** hash table for each page number in the mapping section, so the hash
+** table is never more than half full.  The expected number of collisions
 ** prior to finding a match is 1.  Each entry of the hash table is an
 ** 1-based index of an entry in the mapping section of the same
 ** index block.   Let K be the 1-based index of the largest entry in
@@ -58932,12 +60045,12 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** reached) until an unused hash slot is found. Let the first unused slot
 ** be at index iUnused.  (iUnused might be less than iKey if there was
 ** wrap-around.) Because the hash table is never more than half full,
-** the search is guaranteed to eventually hit an unused entry.  Let 
+** the search is guaranteed to eventually hit an unused entry.  Let
 ** iMax be the value between iKey and iUnused, closest to iUnused,
 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
 ** no hash slot such that aHash[i]==p) then page P is not in the
 ** current index block.  Otherwise the iMax-th mapping entry of the
-** current index block corresponds to the last entry that references 
+** current index block corresponds to the last entry that references
 ** page P.
 **
 ** A hash search begins with the last index block and moves toward the
@@ -58962,7 +60075,7 @@ SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
 ** if no values greater than K0 had ever been inserted into the hash table
 ** in the first place - which is what reader one wants.  Meanwhile, the
 ** second reader using K1 will see additional values that were inserted
-** later, which is exactly what reader two wants.  
+** later, which is exactly what reader two wants.
 **
 ** When a rollback occurs, the value of K is decreased. Hash table entries
 ** that correspond to frames greater than the new K value are removed
@@ -58983,18 +60096,6 @@ SQLITE_PRIVATE int sqlite3WalTrace = 0;
 #endif
 
 /*
-** WAL mode depends on atomic aligned 32-bit loads and stores in a few
-** places.  The following macros try to make this explicit.
-*/
-#if GCC_VESRION>=5004000
-# define AtomicLoad(PTR)       __atomic_load_n((PTR),__ATOMIC_RELAXED)
-# define AtomicStore(PTR,VAL)  __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
-#else
-# define AtomicLoad(PTR)       (*(PTR))
-# define AtomicStore(PTR,VAL)  (*(PTR) = (VAL))
-#endif
-
-/*
 ** The maximum (and only) versions of the wal and wal-index formats
 ** that may be interpreted by this version of SQLite.
 **
@@ -59002,7 +60103,7 @@ SQLITE_PRIVATE int sqlite3WalTrace = 0;
 ** values in the wal-header are correct and (b) the version field is not
 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
 **
-** Similarly, if a client successfully reads a wal-index header (i.e. the 
+** Similarly, if a client successfully reads a wal-index header (i.e. the
 ** checksum test is successful) and finds that the version field is not
 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
 ** returns SQLITE_CANTOPEN.
@@ -59049,7 +60150,7 @@ typedef struct WalCkptInfo WalCkptInfo;
 **
 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
-** added in 3.7.1 when support for 64K pages was added.  
+** added in 3.7.1 when support for 64K pages was added.
 */
 struct WalIndexHdr {
   u32 iVersion;                   /* Wal-index version */
@@ -59091,7 +60192,7 @@ struct WalIndexHdr {
 ** There is one entry in aReadMark[] for each reader lock.  If a reader
 ** holds read-lock K, then the value in aReadMark[K] is no greater than
 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
-** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
+** for any aReadMark[] means that entry is unused.  aReadMark[0] is
 ** a special case; its value is never used and it exists as a place-holder
 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
@@ -59111,7 +60212,7 @@ struct WalIndexHdr {
 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
 ** in the WAL has been backfilled into the database) then new readers
 ** will choose aReadMark[0] which has value 0 and hence such reader will
-** get all their all content directly from the database file and ignore 
+** get all their all content directly from the database file and ignore
 ** the WAL.
 **
 ** Writers normally append new frames to the end of the WAL.  However,
@@ -59153,14 +60254,14 @@ struct WalCkptInfo {
 ** big-endian format in the first 4 bytes of a WAL file.
 **
 ** If the LSB is set, then the checksums for each frame within the WAL
-** file are calculated by treating all data as an array of 32-bit 
-** big-endian words. Otherwise, they are calculated by interpreting 
+** file are calculated by treating all data as an array of 32-bit
+** big-endian words. Otherwise, they are calculated by interpreting
 ** all data as 32-bit little-endian words.
 */
 #define WAL_MAGIC 0x377f0682
 
 /*
-** Return the offset of frame iFrame in the write-ahead log file, 
+** Return the offset of frame iFrame in the write-ahead log file,
 ** assuming a database page size of szPage bytes. The offset returned
 ** is to the start of the write-ahead log frame-header.
 */
@@ -59203,13 +60304,16 @@ struct Wal {
 #ifdef SQLITE_ENABLE_SNAPSHOT
   WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
 #endif
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  sqlite3 *db;
+#endif
 };
 
 /*
 ** Candidate values for Wal.exclusiveMode.
 */
 #define WAL_NORMAL_MODE     0
-#define WAL_EXCLUSIVE_MODE  1     
+#define WAL_EXCLUSIVE_MODE  1
 #define WAL_HEAPMEMORY_MODE 2
 
 /*
@@ -59228,7 +60332,7 @@ typedef u16 ht_slot;
 /*
 ** This structure is used to implement an iterator that loops through
 ** all frames in the WAL in database page order. Where two or more frames
-** correspond to the same database page, the iterator visits only the 
+** correspond to the same database page, the iterator visits only the
 ** frame most recently written to the WAL (in other words, the frame with
 ** the largest index).
 **
@@ -59241,7 +60345,7 @@ typedef u16 ht_slot;
 ** This functionality is used by the checkpoint code (see walCheckpoint()).
 */
 struct WalIterator {
-  int iPrior;                     /* Last result returned from the iterator */
+  u32 iPrior;                     /* Last result returned from the iterator */
   int nSegment;                   /* Number of entries in aSegment[] */
   struct WalSegment {
     int iNext;                    /* Next slot in aIndex[] not yet returned */
@@ -59264,7 +60368,7 @@ struct WalIterator {
 #define HASHTABLE_HASH_1     383                  /* Should be prime */
 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
 
-/* 
+/*
 ** The block of page numbers associated with the first hash-table in a
 ** wal-index is smaller than usual. This is so that there is a complete
 ** hash-table on each aligned 32KB page of the wal-index.
@@ -59318,12 +60422,14 @@ static SQLITE_NOINLINE int walIndexPageRealloc(
     pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
     if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
   }else{
-    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
+    rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
         pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
     );
     assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
     testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
-    if( (rc&0xff)==SQLITE_READONLY ){
+    if( rc==SQLITE_OK ){
+      if( iPage>0 && sqlite3FaultSim(600) ) rc = SQLITE_NOMEM;
+    }else if( (rc&0xff)==SQLITE_READONLY ){
       pWal->readOnly |= WAL_SHM_RDONLY;
       if( rc==SQLITE_READONLY ){
         rc = SQLITE_OK;
@@ -59375,7 +60481,7 @@ static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
 )
 
 /*
-** Generate or extend an 8 byte checksum based on the data in 
+** Generate or extend an 8 byte checksum based on the data in
 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
 ** initial values of 0 and 0 if aIn==NULL).
 **
@@ -59422,6 +60528,10 @@ static void walChecksumBytes(
   aOut[1] = s2;
 }
 
+/*
+** If there is the possibility of concurrent access to the SHM file
+** from multiple threads and/or processes, then do a memory barrier.
+*/
 static void walShmBarrier(Wal *pWal){
   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
     sqlite3OsShmBarrier(pWal->pDbFd);
@@ -59429,11 +60539,24 @@ static void walShmBarrier(Wal *pWal){
 }
 
 /*
+** Add the SQLITE_NO_TSAN as part of the return-type of a function
+** definition as a hint that the function contains constructs that
+** might give false-positive TSAN warnings.
+**
+** See tag-20200519-1.
+*/
+#if defined(__clang__) && !defined(SQLITE_NO_TSAN)
+# define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
+#else
+# define SQLITE_NO_TSAN
+#endif
+
+/*
 ** Write the header information in pWal->hdr into the wal-index.
 **
 ** The checksum on pWal->hdr is updated before it is written.
 */
-static void walIndexWriteHdr(Wal *pWal){
+static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
   const int nCksum = offsetof(WalIndexHdr, aCksum);
 
@@ -59441,6 +60564,7 @@ static void walIndexWriteHdr(Wal *pWal){
   pWal->hdr.isInit = 1;
   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
+  /* Possible TSAN false-positive.  See tag-20200519-1 */
   memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
   walShmBarrier(pWal);
   memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
@@ -59448,11 +60572,11 @@ static void walIndexWriteHdr(Wal *pWal){
 
 /*
 ** This function encodes a single frame header and writes it to a buffer
-** supplied by the caller. A frame-header is made up of a series of 
+** supplied by the caller. A frame-header is made up of a series of
 ** 4-byte big-endian integers, as follows:
 **
 **     0: Page number.
-**     4: For commit records, the size of the database image in pages 
+**     4: For commit records, the size of the database image in pages
 **        after the commit. For all other records, zero.
 **     8: Salt-1 (copied from the wal-header)
 **    12: Salt-2 (copied from the wal-header)
@@ -59503,7 +60627,7 @@ static int walDecodeFrame(
   assert( WAL_FRAME_HDRSIZE==24 );
 
   /* A frame is only valid if the salt values in the frame-header
-  ** match the salt values in the wal-header. 
+  ** match the salt values in the wal-header.
   */
   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
     return 0;
@@ -59517,15 +60641,15 @@ static int walDecodeFrame(
   }
 
   /* A frame is only valid if a checksum of the WAL header,
-  ** all prior frams, the first 16 bytes of this frame-header, 
-  ** and the frame-data matches the checksum in the last 8 
+  ** all prior frams, the first 16 bytes of this frame-header,
+  ** and the frame-data matches the checksum in the last 8
   ** bytes of this frame-header.
   */
   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
-  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
-   || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
+  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
+   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
   ){
     /* Checksum failed. */
     return 0;
@@ -59560,7 +60684,7 @@ static const char *walLockName(int lockIdx){
   }
 }
 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
-    
+
 
 /*
 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
@@ -59576,7 +60700,7 @@ static int walLockShared(Wal *pWal, int lockIdx){
                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
             walLockName(lockIdx), rc ? "failed" : "ok"));
-  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
+  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
   return rc;
 }
 static void walUnlockShared(Wal *pWal, int lockIdx){
@@ -59592,7 +60716,7 @@ static int walLockExclusive(Wal *pWal, int lockIdx, int n){
                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
             walLockName(lockIdx), n, rc ? "failed" : "ok"));
-  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
+  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
   return rc;
 }
 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
@@ -59629,15 +60753,15 @@ struct WalHashLoc {
   u32 iZero;                /* One less than the frame number of first indexed*/
 };
 
-/* 
+/*
 ** Return pointers to the hash table and page number array stored on
 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
 ** numbered starting from 0.
 **
 ** Set output variable pLoc->aHash to point to the start of the hash table
-** in the wal-index file. Set pLoc->iZero to one less than the frame 
+** in the wal-index file. Set pLoc->iZero to one less than the frame
 ** number of the first frame indexed by this hash table. If a
-** slot in the hash table is set to N, it refers to frame number 
+** slot in the hash table is set to N, it refers to frame number
 ** (pLoc->iZero+N) in the log.
 **
 ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
@@ -59669,7 +60793,7 @@ static int walHashGet(
 /*
 ** Return the number of the wal-index page that contains the hash-table
 ** and page-number array that contain entries corresponding to WAL frame
-** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
+** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
 ** are numbered starting from 0.
 */
 static int walFramePage(u32 iFrame){
@@ -59680,6 +60804,7 @@ static int walFramePage(u32 iFrame){
        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
   );
+  assert( iHash>=0 );
   return iHash;
 }
 
@@ -59720,7 +60845,7 @@ static void walCleanupHash(Wal *pWal){
 
   if( pWal->hdr.mxFrame==0 ) return;
 
-  /* Obtain pointers to the hash-table and page-number array containing 
+  /* Obtain pointers to the hash-table and page-number array containing
   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
   ** that the page said hash-table and array reside on is already mapped.(1)
   */
@@ -59739,9 +60864,9 @@ static void walCleanupHash(Wal *pWal){
       sLoc.aHash[i] = 0;
     }
   }
-  
+
   /* Zero the entries in the aPgno array that correspond to frames with
-  ** frame numbers greater than pWal->hdr.mxFrame. 
+  ** frame numbers greater than pWal->hdr.mxFrame.
   */
   nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
   memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
@@ -59784,9 +60909,9 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 
     idx = iFrame - sLoc.iZero;
     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
-    
+
     /* If this is the first entry to be added to this hash-table, zero the
-    ** entire hash table and aPgno[] array before proceeding. 
+    ** entire hash table and aPgno[] array before proceeding.
     */
     if( idx==1 ){
       int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
@@ -59796,8 +60921,8 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 
     /* If the entry in aPgno[] is already set, then the previous writer
     ** must have exited unexpectedly in the middle of a transaction (after
-    ** writing one or more dirty pages to the WAL to free up memory). 
-    ** Remove the remnants of that writers uncommitted transaction from 
+    ** writing one or more dirty pages to the WAL to free up memory).
+    ** Remove the remnants of that writers uncommitted transaction from
     ** the hash-table before writing any new entries.
     */
     if( sLoc.aPgno[idx] ){
@@ -59811,7 +60936,7 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
     }
     sLoc.aPgno[idx] = iPage;
-    sLoc.aHash[iKey] = (ht_slot)idx;
+    AtomicStore(&sLoc.aHash[iKey], (ht_slot)idx);
 
 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
     /* Verify that the number of entries in the hash table exactly equals
@@ -59849,7 +60974,7 @@ static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
 
 
 /*
-** Recover the wal-index by reading the write-ahead log file. 
+** Recover the wal-index by reading the write-ahead log file.
 **
 ** This routine first tries to establish an exclusive lock on the
 ** wal-index to prevent other threads/processes from doing anything
@@ -59876,12 +61001,6 @@ static int walIndexRecover(Wal *pWal){
   assert( pWal->writeLock );
   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
   rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
-  if( rc==SQLITE_OK ){
-    rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
-    if( rc!=SQLITE_OK ){
-      walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
-    }
-  }
   if( rc ){
     return rc;
   }
@@ -59897,15 +61016,16 @@ static int walIndexRecover(Wal *pWal){
 
   if( nSize>WAL_HDRSIZE ){
     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
+    u32 *aPrivate = 0;            /* Heap copy of *-shm hash being populated */
     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
     int szFrame;                  /* Number of bytes in buffer aFrame[] */
     u8 *aData;                    /* Pointer to data part of aFrame buffer */
-    int iFrame;                   /* Index of last frame read */
-    i64 iOffset;                  /* Next offset to read from log file */
     int szPage;                   /* Page size according to the log */
     u32 magic;                    /* Magic value read from WAL header */
     u32 version;                  /* Magic value read from WAL header */
     int isValid;                  /* True if this frame is valid */
+    u32 iPg;                      /* Current 32KB wal-index page */
+    u32 iLastFrame;               /* Last frame in wal, based on nSize alone */
 
     /* Read in the WAL header. */
     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
@@ -59914,16 +61034,16 @@ static int walIndexRecover(Wal *pWal){
     }
 
     /* If the database page size is not a power of two, or is greater than
-    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
+    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
     ** WAL file.
     */
     magic = sqlite3Get4byte(&aBuf[0]);
     szPage = sqlite3Get4byte(&aBuf[8]);
-    if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
-     || szPage&(szPage-1) 
-     || szPage>SQLITE_MAX_PAGE_SIZE 
-     || szPage<512 
+    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
+     || szPage&(szPage-1)
+     || szPage>SQLITE_MAX_PAGE_SIZE
+     || szPage<512
     ){
       goto finished;
     }
@@ -59933,7 +61053,7 @@ static int walIndexRecover(Wal *pWal){
     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
 
     /* Verify that the WAL header checksum is correct */
-    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
+    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
     );
     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
@@ -59952,38 +61072,82 @@ static int walIndexRecover(Wal *pWal){
 
     /* Malloc a buffer to read frames into. */
     szFrame = szPage + WAL_FRAME_HDRSIZE;
-    aFrame = (u8 *)sqlite3Malloc(szFrame);
+    aFrame = (u8 *)sqlite3Malloc(szFrame + WALINDEX_PGSZ);
     if( !aFrame ){
       rc = SQLITE_NOMEM_BKPT;
       goto recovery_error;
     }
     aData = &aFrame[WAL_FRAME_HDRSIZE];
+    aPrivate = (u32*)&aData[szPage];
 
     /* Read all frames from the log file. */
-    iFrame = 0;
-    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
-      u32 pgno;                   /* Database page number for frame */
-      u32 nTruncate;              /* dbsize field from frame header */
-
-      /* Read and decode the next log frame. */
-      iFrame++;
-      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
-      if( rc!=SQLITE_OK ) break;
-      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
-      if( !isValid ) break;
-      rc = walIndexAppend(pWal, iFrame, pgno);
-      if( rc!=SQLITE_OK ) break;
+    iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
+    for(iPg=0; iPg<=(u32)walFramePage(iLastFrame); iPg++){
+      u32 *aShare;
+      u32 iFrame;                 /* Index of last frame read */
+      u32 iLast = MIN(iLastFrame, HASHTABLE_NPAGE_ONE+iPg*HASHTABLE_NPAGE);
+      u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
+      u32 nHdr, nHdr32;
+      rc = walIndexPage(pWal, iPg, (volatile u32**)&aShare);
+      if( rc ) break;
+      pWal->apWiData[iPg] = aPrivate;
+
+      for(iFrame=iFirst; iFrame<=iLast; iFrame++){
+        i64 iOffset = walFrameOffset(iFrame, szPage);
+        u32 pgno;                 /* Database page number for frame */
+        u32 nTruncate;            /* dbsize field from frame header */
 
-      /* If nTruncate is non-zero, this is a commit record. */
-      if( nTruncate ){
-        pWal->hdr.mxFrame = iFrame;
-        pWal->hdr.nPage = nTruncate;
-        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
-        testcase( szPage<=32768 );
-        testcase( szPage>=65536 );
-        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
-        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
+        /* Read and decode the next log frame. */
+        rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
+        if( rc!=SQLITE_OK ) break;
+        isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
+        if( !isValid ) break;
+        rc = walIndexAppend(pWal, iFrame, pgno);
+        if( NEVER(rc!=SQLITE_OK) ) break;
+
+        /* If nTruncate is non-zero, this is a commit record. */
+        if( nTruncate ){
+          pWal->hdr.mxFrame = iFrame;
+          pWal->hdr.nPage = nTruncate;
+          pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
+          testcase( szPage<=32768 );
+          testcase( szPage>=65536 );
+          aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
+          aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
+        }
+      }
+      pWal->apWiData[iPg] = aShare;
+      nHdr = (iPg==0 ? WALINDEX_HDR_SIZE : 0);
+      nHdr32 = nHdr / sizeof(u32);
+#ifndef SQLITE_SAFER_WALINDEX_RECOVERY
+      /* Memcpy() should work fine here, on all reasonable implementations.
+      ** Technically, memcpy() might change the destination to some
+      ** intermediate value before setting to the final value, and that might
+      ** cause a concurrent reader to malfunction.  Memcpy() is allowed to
+      ** do that, according to the spec, but no memcpy() implementation that
+      ** we know of actually does that, which is why we say that memcpy()
+      ** is safe for this.  Memcpy() is certainly a lot faster.
+      */
+      memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
+#else
+      /* In the event that some platform is found for which memcpy()
+      ** changes the destination to some intermediate value before
+      ** setting the final value, this alternative copy routine is
+      ** provided.
+      */
+      {
+        int i;
+        for(i=nHdr32; i<WALINDEX_PGSZ/sizeof(u32); i++){
+          if( aShare[i]!=aPrivate[i] ){
+            /* Atomic memory operations are not required here because if
+            ** the value needs to be changed, that means it is not being
+            ** accessed concurrently. */
+            aShare[i] = aPrivate[i];
+          }
+        }
       }
+#endif
+      if( iFrame<=iLast ) break;
     }
 
     sqlite3_free(aFrame);
@@ -59997,16 +61161,27 @@ finished:
     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
     walIndexWriteHdr(pWal);
 
-    /* Reset the checkpoint-header. This is safe because this thread is 
-    ** currently holding locks that exclude all other readers, writers and
-    ** checkpointers.
+    /* Reset the checkpoint-header. This is safe because this thread is
+    ** currently holding locks that exclude all other writers and
+    ** checkpointers. Then set the values of read-mark slots 1 through N.
     */
     pInfo = walCkptInfo(pWal);
     pInfo->nBackfill = 0;
     pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
     pInfo->aReadMark[0] = 0;
-    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
-    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
+    for(i=1; i<WAL_NREADER; i++){
+      rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
+      if( rc==SQLITE_OK ){
+        if( i==1 && pWal->hdr.mxFrame ){
+          pInfo->aReadMark[i] = pWal->hdr.mxFrame;
+        }else{
+          pInfo->aReadMark[i] = READMARK_NOT_USED;
+        }
+        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
+      }else if( rc!=SQLITE_BUSY ){
+        goto recovery_error;
+      }
+    }
 
     /* If more than one frame was recovered from the log file, report an
     ** event via sqlite3_log(). This is to help with identifying performance
@@ -60024,7 +61199,6 @@ finished:
 recovery_error:
   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
   walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
-  walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
   return rc;
 }
 
@@ -60044,8 +61218,8 @@ static void walIndexClose(Wal *pWal, int isDelete){
   }
 }
 
-/* 
-** Open a connection to the WAL file zWalName. The database file must 
+/*
+** Open a connection to the WAL file zWalName. The database file must
 ** already be opened on connection pDbFd. The buffer that zWalName points
 ** to must remain valid for the lifetime of the returned Wal* handle.
 **
@@ -60055,7 +61229,7 @@ static void walIndexClose(Wal *pWal, int isDelete){
 ** were to do this just after this client opened one of these files, the
 ** system would be badly broken.
 **
-** If the log file is successfully opened, SQLITE_OK is returned and 
+** If the log file is successfully opened, SQLITE_OK is returned and
 ** *ppWal is set to point to a new WAL handle. If an error occurs,
 ** an SQLite error code is returned and *ppWal is left unmodified.
 */
@@ -60219,7 +61393,7 @@ static void walMerge(
     ht_slot logpage;
     Pgno dbpage;
 
-    if( (iLeft<nLeft) 
+    if( (iLeft<nLeft)
      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
     ){
       logpage = aLeft[iLeft++];
@@ -60317,7 +61491,7 @@ static void walMergesort(
 #endif
 }
 
-/* 
+/*
 ** Free an iterator allocated by walIteratorInit().
 */
 static void walIteratorFree(WalIterator *p){
@@ -60325,7 +61499,7 @@ static void walIteratorFree(WalIterator *p){
 }
 
 /*
-** Construct a WalInterator object that can be used to loop over all 
+** Construct a WalInterator object that can be used to loop over all
 ** pages in the WAL following frame nBackfill in ascending order. Frames
 ** nBackfill or earlier may be included - excluding them is an optimization
 ** only. The caller must hold the checkpoint lock.
@@ -60354,7 +61528,7 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
 
   /* Allocate space for the WalIterator object. */
   nSegment = walFramePage(iLast) + 1;
-  nByte = sizeof(WalIterator) 
+  nByte = sizeof(WalIterator)
         + (nSegment-1)*sizeof(struct WalSegment)
         + iLast*sizeof(ht_slot);
   p = (WalIterator *)sqlite3Malloc(nByte);
@@ -60391,7 +61565,7 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
       }
       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
       sLoc.iZero++;
-  
+
       for(j=0; j<nEntry; j++){
         aIndex[j] = (ht_slot)j;
       }
@@ -60412,6 +61586,89 @@ static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
   return rc;
 }
 
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+/*
+** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
+** they are supported by the VFS, and (b) the database handle is configured
+** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
+** or 0 otherwise.
+*/
+static int walEnableBlocking(Wal *pWal){
+  int res = 0;
+  if( pWal->db ){
+    int tmout = pWal->db->busyTimeout;
+    if( tmout ){
+      int rc;
+      rc = sqlite3OsFileControl(
+          pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
+      );
+      res = (rc==SQLITE_OK);
+    }
+  }
+  return res;
+}
+
+/*
+** Disable blocking locks.
+*/
+static void walDisableBlocking(Wal *pWal){
+  int tmout = 0;
+  sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
+}
+
+/*
+** If parameter bLock is true, attempt to enable blocking locks, take
+** the WRITER lock, and then disable blocking locks. If blocking locks
+** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
+** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
+** an error if blocking locks can not be enabled.
+**
+** If the bLock parameter is false and the WRITER lock is held, release it.
+*/
+SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){
+  int rc = SQLITE_OK;
+  assert( pWal->readLock<0 || bLock==0 );
+  if( bLock ){
+    assert( pWal->db );
+    if( walEnableBlocking(pWal) ){
+      rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
+      if( rc==SQLITE_OK ){
+        pWal->writeLock = 1;
+      }
+      walDisableBlocking(pWal);
+    }
+  }else if( pWal->writeLock ){
+    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
+    pWal->writeLock = 0;
+  }
+  return rc;
+}
+
+/*
+** Set the database handle used to determine if blocking locks are required.
+*/
+SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){
+  pWal->db = db;
+}
+
+/*
+** Take an exclusive WRITE lock. Blocking if so configured.
+*/
+static int walLockWriter(Wal *pWal){
+  int rc;
+  walEnableBlocking(pWal);
+  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
+  walDisableBlocking(pWal);
+  return rc;
+}
+#else
+# define walEnableBlocking(x) 0
+# define walDisableBlocking(x)
+# define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
+# define sqlite3WalDb(pWal, db)
+#endif   /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
+
+
 /*
 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
@@ -60429,6 +61686,12 @@ static int walBusyLock(
   do {
     rc = walLockExclusive(pWal, lockIdx, n);
   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  if( rc==SQLITE_BUSY_TIMEOUT ){
+    walDisableBlocking(pWal);
+    rc = SQLITE_BUSY;
+  }
+#endif
   return rc;
 }
 
@@ -60453,8 +61716,8 @@ static int walPagesize(Wal *pWal){
 ** client to write to the database (which may be this one) does so by
 ** writing frames into the start of the log file.
 **
-** The value of parameter salt1 is used as the aSalt[1] value in the 
-** new wal-index header. It should be passed a pseudo-random value (i.e. 
+** The value of parameter salt1 is used as the aSalt[1] value in the
+** new wal-index header. It should be passed a pseudo-random value (i.e.
 ** one obtained from sqlite3_randomness()).
 */
 static void walRestartHdr(Wal *pWal, u32 salt1){
@@ -60466,7 +61729,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){
   sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
   memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
   walIndexWriteHdr(pWal);
-  pInfo->nBackfill = 0;
+  AtomicStore(&pInfo->nBackfill, 0);
   pInfo->nBackfillAttempted = 0;
   pInfo->aReadMark[1] = 0;
   for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
@@ -60482,8 +61745,8 @@ static void walRestartHdr(Wal *pWal, u32 salt1){
 ** that a concurrent reader might be using.
 **
 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
-** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
-** checkpoints are always run by a background thread or background 
+** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
+** checkpoints are always run by a background thread or background
 ** process, foreground threads will never block on a lengthy fsync call.
 **
 ** Fsync is called on the WAL before writing content out of the WAL and
@@ -60496,7 +61759,7 @@ static void walRestartHdr(Wal *pWal, u32 salt1){
 ** database file.
 **
 ** This routine uses and updates the nBackfill field of the wal-index header.
-** This is the only routine that will increase the value of nBackfill.  
+** This is the only routine that will increase the value of nBackfill.
 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
 ** its value.)
 **
@@ -60541,20 +61804,13 @@ static int walCheckpoint(
     mxSafeFrame = pWal->hdr.mxFrame;
     mxPage = pWal->hdr.nPage;
     for(i=1; i<WAL_NREADER; i++){
-      /* Thread-sanitizer reports that the following is an unsafe read,
-      ** as some other thread may be in the process of updating the value
-      ** of the aReadMark[] slot. The assumption here is that if that is
-      ** happening, the other client may only be increasing the value,
-      ** not decreasing it. So assuming either that either the "old" or
-      ** "new" version of the value is read, and not some arbitrary value
-      ** that would never be written by a real client, things are still 
-      ** safe.  */
-      u32 y = pInfo->aReadMark[i];
+      u32 y = AtomicLoad(pInfo->aReadMark+i);
       if( mxSafeFrame>y ){
         assert( y<=pWal->hdr.mxFrame );
         rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
         if( rc==SQLITE_OK ){
-          pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
+          u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
+          AtomicStore(pInfo->aReadMark+i, iMark);
           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
         }else if( rc==SQLITE_BUSY ){
           mxSafeFrame = y;
@@ -60572,7 +61828,7 @@ static int walCheckpoint(
     }
 
     if( pIter
-     && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
+     && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
     ){
       u32 nBackfill = pInfo->nBackfill;
 
@@ -60587,18 +61843,27 @@ static int walCheckpoint(
       if( rc==SQLITE_OK ){
         i64 nReq = ((i64)mxPage * szPage);
         i64 nSize;                    /* Current size of database file */
+        sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
         rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
         if( rc==SQLITE_OK && nSize<nReq ){
-          sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
+          if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
+            /* If the size of the final database is larger than the current
+            ** database plus the amount of data in the wal file, plus the
+            ** maximum size of the pending-byte page (65536 bytes), then
+            ** must be corruption somewhere.  */
+            rc = SQLITE_CORRUPT_BKPT;
+          }else{
+            sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
+          }
         }
-      }
 
+      }
 
       /* Iterate through the contents of the WAL, copying data to the db file */
       while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
         i64 iOffset;
         assert( walFramePgno(pWal, iFrame)==iDbpage );
-        if( db->u1.isInterrupted ){
+        if( AtomicLoad(&db->u1.isInterrupted) ){
           rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
           break;
         }
@@ -60614,6 +61879,7 @@ static int walCheckpoint(
         rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
         if( rc!=SQLITE_OK ) break;
       }
+      sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
 
       /* If work was actually accomplished... */
       if( rc==SQLITE_OK ){
@@ -60626,7 +61892,7 @@ static int walCheckpoint(
           }
         }
         if( rc==SQLITE_OK ){
-          pInfo->nBackfill = mxSafeFrame;
+          AtomicStore(&pInfo->nBackfill, mxSafeFrame);
         }
       }
 
@@ -60642,8 +61908,8 @@ static int walCheckpoint(
   }
 
   /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
-  ** entire wal file has been copied into the database file, then block 
-  ** until all readers have finished using the wal file. This ensures that 
+  ** entire wal file has been copied into the database file, then block
+  ** until all readers have finished using the wal file. This ensures that
   ** the next process to write to the database restarts the wal file.
   */
   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
@@ -60667,7 +61933,7 @@ static int walCheckpoint(
           ** writer clients should see that the entire log file has been
           ** checkpointed and behave accordingly. This seems unsafe though,
           ** as it would leave the system in a state where the contents of
-          ** the wal-index header do not match the contents of the 
+          ** the wal-index header do not match the contents of the
           ** file-system. To avoid this, update the wal-index header to
           ** indicate that the log file contains zero valid frames.  */
           walRestartHdr(pWal, salt1);
@@ -60729,7 +61995,7 @@ SQLITE_PRIVATE int sqlite3WalClose(
       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
       }
-      rc = sqlite3WalCheckpoint(pWal, db, 
+      rc = sqlite3WalCheckpoint(pWal, db,
           SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
       );
       if( rc==SQLITE_OK ){
@@ -60785,7 +62051,7 @@ SQLITE_PRIVATE int sqlite3WalClose(
 ** If the checksum cannot be verified return non-zero. If the header
 ** is read successfully and the checksum verified, return zero.
 */
-static int walIndexTryHdr(Wal *pWal, int *pChanged){
+static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
   u32 aCksum[2];                  /* Checksum on the header content */
   WalIndexHdr h1, h2;             /* Two copies of the header content */
   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
@@ -60798,19 +62064,25 @@ static int walIndexTryHdr(Wal *pWal, int *pChanged){
   ** meaning it is possible that an inconsistent snapshot is read
   ** from the file. If this happens, return non-zero.
   **
+  ** tag-20200519-1:
   ** There are two copies of the header at the beginning of the wal-index.
   ** When reading, read [0] first then [1].  Writes are in the reverse order.
   ** Memory barriers are used to prevent the compiler or the hardware from
-  ** reordering the reads and writes.
+  ** reordering the reads and writes.  TSAN and similar tools can sometimes
+  ** give false-positive warnings about these accesses because the tools do not
+  ** account for the double-read and the memory barrier. The use of mutexes
+  ** here would be problematic as the memory being accessed is potentially
+  ** shared among multiple processes and not all mutex implementions work
+  ** reliably in that environment.
   */
   aHdr = walIndexHdr(pWal);
-  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
+  memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
   walShmBarrier(pWal);
   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
 
   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
     return 1;   /* Dirty read */
-  }  
+  }
   if( h1.isInit==0 ){
     return 1;   /* Malformed header - probably all zeros */
   }
@@ -60846,7 +62118,7 @@ static int walIndexTryHdr(Wal *pWal, int *pChanged){
 ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
 ** to 0.
 **
-** If the wal-index header is successfully read, return SQLITE_OK. 
+** If the wal-index header is successfully read, return SQLITE_OK.
 ** Otherwise an SQLite error code.
 */
 static int walIndexReadHdr(Wal *pWal, int *pChanged){
@@ -60854,7 +62126,7 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){
   int badHdr;                     /* True if a header read failed */
   volatile u32 *page0;            /* Chunk of wal-index containing header */
 
-  /* Ensure that page 0 of the wal-index (the page that contains the 
+  /* Ensure that page 0 of the wal-index (the page that contains the
   ** wal-index header) is mapped. Return early if an error occurs here.
   */
   assert( pChanged );
@@ -60886,7 +62158,7 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){
 
   /* If the first page of the wal-index has been mapped, try to read the
   ** wal-index header immediately, without holding any lock. This usually
-  ** works, but may fail if the wal-index header is corrupt or currently 
+  ** works, but may fail if the wal-index header is corrupt or currently
   ** being modified by another thread or process.
   */
   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
@@ -60894,28 +62166,32 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){
   /* If the first attempt failed, it might have been due to a race
   ** with a writer.  So get a WRITE lock and try again.
   */
-  assert( badHdr==0 || pWal->writeLock==0 );
   if( badHdr ){
     if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
         walUnlockShared(pWal, WAL_WRITE_LOCK);
         rc = SQLITE_READONLY_RECOVERY;
       }
-    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
-      pWal->writeLock = 1;
-      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
-        badHdr = walIndexTryHdr(pWal, pChanged);
-        if( badHdr ){
-          /* If the wal-index header is still malformed even while holding
-          ** a WRITE lock, it can only mean that the header is corrupted and
-          ** needs to be reconstructed.  So run recovery to do exactly that.
-          */
-          rc = walIndexRecover(pWal);
-          *pChanged = 1;
+    }else{
+      int bWriteLock = pWal->writeLock;
+      if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){
+        pWal->writeLock = 1;
+        if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
+          badHdr = walIndexTryHdr(pWal, pChanged);
+          if( badHdr ){
+            /* If the wal-index header is still malformed even while holding
+            ** a WRITE lock, it can only mean that the header is corrupted and
+            ** needs to be reconstructed.  So run recovery to do exactly that.
+            */
+            rc = walIndexRecover(pWal);
+            *pChanged = 1;
+          }
+        }
+        if( bWriteLock==0 ){
+          pWal->writeLock = 0;
+          walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
         }
       }
-      pWal->writeLock = 0;
-      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
     }
   }
 
@@ -60957,15 +62233,15 @@ static int walIndexReadHdr(Wal *pWal, int *pChanged){
 **
 **    The *-wal file has been read and an appropriate wal-index has been
 **    constructed in pWal->apWiData[] using heap memory instead of shared
-**    memory. 
+**    memory.
 **
 ** If this function returns SQLITE_OK, then the read transaction has
-** been successfully opened. In this case output variable (*pChanged) 
+** been successfully opened. In this case output variable (*pChanged)
 ** is set to true before returning if the caller should discard the
-** contents of the page cache before proceeding. Or, if it returns 
-** WAL_RETRY, then the heap memory wal-index has been discarded and 
-** the caller should retry opening the read transaction from the 
-** beginning (including attempting to map the *-shm file). 
+** contents of the page cache before proceeding. Or, if it returns
+** WAL_RETRY, then the heap memory wal-index has been discarded and
+** the caller should retry opening the read transaction from the
+** beginning (including attempting to map the *-shm file).
 **
 ** If an error occurs, an SQLite error code is returned.
 */
@@ -61076,8 +62352,8 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
   ** the caller.  */
   aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
   aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
-  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage); 
-      iOffset+szFrame<=szWal; 
+  for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
+      iOffset+szFrame<=szWal;
       iOffset+=szFrame
   ){
     u32 pgno;                   /* Database page number for frame */
@@ -61125,10 +62401,10 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
 **
 ** The useWal parameter is true to force the use of the WAL and disable
 ** the case where the WAL is bypassed because it has been completely
-** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
-** to make a copy of the wal-index header into pWal->hdr.  If the 
-** wal-index header has changed, *pChanged is set to 1 (as an indication 
-** to the caller that the local page cache is obsolete and needs to be 
+** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
+** to make a copy of the wal-index header into pWal->hdr.  If the
+** wal-index header has changed, *pChanged is set to 1 (as an indication
+** to the caller that the local page cache is obsolete and needs to be
 ** flushed.)  When useWal==1, the wal-index header is assumed to already
 ** be loaded and the pChanged parameter is unused.
 **
@@ -61143,7 +62419,7 @@ static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
 ** bad luck when there is lots of contention for the wal-index, but that
 ** possibility is so small that it can be safely neglected, we believe.
 **
-** On success, this routine obtains a read lock on 
+** On success, this routine obtains a read lock on
 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
 ** that means the Wal does not hold any read lock.  The reader must not
@@ -61181,16 +62457,16 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   **
   ** Circumstances that cause a RETRY should only last for the briefest
   ** instances of time.  No I/O or other system calls are done while the
-  ** locks are held, so the locks should not be held for very long. But 
+  ** locks are held, so the locks should not be held for very long. But
   ** if we are unlucky, another process that is holding a lock might get
-  ** paged out or take a page-fault that is time-consuming to resolve, 
+  ** paged out or take a page-fault that is time-consuming to resolve,
   ** during the few nanoseconds that it is holding the lock.  In that case,
   ** it might take longer than normal for the lock to free.
   **
   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
   ** is more of a scheduler yield than an actual delay.  But on the 10th
-  ** an subsequent retries, the delays start becoming longer and longer, 
+  ** an subsequent retries, the delays start becoming longer and longer,
   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
   ** The total delay time before giving up is less than 10 seconds.
   */
@@ -61221,9 +62497,9 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
       if( pWal->apWiData[0]==0 ){
         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
         ** We assume this is a transient condition, so return WAL_RETRY. The
-        ** xShmMap() implementation used by the default unix and win32 VFS 
-        ** modules may return SQLITE_BUSY due to a race condition in the 
-        ** code that determines whether or not the shared-memory region 
+        ** xShmMap() implementation used by the default unix and win32 VFS
+        ** modules may return SQLITE_BUSY due to a race condition in the
+        ** code that determines whether or not the shared-memory region
         ** must be zeroed before the requested page is returned.
         */
         rc = WAL_RETRY;
@@ -61245,7 +62521,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   assert( pWal->nWiData>0 );
   assert( pWal->apWiData[0]!=0 );
   pInfo = walCkptInfo(pWal);
-  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
+  if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
 #ifdef SQLITE_ENABLE_SNAPSHOT
    && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
 #endif
@@ -61264,7 +62540,7 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
         ** happening, this is usually correct.
         **
-        ** However, if frames have been appended to the log (or if the log 
+        ** However, if frames have been appended to the log (or if the log
         ** is wrapped and written for that matter) before the READ_LOCK(0)
         ** is obtained, that is not necessarily true. A checkpointer may
         ** have started to backfill the appended frames but crashed before
@@ -61307,7 +62583,8 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
     for(i=1; i<WAL_NREADER; i++){
       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
       if( rc==SQLITE_OK ){
-        mxReadMark = AtomicStore(pInfo->aReadMark+i,mxFrame);
+        AtomicStore(pInfo->aReadMark+i,mxFrame);
+        mxReadMark = mxFrame;
         mxI = i;
         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
         break;
@@ -61345,9 +62622,9 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
   ** to read any frames earlier than minFrame from the wal file - they
   ** can be safely read directly from the database file.
   **
-  ** Because a ShmBarrier() call is made between taking the copy of 
+  ** Because a ShmBarrier() call is made between taking the copy of
   ** nBackfill and checking that the wal-header in shared-memory still
-  ** matches the one cached in pWal->hdr, it is guaranteed that the 
+  ** matches the one cached in pWal->hdr, it is guaranteed that the
   ** checkpointer that set nBackfill was not working with a wal-index
   ** header newer than that cached in pWal->hdr. If it were, that could
   ** cause a problem. The checkpointer could omit to checkpoint
@@ -61375,15 +62652,15 @@ static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
 
 #ifdef SQLITE_ENABLE_SNAPSHOT
 /*
-** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted 
+** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
 ** variable so that older snapshots can be accessed. To do this, loop
-** through all wal frames from nBackfillAttempted to (nBackfill+1), 
+** through all wal frames from nBackfillAttempted to (nBackfill+1),
 ** comparing their content to the corresponding page with the database
 ** file, if any. Set nBackfillAttempted to the frame number of the
 ** first frame for which the wal file content matches the db file.
 **
-** This is only really safe if the file-system is such that any page 
-** writes made by earlier checkpointers were atomic operations, which 
+** This is only really safe if the file-system is such that any page
+** writes made by earlier checkpointers were atomic operations, which
 ** is not always true. It is also possible that nBackfillAttempted
 ** may be left set to a value larger than expected, if a wal frame
 ** contains content that duplicate of an earlier version of the same
@@ -61411,7 +62688,7 @@ SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
         rc = SQLITE_NOMEM;
       }else{
         u32 i = pInfo->nBackfillAttempted;
-        for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
+        for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
           WalHashLoc sLoc;          /* Hash table location */
           u32 pgno;                 /* Page number in db file */
           i64 iDbOff;               /* Offset of db file entry */
@@ -61466,12 +62743,35 @@ SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
   int rc;                         /* Return code */
   int cnt = 0;                    /* Number of TryBeginRead attempts */
-
 #ifdef SQLITE_ENABLE_SNAPSHOT
   int bChanged = 0;
   WalIndexHdr *pSnapshot = pWal->pSnapshot;
-  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
-    bChanged = 1;
+#endif
+
+  assert( pWal->ckptLock==0 );
+
+#ifdef SQLITE_ENABLE_SNAPSHOT
+  if( pSnapshot ){
+    if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
+      bChanged = 1;
+    }
+
+    /* It is possible that there is a checkpointer thread running
+    ** concurrent with this code. If this is the case, it may be that the
+    ** checkpointer has already determined that it will checkpoint
+    ** snapshot X, where X is later in the wal file than pSnapshot, but
+    ** has not yet set the pInfo->nBackfillAttempted variable to indicate
+    ** its intent. To avoid the race condition this leads to, ensure that
+    ** there is no checkpointer process by taking a shared CKPT lock
+    ** before checking pInfo->nBackfillAttempted.  */
+    (void)walEnableBlocking(pWal);
+    rc = walLockShared(pWal, WAL_CKPT_LOCK);
+    walDisableBlocking(pWal);
+
+    if( rc!=SQLITE_OK ){
+      return rc;
+    }
+    pWal->ckptLock = 1;
   }
 #endif
 
@@ -61504,48 +62804,42 @@ SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
       assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
       assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
 
-      /* It is possible that there is a checkpointer thread running 
-      ** concurrent with this code. If this is the case, it may be that the
-      ** checkpointer has already determined that it will checkpoint 
-      ** snapshot X, where X is later in the wal file than pSnapshot, but 
-      ** has not yet set the pInfo->nBackfillAttempted variable to indicate 
-      ** its intent. To avoid the race condition this leads to, ensure that
-      ** there is no checkpointer process by taking a shared CKPT lock 
-      ** before checking pInfo->nBackfillAttempted.  
-      **
-      ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
-      **       this already?
-      */
-      rc = walLockShared(pWal, WAL_CKPT_LOCK);
-
-      if( rc==SQLITE_OK ){
-        /* Check that the wal file has not been wrapped. Assuming that it has
-        ** not, also check that no checkpointer has attempted to checkpoint any
-        ** frames beyond pSnapshot->mxFrame. If either of these conditions are
-        ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
-        ** with *pSnapshot and set *pChanged as appropriate for opening the
-        ** snapshot.  */
-        if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
-         && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
-        ){
-          assert( pWal->readLock>0 );
-          memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
-          *pChanged = bChanged;
-        }else{
-          rc = SQLITE_ERROR_SNAPSHOT;
-        }
-
-        /* Release the shared CKPT lock obtained above. */
-        walUnlockShared(pWal, WAL_CKPT_LOCK);
-        pWal->minFrame = 1;
+      /* Check that the wal file has not been wrapped. Assuming that it has
+      ** not, also check that no checkpointer has attempted to checkpoint any
+      ** frames beyond pSnapshot->mxFrame. If either of these conditions are
+      ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
+      ** with *pSnapshot and set *pChanged as appropriate for opening the
+      ** snapshot.  */
+      if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
+       && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
+      ){
+        assert( pWal->readLock>0 );
+        memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
+        *pChanged = bChanged;
+      }else{
+        rc = SQLITE_ERROR_SNAPSHOT;
       }
 
+      /* A client using a non-current snapshot may not ignore any frames
+      ** from the start of the wal file. This is because, for a system
+      ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
+      ** have omitted to checkpoint a frame earlier than minFrame in
+      ** the file because there exists a frame after iSnapshot that
+      ** is the same database page.  */
+      pWal->minFrame = 1;
 
       if( rc!=SQLITE_OK ){
         sqlite3WalEndReadTransaction(pWal);
       }
     }
   }
+
+  /* Release the shared CKPT lock obtained above. */
+  if( pWal->ckptLock ){
+    assert( pSnapshot );
+    walUnlockShared(pWal, WAL_CKPT_LOCK);
+    pWal->ckptLock = 0;
+  }
 #endif
   return rc;
 }
@@ -61585,8 +62879,8 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
 
   /* If the "last page" field of the wal-index header snapshot is 0, then
   ** no data will be read from the wal under any circumstances. Return early
-  ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
-  ** then the WAL is ignored by the reader so return early, as if the 
+  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
+  ** then the WAL is ignored by the reader so return early, as if the
   ** WAL were empty.
   */
   if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
@@ -61599,9 +62893,9 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
   **
   ** This code might run concurrently to the code in walIndexAppend()
-  ** that adds entries to the wal-index (and possibly to this hash 
-  ** table). This means the value just read from the hash 
-  ** slot (aHash[iKey]) may have been added before or after the 
+  ** that adds entries to the wal-index (and possibly to this hash
+  ** table). This means the value just read from the hash
+  ** slot (aHash[iKey]) may have been added before or after the
   ** current read transaction was opened. Values added after the
   ** read transaction was opened may have been written incorrectly -
   ** i.e. these slots may contain garbage data. However, we assume
@@ -61609,13 +62903,13 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
   ** opened remain unmodified.
   **
   ** For the reasons above, the if(...) condition featured in the inner
-  ** loop of the following block is more stringent that would be required 
+  ** loop of the following block is more stringent that would be required
   ** if we had exclusive access to the hash-table:
   **
-  **   (aPgno[iFrame]==pgno): 
+  **   (aPgno[iFrame]==pgno):
   **     This condition filters out normal hash-table collisions.
   **
-  **   (iFrame<=iLast): 
+  **   (iFrame<=iLast):
   **     This condition filters out entries that were added to the hash
   **     table after the current read-transaction had started.
   */
@@ -61625,14 +62919,15 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
     int iKey;                     /* Hash slot index */
     int nCollide;                 /* Number of hash collisions remaining */
     int rc;                       /* Error code */
+    u32 iH;
 
     rc = walHashGet(pWal, iHash, &sLoc);
     if( rc!=SQLITE_OK ){
       return rc;
     }
     nCollide = HASHTABLE_NSLOT;
-    for(iKey=walHash(pgno); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
-      u32 iH = sLoc.aHash[iKey];
+    iKey = walHash(pgno);
+    while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
       u32 iFrame = iH + sLoc.iZero;
       if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){
         assert( iFrame>iRead || CORRUPT_DB );
@@ -61641,6 +62936,7 @@ SQLITE_PRIVATE int sqlite3WalFindFrame(
       if( (nCollide--)==0 ){
         return SQLITE_CORRUPT_BKPT;
       }
+      iKey = walNextHash(iKey);
     }
     if( iRead ) break;
   }
@@ -61689,7 +62985,7 @@ SQLITE_PRIVATE int sqlite3WalReadFrame(
   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
 }
 
-/* 
+/*
 ** Return the size of the database in pages (or zero, if unknown).
 */
 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
@@ -61700,7 +62996,7 @@ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
 }
 
 
-/* 
+/*
 ** This function starts a write transaction on the WAL.
 **
 ** A read transaction must have already been started by a prior call
@@ -61716,6 +63012,16 @@ SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
   int rc;
 
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  /* If the write-lock is already held, then it was obtained before the
+  ** read-transaction was even opened, making this call a no-op.
+  ** Return early. */
+  if( pWal->writeLock ){
+    assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
+    return SQLITE_OK;
+  }
+#endif
+
   /* Cannot start a write transaction without first holding a read
   ** transaction. */
   assert( pWal->readLock>=0 );
@@ -61778,18 +63084,18 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *p
   if( ALWAYS(pWal->writeLock) ){
     Pgno iMax = pWal->hdr.mxFrame;
     Pgno iFrame;
-  
+
     /* Restore the clients cache of the wal-index header to the state it
-    ** was in before the client began writing to the database. 
+    ** was in before the client began writing to the database.
     */
     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
 
-    for(iFrame=pWal->hdr.mxFrame+1; 
-        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
+    for(iFrame=pWal->hdr.mxFrame+1;
+        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
         iFrame++
     ){
       /* This call cannot fail. Unless the page for which the page number
-      ** is passed as the second argument is (a) in the cache and 
+      ** is passed as the second argument is (a) in the cache and
       ** (b) has an outstanding reference, then xUndo is either a no-op
       ** (if (a) is false) or simply expels the page from the cache (if (b)
       ** is false).
@@ -61807,10 +63113,10 @@ SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *p
   return rc;
 }
 
-/* 
-** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
-** values. This function populates the array with values required to 
-** "rollback" the write position of the WAL handle back to the current 
+/*
+** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
+** values. This function populates the array with values required to
+** "rollback" the write position of the WAL handle back to the current
 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
 */
 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
@@ -61821,7 +63127,7 @@ SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
   aWalData[3] = pWal->nCkpt;
 }
 
-/* 
+/*
 ** Move the write position of the WAL back to the point identified by
 ** the values in the aWalData[] array. aWalData must point to an array
 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
@@ -61961,11 +63267,7 @@ static int walWriteOneFrame(
   int rc;                         /* Result code from subfunctions */
   void *pData;                    /* Data actually written */
   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
-#if defined(SQLITE_HAS_CODEC)
-  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
-#else
   pData = pPage->pData;
-#endif
   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
   if( rc ) return rc;
@@ -62027,7 +63329,7 @@ static int walRewriteChecksums(Wal *pWal, u32 iLast){
   return rc;
 }
 
-/* 
+/*
 ** Write a set of frames to the log. The caller must hold the write-lock
 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
 */
@@ -62094,7 +63396,7 @@ SQLITE_PRIVATE int sqlite3WalFrames(
     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
-    
+
     pWal->szPage = szPage;
     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
     pWal->hdr.aFrameCksum[0] = aCksum[0];
@@ -62136,7 +63438,7 @@ SQLITE_PRIVATE int sqlite3WalFrames(
 
     /* Check if this page has already been written into the wal file by
     ** the current transaction. If so, overwrite the existing frame and
-    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that 
+    ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
     ** checksums must be recomputed when the transaction is committed.  */
     if( iFirst && (p->pDirty || isCommit==0) ){
       u32 iWrite = 0;
@@ -62148,11 +63450,7 @@ SQLITE_PRIVATE int sqlite3WalFrames(
         if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
           pWal->iReCksum = iWrite;
         }
-#if defined(SQLITE_HAS_CODEC)
-        if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
-#else
         pData = p->pData;
-#endif
         rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
         if( rc ) return rc;
         p->flags &= ~PGHDR_WAL_APPEND;
@@ -62224,7 +63522,7 @@ SQLITE_PRIVATE int sqlite3WalFrames(
     pWal->truncateOnCommit = 0;
   }
 
-  /* Append data to the wal-index. It is not necessary to lock the 
+  /* Append data to the wal-index. It is not necessary to lock the
   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
   ** guarantees that there are no other writers, and no data that may
   ** be in use by existing readers is being overwritten.
@@ -62263,7 +63561,7 @@ SQLITE_PRIVATE int sqlite3WalFrames(
   return rc;
 }
 
-/* 
+/*
 ** This routine is called to implement sqlite3_wal_checkpoint() and
 ** related interfaces.
 **
@@ -62300,45 +63598,52 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(
   if( pWal->readOnly ) return SQLITE_READONLY;
   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
 
-  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive 
-  ** "checkpoint" lock on the database file. */
-  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
-  if( rc ){
-    /* EVIDENCE-OF: R-10421-19736 If any other process is running a
-    ** checkpoint operation at the same time, the lock cannot be obtained and
-    ** SQLITE_BUSY is returned.
-    ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
-    ** it will not be invoked in this case.
-    */
-    testcase( rc==SQLITE_BUSY );
-    testcase( xBusy!=0 );
-    return rc;
-  }
-  pWal->ckptLock = 1;
+  /* Enable blocking locks, if possible. If blocking locks are successfully
+  ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
+  sqlite3WalDb(pWal, db);
+  (void)walEnableBlocking(pWal);
 
-  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
-  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
-  ** file.
-  **
-  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
-  ** immediately, and a busy-handler is configured, it is invoked and the
-  ** writer lock retried until either the busy-handler returns 0 or the
-  ** lock is successfully obtained.
+  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
+  ** "checkpoint" lock on the database file.
+  ** EVIDENCE-OF: R-10421-19736 If any other process is running a
+  ** checkpoint operation at the same time, the lock cannot be obtained and
+  ** SQLITE_BUSY is returned.
+  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
+  ** it will not be invoked in this case.
   */
-  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
-    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
-    if( rc==SQLITE_OK ){
-      pWal->writeLock = 1;
-    }else if( rc==SQLITE_BUSY ){
-      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
-      xBusy2 = 0;
-      rc = SQLITE_OK;
+  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
+  testcase( rc==SQLITE_BUSY );
+  testcase( rc!=SQLITE_OK && xBusy2!=0 );
+  if( rc==SQLITE_OK ){
+    pWal->ckptLock = 1;
+
+    /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
+    ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
+    ** file.
+    **
+    ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
+    ** immediately, and a busy-handler is configured, it is invoked and the
+    ** writer lock retried until either the busy-handler returns 0 or the
+    ** lock is successfully obtained.
+    */
+    if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
+      rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
+      if( rc==SQLITE_OK ){
+        pWal->writeLock = 1;
+      }else if( rc==SQLITE_BUSY ){
+        eMode2 = SQLITE_CHECKPOINT_PASSIVE;
+        xBusy2 = 0;
+        rc = SQLITE_OK;
+      }
     }
   }
 
+
   /* Read the wal-index header. */
   if( rc==SQLITE_OK ){
+    walDisableBlocking(pWal);
     rc = walIndexReadHdr(pWal, &isChanged);
+    (void)walEnableBlocking(pWal);
     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
     }
@@ -62361,7 +63666,7 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(
   }
 
   if( isChanged ){
-    /* If a new wal-index header was loaded before the checkpoint was 
+    /* If a new wal-index header was loaded before the checkpoint was
     ** performed, then the pager-cache associated with pWal is now
     ** out of date. So zero the cached wal-index header to ensure that
     ** next time the pager opens a snapshot on this database it knows that
@@ -62370,11 +63675,19 @@ SQLITE_PRIVATE int sqlite3WalCheckpoint(
     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
   }
 
+  walDisableBlocking(pWal);
+  sqlite3WalDb(pWal, 0);
+
   /* Release the locks. */
   sqlite3WalEndWriteTransaction(pWal);
-  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
-  pWal->ckptLock = 0;
+  if( pWal->ckptLock ){
+    walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
+    pWal->ckptLock = 0;
+  }
   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
+#endif
   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
 }
 
@@ -62404,7 +63717,7 @@ SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
 ** operation must occur while the pager is still holding the exclusive
 ** lock on the main database file.
 **
-** If op is one, then change from locking_mode=NORMAL into 
+** If op is one, then change from locking_mode=NORMAL into
 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
 ** be released.  Return 1 if the transition is made and 0 if the
 ** WAL is already in exclusive-locking mode - meaning that this
@@ -62421,8 +63734,8 @@ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   assert( pWal->writeLock==0 );
   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
 
-  /* pWal->readLock is usually set, but might be -1 if there was a 
-  ** prior error while attempting to acquire are read-lock. This cannot 
+  /* pWal->readLock is usually set, but might be -1 if there was a
+  ** prior error while attempting to acquire are read-lock. This cannot
   ** happen if the connection is actually in exclusive mode (as no xShmLock
   ** locks are taken in this case). Nor should the pager attempt to
   ** upgrade to exclusive-mode following such an error.
@@ -62453,10 +63766,10 @@ SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
   return rc;
 }
 
-/* 
+/*
 ** Return true if the argument is non-NULL and the WAL module is using
 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
-** WAL module is using shared-memory, return false. 
+** WAL module is using shared-memory, return false.
 */
 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
@@ -62491,11 +63804,14 @@ SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapsho
 
 /* Try to open on pSnapshot when the next read-transaction starts
 */
-SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
+SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
+  Wal *pWal,
+  sqlite3_snapshot *pSnapshot
+){
   pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
 }
 
-/* 
+/*
 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
 */
@@ -62515,7 +63831,7 @@ SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
 /*
 ** The caller currently has a read transaction open on the database.
 ** This function takes a SHARED lock on the CHECKPOINTER slot and then
-** checks if the snapshot passed as the second argument is still 
+** checks if the snapshot passed as the second argument is still
 ** available. If so, SQLITE_OK is returned.
 **
 ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
@@ -62622,16 +63938,16 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
 ** so forth.
 **
-** Finding a particular key requires reading O(log(M)) pages from the 
+** Finding a particular key requires reading O(log(M)) pages from the
 ** disk where M is the number of entries in the tree.
 **
-** In this implementation, a single file can hold one or more separate 
+** In this implementation, a single file can hold one or more separate
 ** BTrees.  Each BTree is identified by the index of its root page.  The
 ** key and data for any entry are combined to form the "payload".  A
 ** fixed amount of payload can be carried directly on the database
 ** page.  If the payload is larger than the preset amount then surplus
 ** bytes are stored on overflow pages.  The payload for an entry
-** and the preceding pointer are combined to form a "Cell".  Each 
+** and the preceding pointer are combined to form a "Cell".  Each
 ** page has a small header which contains the Ptr(N) pointer and other
 ** information such as the size of key and data.
 **
@@ -62761,7 +64077,7 @@ SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
 ** contiguous or in order, but cell pointers are contiguous and in order.
 **
 ** Cell content makes use of variable length integers.  A variable
-** length integer is 1 to 9 bytes where the lower 7 bits of each 
+** length integer is 1 to 9 bytes where the lower 7 bits of each
 ** byte are used.  The integer consists of all bytes that have bit 8 set and
 ** the first byte with bit 8 clear.  The most significant byte of the integer
 ** appears first.  A variable-length integer may not be more than 9 bytes long.
@@ -62834,7 +64150,7 @@ typedef struct CellInfo CellInfo;
 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
 ** header must be exactly 16 bytes including the zero-terminator so
 ** the string itself should be 15 characters long.  If you change
-** the header, then your custom library will not be able to read 
+** the header, then your custom library will not be able to read
 ** databases generated by the standard tools and the standard tools
 ** will not be able to read databases created by your custom library.
 */
@@ -62897,7 +64213,7 @@ struct MemPage {
 
 /*
 ** A linked list of the following structures is stored at BtShared.pLock.
-** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
+** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
 ** is opened on the table with root page BtShared.iTable. Locks are removed
 ** from this list when a transaction is committed or rolled back, or when
 ** a btree handle is closed.
@@ -62921,7 +64237,7 @@ struct BtLock {
 ** see the internals of this structure and only deals with pointers to
 ** this structure.
 **
-** For some database files, the same underlying database cache might be 
+** For some database files, the same underlying database cache might be
 ** shared between multiple connections.  In that case, each connection
 ** has it own instance of this object.  But each instance of this object
 ** points to the same BtShared object.  The database cache and the
@@ -62929,7 +64245,7 @@ struct BtLock {
 ** the BtShared object.
 **
 ** All fields in this structure are accessed under sqlite3.mutex.
-** The pBt pointer itself may not be changed while there exists cursors 
+** The pBt pointer itself may not be changed while there exists cursors
 ** in the referenced BtShared that point back to this Btree since those
 ** cursors have to go through this Btree to find their BtShared and
 ** they often do so without holding sqlite3.mutex.
@@ -62946,6 +64262,9 @@ struct Btree {
   u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
   Btree *pNext;      /* List of other sharable Btrees from the same db */
   Btree *pPrev;      /* Back pointer of the same list */
+#ifdef SQLITE_DEBUG
+  u64 nSeek;         /* Calls to sqlite3BtreeMovetoUnpacked() */
+#endif
 #ifndef SQLITE_OMIT_SHARED_CACHE
   BtLock lock;       /* Object used to lock page 1 */
 #endif
@@ -62957,14 +64276,28 @@ struct Btree {
 ** If the shared-data extension is enabled, there may be multiple users
 ** of the Btree structure. At most one of these may open a write transaction,
 ** but any number may have active read transactions.
+**
+** These values must match SQLITE_TXN_NONE, SQLITE_TXN_READ, and
+** SQLITE_TXN_WRITE
 */
 #define TRANS_NONE  0
 #define TRANS_READ  1
 #define TRANS_WRITE 2
 
+#if TRANS_NONE!=SQLITE_TXN_NONE
+# error wrong numeric code for no-transaction
+#endif
+#if TRANS_READ!=SQLITE_TXN_READ
+# error wrong numeric code for read-transaction
+#endif
+#if TRANS_WRITE!=SQLITE_TXN_WRITE
+# error wrong numeric code for write-transaction
+#endif
+
+
 /*
 ** An instance of this object represents a single database file.
-** 
+**
 ** A single database file can be in use at the same time by two
 ** or more database connections.  When two or more connections are
 ** sharing the same database file, each connection has it own
@@ -62974,7 +64307,7 @@ struct Btree {
 **
 ** Fields in this structure are accessed under the BtShared.mutex
 ** mutex, except for nRef and pNext which are accessed under the
-** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
+** global SQLITE_MUTEX_STATIC_MAIN mutex.  The pPager field
 ** may not be modified once it is initially set as long as nRef>0.
 ** The pSchema field may be set once under BtShared.mutex and
 ** thereafter is unchanged as long as nRef>0.
@@ -63010,9 +64343,7 @@ struct BtShared {
 #endif
   u8 inTransaction;     /* Transaction state */
   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
-#ifdef SQLITE_HAS_CODEC
-  u8 optimalReserve;    /* Desired amount of reserved space per page */
-#endif
+  u8 nReserveWanted;    /* Desired number of extra bytes per page */
   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
@@ -63084,7 +64415,7 @@ struct CellInfo {
 ** particular database connection identified BtCursor.pBtree.db.
 **
 ** Fields in this structure are accessed under the BtShared.mutex
-** found at self->pBt->mutex. 
+** found at self->pBt->mutex.
 **
 ** skipNext meaning:
 ** The meaning of skipNext depends on the value of eState:
@@ -63135,12 +64466,13 @@ struct BtCursor {
 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
 #define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
+#define BTCF_Pinned       0x40   /* Cursor is busy and cannot be moved */
 
 /*
 ** Potential values for BtCursor.eState.
 **
 ** CURSOR_INVALID:
-**   Cursor does not point to a valid entry. This can happen (for example) 
+**   Cursor does not point to a valid entry. This can happen (for example)
 **   because the table is empty or because BtreeCursorFirst() has not been
 **   called.
 **
@@ -63153,9 +64485,9 @@ struct BtCursor {
 **   operation should be a no-op.
 **
 ** CURSOR_REQUIRESEEK:
-**   The table that this cursor was opened on still exists, but has been 
+**   The table that this cursor was opened on still exists, but has been
 **   modified since the cursor was last used. The cursor position is saved
-**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
+**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
 **   this state, restoreCursorPosition() can be called to attempt to
 **   seek the cursor to the saved position.
 **
@@ -63172,13 +64504,13 @@ struct BtCursor {
 #define CURSOR_REQUIRESEEK       3
 #define CURSOR_FAULT             4
 
-/* 
+/*
 ** The database page the PENDING_BYTE occupies. This page is never used.
 */
 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
 
 /*
-** These macros define the location of the pointer-map entry for a 
+** These macros define the location of the pointer-map entry for a
 ** database page. The first argument to each is the number of usable
 ** bytes on each page of the database (often 1024). The second is the
 ** page number to look up in the pointer map.
@@ -63213,10 +64545,10 @@ struct BtCursor {
 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
 **                  used in this case.
 **
-** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
+** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
 **                  is not used in this case.
 **
-** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
+** PTRMAP_OVERFLOW1: The database page is the first page in a list of
 **                   overflow pages. The page number identifies the page that
 **                   contains the cell with a pointer to this overflow page.
 **
@@ -63238,13 +64570,13 @@ struct BtCursor {
 */
 #define btreeIntegrity(p) \
   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
-  assert( p->pBt->inTransaction>=p->inTrans ); 
+  assert( p->pBt->inTransaction>=p->inTrans );
 
 
 /*
 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
 ** if the database supports auto-vacuum or not. Because it is used
-** within an expression that is an argument to another macro 
+** within an expression that is an argument to another macro
 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
 ** So, this macro is defined instead.
 */
@@ -63261,8 +64593,8 @@ struct BtCursor {
 **
 ** The aRef[] array is allocated so that there is 1 bit for each page in
 ** the database. As the integrity-check proceeds, for each page used in
-** the database the corresponding bit is set. This allows integrity-check to 
-** detect pages that are used twice and orphaned pages (both of which 
+** the database the corresponding bit is set. This allows integrity-check to
+** detect pages that are used twice and orphaned pages (both of which
 ** indicate corruption).
 */
 typedef struct IntegrityCk IntegrityCk;
@@ -63273,11 +64605,13 @@ struct IntegrityCk {
   Pgno nPage;       /* Number of pages in the database */
   int mxErr;        /* Stop accumulating errors when this reaches zero */
   int nErr;         /* Number of messages written to zErrMsg so far */
-  int mallocFailed; /* A memory allocation error has occurred */
+  int bOomFault;    /* A memory allocation error has occurred */
   const char *zPfx; /* Error message prefix */
-  int v1, v2;       /* Values for up to two %d fields in zPfx */
+  Pgno v1;          /* Value for first %u substitution in zPfx */
+  int v2;           /* Value for second %d substitution in zPfx */
   StrAccum errMsg;  /* Accumulate the error message text here */
   u32 *heap;        /* Min-heap used for analyzing cell coverage */
+  sqlite3 *db;      /* Database connection running the check */
 };
 
 /*
@@ -63578,10 +64912,10 @@ SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
 
 #ifndef SQLITE_OMIT_INCRBLOB
 /*
-** Enter a mutex on a Btree given a cursor owned by that Btree. 
+** Enter a mutex on a Btree given a cursor owned by that Btree.
 **
-** These entry points are used by incremental I/O only. Enter() is required 
-** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not 
+** These entry points are used by incremental I/O only. Enter() is required
+** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
 ** the build is threadsafe. Leave() is only required by threadsafe builds.
 */
 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
@@ -63651,7 +64985,7 @@ int sqlite3BtreeTrace=1;  /* True to enable tracing */
 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
 
 /*
-** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
+** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
 ** defined, or 0 if it is. For example:
 **
 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
@@ -63666,10 +65000,10 @@ int sqlite3BtreeTrace=1;  /* True to enable tracing */
 /*
 ** A list of BtShared objects that are eligible for participation
 ** in shared cache.  This variable has file scope during normal builds,
-** but the test harness needs to access it so we make it global for 
+** but the test harness needs to access it so we make it global for
 ** test builds.
 **
-** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
+** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
 */
 #ifdef SQLITE_TEST
 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
@@ -63701,7 +65035,7 @@ SQLITE_API int sqlite3_enable_shared_cache(int enable){
   ** manipulate entries in the BtShared.pLock linked list used to store
   ** shared-cache table level locks. If the library is compiled with the
   ** shared-cache feature disabled, then there is only ever one user
-  ** of each BtShared structure and so this locking is not necessary. 
+  ** of each BtShared structure and so this locking is not necessary.
   ** So define the lock related functions as no-ops.
   */
   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
@@ -63712,6 +65046,17 @@ SQLITE_API int sqlite3_enable_shared_cache(int enable){
   #define hasReadConflicts(a, b) 0
 #endif
 
+#ifdef SQLITE_DEBUG
+/*
+** Return and reset the seek counter for a Btree object.
+*/
+SQLITE_PRIVATE sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
+  u64 n =  pBt->nSeek;
+  pBt->nSeek = 0;
+  return n;
+}
+#endif
+
 /*
 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
@@ -63746,15 +65091,15 @@ int corruptPageError(int lineno, MemPage *p){
 /*
 **** This function is only used as part of an assert() statement. ***
 **
-** Check to see if pBtree holds the required locks to read or write to the 
+** Check to see if pBtree holds the required locks to read or write to the
 ** table with root page iRoot.   Return 1 if it does and 0 if not.
 **
-** For example, when writing to a table with root-page iRoot via 
+** For example, when writing to a table with root-page iRoot via
 ** Btree connection pBtree:
 **
 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
 **
-** When writing to an index that resides in a sharable database, the 
+** When writing to an index that resides in a sharable database, the
 ** caller should have first obtained a lock specifying the root page of
 ** the corresponding table. This makes things a bit more complicated,
 ** as this module treats each table as a separate structure. To determine
@@ -63776,7 +65121,7 @@ static int hasSharedCacheTableLock(
   BtLock *pLock;
 
   /* If this database is not shareable, or if the client is reading
-  ** and has the read-uncommitted flag set, then no lock is required. 
+  ** and has the read-uncommitted flag set, then no lock is required.
   ** Return true immediately.
   */
   if( (pBtree->sharable==0)
@@ -63800,29 +65145,31 @@ static int hasSharedCacheTableLock(
   ** table.  */
   if( isIndex ){
     HashElem *p;
+    int bSeen = 0;
     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
       Index *pIdx = (Index *)sqliteHashData(p);
       if( pIdx->tnum==(int)iRoot ){
-        if( iTab ){
+        if( bSeen ){
           /* Two or more indexes share the same root page.  There must
           ** be imposter tables.  So just return true.  The assert is not
           ** useful in that case. */
           return 1;
         }
         iTab = pIdx->pTable->tnum;
+        bSeen = 1;
       }
     }
   }else{
     iTab = iRoot;
   }
 
-  /* Search for the required lock. Either a write-lock on root-page iTab, a 
+  /* Search for the required lock. Either a write-lock on root-page iTab, a
   ** write-lock on the schema table, or (if the client is reading) a
   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
-    if( pLock->pBtree==pBtree 
+    if( pLock->pBtree==pBtree
      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
-     && pLock->eLock>=eLockType 
+     && pLock->eLock>=eLockType
     ){
       return 1;
     }
@@ -63855,7 +65202,7 @@ static int hasSharedCacheTableLock(
 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
   BtCursor *p;
   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
-    if( p->pgnoRoot==iRoot 
+    if( p->pgnoRoot==iRoot
      && p->pBtree!=pBtree
      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
     ){
@@ -63867,7 +65214,7 @@ static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
 #endif    /* #ifdef SQLITE_DEBUG */
 
 /*
-** Query to see if Btree handle p may obtain a lock of type eLock 
+** Query to see if Btree handle p may obtain a lock of type eLock
 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
 ** SQLITE_OK if the lock may be obtained (by calling
 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
@@ -63880,14 +65227,14 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
   assert( p->db!=0 );
   assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
-  
+
   /* If requesting a write-lock, then the Btree must have an open write
-  ** transaction on this file. And, obviously, for this to be so there 
+  ** transaction on this file. And, obviously, for this to be so there
   ** must be an open write transaction on the file itself.
   */
   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
-  
+
   /* This routine is a no-op if the shared-cache is not enabled */
   if( !p->sharable ){
     return SQLITE_OK;
@@ -63902,7 +65249,7 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
   }
 
   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
-    /* The condition (pIter->eLock!=eLock) in the following if(...) 
+    /* The condition (pIter->eLock!=eLock) in the following if(...)
     ** statement is a simplification of:
     **
     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
@@ -63929,7 +65276,7 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
 #ifndef SQLITE_OMIT_SHARED_CACHE
 /*
 ** Add a lock on the table with root-page iTable to the shared-btree used
-** by Btree handle p. Parameter eLock must be either READ_LOCK or 
+** by Btree handle p. Parameter eLock must be either READ_LOCK or
 ** WRITE_LOCK.
 **
 ** This function assumes the following:
@@ -63941,7 +65288,7 @@ static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
 **       with the requested lock (i.e. querySharedCacheTableLock() has
 **       already been called and returned SQLITE_OK).
 **
-** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
+** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
 ** is returned if a malloc attempt fails.
 */
 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
@@ -63955,11 +65302,11 @@ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
 
   /* A connection with the read-uncommitted flag set will never try to
   ** obtain a read-lock using this function. The only read-lock obtained
-  ** by a connection in read-uncommitted mode is on the sqlite_master 
+  ** by a connection in read-uncommitted mode is on the sqlite_schema
   ** table, and that lock is obtained in BtreeBeginTrans().  */
   assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
 
-  /* This function should only be called on a sharable b-tree after it 
+  /* This function should only be called on a sharable b-tree after it
   ** has been determined that no other b-tree holds a conflicting lock.  */
   assert( p->sharable );
   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
@@ -64004,7 +65351,7 @@ static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
 ** Release all the table locks (locks obtained via calls to
 ** the setSharedCacheTableLock() procedure) held by Btree object p.
 **
-** This function assumes that Btree p has an open read or write 
+** This function assumes that Btree p has an open read or write
 ** transaction. If it does not, then the BTS_PENDING flag
 ** may be incorrectly cleared.
 */
@@ -64036,7 +65383,7 @@ static void clearAllSharedCacheTableLocks(Btree *p){
     pBt->pWriter = 0;
     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
   }else if( pBt->nTransaction==2 ){
-    /* This function is called when Btree p is concluding its 
+    /* This function is called when Btree p is concluding its
     ** transaction. If there currently exists a writer, and p is not
     ** that writer, then the number of locks held by connections other
     ** than the writer must be about to drop to zero. In this case
@@ -64082,7 +65429,7 @@ static int cursorHoldsMutex(BtCursor *p){
 }
 
 /* Verify that the cursor and the BtShared agree about what is the current
-** database connetion. This is important in shared-cache mode. If the database 
+** database connetion. This is important in shared-cache mode. If the database
 ** connection pointers get out-of-sync, it is possible for routines like
 ** btreeInitPage() to reference an stale connection pointer that references a
 ** a connection that has already closed.  This routine is used inside assert()
@@ -64153,8 +65500,8 @@ static void invalidateIncrblobCursors(
 #endif /* SQLITE_OMIT_INCRBLOB */
 
 /*
-** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
-** when a page that previously contained data becomes a free-list leaf 
+** Set bit pgno of the BtShared.pHasContent bitvec. This is called
+** when a page that previously contained data becomes a free-list leaf
 ** page.
 **
 ** The BtShared.pHasContent bitvec exists to work around an obscure
@@ -64180,7 +65527,7 @@ static void invalidateIncrblobCursors(
 ** may be lost. In the event of a rollback, it may not be possible
 ** to restore the database to its original configuration.
 **
-** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
+** The solution is the BtShared.pHasContent bitvec. Whenever a page is
 ** moved to become a free-list leaf page, the corresponding bit is
 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
 ** optimization 2 above is omitted if the corresponding bit is already
@@ -64211,7 +65558,7 @@ static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
 */
 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
   Bitvec *p = pBt->pHasContent;
-  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
+  return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
 }
 
 /*
@@ -64241,13 +65588,13 @@ static void btreeReleaseAllCursorPages(BtCursor *pCur){
 ** The cursor passed as the only argument must point to a valid entry
 ** when this function is called (i.e. have eState==CURSOR_VALID). This
 ** function saves the current cursor key in variables pCur->nKey and
-** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 
+** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
 ** code otherwise.
 **
 ** If the cursor is open on an intkey table, then the integer key
 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
-** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 
-** set to point to a malloced buffer pCur->nKey bytes in size containing 
+** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
+** set to point to a malloced buffer pCur->nKey bytes in size containing
 ** the key.
 */
 static int saveCursorKey(BtCursor *pCur){
@@ -64263,8 +65610,8 @@ static int saveCursorKey(BtCursor *pCur){
     /* For an index btree, save the complete key content. It is possible
     ** that the current key is corrupt. In that case, it is possible that
     ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
-    ** up to the size of 1 varint plus 1 8-byte value when the cursor 
-    ** position is restored. Hence the 17 bytes of padding allocated 
+    ** up to the size of 1 varint plus 1 8-byte value when the cursor
+    ** position is restored. Hence the 17 bytes of padding allocated
     ** below. */
     void *pKey;
     pCur->nKey = sqlite3BtreePayloadSize(pCur);
@@ -64286,11 +65633,11 @@ static int saveCursorKey(BtCursor *pCur){
 }
 
 /*
-** Save the current cursor position in the variables BtCursor.nKey 
+** Save the current cursor position in the variables BtCursor.nKey
 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
 **
 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
-** prior to calling this routine.  
+** prior to calling this routine.
 */
 static int saveCursorPosition(BtCursor *pCur){
   int rc;
@@ -64299,6 +65646,9 @@ static int saveCursorPosition(BtCursor *pCur){
   assert( 0==pCur->pKey );
   assert( cursorHoldsMutex(pCur) );
 
+  if( pCur->curFlags & BTCF_Pinned ){
+    return SQLITE_CONSTRAINT_PINNED;
+  }
   if( pCur->eState==CURSOR_SKIPNEXT ){
     pCur->eState = CURSOR_VALID;
   }else{
@@ -64326,7 +65676,7 @@ static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
 ** routine is called just before cursor pExcept is used to modify the
 ** table, for example in BtreeDelete() or BtreeInsert().
 **
-** If there are two or more cursors on the same btree, then all such 
+** If there are two or more cursors on the same btree, then all such
 ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
 ** routine enforces that rule.  This routine only needs to be called in
 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
@@ -64426,9 +65776,9 @@ moveto_done:
 
 /*
 ** Restore the cursor to the position it was in (or as close to as possible)
-** when saveCursorPosition() was called. Note that this call deletes the 
+** when saveCursorPosition() was called. Note that this call deletes the
 ** saved position info stored by saveCursorPosition(), so there can be
-** at most one effective restoreCursorPosition() call after each 
+** at most one effective restoreCursorPosition() call after each
 ** saveCursorPosition().
 */
 static int btreeRestoreCursorPosition(BtCursor *pCur){
@@ -64496,7 +65846,7 @@ SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
 /*
 ** This routine restores a cursor back to its original position after it
 ** has been moved by some outside activity (such as a btree rebalance or
-** a row having been deleted out from under the cursor).  
+** a row having been deleted out from under the cursor).
 **
 ** On success, the *pDifferentRow parameter is false if the cursor is left
 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
@@ -64561,7 +65911,7 @@ static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
   if( pgno<2 ) return 0;
   nPagesPerMapPage = (pBt->usableSize/5)+1;
   iPtrMap = (pgno-2)/nPagesPerMapPage;
-  ret = (iPtrMap*nPagesPerMapPage) + 2; 
+  ret = (iPtrMap*nPagesPerMapPage) + 2;
   if( ret==PENDING_BYTE_PAGE(pBt) ){
     ret++;
   }
@@ -64588,7 +65938,7 @@ static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
   if( *pRC ) return;
 
   assert( sqlite3_mutex_held(pBt->mutex) );
-  /* The master-journal page number must never be used as a pointer map page */
+  /* The super-journal page number must never be used as a pointer map page */
   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
 
   assert( pBt->autoVacuum );
@@ -64907,7 +66257,7 @@ static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
   }
   pIter++;
   if( pPage->intKey ){
-    /* pIter now points at the 64-bit integer key value, a variable length 
+    /* pIter now points at the 64-bit integer key value, a variable length
     ** integer. The following block moves pIter to point at the first byte
     ** past the end of the key value. */
     pEnd = &pIter[9];
@@ -65032,7 +66382,7 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){
   /* This block handles pages with two or fewer free blocks and nMaxFrag
   ** or fewer fragmented bytes. In this case it is faster to move the
   ** two (or one) blocks of cells using memmove() and add the required
-  ** offsets to each pointer in the cell-pointer array than it is to 
+  ** offsets to each pointer in the cell-pointer array than it is to
   ** reconstruct the entire page.  */
   if( (int)data[hdr+7]<=nMaxFrag ){
     int iFree = get2byte(&data[hdr+1]);
@@ -65055,7 +66405,7 @@ static int defragmentPage(MemPage *pPage, int nMaxFrag){
           if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
           memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
           sz += sz2;
-        }else if( iFree+sz>usableSize ){
+        }else if( NEVER(iFree+sz>usableSize) ){
           return SQLITE_CORRUPT_PAGE(pPage);
         }
 
@@ -65210,7 +66560,7 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   int top;                             /* First byte of cell content area */
   int rc = SQLITE_OK;                  /* Integer return code */
   int gap;        /* First byte of gap between cell pointers and cell content */
-  
+
   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
   assert( pPage->pBt );
   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
@@ -65247,8 +66597,10 @@ static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
     if( pSpace ){
+      int g2;
       assert( pSpace+nByte<=data+pPage->pBt->usableSize );
-      if( (*pIdx = (int)(pSpace-data))<=gap ){
+      *pIdx = g2 = (int)(pSpace-data);
+      if( NEVER(g2<=gap) ){
         return SQLITE_CORRUPT_PAGE(pPage);
       }else{
         return SQLITE_OK;
@@ -65316,7 +66668,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
   assert( iSize>=4 );   /* Minimum cell size is 4 */
   assert( iStart<=pPage->pBt->usableSize-4 );
 
-  /* The list of freeblocks must be in ascending order.  Find the 
+  /* The list of freeblocks must be in ascending order.  Find the
   ** spot on the list where iStart should be inserted.
   */
   hdr = pPage->hdrOffset;
@@ -65326,16 +66678,16 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
   }else{
     while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
       if( iFreeBlk<iPtr+4 ){
-        if( iFreeBlk==0 ) break;
+        if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
         return SQLITE_CORRUPT_PAGE(pPage);
       }
       iPtr = iFreeBlk;
     }
-    if( iFreeBlk>pPage->pBt->usableSize-4 ){
+    if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
       return SQLITE_CORRUPT_PAGE(pPage);
     }
     assert( iFreeBlk>iPtr || iFreeBlk==0 );
-  
+
     /* At this point:
     **    iFreeBlk:   First freeblock after iStart, or zero if none
     **    iPtr:       The address of a pointer to iFreeBlk
@@ -65352,7 +66704,7 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
       iSize = iEnd - iStart;
       iFreeBlk = get2byte(&data[iFreeBlk]);
     }
-  
+
     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
     ** pointer in the page header) then check to see if iStart should be
     ** coalesced onto the end of iPtr.
@@ -65374,7 +66726,8 @@ static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
     /* The new freeblock is at the beginning of the cell content area,
     ** so just extend the cell content area rather than create another
     ** freelist entry */
-    if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
+    if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
+    if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
     put2byte(&data[hdr+1], iFreeBlk);
     put2byte(&data[hdr+5], iEnd);
   }else{
@@ -65494,11 +66847,11 @@ static int btreeComputeFreeSpace(MemPage *pPage){
   nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
   if( pc>0 ){
     u32 next, size;
-    if( pc<iCellFirst ){
+    if( pc<top ){
       /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
       ** always be at least one cell before the first freeblock.
       */
-      return SQLITE_CORRUPT_PAGE(pPage); 
+      return SQLITE_CORRUPT_PAGE(pPage);
     }
     while( 1 ){
       if( pc>iCellLast ){
@@ -65537,7 +66890,7 @@ static int btreeComputeFreeSpace(MemPage *pPage){
 
 /*
 ** Do additional sanity check after btreeInitPage() if
-** PRAGMA cell_size_check=ON 
+** PRAGMA cell_size_check=ON
 */
 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
   int iCellFirst;    /* First allowable cell or freeblock offset */
@@ -65575,7 +66928,7 @@ static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
 ** Initialize the auxiliary information for a disk block.
 **
 ** Return SQLITE_OK on success.  If we see that the page does
-** not contain a well-formed database page, then return 
+** not contain a well-formed database page, then return
 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
 ** guarantee that the page is well-formed.  It only shows that
 ** we failed to detect any corruption.
@@ -65680,7 +67033,7 @@ static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
     pPage->hdrOffset = pgno==1 ? 100 : 0;
   }
   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
-  return pPage; 
+  return pPage;
 }
 
 /*
@@ -65733,9 +67086,8 @@ static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
 static Pgno btreePagecount(BtShared *pBt){
   return pBt->nPage;
 }
-SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
+SQLITE_PRIVATE Pgno sqlite3BtreeLastPage(Btree *p){
   assert( sqlite3BtreeHoldsMutex(p) );
-  assert( ((p->pBt->nPage)&0x80000000)==0 );
   return btreePagecount(p->pBt);
 }
 
@@ -65898,17 +67250,16 @@ static int btreeInvokeBusyHandler(void *pArg){
   BtShared *pBt = (BtShared*)pArg;
   assert( pBt->db );
   assert( sqlite3_mutex_held(pBt->db->mutex) );
-  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
-                                  sqlite3PagerFile(pBt->pPager));
+  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
 }
 
 /*
 ** Open a database file.
-** 
+**
 ** zFilename is the name of the database file.  If zFilename is NULL
 ** then an ephemeral database is created.  The ephemeral database might
 ** be exclusively in memory, or it might use a disk-based memory cache.
-** Either way, the ephemeral database will be automatically deleted 
+** Either way, the ephemeral database will be automatically deleted
 ** when sqlite3BtreeClose() is called.
 **
 ** If zFilename is ":memory:" then an in-memory database is created
@@ -65941,7 +67292,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen(
   /* True if opening an ephemeral, temporary database */
   const int isTempDb = zFilename==0 || zFilename[0]==0;
 
-  /* Set the variable isMemdb to true for an in-memory database, or 
+  /* Set the variable isMemdb to true for an in-memory database, or
   ** false for a file-based database.
   */
 #ifdef SQLITE_OMIT_MEMORYDB
@@ -66003,15 +67354,19 @@ SQLITE_PRIVATE int sqlite3BtreeOpen(
         rc = sqlite3OsFullPathname(pVfs, zFilename,
                                    nFullPathname, zFullPathname);
         if( rc ){
-          sqlite3_free(zFullPathname);
-          sqlite3_free(p);
-          return rc;
+          if( rc==SQLITE_OK_SYMLINK ){
+            rc = SQLITE_OK;
+          }else{
+            sqlite3_free(zFullPathname);
+            sqlite3_free(p);
+            return rc;
+          }
         }
       }
 #if SQLITE_THREADSAFE
       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
       sqlite3_mutex_enter(mutexOpen);
-      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
       sqlite3_mutex_enter(mutexShared);
 #endif
       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
@@ -66060,7 +67415,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen(
     assert( sizeof(u32)==4 );
     assert( sizeof(u16)==2 );
     assert( sizeof(Pgno)==4 );
-  
+
     pBt = sqlite3MallocZero( sizeof(*pBt) );
     if( pBt==0 ){
       rc = SQLITE_NOMEM_BKPT;
@@ -66079,7 +67434,7 @@ SQLITE_PRIVATE int sqlite3BtreeOpen(
     pBt->db = db;
     sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
     p->pBt = pBt;
-  
+
     pBt->pCursor = 0;
     pBt->pPage1 = 0;
     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
@@ -66123,14 +67478,14 @@ SQLITE_PRIVATE int sqlite3BtreeOpen(
     if( rc ) goto btree_open_out;
     pBt->usableSize = pBt->pageSize - nReserve;
     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
-   
+
 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
     /* Add the new BtShared object to the linked list sharable BtShareds.
     */
     pBt->nRef = 1;
     if( p->sharable ){
       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
-      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
+      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
         if( pBt->mutex==0 ){
@@ -66195,7 +67550,7 @@ btree_open_out:
     ** do not change the pager-cache size.
     */
     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
-      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
+      sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
     }
 
     pFile = sqlite3PagerFile(pBt->pPager);
@@ -66219,13 +67574,13 @@ btree_open_out:
 */
 static int removeFromSharingList(BtShared *pBt){
 #ifndef SQLITE_OMIT_SHARED_CACHE
-  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
+  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
   BtShared *pList;
   int removed = 0;
 
   assert( sqlite3_mutex_notheld(pBt->mutex) );
-  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
-  sqlite3_mutex_enter(pMaster);
+  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+  sqlite3_mutex_enter(pMainMtx);
   pBt->nRef--;
   if( pBt->nRef<=0 ){
     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
@@ -66244,7 +67599,7 @@ static int removeFromSharingList(BtShared *pBt){
     }
     removed = 1;
   }
-  sqlite3_mutex_leave(pMaster);
+  sqlite3_mutex_leave(pMainMtx);
   return removed;
 #else
   return 1;
@@ -66252,7 +67607,7 @@ static int removeFromSharingList(BtShared *pBt){
 }
 
 /*
-** Make sure pBt->pTmpSpace points to an allocation of 
+** Make sure pBt->pTmpSpace points to an allocation of
 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
 ** pointer.
 */
@@ -66267,7 +67622,7 @@ static void allocateTempSpace(BtShared *pBt){
     ** can mean that fillInCell() only initializes the first 2 or 3
     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
     ** it into a database page. This is not actually a problem, but it
-    ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
+    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
     ** data is passed to system call write(). So to avoid this error,
     ** zero the first 4 bytes of temp space here.
     **
@@ -66320,7 +67675,7 @@ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
   sqlite3BtreeLeave(p);
 
   /* If there are still other outstanding references to the shared-btree
-  ** structure, return now. The remainder of this procedure cleans 
+  ** structure, return now. The remainder of this procedure cleans
   ** up the shared-btree.
   */
   assert( p->wantToLock==0 && p->locked==0 );
@@ -66426,7 +67781,7 @@ SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
 
 /*
 ** Change the default pages size and the number of reserved bytes per page.
-** Or, if the page size has already been fixed, return SQLITE_READONLY 
+** Or, if the page size has already been fixed, return SQLITE_READONLY
 ** without changing anything.
 **
 ** The page size must be a power of 2 between 512 and 65536.  If the page
@@ -66446,19 +67801,17 @@ SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
 */
 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
   int rc = SQLITE_OK;
+  int x;
   BtShared *pBt = p->pBt;
-  assert( nReserve>=-1 && nReserve<=255 );
+  assert( nReserve>=0 && nReserve<=255 );
   sqlite3BtreeEnter(p);
-#if SQLITE_HAS_CODEC
-  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
-#endif
+  pBt->nReserveWanted = nReserve;
+  x = pBt->pageSize - pBt->usableSize;
+  if( nReserve<x ) nReserve = x;
   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
     sqlite3BtreeLeave(p);
     return SQLITE_READONLY;
   }
-  if( nReserve<0 ){
-    nReserve = pBt->pageSize - pBt->usableSize;
-  }
   assert( nReserve>=0 && nReserve<=255 );
   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
         ((pageSize-1)&pageSize)==0 ){
@@ -66487,7 +67840,7 @@ SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
 ** held.
 **
 ** This is useful in one special case in the backup API code where it is
-** known that the shared b-tree mutex is held, but the mutex on the 
+** known that the shared b-tree mutex is held, but the mutex on the
 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
 ** were to be called, it might collide with some other operation on the
 ** database handle that owns *p, causing undefined behavior.
@@ -66504,19 +67857,17 @@ SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
 ** are intentually left unused.  This is the "reserved" space that is
 ** sometimes used by extensions.
 **
-** If SQLITE_HAS_MUTEX is defined then the number returned is the
-** greater of the current reserved space and the maximum requested
-** reserve space.
+** The value returned is the larger of the current reserve size and
+** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
+** The amount of reserve can only grow - never shrink.
 */
-SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
-  int n;
+SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){
+  int n1, n2;
   sqlite3BtreeEnter(p);
-  n = sqlite3BtreeGetReserveNoMutex(p);
-#ifdef SQLITE_HAS_CODEC
-  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
-#endif
+  n1 = (int)p->pBt->nReserveWanted;
+  n2 = sqlite3BtreeGetReserveNoMutex(p);
   sqlite3BtreeLeave(p);
-  return n;
+  return n1>n2 ? n1 : n2;
 }
 
 
@@ -66525,8 +67876,8 @@ SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
 ** No changes are made if mxPage is 0 or negative.
 ** Regardless of the value of mxPage, return the maximum page count.
 */
-SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
-  int n;
+SQLITE_PRIVATE Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
+  Pgno n;
   sqlite3BtreeEnter(p);
   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
   sqlite3BtreeLeave(p);
@@ -66569,7 +67920,7 @@ SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
 /*
 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
-** is disabled. The default value for the auto-vacuum property is 
+** is disabled. The default value for the auto-vacuum property is
 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
 */
 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
@@ -66593,7 +67944,7 @@ SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
 }
 
 /*
-** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
+** Return the value of the 'auto-vacuum' property. If auto-vacuum is
 ** enabled 1 is returned. Otherwise 0.
 */
 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
@@ -66625,9 +67976,9 @@ static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
   Db *pDb;
   if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
     while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
-    if( pDb->bSyncSet==0 
-     && pDb->safety_level!=safety_level 
-     && pDb!=&db->aDb[1] 
+    if( pDb->bSyncSet==0
+     && pDb->safety_level!=safety_level
+     && pDb!=&db->aDb[1]
     ){
       pDb->safety_level = safety_level;
       sqlite3PagerSetFlags(pBt->pPager,
@@ -66650,7 +68001,7 @@ static int newDatabase(BtShared*);
 ** SQLITE_OK is returned on success.  If the file is not a
 ** well-formed database file, then SQLITE_CORRUPT is returned.
 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
-** is returned if we run out of memory. 
+** is returned if we run out of memory.
 */
 static int lockBtree(BtShared *pBt){
   int rc;              /* Result code from subfunctions */
@@ -66667,7 +68018,7 @@ static int lockBtree(BtShared *pBt){
   if( rc!=SQLITE_OK ) return rc;
 
   /* Do some checking to help insure the file we opened really is
-  ** a valid database file. 
+  ** a valid database file.
   */
   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
   sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
@@ -66705,7 +68056,7 @@ static int lockBtree(BtShared *pBt){
     }
 
     /* If the write version is set to 2, this database should be accessed
-    ** in WAL mode. If the log is not already open, open it now. Then 
+    ** in WAL mode. If the log is not already open, open it now. Then
     ** return SQLITE_OK and return without populating BtShared.pPage1.
     ** The caller detects this and calls this function again. This is
     ** required as the version of page 1 currently in the page1 buffer
@@ -66746,8 +68097,8 @@ static int lockBtree(BtShared *pBt){
     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
     ** between 512 and 65536 inclusive. */
     if( ((pageSize-1)&pageSize)!=0
-     || pageSize>SQLITE_MAX_PAGE_SIZE 
-     || pageSize<=256 
+     || pageSize>SQLITE_MAX_PAGE_SIZE
+     || pageSize<=256
     ){
       goto page1_init_failed;
     }
@@ -66755,7 +68106,7 @@ static int lockBtree(BtShared *pBt){
     assert( (pageSize & 7)==0 );
     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
     ** integer at offset 20 is the number of bytes of space at the end of
-    ** each page to reserve for extensions. 
+    ** each page to reserve for extensions.
     **
     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
     ** determined by the one-byte unsigned integer found at an offset of 20
@@ -66845,7 +68196,7 @@ static int countValidCursors(BtShared *pBt, int wrOnly){
   int r = 0;
   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
-     && pCur->eState!=CURSOR_FAULT ) r++; 
+     && pCur->eState!=CURSOR_FAULT ) r++;
   }
   return r;
 }
@@ -66854,7 +68205,7 @@ static int countValidCursors(BtShared *pBt, int wrOnly){
 /*
 ** If there are no outstanding cursors and we are not in the middle
 ** of a transaction but there is a read lock on the database, then
-** this routine unrefs the first page of the database file which 
+** this routine unrefs the first page of the database file which
 ** has the effect of releasing the read lock.
 **
 ** If there is a transaction in progress, this routine is a no-op.
@@ -66938,8 +68289,8 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 ** upgraded to exclusive by calling this routine a second time - the
 ** exclusivity flag only works for a new transaction.
 **
-** A write-transaction must be started before attempting any 
-** changes to the database.  None of the following routines 
+** A write-transaction must be started before attempting any
+** changes to the database.  None of the following routines
 ** will work unless a transaction is started first:
 **
 **      sqlite3BtreeCreateTable()
@@ -66953,7 +68304,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 ** If an initial attempt to acquire the lock fails because of lock contention
 ** and the database was previously unlocked, then invoke the busy handler
 ** if there is one.  But if there was previously a read-lock, do not
-** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
+** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
 ** returned when there is already a read-lock in order to avoid a deadlock.
 **
 ** Suppose there are two processes A and B.  A has a read lock and B has
@@ -66966,6 +68317,7 @@ SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
 */
 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
   BtShared *pBt = p->pBt;
+  Pager *pPager = pBt->pPager;
   int rc = SQLITE_OK;
 
   sqlite3BtreeEnter(p);
@@ -66980,8 +68332,8 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
   }
   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
 
-  if( (p->db->flags & SQLITE_ResetDatabase) 
-   && sqlite3PagerIsreadonly(pBt->pPager)==0 
+  if( (p->db->flags & SQLITE_ResetDatabase)
+   && sqlite3PagerIsreadonly(pPager)==0
   ){
     pBt->btsFlags &= ~BTS_READ_ONLY;
   }
@@ -66995,7 +68347,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
 #ifndef SQLITE_OMIT_SHARED_CACHE
   {
     sqlite3 *pBlock = 0;
-    /* If another database handle has already opened a write transaction 
+    /* If another database handle has already opened a write transaction
     ** on this shared-btree structure and a second write transaction is
     ** requested, return SQLITE_LOCKED.
     */
@@ -67020,19 +68372,31 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
   }
 #endif
 
-  /* Any read-only or read-write transaction implies a read-lock on 
-  ** page 1. So if some other shared-cache client already has a write-lock 
+  /* Any read-only or read-write transaction implies a read-lock on
+  ** page 1. So if some other shared-cache client already has a write-lock
   ** on page 1, the transaction cannot be opened. */
-  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
+  rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
   if( SQLITE_OK!=rc ) goto trans_begun;
 
   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
   do {
+    sqlite3PagerWalDb(pPager, p->db);
+
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+    /* If transitioning from no transaction directly to a write transaction,
+    ** block for the WRITER lock first if possible. */
+    if( pBt->pPage1==0 && wrflag ){
+      assert( pBt->inTransaction==TRANS_NONE );
+      rc = sqlite3PagerWalWriteLock(pPager, 1);
+      if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
+    }
+#endif
+
     /* Call lockBtree() until either pBt->pPage1 is populated or
     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
-    ** reading page 1 it discovers that the page-size of the database 
+    ** reading page 1 it discovers that the page-size of the database
     ** file is not pBt->pageSize. In this case lockBtree() will update
     ** pBt->pageSize to the page-size of the file on disk.
     */
@@ -67042,7 +68406,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
         rc = SQLITE_READONLY;
       }else{
-        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
+        rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
         if( rc==SQLITE_OK ){
           rc = newDatabase(pBt);
         }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
@@ -67053,13 +68417,17 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
         }
       }
     }
-  
+
     if( rc!=SQLITE_OK ){
+      (void)sqlite3PagerWalWriteLock(pPager, 0);
       unlockBtreeIfUnused(pBt);
     }
   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
           btreeInvokeBusyHandler(pBt) );
-  sqlite3PagerResetLockTimeout(pBt->pPager);
+  sqlite3PagerWalDb(pPager, 0);
+#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
+  if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
+#endif
 
   if( rc==SQLITE_OK ){
     if( p->inTrans==TRANS_NONE ){
@@ -67088,7 +68456,7 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVers
 
       /* If the db-size header field is incorrect (as it may be if an old
       ** client has been writing the database file), update it now. Doing
-      ** this sooner rather than later means the database size can safely 
+      ** this sooner rather than later means the database size can safely
       ** re-read the database size from page 1 if a savepoint or transaction
       ** rollback occurs within the transaction.
       */
@@ -67111,7 +68479,7 @@ trans_begun:
       ** open savepoints. If the second parameter is greater than 0 and
       ** the sub-journal is not already open, then it will be opened here.
       */
-      rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
+      rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
     }
   }
 
@@ -67163,7 +68531,7 @@ static int setChildPtrmaps(MemPage *pPage){
 ** that it points to iTo. Parameter eType describes the type of pointer to
 ** be modified, as  follows:
 **
-** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
+** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
 **                   page of pPage.
 **
 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
@@ -67211,9 +68579,9 @@ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
         }
       }
     }
-  
+
     if( i==nCell ){
-      if( eType!=PTRMAP_BTREE || 
+      if( eType!=PTRMAP_BTREE ||
           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
         return SQLITE_CORRUPT_PAGE(pPage);
       }
@@ -67225,11 +68593,11 @@ static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
 
 
 /*
-** Move the open database page pDbPage to location iFreePage in the 
+** Move the open database page pDbPage to location iFreePage in the
 ** database. The pDbPage reference remains valid.
 **
 ** The isCommit flag indicates that there is no need to remember that
-** the journal needs to be sync()ed before database page pDbPage->pgno 
+** the journal needs to be sync()ed before database page pDbPage->pgno
 ** can be written to. The caller has already promised not to write to that
 ** page.
 */
@@ -67246,14 +68614,14 @@ static int relocatePage(
   Pager *pPager = pBt->pPager;
   int rc;
 
-  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
+  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
   assert( sqlite3_mutex_held(pBt->mutex) );
   assert( pDbPage->pBt==pBt );
   if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
 
   /* Move page iDbPage from its current location to page number iFreePage */
-  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
+  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
       iDbPage, iFreePage, iPtrPage, eType));
   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
   if( rc!=SQLITE_OK ){
@@ -67312,19 +68680,19 @@ static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
 
 /*
 ** Perform a single step of an incremental-vacuum. If successful, return
-** SQLITE_OK. If there is no work to do (and therefore no point in 
-** calling this function again), return SQLITE_DONE. Or, if an error 
+** SQLITE_OK. If there is no work to do (and therefore no point in
+** calling this function again), return SQLITE_DONE. Or, if an error
 ** occurs, return some other error code.
 **
-** More specifically, this function attempts to re-organize the database so 
+** More specifically, this function attempts to re-organize the database so
 ** that the last page of the file currently in use is no longer in use.
 **
 ** Parameter nFin is the number of pages that this database would contain
 ** were this function called until it returns SQLITE_DONE.
 **
-** If the bCommit parameter is non-zero, this function assumes that the 
-** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
-** or an error. bCommit is passed true for an auto-vacuum-on-commit 
+** If the bCommit parameter is non-zero, this function assumes that the
+** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
+** or an error. bCommit is passed true for an auto-vacuum-on-commit
 ** operation, or false for an incremental vacuum.
 */
 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
@@ -67355,7 +68723,7 @@ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
       if( bCommit==0 ){
         /* Remove the page from the files free-list. This is not required
         ** if bCommit is non-zero. In that case, the free-list will be
-        ** truncated to zero after this function returns, so it doesn't 
+        ** truncated to zero after this function returns, so it doesn't
         ** matter if it still contains some garbage entries.
         */
         Pgno iFreePg;
@@ -67399,7 +68767,7 @@ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
         releasePage(pFreePg);
       }while( bCommit && iFreePg>nFin );
       assert( iFreePg<iLastPg );
-      
+
       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
       releasePage(pLastPg);
       if( rc!=SQLITE_OK ){
@@ -67420,7 +68788,7 @@ static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
 
 /*
 ** The database opened by the first argument is an auto-vacuum database
-** nOrig pages in size containing nFree free pages. Return the expected 
+** nOrig pages in size containing nFree free pages. Return the expected
 ** size of the database in pages following an auto-vacuum operation.
 */
 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
@@ -67447,7 +68815,7 @@ static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
 **
 ** If the incremental vacuum is finished after this function has run,
 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
-** SQLITE_OK is returned. Otherwise an SQLite error code. 
+** SQLITE_OK is returned. Otherwise an SQLite error code.
 */
 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
   int rc;
@@ -67462,7 +68830,7 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
 
-    if( nOrig<nFin ){
+    if( nOrig<nFin || nFree>=nOrig ){
       rc = SQLITE_CORRUPT_BKPT;
     }else if( nFree>0 ){
       rc = saveAllCursors(pBt, 0, 0);
@@ -67487,7 +68855,7 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
 ** is committed for an auto-vacuum database.
 **
 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
-** the database file should be truncated to during the commit process. 
+** the database file should be truncated to during the commit process.
 ** i.e. the database has been reorganized so that only the first *pnTrunc
 ** pages are in use.
 */
@@ -67559,18 +68927,18 @@ static int autoVacuumCommit(BtShared *pBt){
 **
 ** This call is a no-op if no write-transaction is currently active on pBt.
 **
-** Otherwise, sync the database file for the btree pBt. zMaster points to
-** the name of a master journal file that should be written into the
-** individual journal file, or is NULL, indicating no master journal file 
+** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
+** the name of a super-journal file that should be written into the
+** individual journal file, or is NULL, indicating no super-journal file
 ** (single database transaction).
 **
-** When this is called, the master journal should already have been
+** When this is called, the super-journal should already have been
 ** created, populated with this journal pointer and synced to disk.
 **
 ** Once this is routine has returned, the only thing required to commit
 ** the write-transaction for this database file is to delete the journal.
 */
-SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
+SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
   int rc = SQLITE_OK;
   if( p->inTrans==TRANS_WRITE ){
     BtShared *pBt = p->pBt;
@@ -67587,7 +68955,7 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
     }
 #endif
-    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
+    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
     sqlite3BtreeLeave(p);
   }
   return rc;
@@ -67612,8 +68980,8 @@ static void btreeEndTransaction(Btree *p){
     downgradeAllSharedCacheTableLocks(p);
     p->inTrans = TRANS_READ;
   }else{
-    /* If the handle had any kind of transaction open, decrement the 
-    ** transaction count of the shared btree. If the transaction count 
+    /* If the handle had any kind of transaction open, decrement the
+    ** transaction count of the shared btree. If the transaction count
     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
     ** call below will unlock the pager.  */
     if( p->inTrans!=TRANS_NONE ){
@@ -67624,7 +68992,7 @@ static void btreeEndTransaction(Btree *p){
       }
     }
 
-    /* Set the current transaction state to TRANS_NONE and unlock the 
+    /* Set the current transaction state to TRANS_NONE and unlock the
     ** pager if this call closed the only read or write transaction.  */
     p->inTrans = TRANS_NONE;
     unlockBtreeIfUnused(pBt);
@@ -67645,12 +69013,12 @@ static void btreeEndTransaction(Btree *p){
 ** the rollback journal (which causes the transaction to commit) and
 ** drop locks.
 **
-** Normally, if an error occurs while the pager layer is attempting to 
+** Normally, if an error occurs while the pager layer is attempting to
 ** finalize the underlying journal file, this function returns an error and
 ** the upper layer will attempt a rollback. However, if the second argument
-** is non-zero then this b-tree transaction is part of a multi-file 
-** transaction. In this case, the transaction has already been committed 
-** (by deleting a master journal file) and the caller will ignore this 
+** is non-zero then this b-tree transaction is part of a multi-file
+** transaction. In this case, the transaction has already been committed
+** (by deleting a super-journal file) and the caller will ignore this
 ** functions return code. So, even if an error occurs in the pager layer,
 ** reset the b-tree objects internal state to indicate that the write
 ** transaction has been closed. This is quite safe, as the pager will have
@@ -67665,7 +69033,7 @@ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
   sqlite3BtreeEnter(p);
   btreeIntegrity(p);
 
-  /* If the handle has a write-transaction open, commit the shared-btrees 
+  /* If the handle has a write-transaction open, commit the shared-btrees
   ** transaction and set the shared state to TRANS_READ.
   */
   if( p->inTrans==TRANS_WRITE ){
@@ -67714,15 +69082,15 @@ SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
 **
 ** This routine gets called when a rollback occurs. If the writeOnly
 ** flag is true, then only write-cursors need be tripped - read-only
-** cursors save their current positions so that they may continue 
-** following the rollback. Or, if writeOnly is false, all cursors are 
+** cursors save their current positions so that they may continue
+** following the rollback. Or, if writeOnly is false, all cursors are
 ** tripped. In general, writeOnly is false if the transaction being
 ** rolled back modified the database schema. In this case b-tree root
 ** pages may be moved or deleted from the database altogether, making
 ** it unsafe for read cursors to continue.
 **
-** If the writeOnly flag is true and an error is encountered while 
-** saving the current position of a read-only cursor, all cursors, 
+** If the writeOnly flag is true and an error is encountered while
+** saving the current position of a read-only cursor, all cursors,
 ** including all read-cursors are tripped.
 **
 ** SQLITE_OK is returned if successful, or if an error occurs while
@@ -67828,8 +69196,8 @@ SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
 
 /*
 ** Start a statement subtransaction. The subtransaction can be rolled
-** back independently of the main transaction. You must start a transaction 
-** before starting a subtransaction. The subtransaction is ended automatically 
+** back independently of the main transaction. You must start a transaction
+** before starting a subtransaction. The subtransaction is ended automatically
 ** if the main transaction commits or rolls back.
 **
 ** Statement subtransactions are used around individual SQL statements
@@ -67866,11 +69234,11 @@ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
 /*
 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
-** savepoint identified by parameter iSavepoint, depending on the value 
+** savepoint identified by parameter iSavepoint, depending on the value
 ** of op.
 **
 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
-** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
+** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
 ** contents of the entire transaction are rolled back. This is different
 ** from a normal transaction rollback, as no locks are released and the
 ** transaction remains open.
@@ -67895,7 +69263,7 @@ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
       rc = newDatabase(pBt);
       btreeSetNPage(pBt, pBt->pPage1);
 
-      /* pBt->nPage might be zero if the database was corrupt when 
+      /* pBt->nPage might be zero if the database was corrupt when
       ** the transaction was started. Otherwise, it must be at least 1.  */
       assert( CORRUPT_DB || pBt->nPage>0 );
     }
@@ -67933,10 +69301,10 @@ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
 ** is set.  If FORDELETE is set, that is a hint to the implementation that
 ** this cursor will only be used to seek to and delete entries of an index
 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
-** this implementation.  But in a hypothetical alternative storage engine 
+** this implementation.  But in a hypothetical alternative storage engine
 ** in which index entries are automatically deleted when corresponding table
 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
-** operations on this cursor can be no-ops and all READ operations can 
+** operations on this cursor can be no-ops and all READ operations can
 ** return a null row (2-bytes: 0x01 0x00).
 **
 ** No checking is done to make sure that page iTable really is the
@@ -67948,7 +69316,7 @@ SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
 */
 static int btreeCursor(
   Btree *p,                              /* The btree */
-  int iTable,                            /* Root page of table to open */
+  Pgno iTable,                           /* Root page of table to open */
   int wrFlag,                            /* 1 to write. 0 read-only */
   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
   BtCursor *pCur                         /* Space for new cursor */
@@ -67957,16 +69325,17 @@ static int btreeCursor(
   BtCursor *pX;                          /* Looping over other all cursors */
 
   assert( sqlite3BtreeHoldsMutex(p) );
-  assert( wrFlag==0 
-       || wrFlag==BTREE_WRCSR 
-       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 
+  assert( wrFlag==0
+       || wrFlag==BTREE_WRCSR
+       || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
   );
 
-  /* The following assert statements verify that if this is a sharable 
-  ** b-tree database, the connection is holding the required table locks, 
-  ** and that no other connection has any open cursor that conflicts with 
-  ** this lock.  */
-  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
+  /* The following assert statements verify that if this is a sharable
+  ** b-tree database, the connection is holding the required table locks,
+  ** and that no other connection has any open cursor that conflicts with
+  ** this lock.  The iTable<1 term disables the check for corrupt schemas. */
+  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
+          || iTable<1 );
   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
 
   /* Assert that the caller has opened the required transaction. */
@@ -67979,14 +69348,18 @@ static int btreeCursor(
     allocateTempSpace(pBt);
     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
   }
-  if( iTable==1 && btreePagecount(pBt)==0 ){
-    assert( wrFlag==0 );
-    iTable = 0;
+  if( iTable<=1 ){
+    if( iTable<1 ){
+      return SQLITE_CORRUPT_BKPT;
+    }else if( btreePagecount(pBt)==0 ){
+      assert( wrFlag==0 );
+      iTable = 0;
+    }
   }
 
   /* Now that no other errors can occur, finish filling in the BtCursor
   ** variables and link the cursor into the BtShared list.  */
-  pCur->pgnoRoot = (Pgno)iTable;
+  pCur->pgnoRoot = iTable;
   pCur->iPage = -1;
   pCur->pKeyInfo = pKeyInfo;
   pCur->pBtree = p;
@@ -67996,7 +69369,7 @@ static int btreeCursor(
   /* If there are two or more cursors on the same btree, then all such
   ** cursors *must* have the BTCF_Multiple flag set. */
   for(pX=pBt->pCursor; pX; pX=pX->pNext){
-    if( pX->pgnoRoot==(Pgno)iTable ){
+    if( pX->pgnoRoot==iTable ){
       pX->curFlags |= BTCF_Multiple;
       pCur->curFlags |= BTCF_Multiple;
     }
@@ -68006,22 +69379,31 @@ static int btreeCursor(
   pCur->eState = CURSOR_INVALID;
   return SQLITE_OK;
 }
+static int btreeCursorWithLock(
+  Btree *p,                              /* The btree */
+  Pgno iTable,                           /* Root page of table to open */
+  int wrFlag,                            /* 1 to write. 0 read-only */
+  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
+  BtCursor *pCur                         /* Space for new cursor */
+){
+  int rc;
+  sqlite3BtreeEnter(p);
+  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
+  sqlite3BtreeLeave(p);
+  return rc;
+}
 SQLITE_PRIVATE int sqlite3BtreeCursor(
   Btree *p,                                   /* The btree */
-  int iTable,                                 /* Root page of table to open */
+  Pgno iTable,                                /* Root page of table to open */
   int wrFlag,                                 /* 1 to write. 0 read-only */
   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
   BtCursor *pCur                              /* Write new cursor here */
 ){
-  int rc;
-  if( iTable<1 ){
-    rc = SQLITE_CORRUPT_BKPT;
+  if( p->sharable ){
+    return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
   }else{
-    sqlite3BtreeEnter(p);
-    rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
-    sqlite3BtreeLeave(p);
+    return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
   }
-  return rc;
 }
 
 /*
@@ -68144,6 +69526,18 @@ SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
   return pCur->info.nKey;
 }
 
+/*
+** Pin or unpin a cursor.
+*/
+SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){
+  assert( (pCur->curFlags & BTCF_Pinned)==0 );
+  pCur->curFlags |= BTCF_Pinned;
+}
+SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){
+  assert( (pCur->curFlags & BTCF_Pinned)!=0 );
+  pCur->curFlags &= ~BTCF_Pinned;
+}
+
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
 /*
 ** Return the offset into the database file for the start of the
@@ -68195,15 +69589,15 @@ SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
 
 /*
 ** Given the page number of an overflow page in the database (parameter
-** ovfl), this function finds the page number of the next page in the 
+** ovfl), this function finds the page number of the next page in the
 ** linked list of overflow pages. If possible, it uses the auto-vacuum
-** pointer-map data instead of reading the content of page ovfl to do so. 
+** pointer-map data instead of reading the content of page ovfl to do so.
 **
 ** If an error occurs an SQLite error code is returned. Otherwise:
 **
-** The page number of the next overflow page in the linked list is 
-** written to *pPgnoNext. If page ovfl is the last page in its linked 
-** list, *pPgnoNext is set to zero. 
+** The page number of the next overflow page in the linked list is
+** written to *pPgnoNext. If page ovfl is the last page in its linked
+** list, *pPgnoNext is set to zero.
 **
 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
 ** to page number pOvfl was obtained, then *ppPage is set to point to that
@@ -68227,9 +69621,9 @@ static int getOverflowPage(
 
 #ifndef SQLITE_OMIT_AUTOVACUUM
   /* Try to find the next page in the overflow list using the
-  ** autovacuum pointer-map pages. Guess that the next page in 
-  ** the overflow list is page number (ovfl+1). If that guess turns 
-  ** out to be wrong, fall back to loading the data of page 
+  ** autovacuum pointer-map pages. Guess that the next page in
+  ** the overflow list is page number (ovfl+1). If that guess turns
+  ** out to be wrong, fall back to loading the data of page
   ** number ovfl to determine the next page number.
   */
   if( pBt->autoVacuum ){
@@ -68317,8 +69711,8 @@ static int copyPayload(
 **
 ** If the current cursor entry uses one or more overflow pages
 ** this function may allocate space for and lazily populate
-** the overflow page-list cache array (BtCursor.aOverflow). 
-** Subsequent calls use this cache to make seeking to the supplied offset 
+** the overflow page-list cache array (BtCursor.aOverflow).
+** Subsequent calls use this cache to make seeking to the supplied offset
 ** more efficient.
 **
 ** Once an overflow page-list cache has been allocated, it must be
@@ -68334,7 +69728,7 @@ static int accessPayload(
   BtCursor *pCur,      /* Cursor pointing to entry to read from */
   u32 offset,          /* Begin reading this far into payload */
   u32 amt,             /* Read this many bytes */
-  unsigned char *pBuf, /* Write the bytes into this buffer */ 
+  unsigned char *pBuf, /* Write the bytes into this buffer */
   int eOp              /* zero to read. non-zero to write. */
 ){
   unsigned char *aPayload;
@@ -68425,6 +69819,7 @@ static int accessPayload(
     assert( rc==SQLITE_OK && amt>0 );
     while( nextPage ){
       /* If required, populate the overflow page-list cache. */
+      if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
       assert( pCur->aOverflow[iIdx]==0
               || pCur->aOverflow[iIdx]==nextPage
               || CORRUPT_DB );
@@ -68457,12 +69852,12 @@ static int accessPayload(
 #ifdef SQLITE_DIRECT_OVERFLOW_READ
         /* If all the following are true:
         **
-        **   1) this is a read operation, and 
+        **   1) this is a read operation, and
         **   2) data is required from the start of this overflow page, and
         **   3) there are no dirty pages in the page-cache
         **   4) the database is file-backed, and
         **   5) the page is not in the WAL file
-        **   6) at least 4 bytes have already been read into the output buffer 
+        **   6) at least 4 bytes have already been read into the output buffer
         **
         ** then data can be read directly from the database file into the
         ** output buffer, bypassing the page-cache altogether. This speeds
@@ -68570,7 +69965,7 @@ SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 am
 #endif /* SQLITE_OMIT_INCRBLOB */
 
 /*
-** Return a pointer to payload information from the entry that the 
+** Return a pointer to payload information from the entry that the
 ** pCur cursor is pointing to.  The pointer is to the beginning of
 ** the key if index btrees (pPage->intKey==0) and is the data for
 ** table btrees (pPage->intKey==1). The number of bytes of available
@@ -68662,7 +70057,7 @@ static int moveToChild(BtCursor *pCur, u32 newPgno){
 
 #ifdef SQLITE_DEBUG
 /*
-** Page pParent is an internal (non-leaf) tree page. This function 
+** Page pParent is an internal (non-leaf) tree page. This function
 ** asserts that page number iChild is the left-child if the iIdx'th
 ** cell in page pParent. Or, if iIdx is equal to the total number of
 ** cells in pParent, that page number iChild is the right-child of
@@ -68679,7 +70074,7 @@ static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
   }
 }
 #else
-#  define assertParentIndex(x,y,z) 
+#  define assertParentIndex(x,y,z)
 #endif
 
 /*
@@ -68697,8 +70092,8 @@ static void moveToParent(BtCursor *pCur){
   assert( pCur->iPage>0 );
   assert( pCur->pPage );
   assertParentIndex(
-    pCur->apPage[pCur->iPage-1], 
-    pCur->aiIdx[pCur->iPage-1], 
+    pCur->apPage[pCur->iPage-1],
+    pCur->aiIdx[pCur->iPage-1],
     pCur->pPage->pgno
   );
   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
@@ -68715,19 +70110,19 @@ static void moveToParent(BtCursor *pCur){
 **
 ** If the table has a virtual root page, then the cursor is moved to point
 ** to the virtual root page instead of the actual root page. A table has a
-** virtual root page when the actual root page contains no cells and a 
+** virtual root page when the actual root page contains no cells and a
 ** single child page. This can only happen with the table rooted at page 1.
 **
-** If the b-tree structure is empty, the cursor state is set to 
+** If the b-tree structure is empty, the cursor state is set to
 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
 ** the cursor is set to point to the first cell located on the root
 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
 **
 ** If this function returns successfully, it may be assumed that the
-** page-header flags indicate that the [virtual] root-page is the expected 
+** page-header flags indicate that the [virtual] root-page is the expected
 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
-** indicating a table b-tree, or if the caller did specify a KeyInfo 
+** indicating a table b-tree, or if the caller did specify a KeyInfo
 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
 ** b-tree).
 */
@@ -68778,19 +70173,19 @@ static int moveToRoot(BtCursor *pCur){
   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
   ** NULL, the caller expects a table b-tree. If this is not the case,
-  ** return an SQLITE_CORRUPT error. 
+  ** return an SQLITE_CORRUPT error.
   **
   ** Earlier versions of SQLite assumed that this test could not fail
   ** if the root page was already loaded when this function was called (i.e.
-  ** if pCur->iPage>=0). But this is not so if the database is corrupted 
-  ** in such a way that page pRoot is linked into a second b-tree table 
+  ** if pCur->iPage>=0). But this is not so if the database is corrupted
+  ** in such a way that page pRoot is linked into a second b-tree table
   ** (or the freelist).  */
   assert( pRoot->intKey==1 || pRoot->intKey==0 );
   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
     return SQLITE_CORRUPT_PAGE(pCur->pPage);
   }
 
-skip_init:  
+skip_init:
   pCur->ix = 0;
   pCur->info.nSize = 0;
   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
@@ -68890,14 +70285,14 @@ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
 */
 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   int rc;
+
   assert( cursorOwnsBtShared(pCur) );
   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
 
   /* If the cursor already points to the last entry, this is a no-op. */
   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
 #ifdef SQLITE_DEBUG
-    /* This block serves to assert() that the cursor really does point 
+    /* This block serves to assert() that the cursor really does point
     ** to the last entry in the b-tree. */
     int ii;
     for(ii=0; ii<pCur->iPage; ii++){
@@ -68928,10 +70323,10 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
   return rc;
 }
 
-/* Move the cursor so that it points to an entry near the key 
+/* Move the cursor so that it points to an entry near the key
 ** specified by pIdxKey or intKey.   Return a success code.
 **
-** For INTKEY tables, the intKey parameter is used.  pIdxKey 
+** For INTKEY tables, the intKey parameter is used.  pIdxKey
 ** must be NULL.  For index tables, pIdxKey is used and intKey
 ** is ignored.
 **
@@ -68941,7 +70336,7 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 ** before or after the key.
 **
 ** An integer is written into *pRes which is the result of
-** comparing the key with the entry to which the cursor is 
+** comparing the key with the entry to which the cursor is
 ** pointing.  The meaning of the integer written into
 ** *pRes is as follows:
 **
@@ -68956,7 +70351,7 @@ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
 **                  is larger than intKey/pIdxKey.
 **
 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
-** exists an entry in the table that exactly matches pIdxKey.  
+** exists an entry in the table that exactly matches pIdxKey.
 */
 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
   BtCursor *pCur,          /* The cursor to be moved */
@@ -69009,11 +70404,15 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
     }
   }
 
+#ifdef SQLITE_DEBUG
+  pCur->pBtree->nSeek++;   /* Performance measurement during testing */
+#endif
+
   if( pIdxKey ){
     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
     pIdxKey->errCode = 0;
-    assert( pIdxKey->default_rc==1 
-         || pIdxKey->default_rc==0 
+    assert( pIdxKey->default_rc==1
+         || pIdxKey->default_rc==0
          || pIdxKey->default_rc==-1
     );
   }else{
@@ -69097,9 +70496,9 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
         /* The maximum supported page-size is 65536 bytes. This means that
         ** the maximum number of record bytes stored on an index B-Tree
         ** page is less than 16384 bytes and may be stored as a 2-byte
-        ** varint. This information is used to attempt to avoid parsing 
-        ** the entire cell by checking for the cases where the record is 
-        ** stored entirely within the b-tree page by inspecting the first 
+        ** varint. This information is used to attempt to avoid parsing
+        ** the entire cell by checking for the cases where the record is
+        ** stored entirely within the b-tree page by inspecting the first
         ** 2 bytes of the cell.
         */
         nCell = pCell[0];
@@ -69109,10 +70508,10 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
           ** b-tree page.  */
           testcase( pCell+nCell+1==pPage->aDataEnd );
           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
-        }else if( !(pCell[1] & 0x80) 
+        }else if( !(pCell[1] & 0x80)
           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
         ){
-          /* The record-size field is a 2 byte varint and the record 
+          /* The record-size field is a 2 byte varint and the record
           ** fits entirely on the main b-tree page.  */
           testcase( pCell+nCell+2==pPage->aDataEnd );
           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
@@ -69120,10 +70519,10 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
           /* The record flows over onto one or more overflow pages. In
           ** this case the whole cell needs to be parsed, a buffer allocated
           ** and accessPayload() used to retrieve the record into the
-          ** buffer before VdbeRecordCompare() can be called. 
+          ** buffer before VdbeRecordCompare() can be called.
           **
           ** If the record is corrupt, the xRecordCompare routine may read
-          ** up to two varints past the end of the buffer. An extra 18 
+          ** up to two varints past the end of the buffer. An extra 18
           ** bytes of padding is allocated at the end of the buffer in
           ** case this happens.  */
           void *pCellKey;
@@ -69155,7 +70554,7 @@ SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
           sqlite3_free(pCellKey);
         }
-        assert( 
+        assert(
             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
         );
@@ -69219,7 +70618,7 @@ SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
 
 /*
 ** Return an estimate for the number of rows in the table that pCur is
-** pointing to.  Return a negative number if no estimate is currently 
+** pointing to.  Return a negative number if no estimate is currently
 ** available.
 */
 SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
@@ -69243,7 +70642,7 @@ SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
 }
 
 /*
-** Advance the cursor to the next entry in the database. 
+** Advance the cursor to the next entry in the database.
 ** Return value:
 **
 **    SQLITE_OK        success
@@ -69285,7 +70684,7 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
 
   pPage = pCur->pPage;
   idx = ++pCur->ix;
-  if( !pPage->isInit ){
+  if( !pPage->isInit || sqlite3FaultSim(412) ){
     /* The only known way for this to happen is for there to be a
     ** recursive SQL function that does a DELETE operation as part of a
     ** SELECT which deletes content out from under an active cursor
@@ -69296,12 +70695,15 @@ static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
     return SQLITE_CORRUPT_BKPT;
   }
 
-  /* If the database file is corrupt, it is possible for the value of idx 
+  /* If the database file is corrupt, it is possible for the value of idx
   ** to be invalid here. This can only occur if a second cursor modifies
   ** the page while cursor pCur is holding a reference to it. Which can
   ** only happen if the database is corrupt in such a way as to link the
-  ** page into more than one b-tree structure. */
-  testcase( idx>pPage->nCell );
+  ** page into more than one b-tree structure.
+  **
+  ** Update 2019-12-23: appears to long longer be possible after the
+  ** addition of anotherValidCursor() condition on balance_deeper().  */
+  harmless( idx>pPage->nCell );
 
   if( idx>=pPage->nCell ){
     if( !pPage->leaf ){
@@ -69445,7 +70847,7 @@ SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
 ** SQLITE_OK is returned on success.  Any other return value indicates
 ** an error.  *ppPage is set to NULL in the event of an error.
 **
-** If the "nearby" parameter is not 0, then an effort is made to 
+** If the "nearby" parameter is not 0, then an effort is made to
 ** locate a page close to the page number "nearby".  This can be used in an
 ** attempt to keep related pages close to each other in the database file,
 ** which in turn can make database access faster.
@@ -69487,7 +70889,7 @@ static int allocateBtreePage(
     Pgno iTrunk;
     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
     u32 nSearch = 0;   /* Count of the number of search attempts */
-    
+
     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
     ** shows that the page 'nearby' is somewhere on the free-list, then
     ** the entire-list will be searched for that page.
@@ -69550,8 +70952,8 @@ static int allocateBtreePage(
       ** is the number of leaf page pointers to follow. */
       k = get4byte(&pTrunk->aData[4]);
       if( k==0 && !searchList ){
-        /* The trunk has no leaves and the list is not being searched. 
-        ** So extract the trunk page itself and use it as the newly 
+        /* The trunk has no leaves and the list is not being searched.
+        ** So extract the trunk page itself and use it as the newly
         ** allocated page */
         assert( pPrevTrunk==0 );
         rc = sqlite3PagerWrite(pTrunk->pDbPage);
@@ -69568,8 +70970,8 @@ static int allocateBtreePage(
         rc = SQLITE_CORRUPT_PGNO(iTrunk);
         goto end_allocate_page;
 #ifndef SQLITE_OMIT_AUTOVACUUM
-      }else if( searchList 
-            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
+      }else if( searchList
+            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
       ){
         /* The list is being searched and this trunk page is the page
         ** to allocate, regardless of whether it has leaves.
@@ -69592,13 +70994,13 @@ static int allocateBtreePage(
             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
           }
         }else{
-          /* The trunk page is required by the caller but it contains 
+          /* The trunk page is required by the caller but it contains
           ** pointers to free-list leaves. The first leaf becomes a trunk
           ** page in this case.
           */
           MemPage *pNewTrunk;
           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
-          if( iNewTrunk>mxPage ){ 
+          if( iNewTrunk>mxPage ){
             rc = SQLITE_CORRUPT_PGNO(iTrunk);
             goto end_allocate_page;
           }
@@ -69668,8 +71070,8 @@ static int allocateBtreePage(
           goto end_allocate_page;
         }
         testcase( iPage==mxPage );
-        if( !searchList 
-         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
+        if( !searchList
+         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
         ){
           int noContent;
           *pPgno = iPage;
@@ -69710,7 +71112,7 @@ static int allocateBtreePage(
     ** not set the no-content flag. This causes the pager to load and journal
     ** the current page content before overwriting it.
     **
-    ** Note that the pager will not actually attempt to load or journal 
+    ** Note that the pager will not actually attempt to load or journal
     ** content for any page that really does lie past the end of the database
     ** file on disk. So the effects of disabling the no-content optimization
     ** here are confined to those pages that lie between the end of the
@@ -69767,12 +71169,12 @@ end_allocate_page:
 }
 
 /*
-** This function is used to add page iPage to the database file free-list. 
+** This function is used to add page iPage to the database file free-list.
 ** It is assumed that the page is not already a part of the free-list.
 **
 ** The value passed as the second argument to this function is optional.
-** If the caller happens to have a pointer to the MemPage object 
-** corresponding to page iPage handy, it may pass it as the second value. 
+** If the caller happens to have a pointer to the MemPage object
+** corresponding to page iPage handy, it may pass it as the second value.
 ** Otherwise, it may pass NULL.
 **
 ** If a pointer to a MemPage object is passed as the second argument,
@@ -69780,7 +71182,7 @@ end_allocate_page:
 */
 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
   MemPage *pTrunk = 0;                /* Free-list trunk page */
-  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
+  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
   MemPage *pPage;                     /* Page being freed. May be NULL. */
   int rc;                             /* Return Code */
@@ -69837,6 +71239,10 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
 
     iTrunk = get4byte(&pPage1->aData[32]);
+    if( iTrunk>btreePagecount(pBt) ){
+      rc = SQLITE_CORRUPT_BKPT;
+      goto freepage_out;
+    }
     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
     if( rc!=SQLITE_OK ){
       goto freepage_out;
@@ -69884,7 +71290,7 @@ static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
 
   /* If control flows to this point, then it was not possible to add the
   ** the page being freed as a leaf page of the first trunk in the free-list.
-  ** Possibly because the free-list is empty, or possibly because the 
+  ** Possibly because the free-list is empty, or possibly because the
   ** first trunk in the free-list is full. Either way, the page being freed
   ** will become the new first trunk page in the free-list.
   */
@@ -69945,15 +71351,15 @@ static int clearCell(
   assert( pBt->usableSize > 4 );
   ovflPageSize = pBt->usableSize - 4;
   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
-  assert( nOvfl>0 || 
+  assert( nOvfl>0 ||
     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
   );
   while( nOvfl-- ){
     Pgno iNext = 0;
     MemPage *pOvfl = 0;
     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
-      /* 0 is not a legal page number and page 1 cannot be an 
-      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
+      /* 0 is not a legal page number and page 1 cannot be an
+      ** overflow page. Therefore if ovflPgno<2 or past the end of the
       ** file the database must be corrupt. */
       return SQLITE_CORRUPT_BKPT;
     }
@@ -69965,11 +71371,11 @@ static int clearCell(
     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
     ){
-      /* There is no reason any cursor should have an outstanding reference 
+      /* There is no reason any cursor should have an outstanding reference
       ** to an overflow page belonging to a cell that is being deleted/updated.
-      ** So if there exists more than one reference to this page, then it 
-      ** must not really be an overflow page and the database must be corrupt. 
-      ** It is helpful to detect this before calling freePage2(), as 
+      ** So if there exists more than one reference to this page, then it
+      ** must not really be an overflow page and the database must be corrupt.
+      ** It is helpful to detect this before calling freePage2(), as
       ** freePage2() may zero the page contents if secure-delete mode is
       ** enabled. If this 'overflow' page happens to be a page that the
       ** caller is iterating through or using in some other way, this
@@ -70040,7 +71446,7 @@ static int fillInCell(
     pSrc = pX->pKey;
     nHeader += putVarint32(&pCell[nHeader], nPayload);
   }
-  
+
   /* Fill in the payload */
   pPayload = &pCell[nHeader];
   if( nPayload<=pPage->maxLocal ){
@@ -70131,8 +71537,8 @@ static int fillInCell(
       if( pBt->autoVacuum ){
         do{
           pgnoOvfl++;
-        } while( 
-          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
+        } while(
+          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
         );
       }
 #endif
@@ -70140,9 +71546,9 @@ static int fillInCell(
 #ifndef SQLITE_OMIT_AUTOVACUUM
       /* If the database supports auto-vacuum, and the second or subsequent
       ** overflow page is being allocated, add an entry to the pointer-map
-      ** for that page now. 
+      ** for that page now.
       **
-      ** If this is the first overflow page, then write a partial entry 
+      ** If this is the first overflow page, then write a partial entry
       ** to the pointer-map. If we write nothing to this pointer-map slot,
       ** then the optimistic overflow chain processing in clearCell()
       ** may misinterpret the uninitialized values and delete the
@@ -70241,8 +71647,8 @@ static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
 ** will not fit, then make a copy of the cell content into pTemp if
 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
 ** in pPage->apOvfl[] and make it point to the cell content (either
-** in pTemp or the original pCell) and also record its index. 
-** Allocating a new entry in pPage->aCell[] implies that 
+** in pTemp or the original pCell) and also record its index.
+** Allocating a new entry in pPage->aCell[] implies that
 ** pPage->nOverflow is incremented.
 **
 ** *pRC must be SQLITE_OK when this routine is called.
@@ -70467,16 +71873,16 @@ static u16 cachedCellSize(CellArray *p, int N){
 }
 
 /*
-** Array apCell[] contains pointers to nCell b-tree page cells. The 
+** Array apCell[] contains pointers to nCell b-tree page cells. The
 ** szCell[] array contains the size in bytes of each cell. This function
 ** replaces the current contents of page pPg with the contents of the cell
 ** array.
 **
 ** Some of the cells in apCell[] may currently be stored in pPg. This
-** function works around problems caused by this by making a copy of any 
+** function works around problems caused by this by making a copy of any
 ** such cells before overwriting the page data.
 **
-** The MemPage.nFree field is invalidated by this function. It is the 
+** The MemPage.nFree field is invalidated by this function. It is the
 ** responsibility of the caller to set it correctly.
 */
 static int rebuildPage(
@@ -70500,7 +71906,7 @@ static int rebuildPage(
 
   assert( i<iEnd );
   j = get2byte(&aData[hdr+5]);
-  if( j>(u32)usableSize ){ j = 0; }
+  if( NEVER(j>(u32)usableSize) ){ j = 0; }
   memcpy(&pTmp[j], &aData[j], usableSize - j);
 
   for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
@@ -70526,7 +71932,7 @@ static int rebuildPage(
     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
     memcpy(pData, pCell, sz);
     assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
-    testcase( sz!=pPg->xCellSize(pPg,pCell) );
+    testcase( sz!=pPg->xCellSize(pPg,pCell) )
     i++;
     if( i>=iEnd ) break;
     if( pCArray->ixNx[k]<=i ){
@@ -70559,7 +71965,7 @@ static int rebuildPage(
 ** cell in the array. It is the responsibility of the caller to ensure
 ** that it is safe to overwrite this part of the cell-pointer array.
 **
-** When this function is called, *ppData points to the start of the 
+** When this function is called, *ppData points to the start of the
 ** content area on page pPg. If the size of the content area is extended,
 ** *ppData is updated to point to the new start of the content area
 ** before returning.
@@ -70718,7 +72124,7 @@ static int editPage(
   assert( nCell>=0 );
   if( iOld<iNew ){
     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
-    if( nShift>nCell ) return SQLITE_CORRUPT_BKPT;
+    if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
     nCell -= nShift;
   }
@@ -70829,12 +72235,12 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
   assert( pPage->nOverflow==1 );
-  
+
   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;  /* dbfuzz001.test */
   assert( pPage->nFree>=0 );
   assert( pParent->nFree>=0 );
 
-  /* Allocate a new page. This page will become the right-sibling of 
+  /* Allocate a new page. This page will become the right-sibling of
   ** pPage. Make the parent page writable, so that the new divider cell
   ** may be inserted. If both these operations are successful, proceed.
   */
@@ -70865,7 +72271,7 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
 
     /* If this is an auto-vacuum database, update the pointer map
-    ** with entries for the new page, and any pointer from the 
+    ** with entries for the new page, and any pointer from the
     ** cell on the page to an overflow page. If either of these
     ** operations fails, the return code is set, but the contents
     ** of the parent page are still manipulated by thh code below.
@@ -70879,14 +72285,14 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
         ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
       }
     }
-  
+
     /* Create a divider cell to insert into pParent. The divider cell
     ** consists of a 4-byte page number (the page number of pPage) and
     ** a variable length key value (which must be the same value as the
     ** largest key on pPage).
     **
-    ** To find the largest key value on pPage, first find the right-most 
-    ** cell on pPage. The first two fields of this cell are the 
+    ** To find the largest key value on pPage, first find the right-most
+    ** cell on pPage. The first two fields of this cell are the
     ** record-length (a variable length integer at most 32-bits in size)
     ** and the key value (a variable length integer, may have any value).
     ** The first of the while(...) loops below skips over the record-length
@@ -70907,7 +72313,7 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
 
     /* Set the right-child pointer of pParent to point to the new page. */
     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
-  
+
     /* Release the reference to the new page. */
     releasePage(pNew);
   }
@@ -70919,7 +72325,7 @@ static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
 #if 0
 /*
 ** This function does not contribute anything to the operation of SQLite.
-** it is sometimes activated temporarily while debugging code responsible 
+** it is sometimes activated temporarily while debugging code responsible
 ** for setting pointer-map entries.
 */
 static int ptrmapCheckPages(MemPage **apPage, int nPage){
@@ -70934,7 +72340,7 @@ static int ptrmapCheckPages(MemPage **apPage, int nPage){
     for(j=0; j<pPage->nCell; j++){
       CellInfo info;
       u8 *z;
-     
+
       z = findCell(pPage, j);
       pPage->xParseCell(pPage, z, &info);
       if( info.nLocal<info.nPayload ){
@@ -70959,7 +72365,7 @@ static int ptrmapCheckPages(MemPage **apPage, int nPage){
 #endif
 
 /*
-** This function is used to copy the contents of the b-tree node stored 
+** This function is used to copy the contents of the b-tree node stored
 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
 ** the pointer-map entries for each child page are updated so that the
 ** parent page stored in the pointer map is page pTo. If pFrom contained
@@ -70967,11 +72373,11 @@ static int ptrmapCheckPages(MemPage **apPage, int nPage){
 ** map entries are also updated so that the parent page is page pTo.
 **
 ** If pFrom is currently carrying any overflow cells (entries in the
-** MemPage.apOvfl[] array), they are not copied to pTo. 
+** MemPage.apOvfl[] array), they are not copied to pTo.
 **
 ** Before returning, page pTo is reinitialized using btreeInitPage().
 **
-** The performance of this function is not critical. It is only used by 
+** The performance of this function is not critical. It is only used by
 ** the balance_shallower() and balance_deeper() procedures, neither of
 ** which are called often under normal circumstances.
 */
@@ -70984,20 +72390,20 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
     int rc;
     int iData;
-  
-  
+
+
     assert( pFrom->isInit );
     assert( pFrom->nFree>=iToHdr );
     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
-  
+
     /* Copy the b-tree node content from page pFrom to page pTo. */
     iData = get2byte(&aFrom[iFromHdr+5]);
     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
-  
+
     /* Reinitialize page pTo so that the contents of the MemPage structure
     ** match the new data. The initialization of pTo can actually fail under
-    ** fairly obscure circumstances, even though it is a copy of initialized 
+    ** fairly obscure circumstances, even though it is a copy of initialized
     ** page pFrom.
     */
     pTo->isInit = 0;
@@ -71007,7 +72413,7 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
       *pRC = rc;
       return;
     }
-  
+
     /* If this is an auto-vacuum database, update the pointer-map entries
     ** for any b-tree or overflow pages that pTo now contains the pointers to.
     */
@@ -71022,13 +72428,13 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
 ** same amount of free space. Usually a single sibling on either side of the
 ** page are used in the balancing, though both siblings might come from one
-** side if the page is the first or last child of its parent. If the page 
+** side if the page is the first or last child of its parent. If the page
 ** has fewer than 2 siblings (something which can only happen if the page
 ** is a root page or a child of a root page) then all available siblings
 ** participate in the balancing.
 **
-** The number of siblings of the page might be increased or decreased by 
-** one or two in an effort to keep pages nearly full but not over full. 
+** The number of siblings of the page might be increased or decreased by
+** one or two in an effort to keep pages nearly full but not over full.
 **
 ** Note that when this routine is called, some of the cells on the page
 ** might not actually be stored in MemPage.aData[]. This can happen
@@ -71039,7 +72445,7 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 ** inserted into or removed from the parent page (pParent). Doing so
 ** may cause the parent page to become overfull or underfull. If this
 ** happens, it is the responsibility of the caller to invoke the correct
-** balancing routine to fix this problem (see the balance() routine). 
+** balancing routine to fix this problem (see the balance() routine).
 **
 ** If this routine fails for any reason, it might leave the database
 ** in a corrupted state. So if this routine fails, the database should
@@ -71054,7 +72460,7 @@ static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
 ** enough for all overflow cells.
 **
-** If aOvflSpace is set to a null pointer, this function returns 
+** If aOvflSpace is set to a null pointer, this function returns
 ** SQLITE_NOMEM.
 */
 static int balance_nonroot(
@@ -71101,7 +72507,7 @@ static int balance_nonroot(
   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
 
   /* At this point pParent may have at most one overflow cell. And if
-  ** this overflow cell is present, it must be the cell with 
+  ** this overflow cell is present, it must be the cell with
   ** index iParentIdx. This scenario comes about when this function
   ** is called (indirectly) from sqlite3BtreeDelete().
   */
@@ -71113,11 +72519,11 @@ static int balance_nonroot(
   }
   assert( pParent->nFree>=0 );
 
-  /* Find the sibling pages to balance. Also locate the cells in pParent 
-  ** that divide the siblings. An attempt is made to find NN siblings on 
-  ** either side of pPage. More siblings are taken from one side, however, 
+  /* Find the sibling pages to balance. Also locate the cells in pParent
+  ** that divide the siblings. An attempt is made to find NN siblings on
+  ** either side of pPage. More siblings are taken from one side, however,
   ** if there are fewer than NN siblings on the other side. If pParent
-  ** has NB or fewer children then all children of pParent are taken.  
+  ** has NB or fewer children then all children of pParent are taken.
   **
   ** This loop also drops the divider cells from the parent page. This
   ** way, the remainder of the function does not have to deal with any
@@ -71129,7 +72535,7 @@ static int balance_nonroot(
     nxDiv = 0;
   }else{
     assert( bBulk==0 || bBulk==1 );
-    if( iParentIdx==0 ){                 
+    if( iParentIdx==0 ){
       nxDiv = 0;
     }else if( iParentIdx==i ){
       nxDiv = i-2+bBulk;
@@ -71175,7 +72581,7 @@ static int balance_nonroot(
       ** This is safe because dropping a cell only overwrites the first
       ** four bytes of it, and this function does not need the first
       ** four bytes of the divider cell. So the pointer is safe to use
-      ** later on.  
+      ** later on.
       **
       ** But not if we are in secure-delete mode. In secure-delete mode,
       ** the dropCell() routine will overwrite the entire cell with zeroes.
@@ -71341,7 +72747,7 @@ static int balance_nonroot(
   ** Figure out the number of pages needed to hold all b.nCell cells.
   ** Store this number in "k".  Also compute szNew[] which is the total
   ** size of all cells on the i-th page and cntNew[] which is the index
-  ** in b.apCell[] of the cell that divides page i from page i+1.  
+  ** in b.apCell[] of the cell that divides page i from page i+1.
   ** cntNew[k] should equal b.nCell.
   **
   ** Values computed by this block:
@@ -71351,7 +72757,7 @@ static int balance_nonroot(
   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
   **              the right of the i-th sibling page.
   ** usableSpace: Number of bytes of space available on each sibling.
-  ** 
+  **
   */
   usableSpace = pBt->usableSize - 12 + leafCorrection;
   for(i=k=0; i<nOld; i++, k++){
@@ -71505,15 +72911,15 @@ static int balance_nonroot(
   }
 
   /*
-  ** Reassign page numbers so that the new pages are in ascending order. 
+  ** Reassign page numbers so that the new pages are in ascending order.
   ** This helps to keep entries in the disk file in order so that a scan
-  ** of the table is closer to a linear scan through the file. That in turn 
+  ** of the table is closer to a linear scan through the file. That in turn
   ** helps the operating system to deliver pages from the disk more rapidly.
   **
-  ** An O(n^2) insertion sort algorithm is used, but since n is never more 
+  ** An O(n^2) insertion sort algorithm is used, but since n is never more
   ** than (NB+2) (a small constant), that should not be a problem.
   **
-  ** When NB==3, this one optimization makes the database about 25% faster 
+  ** When NB==3, this one optimization makes the database about 25% faster
   ** for large insertions and deletions.
   */
   for(i=0; i<nNew; i++){
@@ -71522,7 +72928,7 @@ static int balance_nonroot(
     for(j=0; j<i; j++){
       if( aPgno[j]==aPgno[i] ){
         /* This branch is taken if the set of sibling pages somehow contains
-        ** duplicate entries. This can happen if the database is corrupt. 
+        ** duplicate entries. This can happen if the database is corrupt.
         ** It would be simpler to detect this as part of the loop below, but
         ** we do the detection here in order to avoid populating the pager
         ** cache with two separate objects associated with the same
@@ -71568,14 +72974,14 @@ static int balance_nonroot(
   put4byte(pRight, apNew[nNew-1]->pgno);
 
   /* If the sibling pages are not leaves, ensure that the right-child pointer
-  ** of the right-most new sibling page is set to the value that was 
+  ** of the right-most new sibling page is set to the value that was
   ** originally in the same field of the right-most old sibling page. */
   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
   }
 
-  /* Make any required updates to pointer map entries associated with 
+  /* Make any required updates to pointer map entries associated with
   ** cells stored on sibling pages following the balance operation. Pointer
   ** map entries associated with divider cells are set by the insertCell()
   ** routine. The associated pointer map entries are:
@@ -71586,9 +72992,9 @@ static int balance_nonroot(
   **   b) if the sibling pages are not leaves, the child page associated
   **      with the cell.
   **
-  ** If the sibling pages are not leaves, then the pointer map entry 
-  ** associated with the right-child of each sibling may also need to be 
-  ** updated. This happens below, after the sibling pages have been 
+  ** If the sibling pages are not leaves, then the pointer map entry
+  ** associated with the right-child of each sibling may also need to be
+  ** updated. This happens below, after the sibling pages have been
   ** populated, not here.
   */
   if( ISAUTOVACUUM ){
@@ -71613,7 +73019,7 @@ static int balance_nonroot(
       }
 
       /* Cell pCell is destined for new sibling page pNew. Originally, it
-      ** was either part of sibling page iOld (possibly an overflow cell), 
+      ** was either part of sibling page iOld (possibly an overflow cell),
       ** or else the divider cell to the left of sibling page iOld. So,
       ** if sibling page iOld had the same page number as pNew, and if
       ** pCell really was a part of sibling page iOld (not a divider or
@@ -71649,9 +73055,9 @@ static int balance_nonroot(
     if( !pNew->leaf ){
       memcpy(&pNew->aData[8], pCell, 4);
     }else if( leafData ){
-      /* If the tree is a leaf-data tree, and the siblings are leaves, 
-      ** then there is no divider cell in b.apCell[]. Instead, the divider 
-      ** cell consists of the integer key for the right-most cell of 
+      /* If the tree is a leaf-data tree, and the siblings are leaves,
+      ** then there is no divider cell in b.apCell[]. Instead, the divider
+      ** cell consists of the integer key for the right-most cell of
       ** the sibling-page assembled above only.
       */
       CellInfo info;
@@ -71664,9 +73070,9 @@ static int balance_nonroot(
       pCell -= 4;
       /* Obscure case for non-leaf-data trees: If the cell at pCell was
       ** previously stored on a leaf node, and its reported size was 4
-      ** bytes, then it may actually be smaller than this 
+      ** bytes, then it may actually be smaller than this
       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
-      ** any cell). But it is important to pass the correct size to 
+      ** any cell). But it is important to pass the correct size to
       ** insertCell(), so reparse the cell now.
       **
       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
@@ -71758,8 +73164,8 @@ static int balance_nonroot(
     ** b-tree structure by one. This is described as the "balance-shallower"
     ** sub-algorithm in some documentation.
     **
-    ** If this is an auto-vacuum database, the call to copyNodeContent() 
-    ** sets all pointer-map entries corresponding to database image pages 
+    ** If this is an auto-vacuum database, the call to copyNodeContent()
+    ** sets all pointer-map entries corresponding to database image pages
     ** for which the pointer is stored within the content being copied.
     **
     ** It is critical that the child page be defragmented before being
@@ -71770,7 +73176,7 @@ static int balance_nonroot(
     assert( nNew==1 || CORRUPT_DB );
     rc = defragmentPage(apNew[0], -1);
     testcase( rc!=SQLITE_OK );
-    assert( apNew[0]->nFree == 
+    assert( apNew[0]->nFree ==
         (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
           - apNew[0]->nCell*2)
       || rc!=SQLITE_OK
@@ -71800,7 +73206,7 @@ static int balance_nonroot(
 #if 0
   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
     /* The ptrmapCheckPages() contains assert() statements that verify that
-    ** all pointer map pages are set correctly. This is helpful while 
+    ** all pointer map pages are set correctly. This is helpful while
     ** debugging. This is usually disabled because a corrupt database may
     ** cause an assert() statement to fail.  */
     ptrmapCheckPages(apNew, nNew);
@@ -71830,15 +73236,15 @@ balance_cleanup:
 **
 ** A new child page is allocated and the contents of the current root
 ** page, including overflow cells, are copied into the child. The root
-** page is then overwritten to make it an empty page with the right-child 
+** page is then overwritten to make it an empty page with the right-child
 ** pointer pointing to the new page.
 **
-** Before returning, all pointer-map entries corresponding to pages 
+** Before returning, all pointer-map entries corresponding to pages
 ** that the new child-page now contains pointers to are updated. The
 ** entry corresponding to the new right-child pointer of the root
 ** page is also updated.
 **
-** If successful, *ppChild is set to contain a reference to the child 
+** If successful, *ppChild is set to contain a reference to the child
 ** page and SQLITE_OK is returned. In this case the caller is required
 ** to call releasePage() on *ppChild exactly once. If an error occurs,
 ** an error code is returned and *ppChild is set to 0.
@@ -71852,7 +73258,7 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
   assert( pRoot->nOverflow>0 );
   assert( sqlite3_mutex_held(pBt->mutex) );
 
-  /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
+  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
   ** page that will become the new right-child of pPage. Copy the contents
   ** of the node stored on pRoot into the new child page.
   */
@@ -71891,9 +73297,33 @@ static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
 }
 
 /*
+** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
+** on the same B-tree as pCur.
+**
+** This can if a database is corrupt with two or more SQL tables
+** pointing to the same b-tree.  If an insert occurs on one SQL table
+** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
+** table linked to the same b-tree.  If the secondary insert causes a
+** rebalance, that can change content out from under the cursor on the
+** first SQL table, violating invariants on the first insert.
+*/
+static int anotherValidCursor(BtCursor *pCur){
+  BtCursor *pOther;
+  for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
+    if( pOther!=pCur
+     && pOther->eState==CURSOR_VALID
+     && pOther->pPage==pCur->pPage
+    ){
+      return SQLITE_CORRUPT_BKPT;
+    }
+  }
+  return SQLITE_OK;
+}
+
+/*
 ** The page that pCur currently points to has just been modified in
 ** some way. This function figures out if this modification means the
-** tree needs to be balanced, and if so calls the appropriate balancing 
+** tree needs to be balanced, and if so calls the appropriate balancing
 ** routine. Balancing routines are:
 **
 **   balance_quick()
@@ -71917,12 +73347,12 @@ static int balance(BtCursor *pCur){
     if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
       break;
     }else if( (iPage = pCur->iPage)==0 ){
-      if( pPage->nOverflow ){
+      if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
         /* The root page of the b-tree is overfull. In this case call the
         ** balance_deeper() function to create a new child for the root-page
         ** and copy the current contents of the root-page to it. The
         ** next iteration of the do-loop will balance the child page.
-        */ 
+        */
         assert( balance_deeper_called==0 );
         VVA_ONLY( balance_deeper_called++ );
         rc = balance_deeper(pPage, &pCur->apPage[1]);
@@ -71956,17 +73386,17 @@ static int balance(BtCursor *pCur){
           /* Call balance_quick() to create a new sibling of pPage on which
           ** to store the overflow cell. balance_quick() inserts a new cell
           ** into pParent, which may cause pParent overflow. If this
-          ** happens, the next iteration of the do-loop will balance pParent 
+          ** happens, the next iteration of the do-loop will balance pParent
           ** use either balance_nonroot() or balance_deeper(). Until this
           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
-          ** buffer. 
+          ** buffer.
           **
           ** The purpose of the following assert() is to check that only a
           ** single call to balance_quick() is made for each call to this
           ** function. If this were not verified, a subtle bug involving reuse
           ** of the aBalanceQuickSpace[] might sneak in.
           */
-          assert( balance_quick_called==0 ); 
+          assert( balance_quick_called==0 );
           VVA_ONLY( balance_quick_called++ );
           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
         }else
@@ -71977,15 +73407,15 @@ static int balance(BtCursor *pCur){
           ** modifying the contents of pParent, which may cause pParent to
           ** become overfull or underfull. The next iteration of the do-loop
           ** will balance the parent page to correct this.
-          ** 
+          **
           ** If the parent page becomes overfull, the overflow cell or cells
-          ** are stored in the pSpace buffer allocated immediately below. 
+          ** are stored in the pSpace buffer allocated immediately below.
           ** A subsequent iteration of the do-loop will deal with this by
           ** calling balance_nonroot() (balance_deeper() may be called first,
           ** but it doesn't deal with overflow cells - just moves them to a
-          ** different page). Once this subsequent call to balance_nonroot() 
+          ** different page). Once this subsequent call to balance_nonroot()
           ** has completed, it is safe to release the pSpace buffer used by
-          ** the previous call, as the overflow cell data will have been 
+          ** the previous call, as the overflow cell data will have been
           ** copied either into the body of a database page or into the new
           ** pSpace buffer passed to the latter call to balance_nonroot().
           */
@@ -71993,9 +73423,9 @@ static int balance(BtCursor *pCur){
           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
                                pCur->hints&BTREE_BULKLOAD);
           if( pFree ){
-            /* If pFree is not NULL, it points to the pSpace buffer used 
+            /* If pFree is not NULL, it points to the pSpace buffer used
             ** by a previous call to balance_nonroot(). Its contents are
-            ** now stored either on real database pages or within the 
+            ** now stored either on real database pages or within the
             ** new pSpace buffer, so it may be safely freed here. */
             sqlite3PageFree(pFree);
           }
@@ -72114,7 +73544,7 @@ static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
     if( rc ) return rc;
     iOffset += ovflPageSize;
   }while( iOffset<nTotal );
-  return SQLITE_OK;    
+  return SQLITE_OK;
 }
 
 
@@ -72130,7 +73560,7 @@ static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
 ** hold the content of the row.
 **
 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
-** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The 
+** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
 ** pX.pData,nData,nZero fields must be zero.
 **
 ** If the seekResult parameter is non-zero, then a successful call to
@@ -72188,8 +73618,8 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   **
   ** In some cases, the call to btreeMoveto() below is a no-op. For
   ** example, when inserting data into a table with auto-generated integer
-  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
-  ** integer key to use. It then calls this function to actually insert the 
+  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
+  ** integer key to use. It then calls this function to actually insert the
   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
   ** that the cursor is already where it needs to be and returns without
   ** doing any work. To avoid thwarting these optimizations, it is important
@@ -72202,18 +73632,17 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
 
   if( pCur->pKeyInfo==0 ){
     assert( pX->pKey==0 );
-    /* If this is an insert into a table b-tree, invalidate any incrblob 
+    /* If this is an insert into a table b-tree, invalidate any incrblob
     ** cursors open on the row being replaced */
     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
 
-    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
+    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
     ** to a row with the same key as the new entry being inserted.
     */
 #ifdef SQLITE_DEBUG
     if( flags & BTREE_SAVEPOSITION ){
       assert( pCur->curFlags & BTCF_ValidNKey );
       assert( pX->nKey==pCur->info.nKey );
-      assert( pCur->info.nSize!=0 );
       assert( loc==0 );
     }
 #endif
@@ -72244,7 +73673,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   }else{
     /* This is an index or a WITHOUT ROWID table */
 
-    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing 
+    /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
     ** to a row with the same key as the new entry being inserted.
     */
     assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
@@ -72288,13 +73717,19 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
     }
 
   }
-  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
+  assert( pCur->eState==CURSOR_VALID
+       || (pCur->eState==CURSOR_INVALID && loc)
+       || CORRUPT_DB );
 
   pPage = pCur->pPage;
   assert( pPage->intKey || pX->nKey>=0 );
   assert( pPage->leaf || !pPage->intKey );
   if( pPage->nFree<0 ){
-    rc = btreeComputeFreeSpace(pPage);
+    if( pCur->eState>CURSOR_INVALID ){
+      rc = SQLITE_CORRUPT_BKPT;
+    }else{
+      rc = btreeComputeFreeSpace(pPage);
+    }
     if( rc ) return rc;
   }
 
@@ -72323,14 +73758,14 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
     rc = clearCell(pPage, oldCell, &info);
     testcase( pCur->curFlags & BTCF_ValidOvfl );
     invalidateOverflowCache(pCur);
-    if( info.nSize==szNew && info.nLocal==info.nPayload 
+    if( info.nSize==szNew && info.nLocal==info.nPayload
      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
     ){
       /* Overwrite the old cell with the new if they are the same size.
       ** We could also try to do this if the old cell is smaller, then add
       ** the leftover space to the free list.  But experiments show that
       ** doing that is no faster then skipping this optimization and just
-      ** calling dropCell() and insertCell(). 
+      ** calling dropCell() and insertCell().
       **
       ** This optimization cannot be used on an autovacuum database if the
       ** new entry uses overflow pages, as the insertCell() call below is
@@ -72358,7 +73793,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
 
-  /* If no error has occurred and pPage has an overflow cell, call balance() 
+  /* If no error has occurred and pPage has an overflow cell, call balance()
   ** to redistribute the cells within the tree. Since balance() may move
   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
   ** variables.
@@ -72385,7 +73820,7 @@ SQLITE_PRIVATE int sqlite3BtreeInsert(
     rc = balance(pCur);
 
     /* Must make sure nOverflow is reset to zero even if the balance()
-    ** fails. Internal data structure corruption will result otherwise. 
+    ** fails. Internal data structure corruption will result otherwise.
     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
     ** from trying to save the current position of the cursor.  */
     pCur->pPage->nOverflow = 0;
@@ -72412,7 +73847,7 @@ end_insert:
 }
 
 /*
-** Delete the entry that the cursor is pointing to. 
+** Delete the entry that the cursor is pointing to.
 **
 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
 ** the cursor is left pointing at an arbitrary location after the delete.
@@ -72430,12 +73865,12 @@ end_insert:
 */
 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   Btree *p = pCur->pBtree;
-  BtShared *pBt = p->pBt;              
+  BtShared *pBt = p->pBt;
   int rc;                              /* Return code */
   MemPage *pPage;                      /* Page to delete cell from */
   unsigned char *pCell;                /* Pointer to cell to delete */
   int iCellIdx;                        /* Index of cell to delete */
-  int iCellDepth;                      /* Depth of node containing pCell */ 
+  int iCellDepth;                      /* Depth of node containing pCell */
   CellInfo info;                       /* Size of the cell being deleted */
   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
@@ -72462,14 +73897,14 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   /* If the bPreserve flag is set to true, then the cursor position must
   ** be preserved following this delete operation. If the current delete
   ** will cause a b-tree rebalance, then this is done by saving the cursor
-  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 
-  ** returning. 
+  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
+  ** returning.
   **
   ** Or, if the current delete will not cause a rebalance, then the cursor
   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
   ** before or after the deleted entry. In this case set bSkipnext to true.  */
   if( bPreserve ){
-    if( !pPage->leaf 
+    if( !pPage->leaf
      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
      || pPage->nCell==1  /* See dbfuzz001.test for a test case */
     ){
@@ -72564,7 +73999,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
   ** on the leaf node first. If the balance proceeds far enough up the
   ** tree that we can be sure that any problem in the internal node has
   ** been corrected, so be it. Otherwise, after balancing the leaf node,
-  ** walk the cursor up the tree to the internal node and balance it as 
+  ** walk the cursor up the tree to the internal node and balance it as
   ** well.  */
   rc = balance(pCur);
   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
@@ -72612,7 +74047,7 @@ SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
 **     BTREE_ZERODATA                  Used for SQL indices
 */
-static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
+static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
   BtShared *pBt = p->pBt;
   MemPage *pRoot;
   Pgno pgnoRoot;
@@ -72645,6 +74080,9 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
     ** created so far, so the new root-page is (meta[3]+1).
     */
     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
+    if( pgnoRoot>btreePagecount(pBt) ){
+      return SQLITE_CORRUPT_BKPT;
+    }
     pgnoRoot++;
 
     /* The new root-page may not be allocated on a pointer-map page, or the
@@ -72654,8 +74092,7 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
       pgnoRoot++;
     }
-    assert( pgnoRoot>=3 || CORRUPT_DB );
-    testcase( pgnoRoot<3 );
+    assert( pgnoRoot>=3 );
 
     /* Allocate a page. The page that currently resides at pgnoRoot will
     ** be moved to the allocated page (unless the allocated page happens
@@ -72718,7 +74155,7 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
       }
     }else{
       pRoot = pPageMove;
-    } 
+    }
 
     /* Update the pointer-map and meta-data with the new root-page number. */
     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
@@ -72752,10 +74189,10 @@ static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
   zeroPage(pRoot, ptfFlags);
   sqlite3PagerUnref(pRoot->pDbPage);
   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
-  *piTable = (int)pgnoRoot;
+  *piTable = pgnoRoot;
   return SQLITE_OK;
 }
-SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
+SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
   int rc;
   sqlite3BtreeEnter(p);
   rc = btreeCreateTable(p, piTable, flags);
@@ -72871,12 +74308,12 @@ SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
 ** cursors on the table.
 **
 ** If AUTOVACUUM is enabled and the page at iTable is not the last
-** root page in the database file, then the last root page 
+** root page in the database file, then the last root page
 ** in the database file is moved into the slot formerly occupied by
 ** iTable and that last slot formerly occupied by the last root page
 ** is added to the freelist instead of iTable.  In this say, all
 ** root pages are kept at the beginning of the database file, which
-** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
+** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
 ** page number that used to be the last root page in the file before
 ** the move.  If no page gets moved, *piMoved is set to 0.
 ** The last root page is recorded in meta[3] and the value of
@@ -72914,7 +74351,7 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
 
     if( iTable==maxRootPgno ){
       /* If the table being dropped is the table with the largest root-page
-      ** number in the database, put the root page on the free list. 
+      ** number in the database, put the root page on the free list.
       */
       freePage(pPage, &rc);
       releasePage(pPage);
@@ -72923,7 +74360,7 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
       }
     }else{
       /* The table being dropped does not have the largest root-page
-      ** number in the database. So move the page that does into the 
+      ** number in the database. So move the page that does into the
       ** gap left by the deleted root-page.
       */
       MemPage *pMove;
@@ -72965,7 +74402,7 @@ static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
     releasePage(pPage);
   }
 #endif
-  return rc;  
+  return rc;
 }
 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
   int rc;
@@ -72984,7 +74421,7 @@ SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
 ** is the number of free pages currently in the database.  Meta[1]
 ** through meta[15] are available for use by higher layers.  Meta[0]
 ** is read-only, the others are read/write.
-** 
+**
 ** The schema layer numbers meta values differently.  At the schema
 ** layer (and the SetCookie and ReadCookie opcodes) the number of
 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
@@ -73001,7 +74438,7 @@ SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
 
   sqlite3BtreeEnter(p);
   assert( p->inTrans>TRANS_NONE );
-  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
+  assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
   assert( pBt->pPage1 );
   assert( idx>=0 && idx<=15 );
 
@@ -73050,16 +74487,15 @@ SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
   return rc;
 }
 
-#ifndef SQLITE_OMIT_BTREECOUNT
 /*
 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
 ** number of entries in the b-tree and write the result to *pnEntry.
 **
-** SQLITE_OK is returned if the operation is successfully executed. 
+** SQLITE_OK is returned if the operation is successfully executed.
 ** Otherwise, if an error is encountered (i.e. an IO error or database
 ** corruption) an SQLite error code is returned.
 */
-SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
+SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
   i64 nEntry = 0;                      /* Value to return in *pnEntry */
   int rc;                              /* Return code */
 
@@ -73070,13 +74506,13 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   }
 
   /* Unless an error occurs, the following loop runs one iteration for each
-  ** page in the B-Tree structure (not including overflow pages). 
+  ** page in the B-Tree structure (not including overflow pages).
   */
-  while( rc==SQLITE_OK ){
+  while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
     int iIdx;                          /* Index of child node in parent */
     MemPage *pPage;                    /* Current page of the b-tree */
 
-    /* If this is a leaf page or the tree is not an int-key tree, then 
+    /* If this is a leaf page or the tree is not an int-key tree, then
     ** this page contains countable entries. Increment the entry counter
     ** accordingly.
     */
@@ -73085,7 +74521,7 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
       nEntry += pPage->nCell;
     }
 
-    /* pPage is a leaf node. This loop navigates the cursor so that it 
+    /* pPage is a leaf node. This loop navigates the cursor so that it
     ** points to the first interior cell that it points to the parent of
     ** the next page in the tree that has not yet been visited. The
     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
@@ -73109,7 +74545,7 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
       pPage = pCur->pPage;
     }
 
-    /* Descend to the child node of the cell that the cursor currently 
+    /* Descend to the child node of the cell that the cursor currently
     ** points at. This is the right-child if (iIdx==pPage->nCell).
     */
     iIdx = pCur->ix;
@@ -73123,7 +74559,6 @@ SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
   /* An error has occurred. Return an error code. */
   return rc;
 }
-#endif
 
 /*
 ** Return the pager associated with a BTree.  This routine is used for
@@ -73156,7 +74591,7 @@ static void checkAppendMsg(
   sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
   va_end(ap);
   if( pCheck->errMsg.accError==SQLITE_NOMEM ){
-    pCheck->mallocFailed = 1;
+    pCheck->bOomFault = 1;
   }
 }
 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
@@ -73198,13 +74633,14 @@ static int checkRef(IntegrityCk *pCheck, Pgno iPage){
     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
     return 1;
   }
+  if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
   setPageReferenced(pCheck, iPage);
   return 0;
 }
 
 #ifndef SQLITE_OMIT_AUTOVACUUM
 /*
-** Check that the entry in the pointer-map for page iChild maps to 
+** Check that the entry in the pointer-map for page iChild maps to
 ** page iParent, pointer type ptrType. If not, append an error message
 ** to pCheck.
 */
@@ -73220,14 +74656,14 @@ static void checkPtrmap(
 
   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
   if( rc!=SQLITE_OK ){
-    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
+    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
     return;
   }
 
   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
     checkAppendMsg(pCheck,
-      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
+      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
   }
 }
@@ -73240,7 +74676,7 @@ static void checkPtrmap(
 static void checkList(
   IntegrityCk *pCheck,  /* Integrity checking context */
   int isFreeList,       /* True for a freelist.  False for overflow page list */
-  int iPage,            /* Page number for first page in the list */
+  Pgno iPage,           /* Page number for first page in the list */
   u32 N                 /* Expected number of pages in the list */
 ){
   int i;
@@ -73322,7 +74758,7 @@ static void checkList(
 ** property.
 **
 ** This heap is used for cell overlap and coverage testing.  Each u32
-** entry represents the span of a cell or freeblock on a btree page.  
+** entry represents the span of a cell or freeblock on a btree page.
 ** The upper 16 bits are the index of the first byte of a range and the
 ** lower 16 bits are the index of the last byte of that range.
 */
@@ -73352,7 +74788,7 @@ static int btreeHeapPull(u32 *aHeap, u32 *pOut){
     aHeap[j] = x;
     i = j;
   }
-  return 1;  
+  return 1;
 }
 
 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
@@ -73360,7 +74796,7 @@ static int btreeHeapPull(u32 *aHeap, u32 *pOut){
 ** Do various sanity checks on a single page of a tree.  Return
 ** the tree depth.  Root pages return 0.  Parents of root pages
 ** return 1, and so forth.
-** 
+**
 ** These checks are done:
 **
 **      1.  Make sure that cells and freeblocks do not overlap
@@ -73372,7 +74808,7 @@ static int btreeHeapPull(u32 *aHeap, u32 *pOut){
 */
 static int checkTreePage(
   IntegrityCk *pCheck,  /* Context for the sanity check */
-  int iPage,            /* Page number of the page to check */
+  Pgno iPage,           /* Page number of the page to check */
   i64 *piMinKey,        /* Write minimum integer primary key here */
   i64 maxKey            /* Error if integer primary key greater than this */
 ){
@@ -73408,9 +74844,9 @@ static int checkTreePage(
   usableSize = pBt->usableSize;
   if( iPage==0 ) return 0;
   if( checkRef(pCheck, iPage) ) return 0;
-  pCheck->zPfx = "Page %d: ";
+  pCheck->zPfx = "Page %u: ";
   pCheck->v1 = iPage;
-  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
+  if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
     checkAppendMsg(pCheck,
        "unable to get the page. error code=%d", rc);
     goto end_of_check;
@@ -73435,7 +74871,7 @@ static int checkTreePage(
   hdr = pPage->hdrOffset;
 
   /* Set up for cell analysis */
-  pCheck->zPfx = "On tree page %d cell %d: ";
+  pCheck->zPfx = "On tree page %u cell %d: ";
   contentOffset = get2byteNotZero(&data[hdr+5]);
   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
 
@@ -73455,7 +74891,7 @@ static int checkTreePage(
     pgno = get4byte(&data[hdr+8]);
 #ifndef SQLITE_OMIT_AUTOVACUUM
     if( pBt->autoVacuum ){
-      pCheck->zPfx = "On page %d at right child: ";
+      pCheck->zPfx = "On page %u at right child: ";
       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
     }
 #endif
@@ -73558,7 +74994,7 @@ static int checkTreePage(
     **
     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
     ** is the offset of the first freeblock, or zero if there are no
-    ** freeblocks on the page. 
+    ** freeblocks on the page.
     */
     i = get2byte(&data[hdr+1]);
     while( i>0 ){
@@ -73578,13 +75014,13 @@ static int checkTreePage(
       assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
       i = j;
     }
-    /* Analyze the min-heap looking for overlap between cells and/or 
+    /* Analyze the min-heap looking for overlap between cells and/or
     ** freeblocks, and counting the number of untracked bytes in nFrag.
-    ** 
+    **
     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
     ** There is an implied first entry the covers the page header, the cell
     ** pointer index, and the gap between the cell pointer index and the start
-    ** of cell content.  
+    ** of cell content.
     **
     ** The loop below pulls entries from the min-heap in order and compares
     ** the start_address against the previous end_address.  If there is an
@@ -73596,7 +75032,7 @@ static int checkTreePage(
     while( btreeHeapPull(heap,&x) ){
       if( (prev&0xffff)>=(x>>16) ){
         checkAppendMsg(pCheck,
-          "Multiple uses for byte %u of page %d", x>>16, iPage);
+          "Multiple uses for byte %u of page %u", x>>16, iPage);
         break;
       }else{
         nFrag += (x>>16) - (prev&0xffff) - 1;
@@ -73611,7 +75047,7 @@ static int checkTreePage(
     */
     if( heap[0]==0 && nFrag!=data[hdr+7] ){
       checkAppendMsg(pCheck,
-          "Fragmentation of %d bytes reported as %d on page %d",
+          "Fragmentation of %d bytes reported as %d on page %u",
           nFrag, data[hdr+7], iPage);
     }
   }
@@ -73639,10 +75075,20 @@ end_of_check:
 ** allocation errors,  an error message held in memory obtained from
 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
 ** returned.  If a memory allocation error occurs, NULL is returned.
+**
+** If the first entry in aRoot[] is 0, that indicates that the list of
+** root pages is incomplete.  This is a "partial integrity-check".  This
+** happens when performing an integrity check on a single table.  The
+** zero is skipped, of course.  But in addition, the freelist checks
+** and the checks to make sure every page is referenced are also skipped,
+** since obviously it is not possible to know which pages are covered by
+** the unverified btrees.  Except, if aRoot[1] is 1, then the freelist
+** checks are still performed.
 */
 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
+  sqlite3 *db,  /* Database connection that is running the check */
   Btree *p,     /* The btree to be checked */
-  int *aRoot,   /* An array of root pages numbers for individual trees */
+  Pgno *aRoot,  /* An array of root pages numbers for individual trees */
   int nRoot,    /* Number of entries in aRoot[] */
   int mxErr,    /* Stop reporting errors after this many */
   int *pnErr    /* Write number of errors seen to this variable */
@@ -73652,18 +75098,29 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
   BtShared *pBt = p->pBt;
   u64 savedDbFlags = pBt->db->flags;
   char zErr[100];
+  int bPartial = 0;            /* True if not checking all btrees */
+  int bCkFreelist = 1;         /* True to scan the freelist */
   VVA_ONLY( int nRef );
+  assert( nRoot>0 );
+
+  /* aRoot[0]==0 means this is a partial check */
+  if( aRoot[0]==0 ){
+    assert( nRoot>1 );
+    bPartial = 1;
+    if( aRoot[1]!=1 ) bCkFreelist = 0;
+  }
 
   sqlite3BtreeEnter(p);
   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
   assert( nRef>=0 );
+  sCheck.db = db;
   sCheck.pBt = pBt;
   sCheck.pPager = pBt->pPager;
   sCheck.nPage = btreePagecount(sCheck.pBt);
   sCheck.mxErr = mxErr;
   sCheck.nErr = 0;
-  sCheck.mallocFailed = 0;
+  sCheck.bOomFault = 0;
   sCheck.zPfx = 0;
   sCheck.v1 = 0;
   sCheck.v2 = 0;
@@ -73677,12 +75134,12 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 
   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
   if( !sCheck.aPgRef ){
-    sCheck.mallocFailed = 1;
+    sCheck.bOomFault = 1;
     goto integrity_ck_cleanup;
   }
   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
   if( sCheck.heap==0 ){
-    sCheck.mallocFailed = 1;
+    sCheck.bOomFault = 1;
     goto integrity_ck_cleanup;
   }
 
@@ -73691,29 +75148,33 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 
   /* Check the integrity of the freelist
   */
-  sCheck.zPfx = "Main freelist: ";
-  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
-            get4byte(&pBt->pPage1->aData[36]));
-  sCheck.zPfx = 0;
+  if( bCkFreelist ){
+    sCheck.zPfx = "Main freelist: ";
+    checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
+              get4byte(&pBt->pPage1->aData[36]));
+    sCheck.zPfx = 0;
+  }
 
   /* Check all the tables.
   */
 #ifndef SQLITE_OMIT_AUTOVACUUM
-  if( pBt->autoVacuum ){
-    int mx = 0;
-    int mxInHdr;
-    for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
-    mxInHdr = get4byte(&pBt->pPage1->aData[52]);
-    if( mx!=mxInHdr ){
+  if( !bPartial ){
+    if( pBt->autoVacuum ){
+      Pgno mx = 0;
+      Pgno mxInHdr;
+      for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
+      mxInHdr = get4byte(&pBt->pPage1->aData[52]);
+      if( mx!=mxInHdr ){
+        checkAppendMsg(&sCheck,
+          "max rootpage (%d) disagrees with header (%d)",
+          mx, mxInHdr
+        );
+      }
+    }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
       checkAppendMsg(&sCheck,
-        "max rootpage (%d) disagrees with header (%d)",
-        mx, mxInHdr
+        "incremental_vacuum enabled with a max rootpage of zero"
       );
     }
-  }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
-    checkAppendMsg(&sCheck,
-      "incremental_vacuum enabled with a max rootpage of zero"
-    );
   }
 #endif
   testcase( pBt->db->flags & SQLITE_CellSizeCk );
@@ -73722,7 +75183,7 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
     i64 notUsed;
     if( aRoot[i]==0 ) continue;
 #ifndef SQLITE_OMIT_AUTOVACUUM
-    if( pBt->autoVacuum && aRoot[i]>1 ){
+    if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
     }
 #endif
@@ -73732,24 +75193,26 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 
   /* Make sure every page in the file is referenced
   */
-  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
+  if( !bPartial ){
+    for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
 #ifdef SQLITE_OMIT_AUTOVACUUM
-    if( getPageReferenced(&sCheck, i)==0 ){
-      checkAppendMsg(&sCheck, "Page %d is never used", i);
-    }
+      if( getPageReferenced(&sCheck, i)==0 ){
+        checkAppendMsg(&sCheck, "Page %d is never used", i);
+      }
 #else
-    /* If the database supports auto-vacuum, make sure no tables contain
-    ** references to pointer-map pages.
-    */
-    if( getPageReferenced(&sCheck, i)==0 && 
-       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
-      checkAppendMsg(&sCheck, "Page %d is never used", i);
-    }
-    if( getPageReferenced(&sCheck, i)!=0 && 
-       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
-      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
-    }
+      /* If the database supports auto-vacuum, make sure no tables contain
+      ** references to pointer-map pages.
+      */
+      if( getPageReferenced(&sCheck, i)==0 &&
+         (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
+        checkAppendMsg(&sCheck, "Page %d is never used", i);
+      }
+      if( getPageReferenced(&sCheck, i)!=0 &&
+         (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
+        checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
+      }
 #endif
+    }
   }
 
   /* Clean  up and report errors.
@@ -73757,7 +75220,7 @@ SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
 integrity_ck_cleanup:
   sqlite3PageFree(sCheck.heap);
   sqlite3_free(sCheck.aPgRef);
-  if( sCheck.mallocFailed ){
+  if( sCheck.bOomFault ){
     sqlite3_str_reset(&sCheck.errMsg);
     sCheck.nErr++;
   }
@@ -73796,18 +75259,19 @@ SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
 }
 
 /*
-** Return non-zero if a transaction is active.
+** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
+** to describe the current transaction state of Btree p.
 */
-SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
+SQLITE_PRIVATE int sqlite3BtreeTxnState(Btree *p){
   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
-  return (p && (p->inTrans==TRANS_WRITE));
+  return p ? p->inTrans : 0;
 }
 
 #ifndef SQLITE_OMIT_WAL
 /*
 ** Run a checkpoint on the Btree passed as the first argument.
 **
-** Return SQLITE_LOCKED if this or any other connection has an open 
+** Return SQLITE_LOCKED if this or any other connection has an open
 ** transaction on the shared-cache the argument Btree is connected to.
 **
 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
@@ -73829,14 +75293,8 @@ SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *
 #endif
 
 /*
-** Return non-zero if a read (or write) transaction is active.
+** Return true if there is currently a backup running on Btree p.
 */
-SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
-  assert( p );
-  assert( sqlite3_mutex_held(p->db->mutex) );
-  return p->inTrans!=TRANS_NONE;
-}
-
 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
   assert( p );
   assert( sqlite3_mutex_held(p->db->mutex) );
@@ -73846,20 +75304,20 @@ SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
 /*
 ** This function returns a pointer to a blob of memory associated with
 ** a single shared-btree. The memory is used by client code for its own
-** purposes (for example, to store a high-level schema associated with 
+** purposes (for example, to store a high-level schema associated with
 ** the shared-btree). The btree layer manages reference counting issues.
 **
 ** The first time this is called on a shared-btree, nBytes bytes of memory
-** are allocated, zeroed, and returned to the caller. For each subsequent 
+** are allocated, zeroed, and returned to the caller. For each subsequent
 ** call the nBytes parameter is ignored and a pointer to the same blob
-** of memory returned. 
+** of memory returned.
 **
 ** If the nBytes parameter is 0 and the blob of memory has not yet been
 ** allocated, a null pointer is returned. If the blob has already been
 ** allocated, it is returned as normal.
 **
-** Just before the shared-btree is closed, the function passed as the 
-** xFree argument when the memory allocation was made is invoked on the 
+** Just before the shared-btree is closed, the function passed as the
+** xFree argument when the memory allocation was made is invoked on the
 ** blob of allocated memory. The xFree function should not call sqlite3_free()
 ** on the memory, the btree layer does that.
 */
@@ -73875,15 +75333,15 @@ SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void
 }
 
 /*
-** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
-** btree as the argument handle holds an exclusive lock on the 
-** sqlite_master table. Otherwise SQLITE_OK.
+** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
+** btree as the argument handle holds an exclusive lock on the
+** sqlite_schema table. Otherwise SQLITE_OK.
 */
 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
   int rc;
   assert( sqlite3_mutex_held(p->db->mutex) );
   sqlite3BtreeEnter(p);
-  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
+  rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
   sqlite3BtreeLeave(p);
   return rc;
@@ -73917,11 +75375,11 @@ SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
 
 #ifndef SQLITE_OMIT_INCRBLOB
 /*
-** Argument pCsr must be a cursor opened for writing on an 
-** INTKEY table currently pointing at a valid table entry. 
+** Argument pCsr must be a cursor opened for writing on an
+** INTKEY table currently pointing at a valid table entry.
 ** This function modifies the data stored as part of that entry.
 **
-** Only the data content may only be modified, it is not possible to 
+** Only the data content may only be modified, it is not possible to
 ** change the length of the data stored. If this function is called with
 ** parameters that attempt to write past the end of the existing data,
 ** no modifications are made and SQLITE_CORRUPT is returned.
@@ -73952,7 +75410,7 @@ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void
   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
   assert( rc==SQLITE_OK );
 
-  /* Check some assumptions: 
+  /* Check some assumptions:
   **   (a) the cursor is open for writing,
   **   (b) there is a read/write transaction open,
   **   (c) the connection holds a write-lock on the table (if required),
@@ -73971,7 +75429,7 @@ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void
   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
 }
 
-/* 
+/*
 ** Mark this cursor as an incremental blob cursor.
 */
 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
@@ -73981,14 +75439,14 @@ SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
 #endif
 
 /*
-** Set both the "read version" (single byte at byte offset 18) and 
+** Set both the "read version" (single byte at byte offset 18) and
 ** "write version" (single byte at byte offset 19) fields in the database
 ** header to iVersion.
 */
 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
   BtShared *pBt = pBtree->pBt;
   int rc;                         /* Return code */
+
   assert( iVersion==1 || iVersion==2 );
 
   /* If setting the version fields to 1, do not automatically open the
@@ -74046,7 +75504,7 @@ SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
 
 /*
 ** Return the number of connections to the BtShared object accessed by
-** the Btree handle passed as the only argument. For private caches 
+** the Btree handle passed as the only argument. For private caches
 ** this is always 1. For shared caches it may be 1 or greater.
 */
 SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
@@ -74068,7 +75526,7 @@ SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
 **    May you share freely, never taking more than you give.
 **
 *************************************************************************
-** This file contains the implementation of the sqlite3_backup_XXX() 
+** This file contains the implementation of the sqlite3_backup_XXX()
 ** API functions and the related features.
 */
 /* #include "sqliteInt.h" */
@@ -74105,15 +75563,15 @@ struct sqlite3_backup {
 **   Once it has been created using backup_init(), a single sqlite3_backup
 **   structure may be accessed via two groups of thread-safe entry points:
 **
-**     * Via the sqlite3_backup_XXX() API function backup_step() and 
+**     * Via the sqlite3_backup_XXX() API function backup_step() and
 **       backup_finish(). Both these functions obtain the source database
-**       handle mutex and the mutex associated with the source BtShared 
+**       handle mutex and the mutex associated with the source BtShared
 **       structure, in that order.
 **
 **     * Via the BackupUpdate() and BackupRestart() functions, which are
 **       invoked by the pager layer to report various state changes in
 **       the page cache associated with the source database. The mutex
-**       associated with the source database BtShared structure will always 
+**       associated with the source database BtShared structure will always
 **       be held when either of these functions are invoked.
 **
 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
@@ -74134,8 +75592,8 @@ struct sqlite3_backup {
 ** in connection handle pDb. If such a database cannot be found, return
 ** a NULL pointer and write an error message to pErrorDb.
 **
-** If the "temp" database is requested, it may need to be opened by this 
-** function. If an error occurs while doing so, return 0 and write an 
+** If the "temp" database is requested, it may need to be opened by this
+** function. If an error occurs while doing so, return 0 and write an
 ** error message to pErrorDb.
 */
 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
@@ -74171,18 +75629,18 @@ static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
 */
 static int setDestPgsz(sqlite3_backup *p){
   int rc;
-  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
+  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
   return rc;
 }
 
 /*
 ** Check that there is no open read-transaction on the b-tree passed as the
 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
-** is an open read-transaction, return SQLITE_ERROR and leave an error 
+** is an open read-transaction, return SQLITE_ERROR and leave an error
 ** message in database handle db.
 */
 static int checkReadTransaction(sqlite3 *db, Btree *p){
-  if( sqlite3BtreeIsInReadTrans(p) ){
+  if( sqlite3BtreeTxnState(p)!=SQLITE_TXN_NONE ){
     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
     return SQLITE_ERROR;
   }
@@ -74248,13 +75706,13 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init(
     p->iNext = 1;
     p->isAttached = 0;
 
-    if( 0==p->pSrc || 0==p->pDest 
-     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
+    if( 0==p->pSrc || 0==p->pDest
+     || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
      ){
       /* One (or both) of the named databases did not exist or an OOM
       ** error was hit. Or there is a transaction open on the destination
-      ** database. The error has already been written into the pDestDb 
-      ** handle. All that is left to do here is free the sqlite3_backup 
+      ** database. The error has already been written into the pDestDb
+      ** handle. All that is left to do here is free the sqlite3_backup
       ** structure.  */
       sqlite3_free(p);
       p = 0;
@@ -74270,7 +75728,7 @@ SQLITE_API sqlite3_backup *sqlite3_backup_init(
 }
 
 /*
-** Argument rc is an SQLite error code. Return true if this error is 
+** Argument rc is an SQLite error code. Return true if this error is
 ** considered fatal if encountered during a backup operation. All errors
 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
 */
@@ -74279,8 +75737,8 @@ static int isFatalError(int rc){
 }
 
 /*
-** Parameter zSrcData points to a buffer containing the data for 
-** page iSrcPg from the source database. Copy this data into the 
+** Parameter zSrcData points to a buffer containing the data for
+** page iSrcPg from the source database. Copy this data into the
 ** destination database.
 */
 static int backupOnePage(
@@ -74294,13 +75752,6 @@ static int backupOnePage(
   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
-#ifdef SQLITE_HAS_CODEC
-  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
-  ** guaranteed that the shared-mutex is held by this thread, handle
-  ** p->pSrc may not actually be the owner.  */
-  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
-  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
-#endif
   int rc = SQLITE_OK;
   i64 iOff;
 
@@ -74311,33 +75762,13 @@ static int backupOnePage(
   assert( zSrcData );
 
   /* Catch the case where the destination is an in-memory database and the
-  ** page sizes of the source and destination differ. 
+  ** page sizes of the source and destination differ.
   */
   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
     rc = SQLITE_READONLY;
   }
 
-#ifdef SQLITE_HAS_CODEC
-  /* Backup is not possible if the page size of the destination is changing
-  ** and a codec is in use.
-  */
-  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
-    rc = SQLITE_READONLY;
-  }
-
-  /* Backup is not possible if the number of bytes of reserve space differ
-  ** between source and destination.  If there is a difference, try to
-  ** fix the destination to agree with the source.  If that is not possible,
-  ** then the backup cannot proceed.
-  */
-  if( nSrcReserve!=nDestReserve ){
-    u32 newPgsz = nSrcPgsz;
-    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
-    if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY;
-  }
-#endif
-
-  /* This loop runs once for each destination page spanned by the source 
+  /* This loop runs once for each destination page spanned by the source
   ** page. For each iteration, variable iOff is set to the byte offset
   ** of the destination page.
   */
@@ -74356,7 +75787,7 @@ static int backupOnePage(
       ** Then clear the Btree layer MemPage.isInit flag. Both this module
       ** and the pager code use this trick (clearing the first byte
       ** of the page 'extra' space to invalidate the Btree layers
-      ** cached parse of the page). MemPage.isInit is marked 
+      ** cached parse of the page). MemPage.isInit is marked
       ** "MUST BE FIRST" for this purpose.
       */
       memcpy(zOut, zIn, nCopy);
@@ -74376,7 +75807,7 @@ static int backupOnePage(
 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
 ** this function is a no-op.
 **
-** Return SQLITE_OK if everything is successful, or an SQLite error 
+** Return SQLITE_OK if everything is successful, or an SQLite error
 ** code if an error occurs.
 */
 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
@@ -74440,7 +75871,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
     ** one now. If a transaction is opened here, then it will be closed
     ** before this function exits.
     */
-    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
+    if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
       rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
       bCloseTrans = 1;
     }
@@ -74458,7 +75889,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
     /* Lock the destination database, if it is not locked already. */
     if( SQLITE_OK==rc && p->bDestLocked==0
      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
-                                                (int*)&p->iDestSchema)) 
+                                                (int*)&p->iDestSchema))
     ){
       p->bDestLocked = 1;
     }
@@ -74471,7 +75902,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
       rc = SQLITE_READONLY;
     }
-  
+
     /* Now that there is a read-lock on the source database, query the
     ** source pager for the number of pages in the database.
     */
@@ -74498,7 +75929,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
         attachBackupObject(p);
       }
     }
-  
+
     /* Update the schema version field in the destination database. This
     ** is to make sure that the schema-version really does change in
     ** the case where the source and destination databases have the
@@ -74524,12 +75955,12 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
         int nDestTruncate;
         /* Set nDestTruncate to the final number of pages in the destination
         ** database. The complication here is that the destination page
-        ** size may be different to the source page size. 
+        ** size may be different to the source page size.
         **
-        ** If the source page size is smaller than the destination page size, 
+        ** If the source page size is smaller than the destination page size,
         ** round up. In this case the call to sqlite3OsTruncate() below will
         ** fix the size of the file. However it is important to call
-        ** sqlite3PagerTruncateImage() here so that any pages in the 
+        ** sqlite3PagerTruncateImage() here so that any pages in the
         ** destination file that lie beyond the nDestTruncate page mark are
         ** journalled by PagerCommitPhaseOne() before they are destroyed
         ** by the file truncation.
@@ -74553,7 +75984,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
           **
           **   * The destination may need to be truncated, and
           **
-          **   * Data stored on the pages immediately following the 
+          **   * Data stored on the pages immediately following the
           **     pending-byte page in the source database may need to be
           **     copied into the destination database.
           */
@@ -74565,7 +75996,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
           i64 iEnd;
 
           assert( pFile );
-          assert( nDestTruncate==0 
+          assert( nDestTruncate==0
               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
@@ -74575,7 +76006,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
           ** database has been stored in the journal for pDestPager and the
           ** journal synced to disk. So at this point we may safely modify
           ** the database file in any way, knowing that if a power failure
-          ** occurs, the original database will be reconstructed from the 
+          ** occurs, the original database will be reconstructed from the
           ** journal file.  */
           sqlite3PagerPagecount(pDestPager, &nDstPage);
           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
@@ -74595,8 +76026,8 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
           /* Write the extra pages and truncate the database file as required */
           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
           for(
-            iOff=PENDING_BYTE+pgszSrc; 
-            rc==SQLITE_OK && iOff<iEnd; 
+            iOff=PENDING_BYTE+pgszSrc;
+            rc==SQLITE_OK && iOff<iEnd;
             iOff+=pgszSrc
           ){
             PgHdr *pSrcPg = 0;
@@ -74620,7 +76051,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
         }
-    
+
         /* Finish committing the transaction to the destination database. */
         if( SQLITE_OK==rc
          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
@@ -74629,7 +76060,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
         }
       }
     }
-  
+
     /* If bCloseTrans is true, then this function opened a read transaction
     ** on the source database. Close the read transaction here. There is
     ** no need to check the return values of the btree methods here, as
@@ -74641,7 +76072,7 @@ SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
       assert( rc2==SQLITE_OK );
     }
-  
+
     if( rc==SQLITE_IOERR_NOMEM ){
       rc = SQLITE_NOMEM_BKPT;
     }
@@ -74723,7 +76154,7 @@ SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
 }
 
 /*
-** Return the total number of pages in the source database as of the most 
+** Return the total number of pages in the source database as of the most
 ** recent call to sqlite3_backup_step().
 */
 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
@@ -74738,7 +76169,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
 
 /*
 ** This function is called after the contents of page iPage of the
-** source database have been modified. If page iPage has already been 
+** source database have been modified. If page iPage has already been
 ** copied into the destination database, then the data written to the
 ** destination is now invalidated. The destination copy of iPage needs
 ** to be updated with the new data before the backup operation is
@@ -74781,7 +76212,7 @@ SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, con
 ** Restart the backup process. This is called when the pager layer
 ** detects that the database has been modified by an external database
 ** connection. In this case there is no way of knowing which of the
-** pages that have been copied into the destination database are still 
+** pages that have been copied into the destination database are still
 ** valid and which are not, so the entire process needs to be restarted.
 **
 ** It is assumed that the mutex associated with the BtShared object
@@ -74801,8 +76232,8 @@ SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
 ** must be active for both files.
 **
-** The size of file pTo may be reduced by this operation. If anything 
-** goes wrong, the transaction on pTo is rolled back. If successful, the 
+** The size of file pTo may be reduced by this operation. If anything
+** goes wrong, the transaction on pTo is rolled back. If successful, the
 ** transaction is committed before returning.
 */
 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
@@ -74812,7 +76243,7 @@ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   sqlite3BtreeEnter(pTo);
   sqlite3BtreeEnter(pFrom);
 
-  assert( sqlite3BtreeIsInTrans(pTo) );
+  assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   if( pFd->pMethods ){
     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
@@ -74832,15 +76263,11 @@ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
   b.pDest = pTo;
   b.iNext = 1;
 
-#ifdef SQLITE_HAS_CODEC
-  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
-#endif
-
   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
   ** file. By passing this as the number of pages to copy to
-  ** sqlite3_backup_step(), we can guarantee that the copy finishes 
+  ** sqlite3_backup_step(), we can guarantee that the copy finishes
   ** within a single call (unless an error occurs). The assert() statement
-  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
+  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
   ** or an error code.  */
   sqlite3_backup_step(&b, 0x7FFFFFFF);
   assert( b.rc!=SQLITE_OK );
@@ -74852,7 +76279,7 @@ SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
   }
 
-  assert( sqlite3BtreeIsInTrans(pTo)==0 );
+  assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
 copy_finished:
   sqlite3BtreeLeave(pFrom);
   sqlite3BtreeLeave(pTo);
@@ -74895,7 +76322,7 @@ copy_finished:
 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
 */
 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
-  /* If MEM_Dyn is set then Mem.xDel!=0.  
+  /* If MEM_Dyn is set then Mem.xDel!=0.
   ** Mem.xDel might not be initialized if MEM_Dyn is clear.
   */
   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
@@ -74950,7 +76377,7 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
   **   (4) A static string or blob
   */
   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
-    assert( 
+    assert(
       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
@@ -74968,16 +76395,25 @@ SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
 static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
   StrAccum acc;
   assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
-  sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
+  assert( sz>22 );
   if( p->flags & MEM_Int ){
-    sqlite3_str_appendf(&acc, "%lld", p->u.i);
-  }else if( p->flags & MEM_IntReal ){
-    sqlite3_str_appendf(&acc, "%!.15g", (double)p->u.i);
+#if GCC_VERSION>=7000000
+    /* Work-around for GCC bug
+    ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
+    i64 x;
+    assert( (p->flags&MEM_Int)*2==sizeof(x) );
+    memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
+    sqlite3Int64ToText(x, zBuf);
+#else
+    sqlite3Int64ToText(p->u.i, zBuf);
+#endif
   }else{
-    sqlite3_str_appendf(&acc, "%!.15g", p->u.r);
+    sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
+    sqlite3_str_appendf(&acc, "%!.15g",
+         (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
+    assert( acc.zText==zBuf && acc.mxAlloc<=0 );
+    zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
   }
-  assert( acc.zText==zBuf && acc.mxAlloc<=0 );
-  zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
 }
 
 #ifdef SQLITE_DEBUG
@@ -75318,21 +76754,17 @@ SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
 ** This routine calls the xValue method for that function and stores
 ** the results in memory cell pMem.
 **
-** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK 
+** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
 ** otherwise.
 */
 #ifndef SQLITE_OMIT_WINDOWFUNC
 SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
   sqlite3_context ctx;
-  Mem t;
   assert( pFunc!=0 );
   assert( pFunc->xValue!=0 );
   assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
   assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
   memset(&ctx, 0, sizeof(ctx));
-  memset(&t, 0, sizeof(t));
-  t.flags = MEM_Null;
-  t.db = pAccum->db;
   sqlite3VdbeMemSetNull(pOut);
   ctx.pOut = pOut;
   ctx.pMem = pAccum;
@@ -75458,8 +76890,7 @@ SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
     return pMem->u.i;
   }else if( flags & MEM_Real ){
     return doubleToInt64(pMem->u.r);
-  }else if( flags & (MEM_Str|MEM_Blob) ){
-    assert( pMem->z || pMem->n==0 );
+  }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
     return memIntValue(pMem);
   }else{
     return 0;
@@ -75496,7 +76927,7 @@ SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
 
 /*
 ** Return 1 if pMem represents true, and return 0 if pMem represents false.
-** Return the value ifNull if pMem is NULL.  
+** Return the value ifNull if pMem is NULL.
 */
 SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
   testcase( pMem->flags & MEM_IntReal );
@@ -75573,7 +77004,7 @@ SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
   double r2 = (double)i;
   return r1==0.0
       || (memcmp(&r1, &r2, sizeof(r1))==0
-          && (i < 0 ? -i : i) >> 51 == 0);
+          && (i < 0 ? -i : i) >> 53 == 0);
 }
 
 /*
@@ -75616,8 +77047,8 @@ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
 ** affinity even if that results in loss of data.  This routine is
 ** used (for example) to implement the SQL "cast()" operator.
 */
-SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
-  if( pMem->flags & MEM_Null ) return;
+SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
+  if( pMem->flags & MEM_Null ) return SQLITE_OK;
   switch( aff ){
     case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
       if( (pMem->flags & MEM_Blob)==0 ){
@@ -75648,9 +77079,10 @@ SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
-      break;
+      return sqlite3VdbeChangeEncoding(pMem, encoding);
     }
   }
+  return SQLITE_OK;
 }
 
 /*
@@ -75686,7 +77118,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
   }
 }
 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
-  sqlite3VdbeMemSetNull((Mem*)p); 
+  sqlite3VdbeMemSetNull((Mem*)p);
 }
 
 /*
@@ -75807,7 +77239,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
     }
     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
   }
-  return 0; 
+  return 0;
 }
 
 #ifdef SQLITE_DEBUG
@@ -75816,26 +77248,28 @@ SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
 ** its link to a shallow copy and by marking any current shallow
 ** copies of this cell as invalid.
 **
-** This is used for testing and debugging only - to make sure shallow
-** copies are not misused.
+** This is used for testing and debugging only - to help ensure that shallow
+** copies (created by OP_SCopy) are not misused.
 */
 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
   int i;
   Mem *pX;
-  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
+  for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
     if( pX->pScopyFrom==pMem ){
-      /* If pX is marked as a shallow copy of pMem, then verify that
+      u16 mFlags;
+      if( pVdbe->db->flags & SQLITE_VdbeTrace ){
+        sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
+          (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
+      }
+      /* If pX is marked as a shallow copy of pMem, then try to verify that
       ** no significant changes have been made to pX since the OP_SCopy.
       ** A significant change would indicated a missed call to this
       ** function for pX.  Minor changes, such as adding or removing a
       ** dual type, are allowed, as long as the underlying value is the
       ** same. */
-      u16 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
+      mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
       assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
-      assert( (mFlags&MEM_Real)==0 || pMem->u.r==pX->u.r );
-      assert( (mFlags&MEM_Str)==0  || (pMem->n==pX->n && pMem->z==pX->z) );
-      assert( (mFlags&MEM_Blob)==0  || sqlite3BlobCompare(pMem,pX)==0 );
-      
+
       /* pMem is the register that is changing.  But also mark pX as
       ** undefined so that we can quickly detect the shallow-copy error */
       pX->flags = MEM_Undefined;
@@ -75846,7 +77280,6 @@ SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
 }
 #endif /* SQLITE_DEBUG */
 
-
 /*
 ** Make an shallow copy of pFrom into pTo.  Prior contents of
 ** pTo are freed.  The pFrom->z field is not duplicated.  If
@@ -75912,8 +77345,8 @@ SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
 ** Change the value of a Mem to be a string or a BLOB.
 **
 ** The memory management strategy depends on the value of the xDel
-** parameter. If the value passed is SQLITE_TRANSIENT, then the 
-** string is copied into a (possibly existing) buffer managed by the 
+** parameter. If the value passed is SQLITE_TRANSIENT, then the
+** string is copied into a (possibly existing) buffer managed by the
 ** Mem structure. Otherwise, any existing buffer is freed and the
 ** pointer copied.
 **
@@ -75992,10 +77425,19 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 
   pMem->n = nByte;
   pMem->flags = flags;
-  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
+  if( enc ){
+    pMem->enc = enc;
+#ifdef SQLITE_ENABLE_SESSION
+  }else if( pMem->db==0 ){
+    pMem->enc = SQLITE_UTF8;
+#endif
+  }else{
+    assert( pMem->db!=0 );
+    pMem->enc = ENC(pMem->db);
+  }
 
 #ifndef SQLITE_OMIT_UTF16
-  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
+  if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
     return SQLITE_NOMEM_BKPT;
   }
 #endif
@@ -76022,7 +77464,7 @@ SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
 ** If this routine fails for any reason (malloc returns NULL or unable
 ** to read from the disk) then the pMem is left in an inconsistent state.
 */
-static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
   u32 offset,       /* Offset from the start of data to return bytes from. */
   u32 amt,          /* Number of bytes to return. */
@@ -76045,31 +77487,28 @@ static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
   }
   return rc;
 }
-SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
+SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(
   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
-  u32 offset,       /* Offset from the start of data to return bytes from. */
   u32 amt,          /* Number of bytes to return. */
   Mem *pMem         /* OUT: Return data in this Mem structure. */
 ){
-  char *zData;        /* Data from the btree layer */
   u32 available = 0;  /* Number of bytes available on the local btree page */
   int rc = SQLITE_OK; /* Return code */
 
   assert( sqlite3BtreeCursorIsValid(pCur) );
   assert( !VdbeMemDynamic(pMem) );
 
-  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
+  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
   ** that both the BtShared and database handle mutexes are held. */
   assert( !sqlite3VdbeMemIsRowSet(pMem) );
-  zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
-  assert( zData!=0 );
+  pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
+  assert( pMem->z!=0 );
 
-  if( offset+amt<=available ){
-    pMem->z = &zData[offset];
+  if( amt<=available ){
     pMem->flags = MEM_Blob|MEM_Ephem;
     pMem->n = (int)amt;
   }else{
-    rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
+    rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
   }
 
   return rc;
@@ -76151,7 +77590,7 @@ SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
 }
 
 /*
-** Context object passed by sqlite3Stat4ProbeSetValue() through to 
+** Context object passed by sqlite3Stat4ProbeSetValue() through to
 ** valueNew(). See comments above valueNew() for details.
 */
 struct ValueNewStat4Ctx {
@@ -76166,9 +77605,9 @@ struct ValueNewStat4Ctx {
 ** the second argument to this function is NULL, the object is allocated
 ** by calling sqlite3ValueNew().
 **
-** Otherwise, if the second argument is non-zero, then this function is 
+** Otherwise, if the second argument is non-zero, then this function is
 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
-** already been allocated, allocate the UnpackedRecord structure that 
+** already been allocated, allocate the UnpackedRecord structure that
 ** that function will return to its caller here. Then return a pointer to
 ** an sqlite3_value within the UnpackedRecord.a[] array.
 */
@@ -76182,7 +77621,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
       int nByte;                  /* Bytes of space to allocate */
       int i;                      /* Counter variable */
       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
-  
+
       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
       if( pRec ){
@@ -76203,7 +77642,7 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
       if( pRec==0 ) return 0;
       p->ppRec[0] = pRec;
     }
-  
+
     pRec->nField = p->iVal+1;
     return &pRec->aMem[p->iVal];
   }
@@ -76222,11 +77661,11 @@ static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
 **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
 **
 ** then this routine attempts to invoke the SQL function. Assuming no
-** error occurs, output parameter (*ppVal) is set to point to a value 
+** error occurs, output parameter (*ppVal) is set to point to a value
 ** object containing the result before returning SQLITE_OK.
 **
 ** Affinity aff is applied to the result of the function before returning.
-** If the result is a text value, the sqlite3_value object uses encoding 
+** If the result is a text value, the sqlite3_value object uses encoding
 ** enc.
 **
 ** If the conditions above are not met, this function returns SQLITE_OK
@@ -76257,7 +77696,7 @@ static int valueFromFunction(
   if( pList ) nVal = pList->nExpr;
   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
   assert( pFunc );
-  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 
+  if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
   ){
     return SQLITE_OK;
@@ -76405,14 +77844,18 @@ static int valueFromExpr(
     }
   }else if( op==TK_UMINUS ) {
     /* This branch happens for multiple negative signs.  Ex: -(-5) */
-    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx) 
+    if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
      && pVal!=0
     ){
       sqlite3VdbeMemNumerify(pVal);
       if( pVal->flags & MEM_Real ){
         pVal->u.r = -pVal->u.r;
       }else if( pVal->u.i==SMALLEST_INT64 ){
+#ifndef SQLITE_OMIT_FLOATING_POINT
         pVal->u.r = -(double)SMALLEST_INT64;
+#else
+        pVal->u.r = LARGEST_INT64;
+#endif
         MemSetTypeFlag(pVal, MEM_Real);
       }else{
         pVal->u.i = -pVal->u.i;
@@ -76550,8 +77993,8 @@ static int stat4ValueFromExpr(
 }
 
 /*
-** This function is used to allocate and populate UnpackedRecord 
-** structures intended to be compared against sample index keys stored 
+** This function is used to allocate and populate UnpackedRecord
+** structures intended to be compared against sample index keys stored
 ** in the sqlite_stat4 table.
 **
 ** A single call to this function populates zero or more fields of the
@@ -76562,14 +78005,14 @@ static int stat4ValueFromExpr(
 **
 **  * The expression is a bound variable, and this is a reprepare, or
 **
-**  * The sqlite3ValueFromExpr() function is able to extract a value 
+**  * The sqlite3ValueFromExpr() function is able to extract a value
 **    from the expression (i.e. the expression is a literal value).
 **
 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
 ** vector components that match either of the two latter criteria listed
 ** above.
 **
-** Before any value is appended to the record, the affinity of the 
+** Before any value is appended to the record, the affinity of the
 ** corresponding column within index pIdx is applied to it. Before
 ** this function returns, output parameter *pnExtract is set to the
 ** number of values appended to the record.
@@ -76620,9 +78063,9 @@ SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
 
 /*
 ** Attempt to extract a value from expression pExpr using the methods
-** as described for sqlite3Stat4ProbeSetValue() above. 
+** as described for sqlite3Stat4ProbeSetValue() above.
 **
-** If successful, set *ppVal to point to a new value object and return 
+** If successful, set *ppVal to point to a new value object and return
 ** SQLITE_OK. If no value can be extracted, but no other error occurs
 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
 ** does occur, return an SQLite error code. The final value of *ppVal
@@ -76642,7 +78085,7 @@ SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
 ** sqlite3_value object is allocated.
 **
-** If *ppVal is initially NULL then the caller is responsible for 
+** If *ppVal is initially NULL then the caller is responsible for
 ** ensuring that the value written into *ppVal is eventually freed.
 */
 SQLITE_PRIVATE int sqlite3Stat4Column(
@@ -76766,11 +78209,15 @@ SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
 **
 *************************************************************************
 ** This file contains code used for creating, destroying, and populating
-** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) 
+** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
 */
 /* #include "sqliteInt.h" */
 /* #include "vdbeInt.h" */
 
+/* Forward references */
+static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
+static void vdbeFreeOpArray(sqlite3 *, Op *, int);
+
 /*
 ** Create a new virtual database engine.
 */
@@ -76799,6 +78246,13 @@ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
 }
 
 /*
+** Return the Parse object that owns a Vdbe object.
+*/
+SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){
+  return p->pParse;
+}
+
+/*
 ** Change the error string stored in Vdbe.zErrMsg
 */
 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
@@ -76878,7 +78332,7 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
   zTmp = pA->zSql;
   pA->zSql = pB->zSql;
   pB->zSql = zTmp;
-#if 0
+#ifdef SQLITE_ENABLE_NORMALIZE
   zTmp = pA->zNormSql;
   pA->zNormSql = pB->zNormSql;
   pB->zNormSql = zTmp;
@@ -76890,13 +78344,13 @@ SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
 }
 
 /*
-** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
+** Resize the Vdbe.aOp array so that it is at least nOp elements larger
 ** than its current size. nOp is guaranteed to be less than or equal
 ** to 1024/sizeof(Op).
 **
 ** If an out-of-memory error occurs while resizing the array, return
-** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
-** unchanged (this is so that any opcodes already allocated can be 
+** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
+** unchanged (this is so that any opcodes already allocated can be
 ** correctly deallocated along with the rest of the Vdbe).
 */
 static int growOpArray(Vdbe *v, int nOp){
@@ -76904,7 +78358,7 @@ static int growOpArray(Vdbe *v, int nOp){
   Parse *p = v->pParse;
 
   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
-  ** more frequent reallocs and hence provide more opportunities for 
+  ** more frequent reallocs and hence provide more opportunities for
   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
   ** by the minimum* amount required until the size reaches 512.  Normal
@@ -76939,9 +78393,16 @@ static int growOpArray(Vdbe *v, int nOp){
 #ifdef SQLITE_DEBUG
 /* This routine is just a convenient place to set a breakpoint that will
 ** fire after each opcode is inserted and displayed using
-** "PRAGMA vdbe_addoptrace=on".
+** "PRAGMA vdbe_addoptrace=on".  Parameters "pc" (program counter) and
+** pOp are available to make the breakpoint conditional.
+**
+** Other useful labels for breakpoints include:
+**   test_trace_breakpoint(pc,pOp)
+**   sqlite3CorruptError(lineno)
+**   sqlite3MisuseError(lineno)
+**   sqlite3CantopenError(lineno)
 */
-static void test_addop_breakpoint(void){
+static void test_addop_breakpoint(int pc, Op *pOp){
   static int n = 0;
   n++;
 }
@@ -76994,7 +78455,7 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
 #ifdef SQLITE_DEBUG
   if( p->db->flags & SQLITE_VdbeAddopTrace ){
     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
-    test_addop_breakpoint();
+    test_addop_breakpoint(i, &p->aOp[i]);
   }
 #endif
 #ifdef VDBE_PROFILE
@@ -77078,6 +78539,49 @@ SQLITE_PRIVATE int sqlite3VdbeAddOp4(
 }
 
 /*
+** Add an OP_Function or OP_PureFunc opcode.
+**
+** The eCallCtx argument is information (typically taken from Expr.op2)
+** that describes the calling context of the function.  0 means a general
+** function call.  NC_IsCheck means called by a check constraint,
+** NC_IdxExpr means called as part of an index expression.  NC_PartIdx
+** means in the WHERE clause of a partial index.  NC_GenCol means called
+** while computing a generated column value.  0 is the usual case.
+*/
+SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(
+  Parse *pParse,        /* Parsing context */
+  int p1,               /* Constant argument mask */
+  int p2,               /* First argument register */
+  int p3,               /* Register into which results are written */
+  int nArg,             /* Number of argument */
+  const FuncDef *pFunc, /* The function to be invoked */
+  int eCallCtx          /* Calling context */
+){
+  Vdbe *v = pParse->pVdbe;
+  int nByte;
+  int addr;
+  sqlite3_context *pCtx;
+  assert( v );
+  nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
+  pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
+  if( pCtx==0 ){
+    assert( pParse->db->mallocFailed );
+    freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
+    return 0;
+  }
+  pCtx->pOut = 0;
+  pCtx->pFunc = (FuncDef*)pFunc;
+  pCtx->pVdbe = 0;
+  pCtx->isError = 0;
+  pCtx->argc = nArg;
+  pCtx->iOp = sqlite3VdbeCurrentAddr(v);
+  addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
+                           p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
+  sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
+  return addr;
+}
+
+/*
 ** Add an opcode that includes the p4 value with a P4_INT64 or
 ** P4_REAL type.
 */
@@ -77119,7 +78623,7 @@ SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
 #endif
 
 /*
-** Add a new OP_ opcode.
+** Add a new OP_Explain opcode.
 **
 ** If the bPush flag is true, then make this opcode the parent for
 ** subsequent Explains until sqlite3VdbeExplainPop() is called.
@@ -77170,6 +78674,7 @@ SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
   int j;
   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
+  sqlite3MayAbort(p->pParse);
 }
 
 /*
@@ -77293,19 +78798,19 @@ SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
 
 /*
 ** The following type and function are used to iterate through all opcodes
-** in a Vdbe main program and each of the sub-programs (triggers) it may 
+** in a Vdbe main program and each of the sub-programs (triggers) it may
 ** invoke directly or indirectly. It should be used as follows:
 **
 **   Op *pOp;
 **   VdbeOpIter sIter;
 **
 **   memset(&sIter, 0, sizeof(sIter));
-**   sIter.v = v;                            // v is of type Vdbe* 
+**   sIter.v = v;                            // v is of type Vdbe*
 **   while( (pOp = opIterNext(&sIter)) ){
 **     // Do something with pOp
 **   }
 **   sqlite3DbFree(v->db, sIter.apSub);
-** 
+**
 */
 typedef struct VdbeOpIter VdbeOpIter;
 struct VdbeOpIter {
@@ -77338,7 +78843,7 @@ static Op *opIterNext(VdbeOpIter *p){
       p->iSub++;
       p->iAddr = 0;
     }
-  
+
     if( pRet->p4type==P4_SUBPROGRAM ){
       int nByte = (p->nSub+1)*sizeof(SubProgram*);
       int j;
@@ -77369,9 +78874,10 @@ static Op *opIterNext(VdbeOpIter *p){
 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
 **   *  OP_Destroy
 **   *  OP_VUpdate
+**   *  OP_VCreate
 **   *  OP_VRename
 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
-**   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine 
+**   *  OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
 **      (for CREATE TABLE AS SELECT ...)
 **
 ** Then check that the value of Parse.mayAbort is true if an
@@ -77394,10 +78900,11 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
 
   while( (pOp = opIterNext(&sIter))!=0 ){
     int opcode = pOp->opcode;
-    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
+    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
      || opcode==OP_VDestroy
-     || (opcode==OP_ParseSchema && pOp->p4.z==0)
-     || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
+     || opcode==OP_VCreate
+     || opcode==OP_ParseSchema
+     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
       && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
     ){
       hasAbort = 1;
@@ -77406,7 +78913,7 @@ SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
     if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
     if( mayAbort ){
       /* hasCreateIndex may also be set for some DELETE statements that use
-      ** OP_Clear. So this routine may end up returning true in the case 
+      ** OP_Clear. So this routine may end up returning true in the case
       ** where a "DELETE FROM tbl" has a statement-journal but does not
       ** require one. This is not so bad - it is an inefficiency, not a bug. */
       if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
@@ -77501,7 +79008,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
       switch( pOp->opcode ){
         case OP_Transaction: {
           if( pOp->p2!=0 ) p->readOnly = 0;
-          /* fall thru */
+          /* no break */ deliberate_fall_through
         }
         case OP_AutoCommit:
         case OP_Savepoint: {
@@ -77522,7 +79029,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
           pOp->p4.xAdvance = sqlite3BtreeNext;
           pOp->p4type = P4_ADVANCE;
           /* The code generator never codes any of these opcodes as a jump
-          ** to a label.  They are always coded as a jump backwards to a 
+          ** to a label.  They are always coded as a jump backwards to a
           ** known address */
           assert( pOp->p2>=0 );
           break;
@@ -77531,7 +79038,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
           pOp->p4.xAdvance = sqlite3BtreePrevious;
           pOp->p4type = P4_ADVANCE;
           /* The code generator never codes any of these opcodes as a jump
-          ** to a label.  They are always coded as a jump backwards to a 
+          ** to a label.  They are always coded as a jump backwards to a
           ** known address */
           assert( pOp->p2>=0 );
           break;
@@ -77548,6 +79055,7 @@ static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
           n = pOp[-1].p1;
           if( n>nMaxArgs ) nMaxArgs = n;
           /* Fall through into the default case */
+          /* no break */ deliberate_fall_through
         }
 #endif
         default: {
@@ -77629,12 +79137,12 @@ SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
 /*
 ** This function returns a pointer to the array of opcodes associated with
 ** the Vdbe passed as the first argument. It is the callers responsibility
-** to arrange for the returned array to be eventually freed using the 
+** to arrange for the returned array to be eventually freed using the
 ** vdbeFreeOpArray() function.
 **
 ** Before returning, *pnOp is set to the number of entries in the returned
-** array. Also, *pnMaxArg is set to the larger of its current value and 
-** the number of entries in the Vdbe.apArg[] array required to execute the 
+** array. Also, *pnMaxArg is set to the larger of its current value and
+** the number of entries in the Vdbe.apArg[] array required to execute the
 ** returned program.
 */
 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
@@ -77708,7 +79216,7 @@ SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
   Vdbe *p,                        /* VM to add scanstatus() to */
   int addrExplain,                /* Address of OP_Explain (or 0) */
-  int addrLoop,                   /* Address of loop counter */ 
+  int addrLoop,                   /* Address of loop counter */
   int addrVisit,                  /* Address of rows visited counter */
   LogEst nEst,                    /* Estimated number of output rows */
   const char *zName               /* Name of table or index being scanned */
@@ -77758,6 +79266,34 @@ SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   sqlite3VdbeChangeP2(p, addr, p->nOp);
 }
 
+/*
+** Change the P2 operand of the jump instruction at addr so that
+** the jump lands on the next opcode.  Or if the jump instruction was
+** the previous opcode (and is thus a no-op) then simply back up
+** the next instruction counter by one slot so that the jump is
+** overwritten by the next inserted opcode.
+**
+** This routine is an optimization of sqlite3VdbeJumpHere() that
+** strives to omit useless byte-code like this:
+**
+**        7   Once 0 8 0
+**        8   ...
+*/
+SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
+  if( addr==p->nOp-1 ){
+    assert( p->aOp[addr].opcode==OP_Once
+         || p->aOp[addr].opcode==OP_If
+         || p->aOp[addr].opcode==OP_FkIfZero );
+    assert( p->aOp[addr].p4type==0 );
+#ifdef SQLITE_VDBE_COVERAGE
+    sqlite3VdbeGetOp(p,-1)->iSrcLine = 0;  /* Erase VdbeCoverage() macros */
+#endif
+    p->nOp--;
+  }else{
+    sqlite3VdbeChangeP2(p, addr, p->nOp);
+  }
+}
+
 
 /*
 ** If the input FuncDef structure is ephemeral, then free it.  If
@@ -77769,8 +79305,6 @@ static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
   }
 }
 
-static void vdbeFreeOpArray(sqlite3 *, Op *, int);
-
 /*
 ** Delete a P4 value if necessary.
 */
@@ -77780,7 +79314,7 @@ static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
 }
 static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
   freeEphemeralFunction(db, p->pFunc);
- sqlite3DbFreeNN(db, p);
 sqlite3DbFreeNN(db, p);
 }
 static void freeP4(sqlite3 *db, int p4type, void *p4){
   assert( db );
@@ -77828,8 +79362,8 @@ static void freeP4(sqlite3 *db, int p4type, void *p4){
 
 /*
 ** Free the space allocated for aOp and any p4 values allocated for the
-** opcodes contained within. If aOp is not NULL it is assumed to contain 
-** nOp entries. 
+** opcodes contained within. If aOp is not NULL it is assumed to contain
+** nOp entries.
 */
 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
   if( aOp ){
@@ -77838,7 +79372,7 @@ static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
       if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
       sqlite3DbFree(db, pOp->zComment);
-#endif     
+#endif
     }
     sqlite3DbFreeNN(db, aOp);
   }
@@ -77855,6 +79389,13 @@ SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
 }
 
 /*
+** Return true if the given Vdbe has any SubPrograms.
+*/
+SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
+  return pVdbe->pProgram!=0;
+}
+
+/*
 ** Change the opcode at addr into OP_Noop
 */
 SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
@@ -77881,6 +79422,41 @@ SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
   }
 }
 
+#ifdef SQLITE_DEBUG
+/*
+** Generate an OP_ReleaseReg opcode to indicate that a range of
+** registers, except any identified by mask, are no longer in use.
+*/
+SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(
+  Parse *pParse,       /* Parsing context */
+  int iFirst,          /* Index of first register to be released */
+  int N,               /* Number of registers to release */
+  u32 mask,            /* Mask of registers to NOT release */
+  int bUndefine        /* If true, mark registers as undefined */
+){
+  if( N==0 ) return;
+  assert( pParse->pVdbe );
+  assert( iFirst>=1 );
+  assert( iFirst+N-1<=pParse->nMem );
+  if( N<=31 && mask!=0 ){
+    while( N>0 && (mask&1)!=0 ){
+      mask >>= 1;
+      iFirst++;
+      N--;
+    }
+    while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
+      mask &= ~MASKBIT32(N-1);
+      N--;
+    }
+  }
+  if( N>0 ){
+    sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
+    if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
+  }
+}
+#endif /* SQLITE_DEBUG */
+
+
 /*
 ** Change the value of the P4 operand for a specific instruction.
 ** This routine is useful when a large program is loaded from a
@@ -77891,7 +79467,7 @@ SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
 ** the string is made into memory obtained from sqlite3_malloc().
 ** A value of n==0 means copy bytes of zP4 up to and including the
 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
-** 
+**
 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
 ** to a string or structure that is guaranteed to exist for the lifetime of
 ** the Vdbe. In these cases we can just copy the pointer.
@@ -77952,7 +79528,7 @@ SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int
 }
 
 /*
-** Change the P4 operand of the most recently coded instruction 
+** Change the P4 operand of the most recently coded instruction
 ** to the value defined by the arguments.  This is a high-speed
 ** version of sqlite3VdbeChangeP4().
 **
@@ -77998,7 +79574,8 @@ SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
 */
 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
   assert( p->nOp>0 || p->aOp==0 );
-  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
+  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed
+          || p->pParse->nErr>0 );
   if( p->nOp ){
     assert( p->aOp );
     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
@@ -78041,7 +79618,7 @@ SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
 ** is readable but not writable, though it is cast to a writable value.
 ** The return of a dummy opcode allows the call to continue functioning
-** after an OOM fault without having to check to see if the return from 
+** after an OOM fault without having to check to see if the return from
 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
 ** dummy will never be written to.  This is verified by code inspection and
 ** by running with Valgrind.
@@ -78088,17 +79665,19 @@ static int translateP(char c, const Op *pOp){
 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
 */
-static int displayComment(
+SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(
+  sqlite3 *db,       /* Optional - Oom error reporting only */
   const Op *pOp,     /* The opcode to be commented */
-  const char *zP4,   /* Previously obtained value for P4 */
-  char *zTemp,       /* Write result here */
-  int nTemp          /* Space available in zTemp[] */
+  const char *zP4    /* Previously obtained value for P4 */
 ){
   const char *zOpName;
   const char *zSynopsis;
   int nOpName;
-  int ii, jj;
+  int ii;
   char zAlt[50];
+  StrAccum x;
+
+  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
   zOpName = sqlite3OpcodeName(pOp->opcode);
   nOpName = sqlite3Strlen30(zOpName);
   if( zOpName[nOpName+1] ){
@@ -78113,53 +79692,64 @@ static int displayComment(
       }
       zSynopsis = zAlt;
     }
-    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
+    for(ii=0; (c = zSynopsis[ii])!=0; ii++){
       if( c=='P' ){
         c = zSynopsis[++ii];
         if( c=='4' ){
-          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
+          sqlite3_str_appendall(&x, zP4);
         }else if( c=='X' ){
-          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
+          sqlite3_str_appendall(&x, pOp->zComment);
           seenCom = 1;
         }else{
           int v1 = translateP(c, pOp);
           int v2;
-          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
             ii += 3;
-            jj += sqlite3Strlen30(zTemp+jj);
             v2 = translateP(zSynopsis[ii], pOp);
             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
               ii += 2;
               v2++;
             }
-            if( v2>1 ){
-              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
+            if( v2<2 ){
+              sqlite3_str_appendf(&x, "%d", v1);
+            }else{
+              sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
+            }
+          }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
+            sqlite3_context *pCtx = pOp->p4.pCtx;
+            if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
+              sqlite3_str_appendf(&x, "%d", v1);
+            }else if( pCtx->argc>1 ){
+              sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
+            }else if( x.accError==0 ){
+              assert( x.nChar>2 );
+              x.nChar -= 2;
+              ii++;
+            }
+            ii += 3;
+          }else{
+            sqlite3_str_appendf(&x, "%d", v1);
+            if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
+              ii += 4;
             }
-          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
-            ii += 4;
           }
         }
-        jj += sqlite3Strlen30(zTemp+jj);
       }else{
-        zTemp[jj++] = c;
+        sqlite3_str_appendchar(&x, 1, c);
       }
     }
-    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
-      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
-      jj += sqlite3Strlen30(zTemp+jj);
+    if( !seenCom && pOp->zComment ){
+      sqlite3_str_appendf(&x, "; %s", pOp->zComment);
     }
-    if( jj<nTemp ) zTemp[jj] = 0;
   }else if( pOp->zComment ){
-    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
-    jj = sqlite3Strlen30(zTemp);
-  }else{
-    zTemp[0] = 0;
-    jj = 0;
+    sqlite3_str_appendall(&x, pOp->zComment);
+  }
+  if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
+    sqlite3OomFault(db);
   }
-  return jj;
+  return sqlite3StrAccumFinish(&x);
 }
-#endif /* SQLITE_DEBUG */
+#endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
 
 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
 /*
@@ -78240,11 +79830,11 @@ static void displayP4Expr(StrAccum *p, Expr *pExpr){
 ** Compute a string that describes the P4 parameter for an opcode.
 ** Use zTemp for any required temporary buffer space.
 */
-static const char *displayP4(Op *pOp, char *zTemp, int nTemp){
-  const char *zP4 = zTemp;
+SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
+  const char *zP4 = 0;
   StrAccum x;
-  assert( nTemp>=20 );
-  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
+
+  sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
   switch( pOp->p4type ){
     case P4_KEYINFO: {
       int j;
@@ -78255,9 +79845,9 @@ static const char *displayP4(Op *pOp, char *zTemp, int nTemp){
         CollSeq *pColl = pKeyInfo->aColl[j];
         const char *zColl = pColl ? pColl->zName : "";
         if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
-        sqlite3_str_appendf(&x, ",%s%s%s", 
-               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "", 
-               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "", 
+        sqlite3_str_appendf(&x, ",%s%s%s",
+               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
+               (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
                zColl);
       }
       sqlite3_str_append(&x, ")", 1);
@@ -78270,8 +79860,11 @@ static const char *displayP4(Op *pOp, char *zTemp, int nTemp){
     }
 #endif
     case P4_COLLSEQ: {
+      static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
       CollSeq *pColl = pOp->p4.pColl;
-      sqlite3_str_appendf(&x, "(%.20s)", pColl->zName);
+      assert( pColl->enc>=0 && pColl->enc<4 );
+      sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
+                          encnames[pColl->enc]);
       break;
     }
     case P4_FUNCDEF: {
@@ -78279,13 +79872,11 @@ static const char *displayP4(Op *pOp, char *zTemp, int nTemp){
       sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
       break;
     }
-#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
     case P4_FUNCCTX: {
       FuncDef *pDef = pOp->p4.pCtx->pFunc;
       sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
       break;
     }
-#endif
     case P4_INT64: {
       sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
       break;
@@ -78322,41 +79913,37 @@ static const char *displayP4(Op *pOp, char *zTemp, int nTemp){
     }
 #endif
     case P4_INTARRAY: {
-      int i;
-      int *ai = pOp->p4.ai;
-      int n = ai[0];   /* The first element of an INTARRAY is always the
+      u32 i;
+      u32 *ai = pOp->p4.ai;
+      u32 n = ai[0];   /* The first element of an INTARRAY is always the
                        ** count of the number of elements to follow */
       for(i=1; i<=n; i++){
-        sqlite3_str_appendf(&x, ",%d", ai[i]);
+        sqlite3_str_appendf(&x, "%c%u", (i==1 ? '[' : ','), ai[i]);
       }
-      zTemp[0] = '[';
       sqlite3_str_append(&x, "]", 1);
       break;
     }
     case P4_SUBPROGRAM: {
-      sqlite3_str_appendf(&x, "program");
+      zP4 = "program";
       break;
     }
     case P4_DYNBLOB:
     case P4_ADVANCE: {
-      zTemp[0] = 0;
       break;
     }
     case P4_TABLE: {
-      sqlite3_str_appendf(&x, "%s", pOp->p4.pTab->zName);
+      zP4 = pOp->p4.pTab->zName;
       break;
     }
     default: {
       zP4 = pOp->p4.z;
-      if( zP4==0 ){
-        zP4 = zTemp;
-        zTemp[0] = 0;
-      }
     }
   }
-  sqlite3StrAccumFinish(&x);
-  assert( zP4!=0 );
-  return zP4;
+  if( zP4 ) sqlite3_str_appendall(&x, zP4);
+  if( (x.accError & SQLITE_NOMEM)!=0 ){
+    sqlite3OomFault(db);
+  }
+  return sqlite3StrAccumFinish(&x);
 }
 #endif /* VDBE_DISPLAY_P4 */
 
@@ -78387,13 +79974,13 @@ SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
 **
 ** If SQLite is not threadsafe but does support shared-cache mode, then
 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
-** of all of BtShared structures accessible via the database handle 
+** of all of BtShared structures accessible via the database handle
 ** associated with the VM.
 **
 ** If SQLite is not threadsafe and does not support shared-cache mode, this
 ** function is a no-op.
 **
-** The p->btreeMask field is a bitmask of all btrees that the prepared 
+** The p->btreeMask field is a bitmask of all btrees that the prepared
 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
 ** corresponding to btrees that use shared cache.  Then the runtime of
 ** this routine is N*N.  But as N is rarely more than 1, this should not
@@ -78445,25 +80032,31 @@ SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
 ** Print a single opcode.  This routine is used for debugging only.
 */
 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
-  const char *zP4;
-  char zPtr[50];
-  char zCom[100];
+  char *zP4;
+  char *zCom;
+  sqlite3 dummyDb;
   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
   if( pOut==0 ) pOut = stdout;
-  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
+  sqlite3BeginBenignMalloc();
+  dummyDb.mallocFailed = 1;
+  zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
-  displayComment(pOp, zP4, zCom, sizeof(zCom));
+  zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
 #else
-  zCom[0] = 0;
+  zCom = 0;
 #endif
   /* NB:  The sqlite3OpcodeName() function is implemented by code created
   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
   ** information from the vdbe.c source text */
-  fprintf(pOut, zFormat1, pc, 
-      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
-      zCom
+  fprintf(pOut, zFormat1, pc,
+      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
+      zP4 ? zP4 : "", pOp->p5,
+      zCom ? zCom : ""
   );
   fflush(pOut);
+  sqlite3_free(zP4);
+  sqlite3_free(zCom);
+  sqlite3EndBenignMalloc();
 }
 #endif
 
@@ -78500,15 +80093,15 @@ static void releaseMemArray(Mem *p, int N){
       assert( sqlite3VdbeCheckMemInvariants(p) );
 
       /* This block is really an inlined version of sqlite3VdbeMemRelease()
-      ** that takes advantage of the fact that the memory cell value is 
+      ** that takes advantage of the fact that the memory cell value is
       ** being set to NULL after releasing any dynamic resources.
       **
-      ** The justification for duplicating code is that according to 
-      ** callgrind, this causes a certain test case to hit the CPU 4.7 
-      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
+      ** The justification for duplicating code is that according to
+      ** callgrind, this causes a certain test case to hit the CPU 4.7
+      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
       ** sqlite3MemRelease() were called from here. With -O2, this jumps
-      ** to 6.6 percent. The test case is inserting 1000 rows into a table 
-      ** with no indexes using a single prepared INSERT statement, bind() 
+      ** to 6.6 percent. The test case is inserting 1000 rows into a table
+      ** with no indexes using a single prepared INSERT statement, bind()
       ** and reset(). Inserts are grouped into a transaction.
       */
       testcase( p->flags & MEM_Agg );
@@ -78554,74 +80147,29 @@ SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
   pFrame->v->pDelFrame = pFrame;
 }
 
-
-/*
-** Delete a VdbeFrame object and its contents. VdbeFrame objects are
-** allocated by the OP_Program opcode in sqlite3VdbeExec().
-*/
-SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
-  int i;
-  Mem *aMem = VdbeFrameMem(p);
-  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
-  assert( sqlite3VdbeFrameIsValid(p) );
-  for(i=0; i<p->nChildCsr; i++){
-    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
-  }
-  releaseMemArray(aMem, p->nChildMem);
-  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
-  sqlite3DbFree(p->v->db, p);
-}
-
-#ifndef SQLITE_OMIT_EXPLAIN
+#if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
 /*
-** Give a listing of the program in the virtual machine.
+** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
+** QUERY PLAN output.
 **
-** The interface is the same as sqlite3VdbeExec().  But instead of
-** running the code, it invokes the callback once for each instruction.
-** This feature is used to implement "EXPLAIN".
-**
-** When p->explain==1, each instruction is listed.  When
-** p->explain==2, only OP_Explain instructions are listed and these
-** are shown in a different format.  p->explain==2 is used to implement
-** EXPLAIN QUERY PLAN.
-** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
-** are also shown, so that the boundaries between the main program and
-** each trigger are clear.
-**
-** When p->explain==1, first the main program is listed, then each of
-** the trigger subprograms are listed one by one.
+** Return SQLITE_ROW on success.  Return SQLITE_DONE if there are no
+** more opcodes to be displayed.
 */
-SQLITE_PRIVATE int sqlite3VdbeList(
-  Vdbe *p                   /* The VDBE */
+SQLITE_PRIVATE int sqlite3VdbeNextOpcode(
+  Vdbe *p,         /* The statement being explained */
+  Mem *pSub,       /* Storage for keeping track of subprogram nesting */
+  int eMode,       /* 0: normal.  1: EQP.  2:  TablesUsed */
+  int *piPc,       /* IN/OUT: Current rowid.  Overwritten with next rowid */
+  int *piAddr,     /* OUT: Write index into (*paOp)[] here */
+  Op **paOp        /* OUT: Write the opcode array here */
 ){
   int nRow;                            /* Stop when row count reaches this */
   int nSub = 0;                        /* Number of sub-vdbes seen so far */
   SubProgram **apSub = 0;              /* Array of sub-vdbes */
-  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
-  sqlite3 *db = p->db;                 /* The database connection */
-  int i;                               /* Loop counter */
-  int rc = SQLITE_OK;                  /* Return code */
-  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
-  int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
-  Op *pOp = 0;
-
-  assert( p->explain );
-  assert( p->magic==VDBE_MAGIC_RUN );
-  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
-
-  /* Even though this opcode does not use dynamic strings for
-  ** the result, result columns may become dynamic if the user calls
-  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
-  */
-  releaseMemArray(pMem, 8);
-  p->pResultSet = 0;
-
-  if( p->rc==SQLITE_NOMEM ){
-    /* This happens if a malloc() inside a call to sqlite3_column_text() or
-    ** sqlite3_column_text16() failed.  */
-    sqlite3OomFault(db);
-    return SQLITE_ERROR;
-  }
+  int i;                               /* Next instruction address */
+  int rc = SQLITE_OK;                  /* Result code */
+  Op *aOp = 0;                         /* Opcode array */
+  int iPc;                             /* Rowid.  Copy of value in *piPc */
 
   /* When the number of output rows reaches nRow, that means the
   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
@@ -78631,16 +80179,10 @@ SQLITE_PRIVATE int sqlite3VdbeList(
   ** encountered, but p->pc will eventually catch up to nRow.
   */
   nRow = p->nOp;
-  if( bListSubprogs ){
-    /* The first 8 memory cells are used for the result set.  So we will
-    ** commandeer the 9th cell to use as storage for an array of pointers
-    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
-    ** cells.  */
-    assert( p->nMem>9 );
-    pSub = &p->aMem[9];
+  if( pSub!=0 ){
     if( pSub->flags&MEM_Blob ){
-      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
-      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
+      /* pSub is initiallly NULL.  It is initialized to a BLOB by
+      ** the P4_SUBPROGRAM processing logic below */
       nSub = pSub->n/sizeof(Vdbe*);
       apSub = (SubProgram **)pSub->z;
     }
@@ -78648,18 +80190,18 @@ SQLITE_PRIVATE int sqlite3VdbeList(
       nRow += apSub[i]->nOp;
     }
   }
-
+  iPc = *piPc;
   while(1){  /* Loop exits via break */
-    i = p->pc++;
+    i = iPc++;
     if( i>=nRow ){
       p->rc = SQLITE_OK;
       rc = SQLITE_DONE;
       break;
     }
     if( i<p->nOp ){
-      /* The output line number is small enough that we are still in the
+      /* The rowid is small enough that we are still in the
       ** main program. */
-      pOp = &p->aOp[i];
+      aOp = p->aOp;
     }else{
       /* We are currently listing subprograms.  Figure out which one and
       ** pick up the appropriate opcode. */
@@ -78671,7 +80213,7 @@ SQLITE_PRIVATE int sqlite3VdbeList(
         i -= apSub[j]->nOp;
         assert( i<apSub[j]->nOp || j+1<nSub );
       }
-      pOp = &apSub[j]->aOp[i];
+      aOp = apSub[j]->aOp;
     }
 
     /* When an OP_Program opcode is encounter (the only opcode that has
@@ -78679,11 +80221,11 @@ SQLITE_PRIVATE int sqlite3VdbeList(
     ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
     ** has not already been seen.
     */
-    if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
+    if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
       int nByte = (nSub+1)*sizeof(SubProgram*);
       int j;
       for(j=0; j<nSub; j++){
-        if( apSub[j]==pOp->p4.pProgram ) break;
+        if( apSub[j]==aOp[i].p4.pProgram ) break;
       }
       if( j==nSub ){
         p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
@@ -78692,93 +80234,157 @@ SQLITE_PRIVATE int sqlite3VdbeList(
           break;
         }
         apSub = (SubProgram **)pSub->z;
-        apSub[nSub++] = pOp->p4.pProgram;
-        pSub->flags |= MEM_Blob;
+        apSub[nSub++] = aOp[i].p4.pProgram;
+        MemSetTypeFlag(pSub, MEM_Blob);
         pSub->n = nSub*sizeof(SubProgram*);
-        nRow += pOp->p4.pProgram->nOp;
+        nRow += aOp[i].p4.pProgram->nOp;
       }
     }
-    if( p->explain<2 ) break;
-    if( pOp->opcode==OP_Explain ) break;
-    if( pOp->opcode==OP_Init && p->pc>1 ) break;
+    if( eMode==0 ) break;
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+    if( eMode==2 ){
+      Op *pOp = aOp + i;
+      if( pOp->opcode==OP_OpenRead ) break;
+      if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
+      if( pOp->opcode==OP_ReopenIdx ) break;
+    }else
+#endif
+    {
+      assert( eMode==1 );
+      if( aOp[i].opcode==OP_Explain ) break;
+      if( aOp[i].opcode==OP_Init && iPc>1 ) break;
+    }
+  }
+  *piPc = iPc;
+  *piAddr = i;
+  *paOp = aOp;
+  return rc;
+}
+#endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
+
+
+/*
+** Delete a VdbeFrame object and its contents. VdbeFrame objects are
+** allocated by the OP_Program opcode in sqlite3VdbeExec().
+*/
+SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
+  int i;
+  Mem *aMem = VdbeFrameMem(p);
+  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
+  assert( sqlite3VdbeFrameIsValid(p) );
+  for(i=0; i<p->nChildCsr; i++){
+    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
+  }
+  releaseMemArray(aMem, p->nChildMem);
+  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
+  sqlite3DbFree(p->v->db, p);
+}
+
+#ifndef SQLITE_OMIT_EXPLAIN
+/*
+** Give a listing of the program in the virtual machine.
+**
+** The interface is the same as sqlite3VdbeExec().  But instead of
+** running the code, it invokes the callback once for each instruction.
+** This feature is used to implement "EXPLAIN".
+**
+** When p->explain==1, each instruction is listed.  When
+** p->explain==2, only OP_Explain instructions are listed and these
+** are shown in a different format.  p->explain==2 is used to implement
+** EXPLAIN QUERY PLAN.
+** 2018-04-24:  In p->explain==2 mode, the OP_Init opcodes of triggers
+** are also shown, so that the boundaries between the main program and
+** each trigger are clear.
+**
+** When p->explain==1, first the main program is listed, then each of
+** the trigger subprograms are listed one by one.
+*/
+SQLITE_PRIVATE int sqlite3VdbeList(
+  Vdbe *p                   /* The VDBE */
+){
+  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
+  sqlite3 *db = p->db;                 /* The database connection */
+  int i;                               /* Loop counter */
+  int rc = SQLITE_OK;                  /* Return code */
+  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
+  int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
+  Op *aOp;                             /* Array of opcodes */
+  Op *pOp;                             /* Current opcode */
+
+  assert( p->explain );
+  assert( p->magic==VDBE_MAGIC_RUN );
+  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
+
+  /* Even though this opcode does not use dynamic strings for
+  ** the result, result columns may become dynamic if the user calls
+  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
+  */
+  releaseMemArray(pMem, 8);
+  p->pResultSet = 0;
+
+  if( p->rc==SQLITE_NOMEM ){
+    /* This happens if a malloc() inside a call to sqlite3_column_text() or
+    ** sqlite3_column_text16() failed.  */
+    sqlite3OomFault(db);
+    return SQLITE_ERROR;
+  }
+
+  if( bListSubprogs ){
+    /* The first 8 memory cells are used for the result set.  So we will
+    ** commandeer the 9th cell to use as storage for an array of pointers
+    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
+    ** cells.  */
+    assert( p->nMem>9 );
+    pSub = &p->aMem[9];
+  }else{
+    pSub = 0;
   }
 
+  /* Figure out which opcode is next to display */
+  rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
+
   if( rc==SQLITE_OK ){
-    if( db->u1.isInterrupted ){
+    pOp = aOp + i;
+    if( AtomicLoad(&db->u1.isInterrupted) ){
       p->rc = SQLITE_INTERRUPT;
       rc = SQLITE_ERROR;
       sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
     }else{
-      const char *zP4;
-      if( p->explain==1 ){
-        pMem->flags = MEM_Int;
-        pMem->u.i = i;                                /* Program counter */
-        pMem++;
-    
-        pMem->flags = MEM_Static|MEM_Str|MEM_Term;
-        pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
-        assert( pMem->z!=0 );
-        pMem->n = sqlite3Strlen30(pMem->z);
-        pMem->enc = SQLITE_UTF8;
-        pMem++;
-      }
-
-      pMem->flags = MEM_Int;
-      pMem->u.i = pOp->p1;                          /* P1 */
-      pMem++;
-
-      pMem->flags = MEM_Int;
-      pMem->u.i = pOp->p2;                          /* P2 */
-      pMem++;
-
-      pMem->flags = MEM_Int;
-      pMem->u.i = pOp->p3;                          /* P3 */
-      pMem++;
-
-      if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
-        assert( p->db->mallocFailed );
-        return SQLITE_ERROR;
-      }
-      pMem->flags = MEM_Str|MEM_Term;
-      zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
-      if( zP4!=pMem->z ){
-        pMem->n = 0;
-        sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
+      char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
+      if( p->explain==2 ){
+        sqlite3VdbeMemSetInt64(pMem, pOp->p1);
+        sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
+        sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
+        sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
+        p->nResColumn = 4;
       }else{
-        assert( pMem->z!=0 );
-        pMem->n = sqlite3Strlen30(pMem->z);
-        pMem->enc = SQLITE_UTF8;
-      }
-      pMem++;
-
-      if( p->explain==1 ){
-        if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
-          assert( p->db->mallocFailed );
-          return SQLITE_ERROR;
-        }
-        pMem->flags = MEM_Str|MEM_Term;
-        pMem->n = 2;
-        sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
-        pMem->enc = SQLITE_UTF8;
-        pMem++;
-    
+        sqlite3VdbeMemSetInt64(pMem+0, i);
+        sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
+                             -1, SQLITE_UTF8, SQLITE_STATIC);
+        sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
+        sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
+        sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
+        /* pMem+5 for p4 is done last */
+        sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
-        if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
-          assert( p->db->mallocFailed );
-          return SQLITE_ERROR;
+        {
+          char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
+          sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
         }
-        pMem->flags = MEM_Str|MEM_Term;
-        pMem->n = displayComment(pOp, zP4, pMem->z, 500);
-        pMem->enc = SQLITE_UTF8;
 #else
-        pMem->flags = MEM_Null;                       /* Comment */
+        sqlite3VdbeMemSetNull(pMem+7);
 #endif
+        sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
+        p->nResColumn = 8;
+      }
+      p->pResultSet = pMem;
+      if( db->mallocFailed ){
+        p->rc = SQLITE_NOMEM;
+        rc = SQLITE_ERROR;
+      }else{
+        p->rc = SQLITE_OK;
+        rc = SQLITE_ROW;
       }
-
-      p->nResColumn = 8 - 4*(p->explain-1);
-      p->pResultSet = &p->aMem[1];
-      p->rc = SQLITE_OK;
-      rc = SQLITE_ROW;
     }
   }
   return rc;
@@ -78921,11 +80527,11 @@ SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
 ** creating the virtual machine.  This involves things such
 ** as allocating registers and initializing the program counter.
 ** After the VDBE has be prepped, it can be executed by one or more
-** calls to sqlite3VdbeExec().  
+** calls to sqlite3VdbeExec().
 **
 ** This function may be called exactly once on each virtual machine.
 ** After this routine is called the VM has been "packaged" and is ready
-** to run.  After this routine is called, further calls to 
+** to run.  After this routine is called, further calls to
 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
 ** the Vdbe from the Parse object that helped generate it so that the
 ** the Vdbe becomes an independent entity and the Parse object can be
@@ -78957,7 +80563,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(
   nMem = pParse->nMem;
   nCursor = pParse->nTab;
   nArg = pParse->nMaxArg;
-  
+
   /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
   ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
   ** space at the end of aMem[] for cursors 1 and greater.
@@ -78979,16 +80585,35 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 
   resolveP2Values(p, &nArg);
   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
-  if( pParse->explain && nMem<10 ){
-    nMem = 10;
+  if( pParse->explain ){
+    static const char * const azColName[] = {
+       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
+       "id", "parent", "notused", "detail"
+    };
+    int iFirst, mx, i;
+    if( nMem<10 ) nMem = 10;
+    p->explain = pParse->explain;
+    if( pParse->explain==2 ){
+      sqlite3VdbeSetNumCols(p, 4);
+      iFirst = 8;
+      mx = 12;
+    }else{
+      sqlite3VdbeSetNumCols(p, 8);
+      iFirst = 0;
+      mx = 8;
+    }
+    for(i=iFirst; i<mx; i++){
+      sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
+                            azColName[i], SQLITE_STATIC);
+    }
   }
   p->expired = 0;
 
   /* Memory for registers, parameters, cursor, etc, is allocated in one or two
-  ** passes.  On the first pass, we try to reuse unused memory at the 
+  ** passes.  On the first pass, we try to reuse unused memory at the
   ** end of the opcode array.  If we are unable to satisfy all memory
   ** requirements by reusing the opcode array tail, then the second
-  ** pass will fill in the remainder using a fresh memory allocation.  
+  ** pass will fill in the remainder using a fresh memory allocation.
   **
   ** This two-pass approach that reuses as much memory as possible from
   ** the leftover memory at the end of the opcode array.  This can significantly
@@ -79018,7 +80643,6 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 
   p->pVList = pParse->pVList;
   pParse->pVList =  0;
-  p->explain = pParse->explain;
   if( db->mallocFailed ){
     p->nVar = 0;
     p->nCursor = 0;
@@ -79038,7 +80662,7 @@ SQLITE_PRIVATE void sqlite3VdbeMakeReady(
 }
 
 /*
-** Close a VDBE cursor and release all the resources that cursor 
+** Close a VDBE cursor and release all the resources that cursor
 ** happens to hold.
 */
 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
@@ -79120,7 +80744,7 @@ SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
 /*
 ** Close all cursors.
 **
-** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
+** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
 ** cell array. This is necessary as the memory cell array may contain
 ** pointers to VdbeFrame objects, which may in turn contain pointers to
 ** open cursors.
@@ -79206,43 +80830,43 @@ SQLITE_PRIVATE int sqlite3VdbeSetColName(
 ** A read or write transaction may or may not be active on database handle
 ** db. If a transaction is active, commit it. If there is a
 ** write-transaction spanning more than one database file, this routine
-** takes care of the master journal trickery.
+** takes care of the super-journal trickery.
 */
 static int vdbeCommit(sqlite3 *db, Vdbe *p){
   int i;
   int nTrans = 0;  /* Number of databases with an active write-transaction
                    ** that are candidates for a two-phase commit using a
-                   ** master-journal */
+                   ** super-journal */
   int rc = SQLITE_OK;
   int needXcommit = 0;
 
 #ifdef SQLITE_OMIT_VIRTUALTABLE
-  /* With this option, sqlite3VtabSync() is defined to be simply 
-  ** SQLITE_OK so p is not used. 
+  /* With this option, sqlite3VtabSync() is defined to be simply
+  ** SQLITE_OK so p is not used.
   */
   UNUSED_PARAMETER(p);
 #endif
 
   /* Before doing anything else, call the xSync() callback for any
   ** virtual module tables written in this transaction. This has to
-  ** be done before determining whether a master journal file is 
+  ** be done before determining whether a super-journal file is
   ** required, as an xSync() callback may add an attached database
   ** to the transaction.
   */
   rc = sqlite3VtabSync(db, p);
 
   /* This loop determines (a) if the commit hook should be invoked and
-  ** (b) how many database files have open write transactions, not 
-  ** including the temp database. (b) is important because if more than 
-  ** one database file has an open write transaction, a master journal
+  ** (b) how many database files have open write transactions, not
+  ** including the temp database. (b) is important because if more than
+  ** one database file has an open write transaction, a super-journal
   ** file is required for an atomic commit.
-  */ 
-  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
+  */
+  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
     Btree *pBt = db->aDb[i].pBt;
-    if( sqlite3BtreeIsInTrans(pBt) ){
-      /* Whether or not a database might need a master journal depends upon
+    if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
+      /* Whether or not a database might need a super-journal depends upon
       ** its journal mode (among other things).  This matrix determines which
-      ** journal modes use a master journal and which do not */
+      ** journal modes use a super-journal and which do not */
       static const u8 aMJNeeded[] = {
         /* DELETE   */  1,
         /* PERSIST   */ 1,
@@ -79258,7 +80882,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
       if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
        && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
        && sqlite3PagerIsMemdb(pPager)==0
-      ){ 
+      ){
         assert( i!=1 );
         nTrans++;
       }
@@ -79280,11 +80904,11 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
 
   /* The simple case - no more than one database file (not counting the
   ** TEMP database) has a transaction active.   There is no need for the
-  ** master-journal.
+  ** super-journal.
   **
   ** If the return value of sqlite3BtreeGetFilename() is a zero length
-  ** string, it means the main database is :memory: or a temp file.  In 
-  ** that case we do not support atomic multi-file commits, so use the 
+  ** string, it means the main database is :memory: or a temp file.  In
+  ** that case we do not support atomic multi-file commits, so use the
   ** simple case then too.
   */
   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
@@ -79297,7 +80921,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
       }
     }
 
-    /* Do the commit only if all databases successfully complete phase 1. 
+    /* Do the commit only if all databases successfully complete phase 1.
     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
     ** IO error while deleting or truncating a journal file. It is unlikely,
     ** but could happen. In this case abandon processing and return the error.
@@ -79314,124 +80938,125 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
   }
 
   /* The complex case - There is a multi-file write-transaction active.
-  ** This requires a master journal file to ensure the transaction is
+  ** This requires a super-journal file to ensure the transaction is
   ** committed atomically.
   */
 #ifndef SQLITE_OMIT_DISKIO
   else{
     sqlite3_vfs *pVfs = db->pVfs;
-    char *zMaster = 0;   /* File-name for the master journal */
+    char *zSuper = 0;   /* File-name for the super-journal */
     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
-    sqlite3_file *pMaster = 0;
+    sqlite3_file *pSuperJrnl = 0;
     i64 offset = 0;
     int res;
     int retryCount = 0;
     int nMainFile;
 
-    /* Select a master journal file name */
+    /* Select a super-journal file name */
     nMainFile = sqlite3Strlen30(zMainFile);
-    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
-    if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
+    zSuper = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
+    if( zSuper==0 ) return SQLITE_NOMEM_BKPT;
+    zSuper += 4;
     do {
       u32 iRandom;
       if( retryCount ){
         if( retryCount>100 ){
-          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
-          sqlite3OsDelete(pVfs, zMaster, 0);
+          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zSuper);
+          sqlite3OsDelete(pVfs, zSuper, 0);
           break;
         }else if( retryCount==1 ){
-          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
+          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zSuper);
         }
       }
       retryCount++;
       sqlite3_randomness(sizeof(iRandom), &iRandom);
-      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
+      sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
                                (iRandom>>8)&0xffffff, iRandom&0xff);
-      /* The antipenultimate character of the master journal name must
+      /* The antipenultimate character of the super-journal name must
       ** be "9" to avoid name collisions when using 8+3 filenames. */
-      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
-      sqlite3FileSuffix3(zMainFile, zMaster);
-      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
+      assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
+      sqlite3FileSuffix3(zMainFile, zSuper);
+      rc = sqlite3OsAccess(pVfs, zSuper, SQLITE_ACCESS_EXISTS, &res);
     }while( rc==SQLITE_OK && res );
     if( rc==SQLITE_OK ){
-      /* Open the master journal. */
-      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
+      /* Open the super-journal. */
+      rc = sqlite3OsOpenMalloc(pVfs, zSuper, &pSuperJrnl,
           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
-          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
+          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_SUPER_JOURNAL, 0
       );
     }
     if( rc!=SQLITE_OK ){
-      sqlite3DbFree(db, zMaster);
+      sqlite3DbFree(db, zSuper-4);
       return rc;
     }
+
     /* Write the name of each database file in the transaction into the new
-    ** master journal file. If an error occurs at this point close
-    ** and delete the master journal file. All the individual journal files
-    ** still have 'null' as the master journal pointer, so they will roll
+    ** super-journal file. If an error occurs at this point close
+    ** and delete the super-journal file. All the individual journal files
+    ** still have 'null' as the super-journal pointer, so they will roll
     ** back independently if a failure occurs.
     */
     for(i=0; i<db->nDb; i++){
       Btree *pBt = db->aDb[i].pBt;
-      if( sqlite3BtreeIsInTrans(pBt) ){
+      if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
         char const *zFile = sqlite3BtreeGetJournalname(pBt);
         if( zFile==0 ){
           continue;  /* Ignore TEMP and :memory: databases */
         }
         assert( zFile[0]!=0 );
-        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
+        rc = sqlite3OsWrite(pSuperJrnl, zFile, sqlite3Strlen30(zFile)+1,offset);
         offset += sqlite3Strlen30(zFile)+1;
         if( rc!=SQLITE_OK ){
-          sqlite3OsCloseFree(pMaster);
-          sqlite3OsDelete(pVfs, zMaster, 0);
-          sqlite3DbFree(db, zMaster);
+          sqlite3OsCloseFree(pSuperJrnl);
+          sqlite3OsDelete(pVfs, zSuper, 0);
+          sqlite3DbFree(db, zSuper-4);
           return rc;
         }
       }
     }
 
-    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
+    /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
     ** flag is set this is not required.
     */
-    if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
-     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
+    if( 0==(sqlite3OsDeviceCharacteristics(pSuperJrnl)&SQLITE_IOCAP_SEQUENTIAL)
+     && SQLITE_OK!=(rc = sqlite3OsSync(pSuperJrnl, SQLITE_SYNC_NORMAL))
     ){
-      sqlite3OsCloseFree(pMaster);
-      sqlite3OsDelete(pVfs, zMaster, 0);
-      sqlite3DbFree(db, zMaster);
+      sqlite3OsCloseFree(pSuperJrnl);
+      sqlite3OsDelete(pVfs, zSuper, 0);
+      sqlite3DbFree(db, zSuper-4);
       return rc;
     }
 
     /* Sync all the db files involved in the transaction. The same call
-    ** sets the master journal pointer in each individual journal. If
-    ** an error occurs here, do not delete the master journal file.
+    ** sets the super-journal pointer in each individual journal. If
+    ** an error occurs here, do not delete the super-journal file.
     **
     ** If the error occurs during the first call to
     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
-    ** master journal file will be orphaned. But we cannot delete it,
-    ** in case the master journal file name was written into the journal
+    ** super-journal file will be orphaned. But we cannot delete it,
+    ** in case the super-journal file name was written into the journal
     ** file before the failure occurred.
     */
-    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
+    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
       Btree *pBt = db->aDb[i].pBt;
       if( pBt ){
-        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
+        rc = sqlite3BtreeCommitPhaseOne(pBt, zSuper);
       }
     }
-    sqlite3OsCloseFree(pMaster);
+    sqlite3OsCloseFree(pSuperJrnl);
     assert( rc!=SQLITE_BUSY );
     if( rc!=SQLITE_OK ){
-      sqlite3DbFree(db, zMaster);
+      sqlite3DbFree(db, zSuper-4);
       return rc;
     }
 
-    /* Delete the master journal file. This commits the transaction. After
+    /* Delete the super-journal file. This commits the transaction. After
     ** doing this the directory is synced again before any individual
     ** transaction files are deleted.
     */
-    rc = sqlite3OsDelete(pVfs, zMaster, 1);
-    sqlite3DbFree(db, zMaster);
-    zMaster = 0;
+    rc = sqlite3OsDelete(pVfs, zSuper, 1);
+    sqlite3DbFree(db, zSuper-4);
+    zSuper = 0;
     if( rc ){
       return rc;
     }
@@ -79445,7 +81070,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
     */
     disable_simulated_io_errors();
     sqlite3BeginBenignMalloc();
-    for(i=0; i<db->nDb; i++){ 
+    for(i=0; i<db->nDb; i++){
       Btree *pBt = db->aDb[i].pBt;
       if( pBt ){
         sqlite3BtreeCommitPhaseTwo(pBt, 1);
@@ -79461,7 +81086,7 @@ static int vdbeCommit(sqlite3 *db, Vdbe *p){
   return rc;
 }
 
-/* 
+/*
 ** This routine checks that the sqlite3.nVdbeActive count variable
 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
 ** currently active. An assertion fails if the two counts do not match.
@@ -79497,10 +81122,10 @@ static void checkActiveVdbeCnt(sqlite3 *db){
 ** If the Vdbe passed as the first argument opened a statement-transaction,
 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
-** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
+** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
 ** statement transaction is committed.
 **
-** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
+** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
 ** Otherwise SQLITE_OK.
 */
 static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
@@ -79513,7 +81138,7 @@ static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
   assert( db->nStatement>0 );
   assert( p->iStatement==(db->nStatement+db->nSavepoint) );
 
-  for(i=0; i<db->nDb; i++){ 
+  for(i=0; i<db->nDb; i++){
     int rc2 = SQLITE_OK;
     Btree *pBt = db->aDb[i].pBt;
     if( pBt ){
@@ -79540,8 +81165,8 @@ static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
     }
   }
 
-  /* If the statement transaction is being rolled back, also restore the 
-  ** database handles deferred constraint counter to the value it had when 
+  /* If the statement transaction is being rolled back, also restore the
+  ** database handles deferred constraint counter to the value it had when
   ** the statement transaction was opened.  */
   if( eOp==SAVEPOINT_ROLLBACK ){
     db->nDeferredCons = p->nStmtDefCons;
@@ -79558,20 +81183,20 @@ SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
 
 
 /*
-** This function is called when a transaction opened by the database 
-** handle associated with the VM passed as an argument is about to be 
+** This function is called when a transaction opened by the database
+** handle associated with the VM passed as an argument is about to be
 ** committed. If there are outstanding deferred foreign key constraint
 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
 **
-** If there are outstanding FK violations and this function returns 
+** If there are outstanding FK violations and this function returns
 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
 ** and write an error message to it. Then return SQLITE_ERROR.
 */
 #ifndef SQLITE_OMIT_FOREIGN_KEY
 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
   sqlite3 *db = p->db;
-  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
-   || (!deferred && p->nFkConstraint>0) 
+  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
+   || (!deferred && p->nFkConstraint>0)
   ){
     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
     p->errorAction = OE_Abort;
@@ -79601,7 +81226,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
 
   /* This function contains the logic that determines if a statement or
   ** transaction will be committed or rolled back as a result of the
-  ** execution of this virtual machine. 
+  ** execution of this virtual machine.
   **
   ** If any of the following errors occur:
   **
@@ -79639,16 +81264,16 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
     if( isSpecialError ){
-      /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
-      ** no rollback is necessary. Otherwise, at least a savepoint 
-      ** transaction must be rolled back to restore the database to a 
+      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
+      ** no rollback is necessary. Otherwise, at least a savepoint
+      ** transaction must be rolled back to restore the database to a
       ** consistent state.
       **
       ** Even if the statement is read-only, it is important to perform
-      ** a statement or transaction rollback operation. If the error 
+      ** a statement or transaction rollback operation. If the error
       ** occurred while writing to the journal, sub-journal or database
       ** file as part of an effort to free up cache space (see function
-      ** pagerStress() in pager.c), the rollback is required to restore 
+      ** pagerStress() in pager.c), the rollback is required to restore
       ** the pager to a consistent state.
       */
       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
@@ -79670,16 +81295,16 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
     if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
       sqlite3VdbeCheckFk(p, 0);
     }
-  
-    /* If the auto-commit flag is set and this is the only active writer 
-    ** VM, then we do either a commit or rollback of the current transaction. 
+
+    /* If the auto-commit flag is set and this is the only active writer
+    ** VM, then we do either a commit or rollback of the current transaction.
     **
-    ** Note: This block also runs if one of the special errors handled 
-    ** above has occurred. 
+    ** Note: This block also runs if one of the special errors handled
+    ** above has occurred.
     */
-    if( !sqlite3VtabInSync(db) 
-     && db->autoCommit 
-     && db->nVdbeWrite==(p->readOnly==0) 
+    if( !sqlite3VtabInSync(db)
+     && db->autoCommit
+     && db->nVdbeWrite==(p->readOnly==0)
     ){
       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
         rc = sqlite3VdbeCheckFk(p, 1);
@@ -79689,10 +81314,10 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
             return SQLITE_ERROR;
           }
           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
-        }else{ 
-          /* The auto-commit flag is true, the vdbe program was successful 
+        }else{
+          /* The auto-commit flag is true, the vdbe program was successful
           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
-          ** key constraints to hold up the transaction. This means a commit 
+          ** key constraints to hold up the transaction. This means a commit
           ** is required. */
           rc = vdbeCommit(db, p);
         }
@@ -79726,7 +81351,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
         p->nChange = 0;
       }
     }
-  
+
     /* If eStatementOp is non-zero, then a statement transaction needs to
     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
     ** do so. If this operation returns an error, and the current statement
@@ -79747,9 +81372,9 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
         p->nChange = 0;
       }
     }
-  
+
     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
-    ** has been rolled back, update the database connection change-counter. 
+    ** has been rolled back, update the database connection change-counter.
     */
     if( p->changeCntOn ){
       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
@@ -79780,7 +81405,7 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
   }
 
   /* If the auto-commit flag is set to true, then any locks that were held
-  ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
+  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
   ** to invoke any required unlock-notify callbacks.
   */
   if( db->autoCommit ){
@@ -79802,7 +81427,7 @@ SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
 
 /*
 ** Copy the error code and error message belonging to the VDBE passed
-** as the first argument to its database handle (so that they will be 
+** as the first argument to its database handle (so that they will be
 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
 **
 ** This function does not clear the VDBE error code or message, just
@@ -79827,7 +81452,7 @@ SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
 
 #ifdef SQLITE_ENABLE_SQLLOG
 /*
-** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
+** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
 ** invoke it.
 */
 static void vdbeInvokeSqllog(Vdbe *v){
@@ -79878,7 +81503,11 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   */
   if( p->pc>=0 ){
     vdbeInvokeSqllog(p);
-    sqlite3VdbeTransferError(p);
+    if( db->pErr || p->zErrMsg ){
+      sqlite3VdbeTransferError(p);
+    }else{
+      db->errCode = p->rc;
+    }
     if( p->runOnlyOnce ) p->expired = 1;
   }else if( p->rc && p->expired ){
     /* The expired flag was set on the VDBE before the first call
@@ -79891,15 +81520,17 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   /* Reset register contents and reclaim error message memory.
   */
 #ifdef SQLITE_DEBUG
-  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
+  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
   ** Vdbe.aMem[] arrays have already been cleaned up.  */
   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
   if( p->aMem ){
     for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
   }
 #endif
-  sqlite3DbFree(db, p->zErrMsg);
-  p->zErrMsg = 0;
+  if( p->zErrMsg ){
+    sqlite3DbFree(db, p->zErrMsg);
+    p->zErrMsg = 0;
+  }
   p->pResultSet = 0;
 #ifdef SQLITE_DEBUG
   p->nWrite = 0;
@@ -79943,7 +81574,7 @@ SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
   p->magic = VDBE_MAGIC_RESET;
   return p->rc & db->errMask;
 }
+
 /*
 ** Clean up and delete a VDBE after execution.  Return an integer which is
 ** the result code.  Write any error message text into *pzErrMsg.
@@ -79964,8 +81595,8 @@ SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
 ** the first argument.
 **
 ** Or, if iOp is greater than or equal to zero, then the destructor is
-** only invoked for those auxiliary data pointers created by the user 
-** function invoked by the OP_Function opcode at instruction iOp of 
+** only invoked for those auxiliary data pointers created by the user
+** function invoked by the OP_Function opcode at instruction iOp of
 ** VM pVdbe, and only then if:
 **
 **    * the associated function parameter is the 32nd or later (counting
@@ -80069,7 +81700,7 @@ SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
 ** carried out.  Seek the cursor now.  If an error occurs, return
 ** the appropriate error code.
 */
-static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
+SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
   int res, rc;
 #ifdef SQLITE_TEST
   extern int sqlite3_search_count;
@@ -80131,17 +81762,17 @@ SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
 ** If the cursor is already pointing to the correct row and that row has
 ** not been deleted out from under the cursor, then this routine is a no-op.
 */
-SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
+SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, u32 *piCol){
   VdbeCursor *p = *pp;
   assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
   if( p->deferredMoveto ){
-    int iMap;
-    if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
+    u32 iMap;
+    if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){
       *pp = p->pAltCursor;
       *piCol = iMap - 1;
       return SQLITE_OK;
     }
-    return handleDeferredMoveto(p);
+    return sqlite3VdbeFinishMoveto(p);
   }
   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
     return handleMovedCursor(p);
@@ -80268,7 +81899,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
 ** The sizes for serial types less than 128
 */
 static const u8 sqlite3SmallTypeSizes[] = {
-        /*  0   1   2   3   4   5   6   7   8   9 */   
+        /*  0   1   2   3   4   5   6   7   8   9 */
 /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
 /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
 /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
@@ -80291,19 +81922,19 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
   if( serial_type>=128 ){
     return (serial_type-12)/2;
   }else{
-    assert( serial_type<12 
+    assert( serial_type<12
             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
     return sqlite3SmallTypeSizes[serial_type];
   }
 }
 SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
   assert( serial_type<128 );
-  return sqlite3SmallTypeSizes[serial_type];  
+  return sqlite3SmallTypeSizes[serial_type];
 }
 
 /*
-** If we are on an architecture with mixed-endian floating 
-** points (ex: ARM7) then swap the lower 4 bytes with the 
+** If we are on an architecture with mixed-endian floating
+** points (ex: ARM7) then swap the lower 4 bytes with the
 ** upper 4 bytes.  Return the result.
 **
 ** For most architectures, this is a no-op.
@@ -80325,7 +81956,7 @@ SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
 ** (2007-08-30)  Frank van Vugt has studied this problem closely
 ** and has send his findings to the SQLite developers.  Frank
 ** writes that some Linux kernels offer floating point hardware
-** emulation that uses only 32-bit mantissas instead of a full 
+** emulation that uses only 32-bit mantissas instead of a full
 ** 48-bits as required by the IEEE standard.  (This is the
 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
 ** byte swapping becomes very complicated.  To avoid problems,
@@ -80355,7 +81986,7 @@ static u64 floatSwap(u64 in){
 #endif
 
 /*
-** Write the serialized data blob for the value stored in pMem into 
+** Write the serialized data blob for the value stored in pMem into
 ** buf. It is assumed that the caller has allocated sufficient space.
 ** Return the number of bytes written.
 **
@@ -80366,7 +81997,7 @@ static u64 floatSwap(u64 in){
 ** Return the number of bytes actually written into buf[].  The number
 ** of bytes in the zero-filled tail is included in the return value only
 ** if those bytes were zeroed in buf[].
-*/ 
+*/
 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
   u32 len;
 
@@ -80420,7 +82051,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
 ** The few cases that require local variables are broken out into a separate
 ** routine so that in most cases the overhead of moving the stack pointer
 ** is avoided.
-*/ 
+*/
 static u32 serialGet(
   const unsigned char *buf,     /* Buffer to deserialize from */
   u32 serial_type,              /* Serial type to deserialize */
@@ -80504,7 +82135,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
       ** twos-complement integer. */
       pMem->u.i = FOUR_BYTE_INT(buf);
-#ifdef __HP_cc 
+#ifdef __HP_cc
       /* Work around a sign-extension bug in the HP compiler for HP/UX */
       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
 #endif
@@ -80556,7 +82187,7 @@ SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
 ** The space is either allocated using sqlite3DbMallocRaw() or from within
 ** the unaligned buffer passed via the second and third arguments (presumably
 ** stack space). If the former, then *ppFree is set to a pointer that should
-** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
+** be eventually freed by the caller using sqlite3DbFree(). Or, if the
 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
 ** before returning.
 **
@@ -80578,10 +82209,10 @@ SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
 }
 
 /*
-** Given the nKey-byte encoding of a record in pKey[], populate the 
+** Given the nKey-byte encoding of a record in pKey[], populate the
 ** UnpackedRecord structure indicated by the fourth argument with the
 ** contents of the decoded record.
-*/ 
+*/
 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   KeyInfo *pKeyInfo,     /* Information about the record format */
   int nKey,              /* Size of the binary record */
@@ -80589,7 +82220,7 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   UnpackedRecord *p      /* Populate this structure before returning. */
 ){
   const unsigned char *aKey = (const unsigned char *)pKey;
-  u32 d; 
+  u32 d;
   u32 idx;                        /* Offset in aKey[] to read from */
   u16 u;                          /* Unsigned loop counter */
   u32 szHdr;
@@ -80615,7 +82246,7 @@ SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
   }
   if( d>(u32)nKey && u ){
     assert( CORRUPT_DB );
-    /* In a corrupt record entry, the last pMem might have been set up using 
+    /* In a corrupt record entry, the last pMem might have been set up using
     ** uninitialized memory. Overwrite its value with NULL, to prevent
     ** warnings from MSAN. */
     sqlite3VdbeMemSetNull(pMem-1);
@@ -80659,13 +82290,13 @@ static int vdbeRecordCompareDebug(
 
   /* Compilers may complain that mem1.u.i is potentially uninitialized.
   ** We could initialize it, as shown here, to silence those complaints.
-  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
+  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
   ** the unnecessary initialization has a measurable negative performance
   ** impact, since this routine is a very high runner.  And so, we choose
   ** to ignore the compiler warnings and leave this variable uninitialized.
   */
   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
-  
+
   idx1 = getVarint32(aKey1, szHdr1);
   if( szHdr1>98307 ) return SQLITE_CORRUPT;
   d1 = szHdr1;
@@ -80686,7 +82317,7 @@ static int vdbeRecordCompareDebug(
     ** sqlite3VdbeSerialTypeLen() in the common case.
     */
     if( d1+(u64)serial_type1+2>(u64)nKey1
-     && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1 
+     && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
     ){
       break;
     }
@@ -80702,7 +82333,7 @@ static int vdbeRecordCompareDebug(
     if( rc!=0 ){
       assert( mem1.szMalloc==0 );  /* See comment below */
       if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
-       && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null)) 
+       && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
       ){
         rc = -rc;
       }
@@ -80748,7 +82379,7 @@ debugCompareEnd:
 ** incorrectly.
 */
 static void vdbeAssertFieldCountWithinLimits(
-  int nKey, const void *pKey,   /* The record to verify */ 
+  int nKey, const void *pKey,   /* The record to verify */
   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
 ){
   int nField = 0;
@@ -80774,7 +82405,7 @@ static void vdbeAssertFieldCountWithinLimits(
 /*
 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
 ** using the collation sequence pColl. As usual, return a negative , zero
-** or positive value if *pMem1 is less than, equal to or greater than 
+** or positive value if *pMem1 is less than, equal to or greater than
 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
 */
 static int vdbeCompareMemString(
@@ -80863,9 +82494,12 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem
 static int sqlite3IntFloatCompare(i64 i, double r){
   if( sizeof(LONGDOUBLE_TYPE)>8 ){
     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
+    testcase( x<r );
+    testcase( x>r );
+    testcase( x==r );
     if( x<r ) return -1;
-    if( x>r ) return +1;
-    return 0;
+    if( x>r ) return +1;  /*NO_TEST*/ /* work around bugs in gcov */
+    return 0;             /*NO_TEST*/ /* work around bugs in gcov */
   }else{
     i64 y;
     double s;
@@ -80898,7 +82532,7 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C
   f2 = pMem2->flags;
   combined_flags = f1|f2;
   assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
+
   /* If one value is NULL, it is less than the other. If both values
   ** are NULL, return 0.
   */
@@ -80961,7 +82595,7 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C
     }
 
     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
-    assert( pMem1->enc==SQLITE_UTF8 || 
+    assert( pMem1->enc==SQLITE_UTF8 ||
             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
 
     /* The collation sequence must be defined at this point, even if
@@ -80976,7 +82610,7 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C
     /* If a NULL pointer was passed as the collate function, fall through
     ** to the blob case and use memcmp().  */
   }
+
   /* Both values must be blobs.  Compare using memcmp().  */
   return sqlite3BlobCompare(pMem1, pMem2);
 }
@@ -80984,7 +82618,7 @@ SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const C
 
 /*
 ** The first argument passed to this function is a serial-type that
-** corresponds to an integer - all values between 1 and 9 inclusive 
+** corresponds to an integer - all values between 1 and 9 inclusive
 ** except 7. The second points to a buffer containing an integer value
 ** serialized according to serial_type. This function deserializes
 ** and returns the value.
@@ -81026,7 +82660,7 @@ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
 /*
 ** This function compares the two table rows or index records
 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
-** or positive integer if key1 is less than, equal to or 
+** or positive integer if key1 is less than, equal to or
 ** greater than key2.  The {nKey1, pKey1} key must be a blob
 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
 ** key must be a parsed key such as obtained from
@@ -81035,12 +82669,12 @@ static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
 ** If argument bSkip is non-zero, it is assumed that the caller has already
 ** determined that the first fields of the keys are equal.
 **
-** Key1 and Key2 do not have to contain the same number of fields. If all 
-** fields that appear in both keys are equal, then pPKey2->default_rc is 
+** Key1 and Key2 do not have to contain the same number of fields. If all
+** fields that appear in both keys are equal, then pPKey2->default_rc is
 ** returned.
 **
-** If database corruption is discovered, set pPKey2->errCode to 
-** SQLITE_CORRUPT and return 0. If an OOM error is encountered, 
+** If database corruption is discovered, set pPKey2->errCode to
+** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
 */
@@ -81074,13 +82708,13 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
     d1 = szHdr1;
     i = 0;
   }
-  if( d1>(unsigned)nKey1 ){ 
+  if( d1>(unsigned)nKey1 ){
     pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
     return 0;  /* Corruption */
   }
 
   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
-  assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField 
+  assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
        || CORRUPT_DB );
   assert( pPKey2->pKeyInfo->aSortFlags!=0 );
   assert( pPKey2->pKeyInfo->nKeyField>0 );
@@ -81117,7 +82751,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
       serial_type = aKey1[idx1];
       if( serial_type>=10 ){
         /* Serial types 12 or greater are strings and blobs (greater than
-        ** numbers). Types 10 and 11 are currently "reserved for future 
+        ** numbers). Types 10 and 11 are currently "reserved for future
         ** use", so it doesn't really matter what the results of comparing
         ** them to numberic values are.  */
         rc = +1;
@@ -81139,7 +82773,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
 
     /* RHS is a string */
     else if( pRhs->flags & MEM_Str ){
-      getVarint32(&aKey1[idx1], serial_type);
+      getVarint32NR(&aKey1[idx1], serial_type);
       testcase( serial_type==12 );
       if( serial_type<12 ){
         rc = -1;
@@ -81165,7 +82799,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
         }else{
           int nCmp = MIN(mem1.n, pRhs->n);
           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
-          if( rc==0 ) rc = mem1.n - pRhs->n; 
+          if( rc==0 ) rc = mem1.n - pRhs->n;
         }
       }
     }
@@ -81173,7 +82807,7 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
     /* RHS is a blob */
     else if( pRhs->flags & MEM_Blob ){
       assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
-      getVarint32(&aKey1[idx1], serial_type);
+      getVarint32NR(&aKey1[idx1], serial_type);
       testcase( serial_type==12 );
       if( serial_type<12 || (serial_type & 0x01) ){
         rc = -1;
@@ -81234,8 +82868,8 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
   /* rc==0 here means that one or both of the keys ran out of fields and
   ** all the fields up to that point were equal. Return the default_rc
   ** value.  */
-  assert( CORRUPT_DB 
-       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) 
+  assert( CORRUPT_DB
+       || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
        || pPKey2->pKeyInfo->db->mallocFailed
   );
   pPKey2->eqSeen = 1;
@@ -81250,8 +82884,8 @@ SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
 
 
 /*
-** This function is an optimized version of sqlite3VdbeRecordCompare() 
-** that (a) the first field of pPKey2 is an integer, and (b) the 
+** This function is an optimized version of sqlite3VdbeRecordCompare()
+** that (a) the first field of pPKey2 is an integer, and (b) the
 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
 ** byte (i.e. is less than 128).
 **
@@ -81306,7 +82940,7 @@ static int vdbeRecordCompareInt(
       testcase( lhs<0 );
       break;
     }
-    case 8: 
+    case 8:
       lhs = 0;
       break;
     case 9:
@@ -81314,11 +82948,11 @@ static int vdbeRecordCompareInt(
       break;
 
     /* This case could be removed without changing the results of running
-    ** this code. Including it causes gcc to generate a faster switch 
+    ** this code. Including it causes gcc to generate a faster switch
     ** statement (since the range of switch targets now starts at zero and
     ** is contiguous) but does not cause any duplicate code to be generated
-    ** (as gcc is clever enough to combine the two like cases). Other 
-    ** compilers might be similar.  */ 
+    ** (as gcc is clever enough to combine the two like cases). Other
+    ** compilers might be similar.  */
     case 0: case 7:
       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
 
@@ -81332,7 +82966,7 @@ static int vdbeRecordCompareInt(
   }else if( v<lhs ){
     res = pPKey2->r2;
   }else if( pPKey2->nField>1 ){
-    /* The first fields of the two keys are equal. Compare the trailing 
+    /* The first fields of the two keys are equal. Compare the trailing
     ** fields.  */
     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
   }else{
@@ -81347,9 +82981,9 @@ static int vdbeRecordCompareInt(
 }
 
 /*
-** This function is an optimized version of sqlite3VdbeRecordCompare() 
+** This function is an optimized version of sqlite3VdbeRecordCompare()
 ** that (a) the first field of pPKey2 is a string, that (b) the first field
-** uses the collation sequence BINARY and (c) that the size-of-header varint 
+** uses the collation sequence BINARY and (c) that the size-of-header varint
 ** at the start of (pKey1/nKey1) fits in a single byte.
 */
 static int vdbeRecordCompareString(
@@ -81362,10 +82996,13 @@ static int vdbeRecordCompareString(
 
   assert( pPKey2->aMem[0].flags & MEM_Str );
   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
-  getVarint32(&aKey1[1], serial_type);
+  serial_type = (u8)(aKey1[1]);
+  if( serial_type >= 0x80 ){
+    sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
+  }
   if( serial_type<12 ){
     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
-  }else if( !(serial_type & 0x01) ){ 
+  }else if( !(serial_type & 0x01) ){
     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
   }else{
     int nCmp;
@@ -81417,7 +83054,7 @@ SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
   /* varintRecordCompareInt() and varintRecordCompareString() both assume
   ** that the size-of-header varint that occurs at the start of each record
   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
-  ** also assumes that it is safe to overread a buffer by at least the 
+  ** also assumes that it is safe to overread a buffer by at least the
   ** maximum possible legal header size plus 8 bytes. Because there is
   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
   ** buffer passed to varintRecordCompareInt() this makes it convenient to
@@ -81475,7 +83112,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
   /* Get the size of the index entry.  Only indices entries of less
   ** than 2GiB are support - anything large must be database corruption.
   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
-  ** this code can safely assume that nCellKey is 32-bits  
+  ** this code can safely assume that nCellKey is 32-bits
   */
   assert( sqlite3BtreeCursorIsValid(pCur) );
   nCellKey = sqlite3BtreePayloadSize(pCur);
@@ -81483,13 +83120,13 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
 
   /* Read in the complete content of the index entry */
   sqlite3VdbeMemInit(&m, db, 0);
-  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
+  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
   if( rc ){
     return rc;
   }
 
   /* The index entry must begin with a header size */
-  (void)getVarint32((u8*)m.z, szHdr);
+  getVarint32NR((u8*)m.z, szHdr);
   testcase( szHdr==3 );
   testcase( szHdr==m.n );
   testcase( szHdr>0x7fffffff );
@@ -81500,7 +83137,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
 
   /* The last field of the index should be an integer - the ROWID.
   ** Verify that the last entry really is an integer. */
-  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
+  getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
   testcase( typeRowid==1 );
   testcase( typeRowid==2 );
   testcase( typeRowid==3 );
@@ -81540,7 +83177,7 @@ idx_rowid_corruption:
 **
 ** pUnpacked is either created without a rowid or is truncated so that it
 ** omits the rowid at the end.  The rowid at the end of the index entry
-** is ignored as well.  Hence, this routine only compares the prefixes 
+** is ignored as well.  Hence, this routine only compares the prefixes
 ** of the keys prior to the final rowid, not the entire key.
 */
 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
@@ -81565,7 +83202,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
     return SQLITE_CORRUPT_BKPT;
   }
   sqlite3VdbeMemInit(&m, db, 0);
-  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
+  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
   if( rc ){
     return rc;
   }
@@ -81576,7 +83213,7 @@ SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
 
 /*
 ** This routine sets the value to be returned by subsequent calls to
-** sqlite3_changes() on the database handle 'db'. 
+** sqlite3_changes() on the database handle 'db'.
 */
 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, u64 nChange){
   assert( sqlite3_mutex_held(db->mutex) );
@@ -81633,7 +83270,7 @@ SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
 
 /*
 ** Return a pointer to an sqlite3_value structure containing the value bound
-** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
+** parameter iVar of VM v. Except, if the value is an SQL NULL, return
 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
 ** constants) to the value before returning it.
 **
@@ -81681,13 +83318,25 @@ SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
 ** features such as 'now'.
 */
 SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
+  const VdbeOp *pOp;
 #ifdef SQLITE_ENABLE_STAT4
   if( pCtx->pVdbe==0 ) return 1;
 #endif
-  if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
-    sqlite3_result_error(pCtx, 
-       "non-deterministic function in index expression or CHECK constraint",
-       -1);
+  pOp = pCtx->pVdbe->aOp + pCtx->iOp;
+  if( pOp->opcode==OP_PureFunc ){
+    const char *zContext;
+    char *zMsg;
+    if( pOp->p5 & NC_IsCheck ){
+      zContext = "a CHECK constraint";
+    }else if( pOp->p5 & NC_GenCol ){
+      zContext = "a generated column";
+    }else{
+      zContext = "an index";
+    }
+    zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
+                           pCtx->pFunc->zName, zContext);
+    sqlite3_result_error(pCtx, zMsg, -1);
+    sqlite3_free(zMsg);
     return 0;
   }
   return 1;
@@ -81713,7 +83362,7 @@ SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
 
 /*
-** If the second argument is not NULL, release any allocations associated 
+** If the second argument is not NULL, release any allocations associated
 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
 ** structure itself, using sqlite3DbFree().
 **
@@ -81767,7 +83416,7 @@ SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
     }
   }
 
-  assert( pCsr->nField==pTab->nCol 
+  assert( pCsr->nField==pTab->nCol
        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
   );
 
@@ -81876,7 +83525,7 @@ static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
   }
 #endif
   if( db->mTrace & SQLITE_TRACE_PROFILE ){
-    db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
+    db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
   }
   p->startTime = 0;
 }
@@ -82158,7 +83807,7 @@ SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
 SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
   sqlite3ValueFree(pOld);
 }
-  
+
 
 /**************************** sqlite3_result_  *******************************
 ** The following routines are used by user-defined functions to specify
@@ -82200,9 +83849,9 @@ static int invokeValueDestructor(
 }
 #undef sqlite3_result_blob
 SQLITE_API void sqlite3_result_blob(
-  sqlite3_context *pCtx, 
-  const void *z, 
-  int n, 
+  sqlite3_context *pCtx,
+  const void *z,
+  int n,
   void (*xDel)(void *)
 ){
   assert( n>=0 );
@@ -82210,8 +83859,8 @@ SQLITE_API void sqlite3_result_blob(
   setResultStrOrError(pCtx, z, n, 0, xDel);
 }
 SQLITE_API void sqlite3_result_blob64(
-  sqlite3_context *pCtx, 
-  const void *z, 
+  sqlite3_context *pCtx,
+  const void *z,
   sqlite3_uint64 n,
   void (*xDel)(void *)
 ){
@@ -82271,8 +83920,8 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubt
 }
 #undef sqlite3_result_text
 SQLITE_API void sqlite3_result_text(
-  sqlite3_context *pCtx, 
-  const char *z, 
+  sqlite3_context *pCtx,
+  const char *z,
   int n,
   void (*xDel)(void *)
 ){
@@ -82280,8 +83929,8 @@ SQLITE_API void sqlite3_result_text(
   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
 }
 SQLITE_API void sqlite3_result_text64(
-  sqlite3_context *pCtx, 
-  const char *z, 
+  sqlite3_context *pCtx,
+  const char *z,
   sqlite3_uint64 n,
   void (*xDel)(void *),
   unsigned char enc
@@ -82303,27 +83952,27 @@ SQLITE_API void sqlite3_result_text64(
 #undef sqlite3_result_text16be
 #undef sqlite3_result_text16le
 SQLITE_API void sqlite3_result_text16(
-  sqlite3_context *pCtx, 
-  const void *z, 
-  int n, 
+  sqlite3_context *pCtx,
+  const void *z,
+  int n,
   void (*xDel)(void *)
 ){
   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
 }
 SQLITE_API void sqlite3_result_text16be(
-  sqlite3_context *pCtx, 
-  const void *z, 
-  int n, 
+  sqlite3_context *pCtx,
+  const void *z,
+  int n,
   void (*xDel)(void *)
 ){
   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
 }
 SQLITE_API void sqlite3_result_text16le(
-  sqlite3_context *pCtx, 
-  const void *z, 
-  int n, 
+  sqlite3_context *pCtx,
+  const void *z,
+  int n,
   void (*xDel)(void *)
 ){
   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
@@ -82354,7 +84003,7 @@ SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
 #endif
   if( pCtx->pOut->flags & MEM_Null ){
-    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
+    sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
                          SQLITE_UTF8, SQLITE_STATIC);
   }
 }
@@ -82363,7 +84012,7 @@ SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   pCtx->isError = SQLITE_TOOBIG;
-  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
+  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
                        SQLITE_UTF8, SQLITE_STATIC);
 }
 
@@ -82380,7 +84029,7 @@ SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
 ** a MEM_IntReal value.  See the SQLITE_TESTCTRL_RESULT_INTREAL
 ** test-control.
 */
-SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){ 
+SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   if( pCtx->pOut->flags & MEM_Int ){
     pCtx->pOut->flags &= ~MEM_Int;
@@ -82391,7 +84040,7 @@ SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
 
 
 /*
-** This function is called after a transaction has been committed. It 
+** This function is called after a transaction has been committed. It
 ** invokes callbacks registered with sqlite3_wal_hook() as required.
 */
 static int doWalCallbacks(sqlite3 *db){
@@ -82420,7 +84069,7 @@ static int doWalCallbacks(sqlite3 *db){
 ** statement is completely executed or an error occurs.
 **
 ** This routine implements the bulk of the logic behind the sqlite_step()
-** API.  The only thing omitted is the automatic recompile if a 
+** API.  The only thing omitted is the automatic recompile if a
 ** schema change has occurred.  That detail is handled by the
 ** outer sqlite3_step() wrapper procedure.
 */
@@ -82434,15 +84083,15 @@ static int sqlite3Step(Vdbe *p){
     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
     ** with version 3.7.0, we changed this so that sqlite3_reset() would
     ** be called automatically instead of throwing the SQLITE_MISUSE error.
-    ** This "automatic-reset" change is not technically an incompatibility, 
+    ** This "automatic-reset" change is not technically an incompatibility,
     ** since any application that receives an SQLITE_MISUSE is broken by
     ** definition.
     **
     ** Nevertheless, some published applications that were originally written
-    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
+    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
     ** returns, and those were broken by the automatic-reset change.  As a
     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
-    ** legacy behavior of returning SQLITE_MISUSE for cases where the 
+    ** legacy behavior of returning SQLITE_MISUSE for cases where the
     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
     ** or SQLITE_BUSY error.
     */
@@ -82467,6 +84116,13 @@ static int sqlite3Step(Vdbe *p){
   if( p->pc<0 && p->expired ){
     p->rc = SQLITE_SCHEMA;
     rc = SQLITE_ERROR;
+    if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
+      /* If this statement was prepared using saved SQL and an
+      ** error has occurred, then return the error code in p->rc to the
+      ** caller. Set the error code in the database handle to the same value.
+      */
+      rc = sqlite3VdbeTransferError(p);
+    }
     goto end_of_step;
   }
   if( p->pc<0 ){
@@ -82475,10 +84131,10 @@ static int sqlite3Step(Vdbe *p){
     ** from interrupting a statement that has not yet started.
     */
     if( db->nVdbeActive==0 ){
-      db->u1.isInterrupted = 0;
+      AtomicStore(&db->u1.isInterrupted, 0);
     }
 
-    assert( db->nVdbeWrite>0 || db->autoCommit==0 
+    assert( db->nVdbeWrite>0 || db->autoCommit==0
         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
     );
 
@@ -82522,35 +84178,27 @@ static int sqlite3Step(Vdbe *p){
       if( p->rc!=SQLITE_OK ){
         rc = SQLITE_ERROR;
       }
+    }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
+      /* If this statement was prepared using saved SQL and an
+      ** error has occurred, then return the error code in p->rc to the
+      ** caller. Set the error code in the database handle to the same value.
+      */
+      rc = sqlite3VdbeTransferError(p);
     }
   }
 
   db->errCode = rc;
   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
     p->rc = SQLITE_NOMEM_BKPT;
+    if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
   }
 end_of_step:
-  /* At this point local variable rc holds the value that should be 
-  ** returned if this statement was compiled using the legacy 
-  ** sqlite3_prepare() interface. According to the docs, this can only
-  ** be one of the values in the first assert() below. Variable p->rc 
-  ** contains the value that would be returned if sqlite3_finalize() 
-  ** were called on statement p.
-  */
-  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
+  /* There are only a limited number of result codes allowed from the
+  ** statements prepared using the legacy sqlite3_prepare() interface */
+  assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
+       || rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
        || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
   );
-  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
-  if( rc!=SQLITE_ROW 
-   && rc!=SQLITE_DONE
-   && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
-  ){
-    /* If this statement was prepared using saved SQL and an 
-    ** error has occurred, then return the error code in p->rc to the
-    ** caller. Set the error code in the database handle to the same value.
-    */ 
-    rc = sqlite3VdbeTransferError(p);
-  }
   return (rc&db->errMask);
 }
 
@@ -82576,15 +84224,15 @@ SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
     int savedPc = v->pc;
     rc = sqlite3Reprepare(v);
     if( rc!=SQLITE_OK ){
-      /* This case occurs after failing to recompile an sql statement. 
-      ** The error message from the SQL compiler has already been loaded 
-      ** into the database handle. This block copies the error message 
+      /* This case occurs after failing to recompile an sql statement.
+      ** The error message from the SQL compiler has already been loaded
+      ** into the database handle. This block copies the error message
       ** from the database handle into the statement and sets the statement
-      ** program counter to 0 to ensure that when the statement is 
+      ** program counter to 0 to ensure that when the statement is
       ** finalized or reset the parser error message is available via
       ** sqlite3_errmsg() and sqlite3_errcode().
       */
-      const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
+      const char *zErr = (const char *)sqlite3_value_text(db->pErr);
       sqlite3DbFree(db, v->zErrMsg);
       if( !db->mallocFailed ){
         v->zErrMsg = sqlite3DbStrDup(db, zErr);
@@ -82746,9 +84394,9 @@ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
 ** access code.
 */
 SQLITE_API void sqlite3_set_auxdata(
-  sqlite3_context *pCtx, 
-  int iArg, 
-  void *pAux, 
+  sqlite3_context *pCtx,
+  int iArg,
+  void *pAux,
   void (*xDelete)(void*)
 ){
   AuxData *pAuxData;
@@ -82790,7 +84438,7 @@ failed:
 
 #ifndef SQLITE_OMIT_DEPRECATED
 /*
-** Return the number of times the Step function of an aggregate has been 
+** Return the number of times the Step function of an aggregate has been
 ** called.
 **
 ** This function is deprecated.  Do not use it for new code.  It is
@@ -82835,9 +84483,9 @@ static const Mem *columnNullValue(void){
   ** these assert()s from failing, when building with SQLITE_DEBUG defined
   ** using gcc, we force nullMem to be 8-byte aligned using the magical
   ** __attribute__((aligned(8))) macro.  */
-  static const Mem nullMem 
+  static const Mem nullMem
 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
-    __attribute__((aligned(8))) 
+    __attribute__((aligned(8)))
 #endif
     = {
         /* .u          = */ {0},
@@ -82883,9 +84531,9 @@ static Mem *columnMem(sqlite3_stmt *pStmt, int i){
 }
 
 /*
-** This function is called after invoking an sqlite3_value_XXX function on a 
+** This function is called after invoking an sqlite3_value_XXX function on a
 ** column value (i.e. a value returned by evaluating an SQL expression in the
-** select list of a SELECT statement) that may cause a malloc() failure. If 
+** select list of a SELECT statement) that may cause a malloc() failure. If
 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
 ** code of statement pStmt set to SQLITE_NOMEM.
 **
@@ -82924,8 +84572,8 @@ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
   const void *val;
   val = sqlite3_value_blob( columnMem(pStmt,i) );
   /* Even though there is no encoding conversion, value_blob() might
-  ** need to call malloc() to expand the result of a zeroblob() 
-  ** expression. 
+  ** need to call malloc() to expand the result of a zeroblob()
+  ** expression.
   */
   columnMallocFailure(pStmt);
   return val;
@@ -83126,11 +84774,11 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
 
 
 /******************************* sqlite3_bind_  ***************************
-** 
+**
 ** Routines used to attach values to wildcards in a compiled SQL statement.
 */
 /*
-** Unbind the value bound to variable i in virtual machine p. This is the 
+** Unbind the value bound to variable i in virtual machine p. This is the
 ** the same as binding a NULL value to the column. If the "i" parameter is
 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
 **
@@ -83149,7 +84797,7 @@ static int vdbeUnbind(Vdbe *p, int i){
   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
     sqlite3Error(p->db, SQLITE_MISUSE);
     sqlite3_mutex_leave(p->db->mutex);
-    sqlite3_log(SQLITE_MISUSE, 
+    sqlite3_log(SQLITE_MISUSE,
         "bind on a busy prepared statement: [%s]", p->zSql);
     return SQLITE_MISUSE_BKPT;
   }
@@ -83164,10 +84812,10 @@ static int vdbeUnbind(Vdbe *p, int i){
   pVar->flags = MEM_Null;
   p->db->errCode = SQLITE_OK;
 
-  /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
+  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
   ** binding a new value to this variable invalidates the current query plan.
   **
-  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
+  ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
   ** parameter in the WHERE clause might influence the choice of query plan
   ** for a statement, then the statement will be automatically recompiled,
   ** as if there had been a schema change, on the first sqlite3_step() call
@@ -83221,10 +84869,10 @@ static int bindText(
 */
 #undef sqlite3_bind_blob
 SQLITE_API int sqlite3_bind_blob(
-  sqlite3_stmt *pStmt, 
-  int i, 
-  const void *zData, 
-  int nData, 
+  sqlite3_stmt *pStmt,
+  int i,
+  const void *zData,
+  int nData,
   void (*xDel)(void*)
 ){
 #ifdef SQLITE_ENABLE_API_ARMOR
@@ -83233,10 +84881,10 @@ SQLITE_API int sqlite3_bind_blob(
   return bindText(pStmt, i, zData, nData, xDel, 0);
 }
 SQLITE_API int sqlite3_bind_blob64(
-  sqlite3_stmt *pStmt, 
-  int i, 
-  const void *zData, 
-  sqlite3_uint64 nData, 
+  sqlite3_stmt *pStmt,
+  int i,
+  const void *zData,
+  sqlite3_uint64 nData,
   void (*xDel)(void*)
 ){
   assert( xDel!=SQLITE_DYNAMIC );
@@ -83297,20 +84945,20 @@ SQLITE_API int sqlite3_bind_pointer(
   return rc;
 }
 #undef sqlite3_bind_text
-SQLITE_API int sqlite3_bind_text( 
-  sqlite3_stmt *pStmt, 
-  int i, 
-  const char *zData, 
-  int nData, 
+SQLITE_API int sqlite3_bind_text(
+  sqlite3_stmt *pStmt,
+  int i,
+  const char *zData,
+  int nData,
   void (*xDel)(void*)
 ){
   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
 }
-SQLITE_API int sqlite3_bind_text64( 
-  sqlite3_stmt *pStmt, 
-  int i, 
-  const char *zData, 
-  sqlite3_uint64 nData, 
+SQLITE_API int sqlite3_bind_text64(
+  sqlite3_stmt *pStmt,
+  int i,
+  const char *zData,
+  sqlite3_uint64 nData,
   void (*xDel)(void*),
   unsigned char enc
 ){
@@ -83327,10 +84975,10 @@ SQLITE_API int sqlite3_bind_text64(
 #ifndef SQLITE_OMIT_UTF16
 #undef sqlite3_bind_text16
 SQLITE_API int sqlite3_bind_text16(
-  sqlite3_stmt *pStmt, 
-  int i, 
-  const void *zData, 
-  int nData, 
+  sqlite3_stmt *pStmt,
+  int i,
+  const void *zData,
+  int nData,
   void (*xDel)(void*)
 ){
   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
@@ -83395,7 +85043,7 @@ SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint6
 
 /*
 ** Return the number of wildcards that can be potentially bound to.
-** This routine is added to support DBD::SQLite.  
+** This routine is added to support DBD::SQLite.
 */
 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
   Vdbe *p = (Vdbe*)pStmt;
@@ -83540,7 +85188,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
   Vdbe *pVdbe = (Vdbe*)pStmt;
   size_t v;
 #ifdef SQLITE_ENABLE_API_ARMOR
-  if( !pStmt 
+  if( !pStmt
    || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
   ){
     (void)SQLITE_MISUSE_BKPT;
@@ -83619,8 +85267,8 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
 ** if successful, or a NULL pointer if an OOM error is encountered.
 */
 static UnpackedRecord *vdbeUnpackRecord(
-  KeyInfo *pKeyInfo, 
-  int nKey, 
+  KeyInfo *pKeyInfo,
+  int nKey,
   const void *pKey
 ){
   UnpackedRecord *pRet;           /* Return value */
@@ -83649,7 +85297,7 @@ SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppVa
     goto preupdate_old_out;
   }
   if( p->pPk ){
-    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
+    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
   }
   if( iIdx>=p->pCsr->nField || iIdx<0 ){
     rc = SQLITE_RANGE;
@@ -83712,7 +85360,7 @@ SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
 ** only. It returns zero if the change that caused the callback was made
 ** immediately by a user SQL statement. Or, if the change was made by a
 ** trigger program, it returns the number of trigger programs currently
-** on the stack (1 for a top-level trigger, 2 for a trigger fired by a 
+** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
 ** top-level trigger etc.).
 **
 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
@@ -83739,7 +85387,7 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppVa
     goto preupdate_new_out;
   }
   if( p->pPk && p->op!=SQLITE_UPDATE ){
-    iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
+    iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
   }
   if( iIdx>=p->pCsr->nField || iIdx<0 ){
     rc = SQLITE_RANGE;
@@ -83921,8 +85569,8 @@ static int findNextHostParameter(const char *zSql, int *pnToken){
 /*
 ** This function returns a pointer to a nul-terminated string in memory
 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
-** string contains a copy of zRawSql but with host parameters expanded to 
-** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
+** string contains a copy of zRawSql but with host parameters expanded to
+** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
 ** then the returned string holds a copy of zRawSql with "-- " prepended
 ** to each line of text.
 **
@@ -83960,7 +85608,7 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
   char zBase[100];         /* Initial working space */
 
   db = p->db;
-  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), 
+  sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
                       db->aLimit[SQLITE_LIMIT_LENGTH]);
   if( db->nVdbeExec>1 ){
     while( *zRawSql ){
@@ -84028,7 +85676,7 @@ SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
           nOut = SQLITE_TRACE_SIZE_LIMIT;
           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
         }
-#endif    
+#endif
         sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
 #ifdef SQLITE_TRACE_SIZE_LIMIT
         if( nOut<pVar->n ){
@@ -84187,6 +85835,26 @@ SQLITE_API int sqlite3_found_count = 0;
 # define UPDATE_MAX_BLOBSIZE(P)
 #endif
 
+#ifdef SQLITE_DEBUG
+/* This routine provides a convenient place to set a breakpoint during
+** tracing with PRAGMA vdbe_trace=on.  The breakpoint fires right after
+** each opcode is printed.  Variables "pc" (program counter) and pOp are
+** available to add conditionals to the breakpoint.  GDB example:
+**
+**         break test_trace_breakpoint if pc=22
+**
+** Other useful labels for breakpoints include:
+**   test_addop_breakpoint(pc,pOp)
+**   sqlite3CorruptError(lineno)
+**   sqlite3MisuseError(lineno)
+**   sqlite3CantopenError(lineno)
+*/
+static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
+  static int n = 0;
+  n++;
+}
+#endif
+
 /*
 ** Invoke the VDBE coverage callback, if that callback is defined.  This
 ** feature is used for test suite validation only and does not appear an
@@ -84201,7 +85869,7 @@ SQLITE_API int sqlite3_found_count = 0;
 **
 ** In other words, if M is 2, then I is either 0 (for fall-through) or
 ** 1 (for when the branch is taken).  If M is 3, the I is 0 for an
-** ordinary fall-through, I is 1 if the branch was taken, and I is 2 
+** ordinary fall-through, I is 1 if the branch was taken, and I is 2
 ** if the result of comparison is NULL.  For M=3, I=2 the jump may or
 ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
 ** When M is 4, that means that an OP_Jump is being run.  I is 0, 1, or 2
@@ -84295,7 +85963,7 @@ static VdbeCursor *allocateCursor(
   u8 eCurType           /* Type of the new cursor */
 ){
   /* Find the memory cell that will be used to store the blob of memory
-  ** required for this VdbeCursor structure. It is convenient to use a 
+  ** required for this VdbeCursor structure. It is convenient to use a
   ** vdbe memory cell to manage the memory allocation required for a
   ** VdbeCursor structure for the following reasons:
   **
@@ -84316,14 +85984,14 @@ static VdbeCursor *allocateCursor(
 
   int nByte;
   VdbeCursor *pCx = 0;
-  nByte = 
-      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
+  nByte =
+      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
       (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
 
   assert( iCur>=0 && iCur<p->nCursor );
   if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
     /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
-    ** is clear. Otherwise, if this is an ephemeral cursor created by 
+    ** is clear. Otherwise, if this is an ephemeral cursor created by
     ** OP_OpenDup, the cursor will not be closed and will still be part
     ** of a BtShared.pCursor list.  */
     if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;
@@ -84403,7 +86071,7 @@ static void applyNumericAffinity(Mem *pRec, int bTryForInt){
 ** SQLITE_AFF_INTEGER:
 ** SQLITE_AFF_REAL:
 ** SQLITE_AFF_NUMERIC:
-**    Try to convert pRec to an integer representation or a 
+**    Try to convert pRec to an integer representation or a
 **    floating-point representation if an integer representation
 **    is not possible.  Note that the integer representation is
 **    always preferred, even if the affinity is REAL, because
@@ -84434,7 +86102,7 @@ static void applyAffinity(
   }else if( affinity==SQLITE_AFF_TEXT ){
     /* Only attempt the conversion to TEXT if there is an integer or real
     ** representation (blob and NULL do not get converted) but no string
-    ** representation.  It would be harmless to repeat the conversion if 
+    ** representation.  It would be harmless to repeat the conversion if
     ** there is already a string rep, but it is pointless to waste those
     ** CPU cycles. */
     if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
@@ -84466,12 +86134,12 @@ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
 }
 
 /*
-** Exported version of applyAffinity(). This one works on sqlite3_value*, 
+** Exported version of applyAffinity(). This one works on sqlite3_value*,
 ** not the internal Mem* type.
 */
 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
-  sqlite3_value *pVal, 
-  u8 affinity, 
+  sqlite3_value *pVal,
+  u8 affinity,
   u8 enc
 ){
   applyAffinity((Mem *)pVal, affinity, enc);
@@ -84506,7 +86174,7 @@ static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
 
 /*
 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
-** none.  
+** none.
 **
 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
 ** But it does set pMem->u.r and pMem->u.i appropriately.
@@ -84531,12 +86199,9 @@ static u16 numericType(Mem *pMem){
 ** Write a nice string representation of the contents of cell pMem
 ** into buffer zBuf, length nBuf.
 */
-SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
-  char *zCsr = zBuf;
+SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
   int f = pMem->flags;
-
   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
-
   if( f&MEM_Blob ){
     int i;
     char c;
@@ -84552,57 +86217,40 @@ SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
     }else{
       c = 's';
     }
-    *(zCsr++) = c;
-    *(zCsr++) = 'x';
-    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
-    zCsr += sqlite3Strlen30(zCsr);
+    sqlite3_str_appendf(pStr, "%cx[", c);
     for(i=0; i<25 && i<pMem->n; i++){
-      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
-      zCsr += sqlite3Strlen30(zCsr);
+      sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
     }
-    *zCsr++ = '|';
+    sqlite3_str_appendf(pStr, "|");
     for(i=0; i<25 && i<pMem->n; i++){
       char z = pMem->z[i];
-      if( z<32 || z>126 ) *zCsr++ = '.';
-      else *zCsr++ = z;
+      sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
     }
-    *(zCsr++) = ']';
+    sqlite3_str_appendf(pStr,"]");
     if( f & MEM_Zero ){
-      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
-      zCsr += sqlite3Strlen30(zCsr);
+      sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
     }
-    *zCsr = '\0';
   }else if( f & MEM_Str ){
-    int j, k;
-    zBuf[0] = ' ';
+    int j;
+    u8 c;
     if( f & MEM_Dyn ){
-      zBuf[1] = 'z';
+      c = 'z';
       assert( (f & (MEM_Static|MEM_Ephem))==0 );
     }else if( f & MEM_Static ){
-      zBuf[1] = 't';
+      c = 't';
       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
     }else if( f & MEM_Ephem ){
-      zBuf[1] = 'e';
+      c = 'e';
       assert( (f & (MEM_Static|MEM_Dyn))==0 );
     }else{
-      zBuf[1] = 's';
+      c = 's';
     }
-    k = 2;
-    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
-    k += sqlite3Strlen30(&zBuf[k]);
-    zBuf[k++] = '[';
+    sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
     for(j=0; j<25 && j<pMem->n; j++){
-      u8 c = pMem->z[j];
-      if( c>=0x20 && c<0x7f ){
-        zBuf[k++] = c;
-      }else{
-        zBuf[k++] = '.';
-      }
+      c = pMem->z[j];
+      sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
     }
-    zBuf[k++] = ']';
-    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
-    k += sqlite3Strlen30(&zBuf[k]);
-    zBuf[k++] = 0;
+    sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
   }
 }
 #endif
@@ -84637,21 +86285,38 @@ static void memTracePrint(Mem *p){
   }else if( sqlite3VdbeMemIsRowSet(p) ){
     printf(" (rowset)");
   }else{
-    char zBuf[200];
-    sqlite3VdbeMemPrettyPrint(p, zBuf);
-    printf(" %s", zBuf);
+    StrAccum acc;
+    char zBuf[1000];
+    sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
+    sqlite3VdbeMemPrettyPrint(p, &acc);
+    printf(" %s", sqlite3StrAccumFinish(&acc));
   }
   if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
 }
 static void registerTrace(int iReg, Mem *p){
-  printf("REG[%d] = ", iReg);
+  printf("R[%d] = ", iReg);
   memTracePrint(p);
+  if( p->pScopyFrom ){
+    printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
+  }
   printf("\n");
   sqlite3VdbeCheckMemInvariants(p);
 }
 #endif
 
 #ifdef SQLITE_DEBUG
+/*
+** Show the values of all registers in the virtual machine.  Used for
+** interactive debugging.
+*/
+SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){
+  int i;
+  for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
+}
+#endif /* SQLITE_DEBUG */
+
+
+#ifdef SQLITE_DEBUG
 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
 #else
 #  define REGISTER_TRACE(R,M)
@@ -84660,8 +86325,8 @@ static void registerTrace(int iReg, Mem *p){
 
 #ifdef VDBE_PROFILE
 
-/* 
-** hwtime.h contains inline assembler code for implementing 
+/*
+** hwtime.h contains inline assembler code for implementing
 ** high-performance timing routines.
 */
 /************** Include hwtime.h in the middle of vdbe.c *********************/
@@ -84679,7 +86344,7 @@ static void registerTrace(int iReg, Mem *p){
 ******************************************************************************
 **
 ** This file contains inline asm code for retrieving "high-performance"
-** counters for x86 class CPUs.
+** counters for x86 and x86_64 class CPUs.
 */
 #ifndef SQLITE_HWTIME_H
 #define SQLITE_HWTIME_H
@@ -84690,8 +86355,9 @@ static void registerTrace(int iReg, Mem *p){
 ** processor and returns that value.  This can be used for high-res
 ** profiling.
 */
-#if (defined(__GNUC__) || defined(_MSC_VER)) && \
-      (defined(i386) || defined(__i386__) || defined(_M_IX86))
+#if !defined(__STRICT_ANSI__) && \
+    (defined(__GNUC__) || defined(_MSC_VER)) && \
+    (defined(i386) || defined(__i386__) || defined(_M_IX86))
 
   #if defined(__GNUC__)
 
@@ -84712,15 +86378,15 @@ static void registerTrace(int iReg, Mem *p){
 
   #endif
 
-#elif (defined(__GNUC__) && defined(__x86_64__))
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long val;
       __asm__ __volatile__ ("rdtsc" : "=A" (val));
       return val;
   }
-#elif (defined(__GNUC__) && defined(__ppc__))
+
+#elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
 
   __inline__ sqlite_uint64 sqlite3Hwtime(void){
       unsigned long long retval;
@@ -84737,14 +86403,13 @@ static void registerTrace(int iReg, Mem *p){
 
 #else
 
-  #error Need implementation of sqlite3Hwtime() for your platform.
-
   /*
-  ** To compile without implementing sqlite3Hwtime() for your platform,
-  ** you can remove the above #error and use the following
-  ** stub function.  You will lose timing support for many
-  ** of the debugging and testing utilities, but it should at
-  ** least compile and run.
+  ** asm() is needed for hardware timing support.  Without asm(),
+  ** disable the sqlite3Hwtime() routine.
+  **
+  ** sqlite3Hwtime() is only used for some obscure debugging
+  ** and analysis configurations, not in any deliverable, so this
+  ** should not be a great loss.
   */
 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 
@@ -84761,9 +86426,9 @@ SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
 /*
 ** This function is only called from within an assert() expression. It
 ** checks that the sqlite3.nTransaction variable is correctly set to
-** the number of non-transaction savepoints currently in the 
+** the number of non-transaction savepoints currently in the
 ** linked list starting at sqlite3.pSavepoint.
-** 
+**
 ** Usage:
 **
 **     assert( checkSavepointCount(db) );
@@ -84803,7 +86468,7 @@ static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
 
 /*
 ** Execute as much of a VDBE program as we can.
-** This is the core of sqlite3_step().  
+** This is the core of sqlite3_step().
 */
 SQLITE_PRIVATE int sqlite3VdbeExec(
   Vdbe *p                    /* The VDBE */
@@ -84821,9 +86486,9 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   u8 encoding = ENC(db);     /* The database encoding */
   int iCompare = 0;          /* Result of last comparison */
-  unsigned nVmStep = 0;      /* Number of virtual machine steps */
+  u64 nVmStep = 0;           /* Number of virtual machine steps */
 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
-  unsigned nProgressLimit;   /* Invoke xProgress() when nVmStep reaches this */
+  u64 nProgressLimit;        /* Invoke xProgress() when nVmStep reaches this */
 #endif
   Mem *aMem = p->aMem;       /* Copy of p->aMem */
   Mem *pIn1 = 0;             /* 1st input operand */
@@ -84843,7 +86508,7 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
     assert( 0 < db->nProgressOps );
     nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
   }else{
-    nProgressLimit = 0xffffffff;
+    nProgressLimit = LARGEST_UINT64;
   }
 #endif
   if( p->rc==SQLITE_NOMEM ){
@@ -84852,12 +86517,14 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
     goto no_mem;
   }
   assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
+  testcase( p->rc!=SQLITE_OK );
+  p->rc = SQLITE_OK;
   assert( p->bIsReader || p->readOnly!=0 );
   p->iCurrentTime = 0;
   assert( p->explain==0 );
   p->pResultSet = 0;
   db->busyHandler.nBusy = 0;
-  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
+  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
   sqlite3VdbeIOTraceSql(p);
 #ifdef SQLITE_DEBUG
   sqlite3BeginBenignMalloc();
@@ -84905,9 +86572,10 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
 #ifdef SQLITE_DEBUG
     if( db->flags & SQLITE_VdbeTrace ){
       sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
+      test_trace_breakpoint((int)(pOp - aOp),pOp,p);
     }
 #endif
-      
+
 
     /* Check to see if we need to simulate an interrupt.  This only happens
     ** if we have a special test build.
@@ -84961,7 +86629,7 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
     pOrigOp = pOp;
 #endif
-  
+
     switch( pOp->opcode ){
 
 /*****************************************************************************
@@ -85002,7 +86670,7 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
 /* Opcode:  Goto * P2 * * *
 **
 ** An unconditional jump to address P2.
-** The next instruction executed will be 
+** The next instruction executed will be
 ** the one at index P2 from the beginning of
 ** the program.
 **
@@ -85012,13 +86680,27 @@ SQLITE_PRIVATE int sqlite3VdbeExec(
 ** to the current line should be indented for EXPLAIN output.
 */
 case OP_Goto: {             /* jump */
+
+#ifdef SQLITE_DEBUG
+  /* In debuggging mode, when the p5 flags is set on an OP_Goto, that
+  ** means we should really jump back to the preceeding OP_ReleaseReg
+  ** instruction. */
+  if( pOp->p5 ){
+    assert( pOp->p2 < (int)(pOp - aOp) );
+    assert( pOp->p2 > 1 );
+    pOp = &aOp[pOp->p2 - 2];
+    assert( pOp[1].opcode==OP_ReleaseReg );
+    goto check_for_interrupt;
+  }
+#endif
+
 jump_to_p2_and_check_for_interrupt:
   pOp = &aOp[pOp->p2 - 1];
 
   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
   ** OP_VNext, or OP_SorterNext) all jump here upon
   ** completion.  Check to see if sqlite3_interrupt() has been called
-  ** or if the progress callback needs to be invoked. 
+  ** or if the progress callback needs to be invoked.
   **
   ** This code uses unstructured "goto" statements and does not look clean.
   ** But that is not due to sloppy coding habits. The code is written this
@@ -85026,7 +86708,7 @@ jump_to_p2_and_check_for_interrupt:
   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
   ** faster according to "valgrind --tool=cachegrind" */
 check_for_interrupt:
-  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
+  if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   /* Call the progress callback if it is configured and the required number
   ** of VDBE ops have been executed (either since this invocation of
@@ -85038,13 +86720,13 @@ check_for_interrupt:
     assert( db->nProgressOps!=0 );
     nProgressLimit += db->nProgressOps;
     if( db->xProgress(db->pProgressArg) ){
-      nProgressLimit = 0xffffffff;
+      nProgressLimit = LARGEST_UINT64;
       rc = SQLITE_INTERRUPT;
       goto abort_due_to_error;
     }
   }
 #endif
-  
+
   break;
 }
 
@@ -85166,6 +86848,7 @@ case OP_HaltIfNull: {      /* in3 */
 #endif
   if( (pIn3->flags & MEM_Null)==0 ) break;
   /* Fall through into OP_Halt */
+  /* no break */ deliberate_fall_through
 }
 
 /* Opcode:  Halt P1 P2 * P4 P5
@@ -85179,7 +86862,7 @@ case OP_HaltIfNull: {      /* in3 */
 ** whether or not to rollback the current transaction.  Do not rollback
 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
 ** then back out all changes that have occurred during this execution of the
-** VDBE, but do not rollback the transaction. 
+** VDBE, but do not rollback the transaction.
 **
 ** If P4 is not null then it is an error message string.
 **
@@ -85214,7 +86897,7 @@ case OP_Halt: {
     sqlite3VdbeSetChanges(db, p->nChange);
     pcx = sqlite3VdbeFrameRestore(pFrame);
     if( pOp->p2==OE_Ignore ){
-      /* Instruction pcx is the OP_Program that invoked the sub-program 
+      /* Instruction pcx is the OP_Program that invoked the sub-program
       ** currently being halted. If the p2 instruction of this OP_Halt
       ** instruction is set to OE_Ignore, then the sub-program is throwing
       ** an IGNORE exception. In this case jump to the address specified
@@ -85302,7 +86985,7 @@ case OP_Real: {            /* same as TK_FLOAT, out2 */
 /* Opcode: String8 * P2 * P4 *
 ** Synopsis: r[P2]='P4'
 **
-** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
+** P4 points to a nul terminated UTF-8 string. This opcode is transformed
 ** into a String opcode before it is executed for the first time.  During
 ** this transformation, the length of string P4 is computed and stored
 ** as the P1 parameter.
@@ -85336,8 +87019,9 @@ case OP_String8: {         /* same as TK_STRING, out2 */
   pOp->opcode = OP_String;
   assert( rc==SQLITE_OK );
   /* Fall through to the next case, OP_String */
+  /* no break */ deliberate_fall_through
 }
-  
+
 /* Opcode: String P1 P2 P3 P4 P5
 ** Synopsis: r[P2]='P4' (len=P1)
 **
@@ -85488,8 +87172,13 @@ case OP_Move: {
     memAboutToChange(p, pOut);
     sqlite3VdbeMemMove(pOut, pIn1);
 #ifdef SQLITE_DEBUG
-    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
-      pOut->pScopyFrom += pOp->p2 - p1;
+    pIn1->pScopyFrom = 0;
+    { int i;
+      for(i=1; i<p->nMem; i++){
+        if( aMem[i].pScopyFrom==pIn1 ){
+          aMem[i].pScopyFrom = pOut;
+        }
+      }
     }
 #endif
     Deephemeralize(pOut);
@@ -85596,8 +87285,8 @@ case OP_ResultRow: {
     goto abort_due_to_error;
   }
 
-  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
-  ** DML statements invoke this opcode to return the number of rows 
+  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
+  ** DML statements invoke this opcode to return the number of rows
   ** modified to the user. This is the only way that a VM that
   ** opens a statement transaction may invoke this opcode.
   **
@@ -85630,13 +87319,22 @@ case OP_ResultRow: {
             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
     sqlite3VdbeMemNulTerminate(&pMem[i]);
     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
+#ifdef SQLITE_DEBUG
+    /* The registers in the result will not be used again when the
+    ** prepared statement restarts.  This is because sqlite3_column()
+    ** APIs might have caused type conversions of made other changes to
+    ** the register values.  Therefore, we can go ahead and break any
+    ** OP_SCopy dependencies. */
+    pMem[i].pScopyFrom = 0;
+#endif
   }
   if( db->mallocFailed ) goto no_mem;
 
   if( db->mTrace & SQLITE_TRACE_ROW ){
-    db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
+    db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
   }
 
+
   /* Return SQLITE_ROW
   */
   p->pc = (int)(pOp - aOp) + 1;
@@ -85665,7 +87363,6 @@ case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
   pIn1 = &aMem[pOp->p1];
   pIn2 = &aMem[pOp->p2];
   pOut = &aMem[pOp->p3];
-  testcase( pIn1==pIn2 );
   testcase( pOut==pIn2 );
   assert( pIn1!=pOut );
   flags1 = pIn1->flags;
@@ -85742,15 +87439,15 @@ case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
 ** Synopsis: r[P3]=r[P2]/r[P1]
 **
 ** Divide the value in register P1 by the value in register P2
-** and store the result in register P3 (P3=P2/P1). If the value in 
-** register P1 is zero, then the result is NULL. If either input is 
+** and store the result in register P3 (P3=P2/P1). If the value in
+** register P1 is zero, then the result is NULL. If either input is
 ** NULL, the result is NULL.
 */
 /* Opcode: Remainder P1 P2 P3 * *
 ** Synopsis: r[P3]=r[P2]%r[P1]
 **
-** Compute the remainder after integer register P2 is divided by 
-** register P1 and store the result in register P3. 
+** Compute the remainder after integer register P2 is divided by
+** register P1 and store the result in register P3.
 ** If the value in register P1 is zero the result is NULL.
 ** If either operand is NULL, the result is NULL.
 */
@@ -85945,7 +87642,7 @@ case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
 
 /* Opcode: AddImm  P1 P2 * * *
 ** Synopsis: r[P1]=r[P1]+P2
-** 
+**
 ** Add the constant P2 to the value in register P1.
 ** The result is always an integer.
 **
@@ -85960,7 +87657,7 @@ case OP_AddImm: {            /* in1 */
 }
 
 /* Opcode: MustBeInt P1 P2 * * *
-** 
+**
 ** Force the value in register P1 to be an integer.  If the value
 ** in P1 is not an integer and cannot be converted into an integer
 ** without data loss, then jump immediately to P2, or if P2==0
@@ -86012,7 +87709,7 @@ case OP_RealAffinity: {                  /* in1 */
 ** Synopsis: affinity(r[P1])
 **
 ** Force the value in register P1 to be the type defined by P2.
-** 
+**
 ** <ul>
 ** <li> P2=='A' &rarr; BLOB
 ** <li> P2=='B' &rarr; TEXT
@@ -86033,9 +87730,11 @@ case OP_Cast: {                  /* in1 */
   pIn1 = &aMem[pOp->p1];
   memAboutToChange(p, pIn1);
   rc = ExpandBlob(pIn1);
-  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
-  UPDATE_MAX_BLOBSIZE(pIn1);
   if( rc ) goto abort_due_to_error;
+  rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
+  if( rc ) goto abort_due_to_error;
+  UPDATE_MAX_BLOBSIZE(pIn1);
+  REGISTER_TRACE(pOp->p1, pIn1);
   break;
 }
 #endif /* SQLITE_OMIT_CAST */
@@ -86048,14 +87747,14 @@ case OP_Cast: {                  /* in1 */
 ** store the result of comparison in register P2.
 **
 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
-** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
+** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
 ** to coerce both inputs according to this affinity before the
 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 ** affinity is used. Note that the affinity conversions are stored
 ** back into the input registers P1 and P3.  So this opcode can cause
 ** persistent changes to registers P1 and P3.
 **
-** Once any conversions have taken place, and neither value is NULL, 
+** Once any conversions have taken place, and neither value is NULL,
 ** the values are compared. If both values are blobs then memcmp() is
 ** used to determine the results of the comparison.  If both values
 ** are text, then the appropriate collating function specified in
@@ -86094,18 +87793,18 @@ case OP_Cast: {                  /* in1 */
 ** the result of comparison (0 or 1 or NULL) into register P2.
 **
 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
-** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL 
+** reg(P3) is NULL then the take the jump.  If the SQLITE_JUMPIFNULL
 ** bit is clear then fall through if either operand is NULL.
 **
 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
-** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
+** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
 ** to coerce both inputs according to this affinity before the
 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
 ** affinity is used. Note that the affinity conversions are stored
 ** back into the input registers P1 and P3.  So this opcode can cause
 ** persistent changes to registers P1 and P3.
 **
-** Once any conversions have taken place, and neither value is NULL, 
+** Once any conversions have taken place, and neither value is NULL,
 ** the values are compared. If both values are blobs then memcmp() is
 ** used to determine the results of the comparison.  If both values
 ** are text, then the appropriate collating function specified in
@@ -86194,12 +87893,7 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
       if( (flags1 | flags3)&MEM_Str ){
         if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
           applyNumericAffinity(pIn1,0);
-          assert( flags3==pIn3->flags );
-          /* testcase( flags3!=pIn3->flags );
-          ** this used to be possible with pIn1==pIn3, but not since
-          ** the column cache was removed.  The following assignment
-          ** is essentially a no-op.  But, it provides defense-in-depth
-          ** in case our analysis is incorrect, so it is left in. */
+          testcase( flags3==pIn3->flags );
           flags3 = pIn3->flags;
         }
         if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
@@ -86222,7 +87916,7 @@ case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
         sqlite3VdbeMemStringify(pIn1, encoding, 1);
         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
-        assert( pIn1!=pIn3 );
+        if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
       }
       if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
         testcase( pIn3->flags & MEM_Int );
@@ -86257,10 +87951,10 @@ compare_op:
   }
 
   /* Undo any changes made by applyAffinity() to the input registers. */
-  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
-  pIn1->flags = flags1;
   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
   pIn3->flags = flags3;
+  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
+  pIn1->flags = flags1;
 
   if( pOp->p5 & SQLITE_STOREP2 ){
     pOut = &aMem[pOp->p2];
@@ -86296,16 +87990,31 @@ compare_op:
 
 /* Opcode: ElseNotEq * P2 * * *
 **
-** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
-** If result of an OP_Eq comparison on the same two operands
-** would have be NULL or false (0), then then jump to P2. 
-** If the result of an OP_Eq comparison on the two previous operands
-** would have been true (1), then fall through.
+** This opcode must follow an OP_Lt or OP_Gt comparison operator.  There
+** can be zero or more OP_ReleaseReg opcodes intervening, but no other
+** opcodes are allowed to occur between this instruction and the previous
+** OP_Lt or OP_Gt.  Furthermore, the prior OP_Lt or OP_Gt must have the
+** SQLITE_STOREP2 bit set in the P5 field.
+**
+** If result of an OP_Eq comparison on the same two operands as the
+** prior OP_Lt or OP_Gt would have been NULL or false (0), then then
+** jump to P2.  If the result of an OP_Eq comparison on the two previous
+** operands would have been true (1), then fall through.
 */
 case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
-  assert( pOp>aOp );
-  assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
-  assert( pOp[-1].p5 & SQLITE_STOREP2 );
+
+#ifdef SQLITE_DEBUG
+  /* Verify the preconditions of this opcode - that it follows an OP_Lt or
+  ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening
+  ** OP_ReleaseReg opcodes */
+  int iAddr;
+  for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
+    if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
+    assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
+    assert( aOp[iAddr].p5 & SQLITE_STOREP2 );
+    break;
+  }
+#endif /* SQLITE_DEBUG */
   VdbeBranchTaken(iCompare!=0, 2);
   if( iCompare!=0 ) goto jump_to_p2;
   break;
@@ -86318,7 +88027,7 @@ case OP_ElseNotEq: {       /* same as TK_ESCAPE, jump */
 ** instruction.  The permutation is stored in the P4 operand.
 **
 ** The permutation is only valid until the next OP_Compare that has
-** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
+** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
 ** occur immediately prior to the OP_Compare.
 **
 ** The first integer in the P4 integer array is the length of the array
@@ -86358,10 +88067,10 @@ case OP_Compare: {
   int p1;
   int p2;
   const KeyInfo *pKeyInfo;
-  int idx;
+  u32 idx;
   CollSeq *pColl;    /* Collating sequence to use on this term */
   int bRev;          /* True for DESCENDING sort order */
-  int *aPermute;     /* The permutation */
+  u32 *aPermute;     /* The permutation */
 
   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
     aPermute = 0;
@@ -86381,7 +88090,7 @@ case OP_Compare: {
 #ifdef SQLITE_DEBUG
   if( aPermute ){
     int k, mx = 0;
-    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
+    for(k=0; k<n; k++) if( aPermute[k]>(u32)mx ) mx = aPermute[k];
     assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
     assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
   }else{
@@ -86390,7 +88099,7 @@ case OP_Compare: {
   }
 #endif /* SQLITE_DEBUG */
   for(i=0; i<n; i++){
-    idx = aPermute ? aPermute[i] : i;
+    idx = aPermute ? aPermute[i] : (u32)i;
     assert( memIsValid(&aMem[p1+idx]) );
     assert( memIsValid(&aMem[p2+idx]) );
     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
@@ -86400,7 +88109,7 @@ case OP_Compare: {
     bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
     if( iCompare ){
-      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) 
+      if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
        && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
       ){
         iCompare = -iCompare;
@@ -86480,13 +88189,13 @@ case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
 ** IS NOT FALSE operators.
 **
 ** Interpret the value in register P1 as a boolean value.  Store that
-** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is 
+** boolean (a 0 or 1) in register P2.  Or if the value in register P1 is
 ** NULL, then the P3 is stored in register P2.  Invert the answer if P4
 ** is 1.
 **
 ** The logic is summarized like this:
 **
-** <ul> 
+** <ul>
 ** <li> If P3==0 and P4==0  then  r[P2] := r[P1] IS TRUE
 ** <li> If P3==1 and P4==1  then  r[P2] := r[P1] IS FALSE
 ** <li> If P3==0 and P4==1  then  r[P2] := r[P1] IS NOT TRUE
@@ -86506,7 +88215,7 @@ case OP_IsTrue: {               /* in1, out2 */
 ** Synopsis: r[P2]= !r[P1]
 **
 ** Interpret the value in register P1 as a boolean value.  Store the
-** boolean complement in register P2.  If the value in register P1 is 
+** boolean complement in register P2.  If the value in register P1 is
 ** NULL, then a NULL is stored in P2.
 */
 case OP_Not: {                /* same as TK_NOT, in1, out2 */
@@ -86621,7 +88330,7 @@ case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
 /* Opcode: NotNull P1 P2 * * *
 ** Synopsis: if r[P1]!=NULL goto P2
 **
-** Jump to P2 if the value in register P1 is not NULL.  
+** Jump to P2 if the value in register P1 is not NULL.
 */
 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
   pIn1 = &aMem[pOp->p1];
@@ -86686,7 +88395,7 @@ case OP_Offset: {          /* out3 */
 ** Interpret the data that cursor P1 points to as a structure built using
 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
 ** information about the format of the data.)  Extract the P2-th column
-** from this record.  If there are less that (P2+1) 
+** from this record.  If there are less that (P2+1)
 ** values in the record, extract a NULL.
 **
 ** The value extracted is stored in register P3.
@@ -86701,7 +88410,7 @@ case OP_Offset: {          /* out3 */
 ** skipped for length() and all content loading can be skipped for typeof().
 */
 case OP_Column: {
-  int p2;            /* column number to retrieve */
+  u32 p2;            /* column number to retrieve */
   VdbeCursor *pC;    /* The VDBE cursor */
   BtCursor *pCrsr;   /* The BTree cursor */
   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
@@ -86716,11 +88425,13 @@ case OP_Column: {
   u32 t;             /* A type code from the record header */
   Mem *pReg;         /* PseudoTable input register */
 
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
-  p2 = pOp->p2;
+  assert( pC!=0 );
+  p2 = (u32)pOp->p2;
 
   /* If the cursor cache is stale (meaning it is not currently point at
-  ** the correct row) then bring it up-to-date by doing the necessary 
+  ** the correct row) then bring it up-to-date by doing the necessary
   ** B-Tree seek. */
   rc = sqlite3VdbeCursorMoveto(&pC, &p2);
   if( rc ) goto abort_due_to_error;
@@ -86728,9 +88439,8 @@ case OP_Column: {
   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   pDest = &aMem[pOp->p3];
   memAboutToChange(p, pDest);
-  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   assert( pC!=0 );
-  assert( p2<pC->nField );
+  assert( p2<(u32)pC->nField );
   aOffset = pC->aOffset;
   assert( pC->eCurType!=CURTYPE_VTAB );
   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
@@ -86815,19 +88525,19 @@ case OP_Column: {
   */
   if( pC->nHdrParsed<=p2 ){
     /* If there is more header available for parsing in the record, try
-    ** to extract additional fields up through the p2+1-th field 
+    ** to extract additional fields up through the p2+1-th field
     */
     if( pC->iHdrOffset<aOffset[0] ){
       /* Make sure zData points to enough of the record to cover the header. */
       if( pC->aRow==0 ){
         memset(&sMem, 0, sizeof(sMem));
-        rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
+        rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
         if( rc!=SQLITE_OK ) goto abort_due_to_error;
         zData = (u8*)sMem.z;
       }else{
         zData = pC->aRow;
       }
-  
+
       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
     op_column_read_header:
       i = pC->nHdrParsed;
@@ -86845,7 +88555,7 @@ case OP_Column: {
           offset64 += sqlite3VdbeSerialTypeLen(t);
         }
         aOffset[++i] = (u32)(offset64 & 0xffffffff);
-      }while( i<=p2 && zHdr<zEndHdr );
+      }while( (u32)i<=p2 && zHdr<zEndHdr );
 
       /* The record is corrupt if any of the following are true:
       ** (1) the bytes of the header extend past the declared header size
@@ -86935,14 +88645,15 @@ case OP_Column: {
       **    2. the length(X) function if X is a blob, and
       **    3. if the content length is zero.
       ** So we might as well use bogus content rather than reading
-      ** content from disk. 
+      ** content from disk.
       **
       ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
       ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
-      ** read up to 16. So 16 bytes of bogus content is supplied.
+      ** read more.  Use the global constant sqlite3CtypeMap[] as the array,
+      ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
+      ** and it begins with a bunch of zeros.
       */
-      static u8 aZero[16];  /* This is the bogus content */
-      sqlite3VdbeSerialGet(aZero, t, pDest);
+      sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
     }else{
       rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
       if( rc!=SQLITE_OK ) goto abort_due_to_error;
@@ -86985,7 +88696,7 @@ case OP_Affinity: {
   pIn1 = &aMem[pOp->p1];
   while( 1 /*exit-by-break*/ ){
     assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
-    assert( memIsValid(pIn1) );
+    assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
     applyAffinity(pIn1, zAffinity[0], encoding);
     if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
       /* When applying REAL affinity, if the result is still an MEM_Int
@@ -86994,9 +88705,9 @@ case OP_Affinity: {
       ** the type really wants to be REAL. */
       testcase( pIn1->u.i==((sqlite3_int64)1)<<47 );
       testcase( pIn1->u.i==(((sqlite3_int64)1)<<47) - 1 );
-      testcase( pIn1->u.i==((sqlite3_int64)-1)<<47 );
-      testcase( pIn1->u.i==(((sqlite3_int64)-1)<<47) - 1 );
-      if( pIn1->u.i<(((sqlite3_int64)1)<<47) && pIn1->u.i>=(((sqlite3_int64)-1)<<47) ){
+      testcase( pIn1->u.i==-((sqlite3_int64)1)<<47);
+      testcase( pIn1->u.i==-(((sqlite3_int64)1)<<47) + 1 );
+      if( pIn1->u.i<(((sqlite3_int64)1)<<47) && pIn1->u.i>-(((sqlite3_int64)1)<<47) ){
         pIn1->flags |= MEM_IntReal;
         pIn1->flags &= ~MEM_Int;
       }else{
@@ -87028,6 +88739,17 @@ case OP_Affinity: {
 ** macros defined in sqliteInt.h.
 **
 ** If P4 is NULL then all index fields have the affinity BLOB.
+**
+** The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
+** compile-time option is enabled:
+**
+**   * If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
+**     of the right-most table that can be null-trimmed.
+**
+**   * If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
+**     OPFLAG_NOCHNG_MAGIC if the OP_MakeRecord opcode is allowed to
+**     accept no-change records with serial_type 10.  This value is
+**     only used inside an assert() and does not affect the end result.
 */
 case OP_MakeRecord: {
   Mem *pRec;             /* The new record */
@@ -87050,13 +88772,13 @@ case OP_MakeRecord: {
   ** like this:
   **
   ** ------------------------------------------------------------------------
-  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
+  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
   ** ------------------------------------------------------------------------
   **
   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
   ** and so forth.
   **
-  ** Each type field is a varint representing the serial type of the 
+  ** Each type field is a varint representing the serial type of the
   ** corresponding data element (see sqlite3VdbeSerialType()). The
   ** hdr-size field is also a varint which is the offset from the beginning
   ** of the record to data0.
@@ -87146,7 +88868,9 @@ case OP_MakeRecord: {
         ** Give such values a special internal-use-only serial-type of 10
         ** so that they can be passed through to xUpdate and have
         ** a true sqlite3_value_nochange(). */
+#ifndef SQLITE_ENABLE_NULL_TRIM
         assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
+#endif
         pRec->uTemp = 10;
       }else{
         pRec->uTemp = 0;
@@ -87245,7 +88969,7 @@ case OP_MakeRecord: {
   }
   nByte = nHdr+nData;
 
-  /* Make sure the output register has a buffer large enough to store 
+  /* Make sure the output register has a buffer large enough to store
   ** the new record. The output register (pOp->p3) is not allowed to
   ** be one of the input registers (because the following call to
   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
@@ -87295,13 +89019,16 @@ case OP_MakeRecord: {
   break;
 }
 
-/* Opcode: Count P1 P2 * * *
+/* Opcode: Count P1 P2 p3 * *
 ** Synopsis: r[P2]=count()
 **
-** Store the number of entries (an integer value) in the table or index 
-** opened by cursor P1 in register P2
+** Store the number of entries (an integer value) in the table or index
+** opened by cursor P1 in register P2.
+**
+** If P3==0, then an exact count is obtained, which involves visiting
+** every btree page of the table.  But if P3 is non-zero, an estimate
+** is returned based on the current cursor position.
 */
-#ifndef SQLITE_OMIT_BTREECOUNT
 case OP_Count: {         /* out2 */
   i64 nEntry;
   BtCursor *pCrsr;
@@ -87309,14 +89036,17 @@ case OP_Count: {         /* out2 */
   assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
   pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
   assert( pCrsr );
-  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
-  rc = sqlite3BtreeCount(pCrsr, &nEntry);
-  if( rc ) goto abort_due_to_error;
+  if( pOp->p3 ){
+    nEntry = sqlite3BtreeRowCountEst(pCrsr);
+  }else{
+    nEntry = 0;  /* Not needed.  Only used to silence a warning. */
+    rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
+    if( rc ) goto abort_due_to_error;
+  }
   pOut = out2Prerelease(p, pOp);
   pOut->u.i = nEntry;
-  break;
+  goto check_for_interrupt;
 }
-#endif
 
 /* Opcode: Savepoint P1 * * P4 *
 **
@@ -87339,7 +89069,7 @@ case OP_Savepoint: {
   zName = pOp->p4.z;
 
   /* Assert that the p1 parameter is valid. Also that if there is no open
-  ** transaction, then there cannot be any savepoints. 
+  ** transaction, then there cannot be any savepoints.
   */
   assert( db->pSavepoint==0 || db->autoCommit==0 );
   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
@@ -87349,7 +89079,7 @@ case OP_Savepoint: {
 
   if( p1==SAVEPOINT_BEGIN ){
     if( db->nVdbeWrite>0 ){
-      /* A new savepoint cannot be created if there are active write 
+      /* A new savepoint cannot be created if there are active write
       ** statements (i.e. open read/write incremental blob handles).
       */
       sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
@@ -87373,7 +89103,7 @@ case OP_Savepoint: {
       if( pNew ){
         pNew->zName = (char *)&pNew[1];
         memcpy(pNew->zName, zName, nName+1);
-    
+
         /* If there is no open transaction, then mark this as a special
         ** "transaction savepoint". */
         if( db->autoCommit ){
@@ -87397,7 +89127,7 @@ case OP_Savepoint: {
     /* Find the named savepoint. If there is no such savepoint, then an
     ** an error is returned to the user.  */
     for(
-      pSavepoint = db->pSavepoint; 
+      pSavepoint = db->pSavepoint;
       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
       pSavepoint = pSavepoint->pNext
     ){
@@ -87407,7 +89137,7 @@ case OP_Savepoint: {
       sqlite3VdbeError(p, "no such savepoint: %s", zName);
       rc = SQLITE_ERROR;
     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
-      /* It is not possible to release (commit) a savepoint if there are 
+      /* It is not possible to release (commit) a savepoint if there are
       ** active write statements.
       */
       sqlite3VdbeError(p, "cannot release savepoint - "
@@ -87416,8 +89146,8 @@ case OP_Savepoint: {
     }else{
 
       /* Determine whether or not this is a transaction savepoint. If so,
-      ** and this is a RELEASE command, then the current transaction 
-      ** is committed. 
+      ** and this is a RELEASE command, then the current transaction
+      ** is committed.
       */
       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
       if( isTransaction && p1==SAVEPOINT_RELEASE ){
@@ -87431,8 +89161,12 @@ case OP_Savepoint: {
           p->rc = rc = SQLITE_BUSY;
           goto vdbe_return;
         }
-        db->isTransactionSavepoint = 0;
         rc = p->rc;
+        if( rc ){
+          db->autoCommit = 0;
+        }else{
+          db->isTransactionSavepoint = 0;
+        }
       }else{
         int isSchemaChange;
         iSavepoint = db->nSavepoint - iSavepoint - 1;
@@ -87460,8 +89194,9 @@ case OP_Savepoint: {
           db->mDbFlags |= DBFLAG_SchemaChange;
         }
       }
-  
-      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
+      if( rc ) goto abort_due_to_error;
+
+      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
       ** savepoints nested inside of the savepoint being operated on. */
       while( db->pSavepoint!=pSavepoint ){
         pTmp = db->pSavepoint;
@@ -87470,8 +89205,8 @@ case OP_Savepoint: {
         db->nSavepoint--;
       }
 
-      /* If it is a RELEASE, then destroy the savepoint being operated on 
-      ** too. If it is a ROLLBACK TO, then set the number of deferred 
+      /* If it is a RELEASE, then destroy the savepoint being operated on
+      ** too. If it is a ROLLBACK TO, then set the number of deferred
       ** constraint violations present in the database to the value stored
       ** when the savepoint was created.  */
       if( p1==SAVEPOINT_RELEASE ){
@@ -87525,7 +89260,7 @@ case OP_AutoCommit: {
       db->autoCommit = 1;
     }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
       /* If this instruction implements a COMMIT and other VMs are writing
-      ** return an error indicating that the other VMs must complete first. 
+      ** return an error indicating that the other VMs must complete first.
       */
       sqlite3VdbeError(p, "cannot commit transaction - "
                           "SQL statements in progress");
@@ -87542,7 +89277,6 @@ case OP_AutoCommit: {
       p->rc = rc = SQLITE_BUSY;
       goto vdbe_return;
     }
-    assert( db->nStatement==0 );
     sqlite3CloseSavepoints(db);
     if( p->rc==SQLITE_OK ){
       rc = SQLITE_DONE;
@@ -87555,7 +89289,7 @@ case OP_AutoCommit: {
         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
         (iRollback)?"cannot rollback - no transaction is active":
                    "cannot commit - no transaction is active"));
-         
+
     rc = SQLITE_ERROR;
     goto abort_due_to_error;
   }
@@ -87566,9 +89300,10 @@ case OP_AutoCommit: {
 **
 ** Begin a transaction on database P1 if a transaction is not already
 ** active.
-** If P2 is non-zero, then a write-transaction is started, or if a 
+** If P2 is non-zero, then a write-transaction is started, or if a
 ** read-transaction is already active, it is upgraded to a write-transaction.
-** If P2 is zero, then a read-transaction is started.
+** If P2 is zero, then a read-transaction is started.  If P2 is 2 or more
+** then an exclusive transaction is started.
 **
 ** P1 is the index of the database file on which the transaction is
 ** started.  Index 0 is the main database file and index 1 is the
@@ -87602,6 +89337,7 @@ case OP_Transaction: {
 
   assert( p->bIsReader );
   assert( p->readOnly==0 || pOp->p2==0 );
+  assert( pOp->p2>=0 && pOp->p2<=2 );
   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   assert( DbMaskTest(p->btreeMask, pOp->p1) );
   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
@@ -87623,13 +89359,14 @@ case OP_Transaction: {
       goto abort_due_to_error;
     }
 
-    if( pOp->p2 && p->usesStmtJournal 
-     && (db->autoCommit==0 || db->nVdbeRead>1) 
+    if( p->usesStmtJournal
+     && pOp->p2
+     && (db->autoCommit==0 || db->nVdbeRead>1)
     ){
-      assert( sqlite3BtreeIsInTrans(pBt) );
+      assert( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE );
       if( p->iStatement==0 ){
         assert( db->nStatement>=0 && db->nSavepoint>=0 );
-        db->nStatement++; 
+        db->nStatement++;
         p->iStatement = db->nSavepoint + db->nStatement;
       }
 
@@ -87657,7 +89394,7 @@ case OP_Transaction: {
     */
     sqlite3DbFree(db, p->zErrMsg);
     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
-    /* If the schema-cookie from the database file matches the cookie 
+    /* If the schema-cookie from the database file matches the cookie
     ** stored with the in-memory representation of the schema, do
     ** not reload the schema from the database file.
     **
@@ -87667,7 +89404,7 @@ case OP_Transaction: {
     ** prepared queries. If such a query is out-of-date, we do not want to
     ** discard the database schema, as the user code implementing the
     ** v-table would have to be ready for the sqlite3_vtab structure itself
-    ** to be invalidated whenever sqlite3_step() is called from within 
+    ** to be invalidated whenever sqlite3_step() is called from within
     ** a v-table method.
     */
     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
@@ -87711,15 +89448,20 @@ case OP_ReadCookie: {               /* out2 */
   break;
 }
 
-/* Opcode: SetCookie P1 P2 P3 * *
+/* Opcode: SetCookie P1 P2 P3 * P5
 **
 ** Write the integer value P3 into cookie number P2 of database P1.
 ** P2==1 is the schema version.  P2==2 is the database format.
-** P2==3 is the recommended pager cache 
-** size, and so forth.  P1==0 is the main database file and P1==1 is the 
+** P2==3 is the recommended pager cache
+** size, and so forth.  P1==0 is the main database file and P1==1 is the
 ** database file used to store temporary tables.
 **
 ** A transaction must be started before executing this opcode.
+**
+** If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
+** schema version is set to P3-P5.  The "PRAGMA schema_version=N" statement
+** has P5 set to 1, so that the internal schema version will be different
+** from the database schema version, resulting in a schema reset.
 */
 case OP_SetCookie: {
   Db *pDb;
@@ -87736,7 +89478,7 @@ case OP_SetCookie: {
   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
   if( pOp->p2==BTREE_SCHEMA_VERSION ){
     /* When the schema cookie changes, record the new cookie internally */
-    pDb->pSchema->schema_cookie = pOp->p3;
+    pDb->pSchema->schema_cookie = pOp->p3 - pOp->p5;
     db->mDbFlags |= DBFLAG_SchemaChange;
   }else if( pOp->p2==BTREE_FILE_FORMAT ){
     /* Record changes in the file format */
@@ -87756,8 +89498,8 @@ case OP_SetCookie: {
 ** Synopsis: root=P2 iDb=P3
 **
 ** Open a read-only cursor for the database table whose root page is
-** P2 in a database file.  The database file is determined by P3. 
-** P3==0 means the main database, P3==1 means the database used for 
+** P2 in a database file.  The database file is determined by P3.
+** P3==0 means the main database, P3==1 means the database used for
 ** temporary tables, and P3>1 means used the corresponding attached
 ** database.  Give the new cursor an identifier of P1.  The P1
 ** values need not be contiguous but all P1 values should be small integers.
@@ -87767,14 +89509,14 @@ case OP_SetCookie: {
 ** <ul>
 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
-**       of OP_SeekLE/OP_IdxGT)
+**       of OP_SeekLE/OP_IdxLT)
 ** </ul>
 **
 ** The P4 value may be either an integer (P4_INT32) or a pointer to
-** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
+** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
 ** object, then table being opened must be an [index b-tree] where the
-** KeyInfo object defines the content and collating 
-** sequence of that index b-tree. Otherwise, if P4 is an integer 
+** KeyInfo object defines the content and collating
+** sequence of that index b-tree. Otherwise, if P4 is an integer
 ** value, then the table being opened must be a [table b-tree] with a
 ** number of columns no less than the value of P4.
 **
@@ -87797,7 +89539,7 @@ case OP_SetCookie: {
 ** <ul>
 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
-**       of OP_SeekLE/OP_IdxGT)
+**       of OP_SeekLE/OP_IdxLT)
 ** </ul>
 **
 ** See also: OP_OpenRead, OP_OpenWrite
@@ -87810,10 +89552,10 @@ case OP_SetCookie: {
 ** OPFLAG_P2ISREG bit is set in P5 - see below).
 **
 ** The P4 value may be either an integer (P4_INT32) or a pointer to
-** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
+** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
 ** object, then table being opened must be an [index b-tree] where the
-** KeyInfo object defines the content and collating 
-** sequence of that index b-tree. Otherwise, if P4 is an integer 
+** KeyInfo object defines the content and collating
+** sequence of that index b-tree. Otherwise, if P4 is an integer
 ** value, then the table being opened must be a [table b-tree] with a
 ** number of columns no less than the value of P4.
 **
@@ -87821,7 +89563,7 @@ case OP_SetCookie: {
 ** <ul>
 ** <li>  <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
 **       equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
-**       of OP_SeekLE/OP_IdxGT)
+**       of OP_SeekLE/OP_IdxLT)
 ** <li>  <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
 **       and subsequently delete entries in an index btree.  This is a
 **       hint to the storage engine that the storage engine is allowed to
@@ -87839,7 +89581,7 @@ case OP_SetCookie: {
 case OP_ReopenIdx: {
   int nField;
   KeyInfo *pKeyInfo;
-  int p2;
+  u32 p2;
   int iDb;
   int wrFlag;
   Btree *pX;
@@ -87870,7 +89612,7 @@ case OP_OpenWrite:
 
   nField = 0;
   pKeyInfo = 0;
-  p2 = pOp->p2;
+  p2 = (u32)pOp->p2;
   iDb = pOp->p3;
   assert( iDb>=0 && iDb<db->nDb );
   assert( DbMaskTest(p->btreeMask, iDb) );
@@ -87889,7 +89631,7 @@ case OP_OpenWrite:
   }
   if( pOp->p5 & OPFLAG_P2ISREG ){
     assert( p2>0 );
-    assert( p2<=(p->nMem+1 - p->nCursor) );
+    assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
     assert( pOp->opcode==OP_OpenWrite );
     pIn2 = &aMem[p2];
     assert( memIsValid(pIn2) );
@@ -87926,16 +89668,14 @@ case OP_OpenWrite:
   /* Set the VdbeCursor.isTable variable. Previous versions of
   ** SQLite used to check if the root-page flags were sane at this point
   ** and report database corruption if they were not, but this check has
-  ** since moved into the btree layer.  */  
+  ** since moved into the btree layer.  */
   pCur->isTable = pOp->p4type!=P4_KEYINFO;
 
 open_cursor_set_hints:
   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
   testcase( pOp->p5 & OPFLAG_BULKCSR );
-#ifdef SQLITE_ENABLE_CURSOR_HINTS
   testcase( pOp->p2 & OPFLAG_SEEKEQ );
-#endif
   sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
                                (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
   if( rc ) goto abort_due_to_error;
@@ -87955,6 +89695,7 @@ case OP_OpenDup: {
   VdbeCursor *pCx;      /* The new cursor */
 
   pOrig = p->apCsr[pOp->p2];
+  assert( pOrig );
   assert( pOrig->pBtx!=0 );  /* Only ephemeral cursors can be duplicated */
 
   pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
@@ -87975,11 +89716,11 @@ case OP_OpenDup: {
 }
 
 
-/* Opcode: OpenEphemeral P1 P2 * P4 P5
+/* Opcode: OpenEphemeral P1 P2 P3 P4 P5
 ** Synopsis: nColumn=P2
 **
 ** Open a new cursor P1 to a transient table.
-** The cursor is always opened read/write even if 
+** The cursor is always opened read/write even if
 ** the main database is read-only.  The ephemeral
 ** table is deleted automatically when the cursor is closed.
 **
@@ -87995,6 +89736,10 @@ case OP_OpenDup: {
 ** in btree.h.  These flags control aspects of the operation of
 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
 ** added automatically.
+**
+** If P3 is positive, then reg[P3] is modified slightly so that it
+** can be used as zero-length data for OP_Insert.  This is an optimization
+** that avoids an extra OP_Blob opcode to initialize that register.
 */
 /* Opcode: OpenAutoindex P1 P2 * P4 *
 ** Synopsis: nColumn=P2
@@ -88004,12 +89749,12 @@ case OP_OpenDup: {
 ** by this opcode will be used for automatically created transient
 ** indices in joins.
 */
-case OP_OpenAutoindex: 
+case OP_OpenAutoindex:
 case OP_OpenEphemeral: {
   VdbeCursor *pCx;
   KeyInfo *pKeyInfo;
 
-  static const int vfsFlags = 
+  static const int vfsFlags =
       SQLITE_OPEN_READWRITE |
       SQLITE_OPEN_CREATE |
       SQLITE_OPEN_EXCLUSIVE |
@@ -88017,21 +89762,28 @@ case OP_OpenEphemeral: {
       SQLITE_OPEN_TRANSIENT_DB;
   assert( pOp->p1>=0 );
   assert( pOp->p2>=0 );
+  if( pOp->p3>0 ){
+    /* Make register reg[P3] into a value that can be used as the data
+    ** form sqlite3BtreeInsert() where the length of the data is zero. */
+    assert( pOp->p2==0 ); /* Only used when number of columns is zero */
+    assert( pOp->opcode==OP_OpenEphemeral );
+    assert( aMem[pOp->p3].flags & MEM_Null );
+    aMem[pOp->p3].n = 0;
+    aMem[pOp->p3].z = "";
+  }
   pCx = p->apCsr[pOp->p1];
-  if( pCx ){
+  if( pCx && pCx->pBtx ){
     /* If the ephermeral table is already open, erase all existing content
     ** so that the table is empty again, rather than creating a new table. */
     assert( pCx->isEphemeral );
     pCx->seqCount = 0;
     pCx->cacheStatus = CACHE_STALE;
-    if( pCx->pBtx ){
-      rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
-    }
+    rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
   }else{
     pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
     if( pCx==0 ) goto no_mem;
     pCx->isEphemeral = 1;
-    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx, 
+    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
                           BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
                           vfsFlags);
     if( rc==SQLITE_OK ){
@@ -88045,10 +89797,10 @@ case OP_OpenEphemeral: {
       */
       if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
         assert( pOp->p4type==P4_KEYINFO );
-        rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,
-                                     BTREE_BLOBKEY | pOp->p5); 
+        rc = sqlite3BtreeCreateTable(pCx->pBtx, &pCx->pgnoRoot,
+                                     BTREE_BLOBKEY | pOp->p5);
         if( rc==SQLITE_OK ){
-          assert( pCx->pgnoRoot==MASTER_ROOT+1 );
+          assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
           assert( pKeyInfo->db==db );
           assert( pKeyInfo->enc==ENC(db) );
           rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
@@ -88056,8 +89808,8 @@ case OP_OpenEphemeral: {
         }
         pCx->isTable = 0;
       }else{
-        pCx->pgnoRoot = MASTER_ROOT;
-        rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
+        pCx->pgnoRoot = SCHEMA_ROOT;
+        rc = sqlite3BtreeCursor(pCx->pBtx, SCHEMA_ROOT, BTREE_WRCSR,
                                 0, pCx->uc.pCursor);
         pCx->isTable = 1;
       }
@@ -88117,7 +89869,7 @@ case OP_SequenceTest: {
 **
 ** Open a new cursor that points to a fake table that contains a single
 ** row of data.  The content of that one row is the content of memory
-** register P2.  In other words, cursor P1 becomes an alias for the 
+** register P2.  In other words, cursor P1 becomes an alias for the
 ** MEM_Blob content contained in register P2.
 **
 ** A pseudo-table created by this opcode is used to hold a single
@@ -88182,21 +89934,23 @@ case OP_ColumnsUsed: {
 /* Opcode: SeekGE P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
-** use the value in register P3 as the key.  If cursor P1 refers 
-** to an SQL index, then P3 is the first in an array of P4 registers 
-** that are used as an unpacked index key. 
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as the key.  If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
 **
-** Reposition cursor P1 so that  it points to the smallest entry that 
-** is greater than or equal to the key value. If there are no records 
+** Reposition cursor P1 so that  it points to the smallest entry that
+** is greater than or equal to the key value. If there are no records
 ** greater than or equal to the key and P2 is not zero, then jump to P2.
 **
 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
-** opcode will always land on a record that equally equals the key, or
-** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
-** opcode must be followed by an IdxLE opcode with the same arguments.
-** The IdxLE opcode will be skipped if this opcode succeeds, but the
-** IdxLE opcode will be used on subsequent loop iterations.
+** opcode will either land on a record that exactly matches the key, or
+** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
+** this opcode must be followed by an IdxLE opcode with the same arguments.
+** The IdxGT opcode will be skipped if this opcode succeeds, but the
+** IdxGT opcode will be used on subsequent loop iterations.  The
+** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
+** is an equality search.
 **
 ** This opcode leaves the cursor configured to move in forward order,
 ** from the beginning toward the end.  In other words, the cursor is
@@ -88207,13 +89961,13 @@ case OP_ColumnsUsed: {
 /* Opcode: SeekGT P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
-** use the value in register P3 as a key. If cursor P1 refers 
-** to an SQL index, then P3 is the first in an array of P4 registers 
-** that are used as an unpacked index key. 
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
 **
-** Reposition cursor P1 so that  it points to the smallest entry that 
-** is greater than the key value. If there are no records greater than 
+** Reposition cursor P1 so that it points to the smallest entry that
+** is greater than the key value. If there are no records greater than
 ** the key and P2 is not zero, then jump to P2.
 **
 ** This opcode leaves the cursor configured to move in forward order,
@@ -88222,16 +89976,16 @@ case OP_ColumnsUsed: {
 **
 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
 */
-/* Opcode: SeekLT P1 P2 P3 P4 * 
+/* Opcode: SeekLT P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
-** use the value in register P3 as a key. If cursor P1 refers 
-** to an SQL index, then P3 is the first in an array of P4 registers 
-** that are used as an unpacked index key. 
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
 **
-** Reposition cursor P1 so that  it points to the largest entry that 
-** is less than the key value. If there are no records less than 
+** Reposition cursor P1 so that  it points to the largest entry that
+** is less than the key value. If there are no records less than
 ** the key and P2 is not zero, then jump to P2.
 **
 ** This opcode leaves the cursor configured to move in reverse order,
@@ -88243,13 +89997,13 @@ case OP_ColumnsUsed: {
 /* Opcode: SeekLE P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
-** use the value in register P3 as a key. If cursor P1 refers 
-** to an SQL index, then P3 is the first in an array of P4 registers 
-** that are used as an unpacked index key. 
+** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
+** use the value in register P3 as a key. If cursor P1 refers
+** to an SQL index, then P3 is the first in an array of P4 registers
+** that are used as an unpacked index key.
 **
-** Reposition cursor P1 so that it points to the largest entry that 
-** is less than or equal to the key value. If there are no records 
+** Reposition cursor P1 so that it points to the largest entry that
+** is less than or equal to the key value. If there are no records
 ** less than or equal to the key and P2 is not zero, then jump to P2.
 **
 ** This opcode leaves the cursor configured to move in reverse order,
@@ -88257,11 +90011,13 @@ case OP_ColumnsUsed: {
 ** configured to use Prev, not Next.
 **
 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
-** opcode will always land on a record that equally equals the key, or
-** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
-** opcode must be followed by an IdxGE opcode with the same arguments.
+** opcode will either land on a record that exactly matches the key, or
+** else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
+** this opcode must be followed by an IdxLE opcode with the same arguments.
 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
-** IdxGE opcode will be used on subsequent loop iterations.
+** IdxGE opcode will be used on subsequent loop iterations.  The
+** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
+** is an equality search.
 **
 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
 */
@@ -88298,7 +90054,7 @@ case OP_SeekGT: {       /* jump, in3, group */
   pC->cacheStatus = CACHE_STALE;
   if( pC->isTable ){
     u16 flags3, newType;
-    /* The BTREE_SEEK_EQ flag is only set on index cursors */
+    /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
               || CORRUPT_DB );
 
@@ -88357,14 +90113,17 @@ case OP_SeekGT: {       /* jump, in3, group */
       goto abort_due_to_error;
     }
   }else{
-    /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
-    ** OP_SeekLE opcodes are allowed, and these must be immediately followed
-    ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
+    /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
+    ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
+    ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
+    ** with the same key.
     */
     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
       eqOnly = 1;
       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
+      assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
+      assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
       assert( pOp[1].p1==pOp[0].p1 );
       assert( pOp[1].p2==pOp[0].p2 );
       assert( pOp[1].p3==pOp[0].p3 );
@@ -88454,22 +90213,186 @@ seek_not_found:
   break;
 }
 
-/* Opcode: SeekHit P1 P2 * * *
-** Synopsis: seekHit=P2
+
+/* Opcode: SeekScan  P1 P2 * * *
+** Synopsis: Scan-ahead up to P1 rows
 **
-** Set the seekHit flag on cursor P1 to the value in P2.
-** The seekHit flag is used by the IfNoHope opcode.
+** This opcode is a prefix opcode to OP_SeekGE.  In other words, this
+** opcode must be immediately followed by OP_SeekGE. This constraint is
+** checked by assert() statements.
 **
-** P1 must be a valid b-tree cursor.  P2 must be a boolean value,
-** either 0 or 1.
+** This opcode uses the P1 through P4 operands of the subsequent
+** OP_SeekGE.  In the text that follows, the operands of the subsequent
+** OP_SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
+** the P1 and P2 operands of this opcode are also used, and  are called
+** This.P1 and This.P2.
+**
+** This opcode helps to optimize IN operators on a multi-column index
+** where the IN operator is on the later terms of the index by avoiding
+** unnecessary seeks on the btree, substituting steps to the next row
+** of the b-tree instead.  A correct answer is obtained if this opcode
+** is omitted or is a no-op.
+**
+** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
+** is the desired entry that we want the cursor SeekGE.P1 to be pointing
+** to.  Call this SeekGE.P4/P5 row the "target".
+**
+** If the SeekGE.P1 cursor is not currently pointing to a valid row,
+** then this opcode is a no-op and control passes through into the OP_SeekGE.
+**
+** If the SeekGE.P1 cursor is pointing to a valid row, then that row
+** might be the target row, or it might be near and slightly before the
+** target row.  This opcode attempts to position the cursor on the target
+** row by, perhaps by invoking sqlite3BtreeStep() on the cursor
+** between 0 and This.P1 times.
+**
+** There are three possible outcomes from this opcode:<ol>
+**
+** <li> If after This.P1 steps, the cursor is still point to a place that
+**      is earlier in the btree than the target row,
+**      then fall through into the subsquence OP_SeekGE opcode.
+**
+** <li> If the cursor is successfully moved to the target row by 0 or more
+**      sqlite3BtreeNext() calls, then jump to This.P2, which will land just
+**      past the OP_IdxGT opcode that follows the OP_SeekGE.
+**
+** <li> If the cursor ends up past the target row (indicating the the target
+**      row does not exist in the btree) then jump to SeekOP.P2.
+** </ol>
+*/
+case OP_SeekScan: {
+  VdbeCursor *pC;
+  int res;
+  int nStep;
+  UnpackedRecord r;
+
+  assert( pOp[1].opcode==OP_SeekGE );
+
+  /* pOp->p2 points to the first instruction past the OP_IdxGT that
+  ** follows the OP_SeekGE.  */
+  assert( pOp->p2>=(int)(pOp-aOp)+2 );
+  assert( aOp[pOp->p2-1].opcode==OP_IdxGT );
+  assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
+  assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
+  assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
+
+  assert( pOp->p1>0 );
+  pC = p->apCsr[pOp[1].p1];
+  assert( pC!=0 );
+  assert( pC->eCurType==CURTYPE_BTREE );
+  assert( !pC->isTable );
+  if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
+#ifdef SQLITE_DEBUG
+     if( db->flags&SQLITE_VdbeTrace ){
+       printf("... cursor not valid - fall through\n");
+     }
+#endif
+    break;
+  }
+  nStep = pOp->p1;
+  assert( nStep>=1 );
+  r.pKeyInfo = pC->pKeyInfo;
+  r.nField = (u16)pOp[1].p4.i;
+  r.default_rc = 0;
+  r.aMem = &aMem[pOp[1].p3];
+#ifdef SQLITE_DEBUG
+  {
+    int i;
+    for(i=0; i<r.nField; i++){
+      assert( memIsValid(&r.aMem[i]) );
+      REGISTER_TRACE(pOp[1].p3+i, &aMem[pOp[1].p3+i]);
+    }
+  }
+#endif
+  res = 0;  /* Not needed.  Only used to silence a warning. */
+  while(1){
+    rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
+    if( rc ) goto abort_due_to_error;
+    if( res>0 ){
+      seekscan_search_fail:
+#ifdef SQLITE_DEBUG
+      if( db->flags&SQLITE_VdbeTrace ){
+        printf("... %d steps and then skip\n", pOp->p1 - nStep);
+      }
+#endif
+      VdbeBranchTaken(1,3);
+      pOp++;
+      goto jump_to_p2;
+    }
+    if( res==0 ){
+#ifdef SQLITE_DEBUG
+      if( db->flags&SQLITE_VdbeTrace ){
+        printf("... %d steps and then success\n", pOp->p1 - nStep);
+      }
+#endif
+      VdbeBranchTaken(2,3);
+      goto jump_to_p2;
+      break;
+    }
+    if( nStep<=0 ){
+#ifdef SQLITE_DEBUG
+      if( db->flags&SQLITE_VdbeTrace ){
+        printf("... fall through after %d steps\n", pOp->p1);
+      }
+#endif
+      VdbeBranchTaken(0,3);
+      break;
+    }
+    nStep--;
+    rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
+    if( rc ){
+      if( rc==SQLITE_DONE ){
+        rc = SQLITE_OK;
+        goto seekscan_search_fail;
+      }else{
+        goto abort_due_to_error;
+      }
+    }
+  }
+
+  break;
+}
+
+
+/* Opcode: SeekHit P1 P2 P3 * *
+** Synopsis: set P2<=seekHit<=P3
+**
+** Increase or decrease the seekHit value for cursor P1, if necessary,
+** so that it is no less than P2 and no greater than P3.
+**
+** The seekHit integer represents the maximum of terms in an index for which
+** there is known to be at least one match.  If the seekHit value is smaller
+** than the total number of equality terms in an index lookup, then the
+** OP_IfNoHope opcode might run to see if the IN loop can be abandoned
+** early, thus saving work.  This is part of the IN-early-out optimization.
+**
+** P1 must be a valid b-tree cursor.
 */
 case OP_SeekHit: {
   VdbeCursor *pC;
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   assert( pC!=0 );
-  assert( pOp->p2==0 || pOp->p2==1 );
-  pC->seekHit = pOp->p2 & 1;
+  assert( pOp->p3>=pOp->p2 );
+  if( pC->seekHit<pOp->p2 ){
+    pC->seekHit = pOp->p2;
+  }else if( pC->seekHit>pOp->p3 ){
+    pC->seekHit = pOp->p3;
+  }
+  break;
+}
+
+/* Opcode: IfNotOpen P1 P2 * * *
+** Synopsis: if( !csr[P1] ) goto P2
+**
+** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
+*/
+case OP_IfNotOpen: {        /* jump */
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+  VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
+  if( !p->apCsr[pOp->p1] ){
+    goto jump_to_p2_and_check_for_interrupt;
+  }
   break;
 }
 
@@ -88496,9 +90419,9 @@ case OP_SeekHit: {
 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 ** record.
-** 
+**
 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
-** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
+** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
 ** does contain an entry whose prefix matches the P3/P4 record then control
 ** falls through to the next instruction and P1 is left pointing at the
 ** matching entry.
@@ -88513,16 +90436,20 @@ case OP_SeekHit: {
 ** Synopsis: key=r[P3@P4]
 **
 ** Register P3 is the first of P4 registers that form an unpacked
-** record.
+** record.  Cursor P1 is an index btree.  P2 is a jump destination.
+** In other words, the operands to this opcode are the same as the
+** operands to OP_NotFound and OP_IdxGT.
 **
-** Cursor P1 is on an index btree.  If the seekHit flag is set on P1, then
-** this opcode is a no-op.  But if the seekHit flag of P1 is clear, then
-** check to see if there is any entry in P1 that matches the
-** prefix identified by P3 and P4.  If no entry matches the prefix,
-** jump to P2.  Otherwise fall through.
+** This opcode is an optimization attempt only.  If this opcode always
+** falls through, the correct answer is still obtained, but extra works
+** is performed.
 **
-** This opcode behaves like OP_NotFound if the seekHit
-** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
+** A value of N in the seekHit flag of cursor P1 means that there exists
+** a key P3:N that will match some record in the index.  We want to know
+** if it is possible for a record P3:P4 to match some record in the
+** index.  If it is not possible, we can skips some work.  So if seekHit
+** is less than P4, attempt to find out if a match is possible by running
+** OP_NotFound.
 **
 ** This opcode is used in IN clause processing for a multi-column key.
 ** If an IN clause is attached to an element of the key other than the
@@ -88542,7 +90469,7 @@ case OP_SeekHit: {
 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
 ** record.
-** 
+**
 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
 ** contains any NULL value, jump immediately to P2.  If all terms of the
 ** record are not-NULL then a check is done to determine if any row in the
@@ -88564,8 +90491,9 @@ case OP_IfNoHope: {     /* jump, in3 */
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   assert( pC!=0 );
-  if( pC->seekHit ) break;
+  if( pC->seekHit>=pOp->p4.i ) break;
   /* Fall through into OP_NotFound */
+  /* no break */ deliberate_fall_through
 }
 case OP_NoConflict:     /* jump, in3 */
 case OP_NotFound:       /* jump, in3 */
@@ -88645,6 +90573,7 @@ case OP_Found: {        /* jump, in3 */
   }else{
     VdbeBranchTaken(takeJump||alreadyExists==0,2);
     if( takeJump || !alreadyExists ) goto jump_to_p2;
+    if( pOp->opcode==OP_IfNoHope ) pC->seekHit = pOp->p4.i;
   }
   break;
 }
@@ -88654,9 +90583,9 @@ case OP_Found: {        /* jump, in3 */
 **
 ** P1 is the index of a cursor open on an SQL table btree (with integer
 ** keys).  If register P3 does not contain an integer or if P1 does not
-** contain a record with rowid P3 then jump immediately to P2.  
+** contain a record with rowid P3 then jump immediately to P2.
 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
-** a record with rowid P3 then 
+** a record with rowid P3 then
 ** leave the cursor pointing at that record and fall through to the next
 ** instruction.
 **
@@ -88679,7 +90608,7 @@ case OP_Found: {        /* jump, in3 */
 ** P1 is the index of a cursor open on an SQL table btree (with integer
 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
 ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
-** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 
+** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
 ** leave the cursor pointing at that record and fall through to the next
 ** instruction.
 **
@@ -88720,6 +90649,7 @@ case OP_SeekRowid: {        /* jump, in3 */
     goto notExistsWithKey;
   }
   /* Fall through into OP_NotExists */
+  /* no break */ deliberate_fall_through
 case OP_NotExists:          /* jump, in3 */
   pIn3 = &aMem[pOp->p3];
   assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
@@ -88762,7 +90692,7 @@ notExistsWithKey:
 ** Find the next available sequence number for cursor P1.
 ** Write the sequence number into register P2.
 ** The sequence number on the cursor is incremented after this
-** instruction.  
+** instruction.
 */
 case OP_Sequence: {           /* out2 */
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
@@ -88782,9 +90712,9 @@ case OP_Sequence: {           /* out2 */
 ** table that cursor P1 points to.  The new record number is written
 ** written to register P2.
 **
-** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
+** If P3>0 then P3 is a register in the root frame of this VDBE that holds
 ** the largest previously generated record number. No new record numbers are
-** allowed to be less than this value. When this value reaches its maximum, 
+** allowed to be less than this value. When this value reaches its maximum,
 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
 ** generated record number. This P3 mechanism is used to help implement the
 ** AUTOINCREMENT feature.
@@ -88933,8 +90863,8 @@ case OP_NewRowid: {           /* out2 */
 ** is part of an INSERT operation.  The difference is only important to
 ** the update hook.
 **
-** Parameter P4 may point to a Table structure, or may be NULL. If it is 
-** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 
+** Parameter P4 may point to a Table structure, or may be NULL. If it is
+** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
 ** following a successful insert.
 **
 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
@@ -88961,6 +90891,7 @@ case OP_Insert: {
   pC = p->apCsr[pOp->p1];
   assert( pC!=0 );
   assert( pC->eCurType==CURTYPE_BTREE );
+  assert( pC->deferredMoveto==0 );
   assert( pC->uc.pCursor!=0 );
   assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
@@ -88999,7 +90930,7 @@ case OP_Insert: {
 
   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
-  assert( pData->flags & (MEM_Blob|MEM_Str) );
+  assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
   x.pData = pData->z;
   x.nData = pData->n;
   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
@@ -89035,7 +90966,7 @@ case OP_Insert: {
 ** the cursor will be left pointing at  either the next or the previous
 ** record in the table. If it is left pointing at the next record, then
 ** the next Next instruction will be a no-op. As a result, in this case
-** it is ok to delete a record from within a Next loop. If 
+** it is ok to delete a record from within a Next loop. If
 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
 ** left in an undefined state.
 **
@@ -89051,11 +90982,11 @@ case OP_Insert: {
 ** P1 must not be pseudo-table.  It has to be a real table with
 ** multiple rows.
 **
-** If P4 is not NULL then it points to a Table object. In this case either 
+** If P4 is not NULL then it points to a Table object. In this case either
 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
-** have been positioned using OP_NotFound prior to invoking this opcode in 
-** this case. Specifically, if one is configured, the pre-update hook is 
-** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 
+** have been positioned using OP_NotFound prior to invoking this opcode in
+** this case. Specifically, if one is configured, the pre-update hook is
+** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
 **
 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
@@ -89078,7 +91009,11 @@ case OP_Delete: {
   sqlite3VdbeIncrWriteCounter(p, pC);
 
 #ifdef SQLITE_DEBUG
-  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
+  if( pOp->p4type==P4_TABLE
+   && HasRowid(pOp->p4.pTab)
+   && pOp->p5==0
+   && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
+  ){
     /* If p5 is zero, the seek operation that positioned the cursor prior to
     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
     ** the row that is being deleted */
@@ -89090,7 +91025,7 @@ case OP_Delete: {
   /* If the update-hook or pre-update-hook will be invoked, set zDb to
   ** the name of the db to pass as to it. Also set local pTab to a copy
   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
-  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
+  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
   ** VdbeCursor.movetoTarget to the current rowid.  */
   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
     assert( pC->iDb>=0 );
@@ -89108,20 +91043,20 @@ case OP_Delete: {
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
   /* Invoke the pre-update-hook if required. */
   if( db->xPreUpdateCallback && pOp->p4.pTab ){
-    assert( !(opflags & OPFLAG_ISUPDATE) 
-         || HasRowid(pTab)==0 
-         || (aMem[pOp->p3].flags & MEM_Int) 
+    assert( !(opflags & OPFLAG_ISUPDATE)
+         || HasRowid(pTab)==0
+         || (aMem[pOp->p3].flags & MEM_Int)
     );
     sqlite3VdbePreUpdateHook(p, pC,
-        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 
+        (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
         zDb, pTab, pC->movetoTarget,
         pOp->p3
     );
   }
   if( opflags & OPFLAG_ISNOOP ) break;
 #endif
-  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 
+
+  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
@@ -89174,7 +91109,7 @@ case OP_ResetCount: {
 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
 **
 ** P1 is a sorter cursor. This instruction compares a prefix of the
-** record blob in register P3 against a prefix of the entry that 
+** record blob in register P3 against a prefix of the entry that
 ** the sorter cursor currently points to.  Only the first P4 fields
 ** of r[P3] and the sorter record are compared.
 **
@@ -89232,10 +91167,10 @@ case OP_SorterData: {
 /* Opcode: RowData P1 P2 P3 * *
 ** Synopsis: r[P2]=data
 **
-** Write into register P2 the complete row content for the row at 
+** Write into register P2 the complete row content for the row at
 ** which cursor P1 is currently pointing.
-** There is no interpretation of the data.  
-** It is just copied onto the P2 register exactly as 
+** There is no interpretation of the data.
+** It is just copied onto the P2 register exactly as
 ** it is found in the database file.
 **
 ** If cursor P1 is an index, then the content is the key of the row.
@@ -89283,17 +91218,13 @@ case OP_RowData: {
   */
   assert( pC->deferredMoveto==0 );
   assert( sqlite3BtreeCursorIsValid(pCrsr) );
-#if 0  /* Not required due to the previous to assert() statements */
-  rc = sqlite3VdbeCursorMoveto(pC);
-  if( rc!=SQLITE_OK ) goto abort_due_to_error;
-#endif
 
   n = sqlite3BtreePayloadSize(pCrsr);
   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
     goto too_big;
   }
   testcase( n==0 );
-  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
+  rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
   if( rc ) goto abort_due_to_error;
   if( !pOp->p3 ) Deephemeralize(pOut);
   UPDATE_MAX_BLOBSIZE(pOut);
@@ -89388,7 +91319,7 @@ case OP_NullRow: {
 */
 /* Opcode: Last P1 P2 * * *
 **
-** The next use of the Rowid or Column or Prev instruction for P1 
+** The next use of the Rowid or Column or Prev instruction for P1
 ** will refer to the last entry in the database table or index.
 ** If the table or index is empty and P2>0, then jump immediately to P2.
 ** If P2 is 0 or if the table or index is not empty, fall through
@@ -89490,13 +91421,14 @@ case OP_Sort: {        /* jump */
 #endif
   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
   /* Fall through into OP_Rewind */
+  /* no break */ deliberate_fall_through
 }
 /* Opcode: Rewind P1 P2 * * *
 **
-** The next use of the Rowid or Column or Next instruction for P1 
+** The next use of the Rowid or Column or Next instruction for P1
 ** will refer to the first entry in the database table or index.
 ** If the table or index is empty, jump immediately to P2.
-** If the table or index is not empty, fall through to the following 
+** If the table or index is not empty, fall through to the following
 ** instruction.
 **
 ** This opcode leaves the cursor configured to move in forward order,
@@ -89666,11 +91598,41 @@ next_tail:
 ** run faster by avoiding an unnecessary seek on cursor P1.  However,
 ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
 ** seeks on the cursor or if the most recent seek used a key equivalent
-** to P2. 
+** to P2.
 **
 ** This instruction only works for indices.  The equivalent instruction
 ** for tables is OP_Insert.
 */
+case OP_IdxInsert: {        /* in2 */
+  VdbeCursor *pC;
+  BtreePayload x;
+
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+  pC = p->apCsr[pOp->p1];
+  sqlite3VdbeIncrWriteCounter(p, pC);
+  assert( pC!=0 );
+  assert( !isSorter(pC) );
+  pIn2 = &aMem[pOp->p2];
+  assert( pIn2->flags & MEM_Blob );
+  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
+  assert( pC->eCurType==CURTYPE_BTREE );
+  assert( pC->isTable==0 );
+  rc = ExpandBlob(pIn2);
+  if( rc ) goto abort_due_to_error;
+  x.nKey = pIn2->n;
+  x.pKey = pIn2->z;
+  x.aMem = aMem + pOp->p3;
+  x.nMem = (u16)pOp->p4.i;
+  rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
+       (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
+      ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
+      );
+  assert( pC->deferredMoveto==0 );
+  pC->cacheStatus = CACHE_STALE;
+  if( rc) goto abort_due_to_error;
+  break;
+}
+
 /* Opcode: SorterInsert P1 P2 * * *
 ** Synopsis: key=r[P2]
 **
@@ -89678,47 +91640,37 @@ next_tail:
 ** MakeRecord instructions.  This opcode writes that key
 ** into the sorter P1.  Data for the entry is nil.
 */
-case OP_SorterInsert:       /* in2 */
-case OP_IdxInsert: {        /* in2 */
+case OP_SorterInsert: {     /* in2 */
   VdbeCursor *pC;
-  BtreePayload x;
 
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   sqlite3VdbeIncrWriteCounter(p, pC);
   assert( pC!=0 );
-  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
+  assert( isSorter(pC) );
   pIn2 = &aMem[pOp->p2];
   assert( pIn2->flags & MEM_Blob );
-  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
-  assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
   assert( pC->isTable==0 );
   rc = ExpandBlob(pIn2);
   if( rc ) goto abort_due_to_error;
-  if( pOp->opcode==OP_SorterInsert ){
-    rc = sqlite3VdbeSorterWrite(pC, pIn2);
-  }else{
-    x.nKey = pIn2->n;
-    x.pKey = pIn2->z;
-    x.aMem = aMem + pOp->p3;
-    x.nMem = (u16)pOp->p4.i;
-    rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
-         (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), 
-        ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
-        );
-    assert( pC->deferredMoveto==0 );
-    pC->cacheStatus = CACHE_STALE;
-  }
+  rc = sqlite3VdbeSorterWrite(pC, pIn2);
   if( rc) goto abort_due_to_error;
   break;
 }
 
-/* Opcode: IdxDelete P1 P2 P3 * *
+/* Opcode: IdxDelete P1 P2 P3 * P5
 ** Synopsis: key=r[P2@P3]
 **
 ** The content of P3 registers starting at register P2 form
-** an unpacked index key. This opcode removes that entry from the 
+** an unpacked index key. This opcode removes that entry from the
 ** index opened by cursor P1.
+**
+** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
+** if no matching index entry is found.  This happens when running
+** an UPDATE or DELETE statement and the index entry to be updated
+** or deleted is not found.  For some uses of IdxDelete
+** (example:  the EXCEPT operator) it does not matter that no matching
+** entry is found.  For those cases, P5 is zero.
 */
 case OP_IdxDelete: {
   VdbeCursor *pC;
@@ -89735,7 +91687,6 @@ case OP_IdxDelete: {
   sqlite3VdbeIncrWriteCounter(p, pC);
   pCrsr = pC->uc.pCursor;
   assert( pCrsr!=0 );
-  assert( pOp->p5==0 );
   r.pKeyInfo = pC->pKeyInfo;
   r.nField = (u16)pOp->p3;
   r.default_rc = 0;
@@ -89745,6 +91696,9 @@ case OP_IdxDelete: {
   if( res==0 ){
     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
     if( rc ) goto abort_due_to_error;
+  }else if( pOp->p5 ){
+    rc = SQLITE_CORRUPT_INDEX;
+    goto abort_due_to_error;
   }
   assert( pC->deferredMoveto==0 );
   pC->cacheStatus = CACHE_STALE;
@@ -89765,8 +91719,8 @@ case OP_IdxDelete: {
 **
 ** P4 may be an array of integers (type P4_INTARRAY) containing
 ** one entry for each column in the P3 table.  If array entry a(i)
-** is non-zero, then reading column a(i)-1 from cursor P3 is 
-** equivalent to performing the deferred seek and then reading column i 
+** is non-zero, then reading column a(i)-1 from cursor P3 is
+** equivalent to performing the deferred seek and then reading column i
 ** from P1.  This information is stored in P3 and used to redirect
 ** reads against P3 over to P1, thus possibly avoiding the need to
 ** seek and read cursor P3.
@@ -89834,32 +91788,50 @@ case OP_IdxRowid: {           /* out2 */
   break;
 }
 
-/* Opcode: IdxGE P1 P2 P3 P4 P5
+/* Opcode: FinishSeek P1 * * * *
+**
+** If cursor P1 was previously moved via OP_DeferredSeek, complete that
+** seek operation now, without further delay.  If the cursor seek has
+** already occurred, this instruction is a no-op.
+*/
+case OP_FinishSeek: {
+  VdbeCursor *pC;             /* The P1 index cursor */
+
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+  pC = p->apCsr[pOp->p1];
+  if( pC->deferredMoveto ){
+    rc = sqlite3VdbeFinishMoveto(pC);
+    if( rc ) goto abort_due_to_error;
+  }
+  break;
+}
+
+/* Opcode: IdxGE P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** The P4 register values beginning with P3 form an unpacked index 
-** key that omits the PRIMARY KEY.  Compare this key value against the index 
-** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY.  Compare this key value against the index
+** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
 ** fields at the end.
 **
 ** If the P1 index entry is greater than or equal to the key value
 ** then jump to P2.  Otherwise fall through to the next instruction.
 */
-/* Opcode: IdxGT P1 P2 P3 P4 P5
+/* Opcode: IdxGT P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** The P4 register values beginning with P3 form an unpacked index 
-** key that omits the PRIMARY KEY.  Compare this key value against the index 
-** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
+** The P4 register values beginning with P3 form an unpacked index
+** key that omits the PRIMARY KEY.  Compare this key value against the index
+** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
 ** fields at the end.
 **
 ** If the P1 index entry is greater than the key value
 ** then jump to P2.  Otherwise fall through to the next instruction.
 */
-/* Opcode: IdxLT P1 P2 P3 P4 P5
+/* Opcode: IdxLT P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** The P4 register values beginning with P3 form an unpacked index 
+** The P4 register values beginning with P3 form an unpacked index
 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 ** ROWID on the P1 index.
@@ -89867,10 +91839,10 @@ case OP_IdxRowid: {           /* out2 */
 ** If the P1 index entry is less than the key value then jump to P2.
 ** Otherwise fall through to the next instruction.
 */
-/* Opcode: IdxLE P1 P2 P3 P4 P5
+/* Opcode: IdxLE P1 P2 P3 P4 *
 ** Synopsis: key=r[P3@P4]
 **
-** The P4 register values beginning with P3 form an unpacked index 
+** The P4 register values beginning with P3 form an unpacked index
 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
 ** ROWID on the P1 index.
@@ -89893,7 +91865,6 @@ case OP_IdxGE:  {       /* jump */
   assert( pC->eCurType==CURTYPE_BTREE );
   assert( pC->uc.pCursor!=0);
   assert( pC->deferredMoveto==0 );
-  assert( pOp->p5==0 || pOp->p5==1 );
   assert( pOp->p4type==P4_INT32 );
   r.pKeyInfo = pC->pKeyInfo;
   r.nField = (u16)pOp->p4.i;
@@ -89914,8 +91885,31 @@ case OP_IdxGE:  {       /* jump */
     }
   }
 #endif
-  res = 0;  /* Not needed.  Only used to silence a warning. */
-  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
+
+  /* Inlined version of sqlite3VdbeIdxKeyCompare() */
+  {
+    i64 nCellKey = 0;
+    BtCursor *pCur;
+    Mem m;
+
+    assert( pC->eCurType==CURTYPE_BTREE );
+    pCur = pC->uc.pCursor;
+    assert( sqlite3BtreeCursorIsValid(pCur) );
+    nCellKey = sqlite3BtreePayloadSize(pCur);
+    /* nCellKey will always be between 0 and 0xffffffff because of the way
+    ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
+    if( nCellKey<=0 || nCellKey>0x7fffffff ){
+      rc = SQLITE_CORRUPT_BKPT;
+      goto abort_due_to_error;
+    }
+    sqlite3VdbeMemInit(&m, db, 0);
+    rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
+    if( rc ) goto abort_due_to_error;
+    res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, &r, 0);
+    sqlite3VdbeMemRelease(&m);
+  }
+  /* End of inlined sqlite3VdbeIdxKeyCompare() */
+
   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
@@ -89925,7 +91919,7 @@ case OP_IdxGE:  {       /* jump */
     res++;
   }
   VdbeBranchTaken(res>0,2);
-  if( rc ) goto abort_due_to_error;
+  assert( rc==SQLITE_OK );
   if( res>0 ) goto jump_to_p2;
   break;
 }
@@ -89944,15 +91938,15 @@ case OP_IdxGE:  {       /* jump */
 ** root pages contiguous at the beginning of the database.  The former
 ** value of the root page that moved - its value before the move occurred -
 ** is stored in register P2. If no page movement was required (because the
-** table being dropped was already the last one in the database) then a 
-** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero 
+** table being dropped was already the last one in the database) then a
+** zero is stored in register P2.  If AUTOVACUUM is disabled then a zero
 ** is stored in register P2.
 **
 ** This opcode throws an error if there are any active reader VMs when
-** it is invoked. This is done to avoid the difficulty associated with 
-** updating existing cursors when a root page is moved in an AUTOVACUUM 
-** database. This error is thrown even if the database is not an AUTOVACUUM 
-** db in order to avoid introducing an incompatibility between autovacuum 
+** it is invoked. This is done to avoid the difficulty associated with
+** updating existing cursors when a root page is moved in an AUTOVACUUM
+** database. This error is thrown even if the database is not an AUTOVACUUM
+** db in order to avoid introducing an incompatibility between autovacuum
 ** and non-autovacuum modes.
 **
 ** See also: Clear
@@ -90001,8 +91995,8 @@ case OP_Destroy: {     /* out2 */
 ** that is used to store tables create using CREATE TEMPORARY TABLE.
 **
 ** If the P3 value is non-zero, then the table referred to must be an
-** intkey table (an SQL table, not an index). In this case the row change 
-** count is incremented by the number of rows in the table being cleared. 
+** intkey table (an SQL table, not an index). In this case the row change
+** count is incremented by the number of rows in the table being cleared.
 ** If P3 is greater than zero, then the value stored in register P3 is
 ** also incremented by the number of rows in the table being cleared.
 **
@@ -90010,13 +92004,13 @@ case OP_Destroy: {     /* out2 */
 */
 case OP_Clear: {
   u64 nChange;
+
   sqlite3VdbeIncrWriteCounter(p, 0);
   nChange = 0;
   assert( p->readOnly==0 );
   assert( DbMaskTest(p->btreeMask, pOp->p2) );
   rc = sqlite3BtreeClearTable(
-      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
+      db->aDb[pOp->p2].pBt, (u32)pOp->p1, (pOp->p3 ? &nChange : 0)
   );
   if( pOp->p3 ){
     p->nChange += nChange;
@@ -90040,7 +92034,7 @@ case OP_Clear: {
 */
 case OP_ResetSorter: {
   VdbeCursor *pC;
+
   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
   pC = p->apCsr[pOp->p1];
   assert( pC!=0 );
@@ -90065,7 +92059,7 @@ case OP_ResetSorter: {
 ** The root page number of the new b-tree is stored in register P2.
 */
 case OP_CreateBtree: {          /* out2 */
-  int pgno;
+  Pgno pgno;
   Db *pDb;
 
   sqlite3VdbeIncrWriteCounter(p, 0);
@@ -90098,7 +92092,7 @@ case OP_SqlExec: {
 
 /* Opcode: ParseSchema P1 * * P4 *
 **
-** Read and parse all entries from the SQLITE_MASTER table of database P1
+** Read and parse all entries from the schema table of database P1
 ** that match the WHERE clause P4.  If P4 is a NULL pointer, then the
 ** entire schema for P1 is reparsed.
 **
@@ -90107,12 +92101,12 @@ case OP_SqlExec: {
 */
 case OP_ParseSchema: {
   int iDb;
-  const char *zMaster;
+  const char *zSchema;
   char *zSql;
   InitData initData;
 
   /* Any prepared statement that invokes this opcode will hold mutexes
-  ** on every btree.  This is a prerequisite for invoking 
+  ** on every btree.  This is a prerequisite for invoking
   ** sqlite3InitCallback().
   */
 #ifdef SQLITE_DEBUG
@@ -90135,14 +92129,15 @@ case OP_ParseSchema: {
   }else
 #endif
   {
-    zMaster = MASTER_NAME;
+    zSchema = DFLT_SCHEMA_TABLE;
     initData.db = db;
     initData.iDb = iDb;
     initData.pzErrMsg = &p->zErrMsg;
     initData.mInitFlags = 0;
+    initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
     zSql = sqlite3MPrintf(db,
        "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
-       db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
+       db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
     if( zSql==0 ){
       rc = SQLITE_NOMEM_BKPT;
     }else{
@@ -90156,7 +92151,7 @@ case OP_ParseSchema: {
       if( rc==SQLITE_OK && initData.nInitRow==0 ){
         /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
         ** at least one SQL statement. Any less than that indicates that
-        ** the sqlite_master table is corrupt. */
+        ** the sqlite_schema table is corrupt. */
         rc = SQLITE_CORRUPT_BKPT;
       }
       sqlite3DbFreeNN(db, zSql);
@@ -90170,7 +92165,7 @@ case OP_ParseSchema: {
     }
     goto abort_due_to_error;
   }
-  break;  
+  break;
 }
 
 #if !defined(SQLITE_OMIT_ANALYZE)
@@ -90184,7 +92179,7 @@ case OP_LoadAnalysis: {
   assert( pOp->p1>=0 && pOp->p1<db->nDb );
   rc = sqlite3AnalysisLoad(db, pOp->p1);
   if( rc ) goto abort_due_to_error;
-  break;  
+  break;
 }
 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
 
@@ -90192,7 +92187,7 @@ case OP_LoadAnalysis: {
 **
 ** Remove the internal (in-memory) data structures that describe
 ** the table named P4 in database P1.  This is called after a table
-** is dropped from disk (using the Destroy opcode) in order to keep 
+** is dropped from disk (using the Destroy opcode) in order to keep
 ** the internal representation of the
 ** schema consistent with what is on disk.
 */
@@ -90220,7 +92215,7 @@ case OP_DropIndex: {
 **
 ** Remove the internal (in-memory) data structures that describe
 ** the trigger named P4 in database P1.  This is called after a trigger
-** is dropped from disk (using the Destroy opcode) in order to keep 
+** is dropped from disk (using the Destroy opcode) in order to keep
 ** the internal representation of the
 ** schema consistent with what is on disk.
 */
@@ -90240,7 +92235,7 @@ case OP_DropTrigger: {
 **
 ** The register P3 contains one less than the maximum number of allowed errors.
 ** At most reg(P3) errors will be reported.
-** In other words, the analysis stops as soon as reg(P1) errors are 
+** In other words, the analysis stops as soon as reg(P1) errors are
 ** seen.  Reg(P1) is updated with the number of errors remaining.
 **
 ** The root page numbers of all tables in the database are integers
@@ -90253,7 +92248,7 @@ case OP_DropTrigger: {
 */
 case OP_IntegrityCk: {
   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
-  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
+  Pgno *aRoot;    /* Array of rootpage numbers for tables to be checked */
   int nErr;       /* Number of errors reported */
   char *z;        /* Text of the error report */
   Mem *pnErr;     /* Register keeping track of errors remaining */
@@ -90262,7 +92257,7 @@ case OP_IntegrityCk: {
   nRoot = pOp->p2;
   aRoot = pOp->p4.ai;
   assert( nRoot>0 );
-  assert( aRoot[0]==nRoot );
+  assert( aRoot[0]==(Pgno)nRoot );
   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
   pnErr = &aMem[pOp->p3];
   assert( (pnErr->flags & MEM_Int)!=0 );
@@ -90270,7 +92265,7 @@ case OP_IntegrityCk: {
   pIn1 = &aMem[pOp->p1];
   assert( pOp->p5<db->nDb );
   assert( DbMaskTest(p->btreeMask, pOp->p5) );
-  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
+  z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
                                  (int)pnErr->u.i+1, &nErr);
   sqlite3VdbeMemSetNull(pIn1);
   if( nErr==0 ){
@@ -90283,7 +92278,7 @@ case OP_IntegrityCk: {
   }
   UPDATE_MAX_BLOBSIZE(pIn1);
   sqlite3VdbeChangeEncoding(pIn1, encoding);
-  break;
+  goto check_for_interrupt;
 }
 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 
@@ -90320,7 +92315,7 @@ case OP_RowSetRead: {       /* jump, in1, out3 */
 
   pIn1 = &aMem[pOp->p1];
   assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
-  if( (pIn1->flags & MEM_Blob)==0 
+  if( (pIn1->flags & MEM_Blob)==0
    || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
   ){
     /* The boolean index is empty */
@@ -90392,13 +92387,13 @@ case OP_RowSetTest: {                     /* jump, in1, in3 */
 
 /* Opcode: Program P1 P2 P3 P4 P5
 **
-** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
+** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
 **
-** P1 contains the address of the memory cell that contains the first memory 
-** cell in an array of values used as arguments to the sub-program. P2 
-** contains the address to jump to if the sub-program throws an IGNORE 
-** exception using the RAISE() function. Register P3 contains the address 
-** of a memory cell in this (the parent) VM that is used to allocate the 
+** P1 contains the address of the memory cell that contains the first memory
+** cell in an array of values used as arguments to the sub-program. P2
+** contains the address to jump to if the sub-program throws an IGNORE
+** exception using the RAISE() function. Register P3 contains the address
+** of a memory cell in this (the parent) VM that is used to allocate the
 ** memory required by the sub-vdbe at runtime.
 **
 ** P4 is a pointer to the VM containing the trigger program.
@@ -90418,17 +92413,17 @@ case OP_Program: {        /* jump */
   pProgram = pOp->p4.pProgram;
   pRt = &aMem[pOp->p3];
   assert( pProgram->nOp>0 );
-  
-  /* If the p5 flag is clear, then recursive invocation of triggers is 
+
+  /* If the p5 flag is clear, then recursive invocation of triggers is
   ** disabled for backwards compatibility (p5 is set if this sub-program
   ** is really a trigger, not a foreign key action, and the flag set
   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
-  ** 
-  ** It is recursive invocation of triggers, at the SQL level, that is 
-  ** disabled. In some cases a single trigger may generate more than one 
-  ** SubProgram (if the trigger may be executed with more than one different 
+  **
+  ** It is recursive invocation of triggers, at the SQL level, that is
+  ** disabled. In some cases a single trigger may generate more than one
+  ** SubProgram (if the trigger may be executed with more than one different
   ** ON CONFLICT algorithm). SubProgram structures associated with a
-  ** single trigger all have the same value for the SubProgram.token 
+  ** single trigger all have the same value for the SubProgram.token
   ** variable.  */
   if( pOp->p5 ){
     t = pProgram->token;
@@ -90444,10 +92439,10 @@ case OP_Program: {        /* jump */
 
   /* Register pRt is used to store the memory required to save the state
   ** of the current program, and the memory required at runtime to execute
-  ** the trigger program. If this trigger has been fired before, then pRt 
+  ** the trigger program. If this trigger has been fired before, then pRt
   ** is already allocated. Otherwise, it must be initialized.  */
   if( (pRt->flags&MEM_Blob)==0 ){
-    /* SubProgram.nMem is set to the number of memory cells used by the 
+    /* SubProgram.nMem is set to the number of memory cells used by the
     ** program stored in SubProgram.aOp. As well as these, one memory
     ** cell is required for each cursor used by the program. Set local
     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
@@ -90495,7 +92490,7 @@ case OP_Program: {        /* jump */
   }else{
     pFrame = (VdbeFrame*)pRt->z;
     assert( pRt->xDel==sqlite3VdbeFrameMemDel );
-    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
+    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
     assert( pProgram->nCsr==pFrame->nChildCsr );
     assert( (int)(pOp - aOp)==pFrame->pc );
@@ -90529,7 +92524,7 @@ case OP_Program: {        /* jump */
     int i;
     for(i=0; i<p->nMem; i++){
       aMem[i].pScopyFrom = 0;  /* Prevent false-positive AboutToChange() errs */
-      aMem[i].flags |= MEM_Undefined; /* Cause a fault if this reg is reused */
+      MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
     }
   }
 #endif
@@ -90539,10 +92534,10 @@ case OP_Program: {        /* jump */
 
 /* Opcode: Param P1 P2 * * *
 **
-** This opcode is only ever present in sub-programs called via the 
-** OP_Program instruction. Copy a value currently stored in a memory 
-** cell of the calling (parent) frame to cell P2 in the current frames 
-** address space. This is used by trigger programs to access the new.* 
+** This opcode is only ever present in sub-programs called via the
+** OP_Program instruction. Copy a value currently stored in a memory
+** cell of the calling (parent) frame to cell P2 in the current frames
+** address space. This is used by trigger programs to access the new.*
 ** and old.* values.
 **
 ** The address of the cell in the parent frame is determined by adding
@@ -90554,7 +92549,7 @@ case OP_Param: {           /* out2 */
   Mem *pIn;
   pOut = out2Prerelease(p, pOp);
   pFrame = p->pFrame;
-  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
+  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
   break;
 }
@@ -90566,8 +92561,8 @@ case OP_Param: {           /* out2 */
 ** Synopsis: fkctr[P1]+=P2
 **
 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
-** If P1 is non-zero, the database constraint counter is incremented 
-** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
+** If P1 is non-zero, the database constraint counter is incremented
+** (deferred foreign key constraints). Otherwise, if P1 is zero, the
 ** statement counter is incremented (immediate foreign key constraints).
 */
 case OP_FkCounter: {
@@ -90585,7 +92580,7 @@ case OP_FkCounter: {
 ** Synopsis: if fkctr[P1]==0 goto P2
 **
 ** This opcode tests if a foreign key constraint-counter is currently zero.
-** If so, jump to instruction P2. Otherwise, fall through to the next 
+** If so, jump to instruction P2. Otherwise, fall through to the next
 ** instruction.
 **
 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
@@ -90611,7 +92606,7 @@ case OP_FkIfZero: {         /* jump */
 **
 ** P1 is a register in the root frame of this VM (the root frame is
 ** different from the current frame if this instruction is being executed
-** within a sub-program). Set the value of register P1 to the maximum of 
+** within a sub-program). Set the value of register P1 to the maximum of
 ** its current value and the value in register P2.
 **
 ** This instruction throws an error if the memory cell is not initially
@@ -90671,7 +92666,7 @@ case OP_IfPos: {        /* jump, in1 */
 ** and r[P2] is set to be the value of the LIMIT, r[P1].
 **
 ** if r[P1] is zero or negative, that means there is no LIMIT
-** and r[P2] is set to -1. 
+** and r[P2] is set to -1.
 **
 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
 */
@@ -90703,7 +92698,7 @@ case OP_OffsetLimit: {    /* in1, out2, in3 */
 **
 ** Register P1 must contain an integer.  If the content of register P1 is
 ** initially greater than zero, then decrement the value in register P1.
-** If it is non-zero (negative or positive) and then also jump to P2.  
+** If it is non-zero (negative or positive) and then also jump to P2.
 ** If register P1 is initially zero, leave it unchanged and fall through.
 */
 case OP_IfNotZero: {        /* jump, in1 */
@@ -90737,7 +92732,7 @@ case OP_DecrJumpZero: {      /* jump, in1 */
 ** Synopsis: accum=r[P3] step(r[P2@P5])
 **
 ** Execute the xStep function for an aggregate.
-** The function has P5 arguments.  P4 is a pointer to the 
+** The function has P5 arguments.  P4 is a pointer to the
 ** FuncDef structure that specifies the function.  Register P3 is the
 ** accumulator.
 **
@@ -90748,7 +92743,7 @@ case OP_DecrJumpZero: {      /* jump, in1 */
 ** Synopsis: accum=r[P3] inverse(r[P2@P5])
 **
 ** Execute the xInverse function for an aggregate.
-** The function has P5 arguments.  P4 is a pointer to the 
+** The function has P5 arguments.  P4 is a pointer to the
 ** FuncDef structure that specifies the function.  Register P3 is the
 ** accumulator.
 **
@@ -90759,7 +92754,7 @@ case OP_DecrJumpZero: {      /* jump, in1 */
 ** Synopsis: accum=r[P3] step(r[P2@P5])
 **
 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
-** aggregate.  The function has P5 arguments.  P4 is a pointer to the 
+** aggregate.  The function has P5 arguments.  P4 is a pointer to the
 ** FuncDef structure that specifies the function.  Register P3 is the
 ** accumulator.
 **
@@ -90802,6 +92797,7 @@ case OP_AggStep: {
 
   pOp->opcode = OP_AggStep1;
   /* Fall through into OP_AggStep */
+  /* no break */ deliberate_fall_through
 }
 case OP_AggStep1: {
   int i;
@@ -90875,7 +92871,7 @@ case OP_AggStep1: {
 ** Synopsis: accum=r[P1] N=P2
 **
 ** P1 is the memory location that is the accumulator for an aggregate
-** or window function.  Execute the finalizer function 
+** or window function.  Execute the finalizer function
 ** for an aggregate and store the result in P1.
 **
 ** P2 is the number of arguments that the step function takes and
@@ -90914,7 +92910,7 @@ case OP_AggFinal: {
   {
     rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
   }
-  
+
   if( rc ){
     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
     goto abort_due_to_error;
@@ -90960,9 +92956,9 @@ case OP_Checkpoint: {
   }
   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
-  }    
+  }
   break;
-};  
+};
 #endif
 
 #ifndef SQLITE_OMIT_PRAGMA
@@ -90988,9 +92984,9 @@ case OP_JournalMode: {    /* out2 */
 
   pOut = out2Prerelease(p, pOp);
   eNew = pOp->p3;
-  assert( eNew==PAGER_JOURNALMODE_DELETE 
-       || eNew==PAGER_JOURNALMODE_TRUNCATE 
-       || eNew==PAGER_JOURNALMODE_PERSIST 
+  assert( eNew==PAGER_JOURNALMODE_DELETE
+       || eNew==PAGER_JOURNALMODE_TRUNCATE
+       || eNew==PAGER_JOURNALMODE_PERSIST
        || eNew==PAGER_JOURNALMODE_OFF
        || eNew==PAGER_JOURNALMODE_MEMORY
        || eNew==PAGER_JOURNALMODE_WAL
@@ -91009,7 +93005,7 @@ case OP_JournalMode: {    /* out2 */
   zFilename = sqlite3PagerFilename(pPager, 1);
 
   /* Do not allow a transition to journal_mode=WAL for a database
-  ** in temporary storage or if the VFS does not support shared memory 
+  ** in temporary storage or if the VFS does not support shared memory
   */
   if( eNew==PAGER_JOURNALMODE_WAL
    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
@@ -91029,12 +93025,12 @@ case OP_JournalMode: {    /* out2 */
       );
       goto abort_due_to_error;
     }else{
+
       if( eOld==PAGER_JOURNALMODE_WAL ){
         /* If leaving WAL mode, close the log file. If successful, the call
-        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
-        ** file. An EXCLUSIVE lock may still be held on the database file 
-        ** after a successful return. 
+        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
+        ** file. An EXCLUSIVE lock may still be held on the database file
+        ** after a successful return.
         */
         rc = sqlite3PagerCloseWal(pPager, db);
         if( rc==SQLITE_OK ){
@@ -91045,11 +93041,11 @@ case OP_JournalMode: {    /* out2 */
         ** as an intermediate */
         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
       }
-  
+
       /* Open a transaction on the database file. Regardless of the journal
       ** mode, this transaction always uses a rollback journal.
       */
-      assert( sqlite3BtreeIsInTrans(pBt)==0 );
+      assert( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE );
       if( rc==SQLITE_OK ){
         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
       }
@@ -91120,7 +93116,7 @@ case OP_IncrVacuum: {        /* jump */
 ** is executed using sqlite3_step() it will either automatically
 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
 ** or it will fail with SQLITE_SCHEMA.
-** 
+**
 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
 ** then only the currently executing statement is expired.
 **
@@ -91140,12 +93136,42 @@ case OP_Expire: {
   break;
 }
 
+/* Opcode: CursorLock P1 * * * *
+**
+** Lock the btree to which cursor P1 is pointing so that the btree cannot be
+** written by an other cursor.
+*/
+case OP_CursorLock: {
+  VdbeCursor *pC;
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+  pC = p->apCsr[pOp->p1];
+  assert( pC!=0 );
+  assert( pC->eCurType==CURTYPE_BTREE );
+  sqlite3BtreeCursorPin(pC->uc.pCursor);
+  break;
+}
+
+/* Opcode: CursorUnlock P1 * * * *
+**
+** Unlock the btree to which cursor P1 is pointing so that it can be
+** written by other cursors.
+*/
+case OP_CursorUnlock: {
+  VdbeCursor *pC;
+  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
+  pC = p->apCsr[pOp->p1];
+  assert( pC!=0 );
+  assert( pC->eCurType==CURTYPE_BTREE );
+  sqlite3BtreeCursorUnpin(pC->uc.pCursor);
+  break;
+}
+
 #ifndef SQLITE_OMIT_SHARED_CACHE
 /* Opcode: TableLock P1 P2 P3 P4 *
 ** Synopsis: iDb=P1 root=P2 write=P3
 **
 ** Obtain a lock on a particular table. This instruction is only used when
-** the shared-cache feature is enabled. 
+** the shared-cache feature is enabled.
 **
 ** P1 is the index of the database in sqlite3.aDb[] of the database
 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
@@ -91159,7 +93185,7 @@ case OP_Expire: {
 case OP_TableLock: {
   u8 isWriteLock = (u8)pOp->p3;
   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
-    int p1 = pOp->p1; 
+    int p1 = pOp->p1;
     assert( p1>=0 && p1<db->nDb );
     assert( DbMaskTest(p->btreeMask, p1) );
     assert( isWriteLock==0 || isWriteLock==1 );
@@ -91179,7 +93205,7 @@ case OP_TableLock: {
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /* Opcode: VBegin * * * P4 *
 **
-** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
+** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
 ** xBegin method for that table.
 **
 ** Also, whether or not P4 is set, check that this is not being called from
@@ -91199,7 +93225,7 @@ case OP_VBegin: {
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /* Opcode: VCreate P1 P2 * * *
 **
-** P2 is a register that holds the name of a virtual table in database 
+** P2 is a register that holds the name of a virtual table in database
 ** P1. Call the xCreate method for that table.
 */
 case OP_VCreate: {
@@ -91384,7 +93410,7 @@ case OP_VColumn: {
   assert( pModule->xColumn );
   memset(&sContext, 0, sizeof(sContext));
   sContext.pOut = pDest;
-  testcase( (pOp->p5 & OPFLAG_NOCHNG)==0 && pOp->p5!=0 );
+  assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
   if( pOp->p5 & OPFLAG_NOCHNG ){
     sqlite3VdbeMemSetNull(pDest);
     pDest->flags = MEM_Null|MEM_Zero;
@@ -91435,7 +93461,7 @@ case OP_VNext: {   /* jump */
 
   /* Invoke the xNext() method of the module. There is no way for the
   ** underlying implementation to return an error if one occurs during
-  ** xNext(). Instead, if an error occurs, true is returned (indicating that 
+  ** xNext(). Instead, if an error occurs, true is returned (indicating that
   ** data is available) and the error code returned when xColumn or
   ** some other method is next invoked on the save virtual table cursor.
   */
@@ -91463,7 +93489,7 @@ case OP_VRename: {
   sqlite3_vtab *pVtab;
   Mem *pName;
   int isLegacy;
-  
+
   isLegacy = (db->flags & SQLITE_LegacyAlter);
   db->flags |= SQLITE_LegacyAlter;
   pVtab = pOp->p4.pVtab->pVtab;
@@ -91493,23 +93519,23 @@ case OP_VRename: {
 **
 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
 ** This opcode invokes the corresponding xUpdate method. P2 values
-** are contiguous memory cells starting at P3 to pass to the xUpdate 
-** invocation. The value in register (P3+P2-1) corresponds to the 
+** are contiguous memory cells starting at P3 to pass to the xUpdate
+** invocation. The value in register (P3+P2-1) corresponds to the
 ** p2th element of the argv array passed to xUpdate.
 **
 ** The xUpdate method will do a DELETE or an INSERT or both.
 ** The argv[0] element (which corresponds to memory cell P3)
-** is the rowid of a row to delete.  If argv[0] is NULL then no 
-** deletion occurs.  The argv[1] element is the rowid of the new 
-** row.  This can be NULL to have the virtual table select the new 
-** rowid for itself.  The subsequent elements in the array are 
+** is the rowid of a row to delete.  If argv[0] is NULL then no
+** deletion occurs.  The argv[1] element is the rowid of the new
+** row.  This can be NULL to have the virtual table select the new
+** rowid for itself.  The subsequent elements in the array are
 ** the values of columns in the new row.
 **
 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
 ** a row to delete.
 **
 ** P1 is a boolean flag. If it is set to true and the xUpdate call
-** is successful, then the value returned by sqlite3_last_insert_rowid() 
+** is successful, then the value returned by sqlite3_last_insert_rowid()
 ** is set to the value of the rowid for the row just inserted.
 **
 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
@@ -91524,7 +93550,7 @@ case OP_VUpdate: {
   Mem **apArg;
   Mem *pX;
 
-  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
+  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
   );
   assert( p->readOnly==0 );
@@ -91609,72 +93635,52 @@ case OP_MaxPgcnt: {            /* out2 */
 }
 #endif
 
-/* Opcode: Function0 P1 P2 P3 P4 P5
-** Synopsis: r[P3]=func(r[P2@P5])
+/* Opcode: Function P1 P2 P3 P4 *
+** Synopsis: r[P3]=func(r[P2@NP])
 **
-** Invoke a user function (P4 is a pointer to a FuncDef object that
-** defines the function) with P5 arguments taken from register P2 and
-** successors.  The result of the function is stored in register P3.
-** Register P3 must not be one of the function inputs.
+** Invoke a user function (P4 is a pointer to an sqlite3_context object that
+** contains a pointer to the function to be run) with arguments taken
+** from register P2 and successors.  The number of arguments is in
+** the sqlite3_context object that P4 points to.
+** The result of the function is stored
+** in register P3.  Register P3 must not be one of the function inputs.
 **
-** P1 is a 32-bit bitmask indicating whether or not each argument to the 
+** P1 is a 32-bit bitmask indicating whether or not each argument to the
 ** function was determined to be constant at compile time. If the first
 ** argument was constant then bit 0 of P1 is set. This is used to determine
 ** whether meta data associated with a user function argument using the
 ** sqlite3_set_auxdata() API may be safely retained until the next
 ** invocation of this opcode.
 **
-** See also: Function, AggStep, AggFinal
+** See also: AggStep, AggFinal, PureFunc
 */
-/* Opcode: Function P1 P2 P3 P4 P5
-** Synopsis: r[P3]=func(r[P2@P5])
+/* Opcode: PureFunc P1 P2 P3 P4 *
+** Synopsis: r[P3]=func(r[P2@NP])
 **
 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
-** contains a pointer to the function to be run) with P5 arguments taken
-** from register P2 and successors.  The result of the function is stored
+** contains a pointer to the function to be run) with arguments taken
+** from register P2 and successors.  The number of arguments is in
+** the sqlite3_context object that P4 points to.
+** The result of the function is stored
 ** in register P3.  Register P3 must not be one of the function inputs.
 **
-** P1 is a 32-bit bitmask indicating whether or not each argument to the 
+** P1 is a 32-bit bitmask indicating whether or not each argument to the
 ** function was determined to be constant at compile time. If the first
 ** argument was constant then bit 0 of P1 is set. This is used to determine
 ** whether meta data associated with a user function argument using the
 ** sqlite3_set_auxdata() API may be safely retained until the next
 ** invocation of this opcode.
 **
-** SQL functions are initially coded as OP_Function0 with P4 pointing
-** to a FuncDef object.  But on first evaluation, the P4 operand is
-** automatically converted into an sqlite3_context object and the operation
-** changed to this OP_Function opcode.  In this way, the initialization of
-** the sqlite3_context object occurs only once, rather than once for each
-** evaluation of the function.
+** This opcode works exactly like OP_Function.  The only difference is in
+** its name.  This opcode is used in places where the function must be
+** purely non-deterministic.  Some built-in date/time functions can be
+** either determinitic of non-deterministic, depending on their arguments.
+** When those function are used in a non-deterministic way, they will check
+** to see if they were called using OP_PureFunc instead of OP_Function, and
+** if they were, they throw an error.
 **
-** See also: Function0, AggStep, AggFinal
+** See also: AggStep, AggFinal, Function
 */
-case OP_PureFunc0:              /* group */
-case OP_Function0: {            /* group */
-  int n;
-  sqlite3_context *pCtx;
-
-  assert( pOp->p4type==P4_FUNCDEF );
-  n = pOp->p5;
-  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
-  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
-  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
-  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
-  if( pCtx==0 ) goto no_mem;
-  pCtx->pOut = 0;
-  pCtx->pFunc = pOp->p4.pFunc;
-  pCtx->iOp = (int)(pOp - aOp);
-  pCtx->pVdbe = p;
-  pCtx->isError = 0;
-  pCtx->argc = n;
-  pOp->p4type = P4_FUNCCTX;
-  pOp->p4.pCtx = pCtx;
-  assert( OP_PureFunc == OP_PureFunc0+2 );
-  assert( OP_Function == OP_Function0+2 );
-  pOp->opcode += 2;
-  /* Fall through into OP_Function */
-}
 case OP_PureFunc:              /* group */
 case OP_Function: {            /* group */
   int i;
@@ -91689,9 +93695,11 @@ case OP_Function: {            /* group */
   ** reinitializes the relavant parts of the sqlite3_context object */
   pOut = &aMem[pOp->p3];
   if( pCtx->pOut != pOut ){
+    pCtx->pVdbe = p;
     pCtx->pOut = pOut;
     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
   }
+  assert( pCtx->pVdbe==p );
 
   memAboutToChange(p, pOut);
 #ifdef SQLITE_DEBUG
@@ -91779,18 +93787,17 @@ case OP_Init: {          /* jump */
   ){
 #ifndef SQLITE_OMIT_DEPRECATED
     if( db->mTrace & SQLITE_TRACE_LEGACY ){
-      void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
       char *z = sqlite3VdbeExpandSql(p, zTrace);
-      x(db->pTraceArg, z);
+      db->trace.xLegacy(db->pTraceArg, z);
       sqlite3_free(z);
     }else
 #endif
     if( db->nVdbeExec>1 ){
       char *z = sqlite3MPrintf(db, "-- %s", zTrace);
-      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
+      (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
       sqlite3DbFree(db, z);
     }else{
-      (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
+      (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
     }
   }
 #ifdef SQLITE_USE_FCNTL_TRACE
@@ -91863,6 +93870,55 @@ case OP_Abortable: {
 }
 #endif
 
+#ifdef SQLITE_DEBUG
+/* Opcode:  ReleaseReg   P1 P2 P3 * P5
+** Synopsis: release r[P1@P2] mask P3
+**
+** Release registers from service.  Any content that was in the
+** the registers is unreliable after this opcode completes.
+**
+** The registers released will be the P2 registers starting at P1,
+** except if bit ii of P3 set, then do not release register P1+ii.
+** In other words, P3 is a mask of registers to preserve.
+**
+** Releasing a register clears the Mem.pScopyFrom pointer.  That means
+** that if the content of the released register was set using OP_SCopy,
+** a change to the value of the source register for the OP_SCopy will no longer
+** generate an assertion fault in sqlite3VdbeMemAboutToChange().
+**
+** If P5 is set, then all released registers have their type set
+** to MEM_Undefined so that any subsequent attempt to read the released
+** register (before it is reinitialized) will generate an assertion fault.
+**
+** P5 ought to be set on every call to this opcode.
+** However, there are places in the code generator will release registers
+** before their are used, under the (valid) assumption that the registers
+** will not be reallocated for some other purpose before they are used and
+** hence are safe to release.
+**
+** This opcode is only available in testing and debugging builds.  It is
+** not generated for release builds.  The purpose of this opcode is to help
+** validate the generated bytecode.  This opcode does not actually contribute
+** to computing an answer.
+*/
+case OP_ReleaseReg: {
+  Mem *pMem;
+  int i;
+  u32 constMask;
+  assert( pOp->p1>0 );
+  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
+  pMem = &aMem[pOp->p1];
+  constMask = pOp->p3;
+  for(i=0; i<pOp->p2; i++, pMem++){
+    if( i>=32 || (constMask & MASKBIT32(i))==0 ){
+      pMem->pScopyFrom = 0;
+      if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
+    }
+  }
+  break;
+}
+#endif
+
 /* Opcode: Noop * * * * *
 **
 ** Do nothing.  This instruction is often useful as a jump
@@ -91914,6 +93970,12 @@ default: {          /* This is really OP_Noop, OP_Explain */
       if( opProperty & OPFLG_OUT3 ){
         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
       }
+      if( opProperty==0xff ){
+        /* Never happens.  This code exists to avoid a harmless linkage
+        ** warning aboud sqlite3VdbeRegisterDump() being defined but not
+        ** used. */
+        sqlite3VdbeRegisterDump(p);
+      }
     }
 #endif  /* SQLITE_DEBUG */
 #endif  /* NDEBUG */
@@ -91923,7 +93985,11 @@ default: {          /* This is really OP_Noop, OP_Explain */
   ** an error of some kind.
   */
 abort_due_to_error:
-  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
+  if( db->mallocFailed ){
+    rc = SQLITE_NOMEM_BKPT;
+  }else if( rc==SQLITE_IOERR_CORRUPTFS ){
+    rc = SQLITE_CORRUPT_BKPT;
+  }
   assert( rc );
   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
@@ -91931,7 +93997,7 @@ abort_due_to_error:
   p->rc = rc;
   sqlite3SystemError(db, rc);
   testcase( sqlite3GlobalConfig.xLog!=0 );
-  sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
+  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
   sqlite3VdbeHalt(p);
   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
@@ -91948,7 +94014,7 @@ vdbe_return:
   while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
     nProgressLimit += db->nProgressOps;
     if( db->xProgress(db->pProgressArg) ){
-      nProgressLimit = 0xffffffff;
+      nProgressLimit = LARGEST_UINT64;
       rc = SQLITE_INTERRUPT;
       goto abort_due_to_error;
     }
@@ -91956,8 +94022,8 @@ vdbe_return:
 #endif
   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
   sqlite3VdbeLeave(p);
-  assert( rc!=SQLITE_OK || nExtraDelete==0 
-       || sqlite3_strlike("DELETE%",p->zSql,0)!=0 
+  assert( rc!=SQLITE_OK || nExtraDelete==0
+       || sqlite3_strlike("DELETE%",p->zSql,0)!=0
   );
   return rc;
 
@@ -91981,10 +94047,8 @@ no_mem:
   ** flag.
   */
 abort_due_to_interrupt:
-  assert( db->u1.isInterrupted );
-  rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
-  p->rc = rc;
-  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
+  assert( AtomicLoad(&db->u1.isInterrupted) );
+  rc = SQLITE_INTERRUPT;
   goto abort_due_to_error;
 }
 
@@ -92041,7 +94105,7 @@ struct Incrblob {
 ** sqlite3DbFree().
 **
 ** If an error does occur, then the b-tree cursor is closed. All subsequent
-** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
+** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
 ** immediately return SQLITE_ABORT.
 */
 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
@@ -92049,7 +94113,7 @@ static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
   char *zErr = 0;                 /* Error message */
   Vdbe *v = (Vdbe *)p->pStmt;
 
-  /* Set the value of register r[1] in the SQL statement to integer iRow. 
+  /* Set the value of register r[1] in the SQL statement to integer iRow.
   ** This is done directly as a performance optimization
   */
   v->aMem[1].flags = MEM_Int;
@@ -92193,7 +94257,7 @@ SQLITE_API int sqlite3_blob_open(
     }
 
     /* If the value is being opened for writing, check that the
-    ** column is not indexed, and that it is not part of a foreign key. 
+    ** column is not indexed, and that it is not part of a foreign key.
     */
     if( wrFlag ){
       const char *zFault = 0;
@@ -92202,7 +94266,7 @@ SQLITE_API int sqlite3_blob_open(
       if( db->flags&SQLITE_ForeignKeys ){
         /* Check that the column is not part of an FK child key definition. It
         ** is not necessary to check if it is part of a parent key, as parent
-        ** key columns must be indexed. The check below will pick up this 
+        ** key columns must be indexed. The check below will pick up this
         ** case.  */
         FKey *pFKey;
         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
@@ -92236,8 +94300,8 @@ SQLITE_API int sqlite3_blob_open(
     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
     assert( pBlob->pStmt || db->mallocFailed );
     if( pBlob->pStmt ){
-      
-      /* This VDBE program seeks a btree cursor to the identified 
+
+      /* This VDBE program seeks a btree cursor to the identified
       ** db/table/row entry. The reason for using a vdbe program instead
       ** of writing code to use the b-tree layer directly is that the
       ** vdbe program will take advantage of the various transaction,
@@ -92245,11 +94309,11 @@ SQLITE_API int sqlite3_blob_open(
       **
       ** After seeking the cursor, the vdbe executes an OP_ResultRow.
       ** Code external to the Vdbe then "borrows" the b-tree cursor and
-      ** uses it to implement the blob_read(), blob_write() and 
+      ** uses it to implement the blob_read(), blob_write() and
       ** blob_bytes() functions.
       **
       ** The sqlite3_blob_close() function finalizes the vdbe program,
-      ** which closes the b-tree cursor and (possibly) commits the 
+      ** which closes the b-tree cursor and (possibly) commits the
       ** transaction.
       */
       static const int iLn = VDBE_OFFSET_LINENO(2);
@@ -92266,7 +94330,7 @@ SQLITE_API int sqlite3_blob_open(
       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       VdbeOp *aOp;
 
-      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag, 
+      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
                            pTab->pSchema->schema_cookie,
                            pTab->pSchema->iGeneration);
       sqlite3VdbeChangeP5(v, 1);
@@ -92274,7 +94338,7 @@ SQLITE_API int sqlite3_blob_open(
       aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
 
       /* Make sure a mutex is held on the table to be accessed */
-      sqlite3VdbeUsesBtree(v, iDb); 
+      sqlite3VdbeUsesBtree(v, iDb);
 
       if( db->mallocFailed==0 ){
         assert( aOp!=0 );
@@ -92290,17 +94354,17 @@ SQLITE_API int sqlite3_blob_open(
       if( db->mallocFailed==0 ){
 #endif
 
-        /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
+        /* Remove either the OP_OpenWrite or OpenRead. Set the P2
         ** parameter of the other to pTab->tnum.  */
         if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
         aOp[1].p2 = pTab->tnum;
-        aOp[1].p3 = iDb;   
+        aOp[1].p3 = iDb;
 
         /* Configure the number of columns. Configure the cursor to
         ** think that the table has one more column than it really
         ** does. An OP_Column to retrieve this imaginary column will
         ** always return an SQL NULL. This is useful because it means
-        ** we can invoke OP_Column to fill in the vdbe cursors type 
+        ** we can invoke OP_Column to fill in the vdbe cursors type
         ** and offset cache without causing any IO.
         */
         aOp[1].p4type = P4_INT32;
@@ -92313,7 +94377,7 @@ SQLITE_API int sqlite3_blob_open(
         sqlite3VdbeMakeReady(v, &sParse);
       }
     }
-   
+
     pBlob->iCol = iCol;
     pBlob->db = db;
     sqlite3BtreeLeaveAll(db);
@@ -92364,10 +94428,10 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
 ** Perform a read or write operation on a blob
 */
 static int blobReadWrite(
-  sqlite3_blob *pBlob, 
-  void *z, 
-  int n, 
-  int iOffset, 
+  sqlite3_blob *pBlob,
+  void *z,
+  int n,
+  int iOffset,
   int (*xCall)(BtCursor*, u32, u32, void*)
 ){
   int rc;
@@ -92397,14 +94461,14 @@ static int blobReadWrite(
 
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
     if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
-      /* If a pre-update hook is registered and this is a write cursor, 
-      ** invoke it here. 
-      ** 
+      /* If a pre-update hook is registered and this is a write cursor,
+      ** invoke it here.
+      **
       ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
       ** operation should really be an SQLITE_UPDATE. This is probably
-      ** incorrect, but is convenient because at this point the new.* values 
-      ** are not easily obtainable. And for the sessions module, an 
-      ** SQLITE_UPDATE where the PK columns do not change is handled in the 
+      ** incorrect, but is convenient because at this point the new.* values
+      ** are not easily obtainable. And for the sessions module, an
+      ** SQLITE_UPDATE where the PK columns do not change is handled in the
       ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
       ** slightly more efficient). Since you cannot write to a PK column
       ** using the incremental-blob API, this works. For the sessions module
@@ -92464,8 +94528,8 @@ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
 **
 ** If an error occurs, or if the specified row does not exist or does not
 ** contain a blob or text value, then an error code is returned and the
-** database handle error code and message set. If this happens, then all 
-** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
+** database handle error code and message set. If this happens, then all
+** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
 ** immediately return SQLITE_ABORT.
 */
 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
@@ -92559,7 +94623,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 **                                  is like Close() followed by Init() only
 **                                  much faster.
 **
-** The interfaces above must be called in a particular order.  Write() can 
+** The interfaces above must be called in a particular order.  Write() can
 ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
 **
@@ -92567,16 +94631,16 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 **   for each record: Write()
 **   Rewind()
 **     Rowkey()/Compare()
-**   Next() 
+**   Next()
 **   Close()
 **
 ** Algorithm:
 **
-** Records passed to the sorter via calls to Write() are initially held 
+** Records passed to the sorter via calls to Write() are initially held
 ** unsorted in main memory. Assuming the amount of memory used never exceeds
 ** a threshold, when Rewind() is called the set of records is sorted using
 ** an in-memory merge sort. In this case, no temporary files are required
-** and subsequent calls to Rowkey(), Next() and Compare() read records 
+** and subsequent calls to Rowkey(), Next() and Compare() read records
 ** directly from main memory.
 **
 ** If the amount of space used to store records in main memory exceeds the
@@ -92586,10 +94650,10 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 ** of PMAs may be created by merging existing PMAs together - for example
 ** merging two or more level-0 PMAs together creates a level-1 PMA.
 **
-** The threshold for the amount of main memory to use before flushing 
+** The threshold for the amount of main memory to use before flushing
 ** records to a PMA is roughly the same as the limit configured for the
-** page-cache of the main database. Specifically, the threshold is set to 
-** the value returned by "PRAGMA main.page_size" multipled by 
+** page-cache of the main database. Specifically, the threshold is set to
+** the value returned by "PRAGMA main.page_size" multipled by
 ** that returned by "PRAGMA main.cache_size", in bytes.
 **
 ** If the sorter is running in single-threaded mode, then all PMAs generated
@@ -92606,7 +94670,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 ** than zero, and (b) worker threads have been enabled at runtime by calling
 ** "PRAGMA threads=N" with some value of N greater than 0.
 **
-** When Rewind() is called, any data remaining in memory is flushed to a 
+** When Rewind() is called, any data remaining in memory is flushed to a
 ** final PMA. So at this point the data is stored in some number of sorted
 ** PMAs within temporary files on disk.
 **
@@ -92618,16 +94682,16 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 **
 ** Or, if running in multi-threaded mode, then a background thread is
 ** launched to merge the existing PMAs. Once the background thread has
-** merged T bytes of data into a single sorted PMA, the main thread 
+** merged T bytes of data into a single sorted PMA, the main thread
 ** begins reading keys from that PMA while the background thread proceeds
 ** with merging the next T bytes of data. And so on.
 **
-** Parameter T is set to half the value of the memory threshold used 
+** Parameter T is set to half the value of the memory threshold used
 ** by Write() above to determine when to create a new PMA.
 **
-** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when 
-** Rewind() is called, then a hierarchy of incremental-merges is used. 
-** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on 
+** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
+** Rewind() is called, then a hierarchy of incremental-merges is used.
+** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
 ** disk are merged together. Then T bytes of data from the second set, and
 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
 ** PMAs at a time. This done is to improve locality.
@@ -92642,7 +94706,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
 /* #include "sqliteInt.h" */
 /* #include "vdbeInt.h" */
 
-/* 
+/*
 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
 ** messages to stderr that may be helpful in understanding the performance
 ** characteristics of the sorter in multi-threaded mode.
@@ -92671,7 +94735,7 @@ typedef struct SorterList SorterList;       /* In-memory list of records */
 typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
 
 /*
-** A container for a temp file handle and the current amount of data 
+** A container for a temp file handle and the current amount of data
 ** stored in the file.
 */
 struct SorterFile {
@@ -92711,17 +94775,17 @@ struct SorterList {
 ** the MergeEngine.nTree variable.
 **
 ** The final (N/2) elements of aTree[] contain the results of comparing
-** pairs of PMA keys together. Element i contains the result of 
+** pairs of PMA keys together. Element i contains the result of
 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
-** aTree element is set to the index of it. 
+** aTree element is set to the index of it.
 **
 ** For the purposes of this comparison, EOF is considered greater than any
 ** other key value. If the keys are equal (only possible with two EOF
 ** values), it doesn't matter which index is stored.
 **
-** The (N/4) elements of aTree[] that precede the final (N/2) described 
+** The (N/4) elements of aTree[] that precede the final (N/2) described
 ** above contains the index of the smallest of each block of 4 PmaReaders
-** And so on. So that aTree[1] contains the index of the PmaReader that 
+** And so on. So that aTree[1] contains the index of the PmaReader that
 ** currently points to the smallest key value. aTree[0] is unused.
 **
 ** Example:
@@ -92737,7 +94801,7 @@ struct SorterList {
 **
 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
 **
-** The current element is "Apple" (the value of the key indicated by 
+** The current element is "Apple" (the value of the key indicated by
 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
 ** be advanced to the next key in its segment. Say the next key is
 ** "Eggplant":
@@ -92778,8 +94842,8 @@ struct MergeEngine {
 ** each thread requries its own UnpackedRecord object to unpack records in
 ** as part of comparison operations.
 **
-** Before a background thread is launched, variable bDone is set to 0. Then, 
-** right before it exits, the thread itself sets bDone to 1. This is used for 
+** Before a background thread is launched, variable bDone is set to 0. Then,
+** right before it exits, the thread itself sets bDone to 1. This is used for
 ** two purposes:
 **
 **   1. When flushing the contents of memory to a level-0 PMA on disk, to
@@ -92810,7 +94874,7 @@ struct SortSubtask {
 
 
 /*
-** Main sorter structure. A single instance of this is allocated for each 
+** Main sorter structure. A single instance of this is allocated for each
 ** sorter cursor created by the VDBE.
 **
 ** mxKeysize:
@@ -92866,21 +94930,21 @@ struct PmaReader {
 };
 
 /*
-** Normally, a PmaReader object iterates through an existing PMA stored 
+** Normally, a PmaReader object iterates through an existing PMA stored
 ** within a temp file. However, if the PmaReader.pIncr variable points to
 ** an object of the following type, it may be used to iterate/merge through
 ** multiple PMAs simultaneously.
 **
-** There are two types of IncrMerger object - single (bUseThread==0) and 
-** multi-threaded (bUseThread==1). 
+** There are two types of IncrMerger object - single (bUseThread==0) and
+** multi-threaded (bUseThread==1).
 **
-** A multi-threaded IncrMerger object uses two temporary files - aFile[0] 
-** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in 
-** size. When the IncrMerger is initialized, it reads enough data from 
-** pMerger to populate aFile[0]. It then sets variables within the 
-** corresponding PmaReader object to read from that file and kicks off 
-** a background thread to populate aFile[1] with the next mxSz bytes of 
-** sorted record data from pMerger. 
+** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
+** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
+** size. When the IncrMerger is initialized, it reads enough data from
+** pMerger to populate aFile[0]. It then sets variables within the
+** corresponding PmaReader object to read from that file and kicks off
+** a background thread to populate aFile[1] with the next mxSz bytes of
+** sorted record data from pMerger.
 **
 ** When the PmaReader reaches the end of aFile[0], it blocks until the
 ** background thread has finished populating aFile[1]. It then exchanges
@@ -92891,7 +94955,7 @@ struct PmaReader {
 **
 ** A single-threaded IncrMerger does not open any temporary files of its
 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
-** at offset iStartOff of file pTask->file2. And instead of using a 
+** at offset iStartOff of file pTask->file2. And instead of using a
 ** background thread to prepare data for the PmaReader, with a single
 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
 ** keys from pMerger by the calling thread whenever the PmaReader runs out
@@ -93003,7 +95067,7 @@ static int vdbePmaReadBlob(
 
   assert( p->aBuffer );
 
-  /* If there is no more data to be read from the buffer, read the next 
+  /* If there is no more data to be read from the buffer, read the next
   ** p->nBuffer bytes of data from the file into it. Or, if there are less
   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
   iBuf = p->iReadOff % p->nBuffer;
@@ -93024,11 +95088,11 @@ static int vdbePmaReadBlob(
     assert( rc!=SQLITE_IOERR_SHORT_READ );
     if( rc!=SQLITE_OK ) return rc;
   }
-  nAvail = p->nBuffer - iBuf; 
+  nAvail = p->nBuffer - iBuf;
 
   if( nByte<=nAvail ){
     /* The requested data is available in the in-memory buffer. In this
-    ** case there is no need to make a copy of the data, just return a 
+    ** case there is no need to make a copy of the data, just return a
     ** pointer into the buffer to the caller.  */
     *ppOut = &p->aBuffer[iBuf];
     p->iReadOff += nByte;
@@ -93107,7 +95171,7 @@ static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
 
 /*
 ** Attempt to memory map file pFile. If successful, set *pp to point to the
-** new mapping and return SQLITE_OK. If the mapping is not attempted 
+** new mapping and return SQLITE_OK. If the mapping is not attempted
 ** (because the file is too large or the VFS layer is configured not to use
 ** mmap), return SQLITE_OK and set *pp to NULL.
 **
@@ -93128,7 +95192,7 @@ static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
 
 /*
 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
-** that file) and seek it to offset iOff within the file.  Return SQLITE_OK 
+** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
 ** if successful, or an SQLite error code if an error occurs.
 */
 static int vdbePmaReaderSeek(
@@ -93218,11 +95282,11 @@ static int vdbePmaReaderNext(PmaReader *pReadr){
 
 /*
 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
-** starting at offset iStart and ending at offset iEof-1. This function 
-** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 
+** starting at offset iStart and ending at offset iEof-1. This function
+** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
 ** PMA is empty).
 **
-** If the pnByte parameter is NULL, then it is assumed that the file 
+** If the pnByte parameter is NULL, then it is assumed that the file
 ** contains a single PMA, and that that PMA omits the initial length varint.
 */
 static int vdbePmaReaderInit(
@@ -93255,7 +95319,7 @@ static int vdbePmaReaderInit(
 
 /*
 ** A version of vdbeSorterCompare() that assumes that it has already been
-** determined that the first field of key1 is equal to the first field of 
+** determined that the first field of key1 is equal to the first field of
 ** key2.
 */
 static int vdbeSorterCompareTail(
@@ -93273,7 +95337,7 @@ static int vdbeSorterCompareTail(
 }
 
 /*
-** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
+** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
 ** used by the comparison. Return the result of the comparison.
 **
@@ -93319,8 +95383,8 @@ static int vdbeSorterCompareText(
   int n2;
   int res;
 
-  getVarint32(&p1[1], n1);
-  getVarint32(&p2[1], n2);
+  getVarint32NR(&p1[1], n1);
+  getVarint32NR(&p2[1], n2);
   res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
   if( res==0 ){
     res = n1 - n2;
@@ -93419,7 +95483,7 @@ static int vdbeSorterCompareInt(
 ** is non-zero and the sorter is able to guarantee a stable sort, nField
 ** is used instead. This is used when sorting records for a CREATE INDEX
 ** statement. In this case, keys are always delivered to the sorter in
-** order of the primary key, which happens to be make up the final part 
+** order of the primary key, which happens to be make up the final part
 ** of the records being sorted. So if the sort is stable, there is never
 ** any reason to compare PK fields and they can be ignored for a small
 ** performance boost.
@@ -93474,13 +95538,16 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(
   if( pSorter==0 ){
     rc = SQLITE_NOMEM_BKPT;
   }else{
+    Btree *pBt = db->aDb[0].pBt;
     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
     pKeyInfo->db = 0;
     if( nField && nWorker==0 ){
       pKeyInfo->nKeyField = nField;
     }
-    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
+    sqlite3BtreeEnter(pBt);
+    pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);
+    sqlite3BtreeLeave(pBt);
     pSorter->nTask = nWorker + 1;
     pSorter->iPrev = (u8)(nWorker - 1);
     pSorter->bUseThreads = (pSorter->nTask>1);
@@ -93516,7 +95583,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterInit(
       }
     }
 
-    if( pKeyInfo->nAllField<13 
+    if( pKeyInfo->nAllField<13
      && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
      && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
     ){
@@ -93541,7 +95608,7 @@ static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
 }
 
 /*
-** Free all resources owned by the object indicated by argument pTask. All 
+** Free all resources owned by the object indicated by argument pTask. All
 ** fields of *pTask are zeroed before returning.
 */
 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
@@ -93640,7 +95707,7 @@ static int vdbeSorterCreateThread(
 }
 
 /*
-** Join all outstanding threads launched by SorterWrite() to create 
+** Join all outstanding threads launched by SorterWrite() to create
 ** level-0 PMAs.
 */
 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
@@ -93649,10 +95716,10 @@ static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
 
   /* This function is always called by the main user thread.
   **
-  ** If this function is being called after SorterRewind() has been called, 
+  ** If this function is being called after SorterRewind() has been called,
   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
   ** is currently attempt to join one of the other threads. To avoid a race
-  ** condition where this thread also attempts to join the same object, join 
+  ** condition where this thread also attempts to join the same object, join
   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
   for(i=pSorter->nTask-1; i>=0; i--){
     SortSubtask *pTask = &pSorter->aTask[i];
@@ -93824,8 +95891,8 @@ static int vdbeSorterOpenTempFile(
 }
 
 /*
-** If it has not already been allocated, allocate the UnpackedRecord 
-** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 
+** If it has not already been allocated, allocate the UnpackedRecord
+** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
 ** if no allocation was required), or SQLITE_NOMEM otherwise.
 */
 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
@@ -93888,14 +95955,14 @@ static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
   if( p->typeMask==SORTER_TYPE_INTEGER ){
     return vdbeSorterCompareInt;
   }else if( p->typeMask==SORTER_TYPE_TEXT ){
-    return vdbeSorterCompareText; 
+    return vdbeSorterCompareText;
   }
   return vdbeSorterCompare;
 }
 
 /*
-** Sort the linked list of records headed at pTask->pList. Return 
-** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 
+** Sort the linked list of records headed at pTask->pList. Return
+** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
 ** an error occurs.
 */
 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
@@ -93940,8 +96007,8 @@ static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
   }
   pList->pList = p;
 
-  assert( pTask->pUnpacked->errCode==SQLITE_OK 
-       || pTask->pUnpacked->errCode==SQLITE_NOMEM 
+  assert( pTask->pUnpacked->errCode==SQLITE_OK
+       || pTask->pUnpacked->errCode==SQLITE_NOMEM
   );
   return pTask->pUnpacked->errCode;
 }
@@ -93982,8 +96049,8 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
     p->iBufEnd += nCopy;
     if( p->iBufEnd==p->nBuffer ){
-      p->eFWErr = sqlite3OsWrite(p->pFd, 
-          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
+      p->eFWErr = sqlite3OsWrite(p->pFd,
+          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
           p->iWriteOff + p->iBufStart
       );
       p->iBufStart = p->iBufEnd = 0;
@@ -93998,7 +96065,7 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
 /*
 ** Flush any buffered data to disk and clean up the PMA-writer object.
 ** The results of using the PMA-writer after this call are undefined.
-** Return SQLITE_OK if flushing the buffered data succeeds or is not 
+** Return SQLITE_OK if flushing the buffered data succeeds or is not
 ** required. Otherwise, return an SQLite error code.
 **
 ** Before returning, set *piEof to the offset immediately following the
@@ -94007,8 +96074,8 @@ static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
   int rc;
   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
-    p->eFWErr = sqlite3OsWrite(p->pFd, 
-        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
+    p->eFWErr = sqlite3OsWrite(p->pFd,
+        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
         p->iWriteOff + p->iBufStart
     );
   }
@@ -94020,11 +96087,11 @@ static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
 }
 
 /*
-** Write value iVal encoded as a varint to the PMA. Return 
+** Write value iVal encoded as a varint to the PMA. Return
 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
 */
 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
-  int nByte; 
+  int nByte;
   u8 aByte[10];
   nByte = sqlite3PutVarint(aByte, iVal);
   vdbePmaWriteBlob(p, aByte, nByte);
@@ -94032,7 +96099,7 @@ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
 
 /*
 ** Write the current contents of in-memory linked-list pList to a level-0
-** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 
+** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
 ** successful, or an SQLite error code otherwise.
 **
 ** The format of a PMA is:
@@ -94040,8 +96107,8 @@ static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
 **     * A varint. This varint contains the total number of bytes of content
 **       in the PMA (not including the varint itself).
 **
-**     * One or more records packed end-to-end in order of ascending keys. 
-**       Each record consists of a varint followed by a blob of data (the 
+**     * One or more records packed end-to-end in order of ascending keys.
+**       Each record consists of a varint followed by a blob of data (the
 **       key). The varint is the number of bytes in the blob of data.
 */
 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
@@ -94050,7 +96117,7 @@ static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
   PmaWriter writer;               /* Object used to write to the file */
 
 #ifdef SQLITE_DEBUG
-  /* Set iSz to the expected size of file pTask->file after writing the PMA. 
+  /* Set iSz to the expected size of file pTask->file after writing the PMA.
   ** This is used by an assert() statement at the end of this function.  */
   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
 #endif
@@ -94203,7 +96270,7 @@ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
   int nWorker = (pSorter->nTask-1);
 
-  /* Set the flag to indicate that at least one PMA has been written. 
+  /* Set the flag to indicate that at least one PMA has been written.
   ** Or will be, anyhow.  */
   pSorter->bUsePMA = 1;
 
@@ -94213,7 +96280,7 @@ static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
   ** the background thread from a sub-tasks previous turn is still running,
   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
-  ** sub-tasks are prefered as they use background threads - the final 
+  ** sub-tasks are prefered as they use background threads - the final
   ** sub-task uses the main thread. */
   for(i=0; i<nWorker; i++){
     int iTest = (pSorter->iPrev + i + 1) % nWorker;
@@ -94277,7 +96344,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
 
   assert( pCsr->eCurType==CURTYPE_SORTER );
   pSorter = pCsr->uc.pSorter;
-  getVarint32((const u8*)&pVal->z[1], t);
+  getVarint32NR((const u8*)&pVal->z[1], t);
   if( t>0 && t<10 && t!=7 ){
     pSorter->typeMask &= SORTER_TYPE_INTEGER;
   }else if( t>10 && (t & 0x01) ){
@@ -94294,14 +96361,14 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
   ** If using the single large allocation mode (pSorter->aMemory!=0), then
   ** flush the contents of memory to a new PMA if (a) at least one value is
   ** already in memory and (b) the new value will not fit in memory.
-  ** 
+  **
   ** Or, if using separate allocations for each record, flush the contents
   ** of memory to a PMA if either of the following are true:
   **
-  **   * The total memory allocated for the in-memory list is greater 
+  **   * The total memory allocated for the in-memory list is greater
   **     than (page-size * cache-size), or
   **
-  **   * The total memory allocated for the in-memory list is greater 
+  **   * The total memory allocated for the in-memory list is greater
   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
   */
   nReq = pVal->n + sizeof(SorterRecord);
@@ -94440,11 +96507,11 @@ static int vdbeIncrBgPopulate(IncrMerger *pIncr){
 ** aFile[0] such that the PmaReader should start rereading it from the
 ** beginning.
 **
-** For single-threaded objects, this is accomplished by literally reading 
-** keys from pIncr->pMerger and repopulating aFile[0]. 
+** For single-threaded objects, this is accomplished by literally reading
+** keys from pIncr->pMerger and repopulating aFile[0].
 **
-** For multi-threaded objects, all that is required is to wait until the 
-** background thread is finished (if it is not already) and then swap 
+** For multi-threaded objects, all that is required is to wait until the
+** background thread is finished (if it is not already) and then swap
 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
 ** been exhausted, this function also launches a new background thread
 ** to populate the new aFile[1].
@@ -94584,7 +96651,7 @@ static void vdbeMergeEngineCompare(
 #define INCRINIT_TASK   1
 #define INCRINIT_ROOT   2
 
-/* 
+/*
 ** Forward reference required as the vdbeIncrMergeInit() and
 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
 ** building a merge tree.
@@ -94593,7 +96660,7 @@ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
 
 /*
 ** Initialize the MergeEngine object passed as the second argument. Once this
-** function returns, the first key of merged data may be read from the 
+** function returns, the first key of merged data may be read from the
 ** MergeEngine object in the usual fashion.
 **
 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
@@ -94603,8 +96670,8 @@ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
 ** its first key.
 **
-** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 
-** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 
+** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
+** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
 ** to pMerger.
 **
 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
@@ -94659,19 +96726,19 @@ static int vdbeMergeEngineInit(
 ** object at (pReadr->pIncr).
 **
 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
-** in the sub-tree headed by pReadr are also initialized. Data is then 
-** loaded into the buffers belonging to pReadr and it is set to point to 
+** in the sub-tree headed by pReadr are also initialized. Data is then
+** loaded into the buffers belonging to pReadr and it is set to point to
 ** the first key in its range.
 **
 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
 ** to be a multi-threaded PmaReader and this function is being called in a
-** background thread. In this case all PmaReaders in the sub-tree are 
+** background thread. In this case all PmaReaders in the sub-tree are
 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
 ** pReadr is populated. However, pReadr itself is not set up to point
 ** to its first key. A call to vdbePmaReaderNext() is still required to do
-** that. 
+** that.
 **
-** The reason this function does not call vdbePmaReaderNext() immediately 
+** The reason this function does not call vdbePmaReaderNext() immediately
 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
 ** this entire function is being run by thread (pTask->thread), that will
@@ -94727,12 +96794,12 @@ static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
   if( rc==SQLITE_OK && pIncr->bUseThread ){
     /* Use the current thread to populate aFile[1], even though this
     ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
-    ** then this function is already running in background thread 
-    ** pIncr->pTask->thread. 
+    ** then this function is already running in background thread
+    ** pIncr->pTask->thread.
     **
-    ** If this is the INCRINIT_ROOT object, then it is running in the 
+    ** If this is the INCRINIT_ROOT object, then it is running in the
     ** main VDBE thread. But that is Ok, as that thread cannot return
-    ** control to the VDBE or proceed with anything useful until the 
+    ** control to the VDBE or proceed with anything useful until the
     ** first results are ready from this merger object anyway.
     */
     assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
@@ -94749,7 +96816,7 @@ static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
 
 #if SQLITE_MAX_WORKER_THREADS>0
 /*
-** The main routine for vdbePmaReaderIncrMergeInit() operations run in 
+** The main routine for vdbePmaReaderIncrMergeInit() operations run in
 ** background threads.
 */
 static void *vdbePmaReaderBgIncrInit(void *pCtx){
@@ -94767,8 +96834,8 @@ static void *vdbePmaReaderBgIncrInit(void *pCtx){
 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
 ** this routine to initialize the incremental merge.
-** 
-** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), 
+**
+** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
 ** Or, if the IncrMerger is single threaded, the same function is called
 ** using the current thread.
@@ -94798,7 +96865,7 @@ static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
 ** to NULL and return an SQLite error code.
 **
 ** When this function is called, *piOffset is set to the offset of the
-** first PMA to read from pTask->file. Assuming no error occurs, it is 
+** first PMA to read from pTask->file. Assuming no error occurs, it is
 ** set to the offset immediately following the last byte of the last
 ** PMA before returning. If an error does occur, then the final value of
 ** *piOffset is undefined.
@@ -94908,12 +96975,12 @@ static int vdbeSorterAddToTree(
 /*
 ** This function is called as part of a SorterRewind() operation on a sorter
 ** that has already written two or more level-0 PMAs to one or more temp
-** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 
+** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
 ** can be used to incrementally merge all PMAs on disk.
 **
 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
 ** MergeEngine object at the root of the tree before returning. Or, if an
-** error occurs, an SQLite error code is returned and the final value 
+** error occurs, an SQLite error code is returned and the final value
 ** of *ppOut is undefined.
 */
 static int vdbeSorterMergeTreeBuild(
@@ -94925,8 +96992,8 @@ static int vdbeSorterMergeTreeBuild(
   int iTask;
 
 #if SQLITE_MAX_WORKER_THREADS>0
-  /* If the sorter uses more than one task, then create the top-level 
-  ** MergeEngine here. This MergeEngine will read data from exactly 
+  /* If the sorter uses more than one task, then create the top-level
+  ** MergeEngine here. This MergeEngine will read data from exactly
   ** one PmaReader per sub-task.  */
   assert( pSorter->bUseThreads || pSorter->nTask==1 );
   if( pSorter->nTask>1 ){
@@ -95035,7 +97102,7 @@ static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
           }
           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
             /* Check that:
-            **   
+            **
             **   a) The incremental merge object is configured to use the
             **      right task, and
             **   b) If it is using task (nTask-1), it is configured to run
@@ -95098,7 +97165,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
     return rc;
   }
 
-  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 
+  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
   ** function flushes the contents of memory to disk, it immediately always
   ** creates a new list consisting of a single key immediately afterwards.
   ** So the list is never empty at this point.  */
@@ -95110,7 +97177,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
 
   vdbeSorterRewindDebug("rewind");
 
-  /* Assuming no errors have occurred, set up a merger structure to 
+  /* Assuming no errors have occurred, set up a merger structure to
   ** incrementally read and merge all remaining PMAs.  */
   assert( pSorter->pReader==0 );
   if( rc==SQLITE_OK ){
@@ -95164,7 +97231,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
 }
 
 /*
-** Return a pointer to a buffer owned by the sorter that contains the 
+** Return a pointer to a buffer owned by the sorter that contains the
 ** current key.
 */
 static void *vdbeSorterRowkey(
@@ -95264,6 +97331,433 @@ SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
 }
 
 /************** End of vdbesort.c ********************************************/
+/************** Begin file vdbevtab.c ****************************************/
+/*
+** 2020-03-23
+**
+** The author disclaims copyright to this source code.  In place of
+** a legal notice, here is a blessing:
+**
+**    May you do good and not evil.
+**    May you find forgiveness for yourself and forgive others.
+**    May you share freely, never taking more than you give.
+**
+*************************************************************************
+**
+** This file implements virtual-tables for examining the bytecode content
+** of a prepared statement.
+*/
+/* #include "sqliteInt.h" */
+#if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
+/* #include "vdbeInt.h" */
+
+/* An instance of the bytecode() table-valued function.
+*/
+typedef struct bytecodevtab bytecodevtab;
+struct bytecodevtab {
+  sqlite3_vtab base;     /* Base class - must be first */
+  sqlite3 *db;           /* Database connection */
+  int bTablesUsed;       /* 2 for tables_used().  0 for bytecode(). */
+};
+
+/* A cursor for scanning through the bytecode
+*/
+typedef struct bytecodevtab_cursor bytecodevtab_cursor;
+struct bytecodevtab_cursor {
+  sqlite3_vtab_cursor base;  /* Base class - must be first */
+  sqlite3_stmt *pStmt;       /* The statement whose bytecode is displayed */
+  int iRowid;                /* The rowid of the output table */
+  int iAddr;                 /* Address */
+  int needFinalize;          /* Cursors owns pStmt and must finalize it */
+  int showSubprograms;       /* Provide a listing of subprograms */
+  Op *aOp;                   /* Operand array */
+  char *zP4;                 /* Rendered P4 value */
+  const char *zType;         /* tables_used.type */
+  const char *zSchema;       /* tables_used.schema */
+  const char *zName;         /* tables_used.name */
+  Mem sub;                   /* Subprograms */
+};
+
+/*
+** Create a new bytecode() table-valued function.
+*/
+static int bytecodevtabConnect(
+  sqlite3 *db,
+  void *pAux,
+  int argc, const char *const*argv,
+  sqlite3_vtab **ppVtab,
+  char **pzErr
+){
+  bytecodevtab *pNew;
+  int rc;
+  int isTabUsed = pAux!=0;
+  const char *azSchema[2] = {
+    /* bytecode() schema */
+    "CREATE TABLE x("
+      "addr INT,"
+      "opcode TEXT,"
+      "p1 INT,"
+      "p2 INT,"
+      "p3 INT,"
+      "p4 TEXT,"
+      "p5 INT,"
+      "comment TEXT,"
+      "subprog TEXT,"
+      "stmt HIDDEN"
+    ");",
+
+    /* Tables_used() schema */
+    "CREATE TABLE x("
+      "type TEXT,"
+      "schema TEXT,"
+      "name TEXT,"
+      "wr INT,"
+      "subprog TEXT,"
+      "stmt HIDDEN"
+   ");"
+  };
+
+  rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]);
+  if( rc==SQLITE_OK ){
+    pNew = sqlite3_malloc( sizeof(*pNew) );
+    *ppVtab = (sqlite3_vtab*)pNew;
+    if( pNew==0 ) return SQLITE_NOMEM;
+    memset(pNew, 0, sizeof(*pNew));
+    pNew->db = db;
+    pNew->bTablesUsed = isTabUsed*2;
+  }
+  return rc;
+}
+
+/*
+** This method is the destructor for bytecodevtab objects.
+*/
+static int bytecodevtabDisconnect(sqlite3_vtab *pVtab){
+  bytecodevtab *p = (bytecodevtab*)pVtab;
+  sqlite3_free(p);
+  return SQLITE_OK;
+}
+
+/*
+** Constructor for a new bytecodevtab_cursor object.
+*/
+static int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
+  bytecodevtab *pVTab = (bytecodevtab*)p;
+  bytecodevtab_cursor *pCur;
+  pCur = sqlite3_malloc( sizeof(*pCur) );
+  if( pCur==0 ) return SQLITE_NOMEM;
+  memset(pCur, 0, sizeof(*pCur));
+  sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
+  *ppCursor = &pCur->base;
+  return SQLITE_OK;
+}
+
+/*
+** Clear all internal content from a bytecodevtab cursor.
+*/
+static void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){
+  sqlite3_free(pCur->zP4);
+  pCur->zP4 = 0;
+  sqlite3VdbeMemRelease(&pCur->sub);
+  sqlite3VdbeMemSetNull(&pCur->sub);
+  if( pCur->needFinalize ){
+    sqlite3_finalize(pCur->pStmt);
+  }
+  pCur->pStmt = 0;
+  pCur->needFinalize = 0;
+  pCur->zType = 0;
+  pCur->zSchema = 0;
+  pCur->zName = 0;
+}
+
+/*
+** Destructor for a bytecodevtab_cursor.
+*/
+static int bytecodevtabClose(sqlite3_vtab_cursor *cur){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+  bytecodevtabCursorClear(pCur);
+  sqlite3_free(pCur);
+  return SQLITE_OK;
+}
+
+
+/*
+** Advance a bytecodevtab_cursor to its next row of output.
+*/
+static int bytecodevtabNext(sqlite3_vtab_cursor *cur){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+  bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
+  int rc;
+  if( pCur->zP4 ){
+    sqlite3_free(pCur->zP4);
+    pCur->zP4 = 0;
+  }
+  if( pCur->zName ){
+    pCur->zName = 0;
+    pCur->zType = 0;
+    pCur->zSchema = 0;
+  }
+  rc = sqlite3VdbeNextOpcode(
+           (Vdbe*)pCur->pStmt,
+           pCur->showSubprograms ? &pCur->sub : 0,
+           pTab->bTablesUsed,
+           &pCur->iRowid,
+           &pCur->iAddr,
+           &pCur->aOp);
+  if( rc!=SQLITE_OK ){
+    sqlite3VdbeMemSetNull(&pCur->sub);
+    pCur->aOp = 0;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Return TRUE if the cursor has been moved off of the last
+** row of output.
+*/
+static int bytecodevtabEof(sqlite3_vtab_cursor *cur){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+  return pCur->aOp==0;
+}
+
+/*
+** Return values of columns for the row at which the bytecodevtab_cursor
+** is currently pointing.
+*/
+static int bytecodevtabColumn(
+  sqlite3_vtab_cursor *cur,   /* The cursor */
+  sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
+  int i                       /* Which column to return */
+){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+  bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
+  Op *pOp = pCur->aOp + pCur->iAddr;
+  if( pVTab->bTablesUsed ){
+    if( i==4 ){
+      i = 8;
+    }else{
+      if( i<=2 && pCur->zType==0 ){
+        Schema *pSchema;
+        HashElem *k;
+        int iDb = pOp->p3;
+        Pgno iRoot = (Pgno)pOp->p2;
+        sqlite3 *db = pVTab->db;
+        pSchema = db->aDb[iDb].pSchema;
+        pCur->zSchema = db->aDb[iDb].zDbSName;
+        for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
+          Table *pTab = (Table*)sqliteHashData(k);
+          if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
+            pCur->zName = pTab->zName;
+            pCur->zType = "table";
+            break;
+          }
+        }
+        if( pCur->zName==0 ){
+          for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
+            Index *pIdx = (Index*)sqliteHashData(k);
+            if( pIdx->tnum==iRoot ){
+              pCur->zName = pIdx->zName;
+              pCur->zType = "index";
+            }
+          }
+        }
+      }
+      i += 10;
+    }
+  }
+  switch( i ){
+    case 0:   /* addr */
+      sqlite3_result_int(ctx, pCur->iAddr);
+      break;
+    case 1:   /* opcode */
+      sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
+                          -1, SQLITE_STATIC);
+      break;
+    case 2:   /* p1 */
+      sqlite3_result_int(ctx, pOp->p1);
+      break;
+    case 3:   /* p2 */
+      sqlite3_result_int(ctx, pOp->p2);
+      break;
+    case 4:   /* p3 */
+      sqlite3_result_int(ctx, pOp->p3);
+      break;
+    case 5:   /* p4 */
+    case 7:   /* comment */
+      if( pCur->zP4==0 ){
+        pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
+      }
+      if( i==5 ){
+        sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
+      }else{
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+        char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
+        sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
+#endif
+      }
+      break;
+    case 6:     /* p5 */
+      sqlite3_result_int(ctx, pOp->p5);
+      break;
+    case 8: {   /* subprog */
+      Op *aOp = pCur->aOp;
+      assert( aOp[0].opcode==OP_Init );
+      assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
+      if( pCur->iRowid==pCur->iAddr+1 ){
+        break;  /* Result is NULL for the main program */
+      }else if( aOp[0].p4.z!=0 ){
+         sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
+      }else{
+         sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
+      }
+      break;
+    }
+    case 10:  /* tables_used.type */
+      sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
+      break;
+    case 11:  /* tables_used.schema */
+      sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
+      break;
+    case 12:  /* tables_used.name */
+      sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
+      break;
+    case 13:  /* tables_used.wr */
+      sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
+      break;
+  }
+  return SQLITE_OK;
+}
+
+/*
+** Return the rowid for the current row.  In this implementation, the
+** rowid is the same as the output value.
+*/
+static int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
+  *pRowid = pCur->iRowid;
+  return SQLITE_OK;
+}
+
+/*
+** Initialize a cursor.
+**
+**    idxNum==0     means show all subprograms
+**    idxNum==1     means show only the main bytecode and omit subprograms.
+*/
+static int bytecodevtabFilter(
+  sqlite3_vtab_cursor *pVtabCursor,
+  int idxNum, const char *idxStr,
+  int argc, sqlite3_value **argv
+){
+  bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor;
+  bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
+  int rc = SQLITE_OK;
+
+  bytecodevtabCursorClear(pCur);
+  pCur->iRowid = 0;
+  pCur->iAddr = 0;
+  pCur->showSubprograms = idxNum==0;
+  assert( argc==1 );
+  if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
+    const char *zSql = (const char*)sqlite3_value_text(argv[0]);
+    if( zSql==0 ){
+      rc = SQLITE_NOMEM;
+    }else{
+      rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
+      pCur->needFinalize = 1;
+    }
+  }else{
+    pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
+  }
+  if( pCur->pStmt==0 ){
+    pVTab->base.zErrMsg = sqlite3_mprintf(
+       "argument to %s() is not a valid SQL statement",
+       pVTab->bTablesUsed ? "tables_used" : "bytecode"
+    );
+    rc = SQLITE_ERROR;
+  }else{
+    bytecodevtabNext(pVtabCursor);
+  }
+  return rc;
+}
+
+/*
+** We must have a single stmt=? constraint that will be passed through
+** into the xFilter method.  If there is no valid stmt=? constraint,
+** then return an SQLITE_CONSTRAINT error.
+*/
+static int bytecodevtabBestIndex(
+  sqlite3_vtab *tab,
+  sqlite3_index_info *pIdxInfo
+){
+  int i;
+  int rc = SQLITE_CONSTRAINT;
+  struct sqlite3_index_constraint *p;
+  bytecodevtab *pVTab = (bytecodevtab*)tab;
+  int iBaseCol = pVTab->bTablesUsed ? 4 : 8;
+  pIdxInfo->estimatedCost = (double)100;
+  pIdxInfo->estimatedRows = 100;
+  pIdxInfo->idxNum = 0;
+  for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
+    if( p->usable==0 ) continue;
+    if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
+      rc = SQLITE_OK;
+      pIdxInfo->aConstraintUsage[i].omit = 1;
+      pIdxInfo->aConstraintUsage[i].argvIndex = 1;
+    }
+    if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
+      pIdxInfo->aConstraintUsage[i].omit = 1;
+      pIdxInfo->idxNum = 1;
+    }
+  }
+  return rc;
+}
+
+/*
+** This following structure defines all the methods for the
+** virtual table.
+*/
+static sqlite3_module bytecodevtabModule = {
+  /* iVersion    */ 0,
+  /* xCreate     */ 0,
+  /* xConnect    */ bytecodevtabConnect,
+  /* xBestIndex  */ bytecodevtabBestIndex,
+  /* xDisconnect */ bytecodevtabDisconnect,
+  /* xDestroy    */ 0,
+  /* xOpen       */ bytecodevtabOpen,
+  /* xClose      */ bytecodevtabClose,
+  /* xFilter     */ bytecodevtabFilter,
+  /* xNext       */ bytecodevtabNext,
+  /* xEof        */ bytecodevtabEof,
+  /* xColumn     */ bytecodevtabColumn,
+  /* xRowid      */ bytecodevtabRowid,
+  /* xUpdate     */ 0,
+  /* xBegin      */ 0,
+  /* xSync       */ 0,
+  /* xCommit     */ 0,
+  /* xRollback   */ 0,
+  /* xFindMethod */ 0,
+  /* xRename     */ 0,
+  /* xSavepoint  */ 0,
+  /* xRelease    */ 0,
+  /* xRollbackTo */ 0,
+  /* xShadowName */ 0
+};
+
+
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){
+  int rc;
+  rc = sqlite3_create_module(db, "bytecode", &bytecodevtabModule, 0);
+  if( rc==SQLITE_OK ){
+    rc = sqlite3_create_module(db, "tables_used", &bytecodevtabModule, &db);
+  }
+  return rc;
+}
+#elif defined(SQLITE_ENABLE_BYTECODE_VTAB)
+SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; }
+#endif /* SQLITE_ENABLE_BYTECODE_VTAB */
+
+/************** End of vdbevtab.c ********************************************/
 /************** Begin file memjournal.c **************************************/
 /*
 ** 2008 October 7
@@ -95369,7 +97863,7 @@ static int memjrnlRead(
   assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
     sqlite3_int64 iOff = 0;
-    for(pChunk=p->pFirst; 
+    for(pChunk=p->pFirst;
         ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
         pChunk=pChunk->pNext
     ){
@@ -95404,7 +97898,7 @@ static void memjrnlFreeChunks(MemJournal *p){
   for(pIter=p->pFirst; pIter; pIter=pNext){
     pNext = pIter->pNext;
     sqlite3_free(pIter);
-  } 
+  }
   p->pFirst = 0;
 }
 
@@ -95476,7 +97970,7 @@ static int memjrnlWrite(
     ** access writes are not required. The only exception to this is when
     ** the in-memory journal is being used by a connection using the
     ** atomic-write optimization. In this case the first 28 bytes of the
-    ** journal file may be written as part of committing the transaction. */ 
+    ** journal file may be written as part of committing the transaction. */
     assert( iOfst==p->endpoint.iOffset || iOfst==0 );
 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
@@ -95527,7 +98021,7 @@ static int memjrnlWrite(
 **
 ** If the journal file is already on disk, truncate it there. Or, if it
 ** is still in main memory but is being truncated to zero bytes in size,
-** ignore 
+** ignore
 */
 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
   MemJournal *p = (MemJournal *)pJfd;
@@ -95554,8 +98048,8 @@ static int memjrnlClose(sqlite3_file *pJfd){
 /*
 ** Sync the file.
 **
-** If the real file has been created, call its xSync method. Otherwise, 
-** syncing an in-memory journal is a no-op. 
+** If the real file has been created, call its xSync method. Otherwise,
+** syncing an in-memory journal is a no-op.
 */
 static int memjrnlSync(sqlite3_file *pJfd, int flags){
   UNUSED_PARAMETER2(pJfd, flags);
@@ -95596,11 +98090,11 @@ static const struct sqlite3_io_methods MemJournalMethods = {
   0                 /* xUnfetch */
 };
 
-/* 
-** Open a journal file. 
+/*
+** Open a journal file.
 **
-** The behaviour of the journal file depends on the value of parameter 
-** nSpill. If nSpill is 0, then the journal file is always create and 
+** The behaviour of the journal file depends on the value of parameter
+** nSpill. If nSpill is 0, then the journal file is always create and
 ** accessed using the underlying VFS. If nSpill is less than zero, then
 ** all content is always stored in main-memory. Finally, if nSpill is a
 ** positive value, then the journal file is initially created in-memory
@@ -95633,7 +98127,7 @@ SQLITE_PRIVATE int sqlite3JournalOpen(
     assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
   }
 
-  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
+  pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods;
   p->nSpill = nSpill;
   p->flags = flags;
   p->zJournal = zName;
@@ -95651,15 +98145,15 @@ SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
 #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
 /*
-** If the argument p points to a MemJournal structure that is not an 
+** If the argument p points to a MemJournal structure that is not an
 ** in-memory-only journal file (i.e. is one that was opened with a +ve
-** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying 
+** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
 ** file has not yet been created, create it now.
 */
 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
   int rc = SQLITE_OK;
   MemJournal *p = (MemJournal*)pJfd;
-  if( p->pMethod==&MemJournalMethods && (
+  if( pJfd->pMethods==&MemJournalMethods && (
 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
      p->nSpill>0
 #else
@@ -95687,7 +98181,7 @@ SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
   return p->pMethods==&MemJournalMethods;
 }
 
-/* 
+/*
 ** Return the number of bytes required to store a JournalFile that uses vfs
 ** pVfs to create the underlying on-disk files.
 */
@@ -95772,8 +98266,8 @@ static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
     rc = pWalker->xExprCallback(pWalker, pExpr);
     if( rc ) return rc & WRC_Abort;
     if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
+      assert( pExpr->x.pList==0 || pExpr->pRight==0 );
       if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
-       assert( pExpr->x.pList==0 || pExpr->pRight==0 );
       if( pExpr->pRight ){
         assert( !ExprHasProperty(pExpr, EP_WinFunc) );
         pExpr = pExpr->pRight;
@@ -95846,7 +98340,7 @@ SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
 ** Walk the parse trees associated with all subqueries in the
 ** FROM clause of SELECT statement p.  Do not invoke the select
 ** callback on p, but do invoke it on each FROM clause subquery
-** and on any subqueries further down in the tree.  Return 
+** and on any subqueries further down in the tree.  Return
 ** WRC_Abort or WRC_Continue;
 */
 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
@@ -95855,24 +98349,25 @@ SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
   struct SrcList_item *pItem;
 
   pSrc = p->pSrc;
-  assert( pSrc!=0 );
-  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
-    if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
-      return WRC_Abort;
-    }
-    if( pItem->fg.isTabFunc
-     && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
-    ){
-      return WRC_Abort;
+  if( pSrc ){
+    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
+      if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
+        return WRC_Abort;
+      }
+      if( pItem->fg.isTabFunc
+       && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
+      ){
+        return WRC_Abort;
+      }
     }
   }
   return WRC_Continue;
-} 
+}
 
 /*
 ** Call sqlite3WalkExpr() for every expression in Select statement p.
 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
-** on the compound select chain, p->pPrior. 
+** on the compound select chain, p->pPrior.
 **
 ** If it is not NULL, the xSelectCallback() callback is invoked before
 ** the walk of the expressions and FROM clause. The xSelectCallback2()
@@ -95906,6 +98401,43 @@ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
   return WRC_Continue;
 }
 
+/* Increase the walkerDepth when entering a subquery, and
+** descrease when leaving the subquery.
+*/
+SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){
+  UNUSED_PARAMETER(pSelect);
+  pWalker->walkerDepth++;
+  return WRC_Continue;
+}
+SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){
+  UNUSED_PARAMETER(pSelect);
+  pWalker->walkerDepth--;
+}
+
+
+/*
+** No-op routine for the parse-tree walker.
+**
+** When this routine is the Walker.xExprCallback then expression trees
+** are walked without any actions being taken at each node.  Presumably,
+** when this routine is used for Walker.xExprCallback then
+** Walker.xSelectCallback is set to do something useful for every
+** subquery in the parser tree.
+*/
+SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
+  UNUSED_PARAMETER2(NotUsed, NotUsed2);
+  return WRC_Continue;
+}
+
+/*
+** No-op routine for the parse-tree walker for SELECT statements.
+** subquery in the parser tree.
+*/
+SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
+  UNUSED_PARAMETER2(NotUsed, NotUsed2);
+  return WRC_Continue;
+}
+
 /************** End of walker.c **********************************************/
 /************** Begin file resolve.c *****************************************/
 /*
@@ -95927,6 +98459,11 @@ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
 /* #include "sqliteInt.h" */
 
 /*
+** Magic table number to mean the EXCLUDED table in an UPSERT statement.
+*/
+#define EXCLUDED_TABLE_NUMBER  2
+
+/*
 ** Walk the expression tree pExpr and increase the aggregate function
 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
@@ -95934,6 +98471,8 @@ SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
 **
 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
 ** is a helper function - a callback for the tree walker.
+**
+** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
 */
 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
@@ -95991,7 +98530,7 @@ static void resolveAlias(
       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
     }
 
-    /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
+    /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
     ** prevents ExprDelete() from deleting the Expr structure itself,
     ** allowing it to be repopulated by the memcpy() on the following line.
     ** The pExpr->u.zToken might point into memory that will be freed by the
@@ -96042,13 +98581,16 @@ static int nameInUsingClause(IdList *pUsing, const char *zCol){
 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
 ** match anything.
 */
-SQLITE_PRIVATE int sqlite3MatchSpanName(
-  const char *zSpan,
+SQLITE_PRIVATE int sqlite3MatchEName(
+  const struct ExprList_item *pItem,
   const char *zCol,
   const char *zTab,
   const char *zDb
 ){
   int n;
+  const char *zSpan;
+  if( pItem->eEName!=ENAME_TAB ) return 0;
+  zSpan = pItem->zEName;
   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
     return 0;
@@ -96083,8 +98625,33 @@ static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
 }
 
 /*
+** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
+** return the appropriate colUsed mask.
+*/
+SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){
+  int n;
+  Table *pExTab;
+
+  n = pExpr->iColumn;
+  pExTab = pExpr->y.pTab;
+  assert( pExTab!=0 );
+  if( (pExTab->tabFlags & TF_HasGenerated)!=0
+   && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
+  ){
+    testcase( pExTab->nCol==BMS-1 );
+    testcase( pExTab->nCol==BMS );
+    return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
+  }else{
+    testcase( n==BMS-1 );
+    testcase( n==BMS );
+    if( n>=BMS ) n = BMS-1;
+    return ((Bitmask)1)<<n;
+  }
+}
+
+/*
 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
-** that name in the set of source tables in pSrcList and make the pExpr 
+** that name in the set of source tables in pSrcList and make the pExpr
 ** expression node refer back to that source column.  The following changes
 ** are made to pExpr:
 **
@@ -96159,6 +98726,12 @@ static int lookupName(
           break;
         }
       }
+      if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
+        /* This branch is taken when the main database has been renamed
+        ** using SQLITE_DBCONFIG_MAINDBNAME. */
+        pSchema = db->aDb[0].pSchema;
+        zDb = db->aDb[0].zDbSName;
+      }
     }
   }
 
@@ -96170,6 +98743,7 @@ static int lookupName(
 
     if( pSrcList ){
       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
+        u8 hCol;
         pTab = pItem->pTab;
         assert( pTab!=0 && pTab->zName!=0 );
         assert( pTab->nCol>0 );
@@ -96177,7 +98751,7 @@ static int lookupName(
           int hit = 0;
           pEList = pItem->pSelect->pEList;
           for(j=0; j<pEList->nExpr; j++){
-            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
+            if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
               cnt++;
               cntTab = 2;
               pMatch = pItem;
@@ -96203,10 +98777,11 @@ static int lookupName(
         if( 0==(cntTab++) ){
           pMatch = pItem;
         }
+        hCol = sqlite3StrIHash(zCol);
         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
-          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
+          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
             /* If there has been exactly one prior match and this match
-            ** is for the right-hand table of a NATURAL JOIN or is in a 
+            ** is for the right-hand table of a NATURAL JOIN or is in a
             ** USING clause, then skip this match.
             */
             if( cnt==1 ){
@@ -96234,7 +98809,7 @@ static int lookupName(
     } /* if( pSrcList ) */
 
 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
-    /* If we have not already resolved the name, then maybe 
+    /* If we have not already resolved the name, then maybe
     ** it is a new.* or old.* trigger argument reference.  Or
     ** maybe it is an excluded.* from an upsert.
     */
@@ -96258,17 +98833,18 @@ static int lookupName(
         Upsert *pUpsert = pNC->uNC.pUpsert;
         if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
           pTab = pUpsert->pUpsertSrc->a[0].pTab;
-          pExpr->iTable = 2;
+          pExpr->iTable = EXCLUDED_TABLE_NUMBER;
         }
       }
 #endif /* SQLITE_OMIT_UPSERT */
 
-      if( pTab ){ 
+      if( pTab ){
         int iCol;
+        u8 hCol = sqlite3StrIHash(zCol);
         pSchema = pTab->pSchema;
         cntTab++;
         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
-          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
+          if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
             if( iCol==pTab->iPKey ){
               iCol = -1;
             }
@@ -96282,14 +98858,15 @@ static int lookupName(
         if( iCol<pTab->nCol ){
           cnt++;
 #ifndef SQLITE_OMIT_UPSERT
-          if( pExpr->iTable==2 ){
+          if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
             testcase( iCol==(-1) );
             if( IN_RENAME_OBJECT ){
               pExpr->iColumn = iCol;
               pExpr->y.pTab = pTab;
               eNewExprOp = TK_COLUMN;
             }else{
-              pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
+              pExpr->iTable = pNC->uNC.pUpsert->regData +
+                 sqlite3TableColumnToStorage(pTab, iCol);
               eNewExprOp = TK_REGISTER;
               ExprSetProperty(pExpr, EP_Alias);
             }
@@ -96324,7 +98901,7 @@ static int lookupName(
     if( cnt==0
      && cntTab==1
      && pMatch
-     && (pNC->ncFlags & NC_IdxExpr)==0
+     && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
      && sqlite3IsRowid(zCol)
      && VisibleRowid(pMatch->pTab)
     ){
@@ -96358,8 +98935,10 @@ static int lookupName(
       pEList = pNC->uNC.pEList;
       assert( pEList!=0 );
       for(j=0; j<pEList->nExpr; j++){
-        char *zAs = pEList->a[j].zName;
-        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
+        char *zAs = pEList->a[j].zEName;
+        if( pEList->a[j].eEName==ENAME_NAME
+         && sqlite3_stricmp(zAs, zCol)==0
+        ){
           Expr *pOrig;
           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
           assert( pExpr->x.pList==0 );
@@ -96369,7 +98948,9 @@ static int lookupName(
             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
             return WRC_Abort;
           }
-          if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){
+          if( ExprHasProperty(pOrig, EP_Win)
+           && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
+          ){
             sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
             return WRC_Abort;
           }
@@ -96386,7 +98967,7 @@ static int lookupName(
           }
           goto lookupname_end;
         }
-      } 
+      }
     }
 
     /* Advance to the next name context.  The loop will exit when either
@@ -96461,18 +99042,20 @@ static int lookupName(
 
   /* If a column from a table in pSrcList is referenced, then record
   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
-  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
-  ** column number is greater than the number of bits in the bitmask
-  ** then set the high-order bit of the bitmask.
+  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  Bit 63 is
+  ** set if the 63rd or any subsequent column is used.
+  **
+  ** The colUsed mask is an optimization used to help determine if an
+  ** index is a covering index.  The correct answer is still obtained
+  ** if the mask contains extra set bits.  However, it is important to
+  ** avoid setting bits beyond the maximum column number of the table.
+  ** (See ticket [b92e5e8ec2cdbaa1]).
+  **
+  ** If a generated column is referenced, set bits for every column
+  ** of the table.
   */
   if( pExpr->iColumn>=0 && pMatch!=0 ){
-    int n = pExpr->iColumn;
-    testcase( n==BMS-1 );
-    if( n>=BMS ){
-      n = BMS-1;
-    }
-    assert( pMatch->iCursor==pExpr->iTable );
-    pMatch->colUsed |= ((Bitmask)1)<<n;
+    pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
   }
 
   /* Clean up and return
@@ -96511,15 +99094,23 @@ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSr
   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
   if( p ){
     struct SrcList_item *pItem = &pSrc->a[iSrc];
-    p->y.pTab = pItem->pTab;
+    Table *pTab = p->y.pTab = pItem->pTab;
     p->iTable = pItem->iCursor;
     if( p->y.pTab->iPKey==iCol ){
       p->iColumn = -1;
     }else{
       p->iColumn = (ynVar)iCol;
-      testcase( iCol==BMS );
-      testcase( iCol==BMS-1 );
-      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
+      if( (pTab->tabFlags & TF_HasGenerated)!=0
+       && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
+      ){
+        testcase( pTab->nCol==63 );
+        testcase( pTab->nCol==64 );
+        pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
+      }else{
+        testcase( iCol==BMS );
+        testcase( iCol==BMS-1 );
+        pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
+      }
     }
   }
   return p;
@@ -96528,23 +99119,39 @@ SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSr
 /*
 ** Report an error that an expression is not valid for some set of
 ** pNC->ncFlags values determined by validMask.
-*/
-static void notValid(
-  Parse *pParse,       /* Leave error message here */
-  NameContext *pNC,    /* The name context */
-  const char *zMsg,    /* Type of error */
-  int validMask        /* Set of contexts for which prohibited */
-){
-  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
-  if( (pNC->ncFlags & validMask)!=0 ){
-    const char *zIn = "partial index WHERE clauses";
-    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
+**
+** static void notValid(
+**   Parse *pParse,       // Leave error message here
+**   NameContext *pNC,    // The name context
+**   const char *zMsg,    // Type of error
+**   int validMask,       // Set of contexts for which prohibited
+**   Expr *pExpr          // Invalidate this expression on error
+** ){...}
+**
+** As an optimization, since the conditional is almost always false
+** (because errors are rare), the conditional is moved outside of the
+** function call using a macro.
+*/
+static void notValidImpl(
+   Parse *pParse,       /* Leave error message here */
+   NameContext *pNC,    /* The name context */
+   const char *zMsg,    /* Type of error */
+   Expr *pExpr          /* Invalidate this expression on error */
+){
+  const char *zIn = "partial index WHERE clauses";
+  if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
 #ifndef SQLITE_OMIT_CHECK
-    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
+  else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
 #endif
-    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
-  }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
+#endif
+  sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
+  if( pExpr ) pExpr->op = TK_NULL;
 }
+#define sqlite3ResolveNotValid(P,N,M,X,E) \
+  assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
+  if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);
 
 /*
 ** Expression p should encode a floating point value between 1.0 and 0.0.
@@ -96591,33 +99198,30 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
 #endif
   switch( pExpr->op ){
 
-#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
     /* The special operator TK_ROW means use the rowid for the first
     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
-    ** clause processing on UPDATE and DELETE statements.
+    ** clause processing on UPDATE and DELETE statements, and by
+    ** UPDATE ... FROM statement processing.
     */
     case TK_ROW: {
       SrcList *pSrcList = pNC->pSrcList;
       struct SrcList_item *pItem;
-      assert( pSrcList && pSrcList->nSrc==1 );
+      assert( pSrcList && pSrcList->nSrc>=1 );
       pItem = pSrcList->a;
-      assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
       pExpr->op = TK_COLUMN;
       pExpr->y.pTab = pItem->pTab;
       pExpr->iTable = pItem->iCursor;
-      pExpr->iColumn = -1;
+      pExpr->iColumn--;
       pExpr->affExpr = SQLITE_AFF_INTEGER;
       break;
     }
-#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
-          && !defined(SQLITE_OMIT_SUBQUERY) */
 
     /* A column name:                    ID
     ** Or table name and column name:    ID.ID
     ** Or a database, table and column:  ID.ID.ID
     **
     ** The TK_ID and TK_OUT cases are combined so that there will only
-    ** be one call to lookupName().  Then the compiler will in-line 
+    ** be one call to lookupName().  Then the compiler will in-line
     ** lookupName() for a size reduction and performance increase.
     */
     case TK_ID:
@@ -96633,7 +99237,10 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         zColumn = pExpr->u.zToken;
       }else{
         Expr *pLeft = pExpr->pLeft;
-        notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
+        testcase( pNC->ncFlags & NC_IdxExpr );
+        testcase( pNC->ncFlags & NC_GenCol );
+        sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
+                               NC_IdxExpr|NC_GenCol, 0);
         pRight = pExpr->pRight;
         if( pRight->op==TK_ID ){
           zDb = 0;
@@ -96703,7 +99310,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
             ** to likelihood(X,0.9375). */
             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
-          }             
+          }
         }
 #ifndef SQLITE_OMIT_AUTHORIZATION
         {
@@ -96722,33 +99329,39 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
           /* For the purposes of the EP_ConstFunc flag, date and time
           ** functions and other functions that change slowly are considered
-          ** constant because they are constant for the duration of one query */
+          ** constant because they are constant for the duration of one query.
+          ** This allows them to be factored out of inner loops. */
           ExprSetProperty(pExpr,EP_ConstFunc);
         }
         if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
-          /* Date/time functions that use 'now', and other functions like
+          /* Clearly non-deterministic functions like random(), but also
+          ** date/time functions that use 'now', and other functions like
           ** sqlite_version() that might change over time cannot be used
-          ** in an index. */
-          notValid(pParse, pNC, "non-deterministic functions",
-                   NC_IdxExpr|NC_PartIdx);
+          ** in an index or generated column.  Curiously, they can be used
+          ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all
+          ** all this. */
+          sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
+                                 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0);
+        }else{
+          assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
+          pExpr->op2 = pNC->ncFlags & NC_SelfRef;
+          if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
         }
         if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
          && pParse->nested==0
-         && sqlite3Config.bInternalFunctions==0
+         && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
         ){
           /* Internal-use-only functions are disallowed unless the
-          ** SQL is being compiled using sqlite3NestedParse() */
+          ** SQL is being compiled using sqlite3NestedParse() or
+          ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
+          ** used to activate internal functionsn for testing purposes */
           no_such_func = 1;
           pDef = 0;
         }else
-        if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
-         && ExprHasProperty(pExpr, EP_Indirect)
+        if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
          && !IN_RENAME_OBJECT
         ){
-          /* Functions tagged with SQLITE_DIRECTONLY may not be used
-          ** inside of triggers and views */
-          sqlite3ErrorMsg(pParse, "%s() prohibited in triggers and views",
-                          pDef->zName);
+          sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
         }
       }
 
@@ -96759,11 +99372,11 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
         );
         if( pDef && pDef->xValue==0 && pWin ){
-          sqlite3ErrorMsg(pParse, 
+          sqlite3ErrorMsg(pParse,
               "%.*s() may not be used as a window function", nId, zId
           );
           pNC->nErr++;
-        }else if( 
+        }else if(
               (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
            || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
            || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
@@ -96799,8 +99412,8 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         }
 #ifndef SQLITE_OMIT_WINDOWFUNC
         else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
-          sqlite3ErrorMsg(pParse, 
-              "FILTER may not be used with non-aggregate %.*s()", 
+          sqlite3ErrorMsg(pParse,
+              "FILTER may not be used with non-aggregate %.*s()",
               nId, zId
           );
           pNC->nErr++;
@@ -96829,7 +99442,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           Select *pSel = pNC->pWinSelect;
           assert( pWin==pExpr->y.pWin );
           if( IN_RENAME_OBJECT==0 ){
-            sqlite3WindowUpdate(pParse, pSel->pWinDefn, pWin, pDef);
+            sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
           }
           sqlite3WalkExprList(pWalker, pWin->pPartition);
           sqlite3WalkExprList(pWalker, pWin->pOrderBy);
@@ -96862,7 +99475,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         pNC->ncFlags |= savedAllowFlags;
       }
       /* FIX ME:  Compute pExpr->affinity based on the expected return
-      ** type of the function 
+      ** type of the function
       */
       return WRC_Prune;
     }
@@ -96874,7 +99487,12 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       testcase( pExpr->op==TK_IN );
       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
         int nRef = pNC->nRef;
-        notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
+        testcase( pNC->ncFlags & NC_IsCheck );
+        testcase( pNC->ncFlags & NC_PartIdx );
+        testcase( pNC->ncFlags & NC_IdxExpr );
+        testcase( pNC->ncFlags & NC_GenCol );
+        sqlite3ResolveNotValid(pParse, pNC, "subqueries",
+                 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
         assert( pNC->nRef>=nRef );
         if( nRef!=pNC->nRef ){
@@ -96885,7 +99503,12 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       break;
     }
     case TK_VARIABLE: {
-      notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
+      testcase( pNC->ncFlags & NC_IsCheck );
+      testcase( pNC->ncFlags & NC_PartIdx );
+      testcase( pNC->ncFlags & NC_IdxExpr );
+      testcase( pNC->ncFlags & NC_GenCol );
+      sqlite3ResolveNotValid(pParse, pNC, "parameters",
+               NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
       break;
     }
     case TK_IS:
@@ -96894,7 +99517,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
       assert( !ExprHasProperty(pExpr, EP_Reduced) );
       /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
       ** and "x IS NOT FALSE". */
-      if( pRight->op==TK_ID ){
+      if( pRight && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
         int rc = resolveExprStep(pWalker, pRight);
         if( rc==WRC_Abort ) return WRC_Abort;
         if( pRight->op==TK_TRUEFALSE ){
@@ -96903,7 +99526,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
           return WRC_Continue;
         }
       }
-      /* Fall thru */
+      /* no break */ deliberate_fall_through
     }
     case TK_BETWEEN:
     case TK_EQ:
@@ -96937,7 +99560,7 @@ static int resolveExprStep(Walker *pWalker, Expr *pExpr){
         testcase( pExpr->op==TK_BETWEEN );
         sqlite3ErrorMsg(pParse, "row value misused");
       }
-      break; 
+      break;
     }
   }
   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
@@ -96967,8 +99590,9 @@ static int resolveAsName(
   if( pE->op==TK_ID ){
     char *zCol = pE->u.zToken;
     for(i=0; i<pEList->nExpr; i++){
-      char *zAs = pEList->a[i].zName;
-      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
+      if( pEList->a[i].eEName==ENAME_NAME
+       && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
+      ){
         return i+1;
       }
     }
@@ -97047,7 +99671,7 @@ static void resolveOutOfRangeError(
   int i,                 /* The index (1-based) of the term out of range */
   int mx                 /* Largest permissible value of i */
 ){
-  sqlite3ErrorMsg(pParse, 
+  sqlite3ErrorMsg(pParse,
     "%r %s BY term out of range - should be "
     "between 1 and %d", i, zType, mx);
 }
@@ -97102,6 +99726,7 @@ static int resolveCompoundOrderBy(
       Expr *pE, *pDup;
       if( pItem->done ) continue;
       pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
+      if( NEVER(pE==0) ) continue;
       if( sqlite3ExprIsInteger(pE, &iCol) ){
         if( iCol<=0 || iCol>pEList->nExpr ){
           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
@@ -97111,7 +99736,7 @@ static int resolveCompoundOrderBy(
         iCol = resolveAsName(pParse, pEList, pE);
         if( iCol==0 ){
           /* Now test if expression pE matches one of the values returned
-          ** by pSelect. In the usual case this is done by duplicating the 
+          ** by pSelect. In the usual case this is done by duplicating the
           ** expression, resolving any symbols in it, and then comparing
           ** it against each expression returned by the SELECT statement.
           ** Once the comparisons are finished, the duplicate expression
@@ -97281,6 +99906,7 @@ static int resolveOrderGroupBy(
   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
     Expr *pE = pItem->pExpr;
     Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
+    if( NEVER(pE2==0) ) continue;
     if( zType[0]!='G' ){
       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
       if( iCol>0 ){
@@ -97335,7 +99961,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
   ExprList *pGroupBy;     /* The GROUP BY clause */
   Select *pLeftmost;      /* Left-most of SELECT of a compound */
   sqlite3 *db;            /* Database connection */
-  
+
 
   assert( p!=0 );
   if( p->selFlags & SF_Resolved ){
@@ -97389,7 +100015,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
       pSub->pOrderBy = p->pOrderBy;
       p->pOrderBy = 0;
     }
-  
+
     /* Recursively resolve names in all subqueries
     */
     for(i=0; i<p->pSrc->nSrc; i++){
@@ -97416,19 +100042,19 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
         pItem->fg.isCorrelated = (nRef!=0);
       }
     }
-  
+
     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
     ** resolve the result-set expression list.
     */
     sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
     sNC.pSrcList = p->pSrc;
     sNC.pNext = pOuterNC;
-  
+
     /* Resolve names in the result set. */
     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
     sNC.ncFlags &= ~NC_AllowWin;
-  
-    /* If there are no aggregate functions in the result-set, and no GROUP BY 
+
+    /* If there are no aggregate functions in the result-set, and no GROUP BY
     ** expression, do not allow aggregates in any of the other expressions.
     */
     assert( (p->selFlags & SF_Aggregate)==0 );
@@ -97439,14 +100065,14 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
     }else{
       sNC.ncFlags &= ~NC_AllowAgg;
     }
-  
+
     /* If a HAVING clause is present, then there must be a GROUP BY clause.
     */
     if( p->pHaving && !pGroupBy ){
       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
       return WRC_Abort;
     }
-  
+
     /* Add the output column list to the name-context before parsing the
     ** other expressions in the SELECT statement. This is so that
     ** expressions in the WHERE clause (etc.) can refer to expressions by
@@ -97465,19 +100091,19 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
     for(i=0; i<p->pSrc->nSrc; i++){
       struct SrcList_item *pItem = &p->pSrc->a[i];
       if( pItem->fg.isTabFunc
-       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 
+       && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
       ){
         return WRC_Abort;
       }
     }
 
     /* The ORDER BY and GROUP BY clauses may not refer to terms in
-    ** outer queries 
+    ** outer queries
     */
     sNC.pNext = 0;
     sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
 
-    /* If this is a converted compound query, move the ORDER BY clause from 
+    /* If this is a converted compound query, move the ORDER BY clause from
     ** the sub-query back to the parent query. At this point each term
     ** within the ORDER BY clause has been transformed to an integer value.
     ** These integers will be replaced by copies of the corresponding result
@@ -97507,13 +100133,13 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
       return WRC_Abort;
     }
     sNC.ncFlags &= ~NC_AllowWin;
-  
-    /* Resolve the GROUP BY clause.  At the same time, make sure 
+
+    /* Resolve the GROUP BY clause.  At the same time, make sure
     ** the GROUP BY clause does not contain aggregate functions.
     */
     if( pGroupBy ){
       struct ExprList_item *pItem;
-    
+
       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
         return WRC_Abort;
       }
@@ -97568,7 +100194,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
 ** checking on function usage and set a flag if any aggregate functions
 ** are seen.
 **
-** To resolve table columns references we look for nodes (or subtrees) of the 
+** To resolve table columns references we look for nodes (or subtrees) of the
 ** form X.Y.Z or Y.Z or just Z where
 **
 **      X:   The name of a database.  Ex:  "main" or "temp" or
@@ -97600,7 +100226,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
 **
 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
 **
-** Function calls are checked to make sure that the function is 
+** Function calls are checked to make sure that the function is
 ** defined and that the correct number of arguments are specified.
 ** If the function is an aggregate function, then the NC_HasAgg flag is
 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
@@ -97610,7 +100236,7 @@ static int resolveSelectStep(Walker *pWalker, Select *p){
 ** An error message is left in pParse if anything is amiss.  The number
 ** if errors is returned.
 */
-SQLITE_PRIVATE int sqlite3ResolveExprNames( 
+SQLITE_PRIVATE int sqlite3ResolveExprNames(
   NameContext *pNC,       /* Namespace to resolve expressions in. */
   Expr *pExpr             /* The expression to be analyzed. */
 ){
@@ -97649,16 +100275,46 @@ SQLITE_PRIVATE int sqlite3ResolveExprNames(
 ** just like sqlite3ResolveExprNames() except that it works for an expression
 ** list rather than a single expression.
 */
-SQLITE_PRIVATE int sqlite3ResolveExprListNames( 
+SQLITE_PRIVATE int sqlite3ResolveExprListNames(
   NameContext *pNC,       /* Namespace to resolve expressions in. */
   ExprList *pList         /* The expression list to be analyzed. */
 ){
   int i;
-  if( pList ){
-    for(i=0; i<pList->nExpr; i++){
-      if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
+  int savedHasAgg = 0;
+  Walker w;
+  if( pList==0 ) return WRC_Continue;
+  w.pParse = pNC->pParse;
+  w.xExprCallback = resolveExprStep;
+  w.xSelectCallback = resolveSelectStep;
+  w.xSelectCallback2 = 0;
+  w.u.pNC = pNC;
+  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+  for(i=0; i<pList->nExpr; i++){
+    Expr *pExpr = pList->a[i].pExpr;
+    if( pExpr==0 ) continue;
+#if SQLITE_MAX_EXPR_DEPTH>0
+    w.pParse->nHeight += pExpr->nHeight;
+    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
+      return WRC_Abort;
     }
+#endif
+    sqlite3WalkExpr(&w, pExpr);
+#if SQLITE_MAX_EXPR_DEPTH>0
+    w.pParse->nHeight -= pExpr->nHeight;
+#endif
+    assert( EP_Agg==NC_HasAgg );
+    assert( EP_Win==NC_HasWin );
+    testcase( pNC->ncFlags & NC_HasAgg );
+    testcase( pNC->ncFlags & NC_HasWin );
+    if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){
+      ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
+      savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+      pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
+    }
+    if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort;
   }
+  pNC->ncFlags |= savedHasAgg;
   return WRC_Continue;
 }
 
@@ -97694,10 +100350,13 @@ SQLITE_PRIVATE void sqlite3ResolveSelectNames(
 ** Resolve names in expressions that can only reference a single table
 ** or which cannot reference any tables at all.  Examples:
 **
-**    (1)   CHECK constraints
-**    (2)   WHERE clauses on partial indices
-**    (3)   Expressions in indexes on expressions
-**    (4)   Expression arguments to VACUUM INTO.
+**                                                    "type" flag
+**                                                    ------------
+**    (1)   CHECK constraints                         NC_IsCheck
+**    (2)   WHERE clauses on partial indices          NC_PartIdx
+**    (3)   Expressions in indexes on expressions     NC_IdxExpr
+**    (4)   Expression arguments to VACUUM INTO.      0
+**    (5)   GENERATED ALWAYS as expressions           NC_GenCol
 **
 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
 ** nodes of the expression is set to -1 and the Expr.iColumn value is
@@ -97706,18 +100365,19 @@ SQLITE_PRIVATE void sqlite3ResolveSelectNames(
 ** Any errors cause an error message to be set in pParse.
 */
 SQLITE_PRIVATE int sqlite3ResolveSelfReference(
-  Parse *pParse,      /* Parsing context */
-  Table *pTab,        /* The table being referenced, or NULL */
-  int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr, or 0 */
-  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
-  ExprList *pList     /* Expression list to resolve.  May be NULL. */
+  Parse *pParse,   /* Parsing context */
+  Table *pTab,     /* The table being referenced, or NULL */
+  int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
+  Expr *pExpr,     /* Expression to resolve.  May be NULL. */
+  ExprList *pList  /* Expression list to resolve.  May be NULL. */
 ){
   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
   NameContext sNC;                /* Name context for pParse->pNewTable */
   int rc;
 
   assert( type==0 || pTab!=0 );
-  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || pTab==0 );
+  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
+          || type==NC_GenCol || pTab==0 );
   memset(&sNC, 0, sizeof(sNC));
   memset(&sSrc, 0, sizeof(sSrc));
   if( pTab ){
@@ -97725,6 +100385,11 @@ SQLITE_PRIVATE int sqlite3ResolveSelfReference(
     sSrc.a[0].zName = pTab->zName;
     sSrc.a[0].pTab = pTab;
     sSrc.a[0].iCursor = -1;
+    if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
+      /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
+      ** schema elements */
+      type |= NC_FromDDL;
+    }
   }
   sNC.pParse = pParse;
   sNC.pSrcList = &sSrc;
@@ -97768,7 +100433,7 @@ SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
 ** Return the 'affinity' of the expression pExpr if any.
 **
 ** If pExpr is a column, a reference to a column via an 'AS' alias,
-** or a sub-select with a column as the return value, then the 
+** or a sub-select with a column as the return value, then the
 ** affinity of that column is returned. Otherwise, 0x00 is returned,
 ** indicating no affinity for the expression.
 **
@@ -97780,16 +100445,21 @@ SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
 ** SELECT a AS b FROM t1 WHERE b;
 ** SELECT * FROM t1 WHERE (select a from t1);
 */
-SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
+SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
   int op;
-  while( ExprHasProperty(pExpr, EP_Skip) ){
-    assert( pExpr->op==TK_COLLATE );
+  while( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
+    assert( pExpr->op==TK_COLLATE
+         || pExpr->op==TK_IF_NULL_ROW
+         || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
     pExpr = pExpr->pLeft;
     assert( pExpr!=0 );
   }
   op = pExpr->op;
   if( op==TK_SELECT ){
     assert( pExpr->flags&EP_xIsSelect );
+    assert( pExpr->x.pSelect!=0 );
+    assert( pExpr->x.pSelect->pEList!=0 );
+    assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
   }
   if( op==TK_REGISTER ) op = pExpr->op2;
@@ -97808,6 +100478,9 @@ SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
         pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
     );
   }
+  if( op==TK_VECTOR ){
+    return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
+  }
   return pExpr->affExpr;
 }
 
@@ -97849,7 +100522,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
     assert( pExpr->op==TK_COLLATE );
     pExpr = pExpr->pLeft;
-  }   
+  }
   return pExpr;
 }
 
@@ -97869,7 +100542,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
       assert( pExpr->op==TK_COLLATE );
       pExpr = pExpr->pLeft;
     }
-  }   
+  }
   return pExpr;
 }
 
@@ -97887,10 +100560,10 @@ SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
 ** COLLATE operators take first precedence.  Left operands take
 ** precedence over right operands.
 */
-SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
+SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
   sqlite3 *db = pParse->db;
   CollSeq *pColl = 0;
-  Expr *p = pExpr;
+  const Expr *p = pExpr;
   while( p ){
     int op = p->op;
     if( op==TK_REGISTER ) op = p->op2;
@@ -97910,6 +100583,10 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
       p = p->pLeft;
       continue;
     }
+    if( op==TK_VECTOR ){
+      p = p->x.pList->a[0].pExpr;
+      continue;
+    }
     if( op==TK_COLLATE ){
       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
       break;
@@ -97921,10 +100598,10 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
         Expr *pNext  = p->pRight;
         /* The Expr.x union is never used at the same time as Expr.pRight */
         assert( p->x.pList==0 || p->pRight==0 );
-        /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
-        ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
-        ** least one EP_Collate. Thus the following two ALWAYS. */
-        if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
+        if( p->x.pList!=0
+         && !db->mallocFailed
+         && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
+        ){
           int i;
           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
@@ -97939,7 +100616,7 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
       break;
     }
   }
-  if( sqlite3CheckCollSeq(pParse, pColl) ){ 
+  if( sqlite3CheckCollSeq(pParse, pColl) ){
     pColl = 0;
   }
   return pColl;
@@ -97955,7 +100632,7 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
 ** The sqlite3ExprCollSeq() routine works the same except that it
 ** returns NULL if there is no defined collation.
 */
-SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
+SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
   CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
   if( p==0 ) p = pParse->db->pDfltColl;
   assert( p!=0 );
@@ -97965,7 +100642,7 @@ SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
 /*
 ** Return TRUE if the two expressions have equivalent collating sequences.
 */
-SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
+SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
   CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
   CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
   return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
@@ -97976,7 +100653,7 @@ SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
 ** type affinity of the other operand.  This routine returns the
 ** type affinity that should be used for the comparison operator.
 */
-SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
+SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
   char aff1 = sqlite3ExprAffinity(pExpr);
   if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
     /* Both sides of the comparison are columns. If one has numeric
@@ -97998,7 +100675,7 @@ SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
 ** pExpr is a comparison operator.  Return the type affinity that should
 ** be applied to both operands prior to doing the comparison.
 */
-static char comparisonAffinity(Expr *pExpr){
+static char comparisonAffinity(const Expr *pExpr){
   char aff;
   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
@@ -98021,7 +100698,7 @@ static char comparisonAffinity(Expr *pExpr){
 ** if the index with affinity idx_affinity may be used to implement
 ** the comparison in pExpr.
 */
-SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
+SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
   char aff = comparisonAffinity(pExpr);
   if( aff<SQLITE_AFF_TEXT ){
     return 1;
@@ -98036,7 +100713,11 @@ SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
 ** Return the P5 value that should be used for a binary comparison
 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
 */
-static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
+static u8 binaryCompareP5(
+  const Expr *pExpr1,   /* Left operand */
+  const Expr *pExpr2,   /* Right operand */
+  int jumpIfNull        /* Extra flags added to P5 */
+){
   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
   return aff;
@@ -98055,9 +100736,9 @@ static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
 ** it is not considered.
 */
 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
-  Parse *pParse, 
-  Expr *pLeft, 
-  Expr *pRight
+  Parse *pParse,
+  const Expr *pLeft,
+  const Expr *pRight
 ){
   CollSeq *pColl;
   assert( pLeft );
@@ -98074,6 +100755,22 @@ SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
   return pColl;
 }
 
+/* Expresssion p is a comparison operator.  Return a collation sequence
+** appropriate for the comparison operator.
+**
+** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
+** However, if the OP_Commuted flag is set, then the order of the operands
+** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
+** correct collating sequence is found.
+*/
+SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
+  if( ExprHasProperty(p, EP_Commuted) ){
+    return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
+  }else{
+    return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
+  }
+}
+
 /*
 ** Generate code for a comparison operator.
 */
@@ -98084,13 +100781,19 @@ static int codeCompare(
   int opcode,       /* The comparison opcode */
   int in1, int in2, /* Register holding operands */
   int dest,         /* Jump here if true.  */
-  int jumpIfNull    /* If true, jump if either operand is NULL */
+  int jumpIfNull,   /* If true, jump if either operand is NULL */
+  int isCommuted    /* The comparison has been commuted */
 ){
   int p5;
   int addr;
   CollSeq *p4;
 
-  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
+  if( pParse->nErr ) return 0;
+  if( isCommuted ){
+    p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
+  }else{
+    p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
+  }
   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
                            (void*)p4, P4_COLLSEQ);
@@ -98112,7 +100815,7 @@ SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
 }
 
 /*
-** If the expression passed as the only argument is of type TK_VECTOR 
+** If the expression passed as the only argument is of type TK_VECTOR
 ** return the number of expressions in the vector. Or, if the expression
 ** is a sub-select, return the number of columns in the sub-select. For
 ** any other type of expression, return 1.
@@ -98162,7 +100865,7 @@ SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
 ** sqlite3ExprCode() will generate all necessary code to compute
 ** the iField-th column of the vector expression pVector.
 **
-** It is ok for pVector to be a scalar (as long as iField==0).  
+** It is ok for pVector to be a scalar (as long as iField==0).
 ** In that case, this routine works like sqlite3ExprDup().
 **
 ** The caller owns the returned Expr object and is responsible for
@@ -98218,7 +100921,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
 
 /*
 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
-** it. Return the register in which the result is stored (or, if the 
+** it. Return the register in which the result is stored (or, if the
 ** sub-select returns more than one column, the first in an array
 ** of registers in which the result is stored).
 **
@@ -98240,10 +100943,10 @@ static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
 ** the register number of a register that contains the value of
 ** element iField of the vector.
 **
-** If pVector is a TK_SELECT expression, then code for it must have 
+** If pVector is a TK_SELECT expression, then code for it must have
 ** already been generated using the exprCodeSubselect() routine. In this
 ** case parameter regSelect should be the first in an array of registers
-** containing the results of the sub-select. 
+** containing the results of the sub-select.
 **
 ** If pVector is of type TK_VECTOR, then code for the requested field
 ** is generated. In this case (*pRegFree) may be set to the number of
@@ -98301,15 +101004,18 @@ static void codeVectorCompare(
   int regRight = 0;
   u8 opx = op;
   int addrDone = sqlite3VdbeMakeLabel(pParse);
+  int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
 
+  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
+  if( pParse->nErr ) return;
   if( nLeft!=sqlite3ExprVectorSize(pRight) ){
     sqlite3ErrorMsg(pParse, "row value misused");
     return;
   }
-  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 
-       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 
-       || pExpr->op==TK_LT || pExpr->op==TK_GT 
-       || pExpr->op==TK_LE || pExpr->op==TK_GE 
+  assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
+       || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
+       || pExpr->op==TK_LT || pExpr->op==TK_GT
+       || pExpr->op==TK_LE || pExpr->op==TK_GE
   );
   assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
             || (pExpr->op==TK_ISNOT && op==TK_NE) );
@@ -98325,12 +101031,12 @@ static void codeVectorCompare(
 
   for(i=0; 1 /*Loop exits by "break"*/; i++){
     int regFree1 = 0, regFree2 = 0;
-    Expr *pL, *pR; 
+    Expr *pL, *pR;
     int r1, r2;
     assert( i>=0 && i<nLeft );
     r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
     r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
-    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
+    codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
     testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
     testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
     testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
@@ -98371,7 +101077,7 @@ SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
   int rc = SQLITE_OK;
   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
   if( nHeight>mxHeight ){
-    sqlite3ErrorMsg(pParse, 
+    sqlite3ErrorMsg(pParse,
        "Expression tree is too large (maximum depth %d)", mxHeight
     );
     rc = SQLITE_ERROR;
@@ -98416,10 +101122,10 @@ static void heightOfSelect(Select *pSelect, int *pnHeight){
 }
 
 /*
-** Set the Expr.nHeight variable in the structure passed as an 
-** argument. An expression with no children, Expr.pList or 
+** Set the Expr.nHeight variable in the structure passed as an
+** argument. An expression with no children, Expr.pList or
 ** Expr.pSelect member has a height of 1. Any other expression
-** has a height equal to the maximum height of any other 
+** has a height equal to the maximum height of any other
 ** referenced Expr plus one.
 **
 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
@@ -98444,7 +101150,7 @@ static void exprSetHeight(Expr *p){
 ** leave an error in pParse.
 **
 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
-** Expr.flags. 
+** Expr.flags.
 */
 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
   if( pParse->nErr ) return;
@@ -98464,9 +101170,10 @@ SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
 /*
 ** Propagate all EP_Propagate flags from the Expr.x.pList into
-** Expr.flags. 
+** Expr.flags.
 */
 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
+  if( pParse->nErr ) return;
   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
   }
@@ -98533,7 +101240,7 @@ SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
     }
 #if SQLITE_MAX_EXPR_DEPTH>0
     pNew->nHeight = 1;
-#endif  
+#endif
   }
   return pNew;
 }
@@ -98640,9 +101347,11 @@ SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
     return pRight;
   }else if( pRight==0 ){
     return pLeft;
-  }else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){
-    sqlite3ExprUnmapAndDelete(pParse, pLeft);
-    sqlite3ExprUnmapAndDelete(pParse, pRight);
+  }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
+         && !IN_RENAME_OBJECT
+  ){
+    sqlite3ExprDelete(db, pLeft);
+    sqlite3ExprDelete(db, pRight);
     return sqlite3Expr(db, TK_INTEGER, "0");
   }else{
     return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
@@ -98679,8 +101388,42 @@ SQLITE_PRIVATE Expr *sqlite3ExprFunction(
 }
 
 /*
+** Check to see if a function is usable according to current access
+** rules:
+**
+**    SQLITE_FUNC_DIRECT    -     Only usable from top-level SQL
+**
+**    SQLITE_FUNC_UNSAFE    -     Usable if TRUSTED_SCHEMA or from
+**                                top-level SQL
+**
+** If the function is not usable, create an error.
+*/
+SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
+  Parse *pParse,         /* Parsing and code generating context */
+  Expr *pExpr,           /* The function invocation */
+  FuncDef *pDef          /* The function being invoked */
+){
+  assert( !IN_RENAME_OBJECT );
+  assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
+  if( ExprHasProperty(pExpr, EP_FromDDL) ){
+    if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
+     || (pParse->db->flags & SQLITE_TrustedSchema)==0
+    ){
+      /* Functions prohibited in triggers and views if:
+      **     (1) tagged with SQLITE_DIRECTONLY
+      **     (2) not tagged with SQLITE_INNOCUOUS (which means it
+      **         is tagged with SQLITE_FUNC_UNSAFE) and
+      **         SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
+      **         that the schema is possibly tainted).
+      */
+      sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
+    }
+  }
+}
+
+/*
 ** Assign a variable number to an expression that encodes a wildcard
-** in the original SQL statement.  
+** in the original SQL statement.
 **
 ** Wildcards consisting of a single "?" are assigned the next sequential
 ** variable number.
@@ -98818,7 +101561,7 @@ SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
 }
 
 /*
-** Return the number of bytes allocated for the expression structure 
+** Return the number of bytes allocated for the expression structure
 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
 */
@@ -98833,14 +101576,14 @@ static int exprStructSize(Expr *p){
 ** to store a copy of an expression or expression tree.  They differ in
 ** how much of the tree is measured.
 **
-**     dupedExprStructSize()     Size of only the Expr structure 
+**     dupedExprStructSize()     Size of only the Expr structure
 **     dupedExprNodeSize()       Size of Expr + space for token
 **     dupedExprSize()           Expr + token + subtree components
 **
 ***************************************************************************
 **
-** The dupedExprStructSize() function returns two values OR-ed together:  
-** (1) the space required for a copy of the Expr structure only and 
+** The dupedExprStructSize() function returns two values OR-ed together:
+** (1) the space required for a copy of the Expr structure only and
 ** (2) the EP_xxx flags that indicate what the structure size should be.
 ** The return values is always one of:
 **
@@ -98867,7 +101610,7 @@ static int dupedExprStructSize(Expr *p, int flags){
   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
   assert( EXPR_FULLSIZE<=0xfff );
   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
-  if( 0==flags || p->op==TK_SELECT_COLUMN 
+  if( 0==flags || p->op==TK_SELECT_COLUMN
 #ifndef SQLITE_OMIT_WINDOWFUNC
    || ExprHasProperty(p, EP_WinFunc)
 #endif
@@ -98875,9 +101618,9 @@ static int dupedExprStructSize(Expr *p, int flags){
     nSize = EXPR_FULLSIZE;
   }else{
     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
-    assert( !ExprHasProperty(p, EP_FromJoin) ); 
+    assert( !ExprHasProperty(p, EP_FromJoin) );
     assert( !ExprHasProperty(p, EP_MemToken) );
-    assert( !ExprHasProperty(p, EP_NoReduce) );
+    assert( !ExprHasVVAProperty(p, EP_NoReduce) );
     if( p->pLeft || p->x.pList ){
       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
     }else{
@@ -98889,7 +101632,7 @@ static int dupedExprStructSize(Expr *p, int flags){
 }
 
 /*
-** This function returns the space in bytes required to store the copy 
+** This function returns the space in bytes required to store the copy
 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
 ** string is defined.)
 */
@@ -98902,16 +101645,16 @@ static int dupedExprNodeSize(Expr *p, int flags){
 }
 
 /*
-** Return the number of bytes required to create a duplicate of the 
+** Return the number of bytes required to create a duplicate of the
 ** expression passed as the first argument. The second argument is a
 ** mask containing EXPRDUP_XXX flags.
 **
 ** The value returned includes space to create a copy of the Expr struct
 ** itself and the buffer referred to by Expr.u.zToken, if any.
 **
-** If the EXPRDUP_REDUCE flag is set, then the return value includes 
-** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
-** and Expr.pRight variables (but not for any structures pointed to or 
+** If the EXPRDUP_REDUCE flag is set, then the return value includes
+** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
+** and Expr.pRight variables (but not for any structures pointed to or
 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
 */
 static int dupedExprSize(Expr *p, int flags){
@@ -98926,8 +101669,8 @@ static int dupedExprSize(Expr *p, int flags){
 }
 
 /*
-** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
-** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
+** This function is similar to sqlite3ExprDup(), except that if pzBuffer
+** is not NULL then *pzBuffer is assumed to point to a buffer large enough
 ** to store the copy of expression p, the copies of p->u.zToken
 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
 ** if any. Before returning, *pzBuffer is set to the first byte past the
@@ -98973,7 +101716,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
     }else{
       u32 nSize = (u32)exprStructSize(p);
       memcpy(zAlloc, p, nSize);
-      if( nSize<EXPR_FULLSIZE ){ 
+      if( nSize<EXPR_FULLSIZE ){
         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
       }
     }
@@ -98982,6 +101725,10 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
     pNew->flags |= staticFlag;
+    ExprClearVVAProperties(pNew);
+    if( dupFlags ){
+      ExprSetVVAProperty(pNew, EP_Immutable);
+    }
 
     /* Copy the p->u.zToken string, if any. */
     if( nToken ){
@@ -99033,7 +101780,7 @@ static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
 }
 
 /*
-** Create and return a deep copy of the object passed as the second 
+** Create and return a deep copy of the object passed as the second
 ** argument. If an OOM condition is encountered, NULL is returned
 ** and the db->mallocFailed flag set.
 */
@@ -99099,7 +101846,7 @@ static void gatherSelectWindows(Select *p){
 ** without effecting the originals.
 **
 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
-** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
+** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
 ** by subsequent calls to sqlite*ListAppend() routines.
 **
 ** Any tables that the SrcList might point to are not duplicated.
@@ -99129,9 +101876,9 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags)
     Expr *pOldExpr = pOldItem->pExpr;
     Expr *pNewExpr;
     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
-    if( pOldExpr 
+    if( pOldExpr
      && pOldExpr->op==TK_SELECT_COLUMN
-     && (pNewExpr = pItem->pExpr)!=0 
+     && (pNewExpr = pItem->pExpr)!=0
     ){
       assert( pNewExpr->iColumn==0 || i>0 );
       if( pNewExpr->iColumn==0 ){
@@ -99145,12 +101892,11 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags)
         pNewExpr->pLeft = pPriorSelectCol;
       }
     }
-    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
-    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
+    pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
     pItem->sortFlags = pOldItem->sortFlags;
+    pItem->eEName = pOldItem->eEName;
     pItem->done = 0;
     pItem->bNulls = pOldItem->bNulls;
-    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
     pItem->bSorterRef = pOldItem->bSorterRef;
     pItem->u = pOldItem->u;
   }
@@ -99159,7 +101905,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags)
 
 /*
 ** If cursors, triggers, views and subqueries are all omitted from
-** the build, then none of the following routines, except for 
+** the build, then none of the following routines, except for
 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
 ** called with a NULL argument.
 */
@@ -99192,7 +101938,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
     }
     pNewItem->pIBIndex = pOldItem->pIBIndex;
     if( pNewItem->fg.isTabFunc ){
-      pNewItem->u1.pFuncArg = 
+      pNewItem->u1.pFuncArg =
           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
     }
     pTab = pNewItem->pTab = pOldItem->pTab;
@@ -99309,7 +102055,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
     pList->nExpr = 0;
   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
     ExprList *pNew;
-    pNew = sqlite3DbRealloc(db, pList, 
+    pNew = sqlite3DbRealloc(db, pList,
          sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
     if( pNew==0 ){
       goto no_mem;
@@ -99317,13 +102063,13 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
     pList = pNew;
   }
   pItem = &pList->a[pList->nExpr++];
-  assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
+  assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
   assert( offsetof(struct ExprList_item,pExpr)==0 );
-  memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
+  memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
   pItem->pExpr = pExpr;
   return pList;
 
-no_mem:     
+no_mem:
   /* Avoid leaking memory if malloc has failed. */
   sqlite3ExprDelete(db, pExpr);
   sqlite3ExprListDelete(db, pList);
@@ -99356,8 +102102,8 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
   if( NEVER(pColumns==0) ) goto vector_append_error;
   if( pExpr==0 ) goto vector_append_error;
 
-  /* If the RHS is a vector, then we can immediately check to see that 
-  ** the size of the RHS and LHS match.  But if the RHS is a SELECT, 
+  /* If the RHS is a vector, then we can immediately check to see that
+  ** the size of the RHS and LHS match.  But if the RHS is a SELECT,
   ** wildcards ("*") in the result set of the SELECT must be expanded before
   ** we can do the size check, so defer the size check until code generation.
   */
@@ -99376,7 +102122,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
     pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
     if( pList ){
       assert( pList->nExpr==iFirst+i+1 );
-      pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
+      pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
       pColumns->a[i].zName = 0;
     }
   }
@@ -99385,7 +102131,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
     Expr *pFirst = pList->a[iFirst].pExpr;
     assert( pFirst!=0 );
     assert( pFirst->op==TK_SELECT_COLUMN );
-     
+
     /* Store the SELECT statement in pRight so it will be deleted when
     ** sqlite3ExprListDelete() is called */
     pFirst->pRight = pExpr;
@@ -99411,13 +102157,13 @@ SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int
   assert( p->nExpr>0 );
 
   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
-  assert( iSortOrder==SQLITE_SO_UNDEFINED 
-       || iSortOrder==SQLITE_SO_ASC 
-       || iSortOrder==SQLITE_SO_DESC 
+  assert( iSortOrder==SQLITE_SO_UNDEFINED
+       || iSortOrder==SQLITE_SO_ASC
+       || iSortOrder==SQLITE_SO_DESC
   );
-  assert( eNulls==SQLITE_SO_UNDEFINED 
-       || eNulls==SQLITE_SO_ASC 
-       || eNulls==SQLITE_SO_DESC 
+  assert( eNulls==SQLITE_SO_UNDEFINED
+       || eNulls==SQLITE_SO_ASC
+       || eNulls==SQLITE_SO_DESC
   );
 
   pItem = &p->a[p->nExpr-1];
@@ -99436,7 +102182,7 @@ SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int
 }
 
 /*
-** Set the ExprList.a[].zName element of the most recently added item
+** Set the ExprList.a[].zEName element of the most recently added item
 ** on the expression list.
 **
 ** pList might be NULL following an OOM error.  But pName should never be
@@ -99450,15 +102196,22 @@ SQLITE_PRIVATE void sqlite3ExprListSetName(
   int dequote             /* True to cause the name to be dequoted */
 ){
   assert( pList!=0 || pParse->db->mallocFailed!=0 );
+  assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
   if( pList ){
     struct ExprList_item *pItem;
     assert( pList->nExpr>0 );
     pItem = &pList->a[pList->nExpr-1];
-    assert( pItem->zName==0 );
-    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
-    if( dequote ) sqlite3Dequote(pItem->zName);
-    if( IN_RENAME_OBJECT ){
-      sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
+    assert( pItem->zEName==0 );
+    assert( pItem->eEName==ENAME_NAME );
+    pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
+    if( dequote ){
+      /* If dequote==0, then pName->z does not point to part of a DDL
+      ** statement handled by the parser. And so no token need be added
+      ** to the token-map.  */
+      sqlite3Dequote(pItem->zEName);
+      if( IN_RENAME_OBJECT ){
+        sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
+      }
     }
   }
 }
@@ -99482,8 +102235,10 @@ SQLITE_PRIVATE void sqlite3ExprListSetSpan(
   if( pList ){
     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
     assert( pList->nExpr>0 );
-    sqlite3DbFree(db, pItem->zSpan);
-    pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
+    if( pItem->zEName==0 ){
+      pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
+      pItem->eEName = ENAME_SPAN;
+    }
   }
 }
 
@@ -99513,8 +102268,7 @@ static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
   assert( pList->nExpr>0 );
   do{
     sqlite3ExprDelete(db, pItem->pExpr);
-    sqlite3DbFree(db, pItem->zName);
-    sqlite3DbFree(db, pItem->zSpan);
+    sqlite3DbFree(db, pItem->zEName);
     pItem++;
   }while( --i>0 );
   sqlite3DbFreeNN(db, pList);
@@ -99553,18 +102307,33 @@ SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
 }
 
 /*
+** Check the input string to see if it is "true" or "false" (in any case).
+**
+**       If the string is....           Return
+**         "true"                         EP_IsTrue
+**         "false"                        EP_IsFalse
+**         anything else                  0
+*/
+SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){
+  if( sqlite3StrICmp(zIn, "true")==0  ) return EP_IsTrue;
+  if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
+  return 0;
+}
+
+
+/*
 ** If the input expression is an ID with the name "true" or "false"
 ** then convert it into an TK_TRUEFALSE term.  Return non-zero if
 ** the conversion happened, and zero if the expression is unaltered.
 */
 SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
+  u32 v;
   assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
   if( !ExprHasProperty(pExpr, EP_Quoted)
-   && (sqlite3StrICmp(pExpr->u.zToken, "true")==0
-       || sqlite3StrICmp(pExpr->u.zToken, "false")==0)
+   && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
   ){
     pExpr->op = TK_TRUEFALSE;
-    ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse);
+    ExprSetProperty(pExpr, v);
     return 1;
   }
   return 0;
@@ -99626,11 +102395,12 @@ SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
 ** is found to not be a constant.
 **
-** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
-** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
-** an existing schema and 4 when processing a new statement.  A bound
-** parameter raises an error for new statements, but is silently converted
-** to NULL for existing schemas.  This allows sqlite_master tables that 
+** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
+** expressions in a CREATE TABLE statement.  The Walker.eCode value is 5
+** when parsing an existing schema out of the sqlite_schema table and 4
+** when processing a new CREATE TABLE statement.  A bound parameter raises
+** an error for new statements, but is silently converted
+** to NULL for existing schemas.  This allows sqlite_schema tables that
 ** contain a bound parameter because they were generated by older versions
 ** of SQLite to be parsed by newer versions of SQLite without raising a
 ** malformed schema error.
@@ -99650,7 +102420,10 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
     ** and either pWalker->eCode==4 or 5 or the function has the
     ** SQLITE_FUNC_CONST flag. */
     case TK_FUNCTION:
-      if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
+      if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
+       && !ExprHasProperty(pExpr, EP_WinFunc)
+      ){
+        if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
         return WRC_Continue;
       }else{
         pWalker->eCode = 0;
@@ -99662,7 +102435,7 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
       if( sqlite3ExprIdToTrueFalse(pExpr) ){
         return WRC_Prune;
       }
-      /* Fall thru */
+      /* no break */ deliberate_fall_through
     case TK_COLUMN:
     case TK_AGG_FUNCTION:
     case TK_AGG_COLUMN:
@@ -99676,18 +102449,20 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
         return WRC_Continue;
       }
-      /* Fall through */
+      /* no break */ deliberate_fall_through
     case TK_IF_NULL_ROW:
     case TK_REGISTER:
+    case TK_DOT:
       testcase( pExpr->op==TK_REGISTER );
       testcase( pExpr->op==TK_IF_NULL_ROW );
+      testcase( pExpr->op==TK_DOT );
       pWalker->eCode = 0;
       return WRC_Abort;
     case TK_VARIABLE:
       if( pWalker->eCode==5 ){
         /* Silently convert bound parameters that appear inside of CREATE
         ** statements into a NULL when parsing the CREATE statement text out
-        ** of the sqlite_master table */
+        ** of the sqlite_schema table */
         pExpr->op = TK_NULL;
       }else if( pWalker->eCode==4 ){
         /* A bound parameter in a CREATE statement that originates from
@@ -99695,7 +102470,7 @@ static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
         pWalker->eCode = 0;
         return WRC_Abort;
       }
-      /* Fall through */
+      /* no break */ deliberate_fall_through
     default:
       testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
       testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
@@ -99738,7 +102513,7 @@ SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
 **
 ** When this routine returns true, it indicates that the expression
 ** can be added to the pParse->pConstExpr list and evaluated once when
-** the prepared statement starts up.  See sqlite3ExprCodeAtInit().
+** the prepared statement starts up.  See sqlite3ExprCodeRunJustOnce().
 */
 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
   return exprIsConst(p, 2, 0);
@@ -99785,7 +102560,7 @@ static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
 
 /*
 ** Walk the expression tree passed as the first argument. Return non-zero
-** if the expression consists entirely of constants or copies of terms 
+** if the expression consists entirely of constants or copies of terms
 ** in pGroupBy that sort with the BINARY collation sequence.
 **
 ** This routine is used to determine if a term of the HAVING clause can
@@ -99814,9 +102589,21 @@ SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprLi
 }
 
 /*
-** Walk an expression tree.  Return non-zero if the expression is constant
-** or a function call with constant arguments.  Return and 0 if there
-** are any variables.
+** Walk an expression tree for the DEFAULT field of a column definition
+** in a CREATE TABLE statement.  Return non-zero if the expression is
+** acceptable for use as a DEFAULT.  That is to say, return non-zero if
+** the expression is constant or a function call with constant arguments.
+** Return and 0 if there are any variables.
+**
+** isInit is true when parsing from sqlite_schema.  isInit is false when
+** processing a new CREATE TABLE statement.  When isInit is true, parameters
+** (such as ? or $abc) in the expression are converted into NULL.  When
+** isInit is false, parameters raise an error.  Parameters should not be
+** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
+** allowed it, so we need to support it when reading sqlite_schema for
+** backwards compatibility.
+**
+** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
 **
 ** For the purposes of this function, a double-quoted string (ex: "abc")
 ** is considered a variable but a single-quoted string (ex: 'abc') is
@@ -99887,7 +102674,7 @@ SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
 ** Return FALSE if there is no chance that the expression can be NULL.
 **
 ** If the expression might be NULL or if the expression is too complex
-** to tell return TRUE.  
+** to tell return TRUE.
 **
 ** This routine is used as an optimization, to skip OP_IsNull opcodes
 ** when we know that a value cannot be NULL.  Hence, a false positive
@@ -99913,7 +102700,9 @@ SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
     case TK_COLUMN:
       return ExprHasProperty(p, EP_CanBeNull) ||
              p->y.pTab==0 ||  /* Reference to column of index on expression */
-             (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0);
+             (p->iColumn>=0
+              && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
+              && p->y.pTab->aCol[p->iColumn].notNull==0);
     default:
       return 1;
   }
@@ -99973,7 +102762,7 @@ SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
 }
 
 /*
-** pX is the RHS of an IN operator.  If pX is a SELECT statement 
+** pX is the RHS of an IN operator.  If pX is a SELECT statement
 ** that can be simplified to a direct table access, then return
 ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
 ** or if the SELECT statement needs to be manifested into a transient
@@ -100039,7 +102828,7 @@ static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
 
 #ifndef SQLITE_OMIT_SUBQUERY
 /*
-** The argument is an IN operator with a list (not a subquery) on the 
+** The argument is an IN operator with a list (not a subquery) on the
 ** right-hand side.  Return TRUE if that list is constant.
 */
 static int sqlite3InRhsIsConstant(Expr *pIn){
@@ -100098,9 +102887,9 @@ static int sqlite3InRhsIsConstant(Expr *pIn){
 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
 ** a UNIQUE constraint or index.
 **
-** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
-** for fast set membership tests) then an epheremal table must 
-** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 
+** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
+** for fast set membership tests) then an epheremal table must
+** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
 ** index can be found with the specified <columns> as its left-most.
 **
 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
@@ -100112,7 +102901,7 @@ static int sqlite3InRhsIsConstant(Expr *pIn){
 **
 ** When the b-tree is being used for membership tests, the calling function
 ** might need to know whether or not the RHS side of the IN operator
-** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
+** contains a NULL.  If prRhsHasNull is not a NULL pointer and
 ** if there is any chance that the (...) might contain a NULL value at
 ** runtime, then a register is allocated and the register number written
 ** to *prRhsHasNull. If there is no chance that the (...) contains a
@@ -100152,9 +102941,9 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
   assert( pX->op==TK_IN );
   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
 
-  /* If the RHS of this IN(...) operator is a SELECT, and if it matters 
+  /* If the RHS of this IN(...) operator is a SELECT, and if it matters
   ** whether or not the SELECT result contains NULL values, check whether
-  ** or not NULL is actually possible (it may not be, for example, due 
+  ** or not NULL is actually possible (it may not be, for example, due
   ** to NOT NULL constraints in the schema). If no NULL values are possible,
   ** set prRhsHasNull to 0 before continuing.  */
   if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
@@ -100169,12 +102958,12 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
   }
 
   /* Check to see if an existing table or index can be used to
-  ** satisfy the query.  This is preferable to generating a new 
+  ** satisfy the query.  This is preferable to generating a new
   ** ephemeral table.  */
   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
     sqlite3 *db = pParse->db;              /* Database connection */
     Table *pTab;                           /* Table <table>. */
-    i16 iDb;                               /* Database idx for pTab */
+    int iDb;                               /* Database idx for pTab */
     ExprList *pEList = p->pEList;
     int nExpr = pEList->nExpr;
 
@@ -100185,6 +102974,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
 
     /* Code an OP_Transaction and OP_TableLock for <table>. */
     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+    assert( iDb>=0 && iDb<SQLITE_MAX_ATTACHED );
     sqlite3CodeVerifySchema(pParse, iDb);
     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
 
@@ -100204,7 +102994,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
       int affinity_ok = 1;
       int i;
 
-      /* Check that the affinity that will be used to perform each 
+      /* Check that the affinity that will be used to perform each
       ** comparison is the same as the affinity of each column in table
       ** on the RHS of the IN operator.  If it not, it is not possible to
       ** use any index of the RHS table.  */
@@ -100249,14 +103039,14 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
               continue;  /* This index is not unique over the IN RHS columns */
             }
           }
-  
+
           colUsed = 0;   /* Columns of index used so far */
           for(i=0; i<nExpr; i++){
             Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
             Expr *pRhs = pEList->a[i].pExpr;
             CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
             int j;
-  
+
             assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
             for(j=0; j<nExpr; j++){
               if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
@@ -100272,7 +103062,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
             colUsed |= mCol;
             if( aiMap ) aiMap[i] = j;
           }
-  
+
           assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
           if( colUsed==(MASKBIT(nExpr)-1) ){
             /* If we reach this point, that means the index pIdx is usable */
@@ -100284,11 +103074,11 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
             VdbeComment((v, "%s", pIdx->zName));
             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
-  
+
             if( prRhsHasNull ){
 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
               i64 mask = (1<<nExpr)-1;
-              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 
+              sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
                   iTab, 0, 0, (u8*)&mask, P4_INT64);
 #endif
               *prRhsHasNull = ++pParse->nMem;
@@ -100350,8 +103140,8 @@ SQLITE_PRIVATE int sqlite3FindInIndex(
 
 #ifndef SQLITE_OMIT_SUBQUERY
 /*
-** Argument pExpr is an (?, ?...) IN(...) expression. This 
-** function allocates and returns a nul-terminated string containing 
+** Argument pExpr is an (?, ?...) IN(...) expression. This
+** function allocates and returns a nul-terminated string containing
 ** the affinities to be used for each column of the comparison.
 **
 ** It is the responsibility of the caller to ensure that the returned
@@ -100384,20 +103174,22 @@ static char *exprINAffinity(Parse *pParse, Expr *pExpr){
 
 #ifndef SQLITE_OMIT_SUBQUERY
 /*
-** Load the Parse object passed as the first argument with an error 
+** Load the Parse object passed as the first argument with an error
 ** message of the form:
 **
 **   "sub-select returns N columns - expected M"
-*/   
+*/
 SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
-  const char *zFmt = "sub-select returns %d columns - expected %d";
-  sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
+  if( pParse->nErr==0 ){
+    const char *zFmt = "sub-select returns %d columns - expected %d";
+    sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
+  }
 }
 #endif
 
 /*
 ** Expression pExpr is a vector that has been used in a context where
-** it is not permitted. If pExpr is a sub-select vector, this routine 
+** it is not permitted. If pExpr is a sub-select vector, this routine
 ** loads the Parse object with a message of the form:
 **
 **   "sub-select returns N columns - expected 1"
@@ -100405,7 +103197,7 @@ SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpec
 ** Or, if it is a regular scalar vector:
 **
 **   "row value misused"
-*/   
+*/
 SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
 #ifndef SQLITE_OMIT_SUBQUERY
   if( pExpr->flags & EP_xIsSelect ){
@@ -100468,7 +103260,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
   if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
     /* Reuse of the RHS is allowed */
     /* If this routine has already been coded, but the previous code
-    ** might not have been invoked yet, so invoke it now as a subroutine. 
+    ** might not have been invoked yet, so invoke it now as a subroutine.
     */
     if( ExprHasProperty(pExpr, EP_Subrtn) ){
       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
@@ -100485,6 +103277,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
 
     /* Begin coding the subroutine */
     ExprSetProperty(pExpr, EP_Subrtn);
+    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
     pExpr->y.sub.regReturn = ++pParse->nMem;
     pExpr->y.sub.iAddr =
       sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
@@ -100566,6 +103359,8 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
     affinity = sqlite3ExprAffinity(pLeft);
     if( affinity<=SQLITE_AFF_NONE ){
       affinity = SQLITE_AFF_BLOB;
+    }else if( affinity==SQLITE_AFF_REAL ){
+      affinity = SQLITE_AFF_NUMERIC;
     }
     if( pKeyInfo ){
       assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
@@ -100619,7 +103414,7 @@ SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
 **
 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
 **
-** Return the register that holds the result.  For a multi-column SELECT, 
+** Return the register that holds the result.  For a multi-column SELECT,
 ** the result is stored in a contiguous array of registers and the
 ** return value is the register of the left-most result column.
 ** Return 0 if an error occurs.
@@ -100670,7 +103465,7 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
 
     addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
   }
-  
+
   /* For a SELECT, generate code to put the values for all columns of
   ** the first row into an array of registers and return the index of
   ** the first register.
@@ -100678,7 +103473,7 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
   ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
   ** into a register and return that register number.
   **
-  ** In both cases, the query is augmented with "LIMIT 1".  Any 
+  ** In both cases, the query is augmented with "LIMIT 1".  Any
   ** preexisting limit is discarded in place of the new LIMIT 1.
   */
   ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
@@ -100735,9 +103530,9 @@ SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
 
 #ifndef SQLITE_OMIT_SUBQUERY
 /*
-** Expr pIn is an IN(...) expression. This function checks that the 
-** sub-select on the RHS of the IN() operator has the same number of 
-** columns as the vector on the LHS. Or, if the RHS of the IN() is not 
+** Expr pIn is an IN(...) expression. This function checks that the
+** sub-select on the RHS of the IN() operator has the same number of
+** columns as the vector on the LHS. Or, if the RHS of the IN() is not
 ** a sub-query, that the LHS is a vector of size 1.
 */
 SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
@@ -100762,18 +103557,18 @@ SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
 **      x IN (SELECT ...)
 **      x IN (value, value, ...)
 **
-** The left-hand side (LHS) is a scalar or vector expression.  The 
+** The left-hand side (LHS) is a scalar or vector expression.  The
 ** right-hand side (RHS) is an array of zero or more scalar values, or a
 ** subquery.  If the RHS is a subquery, the number of result columns must
 ** match the number of columns in the vector on the LHS.  If the RHS is
-** a list of values, the LHS must be a scalar. 
+** a list of values, the LHS must be a scalar.
 **
 ** The IN operator is true if the LHS value is contained within the RHS.
-** The result is false if the LHS is definitely not in the RHS.  The 
-** result is NULL if the presence of the LHS in the RHS cannot be 
+** The result is false if the LHS is definitely not in the RHS.  The
+** result is NULL if the presence of the LHS in the RHS cannot be
 ** determined due to NULLs.
 **
-** This routine generates code that jumps to destIfFalse if the LHS is not 
+** This routine generates code that jumps to destIfFalse if the LHS is not
 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
 ** within the RHS then fall through.
@@ -100802,9 +103597,10 @@ static void sqlite3ExprCodeIN(
   int destStep6 = 0;    /* Start of code for Step 6 */
   int addrTruthOp;      /* Address of opcode that determines the IN is true */
   int destNotNull;      /* Jump here if a comparison is not true in step 6 */
-  int addrTop;          /* Top of the step-6 loop */ 
+  int addrTop;          /* Top of the step-6 loop */
   int iTab = 0;         /* Index to use */
 
+  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
   pLeft = pExpr->pLeft;
   if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
   zAff = exprINAffinity(pParse, pExpr);
@@ -100827,7 +103623,7 @@ static void sqlite3ExprCodeIN(
                              aiMap, &iTab);
 
   assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
-       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 
+       || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
   );
 #ifdef SQLITE_DEBUG
   /* Confirm that aiMap[] contains nVector integer values between 0 and
@@ -100839,8 +103635,8 @@ static void sqlite3ExprCodeIN(
   }
 #endif
 
-  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 
-  ** vector, then it is stored in an array of nVector registers starting 
+  /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
+  ** vector, then it is stored in an array of nVector registers starting
   ** at r1.
   **
   ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
@@ -100874,37 +103670,35 @@ static void sqlite3ExprCodeIN(
     int r2, regToFree;
     int regCkNull = 0;
     int ii;
-    int bLhsReal;  /* True if the LHS of the IN has REAL affinity */
     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
     if( destIfNull!=destIfFalse ){
       regCkNull = sqlite3GetTempReg(pParse);
       sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
     }
-    bLhsReal = sqlite3ExprAffinity(pExpr->pLeft)==SQLITE_AFF_REAL;
     for(ii=0; ii<pList->nExpr; ii++){
-      if( bLhsReal ){
-        r2 = regToFree = sqlite3GetTempReg(pParse);
-        sqlite3ExprCode(pParse, pList->a[ii].pExpr, r2);
-        sqlite3VdbeAddOp4(v, OP_Affinity, r2, 1, 0, "E", P4_STATIC);
-      }else{
-        r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
-      }
+      r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
       }
+      sqlite3ReleaseTempReg(pParse, regToFree);
       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
-        sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
+        int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
+        sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
                           (void*)pColl, P4_COLLSEQ);
-        VdbeCoverageIf(v, ii<pList->nExpr-1);
-        VdbeCoverageIf(v, ii==pList->nExpr-1);
+        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
+        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
+        VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
+        VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
         sqlite3VdbeChangeP5(v, zAff[0]);
       }else{
+        int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
         assert( destIfNull==destIfFalse );
-        sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
-                          (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
+        sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
+                          (void*)pColl, P4_COLLSEQ);
+        VdbeCoverageIf(v, op==OP_Ne);
+        VdbeCoverageIf(v, op==OP_IsNull);
         sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
       }
-      sqlite3ReleaseTempReg(pParse, regToFree);
     }
     if( regCkNull ){
       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
@@ -100924,6 +103718,7 @@ static void sqlite3ExprCodeIN(
   }else{
     destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
   }
+  if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
   for(i=0; i<nVector; i++){
     Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
     if( sqlite3ExprCanBeNull(p) ){
@@ -100965,7 +103760,7 @@ static void sqlite3ExprCodeIN(
   }
 
   /* Step 5.  If we do not care about the difference between NULL and
-  ** FALSE, then just return false. 
+  ** FALSE, then just return false.
   */
   if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
 
@@ -101026,7 +103821,7 @@ sqlite3ExprCodeIN_oom_error:
 ** Generate an instruction that will put the floating point
 ** value described by z[0..n-1] into register iMem.
 **
-** The z[] string will probably not be zero-terminated.  But the 
+** The z[] string will probably not be zero-terminated.  But the
 ** z[n] character is guaranteed to be something that does not look
 ** like the continuation of the number.
 */
@@ -101105,16 +103900,45 @@ SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
   }
 }
 
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/*
+** Generate code that will compute the value of generated column pCol
+** and store the result in register regOut
+*/
+SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
+  Parse *pParse,
+  Column *pCol,
+  int regOut
+){
+  int iAddr;
+  Vdbe *v = pParse->pVdbe;
+  assert( v!=0 );
+  assert( pParse->iSelfTab!=0 );
+  if( pParse->iSelfTab>0 ){
+    iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
+  }else{
+    iAddr = 0;
+  }
+  sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
+  if( pCol->affinity>=SQLITE_AFF_TEXT ){
+    sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
+  }
+  if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
 /*
 ** Generate code to extract the value of the iCol-th column of a table.
 */
 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
-  Vdbe *v,        /* The VDBE under construction */
+  Vdbe *v,        /* Parsing context */
   Table *pTab,    /* The table containing the value */
   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
   int iCol,       /* Index of the column to extract */
   int regOut      /* Extract the value into this register */
 ){
+  Column *pCol;
+  assert( v!=0 );
   if( pTab==0 ){
     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
     return;
@@ -101122,21 +103946,43 @@ SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
   if( iCol<0 || iCol==pTab->iPKey ){
     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
   }else{
-    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
-    int x = iCol;
-    if( !HasRowid(pTab) && !IsVirtual(pTab) ){
-      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
+    int op;
+    int x;
+    if( IsVirtual(pTab) ){
+      op = OP_VColumn;
+      x = iCol;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
+      Parse *pParse = sqlite3VdbeParser(v);
+      if( pCol->colFlags & COLFLAG_BUSY ){
+        sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
+      }else{
+        int savedSelfTab = pParse->iSelfTab;
+        pCol->colFlags |= COLFLAG_BUSY;
+        pParse->iSelfTab = iTabCur+1;
+        sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
+        pParse->iSelfTab = savedSelfTab;
+        pCol->colFlags &= ~COLFLAG_BUSY;
+      }
+      return;
+#endif
+    }else if( !HasRowid(pTab) ){
+      testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
+      x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
+      op = OP_Column;
+    }else{
+      x = sqlite3TableColumnToStorage(pTab,iCol);
+      testcase( x!=iCol );
+      op = OP_Column;
     }
     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
-  }
-  if( iCol>=0 ){
     sqlite3ColumnDefault(v, pTab, iCol, regOut);
   }
 }
 
 /*
 ** Generate code that will extract the iColumn-th column from
-** table pTab and store the column value in register iReg. 
+** table pTab and store the column value in register iReg.
 **
 ** There must be an open cursor to pTab in iTable when this routine
 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
@@ -101149,11 +103995,11 @@ SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
   int iReg,        /* Store results here */
   u8 p5            /* P5 value for OP_Column + FLAGS */
 ){
-  Vdbe *v = pParse->pVdbe;
-  assert( v!=0 );
-  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
+  assert( pParse->pVdbe!=0 );
+  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
   if( p5 ){
-    sqlite3VdbeChangeP5(v, p5);
+    VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
+    if( pOp->opcode==OP_Column ) pOp->p5 = p5;
   }
   return iReg;
 }
@@ -101163,7 +104009,6 @@ SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
 ** over to iTo..iTo+nReg-1.
 */
 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
-  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
 }
 
@@ -101174,6 +104019,7 @@ SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int n
 */
 static void exprToRegister(Expr *pExpr, int iReg){
   Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
+  if( NEVER(p==0) ) return;
   p->op2 = p->op;
   p->op = TK_REGISTER;
   p->iTable = iReg;
@@ -101215,6 +104061,124 @@ static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
   return iResult;
 }
 
+/*
+** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
+** so that a subsequent copy will not be merged into this one.
+*/
+static void setDoNotMergeFlagOnCopy(Vdbe *v){
+  if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
+    sqlite3VdbeChangeP5(v, 1);  /* Tag trailing OP_Copy as not mergable */
+  }
+}
+
+/*
+** Generate code to implement special SQL functions that are implemented
+** in-line rather than by using the usual callbacks.
+*/
+static int exprCodeInlineFunction(
+  Parse *pParse,        /* Parsing context */
+  ExprList *pFarg,      /* List of function arguments */
+  int iFuncId,          /* Function ID.  One of the INTFUNC_... values */
+  int target            /* Store function result in this register */
+){
+  int nFarg;
+  Vdbe *v = pParse->pVdbe;
+  assert( v!=0 );
+  assert( pFarg!=0 );
+  nFarg = pFarg->nExpr;
+  assert( nFarg>0 );  /* All in-line functions have at least one argument */
+  switch( iFuncId ){
+    case INLINEFUNC_coalesce: {
+      /* Attempt a direct implementation of the built-in COALESCE() and
+      ** IFNULL() functions.  This avoids unnecessary evaluation of
+      ** arguments past the first non-NULL argument.
+      */
+      int endCoalesce = sqlite3VdbeMakeLabel(pParse);
+      int i;
+      assert( nFarg>=2 );
+      sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
+      for(i=1; i<nFarg; i++){
+        sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
+        VdbeCoverage(v);
+        sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
+      }
+      setDoNotMergeFlagOnCopy(v);
+      sqlite3VdbeResolveLabel(v, endCoalesce);
+      break;
+    }
+    case INLINEFUNC_iif: {
+      Expr caseExpr;
+      memset(&caseExpr, 0, sizeof(caseExpr));
+      caseExpr.op = TK_CASE;
+      caseExpr.x.pList = pFarg;
+      return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
+    }
+
+    default: {
+      /* The UNLIKELY() function is a no-op.  The result is the value
+      ** of the first argument.
+      */
+      assert( nFarg==1 || nFarg==2 );
+      target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
+      break;
+    }
+
+  /***********************************************************************
+  ** Test-only SQL functions that are only usable if enabled
+  ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
+  */
+    case INLINEFUNC_expr_compare: {
+      /* Compare two expressions using sqlite3ExprCompare() */
+      assert( nFarg==2 );
+      sqlite3VdbeAddOp2(v, OP_Integer,
+         sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
+         target);
+      break;
+    }
+
+    case INLINEFUNC_expr_implies_expr: {
+      /* Compare two expressions using sqlite3ExprImpliesExpr() */
+      assert( nFarg==2 );
+      sqlite3VdbeAddOp2(v, OP_Integer,
+         sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
+         target);
+      break;
+    }
+
+    case INLINEFUNC_implies_nonnull_row: {
+      /* REsult of sqlite3ExprImpliesNonNullRow() */
+      Expr *pA1;
+      assert( nFarg==2 );
+      pA1 = pFarg->a[1].pExpr;
+      if( pA1->op==TK_COLUMN ){
+        sqlite3VdbeAddOp2(v, OP_Integer,
+           sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
+           target);
+      }else{
+        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+      }
+      break;
+    }
+
+#ifdef SQLITE_DEBUG
+    case INLINEFUNC_affinity: {
+      /* The AFFINITY() function evaluates to a string that describes
+      ** the type affinity of the argument.  This is used for testing of
+      ** the SQLite type logic.
+      */
+      const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
+      char aff;
+      assert( nFarg==1 );
+      aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
+      sqlite3VdbeLoadString(v, target,
+              (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
+      break;
+    }
+#endif
+  }
+  return target;
+}
+
 
 /*
 ** Generate code into the current Vdbe to evaluate the given
@@ -101238,33 +104202,45 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target)
   int p5 = 0;
 
   assert( target>0 && target<=pParse->nMem );
-  if( v==0 ){
-    assert( pParse->db->mallocFailed );
-    return 0;
-  }
+  assert( v!=0 );
 
 expr_code_doover:
   if( pExpr==0 ){
     op = TK_NULL;
   }else{
+    assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
     op = pExpr->op;
   }
   switch( op ){
     case TK_AGG_COLUMN: {
       AggInfo *pAggInfo = pExpr->pAggInfo;
-      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
+      struct AggInfo_col *pCol;
+      assert( pAggInfo!=0 );
+      assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
+      pCol = &pAggInfo->aCol[pExpr->iAgg];
       if( !pAggInfo->directMode ){
         assert( pCol->iMem>0 );
         return pCol->iMem;
       }else if( pAggInfo->useSortingIdx ){
+        Table *pTab = pCol->pTab;
         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
                               pCol->iSorterColumn, target);
+        if( pCol->iColumn<0 ){
+          VdbeComment((v,"%s.rowid",pTab->zName));
+        }else{
+          VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
+          if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
+            sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
+          }
+        }
         return target;
       }
       /* Otherwise, fall thru into the TK_COLUMN case */
+      /* no break */ deliberate_fall_through
     }
     case TK_COLUMN: {
       int iTab = pExpr->iTable;
+      int iReg;
       if( ExprHasProperty(pExpr, EP_FixedCol) ){
         /* This COLUMN expression is really a constant due to WHERE clause
         ** constraints, and that constant is coded by the pExpr->pLeft
@@ -101272,16 +104248,17 @@ expr_code_doover:
         ** datatype by applying the Affinity of the table column to the
         ** constant.
         */
-        int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
-        int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
+        int aff;
+        iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
+        if( pExpr->y.pTab ){
+          aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
+        }else{
+          aff = pExpr->affExpr;
+        }
         if( aff>SQLITE_AFF_BLOB ){
           static const char zAff[] = "B\000C\000D\000E";
           assert( SQLITE_AFF_BLOB=='A' );
           assert( SQLITE_AFF_TEXT=='B' );
-          if( iReg!=target ){
-            sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
-            iReg = target;
-          }
           sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
                             &zAff[(aff-'B')*2], P4_STATIC);
         }
@@ -101289,19 +104266,46 @@ expr_code_doover:
       }
       if( iTab<0 ){
         if( pParse->iSelfTab<0 ){
-          /* Generating CHECK constraints or inserting into partial index */
-          assert( pExpr->y.pTab!=0 );
-          assert( pExpr->iColumn>=XN_ROWID );
-          assert( pExpr->iColumn<pExpr->y.pTab->nCol );
-          if( pExpr->iColumn>=0
-            && pExpr->y.pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
-          ){
-            sqlite3VdbeAddOp2(v, OP_SCopy, pExpr->iColumn - pParse->iSelfTab,
-                              target);
+          /* Other columns in the same row for CHECK constraints or
+          ** generated columns or for inserting into partial index.
+          ** The row is unpacked into registers beginning at
+          ** 0-(pParse->iSelfTab).  The rowid (if any) is in a register
+          ** immediately prior to the first column.
+          */
+          Column *pCol;
+          Table *pTab = pExpr->y.pTab;
+          int iSrc;
+          int iCol = pExpr->iColumn;
+          assert( pTab!=0 );
+          assert( iCol>=XN_ROWID );
+          assert( iCol<pTab->nCol );
+          if( iCol<0 ){
+            return -1-pParse->iSelfTab;
+          }
+          pCol = pTab->aCol + iCol;
+          testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
+          iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+          if( pCol->colFlags & COLFLAG_GENERATED ){
+            if( pCol->colFlags & COLFLAG_BUSY ){
+              sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
+                              pCol->zName);
+              return 0;
+            }
+            pCol->colFlags |= COLFLAG_BUSY;
+            if( pCol->colFlags & COLFLAG_NOTAVAIL ){
+              sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
+            }
+            pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
+            return iSrc;
+          }else
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+          if( pCol->affinity==SQLITE_AFF_REAL ){
+            sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
             sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
             return target;
           }else{
-            return pExpr->iColumn - pParse->iSelfTab;
+            return iSrc;
           }
         }else{
           /* Coding an expression that is part of an index where column names
@@ -101309,9 +104313,13 @@ expr_code_doover:
           iTab = pParse->iSelfTab - 1;
         }
       }
-      return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
+      iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
                                pExpr->iColumn, iTab, target,
                                pExpr->op2);
+      if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
+        sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
+      }
+      return iReg;
     }
     case TK_INTEGER: {
       codeInteger(pParse, pExpr, 0, target);
@@ -101333,7 +104341,12 @@ expr_code_doover:
       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
       return target;
     }
-    case TK_NULL: {
+    default: {
+      /* Make NULL the default case so that if a bug causes an illegal
+      ** Expr node to be passed into this function, it will be handled
+      ** sanely and not crash.  But keep the assert() to bring the problem
+      ** to the attention of the developers. */
+      assert( op==TK_NULL );
       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
       return target;
     }
@@ -101360,7 +104373,7 @@ expr_code_doover:
       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
       if( pExpr->u.zToken[1]!=0 ){
         const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
-        assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
+        assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
         pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
         sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
       }
@@ -101400,7 +104413,8 @@ expr_code_doover:
         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
         codeCompare(pParse, pLeft, pExpr->pRight, op,
-            r1, r2, inReg, SQLITE_STOREP2 | p5);
+            r1, r2, inReg, SQLITE_STOREP2 | p5,
+            ExprHasProperty(pExpr,EP_Commuted));
         assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
         assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
         assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
@@ -101422,7 +104436,7 @@ expr_code_doover:
     case TK_BITOR:
     case TK_SLASH:
     case TK_LSHIFT:
-    case TK_RSHIFT: 
+    case TK_RSHIFT:
     case TK_CONCAT: {
       assert( TK_AND==OP_And );            testcase( op==TK_AND );
       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
@@ -101458,6 +104472,7 @@ expr_code_doover:
         tempX.op = TK_INTEGER;
         tempX.flags = EP_IntValue|EP_TokenOnly;
         tempX.u.iValue = 0;
+        ExprClearVVAProperties(&tempX);
         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
@@ -101503,7 +104518,10 @@ expr_code_doover:
     }
     case TK_AGG_FUNCTION: {
       AggInfo *pInfo = pExpr->pAggInfo;
-      if( pInfo==0 ){
+      if( pInfo==0
+       || NEVER(pExpr->iAgg<0)
+       || NEVER(pExpr->iAgg>=pInfo->nFunc)
+      ){
         assert( !ExprHasProperty(pExpr, EP_IntValue) );
         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
       }else{
@@ -101529,16 +104547,13 @@ expr_code_doover:
 #endif
 
       if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
-        /* SQL functions can be expensive. So try to move constant functions
-        ** out of the inner loop, even if that means an extra OP_Copy. */
-        return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
+        /* SQL functions can be expensive. So try to avoid running them
+        ** multiple times if we know they always give the same result */
+        return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
       }
       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
-      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
-        pFarg = 0;
-      }else{
-        pFarg = pExpr->x.pList;
-      }
+      assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
+      pFarg = pExpr->x.pList;
       nFarg = pFarg ? pFarg->nExpr : 0;
       assert( !ExprHasProperty(pExpr, EP_IntValue) );
       zId = pExpr->u.zToken;
@@ -101552,48 +104567,15 @@ expr_code_doover:
         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
         break;
       }
-
-      /* Attempt a direct implementation of the built-in COALESCE() and
-      ** IFNULL() functions.  This avoids unnecessary evaluation of
-      ** arguments past the first non-NULL argument.
-      */
-      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
-        int endCoalesce = sqlite3VdbeMakeLabel(pParse);
-        assert( nFarg>=2 );
-        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
-        for(i=1; i<nFarg; i++){
-          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
-          VdbeCoverage(v);
-          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
-        }
-        sqlite3VdbeResolveLabel(v, endCoalesce);
-        break;
+      if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
+        assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
+        assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
+        return exprCodeInlineFunction(pParse, pFarg,
+             SQLITE_PTR_TO_INT(pDef->pUserData), target);
+      }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
+        sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
       }
 
-      /* The UNLIKELY() function is a no-op.  The result is the value
-      ** of the first argument.
-      */
-      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
-        assert( nFarg>=1 );
-        return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
-      }
-
-#ifdef SQLITE_DEBUG
-      /* The AFFINITY() function evaluates to a string that describes
-      ** the type affinity of the argument.  This is used for testing of
-      ** the SQLite type logic.
-      */
-      if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
-        const char *const azAff[] = { "blob", "text", "numeric", "integer", "real" };
-        char aff;
-        assert( nFarg==1 );
-        aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
-        sqlite3VdbeLoadString(v, target, 
-                (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
-        return target;
-      }
-#endif
-
       for(i=0; i<nFarg; i++){
         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
           testcase( i==31 );
@@ -101625,7 +104607,7 @@ expr_code_doover:
             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
-            pFarg->a[0].pExpr->op2 = 
+            pFarg->a[0].pExpr->op2 =
                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
           }
         }
@@ -101644,7 +104626,7 @@ expr_code_doover:
       ** see if it is a column in a virtual table.  This is done because
       ** the left operand of infix functions (the operand we want to
       ** control overloading) ends up as the second argument to the
-      ** function.  The expression "A glob B" is equivalent to 
+      ** function.  The expression "A glob B" is equivalent to
       ** "glob(B,A).  We want to use the A in "A glob B" to test
       ** for function overloading.  But we use the B term in "glob(B,A)".
       */
@@ -101655,7 +104637,7 @@ expr_code_doover:
       }
 #endif
       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
-        if( !pColl ) pColl = db->pDfltColl; 
+        if( !pColl ) pColl = db->pDfltColl;
         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
       }
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
@@ -101669,12 +104651,15 @@ expr_code_doover:
       }else
 #endif
       {
-        sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
-                          constMask, r1, target, (char*)pDef, P4_FUNCDEF);
-        sqlite3VdbeChangeP5(v, (u8)nFarg);
+        sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
+                                   pDef, pExpr->op2);
       }
-      if( nFarg && constMask==0 ){
-        sqlite3ReleaseTempRange(pParse, r1, nFarg);
+      if( nFarg ){
+        if( constMask==0 ){
+          sqlite3ReleaseTempRange(pParse, r1, nFarg);
+        }else{
+          sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
+        }
       }
       return target;
     }
@@ -101684,7 +104669,9 @@ expr_code_doover:
       int nCol;
       testcase( op==TK_EXISTS );
       testcase( op==TK_SELECT );
-      if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
+      if( pParse->db->mallocFailed ){
+        return 0;
+      }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
         sqlite3SubselectError(pParse, nCol, 1);
       }else{
         return sqlite3CodeSubselect(pParse, pExpr);
@@ -101735,7 +104722,7 @@ expr_code_doover:
       return target;
     }
     case TK_SPAN:
-    case TK_COLLATE: 
+    case TK_COLLATE:
     case TK_UPLUS: {
       pExpr = pExpr->pLeft;
       goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
@@ -101751,7 +104738,7 @@ expr_code_doover:
       **
       ** The expression is implemented using an OP_Param opcode. The p1
       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
-      ** to reference another column of the old.* pseudo-table, where 
+      ** to reference another column of the old.* pseudo-table, where
       ** i is the index of the column. For a new.rowid reference, p1 is
       ** set to (n+1), where n is the number of columns in each pseudo-table.
       ** For a reference to any other column in the new.* pseudo-table, p1
@@ -101765,20 +104752,22 @@ expr_code_doover:
       **
       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
       **   p1==1   ->    old.a         p1==4   ->    new.a
-      **   p1==2   ->    old.b         p1==5   ->    new.b       
+      **   p1==2   ->    old.b         p1==5   ->    new.b
       */
       Table *pTab = pExpr->y.pTab;
-      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
+      int iCol = pExpr->iColumn;
+      int p1 = pExpr->iTable * (pTab->nCol+1) + 1
+                     + sqlite3TableColumnToStorage(pTab, iCol);
 
       assert( pExpr->iTable==0 || pExpr->iTable==1 );
-      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
-      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
+      assert( iCol>=-1 && iCol<pTab->nCol );
+      assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
       assert( p1>=0 && p1<(pTab->nCol*2+2) );
 
       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
       VdbeComment((v, "r[%d]=%s.%s", target,
         (pExpr->iTable ? "new" : "old"),
-        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName)
+        (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
       ));
 
 #ifndef SQLITE_OMIT_FLOATING_POINT
@@ -101787,9 +104776,7 @@ expr_code_doover:
       **
       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
       ** floating point when extracting it from the record.  */
-      if( pExpr->iColumn>=0 
-       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
-      ){
+      if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
       }
 #endif
@@ -101844,7 +104831,7 @@ expr_code_doover:
     ** or if there is no matching Ei, the ELSE term Y, or if there is
     ** no ELSE term, NULL.
     */
-    default: assert( op==TK_CASE ); {
+    case TK_CASE: {
       int endLabel;                     /* GOTO label for end of CASE stmt */
       int nextCase;                     /* GOTO label for next WHEN clause */
       int nExpr;                        /* 2x number of WHEN terms */
@@ -101903,17 +104890,18 @@ expr_code_doover:
         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
       }
       sqlite3ExprDelete(db, pDel);
+      setDoNotMergeFlagOnCopy(v);
       sqlite3VdbeResolveLabel(v, endLabel);
       break;
     }
 #ifndef SQLITE_OMIT_TRIGGER
     case TK_RAISE: {
-      assert( pExpr->affExpr==OE_Rollback 
+      assert( pExpr->affExpr==OE_Rollback
            || pExpr->affExpr==OE_Abort
            || pExpr->affExpr==OE_Fail
            || pExpr->affExpr==OE_Ignore
       );
-      if( !pParse->pTriggerTab ){
+      if( !pParse->pTriggerTab && !pParse->nested ){
         sqlite3ErrorMsg(pParse,
                        "RAISE() may only be used within a trigger-program");
         return 0;
@@ -101927,8 +104915,9 @@ expr_code_doover:
             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
         VdbeCoverage(v);
       }else{
-        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
-                              pExpr->affExpr, pExpr->u.zToken, 0, 0);
+        sqlite3HaltConstraint(pParse,
+             pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
+             pExpr->affExpr, pExpr->u.zToken, 0, 0);
       }
 
       break;
@@ -101941,15 +104930,23 @@ expr_code_doover:
 }
 
 /*
-** Factor out the code of the given expression to initialization time.
+** Generate code that will evaluate expression pExpr just one time
+** per prepared statement execution.
+**
+** If the expression uses functions (that might throw an exception) then
+** guard them with an OP_Once opcode to ensure that the code is only executed
+** once. If no functions are involved, then factor the code out and put it at
+** the end of the prepared statement in the initialization section.
 **
 ** If regDest>=0 then the result is always stored in that register and the
-** result is not reusable.  If regDest<0 then this routine is free to 
-** store the value whereever it wants.  The register where the expression 
-** is stored is returned.  When regDest<0, two identical expressions will
-** code to the same register.
-*/
-SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
+** result is not reusable.  If regDest<0 then this routine is free to
+** store the value whereever it wants.  The register where the expression
+** is stored is returned.  When regDest<0, two identical expressions might
+** code to the same register, if they do not contain function calls and hence
+** are factored out into the initialization section at the end of the
+** prepared statement.
+*/
+SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(
   Parse *pParse,    /* Parsing context */
   Expr *pExpr,      /* The expression to code when the VDBE initializes */
   int regDest       /* Store the value in this register */
@@ -101967,14 +104964,29 @@ SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
     }
   }
   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
-  p = sqlite3ExprListAppend(pParse, p, pExpr);
-  if( p ){
-     struct ExprList_item *pItem = &p->a[p->nExpr-1];
-     pItem->reusable = regDest<0;
-     if( regDest<0 ) regDest = ++pParse->nMem;
-     pItem->u.iConstExprReg = regDest;
+  if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
+    Vdbe *v = pParse->pVdbe;
+    int addr;
+    assert( v );
+    addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
+    pParse->okConstFactor = 0;
+    if( !pParse->db->mallocFailed ){
+      if( regDest<0 ) regDest = ++pParse->nMem;
+      sqlite3ExprCode(pParse, pExpr, regDest);
+    }
+    pParse->okConstFactor = 1;
+    sqlite3ExprDelete(pParse->db, pExpr);
+    sqlite3VdbeJumpHere(v, addr);
+  }else{
+    p = sqlite3ExprListAppend(pParse, p, pExpr);
+    if( p ){
+       struct ExprList_item *pItem = &p->a[p->nExpr-1];
+       pItem->reusable = regDest<0;
+       if( regDest<0 ) regDest = ++pParse->nMem;
+       pItem->u.iConstExprReg = regDest;
+    }
+    pParse->pConstExpr = p;
   }
-  pParse->pConstExpr = p;
   return regDest;
 }
 
@@ -101995,11 +105007,12 @@ SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
   int r2;
   pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
   if( ConstFactorOk(pParse)
+   && ALWAYS(pExpr!=0)
    && pExpr->op!=TK_REGISTER
    && sqlite3ExprIsConstantNotJoin(pExpr)
   ){
     *pReg  = 0;
-    r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
+    r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
   }else{
     int r1 = sqlite3GetTempReg(pParse);
     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
@@ -102021,15 +105034,19 @@ SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
   int inReg;
 
+  assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
   assert( target>0 && target<=pParse->nMem );
-  if( pExpr && pExpr->op==TK_REGISTER ){
-    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
-  }else{
-    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
-    assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
-    if( inReg!=target && pParse->pVdbe ){
-      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
+  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
+  if( pParse->pVdbe==0 ) return;
+  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
+  if( inReg!=target ){
+    u8 op;
+    if( ExprHasProperty(pExpr,EP_Subquery) ){
+      op = OP_Copy;
+    }else{
+      op = OP_SCopy;
     }
+    sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
   }
 }
 
@@ -102053,37 +105070,13 @@ SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
 */
 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
   if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
-    sqlite3ExprCodeAtInit(pParse, pExpr, target);
+    sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
   }else{
-    sqlite3ExprCode(pParse, pExpr, target);
+    sqlite3ExprCodeCopy(pParse, pExpr, target);
   }
 }
 
 /*
-** Generate code that evaluates the given expression and puts the result
-** in register target.
-**
-** Also make a copy of the expression results into another "cache" register
-** and modify the expression so that the next time it is evaluated,
-** the result is a copy of the cache register.
-**
-** This routine is used for expressions that are used multiple 
-** times.  They are evaluated once and the results of the expression
-** are reused.
-*/
-SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
-  Vdbe *v = pParse->pVdbe;
-  int iMem;
-
-  assert( target>0 );
-  assert( pExpr->op!=TK_REGISTER );
-  sqlite3ExprCode(pParse, pExpr, target);
-  iMem = ++pParse->nMem;
-  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
-  exprToRegister(pExpr, iMem);
-}
-
-/*
 ** Generate code that pushes the value of every element of the given
 ** expression list into a sequence of registers beginning at target.
 **
@@ -102137,7 +105130,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList(
     }else if( (flags & SQLITE_ECEL_FACTOR)!=0
            && sqlite3ExprIsConstantNotJoin(pExpr)
     ){
-      sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
+      sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
     }else{
       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
       if( inReg!=target+i ){
@@ -102146,6 +105139,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList(
          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
          && pOp->p1+pOp->p3+1==inReg
          && pOp->p2+pOp->p3+1==target+i
+         && pOp->p5==0  /* The do-not-merge flag must be clear */
         ){
           pOp->p3++;
         }else{
@@ -102162,7 +105156,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList(
 **
 **    x BETWEEN y AND z
 **
-** The above is equivalent to 
+** The above is equivalent to
 **
 **    x>=y AND x<=z
 **
@@ -102259,6 +105253,7 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int
   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
+  assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
   op = pExpr->op;
   switch( op ){
     case TK_AND:
@@ -102308,7 +105303,7 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int
       testcase( op==TK_ISNOT );
       op = (op==TK_IS) ? TK_EQ : TK_NE;
       jumpIfNull = SQLITE_NULLEQ;
-      /* Fall thru */
+      /* no break */ deliberate_fall_through
     case TK_LT:
     case TK_LE:
     case TK_GT:
@@ -102320,7 +105315,7 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int
       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
-                  r1, r2, dest, jumpIfNull);
+                  r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
@@ -102378,7 +105373,7 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int
     }
   }
   sqlite3ReleaseTempReg(pParse, regFree1);
-  sqlite3ReleaseTempReg(pParse, regFree2);  
+  sqlite3ReleaseTempReg(pParse, regFree2);
 }
 
 /*
@@ -102400,6 +105395,7 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int
   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
   if( pExpr==0 )    return;
+  assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
 
   /* The value of pExpr->op and op are related as follows:
   **
@@ -102483,7 +105479,7 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int
       testcase( pExpr->op==TK_ISNOT );
       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
       jumpIfNull = SQLITE_NULLEQ;
-      /* Fall thru */
+      /* no break */ deliberate_fall_through
     case TK_LT:
     case TK_LE:
     case TK_GT:
@@ -102495,7 +105491,7 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int
       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
-                  r1, r2, dest, jumpIfNull);
+                  r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
@@ -102537,7 +105533,7 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int
     }
 #endif
     default: {
-    default_expr: 
+    default_expr:
       if( ExprAlwaysFalse(pExpr) ){
         sqlite3VdbeGoto(v, dest);
       }else if( ExprAlwaysTrue(pExpr) ){
@@ -102587,7 +105583,7 @@ static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
   int res = 0;
   int iVar;
   sqlite3_value *pL, *pR = 0;
-  
+
   sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
   if( pR ){
     iVar = pVar->iColumn;
@@ -102629,9 +105625,9 @@ static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
 ** an incorrect 0 or 1 could lead to a malfunction.
 **
 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
-** pParse->pReprepare can be matched against literals in pB.  The 
+** pParse->pReprepare can be matched against literals in pB.  The
 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
-** If pParse is NULL (the normal case) then any TK_VARIABLE term in 
+** If pParse is NULL (the normal case) then any TK_VARIABLE term in
 ** Argument pParse should normally be NULL. If it is not NULL and pA or
 ** pB causes a return value of 2.
 */
@@ -102681,8 +105677,9 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTa
       return 2;
     }
   }
-  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
-  if( (combinedFlags & EP_TokenOnly)==0 ){
+  if( (pA->flags & (EP_Distinct|EP_Commuted))
+     != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
+  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
     if( combinedFlags & EP_xIsSelect ) return 2;
     if( (combinedFlags & EP_FixedCol)==0
      && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
@@ -102690,21 +105687,22 @@ SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTa
     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
     if( pA->op!=TK_STRING
      && pA->op!=TK_TRUEFALSE
-     && (combinedFlags & EP_Reduced)==0
+     && ALWAYS((combinedFlags & EP_Reduced)==0)
     ){
       if( pA->iColumn!=pB->iColumn ) return 2;
-      if( pA->op2!=pB->op2 ) return 2;
-      if( pA->op!=TK_IN
-       && pA->iTable!=pB->iTable 
-       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
+      if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
+      if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
+        return 2;
+      }
     }
   }
   return 0;
 }
 
 /*
-** Compare two ExprList objects.  Return 0 if they are identical and 
-** non-zero if they differ in any way.
+** Compare two ExprList objects.  Return 0 if they are identical, 1
+** if they are certainly different, or 2 if it is not possible to
+** determine if they are identical or not.
 **
 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
@@ -102723,10 +105721,11 @@ SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
   if( pA==0 || pB==0 ) return 1;
   if( pA->nExpr!=pB->nExpr ) return 1;
   for(i=0; i<pA->nExpr; i++){
+    int res;
     Expr *pExprA = pA->a[i].pExpr;
     Expr *pExprB = pB->a[i].pExpr;
     if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
-    if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
+    if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
   }
   return 0;
 }
@@ -102789,16 +105788,16 @@ static int exprImpliesNotNull(
     case TK_MINUS:
     case TK_BITOR:
     case TK_LSHIFT:
-    case TK_RSHIFT: 
-    case TK_CONCAT: 
+    case TK_RSHIFT:
+    case TK_CONCAT:
       seenNot = 1;
-      /* Fall thru */
+      /* no break */ deliberate_fall_through
     case TK_STAR:
     case TK_REM:
     case TK_BITAND:
     case TK_SLASH: {
       if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
-      /* Fall thru into the next case */
+      /* no break */ deliberate_fall_through
     }
     case TK_SPAN:
     case TK_COLLATE:
@@ -102835,9 +105834,9 @@ static int exprImpliesNotNull(
 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
 ** Expr.iTable<0 then assume a table number given by iTab.
 **
-** If pParse is not NULL, then the values of bound variables in pE1 are 
+** If pParse is not NULL, then the values of bound variables in pE1 are
 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
-** modified to record which bound variables are referenced.  If pParse 
+** modified to record which bound variables are referenced.  If pParse
 ** is NULL, then false will be returned if pE1 contains any bound variables.
 **
 ** When in doubt, return false.  Returning true might give a performance
@@ -102863,7 +105862,7 @@ SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, i
 }
 
 /*
-** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
+** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
 ** If the expression node requires that the table at pWalker->iCur
 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
 **
@@ -102881,6 +105880,7 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
     case TK_NOTNULL:
     case TK_IS:
     case TK_OR:
+    case TK_VECTOR:
     case TK_CASE:
     case TK_IN:
     case TK_FUNCTION:
@@ -102890,6 +105890,7 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
       testcase( pExpr->op==TK_NOTNULL );
       testcase( pExpr->op==TK_IS );
       testcase( pExpr->op==TK_OR );
+      testcase( pExpr->op==TK_VECTOR );
       testcase( pExpr->op==TK_CASE );
       testcase( pExpr->op==TK_IN );
       testcase( pExpr->op==TK_FUNCTION );
@@ -102903,15 +105904,20 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
       return WRC_Prune;
 
     case TK_AND:
-      if( sqlite3ExprImpliesNonNullRow(pExpr->pLeft, pWalker->u.iCur)
-       && sqlite3ExprImpliesNonNullRow(pExpr->pRight, pWalker->u.iCur)
-      ){
-        pWalker->eCode = 1;
+      if( pWalker->eCode==0 ){
+        sqlite3WalkExpr(pWalker, pExpr->pLeft);
+        if( pWalker->eCode ){
+          pWalker->eCode = 0;
+          sqlite3WalkExpr(pWalker, pExpr->pRight);
+        }
       }
       return WRC_Prune;
 
     case TK_BETWEEN:
-      sqlite3WalkExpr(pWalker, pExpr->pLeft);
+      if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
+        assert( pWalker->eCode );
+        return WRC_Abort;
+      }
       return WRC_Prune;
 
     /* Virtual tables are allowed to use constraints like x=NULL.  So
@@ -102922,19 +105928,26 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
     case TK_LT:
     case TK_LE:
     case TK_GT:
-    case TK_GE:
+    case TK_GE: {
+      Expr *pLeft = pExpr->pLeft;
+      Expr *pRight = pExpr->pRight;
       testcase( pExpr->op==TK_EQ );
       testcase( pExpr->op==TK_NE );
       testcase( pExpr->op==TK_LT );
       testcase( pExpr->op==TK_LE );
       testcase( pExpr->op==TK_GT );
       testcase( pExpr->op==TK_GE );
-      if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab))
-       || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab))
+      /* The y.pTab=0 assignment in wherecode.c always happens after the
+      ** impliesNotNullRow() test */
+      if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
+                               && IsVirtual(pLeft->y.pTab))
+       || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
+                               && IsVirtual(pRight->y.pTab))
       ){
-       return WRC_Prune;
+        return WRC_Prune;
       }
-
+      /* no break */ deliberate_fall_through
+    }
     default:
       return WRC_Continue;
   }
@@ -102965,14 +105978,13 @@ static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
 SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
   Walker w;
   p = sqlite3ExprSkipCollateAndLikely(p);
-  while( p ){
-    if( p->op==TK_NOTNULL ){
-      p = p->pLeft;
-    }else if( p->op==TK_AND ){
+  if( p==0 ) return 0;
+  if( p->op==TK_NOTNULL ){
+    p = p->pLeft;
+  }else{
+    while( p->op==TK_AND ){
       if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
       p = p->pRight;
-    }else{
-      break;
     }
   }
   w.xExprCallback = impliesNotNullRow;
@@ -102997,14 +106009,14 @@ struct IdxCover {
 };
 
 /*
-** Check to see if there are references to columns in table 
+** Check to see if there are references to columns in table
 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
 ** pWalker->u.pIdxCover->pIdx.
 */
 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
   if( pExpr->op==TK_COLUMN
    && pExpr->iTable==pWalker->u.pIdxCover->iCur
-   && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
+   && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
   ){
     pWalker->eCode = 1;
     return WRC_Abort;
@@ -103041,26 +106053,42 @@ SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
 
 /*
 ** An instance of the following structure is used by the tree walker
-** to count references to table columns in the arguments of an 
+** to count references to table columns in the arguments of an
 ** aggregate function, in order to implement the
 ** sqlite3FunctionThisSrc() routine.
 */
 struct SrcCount {
   SrcList *pSrc;   /* One particular FROM clause in a nested query */
+  int iSrcInner;   /* Smallest cursor number in this context */
   int nThis;       /* Number of references to columns in pSrcList */
   int nOther;      /* Number of references to columns in other FROM clauses */
 };
 
 /*
+** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first
+** SELECT with a FROM clause encountered during this iteration, set
+** SrcCount.iSrcInner to the cursor number of the leftmost object in
+** the FROM cause.
+*/
+static int selectSrcCount(Walker *pWalker, Select *pSel){
+  struct SrcCount *p = pWalker->u.pSrcCount;
+  if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){
+    pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;
+  }
+  return WRC_Continue;
+}
+
+/*
 ** Count the number of references to columns.
 */
 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
-  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
-  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
-  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
-  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
-  ** NEVER() will need to be removed. */
-  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
+  /* There was once a NEVER() on the second term on the grounds that
+  ** sqlite3FunctionUsesThisSrc() was always called before
+  ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
+  ** been converted into TK_AGG_COLUMN. But this is no longer true due
+  ** to window functions - sqlite3WindowRewrite() may now indirectly call
+  ** FunctionUsesThisSrc() when creating a new sub-select. */
+  if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
     int i;
     struct SrcCount *p = pWalker->u.pSrcCount;
     SrcList *pSrc = p->pSrc;
@@ -103070,7 +106098,7 @@ static int exprSrcCount(Walker *pWalker, Expr *pExpr){
     }
     if( i<nSrc ){
       p->nThis++;
-    }else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
+    }else if( pExpr->iTable<p->iSrcInner ){
       /* In a well-formed parse tree (no name resolution errors),
       ** TK_COLUMN nodes with smaller Expr.iTable values are in an
       ** outer context.  Those are the only ones to count as "other" */
@@ -103092,16 +106120,80 @@ SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
   assert( pExpr->op==TK_AGG_FUNCTION );
   memset(&w, 0, sizeof(w));
   w.xExprCallback = exprSrcCount;
-  w.xSelectCallback = sqlite3SelectWalkNoop;
+  w.xSelectCallback = selectSrcCount;
   w.u.pSrcCount = &cnt;
   cnt.pSrc = pSrcList;
+  cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;
   cnt.nThis = 0;
   cnt.nOther = 0;
   sqlite3WalkExprList(&w, pExpr->x.pList);
+#ifndef SQLITE_OMIT_WINDOWFUNC
+  if( ExprHasProperty(pExpr, EP_WinFunc) ){
+    sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
+  }
+#endif
   return cnt.nThis>0 || cnt.nOther==0;
 }
 
 /*
+** This is a Walker expression node callback.
+**
+** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
+** object that is referenced does not refer directly to the Expr.  If
+** it does, make a copy.  This is done because the pExpr argument is
+** subject to change.
+**
+** The copy is stored on pParse->pConstExpr with a register number of 0.
+** This will cause the expression to be deleted automatically when the
+** Parse object is destroyed, but the zero register number means that it
+** will not generate any code in the preamble.
+*/
+static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
+  if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
+   && pExpr->pAggInfo!=0
+  ){
+    AggInfo *pAggInfo = pExpr->pAggInfo;
+    int iAgg = pExpr->iAgg;
+    Parse *pParse = pWalker->pParse;
+    sqlite3 *db = pParse->db;
+    assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION );
+    if( pExpr->op==TK_AGG_COLUMN ){
+      assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
+      if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){
+        pExpr = sqlite3ExprDup(db, pExpr, 0);
+        if( pExpr ){
+          pAggInfo->aCol[iAgg].pCExpr = pExpr;
+          pParse->pConstExpr =
+             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+        }
+      }
+    }else{
+      assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
+      if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){
+        pExpr = sqlite3ExprDup(db, pExpr, 0);
+        if( pExpr ){
+          pAggInfo->aFunc[iAgg].pFExpr = pExpr;
+          pParse->pConstExpr =
+             sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
+        }
+      }
+    }
+  }
+  return WRC_Continue;
+}
+
+/*
+** Initialize a Walker object so that will persist AggInfo entries referenced
+** by the tree that is walked.
+*/
+SQLITE_PRIVATE void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
+  memset(pWalker, 0, sizeof(*pWalker));
+  pWalker->pParse = pParse;
+  pWalker->xExprCallback = agginfoPersistExprCb;
+  pWalker->xSelectCallback = sqlite3SelectWalkNoop;
+}
+
+/*
 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
 ** the new element.  Return a negative number if malloc fails.
 */
@@ -103115,7 +106207,7 @@ static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
        &i
   );
   return i;
-}    
+}
 
 /*
 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
@@ -103124,14 +106216,14 @@ static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
   int i;
   pInfo->aFunc = sqlite3ArrayAllocate(
-       db, 
+       db,
        pInfo->aFunc,
        sizeof(pInfo->aFunc[0]),
        &pInfo->nFunc,
        &i
   );
   return i;
-}    
+}
 
 /*
 ** This is the xExprCallback for a tree walker.  It is used to
@@ -103160,7 +106252,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
           if( pExpr->iTable==pItem->iCursor ){
             /* If we reach this point, it means that pExpr refers to a table
-            ** that is in the FROM clause of the aggregate query.  
+            ** that is in the FROM clause of the aggregate query.
             **
             ** Make an entry for the column in pAggInfo->aCol[] if there
             ** is not an entry there already.
@@ -103174,7 +106266,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
               }
             }
             if( (k>=pAggInfo->nColumn)
-             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
+             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
             ){
               pCol = &pAggInfo->aCol[k];
               pCol->pTab = pExpr->y.pTab;
@@ -103182,7 +106274,7 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
               pCol->iColumn = pExpr->iColumn;
               pCol->iMem = ++pParse->nMem;
               pCol->iSorterColumn = -1;
-              pCol->pExpr = pExpr;
+              pCol->pCExpr = pExpr;
               if( pAggInfo->pGroupBy ){
                 int j, n;
                 ExprList *pGB = pAggInfo->pGroupBy;
@@ -103220,12 +106312,12 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
       if( (pNC->ncFlags & NC_InAggFunc)==0
        && pWalker->walkerDepth==pExpr->op2
       ){
-        /* Check to see if pExpr is a duplicate of another aggregate 
+        /* Check to see if pExpr is a duplicate of another aggregate
         ** function that is already in the pAggInfo structure
         */
         struct AggInfo_func *pItem = pAggInfo->aFunc;
         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
-          if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
+          if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
             break;
           }
         }
@@ -103237,11 +106329,11 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
           if( i>=0 ){
             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
             pItem = &pAggInfo->aFunc[i];
-            pItem->pExpr = pExpr;
+            pItem->pFExpr = pExpr;
             pItem->iMem = ++pParse->nMem;
             assert( !ExprHasProperty(pExpr, EP_IntValue) );
             pItem->pFunc = sqlite3FindFunction(pParse->db,
-                   pExpr->u.zToken, 
+                   pExpr->u.zToken,
                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
             if( pExpr->flags & EP_Distinct ){
               pItem->iDistinct = pParse->nTab++;
@@ -103264,15 +106356,6 @@ static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
   }
   return WRC_Continue;
 }
-static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
-  UNUSED_PARAMETER(pSelect);
-  pWalker->walkerDepth++;
-  return WRC_Continue;
-}
-static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
-  UNUSED_PARAMETER(pSelect);
-  pWalker->walkerDepth--;
-}
 
 /*
 ** Analyze the pExpr expression looking for aggregate functions and
@@ -103286,8 +106369,8 @@ static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
   Walker w;
   w.xExprCallback = analyzeAggregate;
-  w.xSelectCallback = analyzeAggregatesInSelect;
-  w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
+  w.xSelectCallback = sqlite3WalkerDepthIncrease;
+  w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
   w.walkerDepth = 0;
   w.u.pNC = pNC;
   w.pParse = 0;
@@ -103326,8 +106409,11 @@ SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
 ** purpose.
 */
 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
-  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
-    pParse->aTempReg[pParse->nTempReg++] = iReg;
+  if( iReg ){
+    sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
+    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
+      pParse->aTempReg[pParse->nTempReg++] = iReg;
+    }
   }
 }
 
@@ -103353,6 +106439,7 @@ SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
     sqlite3ReleaseTempReg(pParse, iReg);
     return;
   }
+  sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
   if( nReg>pParse->nRangeReg ){
     pParse->nRangeReg = nReg;
     pParse->iRangeReg = iReg;
@@ -103428,11 +106515,10 @@ SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
 ** Or, if zName is not a system table, zero is returned.
 */
 static int isAlterableTable(Parse *pParse, Table *pTab){
-  if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) 
+  if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
 #ifndef SQLITE_OMIT_VIRTUALTABLE
-   || ( (pTab->tabFlags & TF_Shadow) 
-     && (pParse->db->flags & SQLITE_Defensive)
-     && pParse->db->nVdbeExec==0
+   || ( (pTab->tabFlags & TF_Shadow)!=0
+        && sqlite3ReadOnlyShadowTables(pParse->db)
    )
 #endif
   ){
@@ -103450,24 +106536,24 @@ static int isAlterableTable(Parse *pParse, Table *pTab){
 ** objects unusable.
 */
 static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
-  sqlite3NestedParse(pParse, 
+  sqlite3NestedParse(pParse,
       "SELECT 1 "
-      "FROM \"%w\".%s "
+      "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
       " AND sql NOT LIKE 'create virtual%%'"
       " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
-      zDb, MASTER_NAME, 
+      zDb,
       zDb, bTemp
   );
 
   if( bTemp==0 ){
-    sqlite3NestedParse(pParse, 
+    sqlite3NestedParse(pParse,
         "SELECT 1 "
-        "FROM temp.%s "
+        "FROM temp." DFLT_SCHEMA_TABLE " "
         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
         " AND sql NOT LIKE 'create virtual%%'"
         " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
-        MASTER_NAME, zDb 
+        zDb
     );
   }
 }
@@ -103486,8 +106572,8 @@ static void renameReloadSchema(Parse *pParse, int iDb){
 }
 
 /*
-** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
-** command. 
+** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
+** command.
 */
 SQLITE_PRIVATE void sqlite3AlterRenameTable(
   Parse *pParse,            /* Parser context. */
@@ -103497,7 +106583,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   int iDb;                  /* Database that contains the table */
   const char *zDb;          /* Name of database iDb */
   Table *pTab;              /* Table being renamed */
-  char *zName = 0;          /* NULL-terminated version of pName */ 
+  char *zName = 0;          /* NULL-terminated version of pName */
   sqlite3 *db = pParse->db; /* Database connection */
   int nTabName;             /* Number of UTF-8 characters in zTabName */
   const char *zTabName;     /* Original name of the table */
@@ -103505,7 +106591,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
   u32 savedDbFlags;         /* Saved value of db->mDbFlags */
 
-  savedDbFlags = db->mDbFlags;  
+  savedDbFlags = db->mDbFlags;
   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
   assert( pSrc->nSrc==1 );
   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
@@ -103523,8 +106609,11 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
   /* Check that a table or index named 'zName' does not already exist
   ** in database iDb. If so, this is an error.
   */
-  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
-    sqlite3ErrorMsg(pParse, 
+  if( sqlite3FindTable(db, zName, zDb)
+   || sqlite3FindIndex(db, zName, zDb)
+   || sqlite3IsShadowTableOf(db, pTab, zName)
+  ){
+    sqlite3ErrorMsg(pParse,
         "there is already another table or index with this name: %s", zName);
     goto exit_rename_table;
   }
@@ -103567,7 +106656,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
 
   /* Begin a transaction for database iDb. Then modify the schema cookie
   ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
-  ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the 
+  ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
   ** nested SQL may raise an exception.  */
   v = sqlite3GetVdbe(pParse);
   if( v==0 ){
@@ -103581,18 +106670,18 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
 
   /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
   ** the schema to use the new table name.  */
-  sqlite3NestedParse(pParse, 
-      "UPDATE \"%w\".%s SET "
+  sqlite3NestedParse(pParse,
+      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
       "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
       "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
-      , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
+      , zDb, zDb, zTabName, zName, (iDb==1), zTabName
   );
 
-  /* Update the tbl_name and name columns of the sqlite_master table
+  /* Update the tbl_name and name columns of the sqlite_schema table
   ** as required.  */
   sqlite3NestedParse(pParse,
-      "UPDATE %Q.%s SET "
+      "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
           "tbl_name = %Q, "
           "name = CASE "
             "WHEN type='table' THEN %Q "
@@ -103601,14 +106690,14 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
             "ELSE name END "
       "WHERE tbl_name=%Q COLLATE nocase AND "
-          "(type='table' OR type='index' OR type='trigger');", 
-      zDb, MASTER_NAME, 
-      zName, zName, zName, 
+          "(type='table' OR type='index' OR type='trigger');",
+      zDb,
+      zName, zName, zName,
       nTabName, zTabName
   );
 
 #ifndef SQLITE_OMIT_AUTOINCREMENT
-  /* If the sqlite_sequence table exists in this database, then update 
+  /* If the sqlite_sequence table exists in this database, then update
   ** it with the new table name.
   */
   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
@@ -103619,11 +106708,11 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable(
 #endif
 
   /* If the table being renamed is not itself part of the temp database,
-  ** edit view and trigger definitions within the temp database 
+  ** edit view and trigger definitions within the temp database
   ** as required.  */
   if( iDb!=1 ){
-    sqlite3NestedParse(pParse, 
-        "UPDATE sqlite_temp_master SET "
+    sqlite3NestedParse(pParse,
+        "UPDATE sqlite_temp_schema SET "
             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
             "tbl_name = "
               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
@@ -103656,6 +106745,22 @@ exit_rename_table:
 }
 
 /*
+** Write code that will raise an error if the table described by
+** zDb and zTab is not empty.
+*/
+static void sqlite3ErrorIfNotEmpty(
+  Parse *pParse,        /* Parsing context */
+  const char *zDb,      /* Schema holding the table */
+  const char *zTab,     /* Table to check for empty */
+  const char *zErr      /* Error message text */
+){
+  sqlite3NestedParse(pParse,
+     "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
+     zErr, zDb, zTab
+  );
+}
+
+/*
 ** This function is called after an "ALTER TABLE ... ADD" statement
 ** has been parsed. Argument pColDef contains the text of the new
 ** column definition.
@@ -103697,14 +106802,6 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
   }
 #endif
 
-  /* If the default value for the new column was specified with a 
-  ** literal NULL, then set pDflt to 0. This simplifies checking
-  ** for an SQL NULL default below.
-  */
-  assert( pDflt==0 || pDflt->op==TK_SPAN );
-  if( pDflt && pDflt->pLeft->op==TK_NULL ){
-    pDflt = 0;
-  }
 
   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
   ** If there is a NOT NULL constraint, then the default value for the
@@ -103715,39 +106812,52 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
     return;
   }
   if( pNew->pIndex ){
-    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
-    return;
-  }
-  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
-    sqlite3ErrorMsg(pParse, 
-        "Cannot add a REFERENCES column with non-NULL default value");
-    return;
-  }
-  if( pCol->notNull && !pDflt ){
-    sqlite3ErrorMsg(pParse, 
-        "Cannot add a NOT NULL column with default value NULL");
+    sqlite3ErrorMsg(pParse,
+         "Cannot add a UNIQUE column");
     return;
   }
-
-  /* Ensure the default expression is something that sqlite3ValueFromExpr()
-  ** can handle (i.e. not CURRENT_TIME etc.)
-  */
-  if( pDflt ){
-    sqlite3_value *pVal = 0;
-    int rc;
-    rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
-    assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
-    if( rc!=SQLITE_OK ){
-      assert( db->mallocFailed == 1 );
-      return;
+  if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
+    /* If the default value for the new column was specified with a
+    ** literal NULL, then set pDflt to 0. This simplifies checking
+    ** for an SQL NULL default below.
+    */
+    assert( pDflt==0 || pDflt->op==TK_SPAN );
+    if( pDflt && pDflt->pLeft->op==TK_NULL ){
+      pDflt = 0;
     }
-    if( !pVal ){
-      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
-      return;
+    if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
+      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+          "Cannot add a REFERENCES column with non-NULL default value");
+    }
+    if( pCol->notNull && !pDflt ){
+      sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+          "Cannot add a NOT NULL column with default value NULL");
+    }
+
+
+    /* Ensure the default expression is something that sqlite3ValueFromExpr()
+    ** can handle (i.e. not CURRENT_TIME etc.)
+    */
+    if( pDflt ){
+      sqlite3_value *pVal = 0;
+      int rc;
+      rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
+      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
+      if( rc!=SQLITE_OK ){
+        assert( db->mallocFailed == 1 );
+        return;
+      }
+      if( !pVal ){
+        sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
+           "Cannot add a column with non-constant default");
+      }
+      sqlite3ValueFree(pVal);
     }
-    sqlite3ValueFree(pVal);
+  }else if( pCol->colFlags & COLFLAG_STORED ){
+    sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
   }
 
+
   /* Modify the CREATE TABLE statement. */
   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
   if( zCol ){
@@ -103757,11 +106867,11 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
       *zEnd-- = '\0';
     }
     db->mDbFlags |= DBFLAG_PreferBuiltin;
-    sqlite3NestedParse(pParse, 
-        "UPDATE \"%w\".%s SET "
+    sqlite3NestedParse(pParse,
+        "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
-        "WHERE type = 'table' AND name = %Q", 
-      zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
+        "WHERE type = 'table' AND name = %Q",
+      zDb, pNew->addColOffset, zCol, pNew->addColOffset+1,
       zTab
     );
     sqlite3DbFree(db, zCol);
@@ -103790,14 +106900,14 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
 
 /*
 ** This function is called by the parser after the table-name in
-** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
+** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
 ** pSrc is the full-name of the table being altered.
 **
 ** This routine makes a (partial) copy of the Table structure
 ** for the table being altered and sets Parse.pNewTable to point
 ** to it. Routines called by the parser as the column definition
-** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
-** the copy. The copy of the Table structure is deleted by tokenize.c 
+** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
+** the copy. The copy of the Table structure is deleted by tokenize.c
 ** after parsing is finished.
 **
 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
@@ -103863,6 +106973,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
   for(i=0; i<pNew->nCol; i++){
     Column *pCol = &pNew->aCol[i];
     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
+    pCol->hName = sqlite3StrIHash(pCol->zName);
     pCol->zColl = 0;
     pCol->pDflt = 0;
   }
@@ -103936,7 +107047,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
   if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
 
-  /* Which schema holds the table to be altered */  
+  /* Which schema holds the table to be altered */
   iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
   assert( iSchema>=0 );
   zDb = db->aDb[iSchema].zDbSName;
@@ -103962,29 +107073,28 @@ SQLITE_PRIVATE void sqlite3AlterRenameColumn(
 
   /* Do the rename operation using a recursive UPDATE statement that
   ** uses the sqlite_rename_column() SQL function to compute the new
-  ** CREATE statement text for the sqlite_master table.
+  ** CREATE statement text for the sqlite_schema table.
   */
   sqlite3MayAbort(pParse);
   zNew = sqlite3NameFromToken(db, pNew);
   if( !zNew ) goto exit_rename_column;
   assert( pNew->n>0 );
   bQuote = sqlite3Isquote(pNew->z[0]);
-  sqlite3NestedParse(pParse, 
-      "UPDATE \"%w\".%s SET "
+  sqlite3NestedParse(pParse,
+      "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
       " AND (type != 'index' OR tbl_name = %Q)"
       " AND sql NOT LIKE 'create virtual%%'",
-      zDb, MASTER_NAME, 
+      zDb,
       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
       pTab->zName
   );
 
-  sqlite3NestedParse(pParse, 
-      "UPDATE temp.%s SET "
+  sqlite3NestedParse(pParse,
+      "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
       "WHERE type IN ('trigger', 'view')",
-      MASTER_NAME, 
       zDb, pTab->zName, iCol, zNew, bQuote
   );
 
@@ -104031,7 +107141,7 @@ struct RenameCtx {
   RenameToken *pList;             /* List of tokens to overwrite */
   int nList;                      /* Number of tokens in pList */
   int iCol;                       /* Index of column being renamed */
-  Table *pTab;                    /* Table being ALTERed */ 
+  Table *pTab;                    /* Table being ALTERed */
   const char *zOld;               /* Old column name */
 };
 
@@ -104039,14 +107149,14 @@ struct RenameCtx {
 /*
 ** This function is only for debugging. It performs two tasks:
 **
-**   1. Checks that pointer pPtr does not already appear in the 
+**   1. Checks that pointer pPtr does not already appear in the
 **      rename-token list.
 **
 **   2. Dereferences each pointer in the rename-token list.
 **
 ** The second is most effective when debugging under valgrind or
-** address-sanitizer or similar. If any of these pointers no longer 
-** point to valid objects, an exception is raised by the memory-checking 
+** address-sanitizer or similar. If any of these pointers no longer
+** point to valid objects, an exception is raised by the memory-checking
 ** tool.
 **
 ** The point of this is to prevent comparisons of invalid pointer values.
@@ -104091,12 +107201,14 @@ SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pTo
   RenameToken *pNew;
   assert( pPtr || pParse->db->mallocFailed );
   renameTokenCheckAll(pParse, pPtr);
-  pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
-  if( pNew ){
-    pNew->p = pPtr;
-    pNew->t = *pToken;
-    pNew->pNext = pParse->pRename;
-    pParse->pRename = pNew;
+  if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
+    pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
+    if( pNew ){
+      pNew->p = pPtr;
+      pNew->t = *pToken;
+      pNew->pNext = pParse->pRename;
+      pParse->pRename = pNew;
+    }
   }
 
   return pPtr;
@@ -104128,16 +107240,38 @@ static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
 }
 
 /*
+** Iterate through the Select objects that are part of WITH clauses attached
+** to select statement pSelect.
+*/
+static void renameWalkWith(Walker *pWalker, Select *pSelect){
+  With *pWith = pSelect->pWith;
+  if( pWith ){
+    int i;
+    for(i=0; i<pWith->nCte; i++){
+      Select *p = pWith->a[i].pSelect;
+      NameContext sNC;
+      memset(&sNC, 0, sizeof(sNC));
+      sNC.pParse = pWalker->pParse;
+      sqlite3SelectPrep(sNC.pParse, p, &sNC);
+      sqlite3WalkSelect(pWalker, p);
+      sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
+    }
+  }
+}
+
+/*
 ** Walker callback used by sqlite3RenameExprUnmap().
 */
 static int renameUnmapSelectCb(Walker *pWalker, Select *p){
   Parse *pParse = pWalker->pParse;
   int i;
+  if( pParse->nErr ) return WRC_Abort;
+  if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
   if( ALWAYS(p->pEList) ){
     ExprList *pList = p->pEList;
     for(i=0; i<pList->nExpr; i++){
-      if( pList->a[i].zName ){
-        sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
+      if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
+        sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
       }
     }
   }
@@ -104145,8 +107279,11 @@ static int renameUnmapSelectCb(Walker *pWalker, Select *p){
     SrcList *pSrc = p->pSrc;
     for(i=0; i<pSrc->nSrc; i++){
       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
+      if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
     }
   }
+
+  renameWalkWith(pWalker, p);
   return WRC_Continue;
 }
 
@@ -104154,16 +107291,19 @@ static int renameUnmapSelectCb(Walker *pWalker, Select *p){
 ** Remove all nodes that are part of expression pExpr from the rename list.
 */
 SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
+  u8 eMode = pParse->eParseMode;
   Walker sWalker;
   memset(&sWalker, 0, sizeof(Walker));
   sWalker.pParse = pParse;
   sWalker.xExprCallback = renameUnmapExprCb;
   sWalker.xSelectCallback = renameUnmapSelectCb;
+  pParse->eParseMode = PARSE_MODE_UNMAP;
   sqlite3WalkExpr(&sWalker, pExpr);
+  pParse->eParseMode = eMode;
 }
 
 /*
-** Remove all nodes that are part of expression-list pEList from the 
+** Remove all nodes that are part of expression-list pEList from the
 ** rename list.
 */
 SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
@@ -104175,7 +107315,9 @@ SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
     sWalker.xExprCallback = renameUnmapExprCb;
     sqlite3WalkExprList(&sWalker, pEList);
     for(i=0; i<pEList->nExpr; i++){
-      sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
+      if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
+        sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
+      }
     }
   }
 }
@@ -104214,29 +107356,12 @@ static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
 }
 
 /*
-** Iterate through the Select objects that are part of WITH clauses attached
-** to select statement pSelect.
-*/
-static void renameWalkWith(Walker *pWalker, Select *pSelect){
-  if( pSelect->pWith ){
-    int i;
-    for(i=0; i<pSelect->pWith->nCte; i++){
-      Select *p = pSelect->pWith->a[i].pSelect;
-      NameContext sNC;
-      memset(&sNC, 0, sizeof(sNC));
-      sNC.pParse = pWalker->pParse;
-      sqlite3SelectPrep(sNC.pParse, p, &sNC);
-      sqlite3WalkSelect(pWalker, p);
-    }
-  }
-}
-
-/*
 ** This is a Walker select callback. It does nothing. It is only required
 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
 ** descend into sub-select statements.
 */
 static int renameColumnSelectCb(Walker *pWalker, Select *p){
+  if( p->selFlags & SF_View ) return WRC_Prune;
   renameWalkWith(pWalker, p);
   return WRC_Continue;
 }
@@ -104252,13 +107377,13 @@ static int renameColumnSelectCb(Walker *pWalker, Select *p){
 */
 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
   RenameCtx *p = pWalker->u.pRename;
-  if( pExpr->op==TK_TRIGGER 
-   && pExpr->iColumn==p->iCol 
+  if( pExpr->op==TK_TRIGGER
+   && pExpr->iColumn==p->iCol
    && pWalker->pParse->pTriggerTab==p->pTab
   ){
     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
-  }else if( pExpr->op==TK_COLUMN 
-   && pExpr->iColumn==p->iCol 
+  }else if( pExpr->op==TK_COLUMN
+   && pExpr->iColumn==p->iCol
    && p->pTab==pExpr->y.pTab
   ){
     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
@@ -104297,7 +107422,7 @@ static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
 ** adds context to the error message and then stores it in pCtx.
 */
 static void renameColumnParseError(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int bPost,
   sqlite3_value *pType,
   sqlite3_value *pObject,
@@ -104307,7 +107432,7 @@ static void renameColumnParseError(
   const char *zN = (const char*)sqlite3_value_text(pObject);
   char *zErr;
 
-  zErr = sqlite3_mprintf("error in %s %s%s: %s", 
+  zErr = sqlite3_mprintf("error in %s %s%s: %s",
       zT, zN, (bPost ? " after rename" : ""),
       pParse->zErrMsg
   );
@@ -104317,21 +107442,24 @@ static void renameColumnParseError(
 
 /*
 ** For each name in the the expression-list pEList (i.e. each
-** pEList->a[i].zName) that matches the string in zOld, extract the 
+** pEList->a[i].zName) that matches the string in zOld, extract the
 ** corresponding rename-token from Parse object pParse and add it
 ** to the RenameCtx pCtx.
 */
 static void renameColumnElistNames(
-  Parse *pParse, 
-  RenameCtx *pCtx, 
-  ExprList *pEList, 
+  Parse *pParse,
+  RenameCtx *pCtx,
+  ExprList *pEList,
   const char *zOld
 ){
   if( pEList ){
     int i;
     for(i=0; i<pEList->nExpr; i++){
-      char *zName = pEList->a[i].zName;
-      if( 0==sqlite3_stricmp(zName, zOld) ){
+      char *zName = pEList->a[i].zEName;
+      if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
+       && ALWAYS(zName!=0)
+       && 0==sqlite3_stricmp(zName, zOld)
+      ){
         renameTokenFind(pParse, pCtx, (void*)zName);
       }
     }
@@ -104339,14 +107467,14 @@ static void renameColumnElistNames(
 }
 
 /*
-** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) 
-** that matches the string in zOld, extract the corresponding rename-token 
+** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
+** that matches the string in zOld, extract the corresponding rename-token
 ** from Parse object pParse and add it to the RenameCtx pCtx.
 */
 static void renameColumnIdlistNames(
-  Parse *pParse, 
-  RenameCtx *pCtx, 
-  IdList *pIdList, 
+  Parse *pParse,
+  RenameCtx *pCtx,
+  IdList *pIdList,
   const char *zOld
 ){
   if( pIdList ){
@@ -104367,7 +107495,6 @@ static void renameColumnIdlistNames(
 static int renameParseSql(
   Parse *p,                       /* Memory to use for Parse object */
   const char *zDb,                /* Name of schema SQL belongs to */
-  int bTable,                     /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
   sqlite3 *db,                    /* Database handle */
   const char *zSql,               /* SQL to parse */
   int bTemp                       /* True if SQL is from temp schema */
@@ -104381,7 +107508,7 @@ static int renameParseSql(
   ** occurs and the parse does not result in a new table, index or
   ** trigger object, the database must be corrupt. */
   memset(p, 0, sizeof(Parse));
-  p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
+  p->eParseMode = PARSE_MODE_RENAME;
   p->db = db;
   p->nQueryLoop = 1;
   rc = sqlite3RunParser(p, zSql, &zErr);
@@ -104389,8 +107516,8 @@ static int renameParseSql(
   assert( rc!=SQLITE_OK || zErr==0 );
   p->zErrMsg = zErr;
   if( db->mallocFailed ) rc = SQLITE_NOMEM;
-  if( rc==SQLITE_OK 
-   && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 
+  if( rc==SQLITE_OK
+   && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
   ){
     rc = SQLITE_CORRUPT_BKPT;
   }
@@ -104435,8 +107562,8 @@ static int renameEditSql(
   char *zOut;
   int nQuot;
 
-  /* Set zQuot to point to a buffer containing a quoted copy of the 
-  ** identifier zNew. If the corresponding identifier in the original 
+  /* Set zQuot to point to a buffer containing a quoted copy of the
+  ** identifier zNew. If the corresponding identifier in the original
   ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
   ** point to zQuot so that all substitutions are made using the
   ** quoted version of the new column name.  */
@@ -104476,7 +107603,7 @@ static int renameEditSql(
 
       iOff = pBest->t.z - zSql;
       if( pBest->t.n!=nReplace ){
-        memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], 
+        memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
             nOut - (iOff + pBest->t.n)
         );
         nOut += nReplace - pBest->t.n;
@@ -104498,11 +107625,11 @@ static int renameEditSql(
 
 /*
 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
-** it was read from the schema of database zDb. Return SQLITE_OK if 
+** it was read from the schema of database zDb. Return SQLITE_OK if
 ** successful. Otherwise, return an SQLite error code and leave an error
 ** message in the Parse object.
 */
-static int renameResolveTrigger(Parse *pParse, const char *zDb){
+static int renameResolveTrigger(Parse *pParse){
   sqlite3 *db = pParse->db;
   Trigger *pNew = pParse->pNewTrigger;
   TriggerStep *pStep;
@@ -104512,7 +107639,7 @@ static int renameResolveTrigger(Parse *pParse, const char *zDb){
   memset(&sNC, 0, sizeof(sNC));
   sNC.pParse = pParse;
   assert( pNew->pTabSchema );
-  pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, 
+  pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
   );
   pParse->eTriggerOp = pNew->op;
@@ -104533,17 +107660,30 @@ static int renameResolveTrigger(Parse *pParse, const char *zDb){
       if( pParse->nErr ) rc = pParse->rc;
     }
     if( rc==SQLITE_OK && pStep->zTarget ){
-      Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
-      if( pTarget==0 ){
-        rc = SQLITE_ERROR;
-      }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
-        SrcList sSrc;
-        memset(&sSrc, 0, sizeof(sSrc));
-        sSrc.nSrc = 1;
-        sSrc.a[0].zName = pStep->zTarget;
-        sSrc.a[0].pTab = pTarget;
-        sNC.pSrcList = &sSrc;
-        if( pStep->pWhere ){
+      SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
+      if( pSrc ){
+        int i;
+        for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
+          struct SrcList_item *p = &pSrc->a[i];
+          p->iCursor = pParse->nTab++;
+          if( p->pSelect ){
+            sqlite3SelectPrep(pParse, p->pSelect, 0);
+            sqlite3ExpandSubquery(pParse, p);
+            assert( i>0 );
+            assert( pStep->pFrom->a[i-1].pSelect );
+            sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
+          }else{
+            p->pTab = sqlite3LocateTableItem(pParse, 0, p);
+            if( p->pTab==0 ){
+              rc = SQLITE_ERROR;
+            }else{
+              p->pTab->nTabRef++;
+              rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
+            }
+          }
+        }
+        sNC.pSrcList = pSrc;
+        if( rc==SQLITE_OK && pStep->pWhere ){
           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
         }
         if( rc==SQLITE_OK ){
@@ -104553,7 +107693,7 @@ static int renameResolveTrigger(Parse *pParse, const char *zDb){
         if( pStep->pUpsert ){
           Upsert *pUpsert = pStep->pUpsert;
           assert( rc==SQLITE_OK );
-          pUpsert->pUpsertSrc = &sSrc;
+          pUpsert->pUpsertSrc = pSrc;
           sNC.uNC.pUpsert = pUpsert;
           sNC.ncFlags = NC_UUpsert;
           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
@@ -104570,6 +107710,9 @@ static int renameResolveTrigger(Parse *pParse, const char *zDb){
           sNC.ncFlags = 0;
         }
         sNC.pSrcList = 0;
+        sqlite3SrcListDelete(db, pSrc);
+      }else{
+        rc = SQLITE_NOMEM;
       }
     }
   }
@@ -104598,6 +107741,12 @@ static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
     }
+    if( pStep->pFrom ){
+      int i;
+      for(i=0; i<pStep->pFrom->nSrc; i++){
+        sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
+      }
+    }
   }
 }
 
@@ -104688,7 +107837,7 @@ static void renameColumnFunc(
 #ifndef SQLITE_OMIT_AUTHORIZATION
   db->xAuth = 0;
 #endif
-  rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
+  rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
 
   /* Find tokens that need to be replaced. */
   memset(&sWalker, 0, sizeof(Walker));
@@ -104702,8 +107851,9 @@ static void renameColumnFunc(
   if( sParse.pNewTable ){
     Select *pSelect = sParse.pNewTable->pSelect;
     if( pSelect ){
+      pSelect->selFlags &= ~SF_View;
       sParse.rc = SQLITE_OK;
-      sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
+      sqlite3SelectPrep(&sParse, pSelect, 0);
       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
       if( rc==SQLITE_OK ){
         sqlite3WalkSelect(&sWalker, pSelect);
@@ -104730,6 +107880,11 @@ static void renameColumnFunc(
           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
         }
       }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+      for(i=0; i<sParse.pNewTable->nCol; i++){
+        sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
+      }
+#endif
 
       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
         for(i=0; i<pFKey->nCol; i++){
@@ -104750,11 +107905,11 @@ static void renameColumnFunc(
   }else{
     /* A trigger */
     TriggerStep *pStep;
-    rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
+    rc = renameResolveTrigger(&sParse);
     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
 
     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
-      if( pStep->zTarget ){ 
+      if( pStep->zTarget ){
         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
         if( pTarget==pTab ){
           if( pStep->pUpsert ){
@@ -104798,7 +107953,7 @@ renameColumnFunc_done:
 }
 
 /*
-** Walker expression callback used by "RENAME TABLE". 
+** Walker expression callback used by "RENAME TABLE".
 */
 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
   RenameCtx *p = pWalker->u.pRename;
@@ -104809,12 +107964,13 @@ static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
 }
 
 /*
-** Walker select callback used by "RENAME TABLE". 
+** Walker select callback used by "RENAME TABLE".
 */
 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
   int i;
   RenameCtx *p = pWalker->u.pRename;
   SrcList *pSrc = pSelect->pSrc;
+  if( pSelect->selFlags & SF_View ) return WRC_Prune;
   if( pSrc==0 ){
     assert( pWalker->pParse->db->mallocFailed );
     return WRC_Abort;
@@ -104834,7 +107990,7 @@ static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
 /*
 ** This C function implements an SQL user function that is used by SQL code
 ** generated by the ALTER TABLE ... RENAME command to modify the definition
-** of any foreign key constraints that use the table being renamed as the 
+** of any foreign key constraints that use the table being renamed as the
 ** parent table. It is passed three arguments:
 **
 **   0: The database containing the table being renamed.
@@ -104885,7 +108041,7 @@ static void renameTableFunc(
     sWalker.xSelectCallback = renameTableSelectCb;
     sWalker.u.pRename = &sCtx;
 
-    rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
 
     if( rc==SQLITE_OK ){
       int isLegacy = (db->flags & SQLITE_LegacyAlter);
@@ -104894,13 +108050,19 @@ static void renameTableFunc(
 
         if( pTab->pSelect ){
           if( isLegacy==0 ){
+            Select *pSelect = pTab->pSelect;
             NameContext sNC;
             memset(&sNC, 0, sizeof(sNC));
             sNC.pParse = &sParse;
 
+            assert( pSelect->selFlags & SF_View );
+            pSelect->selFlags &= ~SF_View;
             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
-            if( sParse.nErr ) rc = sParse.rc;
-            sqlite3WalkSelect(&sWalker, pTab->pSelect);
+            if( sParse.nErr ){
+              rc = sParse.rc;
+            }else{
+              sqlite3WalkSelect(&sWalker, pTab->pSelect);
+            }
           }
         }else{
           /* Modify any FK definitions to point to the new table. */
@@ -104939,14 +108101,14 @@ static void renameTableFunc(
       else{
         Trigger *pTrigger = sParse.pNewTrigger;
         TriggerStep *pStep;
-        if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) 
+        if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
             && sCtx.pTab->pSchema==pTrigger->pTabSchema
           ){
           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
         }
 
         if( isLegacy==0 ){
-          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
+          rc = renameResolveTrigger(&sParse);
           if( rc==SQLITE_OK ){
             renameWalkTrigger(&sWalker, pTrigger);
             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
@@ -105021,7 +108183,7 @@ static void renameTableTest(
   if( zDb && zInput ){
     int rc;
     Parse sParse;
-    rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
+    rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
     if( rc==SQLITE_OK ){
       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
         NameContext sNC;
@@ -105033,7 +108195,7 @@ static void renameTableTest(
 
       else if( sParse.pNewTrigger ){
         if( isLegacy==0 ){
-          rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
+          rc = renameResolveTrigger(&sParse);
         }
         if( rc==SQLITE_OK ){
           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
@@ -105101,7 +108263,7 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 ** created and used by SQLite versions 3.7.9 through 3.29.0 when
 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
 ** is a superset of sqlite_stat2 and is also now deprecated.  The
-** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only 
+** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
 ** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
 ** versions 3.8.1 and later.  STAT4 is the only variant that is still
 ** supported.
@@ -105120,7 +108282,7 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 ** integer is the average number of rows in the index that have the same
 ** value in the first column of the index.  The third integer is the average
 ** number of rows in the index that have the same value for the first two
-** columns.  The N-th integer (for N>1) is the average number of rows in 
+** columns.  The N-th integer (for N>1) is the average number of rows in
 ** the index which have the same value for the first N-1 columns.  For
 ** a K-column index, there will be K+1 integers in the stat column.  If
 ** the index is unique, then the last integer will be 1.
@@ -105130,7 +108292,7 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 ** must be separated from the last integer by a single space.  If the
 ** "unordered" keyword is present, then the query planner assumes that
 ** the index is unordered and will not use the index for a range query.
-** 
+**
 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
 ** column contains a single integer which is the (estimated) number of
 ** rows in the table identified by sqlite_stat1.tbl.
@@ -105188,9 +108350,9 @@ SQLITE_PRIVATE void sqlite3AlterFunctions(void){
 ** number of entries that are strictly less than the sample.  The first
 ** integer in nLt contains the number of entries in the index where the
 ** left-most column is less than the left-most column of the sample.
-** The K-th integer in the nLt entry is the number of index entries 
+** The K-th integer in the nLt entry is the number of index entries
 ** where the first K columns are less than the first K columns of the
-** sample.  The nDLt column is like nLt except that it contains the 
+** sample.  The nDLt column is like nLt except that it contains the
 ** number of distinct entries in the index that are less than the
 ** sample.
 **
@@ -105257,8 +108419,13 @@ static void openStatTable(
   sqlite3 *db = pParse->db;
   Db *pDb;
   Vdbe *v = sqlite3GetVdbe(pParse);
-  int aRoot[ArraySize(aTable)];
+  u32 aRoot[ArraySize(aTable)];
   u8 aCreateTbl[ArraySize(aTable)];
+#ifdef SQLITE_ENABLE_STAT4
+  const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
+#else
+  const int nToOpen = 1;
+#endif
 
   if( v==0 ) return;
   assert( sqlite3BtreeHoldsAllMutexes(db) );
@@ -105271,24 +108438,24 @@ static void openStatTable(
   for(i=0; i<ArraySize(aTable); i++){
     const char *zTab = aTable[i].zName;
     Table *pStat;
+    aCreateTbl[i] = 0;
     if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
-      if( aTable[i].zCols ){
-        /* The sqlite_statN table does not exist. Create it. Note that a 
-        ** side-effect of the CREATE TABLE statement is to leave the rootpage 
-        ** of the new table in register pParse->regRoot. This is important 
+      if( i<nToOpen ){
+        /* The sqlite_statN table does not exist. Create it. Note that a
+        ** side-effect of the CREATE TABLE statement is to leave the rootpage
+        ** of the new table in register pParse->regRoot. This is important
         ** because the OpenWrite opcode below will be needing it. */
         sqlite3NestedParse(pParse,
             "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
         );
-        aRoot[i] = pParse->regRoot;
+        aRoot[i] = (u32)pParse->regRoot;
         aCreateTbl[i] = OPFLAG_P2ISREG;
       }
     }else{
-      /* The table already exists. If zWhere is not NULL, delete all entries 
+      /* The table already exists. If zWhere is not NULL, delete all entries
       ** associated with the table zWhere. If zWhere is NULL, delete the
       ** entire contents of the table. */
       aRoot[i] = pStat->tnum;
-      aCreateTbl[i] = 0;
       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
       if( zWhere ){
         sqlite3NestedParse(pParse,
@@ -105301,15 +108468,15 @@ static void openStatTable(
 #endif
       }else{
         /* The sqlite_stat[134] table already exists.  Delete all rows. */
-        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
+        sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb);
       }
     }
   }
 
   /* Open the sqlite_stat[134] tables for writing. */
-  for(i=0; aTable[i].zCols; i++){
+  for(i=0; i<nToOpen; i++){
     assert( i<ArraySize(aTable) );
-    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
+    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, (int)aRoot[i], iDb, 3);
     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
     VdbeComment((v, aTable[i].zName));
   }
@@ -105327,9 +108494,9 @@ static void openStatTable(
 ** share an instance of the following structure to hold their state
 ** information.
 */
-typedef struct Stat4Accum Stat4Accum;
-typedef struct Stat4Sample Stat4Sample;
-struct Stat4Sample {
+typedef struct StatAccum StatAccum;
+typedef struct StatSample StatSample;
+struct StatSample {
   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
 #ifdef SQLITE_ENABLE_STAT4
@@ -105343,28 +108510,33 @@ struct Stat4Sample {
   int iCol;                       /* If !isPSample, the reason for inclusion */
   u32 iHash;                      /* Tiebreaker hash */
 #endif
-};                                                    
-struct Stat4Accum {
-  tRowcnt nRow;             /* Number of rows in the entire table */
-  tRowcnt nPSample;         /* How often to do a periodic sample */
+};
+struct StatAccum {
+  sqlite3 *db;              /* Database connection, for malloc() */
+  tRowcnt nEst;             /* Estimated number of rows */
+  tRowcnt nRow;             /* Number of rows visited so far */
+  int nLimit;               /* Analysis row-scan limit */
   int nCol;                 /* Number of columns in index + pk/rowid */
   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
+  u8 nSkipAhead;            /* Number of times of skip-ahead */
+  StatSample current;       /* Current row as a StatSample */
+#ifdef SQLITE_ENABLE_STAT4
+  tRowcnt nPSample;         /* How often to do a periodic sample */
   int mxSample;             /* Maximum number of samples to accumulate */
-  Stat4Sample current;      /* Current row as a Stat4Sample */
   u32 iPrn;                 /* Pseudo-random number used for sampling */
-  Stat4Sample *aBest;       /* Array of nCol best samples */
+  StatSample *aBest;        /* Array of nCol best samples */
   int iMin;                 /* Index in a[] of entry with minimum score */
   int nSample;              /* Current number of samples */
   int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
   int iGet;                 /* Index of current sample accessed by stat_get() */
-  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
-  sqlite3 *db;              /* Database connection, for malloc() */
+  StatSample *a;            /* Array of mxSample StatSample objects */
+#endif
 };
 
-/* Reclaim memory used by a Stat4Sample
+/* Reclaim memory used by a StatSample
 */
 #ifdef SQLITE_ENABLE_STAT4
-static void sampleClear(sqlite3 *db, Stat4Sample *p){
+static void sampleClear(sqlite3 *db, StatSample *p){
   assert( db!=0 );
   if( p->nRowid ){
     sqlite3DbFree(db, p->u.aRowid);
@@ -105376,7 +108548,7 @@ static void sampleClear(sqlite3 *db, Stat4Sample *p){
 /* Initialize the BLOB value of a ROWID
 */
 #ifdef SQLITE_ENABLE_STAT4
-static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
+static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
   assert( db!=0 );
   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   p->u.aRowid = sqlite3DbMallocRawNN(db, n);
@@ -105392,7 +108564,7 @@ static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
 /* Initialize the INTEGER value of a ROWID.
 */
 #ifdef SQLITE_ENABLE_STAT4
-static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
+static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
   assert( db!=0 );
   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   p->nRowid = 0;
@@ -105405,7 +108577,7 @@ static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
 ** Copy the contents of object (*pFrom) into (*pTo).
 */
 #ifdef SQLITE_ENABLE_STAT4
-static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
+static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
   pTo->isPSample = pFrom->isPSample;
   pTo->iCol = pFrom->iCol;
   pTo->iHash = pFrom->iHash;
@@ -105421,40 +108593,41 @@ static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
 #endif
 
 /*
-** Reclaim all memory of a Stat4Accum structure.
+** Reclaim all memory of a StatAccum structure.
 */
-static void stat4Destructor(void *pOld){
-  Stat4Accum *p = (Stat4Accum*)pOld;
+static void statAccumDestructor(void *pOld){
+  StatAccum *p = (StatAccum*)pOld;
 #ifdef SQLITE_ENABLE_STAT4
-  int i;
-  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
-  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
-  sampleClear(p->db, &p->current);
+  if( p->mxSample ){
+    int i;
+    for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
+    for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
+    sampleClear(p->db, &p->current);
+  }
 #endif
   sqlite3DbFree(p->db, p);
 }
 
 /*
-** Implementation of the stat_init(N,K,C) SQL function. The three parameters
+** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
 ** are:
 **     N:    The number of columns in the index including the rowid/pk (note 1)
 **     K:    The number of columns in the index excluding the rowid/pk.
-**     C:    The number of rows in the index (note 2)
+**     C:    Estimated number of rows in the index
+**     L:    A limit on the number of rows to scan, or 0 for no-limit
 **
 ** Note 1:  In the special case of the covering index that implements a
 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
 ** total number of columns in the table.
 **
-** Note 2:  C is only used for STAT4.
-**
 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
 ** PRIMARY KEY of the table.  The covering index that implements the
 ** original WITHOUT ROWID table as N==K as a special case.
 **
-** This routine allocates the Stat4Accum object in heap memory. The return 
-** value is a pointer to the Stat4Accum object.  The datatype of the
-** return value is BLOB, but it is really just a pointer to the Stat4Accum
+** This routine allocates the StatAccum object in heap memory. The return
+** value is a pointer to the StatAccum object.  The datatype of the
+** return value is BLOB, but it is really just a pointer to the StatAccum
 ** object.
 */
 static void statInit(
@@ -105462,14 +108635,15 @@ static void statInit(
   int argc,
   sqlite3_value **argv
 ){
-  Stat4Accum *p;
+  StatAccum *p;
   int nCol;                       /* Number of columns in index being sampled */
   int nKeyCol;                    /* Number of key columns */
   int nColUp;                     /* nCol rounded up for alignment */
   int n;                          /* Bytes of space to allocate */
-  sqlite3 *db;                    /* Database connection */
+  sqlite3 *db = sqlite3_context_db_handle(context);   /* Database connection */
 #ifdef SQLITE_ENABLE_STAT4
-  int mxSample = SQLITE_STAT4_SAMPLES;
+  /* Maximum number of samples.  0 if STAT4 data is not collected */
+  int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
 #endif
 
   /* Decode the three function arguments */
@@ -105481,16 +108655,17 @@ static void statInit(
   assert( nKeyCol<=nCol );
   assert( nKeyCol>0 );
 
-  /* Allocate the space required for the Stat4Accum object */
-  n = sizeof(*p) 
-    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
-    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
+  /* Allocate the space required for the StatAccum object */
+  n = sizeof(*p)
+    + sizeof(tRowcnt)*nColUp                  /* StatAccum.anEq */
+    + sizeof(tRowcnt)*nColUp;                 /* StatAccum.anDLt */
 #ifdef SQLITE_ENABLE_STAT4
-    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
-    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
-    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
+  if( mxSample ){
+    n += sizeof(tRowcnt)*nColUp                  /* StatAccum.anLt */
+      + sizeof(StatSample)*(nCol+mxSample)       /* StatAccum.aBest[], a[] */
+      + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
+  }
 #endif
-  ;
   db = sqlite3_context_db_handle(context);
   p = sqlite3DbMallocZero(db, n);
   if( p==0 ){
@@ -105499,25 +108674,28 @@ static void statInit(
   }
 
   p->db = db;
+  p->nEst = sqlite3_value_int64(argv[2]);
   p->nRow = 0;
+  p->nLimit = sqlite3_value_int64(argv[3]);
   p->nCol = nCol;
   p->nKeyCol = nKeyCol;
+  p->nSkipAhead = 0;
   p->current.anDLt = (tRowcnt*)&p[1];
   p->current.anEq = &p->current.anDLt[nColUp];
 
 #ifdef SQLITE_ENABLE_STAT4
-  {
+  p->mxSample = p->nLimit==0 ? mxSample : 0;
+  if( mxSample ){
     u8 *pSpace;                     /* Allocated space not yet assigned */
     int i;                          /* Used to iterate through p->aSample[] */
 
     p->iGet = -1;
-    p->mxSample = mxSample;
-    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
+    p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
     p->current.anLt = &p->current.anEq[nColUp];
     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
-  
-    /* Set up the Stat4Accum.a[] and aBest[] arrays */
-    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
+
+    /* Set up the StatAccum.a[] and aBest[] arrays */
+    p->a = (struct StatSample*)&p->current.anLt[nColUp];
     p->aBest = &p->a[mxSample];
     pSpace = (u8*)(&p->a[mxSample+nCol]);
     for(i=0; i<(mxSample+nCol); i++){
@@ -105526,7 +108704,7 @@ static void statInit(
       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
     }
     assert( (pSpace - (u8*)p)==n );
-  
+
     for(i=0; i<nCol; i++){
       p->aBest[i].iCol = i;
     }
@@ -105537,10 +108715,10 @@ static void statInit(
   ** only the pointer (the 2nd parameter) matters.  The size of the object
   ** (given by the 3rd parameter) is never used and can be any positive
   ** value. */
-  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
+  sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
 }
 static const FuncDef statInitFuncdef = {
-  2+IsStat4,       /* nArg */
+  4,               /* nArg */
   SQLITE_UTF8,     /* funcFlags */
   0,               /* pUserData */
   0,               /* pNext */
@@ -105553,20 +108731,20 @@ static const FuncDef statInitFuncdef = {
 
 #ifdef SQLITE_ENABLE_STAT4
 /*
-** pNew and pOld are both candidate non-periodic samples selected for 
-** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
+** pNew and pOld are both candidate non-periodic samples selected for
+** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
 ** considering only any trailing columns and the sample hash value, this
 ** function returns true if sample pNew is to be preferred over pOld.
 ** In other words, if we assume that the cardinalities of the selected
 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
 **
 ** This function assumes that for each argument sample, the contents of
-** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
+** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
 */
 static int sampleIsBetterPost(
-  Stat4Accum *pAccum, 
-  Stat4Sample *pNew, 
-  Stat4Sample *pOld
+  StatAccum *pAccum,
+  StatSample *pNew,
+  StatSample *pOld
 ){
   int nCol = pAccum->nCol;
   int i;
@@ -105585,12 +108763,12 @@ static int sampleIsBetterPost(
 ** Return true if pNew is to be preferred over pOld.
 **
 ** This function assumes that for each argument sample, the contents of
-** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
+** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
 */
 static int sampleIsBetter(
-  Stat4Accum *pAccum, 
-  Stat4Sample *pNew, 
-  Stat4Sample *pOld
+  StatAccum *pAccum,
+  StatSample *pNew,
+  StatSample *pOld
 ){
   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
@@ -105610,30 +108788,30 @@ static int sampleIsBetter(
 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
 ** remove the least desirable sample from p->a[] to make room.
 */
-static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
-  Stat4Sample *pSample = 0;
+static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
+  StatSample *pSample = 0;
   int i;
 
   assert( IsStat4 || nEqZero==0 );
 
-  /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
-  ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
+  /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
+  ** values in the anEq[] array of any sample in StatAccum.a[]. In
   ** other words, if nMaxEqZero is n, then it is guaranteed that there
-  ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
+  ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
   if( nEqZero>p->nMaxEqZero ){
     p->nMaxEqZero = nEqZero;
   }
   if( pNew->isPSample==0 ){
-    Stat4Sample *pUpgrade = 0;
+    StatSample *pUpgrade = 0;
     assert( pNew->anEq[pNew->iCol]>0 );
 
-    /* This sample is being added because the prefix that ends in column 
+    /* This sample is being added because the prefix that ends in column
     ** iCol occurs many times in the table. However, if we have already
     ** added a sample that shares this prefix, there is no need to add
     ** this one. Instead, upgrade the priority of the highest priority
     ** existing sample that shares this prefix.  */
     for(i=p->nSample-1; i>=0; i--){
-      Stat4Sample *pOld = &p->a[i];
+      StatSample *pOld = &p->a[i];
       if( pOld->anEq[pNew->iCol]==0 ){
         if( pOld->isPSample ) return;
         assert( pOld->iCol>pNew->iCol );
@@ -105652,7 +108830,7 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
 
   /* If necessary, remove sample iMin to make room for the new sample. */
   if( p->nSample>=p->mxSample ){
-    Stat4Sample *pMin = &p->a[p->iMin];
+    StatSample *pMin = &p->a[p->iMin];
     tRowcnt *anEq = pMin->anEq;
     tRowcnt *anLt = pMin->anLt;
     tRowcnt *anDLt = pMin->anDLt;
@@ -105669,7 +108847,7 @@ static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
   /* The "rows less-than" for the rowid column must be greater than that
   ** for the last sample in the p->a[] array. Otherwise, the samples would
   ** be out of order. */
-  assert( p->nSample==0 
+  assert( p->nSample==0
        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
 
   /* Insert the new sample */
@@ -105695,20 +108873,20 @@ find_new_min:
 }
 #endif /* SQLITE_ENABLE_STAT4 */
 
+#ifdef SQLITE_ENABLE_STAT4
 /*
 ** Field iChng of the index being scanned has changed. So at this point
 ** p->current contains a sample that reflects the previous row of the
 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
 ** correct at this point.
 */
-static void samplePushPrevious(Stat4Accum *p, int iChng){
-#ifdef SQLITE_ENABLE_STAT4
+static void samplePushPrevious(StatAccum *p, int iChng){
   int i;
 
   /* Check if any samples from the aBest[] array should be pushed
   ** into IndexSample.a[] at this point.  */
   for(i=(p->nCol-2); i>=iChng; i--){
-    Stat4Sample *pBest = &p->aBest[i];
+    StatSample *pBest = &p->aBest[i];
     pBest->anEq[i] = p->current.anEq[i];
     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
       sampleInsert(p, pBest, i);
@@ -105732,27 +108910,25 @@ static void samplePushPrevious(Stat4Accum *p, int iChng){
     }
     p->nMaxEqZero = iChng;
   }
-#endif
-
-#ifndef SQLITE_ENABLE_STAT4
-  UNUSED_PARAMETER( p );
-  UNUSED_PARAMETER( iChng );
-#endif
 }
+#endif /* SQLITE_ENABLE_STAT4 */
 
 /*
 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
 ** Arguments:
 **
-**    P     Pointer to the Stat4Accum object created by stat_init()
+**    P     Pointer to the StatAccum object created by stat_init()
 **    C     Index of left-most column to differ from previous row
 **    R     Rowid for the current row.  Might be a key record for
 **          WITHOUT ROWID tables.
 **
-** This SQL function always returns NULL.  It's purpose it to accumulate
-** statistical data and/or samples in the Stat4Accum object about the
-** index being analyzed.  The stat_get() SQL function will later be used to
-** extract relevant information for constructing the sqlite_statN tables.
+** The purpose of this routine is to collect statistical data and/or
+** samples from the index being analyzed into the StatAccum object.
+** The stat_get() SQL function will be used afterwards to
+** retrieve the information gathered.
+**
+** This SQL function usually returns NULL, but might return an integer
+** if it wants the byte-code to do special processing.
 **
 ** The R parameter is only used for STAT4
 */
@@ -105764,7 +108940,7 @@ static void statPush(
   int i;
 
   /* The three function arguments */
-  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
+  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
   int iChng = sqlite3_value_int(argv[1]);
 
   UNUSED_PARAMETER( argc );
@@ -105777,7 +108953,9 @@ static void statPush(
     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
   }else{
     /* Second and subsequent calls get processed here */
-    samplePushPrevious(p, iChng);
+#ifdef SQLITE_ENABLE_STAT4
+    if( p->mxSample ) samplePushPrevious(p, iChng);
+#endif
 
     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
     ** to the current row of the index. */
@@ -105787,26 +108965,25 @@ static void statPush(
     for(i=iChng; i<p->nCol; i++){
       p->current.anDLt[i]++;
 #ifdef SQLITE_ENABLE_STAT4
-      p->current.anLt[i] += p->current.anEq[i];
+      if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
 #endif
       p->current.anEq[i] = 1;
     }
   }
-  p->nRow++;
-#ifdef SQLITE_ENABLE_STAT4
-  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
-    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
-  }else{
-    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
-                                       sqlite3_value_blob(argv[2]));
-  }
-  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
-#endif
 
+  p->nRow++;
 #ifdef SQLITE_ENABLE_STAT4
-  {
-    tRowcnt nLt = p->current.anLt[p->nCol-1];
+  if( p->mxSample ){
+    tRowcnt nLt;
+    if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
+      sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
+    }else{
+      sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
+                                         sqlite3_value_blob(argv[2]));
+    }
+    p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
 
+    nLt = p->current.anLt[p->nCol-1];
     /* Check if this is to be a periodic sample. If so, add it. */
     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
       p->current.isPSample = 1;
@@ -105822,9 +108999,14 @@ static void statPush(
         sampleCopy(p, &p->aBest[i], &p->current);
       }
     }
-  }
+  }else
 #endif
+  if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
+    p->nSkipAhead++;
+    sqlite3_result_int(context, p->current.anDLt[0]>0);
+  }
 }
+
 static const FuncDef statPushFuncdef = {
   2+IsStat4,       /* nArg */
   SQLITE_UTF8,     /* funcFlags */
@@ -105846,15 +109028,15 @@ static const FuncDef statPushFuncdef = {
 /*
 ** Implementation of the stat_get(P,J) SQL function.  This routine is
 ** used to query statistical information that has been gathered into
-** the Stat4Accum object by prior calls to stat_push().  The P parameter
-** has type BLOB but it is really just a pointer to the Stat4Accum object.
+** the StatAccum object by prior calls to stat_push().  The P parameter
+** has type BLOB but it is really just a pointer to the StatAccum object.
 ** The content to returned is determined by the parameter J
 ** which is one of the STAT_GET_xxxx values defined above.
 **
 ** The stat_get(P,J) function is not available to generic SQL.  It is
 ** inserted as part of a manually constructed bytecode program.  (See
 ** the callStatGet() routine below.)  It is guaranteed that the P
-** parameter will always be a poiner to a Stat4Accum object, never a
+** parameter will always be a pointer to a StatAccum object, never a
 ** NULL.
 **
 ** If STAT4 is not enabled, then J is always
@@ -105867,15 +109049,16 @@ static void statGet(
   int argc,
   sqlite3_value **argv
 ){
-  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
+  StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
 #ifdef SQLITE_ENABLE_STAT4
   /* STAT4 has a parameter on this routine. */
   int eCall = sqlite3_value_int(argv[1]);
   assert( argc==2 );
-  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
+  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
-       || eCall==STAT_GET_NDLT 
+       || eCall==STAT_GET_NDLT
   );
+  assert( eCall==STAT_GET_STAT1 || p->mxSample );
   if( eCall==STAT_GET_STAT1 )
 #else
   assert( argc==1 );
@@ -105884,20 +109067,20 @@ static void statGet(
     /* Return the value to store in the "stat" column of the sqlite_stat1
     ** table for this index.
     **
-    ** The value is a string composed of a list of integers describing 
-    ** the index. The first integer in the list is the total number of 
-    ** entries in the index. There is one additional integer in the list 
+    ** The value is a string composed of a list of integers describing
+    ** the index. The first integer in the list is the total number of
+    ** entries in the index. There is one additional integer in the list
     ** for each indexed column. This additional integer is an estimate of
-    ** the number of rows matched by a stabbing query on the index using
+    ** the number of rows matched by a equality query on the index using
     ** a key with the corresponding number of fields. In other words,
-    ** if the index is on columns (a,b) and the sqlite_stat1 value is 
+    ** if the index is on columns (a,b) and the sqlite_stat1 value is
     ** "100 10 2", then SQLite estimates that:
     **
     **   * the index contains 100 rows,
     **   * "WHERE a=?" matches 10 rows, and
     **   * "WHERE a=? AND b=?" matches 2 rows.
     **
-    ** If D is the count of distinct values and K is the total number of 
+    ** If D is the count of distinct values and K is the total number of
     ** rows, then each estimate is computed as:
     **
     **        I = (K+D-1)/D
@@ -105911,7 +109094,8 @@ static void statGet(
       return;
     }
 
-    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
+    sqlite3_snprintf(24, zRet, "%llu",
+        p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
     z = zRet + sqlite3Strlen30(zRet);
     for(i=0; i<p->nKeyCol; i++){
       u64 nDistinct = p->current.anDLt[i] + 1;
@@ -105931,7 +109115,7 @@ static void statGet(
       p->iGet = 0;
     }
     if( p->iGet<p->nSample ){
-      Stat4Sample *pS = p->a + p->iGet;
+      StatSample *pS = p->a + p->iGet;
       if( pS->nRowid==0 ){
         sqlite3_result_int64(context, pS->u.iRowid);
       }else{
@@ -105947,7 +109131,7 @@ static void statGet(
       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
       default: {
-        aCnt = p->a[p->iGet].anDLt; 
+        aCnt = p->a[p->iGet].anDLt;
         p->iGet++;
         break;
       }
@@ -105987,19 +109171,42 @@ static const FuncDef statGetFuncdef = {
   {0}
 };
 
-static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
-  assert( regOut!=regStat4 && regOut!=regStat4+1 );
+static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
 #ifdef SQLITE_ENABLE_STAT4
-  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
+  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
 #elif SQLITE_DEBUG
   assert( iParam==STAT_GET_STAT1 );
 #else
   UNUSED_PARAMETER( iParam );
 #endif
-  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
-                    (char*)&statGetFuncdef, P4_FUNCDEF);
-  sqlite3VdbeChangeP5(v, 1 + IsStat4);
+  assert( regOut!=regStat && regOut!=regStat+1 );
+  sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
+                             &statGetFuncdef, 0);
+}
+
+#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
+/* Add a comment to the most recent VDBE opcode that is the name
+** of the k-th column of the pIdx index.
+*/
+static void analyzeVdbeCommentIndexWithColumnName(
+  Vdbe *v,         /* Prepared statement under construction */
+  Index *pIdx,     /* Index whose column is being loaded */
+  int k            /* Which column index */
+){
+  int i;           /* Index of column in the table */
+  assert( k>=0 && k<pIdx->nColumn );
+  i = pIdx->aiColumn[k];
+  if( NEVER(i==XN_ROWID) ){
+    VdbeComment((v,"%s.rowid",pIdx->zName));
+  }else if( i==XN_EXPR ){
+    VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
+  }else{
+    VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zName));
+  }
 }
+#else
+# define analyzeVdbeCommentIndexWithColumnName(a,b,c)
+#endif /* SQLITE_DEBUG */
 
 /*
 ** Generate code to do an analysis of all indices associated with
@@ -106023,18 +109230,17 @@ static void analyzeOneTable(
   int iDb;                     /* Index of database containing pTab */
   u8 needTableCnt = 1;         /* True to count the table */
   int regNewRowid = iMem++;    /* Rowid for the inserted record */
-  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
+  int regStat = iMem++;        /* Register to hold StatAccum object */
   int regChng = iMem++;        /* Index of changed index field */
-#ifdef SQLITE_ENABLE_STAT4
   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
-#endif
   int regTemp = iMem++;        /* Temporary use register */
+  int regTemp2 = iMem++;       /* Second temporary use register */
   int regTabname = iMem++;     /* Register containing table name */
   int regIdxname = iMem++;     /* Register containing index name */
   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
   int regPrev = iMem;          /* MUST BE LAST (see below) */
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
-  Table *pStat1 = 0; 
+  Table *pStat1 = 0;
 #endif
 
   pParse->nMem = MAX(pParse->nMem, iMem);
@@ -106073,7 +109279,7 @@ static void analyzeOneTable(
   }
 #endif
 
-  /* Establish a read-lock on the table at the shared-cache level. 
+  /* Establish a read-lock on the table at the shared-cache level.
   ** Open a read-only cursor on the table. Also allocate a cursor number
   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
   ** this time though.  */
@@ -106139,9 +109345,9 @@ static void analyzeOneTable(
     **  end_of_scan:
     */
 
-    /* Make sure there are enough memory cells allocated to accommodate 
+    /* Make sure there are enough memory cells allocated to accommodate
     ** the regPrev array and a trailing rowid (the rowid slot is required
-    ** when building a record to insert into the sample column of 
+    ** when building a record to insert into the sample column of
     ** the sqlite_stat4 table.  */
     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
 
@@ -106152,23 +109358,31 @@ static void analyzeOneTable(
     VdbeComment((v, "%s", pIdx->zName));
 
     /* Invoke the stat_init() function. The arguments are:
-    ** 
+    **
     **    (1) the number of columns in the index including the rowid
     **        (or for a WITHOUT ROWID table, the number of PK columns),
     **    (2) the number of columns in the key without the rowid/pk
-    **    (3) the number of rows in the index,
-    **
-    **
-    ** The third argument is only used for STAT4
+    **    (3) estimated number of rows in the index,
     */
+    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
+    assert( regRowid==regStat+2 );
+    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
 #ifdef SQLITE_ENABLE_STAT4
-    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
+    if( OptimizationEnabled(db, SQLITE_Stat4) ){
+      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);
+      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
+      VdbeCoverage(v);
+    }else
 #endif
-    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
-    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
-    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
-                     (char*)&statInitFuncdef, P4_FUNCDEF);
-    sqlite3VdbeChangeP5(v, 2+IsStat4);
+    {
+      addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
+      VdbeCoverage(v);
+      sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);
+    }
+    assert( regTemp2==regStat+4 );
+    sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
+    sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
+                               &statInitFuncdef, 0);
 
     /* Implementation of the following:
     **
@@ -106178,8 +109392,6 @@ static void analyzeOneTable(
     **   goto next_push_0;
     **
     */
-    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
-    VdbeCoverage(v);
     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
     addrNextRow = sqlite3VdbeCurrentAddr(v);
 
@@ -106203,7 +109415,7 @@ static void analyzeOneTable(
       addrNextRow = sqlite3VdbeCurrentAddr(v);
       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
         /* For a single-column UNIQUE index, once we have found a non-NULL
-        ** row, we know that all the rest will be distinct, so skip 
+        ** row, we know that all the rest will be distinct, so skip
         ** subsequent distinctness tests. */
         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
         VdbeCoverage(v);
@@ -106212,15 +109424,16 @@ static void analyzeOneTable(
         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
-        aGotoChng[i] = 
+        analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
+        aGotoChng[i] =
         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
         VdbeCoverage(v);
       }
       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
       sqlite3VdbeGoto(v, endDistinctTest);
-  
-  
+
+
       /*
       **  chng_addr_0:
       **   regPrev(0) = idx(0)
@@ -106232,11 +109445,12 @@ static void analyzeOneTable(
       for(i=0; i<nColTest; i++){
         sqlite3VdbeJumpHere(v, aGotoChng[i]);
         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
+        analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
       }
       sqlite3VdbeResolveLabel(v, endDistinctTest);
       sqlite3DbFree(db, aGotoChng);
     }
-  
+
     /*
     **  chng_addr_N:
     **   regRowid = idx(rowid)            // STAT4 only
@@ -106245,31 +109459,46 @@ static void analyzeOneTable(
     **   if !eof(csr) goto next_row;
     */
 #ifdef SQLITE_ENABLE_STAT4
-    assert( regRowid==(regStat4+2) );
-    if( HasRowid(pTab) ){
-      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
-    }else{
-      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
-      int j, k, regKey;
-      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
-      for(j=0; j<pPk->nKeyCol; j++){
-        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
-        assert( k>=0 && k<pIdx->nColumn );
-        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
-        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
+    if( OptimizationEnabled(db, SQLITE_Stat4) ){
+      assert( regRowid==(regStat+2) );
+      if( HasRowid(pTab) ){
+        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
+      }else{
+        Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
+        int j, k, regKey;
+        regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
+        for(j=0; j<pPk->nKeyCol; j++){
+          k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
+          assert( k>=0 && k<pIdx->nColumn );
+          sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
+          analyzeVdbeCommentIndexWithColumnName(v,pIdx,k);
+        }
+        sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
+        sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
       }
-      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
-      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
     }
 #endif
-    assert( regChng==(regStat4+1) );
-    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
-                     (char*)&statPushFuncdef, P4_FUNCDEF);
-    sqlite3VdbeChangeP5(v, 2+IsStat4);
-    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
+    assert( regChng==(regStat+1) );
+    {
+      sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
+                                 &statPushFuncdef, 0);
+      if( db->nAnalysisLimit ){
+        int j1, j2, j3;
+        j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
+        j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
+        j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
+        VdbeCoverage(v);
+        sqlite3VdbeJumpHere(v, j1);
+        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
+        sqlite3VdbeJumpHere(v, j2);
+        sqlite3VdbeJumpHere(v, j3);
+      }else{
+        sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
+      }
+    }
 
     /* Add the entry to the stat1 table. */
-    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
+    callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
     assert( "BBB"[0]==SQLITE_AFF_TEXT );
     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
@@ -106281,7 +109510,7 @@ static void analyzeOneTable(
 
     /* Add the entries to the stat4 table. */
 #ifdef SQLITE_ENABLE_STAT4
-    {
+    if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
       int regEq = regStat1;
       int regLt = regStat1+1;
       int regDLt = regStat1+2;
@@ -106295,12 +109524,12 @@ static void analyzeOneTable(
       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
 
       addrNext = sqlite3VdbeCurrentAddr(v);
-      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
+      callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
       VdbeCoverage(v);
-      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
-      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
-      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
+      callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
+      callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
+      callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
       VdbeCoverage(v);
       for(i=0; i<nCol; i++){
@@ -106541,7 +109770,7 @@ static void decodeIntArray(
 
 /*
 ** This callback is invoked once for each index when reading the
-** sqlite_stat1 table.  
+** sqlite_stat1 table.
 **
 **     argv[0] = name of the table
 **     argv[1] = name of the index (might be NULL)
@@ -106579,7 +109808,7 @@ static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
     tRowcnt *aiRowEst = 0;
     int nCol = pIndex->nKeyCol+1;
 #ifdef SQLITE_ENABLE_STAT4
-    /* Index.aiRowEst may already be set here if there are duplicate 
+    /* Index.aiRowEst may already be set here if there are duplicate
     ** sqlite_stat1 entries for this index. In that case just clobber
     ** the old data with the new instead of allocating a new array.  */
     if( pIndex->aiRowEst==0 ){
@@ -106636,7 +109865,7 @@ SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
 #ifdef SQLITE_ENABLE_STAT4
 /*
 ** Populate the pIdx->aAvgEq[] array based on the samples currently
-** stored in pIdx->aSample[]. 
+** stored in pIdx->aSample[].
 */
 static void initAvgEq(Index *pIdx){
   if( pIdx ){
@@ -106672,12 +109901,12 @@ static void initAvgEq(Index *pIdx){
       pIdx->nRowEst0 = nRow;
 
       /* Set nSum to the number of distinct (iCol+1) field prefixes that
-      ** occur in the stat4 table for this index. Set sumEq to the sum of 
-      ** the nEq values for column iCol for the same set (adding the value 
+      ** occur in the stat4 table for this index. Set sumEq to the sum of
+      ** the nEq values for column iCol for the same set (adding the value
       ** only once where there exist duplicate prefixes).  */
       for(i=0; i<nSample; i++){
         if( i==(pIdx->nSample-1)
-         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
+         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
         ){
           sumEq += aSample[i].anEq[iCol];
           nSum100 += 100;
@@ -106777,6 +110006,7 @@ static int loadStatTbl(
     }
     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
+    pIdx->pTable->tabFlags |= TF_HasStat4;
     for(i=0; i<nSample; i++){
       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
@@ -106804,7 +110034,7 @@ static int loadStatTbl(
     if( zIndex==0 ) continue;
     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
     if( pIdx==0 ) continue;
-    /* This next condition is true if data has already been loaded from 
+    /* This next condition is true if data has already been loaded from
     ** the sqlite_stat4 table. */
     nCol = pIdx->nSampleCol;
     if( pIdx!=pPrevIdx ){
@@ -106839,7 +110069,7 @@ static int loadStatTbl(
 }
 
 /*
-** Load content from the sqlite_stat4 table into 
+** Load content from the sqlite_stat4 table into
 ** the Index.aSample[] arrays of all indices.
 */
 static int loadStat4(sqlite3 *db, const char *zDb){
@@ -106848,7 +110078,7 @@ static int loadStat4(sqlite3 *db, const char *zDb){
   assert( db->lookaside.bDisable );
   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
     rc = loadStatTbl(db,
-      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
+      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
       zDb
     );
@@ -106864,11 +110094,11 @@ static int loadStat4(sqlite3 *db, const char *zDb){
 ** Index.aSample[] arrays.
 **
 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
-** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined 
-** during compilation and the sqlite_stat4 table is present, no data is 
+** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
+** during compilation and the sqlite_stat4 table is present, no data is
 ** read from it.
 **
-** If SQLITE_ENABLE_STAT4 was defined during compilation and the 
+** If SQLITE_ENABLE_STAT4 was defined during compilation and the
 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
 ** returned. However, in this case, data is read from the sqlite_stat1
 ** table (if it is present) before returning.
@@ -106906,7 +110136,7 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   sInfo.db = db;
   sInfo.zDatabase = db->aDb[iDb].zDbSName;
   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
-    zSql = sqlite3MPrintf(db, 
+    zSql = sqlite3MPrintf(db,
         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
     if( zSql==0 ){
       rc = SQLITE_NOMEM_BKPT;
@@ -106926,9 +110156,9 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
   /* Load the statistics from the sqlite_stat4 table. */
 #ifdef SQLITE_ENABLE_STAT4
   if( rc==SQLITE_OK ){
-    db->lookaside.bDisable++;
+    DisableLookaside;
     rc = loadStat4(db, sInfo.zDatabase);
-    db->lookaside.bDisable--;
+    EnableLookaside;
   }
   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
     Index *pIdx = sqliteHashData(i);
@@ -106996,6 +110226,17 @@ static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
 }
 
 /*
+** Return true if zName points to a name that may be used to refer to
+** database iDb attached to handle db.
+*/
+SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){
+  return (
+      sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
+   || (iDb==0 && sqlite3StrICmp("main", zName)==0)
+  );
+}
+
+/*
 ** An SQL user-function registered to do the work of an ATTACH statement. The
 ** three arguments to the function come directly from an attach statement:
 **
@@ -107061,20 +110302,19 @@ static void attachFunc(
     **     * Specified database name already being used.
     */
     if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
-      zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
+      zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
         db->aLimit[SQLITE_LIMIT_ATTACHED]
       );
       goto attach_error;
     }
     for(i=0; i<db->nDb; i++){
-      const char *z = db->aDb[i].zDbSName;
-      assert( z && zName );
-      if( sqlite3StrICmp(z, zName)==0 ){
+      assert( zName );
+      if( sqlite3DbIsNamed(db, i, zName) ){
         zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
         goto attach_error;
       }
     }
-  
+
     /* Allocate the new entry in the db->aDb[] array and initialize the schema
     ** hash tables.
     */
@@ -107089,7 +110329,7 @@ static void attachFunc(
     db->aDb = aNew;
     pNew = &db->aDb[db->nDb];
     memset(pNew, 0, sizeof(*pNew));
-  
+
     /* Open the database file. If the btree is successfully opened, use
     ** it to obtain the database schema. At this point the schema may
     ** or may not be initialized.
@@ -107118,7 +110358,7 @@ static void attachFunc(
     if( !pNew->pSchema ){
       rc = SQLITE_NOMEM_BKPT;
     }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
-      zErrDyn = sqlite3MPrintf(db, 
+      zErrDyn = sqlite3MPrintf(db,
         "attached databases must use the same text encoding as main database");
       rc = SQLITE_ERROR;
     }
@@ -107137,46 +110377,10 @@ static void attachFunc(
   if( rc==SQLITE_OK && pNew->zDbSName==0 ){
     rc = SQLITE_NOMEM_BKPT;
   }
-
-
-#ifdef SQLITE_HAS_CODEC
-  if( rc==SQLITE_OK ){
-    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
-    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
-    int nKey;
-    char *zKey;
-    int t = sqlite3_value_type(argv[2]);
-    switch( t ){
-      case SQLITE_INTEGER:
-      case SQLITE_FLOAT:
-        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
-        rc = SQLITE_ERROR;
-        break;
-        
-      case SQLITE_TEXT:
-      case SQLITE_BLOB:
-        nKey = sqlite3_value_bytes(argv[2]);
-        zKey = (char *)sqlite3_value_blob(argv[2]);
-        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
-        break;
-
-      case SQLITE_NULL:
-        /* No key specified.  Use the key from URI filename, or if none,
-        ** use the key from the main database. */
-        if( sqlite3CodecQueryParameters(db, zName, zPath)==0 ){
-          sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
-          if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
-            rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
-          }
-        }
-        break;
-    }
-  }
-#endif
-  sqlite3_free( zPath );
+  sqlite3_free_filename( zPath );
 
   /* If the file was opened successfully, read the schema for the new database.
-  ** If this fails, or if opening the file failed, then close the file and 
+  ** If this fails, or if opening the file failed, then close the file and
   ** remove the entry from the db->aDb[] array. i.e. put everything back the
   ** way we found it.
   */
@@ -107220,7 +110424,7 @@ static void attachFunc(
     }
     goto attach_error;
   }
-  
+
   return;
 
 attach_error:
@@ -107258,7 +110462,7 @@ static void detachFunc(
   for(i=0; i<db->nDb; i++){
     pDb = &db->aDb[i];
     if( pDb->pBt==0 ) continue;
-    if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
+    if( sqlite3DbIsNamed(db, i, zName) ) break;
   }
 
   if( i>=db->nDb ){
@@ -107269,7 +110473,9 @@ static void detachFunc(
     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
     goto detach_error;
   }
-  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
+  if( sqlite3BtreeTxnState(pDb->pBt)!=SQLITE_TXN_NONE
+   || sqlite3BtreeIsInBackup(pDb->pBt)
+  ){
     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
     goto detach_error;
   }
@@ -107319,7 +110525,7 @@ static void codeAttach(
   memset(&sName, 0, sizeof(NameContext));
   sName.pParse = pParse;
 
-  if( 
+  if(
       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
@@ -107351,18 +110557,15 @@ static void codeAttach(
 
   assert( v || db->mallocFailed );
   if( v ){
-    sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
-                      (char *)pFunc, P4_FUNCDEF);
-    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
-    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
+    sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
+                               pFunc->nArg, pFunc, 0);
     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
     ** statement only). For DETACH, set it to false (expire all existing
     ** statements).
     */
     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
   }
-  
+
 attach_end:
   sqlite3ExprDelete(db, pFilename);
   sqlite3ExprDelete(db, pDbname);
@@ -107430,7 +110633,7 @@ SQLITE_PRIVATE void sqlite3FixInit(
   pFix->pSchema = db->aDb[iDb].pSchema;
   pFix->zType = zType;
   pFix->pName = pName;
-  pFix->bVarOnly = (iDb==1);
+  pFix->bTemp = (iDb==1);
 }
 
 /*
@@ -107452,22 +110655,24 @@ SQLITE_PRIVATE int sqlite3FixSrcList(
   SrcList *pList       /* The Source list to check and modify */
 ){
   int i;
-  const char *zDb;
   struct SrcList_item *pItem;
+  sqlite3 *db = pFix->pParse->db;
+  int iDb = sqlite3FindDbName(db, pFix->zDb);
 
   if( NEVER(pList==0) ) return 0;
-  zDb = pFix->zDb;
+
   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
-    if( pFix->bVarOnly==0 ){
-      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
+    if( pFix->bTemp==0 ){
+      if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
         sqlite3ErrorMsg(pFix->pParse,
             "%s %T cannot reference objects in database %s",
             pFix->zType, pFix->pName, pItem->zDatabase);
         return 1;
       }
-      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
+      sqlite3DbFree(db, pItem->zDatabase);
       pItem->zDatabase = 0;
       pItem->pSchema = pFix->pSchema;
+      pItem->fg.fromDDL = 1;
     }
 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
@@ -107523,7 +110728,7 @@ SQLITE_PRIVATE int sqlite3FixExpr(
   Expr *pExpr        /* The expression to be fixed to one database */
 ){
   while( pExpr ){
-    ExprSetProperty(pExpr, EP_Indirect);
+    if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
     if( pExpr->op==TK_VARIABLE ){
       if( pFix->pParse->db->init.busy ){
         pExpr->op = TK_NULL;
@@ -107576,6 +110781,9 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep(
     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
       return 1;
     }
+    if( pStep->pFrom && sqlite3FixSrcList(pFix, pStep->pFrom) ){
+      return 1;
+    }
 #ifndef SQLITE_OMIT_UPSERT
     if( pStep->pUpsert ){
       Upsert *pUp = pStep->pUpsert;
@@ -107728,10 +110936,10 @@ SQLITE_PRIVATE int sqlite3AuthReadCol(
 
 /*
 ** The pExpr should be a TK_COLUMN expression.  The table referred to
-** is in pTabList or else it is the NEW or OLD table of a trigger.  
+** is in pTabList or else it is the NEW or OLD table of a trigger.
 ** Check to see if it is OK to read this particular column.
 **
-** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
+** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
 ** then generate an error.
 */
@@ -107848,7 +111056,7 @@ SQLITE_PRIVATE int sqlite3AuthCheck(
 */
 SQLITE_PRIVATE void sqlite3AuthContextPush(
   Parse *pParse,
-  AuthContext *pContext, 
+  AuthContext *pContext,
   const char *zContext
 ){
   assert( pParse );
@@ -107905,13 +111113,13 @@ SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
 */
 struct TableLock {
   int iDb;               /* The database containing the table to be locked */
-  int iTab;              /* The root page of the table to be locked */
+  Pgno iTab;             /* The root page of the table to be locked */
   u8 isWriteLock;        /* True for write lock.  False for a read lock */
   const char *zLockName; /* Name of the table */
 };
 
 /*
-** Record the fact that we want to lock a table at run-time.  
+** Record the fact that we want to lock a table at run-time.
 **
 ** The table to be locked has root page iTab and is found in database iDb.
 ** A read or a write lock can be taken depending on isWritelock.
@@ -107923,11 +111131,11 @@ struct TableLock {
 SQLITE_PRIVATE void sqlite3TableLock(
   Parse *pParse,     /* Parsing context */
   int iDb,           /* Index of the database containing the table to lock */
-  int iTab,          /* Root page number of the table to be locked */
+  Pgno iTab,         /* Root page number of the table to be locked */
   u8 isWriteLock,    /* True for a write lock */
   const char *zName  /* Name of the table to be locked */
 ){
-  Parse *pToplevel = sqlite3ParseToplevel(pParse);
+  Parse *pToplevel;
   int i;
   int nBytes;
   TableLock *p;
@@ -107935,6 +111143,7 @@ SQLITE_PRIVATE void sqlite3TableLock(
 
   if( iDb==1 ) return;
   if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
+  pToplevel = sqlite3ParseToplevel(pParse);
   for(i=0; i<pToplevel->nTableLock; i++){
     p = &pToplevel->aTableLock[i];
     if( p->iDb==iDb && p->iTab==iTab ){
@@ -107964,10 +111173,8 @@ SQLITE_PRIVATE void sqlite3TableLock(
 */
 static void codeTableLocks(Parse *pParse){
   int i;
-  Vdbe *pVdbe; 
-
-  pVdbe = sqlite3GetVdbe(pParse);
-  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
+  Vdbe *pVdbe = pParse->pVdbe;
+  assert( pVdbe!=0 );
 
   for(i=0; i<pParse->nTableLock; i++){
     TableLock *p = &pParse->aTableLock[i];
@@ -108019,7 +111226,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
   ** vdbe program
   */
   v = sqlite3GetVdbe(pParse);
-  assert( !pParse->isMultiWrite 
+  assert( !pParse->isMultiWrite
        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
   if( v ){
     sqlite3VdbeAddOp0(v, OP_Halt);
@@ -108041,7 +111248,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
     ** transaction on each used database and to verify the schema cookie
     ** on each used database.
     */
-    if( db->mallocFailed==0 
+    if( db->mallocFailed==0
      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
     ){
       int iDb, i;
@@ -108071,8 +111278,8 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
       pParse->nVtabLock = 0;
 #endif
 
-      /* Once all the cookies have been verified and transactions opened, 
-      ** obtain the required table-locks. This is a no-op unless the 
+      /* Once all the cookies have been verified and transactions opened,
+      ** obtain the required table-locks. This is a no-op unless the
       ** shared-cache feature is enabled.
       */
       codeTableLocks(pParse);
@@ -108081,12 +111288,21 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
       */
       sqlite3AutoincrementBegin(pParse);
 
-      /* Code constant expressions that where factored out of inner loops */
+      /* Code constant expressions that where factored out of inner loops.
+      **
+      ** The pConstExpr list might also contain expressions that we simply
+      ** want to keep around until the Parse object is deleted.  Such
+      ** expressions have iConstExprReg==0.  Do not generate code for
+      ** those expressions, of course.
+      */
       if( pParse->pConstExpr ){
         ExprList *pEL = pParse->pConstExpr;
         pParse->okConstFactor = 0;
         for(i=0; i<pEL->nExpr; i++){
-          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
+          int iReg = pEL->a[i].u.iConstExprReg;
+          if( iReg>0 ){
+            sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
+          }
         }
       }
 
@@ -108118,7 +111334,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
 ** outermost parser.
 **
 ** Not everything is nestable.  This facility is designed to permit
-** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
+** INSERT, UPDATE, and DELETE operations against the schema table.  Use
 ** care if you decide to try to use this routine for some other purposes.
 */
 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
@@ -108186,22 +111402,59 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha
     return 0;
   }
 #endif
-  while(1){
-    for(i=OMIT_TEMPDB; i<db->nDb; i++){
-      int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
-      if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
-        assert( sqlite3SchemaMutexHeld(db, j, 0) );
-        p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
-        if( p ) return p;
+  if( zDatabase ){
+    for(i=0; i<db->nDb; i++){
+      if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
+    }
+    if( i>=db->nDb ){
+      /* No match against the official names.  But always match "main"
+      ** to schema 0 as a legacy fallback. */
+      if( sqlite3StrICmp(zDatabase,"main")==0 ){
+        i = 0;
+      }else{
+        return 0;
+      }
+    }
+    p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
+    if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
+      if( i==1 ){
+        if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0
+         || sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0
+         || sqlite3StrICmp(zName+7, &DFLT_SCHEMA_TABLE[7])==0
+        ){
+          p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
+                              DFLT_TEMP_SCHEMA_TABLE);
+        }
+      }else{
+        if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
+          p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
+                              DFLT_SCHEMA_TABLE);
+        }
+      }
+    }
+  }else{
+    /* Match against TEMP first */
+    p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
+    if( p ) return p;
+    /* The main database is second */
+    p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
+    if( p ) return p;
+    /* Attached databases are in order of attachment */
+    for(i=2; i<db->nDb; i++){
+      assert( sqlite3SchemaMutexHeld(db, i, 0) );
+      p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
+      if( p ) break;
+    }
+    if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
+      if( sqlite3StrICmp(zName+7, &ALT_SCHEMA_TABLE[7])==0 ){
+        p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, DFLT_SCHEMA_TABLE);
+      }else if( sqlite3StrICmp(zName+7, &ALT_TEMP_SCHEMA_TABLE[7])==0 ){
+        p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
+                            DFLT_TEMP_SCHEMA_TABLE);
       }
     }
-    /* Not found.  If the name we were looking for was temp.sqlite_master
-    ** then change the name to sqlite_temp_master and try again. */
-    if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
-    if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
-    zName = TEMP_MASTER_NAME;
   }
-  return 0;
+  return p;
 }
 
 /*
@@ -108225,7 +111478,7 @@ SQLITE_PRIVATE Table *sqlite3LocateTable(
 
   /* Read the database schema. If an error occurs, leave an error message
   ** and code in pParse and return NULL. */
-  if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 
+  if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
    && SQLITE_OK!=sqlite3ReadSchema(pParse)
   ){
     return 0;
@@ -108275,7 +111528,7 @@ SQLITE_PRIVATE Table *sqlite3LocateTable(
 ** sqlite3FixSrcList() for details.
 */
 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
-  Parse *pParse, 
+  Parse *pParse,
   u32 flags,
   struct SrcList_item *p
 ){
@@ -108291,7 +111544,7 @@ SQLITE_PRIVATE Table *sqlite3LocateTableItem(
 }
 
 /*
-** Locate the in-memory structure that describes 
+** Locate the in-memory structure that describes
 ** a particular index given the name of that index
 ** and the name of the database that contains the index.
 ** Return NULL if not found.
@@ -108311,7 +111564,7 @@ SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const cha
     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
     Schema *pSchema = db->aDb[j].pSchema;
     assert( pSchema );
-    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
+    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
     assert( sqlite3SchemaMutexHeld(db, j, 0) );
     p = sqlite3HashFind(&pSchema->idxHash, zName);
     if( p ) break;
@@ -108464,6 +111717,7 @@ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
   assert( pTable!=0 );
   if( (pCol = pTable->aCol)!=0 ){
     for(i=0; i<pTable->nCol; i++, pCol++){
+      assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );
       sqlite3DbFree(db, pCol->zName);
       sqlite3ExprDelete(db, pCol->pDflt);
       sqlite3DbFree(db, pCol->zColl);
@@ -108478,10 +111732,10 @@ SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
 **
 ** This routine just deletes the data structure.  It does not unlink
 ** the table data structure from the hash table.  But it does destroy
-** memory structures of the indices and foreign keys associated with 
+** memory structures of the indices and foreign keys associated with
 ** the table.
 **
-** The db parameter is optional.  It is needed if the Table object 
+** The db parameter is optional.  It is needed if the Table object
 ** contains lookaside memory.  (Table objects in the schema do not use
 ** lookaside memory, but some ephemeral Table objects do.)  Or the
 ** db parameter can be used with db->pnBytesFreed to measure the memory
@@ -108493,7 +111747,7 @@ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
 #ifdef SQLITE_DEBUG
   /* Record the number of outstanding lookaside allocations in schema Tables
   ** prior to doing any free() operations. Since schema Tables do not use
-  ** lookaside, this number should not change. 
+  ** lookaside, this number should not change.
   **
   ** If malloc has already failed, it may be that it failed while allocating
   ** a Table object that was going to be marked ephemeral. So do not check
@@ -108510,7 +111764,7 @@ static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
     assert( pIndex->pSchema==pTable->pSchema
          || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
     if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
-      char *zName = pIndex->zName; 
+      char *zName = pIndex->zName;
       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
          &pIndex->pSchema->idxHash, zName, 0
       );
@@ -108590,13 +111844,13 @@ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
 }
 
 /*
-** Open the sqlite_master table stored in database number iDb for
+** Open the sqlite_schema table stored in database number iDb for
 ** writing. The table is opened using cursor 0.
 */
-SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
+SQLITE_PRIVATE void sqlite3OpenSchemaTable(Parse *p, int iDb){
   Vdbe *v = sqlite3GetVdbe(p);
-  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
-  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
+  sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, DFLT_SCHEMA_TABLE);
+  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
   if( p->nTab==0 ){
     p->nTab = 1;
   }
@@ -108625,7 +111879,7 @@ SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
 /*
 ** The token *pName contains the name of a database (either "main" or
 ** "temp" or the name of an attached db). This routine returns the
-** index of the named database in db->aDb[], or -1 if the named db 
+** index of the named database in db->aDb[], or -1 if the named db
 ** does not exist.
 */
 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
@@ -108641,7 +111895,7 @@ SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
 ** pName1 and pName2. If the table name was fully qualified, for example:
 **
 ** CREATE TABLE xxx.yyy (...);
-** 
+**
 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
 ** the table name is not fully qualified, i.e.:
 **
@@ -108704,7 +111958,7 @@ SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
 ** is reserved for internal use.
 **
-** When parsing the sqlite_master table, this routine also checks to
+** When parsing the sqlite_schema table, this routine also checks to
 ** make sure the "type", "name", and "tbl_name" columns are consistent
 ** with the SQL.
 */
@@ -108715,7 +111969,10 @@ SQLITE_PRIVATE int sqlite3CheckObjectName(
   const char *zTblName      /* Parent table name for triggers and indexes */
 ){
   sqlite3 *db = pParse->db;
-  if( sqlite3WritableSchema(db) || db->init.imposterTable ){
+  if( sqlite3WritableSchema(db)
+   || db->init.imposterTable
+   || !sqlite3Config.bExtraSchemaChecks
+  ){
     /* Skip these error checks for writable_schema=ON */
     return SQLITE_OK;
   }
@@ -108724,19 +111981,18 @@ SQLITE_PRIVATE int sqlite3CheckObjectName(
      || sqlite3_stricmp(zName, db->init.azInit[1])
      || sqlite3_stricmp(zTblName, db->init.azInit[2])
     ){
-      if( sqlite3Config.bExtraSchemaChecks ){
-        sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
-        return SQLITE_ERROR;
-      }
+      sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
+      return SQLITE_ERROR;
     }
   }else{
-    if( pParse->nested==0 
-     && 0==sqlite3StrNICmp(zName, "sqlite_", 7)
+    if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
+     || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
     ){
       sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
                       zName);
       return SQLITE_ERROR;
     }
+
   }
   return SQLITE_OK;
 }
@@ -108751,10 +112007,12 @@ SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
 }
 
 /*
-** Return the column of index pIdx that corresponds to table
-** column iCol.  Return -1 if not found.
+** Convert an table column number into a index column number.  That is,
+** for the column iCol in the table (as defined by the CREATE TABLE statement)
+** find the (first) offset of that column in index pIdx.  Or return -1
+** if column iCol is not used in index pIdx.
 */
-SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
+SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
   int i;
   for(i=0; i<pIdx->nColumn; i++){
     if( iCol==pIdx->aiColumn[i] ) return i;
@@ -108762,6 +112020,84 @@ SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
   return -1;
 }
 
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* Convert a storage column number into a table column number.
+**
+** The storage column number (0,1,2,....) is the index of the value
+** as it appears in the record on disk.  The true column number
+** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
+**
+** The storage column number is less than the table column number if
+** and only there are VIRTUAL columns to the left.
+**
+** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
+*/
+SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
+  if( pTab->tabFlags & TF_HasVirtual ){
+    int i;
+    for(i=0; i<=iCol; i++){
+      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
+    }
+  }
+  return iCol;
+}
+#endif
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* Convert a table column number into a storage column number.
+**
+** The storage column number (0,1,2,....) is the index of the value
+** as it appears in the record on disk.  Or, if the input column is
+** the N-th virtual column (zero-based) then the storage number is
+** the number of non-virtual columns in the table plus N.
+**
+** The true column number is the index (0,1,2,...) of the column in
+** the CREATE TABLE statement.
+**
+** If the input column is a VIRTUAL column, then it should not appear
+** in storage.  But the value sometimes is cached in registers that
+** follow the range of registers used to construct storage.  This
+** avoids computing the same VIRTUAL column multiple times, and provides
+** values for use by OP_Param opcodes in triggers.  Hence, if the
+** input column is a VIRTUAL table, put it after all the other columns.
+**
+** In the following, N means "normal column", S means STORED, and
+** V means VIRTUAL.  Suppose the CREATE TABLE has columns like this:
+**
+**        CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
+**                     -- 0 1 2 3 4 5 6 7 8
+**
+** Then the mapping from this function is as follows:
+**
+**    INPUTS:     0 1 2 3 4 5 6 7 8
+**    OUTPUTS:    0 1 6 2 3 7 4 5 8
+**
+** So, in other words, this routine shifts all the virtual columns to
+** the end.
+**
+** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
+** this routine is a no-op macro.  If the pTab does not have any virtual
+** columns, then this routine is no-op that always return iCol.  If iCol
+** is negative (indicating the ROWID column) then this routine return iCol.
+*/
+SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
+  int i;
+  i16 n;
+  assert( iCol<pTab->nCol );
+  if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
+  for(i=0, n=0; i<iCol; i++){
+    if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
+  }
+  if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
+    /* iCol is a virtual column itself */
+    return pTab->nNVCol + i - n;
+  }else{
+    /* iCol is a normal or stored column */
+    return n;
+  }
+}
+#endif
+
 /*
 ** Begin constructing a new table representation in memory.  This is
 ** the first of several action routines that get called in response
@@ -108795,7 +112131,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
   Token *pName;    /* Unqualified name of the table to create */
 
   if( db->init.busy && db->init.newTnum==1 ){
-    /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
+    /* Special case:  Parsing the sqlite_schema or sqlite_temp_schema schema */
     iDb = db->init.iDb;
     zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
     pName = pName1;
@@ -108804,7 +112140,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
     if( iDb<0 ) return;
     if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
-      /* If creating a temp table, the name may not be qualified. Unless 
+      /* If creating a temp table, the name may not be qualified. Unless
       ** the database name is "temp" anyway.  */
       sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
       return;
@@ -108901,10 +112237,10 @@ SQLITE_PRIVATE void sqlite3StartTable(
 #endif
 
   /* Begin generating the code that will insert the table record into
-  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
+  ** the schema table.  Note in particular that we must go ahead
   ** and allocate the record number for the table entry now.  Before any
   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
-  ** indices to be created and the table record must come before the 
+  ** indices to be created and the table record must come before the
   ** indices.  Hence, the record number for the table must be allocated
   ** now.
   */
@@ -108922,7 +112258,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
     }
 #endif
 
-    /* If the file format and encoding in the database have not been set, 
+    /* If the file format and encoding in the database have not been set,
     ** set them now.
     */
     reg1 = pParse->regRowid = ++pParse->nMem;
@@ -108937,7 +112273,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
     sqlite3VdbeJumpHere(v, addr1);
 
-    /* This just creates a place-holder record in the sqlite_master table.
+    /* This just creates a place-holder record in the sqlite_schema table.
     ** The record created does not contain anything yet.  It will be replaced
     ** by the real entry in code generated at sqlite3EndTable().
     **
@@ -108955,7 +112291,7 @@ SQLITE_PRIVATE void sqlite3StartTable(
       pParse->addrCrTab =
          sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
     }
-    sqlite3OpenMasterTable(pParse, iDb);
+    sqlite3OpenSchemaTable(pParse, iDb);
     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
     sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
@@ -109031,8 +112367,9 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
   pCol = &p->aCol[p->nCol];
   memset(pCol, 0, sizeof(p->aCol[0]));
   pCol->zName = z;
+  pCol->hName = sqlite3StrIHash(z);
   sqlite3ColumnPropertiesFromName(p, pCol);
+
   if( pType->n==0 ){
     /* If there is no type specified, columns have the default affinity
     ** 'BLOB' with a default size of 4 bytes. */
@@ -109052,6 +112389,7 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
     pCol->colFlags |= COLFLAG_HASTYPE;
   }
   p->nCol++;
+  p->nNVCol++;
   pParse->constraintName.n = 0;
 }
 
@@ -109087,11 +112425,11 @@ SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
 ** Scan the column type name zType (length nType) and return the
 ** associated affinity type.
 **
-** This routine does a case-independent search of zType for the 
+** This routine does a case-independent search of zType for the
 ** substrings in the following table. If one of the substrings is
 ** found, the corresponding affinity is returned. If zType contains
-** more than one of the substrings, entries toward the top of 
-** the table take priority. For example, if zType is 'BLOBINT', 
+** more than one of the substrings, entries toward the top of
+** the table take priority. For example, if zType is 'BLOBINT',
 ** SQLITE_AFF_INTEGER is returned.
 **
 ** Substring     | Affinity
@@ -109196,10 +112534,17 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue(
   sqlite3 *db = pParse->db;
   p = pParse->pNewTable;
   if( p!=0 ){
+    int isInit = db->init.busy && db->init.iDb!=1;
     pCol = &(p->aCol[p->nCol-1]);
-    if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
+    if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
           pCol->zName);
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    }else if( pCol->colFlags & COLFLAG_GENERATED ){
+      testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+      testcase( pCol->colFlags & COLFLAG_STORED );
+      sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
+#endif
     }else{
       /* A copy of pExpr is used instead of the original, as pExpr contains
       ** tokens that point to volatile memory.
@@ -109223,7 +112568,7 @@ SQLITE_PRIVATE void sqlite3AddDefaultValue(
 
 /*
 ** Backwards Compatibility Hack:
-** 
+**
 ** Historical versions of SQLite accepted strings as column names in
 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
 **
@@ -109246,7 +112591,22 @@ static void sqlite3StringToId(Expr *p){
 }
 
 /*
-** Designate the PRIMARY KEY for the table.  pList is a list of names 
+** Tag the given column as being part of the PRIMARY KEY
+*/
+static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
+  pCol->colFlags |= COLFLAG_PRIMKEY;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  if( pCol->colFlags & COLFLAG_GENERATED ){
+    testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+    testcase( pCol->colFlags & COLFLAG_STORED );
+    sqlite3ErrorMsg(pParse,
+      "generated columns cannot be part of the PRIMARY KEY");
+  }
+#endif
+}
+
+/*
+** Designate the PRIMARY KEY for the table.  pList is a list of names
 ** of columns that form the primary key.  If pList is NULL, then the
 ** most recently added column of the table is the primary key.
 **
@@ -109276,7 +112636,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   int nTerm;
   if( pTab==0 ) goto primary_key_exit;
   if( pTab->tabFlags & TF_HasPrimaryKey ){
-    sqlite3ErrorMsg(pParse, 
+    sqlite3ErrorMsg(pParse,
       "table \"%s\" has more than one primary key", pTab->zName);
     goto primary_key_exit;
   }
@@ -109284,7 +112644,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
   if( pList==0 ){
     iCol = pTab->nCol - 1;
     pCol = &pTab->aCol[iCol];
-    pCol->colFlags |= COLFLAG_PRIMKEY;
+    makeColumnPartOfPrimaryKey(pParse, pCol);
     nTerm = 1;
   }else{
     nTerm = pList->nExpr;
@@ -109297,7 +112657,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
         for(iCol=0; iCol<pTab->nCol; iCol++){
           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
             pCol = &pTab->aCol[iCol];
-            pCol->colFlags |= COLFLAG_PRIMKEY;
+            makeColumnPartOfPrimaryKey(pParse, pCol);
             break;
           }
         }
@@ -109318,6 +112678,7 @@ SQLITE_PRIVATE void sqlite3AddPrimaryKey(
     assert( autoInc==0 || autoInc==1 );
     pTab->tabFlags |= autoInc*TF_Autoincrement;
     if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
+    (void)sqlite3HasExplicitNulls(pParse, pList);
   }else if( autoInc ){
 #ifndef SQLITE_OMIT_AUTOINCREMENT
     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
@@ -109338,8 +112699,10 @@ primary_key_exit:
 ** Add a new CHECK constraint to the table currently under construction.
 */
 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
-  Parse *pParse,    /* Parsing context */
-  Expr *pCheckExpr  /* The check expression */
+  Parse *pParse,      /* Parsing context */
+  Expr *pCheckExpr,   /* The check expression */
+  const char *zStart, /* Opening "(" */
+  const char *zEnd    /* Closing ")" */
 ){
 #ifndef SQLITE_OMIT_CHECK
   Table *pTab = pParse->pNewTable;
@@ -109350,6 +112713,13 @@ SQLITE_PRIVATE void sqlite3AddCheckConstraint(
     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
     if( pParse->constraintName.n ){
       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
+    }else{
+      Token t;
+      for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
+      while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
+      t.z = zStart;
+      t.n = (int)(zEnd - t.z);
+      sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
     }
   }else
 #endif
@@ -109368,7 +112738,7 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   char *zColl;              /* Dequoted name of collation sequence */
   sqlite3 *db;
 
-  if( (p = pParse->pNewTable)==0 ) return;
+  if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
   i = p->nCol-1;
   db = pParse->db;
   zColl = sqlite3NameFromToken(db, pToken);
@@ -109378,7 +112748,7 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
     Index *pIdx;
     sqlite3DbFree(db, p->aCol[i].zColl);
     p->aCol[i].zColl = zColl;
-  
+
     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
     ** then an index may have been created on this column before the
     ** collation type was added. Correct this if it is the case.
@@ -109394,41 +112764,58 @@ SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
   }
 }
 
-/*
-** This function returns the collation sequence for database native text
-** encoding identified by the string zName, length nName.
-**
-** If the requested collation sequence is not available, or not available
-** in the database native encoding, the collation factory is invoked to
-** request it. If the collation factory does not supply such a sequence,
-** and the sequence is available in another text encoding, then that is
-** returned instead.
-**
-** If no versions of the requested collations sequence are available, or
-** another error occurs, NULL is returned and an error message written into
-** pParse.
-**
-** This routine is a wrapper around sqlite3FindCollSeq().  This routine
-** invokes the collation factory if the named collation cannot be found
-** and generates an error message.
-**
-** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
+/* Change the most recently parsed column to be a GENERATED ALWAYS AS
+** column.
 */
-SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
-  sqlite3 *db = pParse->db;
-  u8 enc = ENC(db);
-  u8 initbusy = db->init.busy;
-  CollSeq *pColl;
-
-  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
-  if( !initbusy && (!pColl || !pColl->xCmp) ){
-    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
+SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  u8 eType = COLFLAG_VIRTUAL;
+  Table *pTab = pParse->pNewTable;
+  Column *pCol;
+  if( pTab==0 ){
+    /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
+    goto generated_done;
+  }
+  pCol = &(pTab->aCol[pTab->nCol-1]);
+  if( IN_DECLARE_VTAB ){
+    sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
+    goto generated_done;
+  }
+  if( pCol->pDflt ) goto generated_error;
+  if( pType ){
+    if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
+      /* no-op */
+    }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
+      eType = COLFLAG_STORED;
+    }else{
+      goto generated_error;
+    }
   }
+  if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
+  pCol->colFlags |= eType;
+  assert( TF_HasVirtual==COLFLAG_VIRTUAL );
+  assert( TF_HasStored==COLFLAG_STORED );
+  pTab->tabFlags |= eType;
+  if( pCol->colFlags & COLFLAG_PRIMKEY ){
+    makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
+  }
+  pCol->pDflt = pExpr;
+  pExpr = 0;
+  goto generated_done;
 
-  return pColl;
+generated_error:
+  sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
+                  pCol->zName);
+generated_done:
+  sqlite3ExprDelete(pParse->db, pExpr);
+#else
+  /* Throw and error for the GENERATED ALWAYS AS clause if the
+  ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
+  sqlite3ErrorMsg(pParse, "generated columns not supported");
+  sqlite3ExprDelete(pParse->db, pExpr);
+#endif
 }
 
-
 /*
 ** Generate code that will increment the schema cookie.
 **
@@ -109452,7 +112839,7 @@ SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
   sqlite3 *db = pParse->db;
   Vdbe *v = pParse->pVdbe;
   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
-  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 
+  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
                    (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
 }
 
@@ -109473,13 +112860,13 @@ static int identLength(const char *z){
 }
 
 /*
-** The first parameter is a pointer to an output buffer. The second 
+** The first parameter is a pointer to an output buffer. The second
 ** parameter is a pointer to an integer that contains the offset at
 ** which to write into the output buffer. This function copies the
 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
 ** to the specified offset in the buffer and updates *pIdx to refer
 ** to the first byte after the last byte written before returning.
-** 
+**
 ** If the string zSignedIdent consists entirely of alpha-numeric
 ** characters, does not begin with a digit and is not an SQL keyword,
 ** then it is copied to the output buffer exactly as it is. Otherwise,
@@ -109523,7 +112910,7 @@ static char *createTableStmt(sqlite3 *db, Table *p){
     n += identLength(pCol->zName) + 5;
   }
   n += identLength(p->zName);
-  if( n<50 ){ 
+  if( n<50 ){
     zSep = "";
     zSep2 = ",";
     zEnd = ")";
@@ -109564,10 +112951,10 @@ static char *createTableStmt(sqlite3 *db, Table *p){
     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
     testcase( pCol->affinity==SQLITE_AFF_REAL );
-    
+
     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
     len = sqlite3Strlen30(zType);
-    assert( pCol->affinity==SQLITE_AFF_BLOB 
+    assert( pCol->affinity==SQLITE_AFF_BLOB
             || pCol->affinity==sqlite3AffinityType(zType, 0) );
     memcpy(&zStmt[k], zType, len);
     k += len;
@@ -109586,12 +112973,15 @@ static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
   int nByte;
   if( pIdx->nColumn>=N ) return SQLITE_OK;
   assert( pIdx->isResized==0 );
-  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
+  nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*N;
   zExtra = sqlite3DbMallocZero(db, nByte);
   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
   pIdx->azColl = (const char**)zExtra;
   zExtra += sizeof(char*)*N;
+  memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
+  pIdx->aiRowLogEst = (LogEst*)zExtra;
+  zExtra += sizeof(LogEst)*N;
   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
   pIdx->aiColumn = (i16*)zExtra;
   zExtra += sizeof(i16)*N;
@@ -109670,7 +113060,7 @@ static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
   assert( j!=XN_ROWID && j!=XN_EXPR );
   for(i=0; i<nKey; i++){
     assert( pIdx->aiColumn[i]>=0 || j>=0 );
-    if( pIdx->aiColumn[i]==j 
+    if( pIdx->aiColumn[i]==j
      && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
     ){
       return 1;
@@ -109686,15 +113076,24 @@ static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
 ** high-order bit of colNotIdxed is always 1.  All unindexed columns
 ** of the table have a 1.
 **
+** 2019-10-24:  For the purpose of this computation, virtual columns are
+** not considered to be covered by the index, even if they are in the
+** index, because we do not trust the logic in whereIndexExprTrans() to be
+** able to find all instances of a reference to the indexed table column
+** and convert them into references to the index.  Hence we always want
+** the actual table at hand in order to recompute the virtual column, if
+** necessary.
+**
 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
 ** to determine if the index is covering index.
 */
 static void recomputeColumnsNotIndexed(Index *pIdx){
   Bitmask m = 0;
   int j;
+  Table *pTab = pIdx->pTable;
   for(j=pIdx->nColumn-1; j>=0; j--){
     int x = pIdx->aiColumn[j];
-    if( x>=0 ){
+    if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
       testcase( x==BMS-1 );
       testcase( x==BMS-2 );
       if( x<BMS-1 ) m |= MASKBIT(x);
@@ -109712,11 +113111,11 @@ static void recomputeColumnsNotIndexed(Index *pIdx){
 ** Changes include:
 **
 **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
-**     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY 
+**     (2)  Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
 **          into BTREE_BLOBKEY.
-**     (3)  Bypass the creation of the sqlite_master table entry
+**     (3)  Bypass the creation of the sqlite_schema table entry
 **          for the PRIMARY KEY as the primary key index is now
-**          identified by the sqlite_master table entry of the table itself.
+**          identified by the sqlite_schema table entry of the table itself.
 **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
 **          schema to the rootpage from the main table.
 **     (5)  Add all table columns to the PRIMARY KEY Index object
@@ -109745,6 +113144,7 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
         pTab->aCol[i].notNull = OE_Abort;
       }
     }
+    pTab->tabFlags |= TF_HasNotNull;
   }
 
   /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
@@ -109756,13 +113156,13 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   }
 
   /* Locate the PRIMARY KEY index.  Or, if this table was originally
-  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
+  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
   */
   if( pTab->iPKey>=0 ){
     ExprList *pList;
     Token ipkToken;
     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
-    pList = sqlite3ExprListAppend(pParse, 0, 
+    pList = sqlite3ExprListAppend(pParse, 0,
                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
     if( pList==0 ) return;
     if( IN_RENAME_OBJECT ){
@@ -109802,13 +113202,13 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
   nPk = pPk->nColumn = pPk->nKeyCol;
 
-  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
+  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
   ** table entry. This is only required if currently generating VDBE
   ** code for a CREATE TABLE (not when parsing one as part of reading
   ** a database schema).  */
   if( v && pPk->tnum>0 ){
     assert( db->init.busy==0 );
-    sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
+    sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
   }
 
   /* The root page of the PRIMARY KEY is the table root page */
@@ -109852,11 +113252,14 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
   */
   nExtra = 0;
   for(i=0; i<pTab->nCol; i++){
-    if( !hasColumn(pPk->aiColumn, nPk, i) ) nExtra++;
+    if( !hasColumn(pPk->aiColumn, nPk, i)
+     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
   }
   if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
   for(i=0, j=nPk; i<pTab->nCol; i++){
-    if( !hasColumn(pPk->aiColumn, j, i) ){
+    if( !hasColumn(pPk->aiColumn, j, i)
+     && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
+    ){
       assert( j<pPk->nColumn );
       pPk->aiColumn[j] = i;
       pPk->azColl[j] = sqlite3StrBINARY;
@@ -109864,10 +113267,32 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
     }
   }
   assert( pPk->nColumn==j );
-  assert( pTab->nCol<=j );
+  assert( pTab->nNVCol<=j );
   recomputeColumnsNotIndexed(pPk);
 }
 
+
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+/*
+** Return true if pTab is a virtual table and zName is a shadow table name
+** for that virtual table.
+*/
+SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
+  int nName;                    /* Length of zName */
+  Module *pMod;                 /* Module for the virtual table */
+
+  if( !IsVirtual(pTab) ) return 0;
+  nName = sqlite3Strlen30(pTab->zName);
+  if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
+  if( zName[nName]!='_' ) return 0;
+  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
+  if( pMod==0 ) return 0;
+  if( pMod->pModule->iVersion<3 ) return 0;
+  if( pMod->pModule->xShadowName==0 ) return 0;
+  return pMod->pModule->xShadowName(zName+nName+1);
+}
+#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
+
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /*
 ** Return true if zName is a shadow table name in the current database
@@ -109876,11 +113301,9 @@ static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
 ** zName is temporarily modified while this routine is running, but is
 ** restored to its original value prior to this routine returning.
 */
-static int isShadowTableName(sqlite3 *db, char *zName){
+SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
   char *zTail;                  /* Pointer to the last "_" in zName */
   Table *pTab;                  /* Table that zName is a shadow of */
-  Module *pMod;                 /* Module for the virtual table */
-
   zTail = strrchr(zName, '_');
   if( zTail==0 ) return 0;
   *zTail = 0;
@@ -109888,16 +113311,37 @@ static int isShadowTableName(sqlite3 *db, char *zName){
   *zTail = '_';
   if( pTab==0 ) return 0;
   if( !IsVirtual(pTab) ) return 0;
-  pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
-  if( pMod==0 ) return 0;
-  if( pMod->pModule->iVersion<3 ) return 0;
-  if( pMod->pModule->xShadowName==0 ) return 0;
-  return pMod->pModule->xShadowName(zTail+1);
+  return sqlite3IsShadowTableOf(db, pTab, zName);
 }
-#else
-# define isShadowTableName(x,y) 0
 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
 
+
+#ifdef SQLITE_DEBUG
+/*
+** Mark all nodes of an expression as EP_Immutable, indicating that
+** they should not be changed.  Expressions attached to a table or
+** index definition are tagged this way to help ensure that we do
+** not pass them into code generator routines by mistake.
+*/
+static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
+  ExprSetVVAProperty(pExpr, EP_Immutable);
+  return WRC_Continue;
+}
+static void markExprListImmutable(ExprList *pList){
+  if( pList ){
+    Walker w;
+    memset(&w, 0, sizeof(w));
+    w.xExprCallback = markImmutableExprStep;
+    w.xSelectCallback = sqlite3SelectWalkNoop;
+    w.xSelectCallback2 = 0;
+    sqlite3WalkExprList(&w, pList);
+  }
+}
+#else
+#define markExprListImmutable(X)  /* no-op */
+#endif /* SQLITE_DEBUG */
+
+
 /*
 ** This routine is called to report the final ")" that terminates
 ** a CREATE TABLE statement.
@@ -109906,15 +113350,15 @@ static int isShadowTableName(sqlite3 *db, char *zName){
 ** is added to the internal hash tables, assuming no errors have
 ** occurred.
 **
-** An entry for the table is made in the master table on disk, unless
+** An entry for the table is made in the schema table on disk, unless
 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
-** it means we are reading the sqlite_master table because we just
-** connected to the database or because the sqlite_master table has
+** it means we are reading the sqlite_schema table because we just
+** connected to the database or because the sqlite_schema table has
 ** recently changed, so the entry for this table already exists in
-** the sqlite_master table.  We do not want to create it again.
+** the sqlite_schema table.  We do not want to create it again.
 **
 ** If the pSelect argument is not NULL, it means that this routine
-** was called to create a table generated from a 
+** was called to create a table generated from a
 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
 ** the new table will match the result set of the SELECT.
 */
@@ -109937,17 +113381,17 @@ SQLITE_PRIVATE void sqlite3EndTable(
   p = pParse->pNewTable;
   if( p==0 ) return;
 
-  if( pSelect==0 && isShadowTableName(db, p->zName) ){
+  if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
     p->tabFlags |= TF_Shadow;
   }
 
   /* If the db->init.busy is 1 it means we are reading the SQL off the
-  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
+  ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
   ** So do not write to the disk again.  Extract the root page number
   ** for the table from the db->init.newTnum field.  (The page number
   ** should have been put there by the sqliteOpenCb routine.)
   **
-  ** If the root page number is 1, that means this is the sqlite_master
+  ** If the root page number is 1, that means this is the sqlite_schema
   ** table itself.  So mark it read-only.
   */
   if( db->init.busy ){
@@ -109973,12 +113417,11 @@ SQLITE_PRIVATE void sqlite3EndTable(
     }
     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
-    }else{
-      p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
-      convertToWithoutRowidTable(pParse, p);
+      return;
     }
+    p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
+    convertToWithoutRowidTable(pParse, p);
   }
-
   iDb = sqlite3SchemaToIndex(db, p->pSchema);
 
 #ifndef SQLITE_OMIT_CHECK
@@ -109986,8 +113429,47 @@ SQLITE_PRIVATE void sqlite3EndTable(
   */
   if( p->pCheck ){
     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
+    if( pParse->nErr ){
+      /* If errors are seen, delete the CHECK constraints now, else they might
+      ** actually be used if PRAGMA writable_schema=ON is set. */
+      sqlite3ExprListDelete(db, p->pCheck);
+      p->pCheck = 0;
+    }else{
+      markExprListImmutable(p->pCheck);
+    }
   }
 #endif /* !defined(SQLITE_OMIT_CHECK) */
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  if( p->tabFlags & TF_HasGenerated ){
+    int ii, nNG = 0;
+    testcase( p->tabFlags & TF_HasVirtual );
+    testcase( p->tabFlags & TF_HasStored );
+    for(ii=0; ii<p->nCol; ii++){
+      u32 colFlags = p->aCol[ii].colFlags;
+      if( (colFlags & COLFLAG_GENERATED)!=0 ){
+        Expr *pX = p->aCol[ii].pDflt;
+        testcase( colFlags & COLFLAG_VIRTUAL );
+        testcase( colFlags & COLFLAG_STORED );
+        if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
+          /* If there are errors in resolving the expression, change the
+          ** expression to a NULL.  This prevents code generators that operate
+          ** on the expression from inserting extra parts into the expression
+          ** tree that have been allocated from lookaside memory, which is
+          ** illegal in a schema and will lead to errors or heap corruption
+          ** when the database connection closes. */
+          sqlite3ExprDelete(db, pX);
+          p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
+        }
+      }else{
+        nNG++;
+      }
+    }
+    if( nNG==0 ){
+      sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
+      return;
+    }
+  }
+#endif
 
   /* Estimate the average row size for the table and for all implied indices */
   estimateTableWidth(p);
@@ -109996,7 +113478,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
   }
 
   /* If not initializing, then create a record for the new table
-  ** in the SQLITE_MASTER table of the database.
+  ** in the schema table of the database.
   **
   ** If this is a TEMPORARY table, write the entry into the auxiliary
   ** file instead of into the main database file.
@@ -110013,7 +113495,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
 
     sqlite3VdbeAddOp1(v, OP_Close, 0);
 
-    /* 
+    /*
     ** Initialize zType for the new view or table.
     */
     if( p->pSelect==0 ){
@@ -110064,7 +113546,7 @@ SQLITE_PRIVATE void sqlite3EndTable(
       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
       if( pSelTab==0 ) return;
       assert( p->aCol==0 );
-      p->nCol = pSelTab->nCol;
+      p->nCol = p->nNVCol = pSelTab->nCol;
       p->aCol = pSelTab->aCol;
       pSelTab->nCol = 0;
       pSelTab->aCol = 0;
@@ -110092,20 +113574,20 @@ SQLITE_PRIVATE void sqlite3EndTable(
       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
       n = (int)(pEnd2->z - pParse->sNameToken.z);
       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
-      zStmt = sqlite3MPrintf(db, 
+      zStmt = sqlite3MPrintf(db,
           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
       );
     }
 
-    /* A slot for the record has already been allocated in the 
-    ** SQLITE_MASTER table.  We just need to update that slot with all
+    /* A slot for the record has already been allocated in the
+    ** schema table.  We just need to update that slot with all
     ** the information we've collected.
     */
     sqlite3NestedParse(pParse,
-      "UPDATE %Q.%s "
-         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
-       "WHERE rowid=#%d",
-      db->aDb[iDb].zDbSName, MASTER_NAME,
+      "UPDATE %Q." DFLT_SCHEMA_TABLE
+      " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
+      WHERE rowid=#%d",
+      db->aDb[iDb].zDbSName,
       zType,
       p->zName,
       p->zName,
@@ -110137,7 +113619,6 @@ SQLITE_PRIVATE void sqlite3EndTable(
            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
   }
 
-
   /* Add the table to the in-memory representation of the database.
   */
   if( db->init.busy ){
@@ -110208,6 +113689,7 @@ SQLITE_PRIVATE void sqlite3CreateView(
   ** allocated rather than point to the input string - which means that
   ** they will persist after the current sqlite3_exec() call returns.
   */
+  pSelect->selFlags |= SF_View;
   if( IN_RENAME_OBJECT ){
     p->pSelect = pSelect;
     pSelect = 0;
@@ -110233,7 +113715,7 @@ SQLITE_PRIVATE void sqlite3CreateView(
   sEnd.z = &z[n-1];
   sEnd.n = 1;
 
-  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
+  /* Use sqlite3EndTable() to add the view to the schema table */
   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
 
 create_view_fail:
@@ -110293,7 +113775,7 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   ** Actually, the error above is now caught prior to reaching this point.
   ** But the following test is still important as it does come up
   ** in the following:
-  ** 
+  **
   **     CREATE TABLE main.ex1(a);
   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
   **     SELECT * FROM temp.ex1;
@@ -110314,14 +113796,12 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
   assert( pTable->pSelect );
   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
   if( pSel ){
-#ifndef SQLITE_OMIT_ALTERTABLE
     u8 eParseMode = pParse->eParseMode;
     pParse->eParseMode = PARSE_MODE_NORMAL;
-#endif
     n = pParse->nTab;
     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
     pTable->nCol = -1;
-    db->lookaside.bDisable++;
+    DisableLookaside;
 #ifndef SQLITE_OMIT_AUTHORIZATION
     xAuth = db->xAuth;
     db->xAuth = 0;
@@ -110331,23 +113811,26 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
 #endif
     pParse->nTab = n;
-    if( pTable->pCheck ){
+    if( pSelTab==0 ){
+      pTable->nCol = 0;
+      nErr++;
+    }else if( pTable->pCheck ){
       /* CREATE VIEW name(arglist) AS ...
       ** The names of the columns in the table are taken from
       ** arglist which is stored in pTable->pCheck.  The pCheck field
       ** normally holds CHECK constraints on an ordinary table, but for
       ** a VIEW it holds the list of column names.
       */
-      sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
+      sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
                                  &pTable->nCol, &pTable->aCol);
-      if( db->mallocFailed==0 
+      if( db->mallocFailed==0
        && pParse->nErr==0
        && pTable->nCol==pSel->pEList->nExpr
       ){
         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
                                                SQLITE_AFF_NONE);
       }
-    }else if( pSelTab ){
+    }else{
       /* CREATE VIEW name AS...  without an argument list.  Construct
       ** the column names from the SELECT statement that defines the view.
       */
@@ -110357,16 +113840,12 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
       pSelTab->nCol = 0;
       pSelTab->aCol = 0;
       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
-    }else{
-      pTable->nCol = 0;
-      nErr++;
     }
+    pTable->nNVCol = pTable->nCol;
     sqlite3DeleteTable(db, pSelTab);
     sqlite3SelectDelete(db, pSel);
-    db->lookaside.bDisable--;
-#ifndef SQLITE_OMIT_ALTERTABLE
+    EnableLookaside;
     pParse->eParseMode = eParseMode;
-#endif
   } else {
     nErr++;
   }
@@ -110377,7 +113856,7 @@ SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
     pTable->nCol = 0;
   }
 #endif /* SQLITE_OMIT_VIEW */
-  return nErr;  
+  return nErr;
 }
 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
 
@@ -110413,7 +113892,7 @@ static void sqliteViewResetAll(sqlite3 *db, int idx){
 ** on tables and/or indices that are the process of being deleted.
 ** If you are unlucky, one of those deleted indices or tables might
 ** have the same rootpage number as the real table or index that is
-** being moved.  So we cannot stop searching after the first match 
+** being moved.  So we cannot stop searching after the first match
 ** because the first match might be for one of the deleted indices
 ** or tables and not the table/index that is actually being moved.
 ** We must continue looping until all tables and indices with
@@ -110421,7 +113900,7 @@ static void sqliteViewResetAll(sqlite3 *db, int idx){
 ** in order to be certain that we got the right one.
 */
 #ifndef SQLITE_OMIT_AUTOVACUUM
-SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
+SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
   HashElem *pElem;
   Hash *pHash;
   Db *pDb;
@@ -110447,10 +113926,10 @@ SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iT
 
 /*
 ** Write code to erase the table with root-page iTable from database iDb.
-** Also write code to modify the sqlite_master table and internal schema
+** Also write code to modify the sqlite_schema table and internal schema
 ** if a root-page of another table is moved by the btree-layer whilst
 ** erasing iTable (this can happen with an auto-vacuum database).
-*/ 
+*/
 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
   Vdbe *v = sqlite3GetVdbe(pParse);
   int r1 = sqlite3GetTempReg(pParse);
@@ -110460,30 +113939,31 @@ static void destroyRootPage(Parse *pParse, int iTable, int iDb){
 #ifndef SQLITE_OMIT_AUTOVACUUM
   /* OP_Destroy stores an in integer r1. If this integer
   ** is non-zero, then it is the root page number of a table moved to
-  ** location iTable. The following code modifies the sqlite_master table to
+  ** location iTable. The following code modifies the sqlite_schema table to
   ** reflect this.
   **
   ** The "#NNN" in the SQL is a special constant that means whatever value
   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
   ** token for additional information.
   */
-  sqlite3NestedParse(pParse, 
-     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
-     pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
+  sqlite3NestedParse(pParse,
+     "UPDATE %Q." DFLT_SCHEMA_TABLE
+     " SET rootpage=%d WHERE #%d AND rootpage=#%d",
+     pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
 #endif
   sqlite3ReleaseTempReg(pParse, r1);
 }
 
 /*
 ** Write VDBE code to erase table pTab and all associated indices on disk.
-** Code to update the sqlite_master tables and internal schema definitions
+** Code to update the sqlite_schema tables and internal schema definitions
 ** in case a root-page belonging to another table is moved by the btree layer
 ** is also added (this can happen with an auto-vacuum database).
 */
 static void destroyTable(Parse *pParse, Table *pTab){
   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
   ** is not defined), then it is important to call OP_Destroy on the
-  ** table and index root-pages in order, starting with the numerically 
+  ** table and index root-pages in order, starting with the numerically
   ** largest root-page number. This guarantees that none of the root-pages
   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
   ** following were coded:
@@ -110493,22 +113973,22 @@ static void destroyTable(Parse *pParse, Table *pTab){
   ** OP_Destroy 5 0
   **
   ** and root page 5 happened to be the largest root-page number in the
-  ** database, then root page 5 would be moved to page 4 by the 
+  ** database, then root page 5 would be moved to page 4 by the
   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
   ** a free-list page.
   */
-  int iTab = pTab->tnum;
-  int iDestroyed = 0;
+  Pgno iTab = pTab->tnum;
+  Pgno iDestroyed = 0;
 
   while( 1 ){
     Index *pIdx;
-    int iLargest = 0;
+    Pgno iLargest = 0;
 
     if( iDestroyed==0 || iTab<iDestroyed ){
       iLargest = iTab;
     }
     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
-      int iIdx = pIdx->tnum;
+      Pgno iIdx = pIdx->tnum;
       assert( pIdx->pSchema==pTab->pSchema );
       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
         iLargest = iIdx;
@@ -110569,12 +114049,12 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in
 #endif
 
   /* Drop all triggers associated with the table being dropped. Code
-  ** is generated to remove entries from sqlite_master and/or
-  ** sqlite_temp_master if required.
+  ** is generated to remove entries from sqlite_schema and/or
+  ** sqlite_temp_schema if required.
   */
   pTrigger = sqlite3TriggerList(pParse, pTab);
   while( pTrigger ){
-    assert( pTrigger->pSchema==pTab->pSchema || 
+    assert( pTrigger->pSchema==pTab->pSchema ||
         pTrigger->pSchema==db->aDb[1].pSchema );
     sqlite3DropTriggerPtr(pParse, pTrigger);
     pTrigger = pTrigger->pNext;
@@ -110594,16 +114074,17 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in
   }
 #endif
 
-  /* Drop all SQLITE_MASTER table and index entries that refer to the
-  ** table. The program name loops through the master table and deletes
+  /* Drop all entries in the schema table that refer to the
+  ** table. The program name loops through the schema table and deletes
   ** every row that refers to a table of the same name as the one being
   ** dropped. Triggers are handled separately because a trigger can be
   ** created in the temp database that refers to a table in another
   ** database.
   */
-  sqlite3NestedParse(pParse, 
-      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
-      pDb->zDbSName, MASTER_NAME, pTab->zName);
+  sqlite3NestedParse(pParse,
+      "DELETE FROM %Q." DFLT_SCHEMA_TABLE
+      " WHERE tbl_name=%Q and type!='trigger'",
+      pDb->zDbSName, pTab->zName);
   if( !isView && !IsVirtual(pTab) ){
     destroyTable(pParse, pTab);
   }
@@ -110621,6 +114102,37 @@ SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, in
 }
 
 /*
+** Return TRUE if shadow tables should be read-only in the current
+** context.
+*/
+SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+  if( (db->flags & SQLITE_Defensive)!=0
+   && db->pVtabCtx==0
+   && db->nVdbeExec==0
+  ){
+    return 1;
+  }
+#endif
+  return 0;
+}
+
+/*
+** Return true if it is not allowed to drop the given table
+*/
+static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
+  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
+    if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
+    if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
+    return 1;
+  }
+  if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
+    return 1;
+  }
+  return 0;
+}
+
+/*
 ** This routine is called to do the work of a DROP TABLE statement.
 ** pName is the name of the table to be dropped.
 */
@@ -110689,9 +114201,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView,
     }
   }
 #endif
-  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
-    && sqlite3StrNICmp(pTab->zName+7, "stat", 4)!=0
-    && sqlite3StrNICmp(pTab->zName+7, "parameters", 10)!=0 ){
+  if( tableMayNotBeDropped(db, pTab) ){
     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
     goto exit_drop_table;
   }
@@ -110710,7 +114220,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView,
   }
 #endif
 
-  /* Generate code to remove the table from the master table
+  /* Generate code to remove the table from the schema table
   ** on disk.
   */
   v = sqlite3GetVdbe(pParse);
@@ -110783,7 +114293,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
   if( pToCol ){
     for(i=0; i<pToCol->nExpr; i++){
-      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
+      nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
     }
   }
   pFKey = sqlite3DbMallocZero(db, nByte );
@@ -110808,30 +114318,30 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
     for(i=0; i<nCol; i++){
       int j;
       for(j=0; j<p->nCol; j++){
-        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
+        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
           pFKey->aCol[i].iFrom = j;
           break;
         }
       }
       if( j>=p->nCol ){
-        sqlite3ErrorMsg(pParse, 
-          "unknown column \"%s\" in foreign key definition", 
-          pFromCol->a[i].zName);
+        sqlite3ErrorMsg(pParse,
+          "unknown column \"%s\" in foreign key definition",
+          pFromCol->a[i].zEName);
         goto fk_end;
       }
       if( IN_RENAME_OBJECT ){
-        sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
+        sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
       }
     }
   }
   if( pToCol ){
     for(i=0; i<nCol; i++){
-      int n = sqlite3Strlen30(pToCol->a[i].zName);
+      int n = sqlite3Strlen30(pToCol->a[i].zEName);
       pFKey->aCol[i].zCol = z;
       if( IN_RENAME_OBJECT ){
-        sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
+        sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
       }
-      memcpy(z, pToCol->a[i].zName, n);
+      memcpy(z, pToCol->a[i].zEName, n);
       z[n] = 0;
       z += n+1;
     }
@@ -110841,7 +114351,7 @@ SQLITE_PRIVATE void sqlite3CreateForeignKey(
   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
 
   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
-  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
+  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
       pFKey->zTo, (void *)pFKey
   );
   if( pNextTo==pFKey ){
@@ -110901,7 +114411,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
   int addr1;                     /* Address of top of loop */
   int addr2;                     /* Address to jump to for next iteration */
-  int tnum;                      /* Root page of index */
+  Pgno tnum;                     /* Root page of index */
   int iPartIdxLabel;             /* Jump to this label to skip a row */
   Vdbe *v;                       /* Generate code into this virtual machine */
   KeyInfo *pKey;                 /* KeyInfo for index */
@@ -110922,7 +114432,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   v = sqlite3GetVdbe(pParse);
   if( v==0 ) return;
   if( memRootPage>=0 ){
-    tnum = memRootPage;
+    tnum = (Pgno)memRootPage;
   }else{
     tnum = pIndex->tnum;
   }
@@ -110947,7 +114457,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
   sqlite3VdbeJumpHere(v, addr1);
   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
-  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
+  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
                     (char *)pKey, P4_KEYINFO);
   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
 
@@ -110966,7 +114476,7 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
     ** user function that throws an exception when it is evaluated. But the
     ** overhead of adding a statement journal to a CREATE INDEX statement is
     ** very small (since most of the pages written do not contain content that
-    ** needs to be restored if the statement aborts), so we call 
+    ** needs to be restored if the statement aborts), so we call
     ** sqlite3MayAbort() for all CREATE INDEX statements.  */
     sqlite3MayAbort(pParse);
     addr2 = sqlite3VdbeCurrentAddr(v);
@@ -111039,7 +114549,7 @@ SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
     for(i=0; i<pList->nExpr; i++){
       if( pList->a[i].bNulls ){
         u8 sf = pList->a[i].sortFlags;
-        sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s", 
+        sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
             (sf==0 || sf==3) ? "FIRST" : "LAST"
         );
         return 1;
@@ -111050,8 +114560,8 @@ SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
 }
 
 /*
-** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
-** and pTblList is the name of the table that is to be indexed.  Both will 
+** Create a new index for an SQL table.  pName1.pName2 is the name of the index
+** and pTblList is the name of the table that is to be indexed.  Both will
 ** be NULL for a primary key or an index that is created to satisfy a
 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
 ** as the table to be indexed.  pParse->pNewTable is a table that is
@@ -111059,7 +114569,7 @@ SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
 **
 ** pList is a list of columns to be indexed.  pList will be NULL if this
 ** is a primary key or unique-constraint on the most recent column added
-** to the table currently under construction.  
+** to the table currently under construction.
 */
 SQLITE_PRIVATE void sqlite3CreateIndex(
   Parse *pParse,     /* All information about this parse */
@@ -111109,7 +114619,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
   */
   if( pTblName!=0 ){
 
-    /* Use the two-part index name to determine the database 
+    /* Use the two-part index name to determine the database
     ** to search for the table. 'Fix' the table name to this db
     ** before looking up the table.
     */
@@ -111141,7 +114651,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     assert( db->mallocFailed==0 || pTab==0 );
     if( pTab==0 ) goto exit_create_index;
     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
-      sqlite3ErrorMsg(pParse, 
+      sqlite3ErrorMsg(pParse,
            "cannot create a TEMP index on non-TEMP table \"%s\"",
            pTab->zName);
       goto exit_create_index;
@@ -111158,16 +114668,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
 
   assert( pTab!=0 );
   assert( pParse->nErr==0 );
-  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
+  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
        && db->init.busy==0
        && pTblName!=0
 #if SQLITE_USER_AUTHENTICATION
        && sqlite3UserAuthTable(pTab->zName)==0
 #endif
-#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
-       && sqlite3StrICmp(&pTab->zName[7],"master")!=0
-#endif
- ){
+  ){
     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
     goto exit_create_index;
   }
@@ -111186,10 +114693,10 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
 
   /*
   ** Find the name of the index.  Make sure there is not already another
-  ** index or table with the same name.  
+  ** index or table with the same name.
   **
   ** Exception:  If we are reading the names of permanent indices from the
-  ** sqlite_master table (because some other process changed the schema) and
+  ** sqlite_schema table (because some other process changed the schema) and
   ** one of the index names collides with the name of a temporary table or
   ** index, then we will continue to process this index.
   **
@@ -111284,8 +114791,8 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     }
   }
 
-  /* 
-  ** Allocate the index structure. 
+  /*
+  ** Allocate the index structure.
   */
   nName = sqlite3Strlen30(zName);
   nExtraCol = pPk ? pPk->nKeyCol : 1;
@@ -111362,8 +114869,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
       assert( j<=0x7fff );
       if( j<0 ){
         j = pTab->iPKey;
-      }else if( pTab->aCol[j].notNull==0 ){
-        pIndex->uniqNotNull = 0;
+      }else{
+        if( pTab->aCol[j].notNull==0 ){
+          pIndex->uniqNotNull = 0;
+        }
+        if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
+          pIndex->bHasVCol = 1;
+        }
       }
       pIndex->aiColumn[i] = (i16)j;
     }
@@ -111398,7 +114910,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
       int x = pPk->aiColumn[j];
       assert( x>=0 );
       if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
-        pIndex->nColumn--; 
+        pIndex->nColumn--;
       }else{
         testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
         pIndex->aiColumn[i] = x;
@@ -111417,14 +114929,14 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
 
   /* If this index contains every column of its table, then mark
   ** it as a covering index */
-  assert( HasRowid(pTab) 
-      || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
+  assert( HasRowid(pTab)
+      || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
   recomputeColumnsNotIndexed(pIndex);
   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
     pIndex->isCovering = 1;
     for(j=0; j<pTab->nCol; j++){
       if( j==pTab->iPKey ) continue;
-      if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
+      if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
       pIndex->isCovering = 0;
       break;
     }
@@ -111473,13 +114985,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
         if( pIdx->onError!=pIndex->onError ){
           /* This constraint creates the same index as a previous
           ** constraint specified somewhere in the CREATE TABLE statement.
-          ** However the ON CONFLICT clauses are different. If both this 
+          ** However the ON CONFLICT clauses are different. If both this
           ** constraint and the previous equivalent constraint have explicit
           ** ON CONFLICT clauses this is an error. Otherwise, use the
           ** explicitly specified behavior for the index.
           */
           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
-            sqlite3ErrorMsg(pParse, 
+            sqlite3ErrorMsg(pParse,
                 "conflicting ON CONFLICT clauses specified", 0);
           }
           if( pIdx->onError==OE_Default ){
@@ -111500,7 +115012,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
   if( !IN_RENAME_OBJECT ){
 
     /* Link the new Index structure to its table and to the other
-    ** in-memory database structures. 
+    ** in-memory database structures.
     */
     assert( pParse->nErr==0 );
     if( db->init.busy ){
@@ -111515,7 +115027,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
           goto exit_create_index;
         }
       }
-      p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
+      p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
           pIndex->zName, pIndex);
       if( p ){
         assert( p==pIndex );  /* Malloc must have failed */
@@ -111528,8 +115040,8 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
     /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
     ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
     ** emit code to allocate the index rootpage on disk and make an entry for
-    ** the index in the sqlite_master table and populate the index with
-    ** content.  But, do not do this if we are simply reading the sqlite_master
+    ** the index in the sqlite_schema table and populate the index with
+    ** content.  But, do not do this if we are simply reading the sqlite_schema
     ** table to parse the schema, or if this index is the PRIMARY KEY index
     ** of a WITHOUT ROWID table.
     **
@@ -111549,12 +115061,12 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
       sqlite3BeginWriteOperation(pParse, 1, iDb);
 
       /* Create the rootpage for the index using CreateIndex. But before
-      ** doing so, code a Noop instruction and store its address in 
-      ** Index.tnum. This is required in case this index is actually a 
-      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 
+      ** doing so, code a Noop instruction and store its address in
+      ** Index.tnum. This is required in case this index is actually a
+      ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
       ** that case the convertToWithoutRowidTable() routine will replace
       ** the Noop with a Goto to jump over the VDBE code generated below. */
-      pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
+      pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
       sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
 
       /* Gather the complete text of the CREATE INDEX statement into
@@ -111573,11 +115085,11 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
         zStmt = 0;
       }
 
-      /* Add an entry in sqlite_master for this index
+      /* Add an entry in sqlite_schema for this index
       */
-      sqlite3NestedParse(pParse, 
-          "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
-          db->aDb[iDb].zDbSName, MASTER_NAME,
+      sqlite3NestedParse(pParse,
+          "INSERT INTO %Q." DFLT_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
+          db->aDb[iDb].zDbSName,
           pIndex->zName,
           pTab->zName,
           iMem,
@@ -111596,29 +115108,12 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
         sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
       }
 
-      sqlite3VdbeJumpHere(v, pIndex->tnum);
+      sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
     }
   }
-
-  /* When adding an index to the list of indices for a table, make
-  ** sure all indices labeled OE_Replace come after all those labeled
-  ** OE_Ignore.  This is necessary for the correct constraint check
-  ** processing (in sqlite3GenerateConstraintChecks()) as part of
-  ** UPDATE and INSERT statements.  
-  */
   if( db->init.busy || pTblName==0 ){
-    if( onError!=OE_Replace || pTab->pIndex==0
-         || pTab->pIndex->onError==OE_Replace){
-      pIndex->pNext = pTab->pIndex;
-      pTab->pIndex = pIndex;
-    }else{
-      Index *pOther = pTab->pIndex;
-      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
-        pOther = pOther->pNext;
-      }
-      pIndex->pNext = pOther->pNext;
-      pOther->pNext = pIndex;
-    }
+    pIndex->pNext = pTab->pIndex;
+    pTab->pIndex = pIndex;
     pIndex = 0;
   }
   else if( IN_RENAME_OBJECT ){
@@ -111630,6 +115125,21 @@ SQLITE_PRIVATE void sqlite3CreateIndex(
   /* Clean up before exiting */
 exit_create_index:
   if( pIndex ) sqlite3FreeIndex(db, pIndex);
+  if( pTab ){  /* Ensure all REPLACE indexes are at the end of the list */
+    Index **ppFrom = &pTab->pIndex;
+    Index *pThis;
+    for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
+      Index *pNext;
+      if( pThis->onError!=OE_Replace ) continue;
+      while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
+        *ppFrom = pNext;
+        pThis->pNext = pNext->pNext;
+        pNext->pNext = pThis;
+        ppFrom = &pNext->pNext;
+      }
+      break;
+    }
+  }
   sqlite3ExprDelete(db, pPIWhere);
   sqlite3ExprListDelete(db, pList);
   sqlite3SrcListDelete(db, pTblName);
@@ -111655,21 +115165,33 @@ exit_create_index:
 ** are based on typical values found in actual indices.
 */
 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
-  /*                10,  9,  8,  7,  6 */
-  LogEst aVal[] = { 33, 32, 30, 28, 26 };
+               /*                10,  9,  8,  7,  6 */
+  static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
   LogEst *a = pIdx->aiRowLogEst;
+  LogEst x;
   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
   int i;
 
   /* Indexes with default row estimates should not have stat1 data */
   assert( !pIdx->hasStat1 );
 
-  /* Set the first entry (number of rows in the index) to the estimated 
+  /* Set the first entry (number of rows in the index) to the estimated
   ** number of rows in the table, or half the number of rows in the table
-  ** for a partial index.   But do not let the estimate drop below 10. */
-  a[0] = pIdx->pTable->nRowLogEst;
-  if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
-  if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
+  ** for a partial index.
+  **
+  ** 2020-05-27:  If some of the stat data is coming from the sqlite_stat1
+  ** table but other parts we are having to guess at, then do not let the
+  ** estimated number of rows in the table be less than 1000 (LogEst 99).
+  ** Failure to do this can cause the indexes for which we do not have
+  ** stat1 data to be ignored by the query planner.
+  */
+  x = pIdx->pTable->nRowLogEst;
+  assert( 99==sqlite3LogEst(1000) );
+  if( x<99 ){
+    pIdx->pTable->nRowLogEst = x = 99;
+  }
+  if( pIdx->pPartIdxWhere!=0 ) x -= 10;  assert( 10==sqlite3LogEst(2) );
+  a[0] = x;
 
   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
   ** 6 and each subsequent value (if any) is 5.  */
@@ -111732,13 +115254,13 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists
   }
 #endif
 
-  /* Generate code to remove the index and from the master table */
+  /* Generate code to remove the index and from the schema table */
   v = sqlite3GetVdbe(pParse);
   if( v ){
     sqlite3BeginWriteOperation(pParse, 1, iDb);
     sqlite3NestedParse(pParse,
-       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
-       db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
+       "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
+       db->aDb[iDb].zDbSName, pIndex->zName
     );
     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
     sqlite3ChangeCookie(pParse, iDb);
@@ -111948,7 +115470,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
 ** database name prefix.  Like this:  "database.table".  The pDatabase
 ** points to the table name and the pTable points to the database name.
 ** The SrcList.a[].zName field is filled with the table name which might
-** come from pTable (if pDatabase is NULL) or from pDatabase.  
+** come from pTable (if pDatabase is NULL) or from pDatabase.
 ** SrcList.a[].zDatabase is filled with the database name from pTable,
 ** or with NULL if no database is specified.
 **
@@ -112020,7 +115542,7 @@ SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
   assert(pList || pParse->db->mallocFailed );
   if( pList ){
     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
-      if( pItem->iCursor>=0 ) break;
+      if( pItem->iCursor>=0 ) continue;
       pItem->iCursor = pParse->nTab++;
       if( pItem->pSelect ){
         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
@@ -112037,15 +115559,15 @@ SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
   struct SrcList_item *pItem;
   if( pList==0 ) return;
   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
-    sqlite3DbFree(db, pItem->zDatabase);
+    if( pItem->zDatabase ) sqlite3DbFreeNN(db, pItem->zDatabase);
     sqlite3DbFree(db, pItem->zName);
-    sqlite3DbFree(db, pItem->zAlias);
+    if( pItem->zAlias ) sqlite3DbFreeNN(db, pItem->zAlias);
     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
     sqlite3DeleteTable(db, pItem->pTab);
-    sqlite3SelectDelete(db, pItem->pSelect);
-    sqlite3ExprDelete(db, pItem->pOn);
-    sqlite3IdListDelete(db, pItem->pUsing);
+    if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
+    if( pItem->pOn ) sqlite3ExprDelete(db, pItem->pOn);
+    if( pItem->pUsing ) sqlite3IdListDelete(db, pItem->pUsing);
   }
   sqlite3DbFreeNN(db, pList);
 }
@@ -112079,7 +115601,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
   struct SrcList_item *pItem;
   sqlite3 *db = pParse->db;
   if( !p && (pOn || pUsing) ){
-    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
+    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
       (pOn ? "ON" : "USING")
     );
     goto append_from_error;
@@ -112114,7 +115636,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
 }
 
 /*
-** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
+** Add an INDEXED BY or NOT INDEXED clause to the most recently added
 ** element of the source-list passed as the second argument.
 */
 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
@@ -112127,7 +115649,7 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI
     assert( pItem->fg.isIndexedBy==0 );
     assert( pItem->fg.isTabFunc==0 );
     if( pIndexedBy->n==1 && !pIndexedBy->z ){
-      /* A "NOT INDEXED" clause was supplied. See parse.y 
+      /* A "NOT INDEXED" clause was supplied. See parse.y
       ** construct "indexed_opt" for details. */
       pItem->fg.notIndexed = 1;
     }else{
@@ -112138,6 +115660,26 @@ SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pI
 }
 
 /*
+** Append the contents of SrcList p2 to SrcList p1 and return the resulting
+** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
+** are deleted by this function.
+*/
+SQLITE_PRIVATE SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
+  assert( p1 && p1->nSrc==1 );
+  if( p2 ){
+    SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
+    if( pNew==0 ){
+      sqlite3SrcListDelete(pParse->db, p2);
+    }else{
+      p1 = pNew;
+      memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(struct SrcList_item));
+      sqlite3DbFree(pParse->db, p2);
+    }
+  }
+  return p1;
+}
+
+/*
 ** Add the list of function arguments to the SrcList entry for a
 ** table-valued-function.
 */
@@ -112197,7 +115739,16 @@ SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
   if( !v ) return;
   if( type!=TK_DEFERRED ){
     for(i=0; i<db->nDb; i++){
-      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
+      int eTxnType;
+      Btree *pBt = db->aDb[i].pBt;
+      if( pBt && sqlite3BtreeIsReadonly(pBt) ){
+        eTxnType = 0;  /* Read txn */
+      }else if( type==TK_EXCLUSIVE ){
+        eTxnType = 2;  /* Exclusive txn */
+      }else{
+        eTxnType = 1;  /* Write txn */
+      }
+      sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
       sqlite3VdbeUsesBtree(v, i);
     }
   }
@@ -112217,7 +115768,7 @@ SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
   assert( pParse->db!=0 );
   assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
   isRollback = eType==TK_ROLLBACK;
-  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, 
+  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
        isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
     return;
   }
@@ -112229,7 +115780,7 @@ SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
 
 /*
 ** This function is called by the parser when it parses a command to create,
-** release or rollback an SQL savepoint. 
+** release or rollback an SQL savepoint.
 */
 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
   char *zName = sqlite3NameFromToken(pParse->db, pName);
@@ -112256,7 +115807,7 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
   if( db->aDb[1].pBt==0 && !pParse->explain ){
     int rc;
     Btree *pBt;
-    static const int flags = 
+    static const int flags =
           SQLITE_OPEN_READWRITE |
           SQLITE_OPEN_CREATE |
           SQLITE_OPEN_EXCLUSIVE |
@@ -112272,7 +115823,7 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
     }
     db->aDb[1].pBt = pBt;
     assert( db->aDb[1].pSchema );
-    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
+    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
       sqlite3OomFault(db);
       return 1;
     }
@@ -112286,13 +115837,11 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
 ** will occur at the end of the top-level VDBE and will be generated
 ** later, by sqlite3FinishCoding().
 */
-SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
-  Parse *pToplevel = sqlite3ParseToplevel(pParse);
-
-  assert( iDb>=0 && iDb<pParse->db->nDb );
-  assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
+static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
+  assert( iDb>=0 && iDb<pToplevel->db->nDb );
+  assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
   assert( iDb<SQLITE_MAX_ATTACHED+2 );
-  assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
+  assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
     DbMaskSet(pToplevel->cookieMask, iDb);
     if( !OMIT_TEMPDB && iDb==1 ){
@@ -112300,9 +115849,13 @@ SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
     }
   }
 }
+SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
+  sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
+}
+
 
 /*
-** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
+** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
 ** attached database. Otherwise, invoke it for the database named zDb only.
 */
 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
@@ -112331,7 +115884,7 @@ SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb)
 */
 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
   Parse *pToplevel = sqlite3ParseToplevel(pParse);
-  sqlite3CodeVerifySchema(pParse, iDb);
+  sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
   DbMaskSet(pToplevel->writeMask, iDb);
   pToplevel->isMultiWrite |= setStatement;
 }
@@ -112348,9 +115901,9 @@ SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
   pToplevel->isMultiWrite = 1;
 }
 
-/* 
+/*
 ** The code generator calls this routine if is discovers that it is
-** possible to abort a statement prior to completion.  In order to 
+** possible to abort a statement prior to completion.  In order to
 ** perform this abort without corrupting the database, we need to make
 ** sure that the statement is protected by a statement transaction.
 **
@@ -112359,7 +115912,7 @@ SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
 ** such that the abort must occur after the multiwrite.  This makes
 ** some statements involving the REPLACE conflict resolution algorithm
 ** go a little faster.  But taking advantage of this time dependency
-** makes it more difficult to prove that the code is correct (in 
+** makes it more difficult to prove that the code is correct (in
 ** particular, it prevents us from writing an effective
 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
 ** to take the safe route and skip the optimization.
@@ -112382,8 +115935,10 @@ SQLITE_PRIVATE void sqlite3HaltConstraint(
   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
   u8 p5Errmsg       /* P5_ErrMsg type */
 ){
-  Vdbe *v = sqlite3GetVdbe(pParse);
-  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
+  Vdbe *v;
+  assert( pParse->pVdbe!=0 );
+  v = sqlite3GetVdbe(pParse);
+  assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
   if( onError==OE_Abort ){
     sqlite3MayAbort(pParse);
   }
@@ -112404,7 +115959,7 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint(
   StrAccum errMsg;
   Table *pTab = pIdx->pTable;
 
-  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 
+  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
                       pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
   if( pIdx->aColExpr ){
     sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
@@ -112420,8 +115975,8 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint(
     }
   }
   zErr = sqlite3StrAccumFinish(&errMsg);
-  sqlite3HaltConstraint(pParse, 
-    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
+  sqlite3HaltConstraint(pParse,
+    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
                             : SQLITE_CONSTRAINT_UNIQUE,
     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
 }
@@ -112433,7 +115988,7 @@ SQLITE_PRIVATE void sqlite3UniqueConstraint(
 SQLITE_PRIVATE void sqlite3RowidConstraint(
   Parse *pParse,    /* Parsing context */
   int onError,      /* Conflict resolution algorithm */
-  Table *pTab       /* The table with the non-unique rowid */ 
+  Table *pTab       /* The table with the non-unique rowid */
 ){
   char *zMsg;
   int rc;
@@ -112627,9 +116182,9 @@ SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
 }
 
 #ifndef SQLITE_OMIT_CTE
-/* 
-** This routine is invoked once per CTE by the parser while parsing a 
-** WITH clause. 
+/*
+** This routine is invoked once per CTE by the parser while parsing a
+** WITH clause.
 */
 SQLITE_PRIVATE With *sqlite3WithAdd(
   Parse *pParse,          /* Parsing context */
@@ -112698,7 +116253,7 @@ SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
 /************** End of build.c ***********************************************/
 /************** Begin file callback.c ****************************************/
 /*
-** 2005 May 23 
+** 2005 May 23
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
@@ -112765,58 +116320,13 @@ static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
 }
 
 /*
-** This function is responsible for invoking the collation factory callback
-** or substituting a collation sequence of a different encoding when the
-** requested collation sequence is not available in the desired encoding.
-** 
-** If it is not NULL, then pColl must point to the database native encoding 
-** collation sequence with name zName, length nName.
-**
-** The return value is either the collation sequence to be used in database
-** db for collation type name zName, length nName, or NULL, if no collation
-** sequence can be found.  If no collation is found, leave an error message.
-**
-** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
-*/
-SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
-  Parse *pParse,        /* Parsing context */
-  u8 enc,               /* The desired encoding for the collating sequence */
-  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
-  const char *zName     /* Collating sequence name */
-){
-  CollSeq *p;
-  sqlite3 *db = pParse->db;
-
-  p = pColl;
-  if( !p ){
-    p = sqlite3FindCollSeq(db, enc, zName, 0);
-  }
-  if( !p || !p->xCmp ){
-    /* No collation sequence of this type for this encoding is registered.
-    ** Call the collation factory to see if it can supply us with one.
-    */
-    callCollNeeded(db, enc, zName);
-    p = sqlite3FindCollSeq(db, enc, zName, 0);
-  }
-  if( p && !p->xCmp && synthCollSeq(db, p) ){
-    p = 0;
-  }
-  assert( !p || p->xCmp );
-  if( p==0 ){
-    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
-    pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
-  }
-  return p;
-}
-
-/*
 ** This routine is called on a collation sequence before it is used to
 ** check that it is defined. An undefined collation sequence exists when
 ** a database is loaded that contains references to collation sequences
 ** that have not been defined by sqlite3_create_collation() etc.
 **
 ** If required, this routine calls the 'collation needed' callback to
-** request a definition of the collating sequence. If this doesn't work, 
+** request a definition of the collating sequence. If this doesn't work,
 ** an equivalent collating sequence that uses a text encoding different
 ** from the main database is substituted, if one is available.
 */
@@ -112870,7 +116380,7 @@ static CollSeq *findCollSeqEntry(
       memcpy(pColl[0].zName, zName, nName);
       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
 
-      /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
+      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
       ** return the pColl pointer to be deleted (because it wasn't added
       ** to the hash table).
       */
@@ -112901,20 +116411,112 @@ static CollSeq *findCollSeqEntry(
 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
 */
 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
-  sqlite3 *db,
-  u8 enc,
-  const char *zName,
-  int create
+  sqlite3 *db,          /* Database connection to search */
+  u8 enc,               /* Desired text encoding */
+  const char *zName,    /* Name of the collating sequence.  Might be NULL */
+  int create            /* True to create CollSeq if doesn't already exist */
 ){
   CollSeq *pColl;
+  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
+  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
   if( zName ){
     pColl = findCollSeqEntry(db, zName, create);
+    if( pColl ) pColl += enc-1;
   }else{
     pColl = db->pDfltColl;
   }
-  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
-  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
-  if( pColl ) pColl += enc-1;
+  return pColl;
+}
+
+/*
+** Change the text encoding for a database connection. This means that
+** the pDfltColl must change as well.
+*/
+SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
+  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
+  db->enc = enc;
+  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
+  ** strings is BINARY.
+  */
+  db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
+}
+
+/*
+** This function is responsible for invoking the collation factory callback
+** or substituting a collation sequence of a different encoding when the
+** requested collation sequence is not available in the desired encoding.
+**
+** If it is not NULL, then pColl must point to the database native encoding
+** collation sequence with name zName, length nName.
+**
+** The return value is either the collation sequence to be used in database
+** db for collation type name zName, length nName, or NULL, if no collation
+** sequence can be found.  If no collation is found, leave an error message.
+**
+** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
+*/
+SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
+  Parse *pParse,        /* Parsing context */
+  u8 enc,               /* The desired encoding for the collating sequence */
+  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
+  const char *zName     /* Collating sequence name */
+){
+  CollSeq *p;
+  sqlite3 *db = pParse->db;
+
+  p = pColl;
+  if( !p ){
+    p = sqlite3FindCollSeq(db, enc, zName, 0);
+  }
+  if( !p || !p->xCmp ){
+    /* No collation sequence of this type for this encoding is registered.
+    ** Call the collation factory to see if it can supply us with one.
+    */
+    callCollNeeded(db, enc, zName);
+    p = sqlite3FindCollSeq(db, enc, zName, 0);
+  }
+  if( p && !p->xCmp && synthCollSeq(db, p) ){
+    p = 0;
+  }
+  assert( !p || p->xCmp );
+  if( p==0 ){
+    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
+    pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
+  }
+  return p;
+}
+
+/*
+** This function returns the collation sequence for database native text
+** encoding identified by the string zName.
+**
+** If the requested collation sequence is not available, or not available
+** in the database native encoding, the collation factory is invoked to
+** request it. If the collation factory does not supply such a sequence,
+** and the sequence is available in another text encoding, then that is
+** returned instead.
+**
+** If no versions of the requested collations sequence are available, or
+** another error occurs, NULL is returned and an error message written into
+** pParse.
+**
+** This routine is a wrapper around sqlite3FindCollSeq().  This routine
+** invokes the collation factory if the named collation cannot be found
+** and generates an error message.
+**
+** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
+*/
+SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
+  sqlite3 *db = pParse->db;
+  u8 enc = ENC(db);
+  u8 initbusy = db->init.busy;
+  CollSeq *pColl;
+
+  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
+  if( !initbusy && (!pColl || !pColl->xCmp) ){
+    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
+  }
+
   return pColl;
 }
 
@@ -112928,7 +116530,7 @@ SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
 ** is also -1.  In other words, we are searching for a function that
 ** takes a variable number of arguments.
 **
-** If nArg is -2 that means that we are searching for any function 
+** If nArg is -2 that means that we are searching for any function
 ** regardless of the number of arguments it uses, so return a positive
 ** match score for any
 **
@@ -112953,12 +116555,13 @@ static int matchQuality(
   u8 enc          /* Desired text encoding */
 ){
   int match;
-
-  /* nArg of -2 is a special case */
-  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
+  assert( p->nArg>=-1 );
 
   /* Wrong number of arguments means "no match" */
-  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
+  if( p->nArg!=nArg ){
+    if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
+    if( p->nArg>=0 ) return 0;
+  }
 
   /* Give a better score to a function with a specific number of arguments
   ** than to function that accepts any number of arguments. */
@@ -113021,8 +116624,8 @@ SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
     }
   }
 }
-  
-  
+
+
 
 /*
 ** Locate a user function given a name, a number of arguments and a flag
@@ -113083,7 +116686,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   ** have fields overwritten with new information appropriate for the
   ** new function.  But the FuncDefs for built-in functions are read-only.
   ** So we must not search for built-ins when creating a new function.
-  */ 
+  */
   if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
     bestScore = 0;
     h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
@@ -113102,7 +116705,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
   ** exact match for the name, number of arguments and encoding, then add a
   ** new entry to the hash table and return it.
   */
-  if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
+  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
     FuncDef *pOther;
     u8 *z;
@@ -113129,7 +116732,7 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
 
 /*
 ** Free all resources held by the schema structure. The void* argument points
-** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
+** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
 ** of the schema hash tables).
 **
@@ -113209,7 +116812,7 @@ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
 ** (as in the FROM clause of a SELECT statement) in this case it contains
 ** the name of a single table, as one might find in an INSERT, DELETE,
 ** or UPDATE statement.  Look up that table in the symbol table and
-** return a pointer.  Set an error message and return NULL if the table 
+** return a pointer.  Set an error message and return NULL if the table
 ** name is not found or if any other error occurs.
 **
 ** The following fields are initialized appropriate in pSrc:
@@ -113221,7 +116824,7 @@ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
   struct SrcList_item *pItem = pSrc->a;
   Table *pTab;
-  assert( pItem && pSrc->nSrc==1 );
+  assert( pItem && pSrc->nSrc>=1 );
   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
   sqlite3DeleteTable(pParse->db, pItem->pTab);
   pItem->pTab = pTab;
@@ -113241,8 +116844,8 @@ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
 **   1) It is a virtual table and no implementation of the xUpdate method
 **      has been provided
 **
-**   2) It is a system table (i.e. sqlite_master), this call is not
-**      part of a nested parse and writable_schema pragma has not 
+**   2) It is a system table (i.e. sqlite_schema), this call is not
+**      part of a nested parse and writable_schema pragma has not
 **      been specified
 **
 **   3) The table is a shadow table, the database connection is in
@@ -113260,11 +116863,7 @@ static int tabIsReadOnly(Parse *pParse, Table *pTab){
     return sqlite3WritableSchema(db)==0 && pParse->nested==0;
   }
   assert( pTab->tabFlags & TF_Shadow );
-  return (db->flags & SQLITE_Defensive)!=0 
-#ifndef SQLITE_OMIT_VIRTUALTABLE
-          && db->pVtabCtx==0
-#endif
-          && db->nVdbeExec==0;
+  return sqlite3ReadOnlyShadowTables(db);
 }
 
 /*
@@ -113315,7 +116914,7 @@ SQLITE_PRIVATE void sqlite3MaterializeView(
     assert( pFrom->a[0].pOn==0 );
     assert( pFrom->a[0].pUsing==0 );
   }
-  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy, 
+  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
                           SF_IncludeHidden, pLimit);
   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
   sqlite3Select(pParse, pSel, &dest);
@@ -113364,11 +116963,11 @@ SQLITE_PRIVATE Expr *sqlite3LimitWhere(
     return pWhere;
   }
 
-  /* Generate a select expression tree to enforce the limit/offset 
+  /* Generate a select expression tree to enforce the limit/offset
   ** term for the DELETE or UPDATE statement.  For example:
   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   ** becomes:
-  **   DELETE FROM table_a WHERE rowid IN ( 
+  **   DELETE FROM table_a WHERE rowid IN (
   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
   **   );
   */
@@ -113406,7 +117005,7 @@ SQLITE_PRIVATE Expr *sqlite3LimitWhere(
   pSrc->a[0].pIBIndex = 0;
 
   /* generate the SELECT expression tree. */
-  pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0, 
+  pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
       pOrderBy,0,pLimit
   );
 
@@ -113462,7 +117061,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
   int bComplex;          /* True if there are triggers or FKs or
                          ** subqueries in the WHERE clause */
+
 #ifndef SQLITE_OMIT_TRIGGER
   int isView;                  /* True if attempting to delete from a view */
   Trigger *pTrigger;           /* List of table triggers, if required */
@@ -113526,7 +117125,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   }
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   assert( iDb<db->nDb );
-  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, 
+  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
                             db->aDb[iDb].zDbSName);
   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
   if( rcauth==SQLITE_DENY ){
@@ -113562,7 +117161,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   */
 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
   if( isView ){
-    sqlite3MaterializeView(pParse, pTab, 
+    sqlite3MaterializeView(pParse, pTab,
         pWhere, pOrderBy, pLimit, iTabCur
     );
     iDataCur = iIdxCur = iTabCur;
@@ -113594,7 +117193,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
   /* Special case: A DELETE without a WHERE clause deletes everything.
   ** It is easier just to erase the whole table. Prior to version 3.6.5,
-  ** this optimization caused the row change count (the value returned by 
+  ** this optimization caused the row change count (the value returned by
   ** API function sqlite3_count_changes) to be set incorrectly.
   **
   ** The "rcauth==SQLITE_OK" terms is the
@@ -113624,7 +117223,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
   }else
 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
   {
-    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
+    u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK;
     if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
     wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
     if( HasRowid(pTab) ){
@@ -113645,7 +117244,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
     }
-  
+
     /* Construct a query to find the rowid or primary key for every row
     ** to be deleted, based on the WHERE clause. Set variable eOnePass
     ** to indicate the strategy used to implement this delete:
@@ -113660,12 +117259,15 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
     assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
     if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
-  
+    if( sqlite3WhereUsesDeferredSeek(pWInfo) ){
+      sqlite3VdbeAddOp1(v, OP_FinishSeek, iTabCur);
+    }
+
     /* Keep track of the number of rows to be deleted */
     if( memCnt ){
       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
     }
-  
+
     /* Extract the rowid or primary key for the current row */
     if( pPk ){
       for(i=0; i<nPk; i++){
@@ -113678,7 +117280,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
       iKey = ++pParse->nMem;
       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
     }
-  
+
     if( eOnePass!=ONEPASS_OFF ){
       /* For ONEPASS, no need to store the rowid/primary-key. There is only
       ** one, so just keep it in its register(s) and fall through to the
@@ -113694,6 +117296,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
+      addrBypass = sqlite3VdbeMakeLabel(pParse);
     }else{
       if( pPk ){
         /* Add the PK key for this row to the temporary table */
@@ -113707,19 +117310,12 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
         nKey = 1;  /* OP_DeferredSeek always uses a single rowid */
         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
       }
-    }
-  
-    /* If this DELETE cannot use the ONEPASS strategy, this is the 
-    ** end of the WHERE loop */
-    if( eOnePass!=ONEPASS_OFF ){
-      addrBypass = sqlite3VdbeMakeLabel(pParse);
-    }else{
       sqlite3WhereEnd(pWInfo);
     }
-  
-    /* Unless this is a view, open cursors for the table we are 
+
+    /* Unless this is a view, open cursors for the table we are
     ** deleting from and all its indices. If this is a view, then the
-    ** only effect this statement has is to fire the INSTEAD OF 
+    ** only effect this statement has is to fire the INSTEAD OF
     ** triggers.
     */
     if( !isView ){
@@ -113732,9 +117328,11 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
                                  iTabCur, aToOpen, &iDataCur, &iIdxCur);
       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
-      if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
+      if( eOnePass==ONEPASS_MULTI ){
+        sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
+      }
     }
-  
+
     /* Set up a loop over the rowids/primary-keys that were found in the
     ** where-clause loop above.
     */
@@ -113757,8 +117355,8 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
       VdbeCoverage(v);
       assert( nKey==1 );
-    }  
-  
+    }
+
     /* Delete the row */
 #ifndef SQLITE_OMIT_VIRTUALTABLE
     if( IsVirtual(pTab) ){
@@ -113781,7 +117379,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
           iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
     }
-  
+
     /* End of the loop over all rowids/primary-keys. */
     if( eOnePass!=ONEPASS_OFF ){
       sqlite3VdbeResolveLabel(v, addrBypass);
@@ -113792,7 +117390,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     }else{
       sqlite3VdbeGoto(v, addrLoop);
       sqlite3VdbeJumpHere(v, addrLoop);
-    }     
+    }
   } /* End non-truncate path */
 
   /* Update the sqlite_sequence table by storing the content of the
@@ -113803,7 +117401,7 @@ SQLITE_PRIVATE void sqlite3DeleteFrom(
     sqlite3AutoincrementEnd(pParse);
   }
 
-  /* Return the number of rows that were deleted. If this routine is 
+  /* Return the number of rows that were deleted. If this routine is
   ** generating code because of a call to sqlite3NestedParse(), do not
   ** invoke the callback function.
   */
@@ -113860,7 +117458,7 @@ delete_from_cleanup:
 **   and nPk before reading from it.
 **
 **   If eMode is ONEPASS_MULTI, then this call is being made as part
-**   of a ONEPASS delete that affects multiple rows. In this case, if 
+**   of a ONEPASS delete that affects multiple rows. In this case, if
 **   iIdxNoSeek is a valid cursor number (>=0) and is not the same as
 **   iDataCur, then its position should be preserved following the delete
 **   operation. Or, if iIdxNoSeek is not a valid cursor number, the
@@ -113896,7 +117494,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
                          iDataCur, iIdxCur, iPk, (int)nPk));
 
-  /* Seek cursor iCur to the row to delete. If this row no longer exists 
+  /* Seek cursor iCur to the row to delete. If this row no longer exists
   ** (this can happen if a trigger program has already deleted it), do
   ** not attempt to delete it or fire any DELETE triggers.  */
   iLabel = sqlite3VdbeMakeLabel(pParse);
@@ -113906,7 +117504,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
     VdbeCoverageIf(v, opSeek==OP_NotExists);
     VdbeCoverageIf(v, opSeek==OP_NotFound);
   }
+
   /* If there are any triggers to fire, allocate a range of registers to
   ** use for the old.* references in the triggers.  */
   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
@@ -113923,24 +117521,25 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
     iOld = pParse->nMem+1;
     pParse->nMem += (1 + pTab->nCol);
 
-    /* Populate the OLD.* pseudo-table register array. These values will be 
+    /* Populate the OLD.* pseudo-table register array. These values will be
     ** used by any BEFORE and AFTER triggers that exist.  */
     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
     for(iCol=0; iCol<pTab->nCol; iCol++){
       testcase( mask!=0xffffffff && iCol==31 );
       testcase( mask!=0xffffffff && iCol==32 );
       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
-        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
+        int kk = sqlite3TableColumnToStorage(pTab, iCol);
+        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
       }
     }
 
     /* Invoke BEFORE DELETE trigger programs. */
     addrStart = sqlite3VdbeCurrentAddr(v);
-    sqlite3CodeRowTrigger(pParse, pTrigger, 
+    sqlite3CodeRowTrigger(pParse, pTrigger,
         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
     );
 
-    /* If any BEFORE triggers were coded, then seek the cursor to the 
+    /* If any BEFORE triggers were coded, then seek the cursor to the
     ** row to be deleted again. It may be that the BEFORE triggers moved
     ** the cursor or already deleted the row that the cursor was
     ** pointing to.
@@ -113957,21 +117556,21 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
     }
 
     /* Do FK processing. This call checks that any FK constraints that
-    ** refer to this table (i.e. constraints attached to other tables) 
+    ** refer to this table (i.e. constraints attached to other tables)
     ** are not violated by deleting this row.  */
     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
   }
 
   /* Delete the index and table entries. Skip this step if pTab is really
   ** a view (in which case the only effect of the DELETE statement is to
-  ** fire the INSTEAD OF triggers).  
+  ** fire the INSTEAD OF triggers).
   **
   ** If variable 'count' is non-zero, then this OP_Delete instruction should
   ** invoke the update-hook. The pre-update-hook, on the other hand should
   ** be invoked unless table pTab is a system table. The difference is that
-  ** the update-hook is not invoked for rows removed by REPLACE, but the 
+  ** the update-hook is not invoked for rows removed by REPLACE, but the
   ** pre-update-hook is.
-  */ 
+  */
   if( pTab->pSelect==0 ){
     u8 p5 = 0;
     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
@@ -113991,16 +117590,16 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete(
 
   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
   ** handle rows (possibly in other tables) that refer via a foreign key
-  ** to the row just deleted. */ 
+  ** to the row just deleted. */
   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
 
   /* Invoke AFTER DELETE trigger programs. */
-  sqlite3CodeRowTrigger(pParse, pTrigger, 
+  sqlite3CodeRowTrigger(pParse, pTrigger,
       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
   );
 
   /* Jump here if the row had already been deleted before any BEFORE
-  ** trigger programs were invoked. Or if a trigger program throws a 
+  ** trigger programs were invoked. Or if a trigger program throws a
   ** RAISE(IGNORE) exception.  */
   sqlite3VdbeResolveLabel(v, iLabel);
   VdbeModuleComment((v, "END: GenRowDel()"));
@@ -114052,6 +117651,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
         &iPartIdxLabel, pPrior, r1);
     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
+    sqlite3VdbeChangeP5(v, 1);  /* Cause IdxDelete to error if no entry found */
     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
     pPrior = pIdx;
   }
@@ -114084,7 +117684,7 @@ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
 ** its key into the same sequence of registers and if pPrior and pIdx share
 ** a column in common, then the register corresponding to that column already
 ** holds the correct value and the loading of that register is skipped.
-** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
+** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
 ** on a table with multiple indices, and especially with the ROWID or
 ** PRIMARY KEY columns of the index.
 */
@@ -114107,9 +117707,11 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey(
     if( pIdx->pPartIdxWhere ){
       *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
       pParse->iSelfTab = iDataCur + 1;
-      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
+      sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
                             SQLITE_JUMPIFNULL);
       pParse->iSelfTab = 0;
+      pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
+                  ** pPartIdxWhere may have corrupted regPrior registers */
     }else{
       *piPartIdxLabel = 0;
     }
@@ -114136,10 +117738,6 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey(
   }
   if( regOut ){
     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
-    if( pIdx->pTable->pSelect ){
-      const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
-      sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
-    }
   }
   sqlite3ReleaseTempRange(pParse, regBase, nCol);
   return regBase;
@@ -114176,7 +117774,9 @@ SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
 /* #include "sqliteInt.h" */
 /* #include <stdlib.h> */
 /* #include <assert.h> */
+#ifndef SQLITE_OMIT_FLOATING_POINT
 /* #include <math.h> */
+#endif
 /* #include "vdbeInt.h" */
 
 /*
@@ -114299,7 +117899,7 @@ static void lengthFunc(
 ** Implementation of the abs() function.
 **
 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
-** the numeric argument X. 
+** the numeric argument X.
 */
 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   assert( argc==1 );
@@ -114316,7 +117916,7 @@ static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
           return;
         }
         iVal = -iVal;
-      } 
+      }
       sqlite3_result_int64(context, iVal);
       break;
     }
@@ -114568,7 +118168,7 @@ static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
   */
   if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
     /* The value has no fractional part so there is nothing to round */
-  }else if( n==0 ){  
+  }else if( n==0 ){
     r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
   }else{
     zBuf = sqlite3_mprintf("%.*f",n,r);
@@ -114661,7 +118261,7 @@ static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 #define noopFunc versionFunc   /* Substitute function - never called */
 
 /*
-** Implementation of random().  Return a random integer.  
+** Implementation of random().  Return a random integer.
 */
 static void randomFunc(
   sqlite3_context *context,
@@ -114672,11 +118272,11 @@ static void randomFunc(
   UNUSED_PARAMETER2(NotUsed, NotUsed2);
   sqlite3_randomness(sizeof(r), &r);
   if( r<0 ){
-    /* We need to prevent a random number of 0x8000000000000000 
+    /* We need to prevent a random number of 0x8000000000000000
     ** (or -9223372036854775808) since when you do abs() of that
     ** number of you get the same value back again.  To do this
     ** in a way that is testable, mask the sign bit off of negative
-    ** values, resulting in a positive value.  Then take the 
+    ** values, resulting in a positive value.  Then take the
     ** 2s complement of that positive value.  The end result can
     ** therefore be no less than -9223372036854775807.
     */
@@ -114714,8 +118314,8 @@ static void randomBlob(
 ** value is the same as the sqlite3_last_insert_rowid() API function.
 */
 static void last_insert_rowid(
-  sqlite3_context *context, 
-  int NotUsed, 
+  sqlite3_context *context,
+  int NotUsed,
   sqlite3_value **NotUsed2
 ){
   sqlite3 *db = sqlite3_context_db_handle(context);
@@ -114823,7 +118423,7 @@ static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
 ** it the last character in the list.
 **
 ** Like matching rules:
-** 
+**
 **      '%'       Matches any sequence of zero or more characters
 **
 ***     '_'       Matches any one character
@@ -114846,7 +118446,7 @@ static int patternCompare(
   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
   const u8 *zEscaped = 0;          /* One past the last escaped input char */
-  
+
   while( (c = Utf8Read(zPattern))!=0 ){
     if( c==matchAll ){  /* Match "*" */
       /* Skip over multiple "*" characters in the pattern.  If there
@@ -115002,8 +118602,8 @@ SQLITE_API int sqlite3_like_count = 0;
 ** the GLOB operator.
 */
 static void likeFunc(
-  sqlite3_context *context, 
-  int argc, 
+  sqlite3_context *context,
+  int argc,
   sqlite3_value **argv
 ){
   const unsigned char *zA, *zB;
@@ -115011,6 +118611,7 @@ static void likeFunc(
   int nPat;
   sqlite3 *db = sqlite3_context_db_handle(context);
   struct compareInfo *pInfo = sqlite3_user_data(context);
+  struct compareInfo backupInfo;
 
 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
@@ -115041,11 +118642,17 @@ static void likeFunc(
     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
     if( zEsc==0 ) return;
     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
-      sqlite3_result_error(context, 
+      sqlite3_result_error(context,
           "ESCAPE expression must be a single character", -1);
       return;
     }
     escape = sqlite3Utf8Read(&zEsc);
+    if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
+      memcpy(&backupInfo, pInfo, sizeof(backupInfo));
+      pInfo = &backupInfo;
+      if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
+      if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
+    }
   }else{
     escape = pInfo->matchSet;
   }
@@ -115148,8 +118755,8 @@ static void compileoptionusedFunc(
 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 
 /*
-** Implementation of the sqlite_compileoption_get() function. 
-** The result is a string that identifies the compiler options 
+** Implementation of the sqlite_compileoption_get() function.
+** The result is a string that identifies the compiler options
 ** used to build SQLite.
 */
 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
@@ -115173,7 +118780,7 @@ static void compileoptiongetFunc(
 ** digits. */
 static const char hexdigits[] = {
   '0', '1', '2', '3', '4', '5', '6', '7',
-  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
+  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
 };
 
 /*
@@ -115208,7 +118815,7 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
       char const *zBlob = sqlite3_value_blob(argv[0]);
       int nBlob = sqlite3_value_bytes(argv[0]);
       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
-      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
+      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
       if( zText ){
         int i;
         for(i=0; i<nBlob; i++){
@@ -115257,7 +118864,7 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
 
 /*
 ** The unicode() function.  Return the integer unicode code-point value
-** for the first character of the input string. 
+** for the first character of the input string.
 */
 static void unicodeFunc(
   sqlite3_context *context,
@@ -115413,7 +119020,7 @@ static void replaceFunc(
   if( zOut==0 ){
     return;
   }
-  loopLimit = nStr - nPattern;  
+  loopLimit = nStr - nPattern;
   cntExpand = 0;
   for(i=j=0; i<=loopLimit; i++){
     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
@@ -115569,7 +119176,7 @@ static void unknownFunc(
 ** Compute the soundex encoding of a word.
 **
 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
-** soundex encoding of the string X. 
+** soundex encoding of the string X.
 */
 static void soundexFunc(
   sqlite3_context *context,
@@ -115658,7 +119265,7 @@ static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
 typedef struct SumCtx SumCtx;
 struct SumCtx {
   double rSum;      /* Floating point sum */
-  i64 iSum;         /* Integer sum */   
+  i64 iSum;         /* Integer sum */
   i64 cnt;          /* Number of elements summed */
   u8 overflow;      /* True if integer overflow seen */
   u8 approx;        /* True if non-integer value was input to the sum */
@@ -115772,13 +119379,13 @@ static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
 
 #ifndef SQLITE_OMIT_DEPRECATED
   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
-  ** sure it still operates correctly, verify that its count agrees with our 
+  ** sure it still operates correctly, verify that its count agrees with our
   ** internal count when using count(*) and when the total count can be
   ** expressed as a 32-bit integer. */
   assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
           || p->n==sqlite3_aggregate_count(context) );
 #endif
-}   
+}
 static void countFinalize(sqlite3_context *context){
   CountCtx *p;
   p = sqlite3_aggregate_context(context, 0);
@@ -115795,7 +119402,7 @@ static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
     p->bInverse = 1;
 #endif
   }
-}   
+}
 #else
 # define countInverse 0
 #endif /* SQLITE_OMIT_WINDOWFUNC */
@@ -115804,8 +119411,8 @@ static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
 ** Routines to implement min() and max() aggregate functions.
 */
 static void minmaxStep(
-  sqlite3_context *context, 
-  int NotUsed, 
+  sqlite3_context *context,
+  int NotUsed,
   sqlite3_value **argv
 ){
   Mem *pArg  = (Mem *)argv[0];
@@ -115937,8 +119544,8 @@ static void groupConcatFinalize(sqlite3_context *context){
       sqlite3_result_error_toobig(context);
     }else if( pAccum->accError==SQLITE_NOMEM ){
       sqlite3_result_error_nomem(context);
-    }else{    
-      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
+    }else{
+      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
                           sqlite3_free);
     }
   }
@@ -115952,7 +119559,7 @@ static void groupConcatValue(sqlite3_context *context){
       sqlite3_result_error_toobig(context);
     }else if( pAccum->accError==SQLITE_NOMEM ){
       sqlite3_result_error_nomem(context);
-    }else{    
+    }else{
       const char *zText = sqlite3_str_value(pAccum);
       sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
     }
@@ -116000,7 +119607,7 @@ SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive)
 ** pExpr points to an expression which implements a function.  If
 ** it is appropriate to apply the LIKE optimization to that function
 ** then set aWc[0] through aWc[2] to the wildcard characters and the
-** escape character and then return TRUE.  If the function is not a 
+** escape character and then return TRUE.  If the function is not a
 ** LIKE-style function then return FALSE.
 **
 ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
@@ -116022,9 +119629,22 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas
   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
   nExpr = pExpr->x.pList->nExpr;
   pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
+#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
+  if( pDef==0 ) return 0;
+#endif
   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
     return 0;
   }
+
+  /* The memcpy() statement assumes that the wildcard characters are
+  ** the first three statements in the compareInfo structure.  The
+  ** asserts() that follow verify that assumption
+  */
+  memcpy(aWc, pDef->pUserData, 3);
+  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
+  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
+  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
+
   if( nExpr<3 ){
     aWc[3] = 0;
   }else{
@@ -116033,17 +119653,11 @@ SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocas
     if( pEscape->op!=TK_STRING ) return 0;
     zEscape = pEscape->u.zToken;
     if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
+    if( zEscape[0]==aWc[0] ) return 0;
+    if( zEscape[0]==aWc[1] ) return 0;
     aWc[3] = zEscape[0];
   }
 
-  /* The memcpy() statement assumes that the wildcard characters are
-  ** the first three statements in the compareInfo structure.  The
-  ** asserts() that follow verify that assumption
-  */
-  memcpy(aWc, pDef->pUserData, 3);
-  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
-  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
-  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
   return 1;
 }
@@ -116067,12 +119681,20 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
   ** For peak efficiency, put the most frequently used function last.
   */
   static FuncDef aBuiltinFunc[] = {
+/***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
+    TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
+    TEST_FUNC(expr_compare,        2, INLINEFUNC_expr_compare,        0),
+    TEST_FUNC(expr_implies_expr,   2, INLINEFUNC_expr_implies_expr,   0),
+#ifdef SQLITE_DEBUG
+    TEST_FUNC(affinity,          1, INLINEFUNC_affinity, 0),
+#endif
+/***** Regular functions *****/
 #ifdef SQLITE_SOUNDEX
     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
 #endif
 #ifndef SQLITE_OMIT_LOAD_EXTENSION
-    VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
-    VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
+    SFUNCTION(load_extension,    1, 0, 0, loadExt          ),
+    SFUNCTION(load_extension,    2, 0, 0, loadExt          ),
 #endif
 #if SQLITE_USER_AUTHENTICATION
     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
@@ -116081,12 +119703,9 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
     DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
-    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
-    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
-    FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
-#ifdef SQLITE_DEBUG
-    FUNCTION2(affinity,          1, 0, 0, noopFunc,  SQLITE_FUNC_AFFINITY),
-#endif
+    INLINE_FUNC(unlikely,        1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
+    INLINE_FUNC(likelihood,      2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
+    INLINE_FUNC(likely,          1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
     FUNCTION2(sqlite_offset,     1, 0, 0, noopFunc,  SQLITE_FUNC_OFFSET|
                                                      SQLITE_FUNC_TYPEOF),
@@ -116119,7 +119738,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     FUNCTION(upper,              1, 0, 0, upperFunc        ),
     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
     FUNCTION(hex,                1, 0, 0, hexFunc          ),
-    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
+    INLINE_FUNC(ifnull,          2, INLINEFUNC_coalesce, 0 ),
     VFUNCTION(random,            0, 0, 0, randomFunc       ),
     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
@@ -116134,18 +119753,20 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
     FUNCTION(substr,             2, 0, 0, substrFunc       ),
     FUNCTION(substr,             3, 0, 0, substrFunc       ),
+    FUNCTION(substring,          2, 0, 0, substrFunc       ),
+    FUNCTION(substring,          3, 0, 0, substrFunc       ),
     WAGGREGATE(sum,   1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
     WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
     WAGGREGATE(avg,   1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
-    WAGGREGATE(count, 0,0,0, countStep, 
+    WAGGREGATE(count, 0,0,0, countStep,
         countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT  ),
-    WAGGREGATE(count, 1,0,0, countStep, 
+    WAGGREGATE(count, 1,0,0, countStep,
         countFinalize, countFinalize, countInverse, 0  ),
-    WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep, 
+    WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
-    WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep, 
+    WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
         groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
-  
+
     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
 #ifdef SQLITE_CASE_SENSITIVE_LIKE
     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
@@ -116159,7 +119780,8 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 #endif
     FUNCTION(coalesce,           1, 0, 0, 0                ),
     FUNCTION(coalesce,           0, 0, 0, 0                ),
-    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
+    INLINE_FUNC(coalesce,       -1, INLINEFUNC_coalesce, 0 ),
+    INLINE_FUNC(iif,             3, INLINEFUNC_iif,      0 ),
   };
 #ifndef SQLITE_OMIT_ALTERTABLE
   sqlite3AlterFunctions();
@@ -116212,25 +119834,25 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
 ** If an immediate foreign key constraint is violated,
 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
-** statement transaction rolled back. If a 
-** deferred foreign key constraint is violated, no action is taken 
-** immediately. However if the application attempts to commit the 
+** statement transaction rolled back. If a
+** deferred foreign key constraint is violated, no action is taken
+** immediately. However if the application attempts to commit the
 ** transaction before fixing the constraint violation, the attempt fails.
 **
 ** Deferred constraints are implemented using a simple counter associated
-** with the database handle. The counter is set to zero each time a 
-** database transaction is opened. Each time a statement is executed 
+** with the database handle. The counter is set to zero each time a
+** database transaction is opened. Each time a statement is executed
 ** that causes a foreign key violation, the counter is incremented. Each
 ** time a statement is executed that removes an existing violation from
 ** the database, the counter is decremented. When the transaction is
 ** committed, the commit fails if the current value of the counter is
 ** greater than zero. This scheme has two big drawbacks:
 **
-**   * When a commit fails due to a deferred foreign key constraint, 
+**   * When a commit fails due to a deferred foreign key constraint,
 **     there is no way to tell which foreign constraint is not satisfied,
 **     or which row it is not satisfied for.
 **
-**   * If the database contains foreign key violations when the 
+**   * If the database contains foreign key violations when the
 **     transaction is opened, this may cause the mechanism to malfunction.
 **
 ** Despite these problems, this approach is adopted as it seems simpler
@@ -116242,26 +119864,26 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 **        the parent table for a match. If none is found increment the
 **        constraint counter.
 **
-**   I.2) For each FK for which the table is the parent table, 
+**   I.2) For each FK for which the table is the parent table,
 **        search the child table for rows that correspond to the new
 **        row in the parent table. Decrement the counter for each row
 **        found (as the constraint is now satisfied).
 **
 ** DELETE operations:
 **
-**   D.1) For each FK for which the table is the child table, 
-**        search the parent table for a row that corresponds to the 
-**        deleted row in the child table. If such a row is not found, 
+**   D.1) For each FK for which the table is the child table,
+**        search the parent table for a row that corresponds to the
+**        deleted row in the child table. If such a row is not found,
 **        decrement the counter.
 **
-**   D.2) For each FK for which the table is the parent table, search 
-**        the child table for rows that correspond to the deleted row 
+**   D.2) For each FK for which the table is the parent table, search
+**        the child table for rows that correspond to the deleted row
 **        in the parent table. For each found increment the counter.
 **
 ** UPDATE operations:
 **
 **   An UPDATE command requires that all 4 steps above are taken, but only
-**   for FK constraints for which the affected columns are actually 
+**   for FK constraints for which the affected columns are actually
 **   modified (values must be compared at runtime).
 **
 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
@@ -116270,10 +119892,10 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
 ** resolution is considered to delete rows before the new row is inserted.
 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
-** is thrown, even if the FK constraint would be satisfied after the new 
+** is thrown, even if the FK constraint would be satisfied after the new
 ** row is inserted.
 **
-** Immediate constraints are usually handled similarly. The only difference 
+** Immediate constraints are usually handled similarly. The only difference
 ** is that the counter used is stored as part of each individual statement
 ** object (struct Vdbe). If, after the statement has run, its immediate
 ** constraint counter is greater than zero,
@@ -116284,7 +119906,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 ** INSERT violates a foreign key constraint. This is necessary as such
 ** an INSERT does not open a statement transaction.
 **
-** TODO: How should dropping a table be handled? How should renaming a 
+** TODO: How should dropping a table be handled? How should renaming a
 ** table be handled?
 **
 **
@@ -116295,7 +119917,7 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 ** for those two operations needs to know whether or not the operation
 ** requires any FK processing and, if so, which columns of the original
 ** row are required by the FK processing VDBE code (i.e. if FKs were
-** implemented using triggers, which of the old.* columns would be 
+** implemented using triggers, which of the old.* columns would be
 ** accessed). No information is required by the code-generator before
 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
 ** generation code to query for this information are:
@@ -116332,13 +119954,13 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 /*
 ** A foreign key constraint requires that the key columns in the parent
 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
-** Given that pParent is the parent table for foreign key constraint pFKey, 
-** search the schema for a unique index on the parent key columns. 
+** Given that pParent is the parent table for foreign key constraint pFKey,
+** search the schema for a unique index on the parent key columns.
+**
+** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
+** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
+** is set to point to the unique index.
 **
-** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
-** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
-** is set to point to the unique index. 
-** 
 ** If the parent key consists of a single column (the foreign key constraint
 ** is not a composite foreign key), output variable *paiCol is set to NULL.
 ** Otherwise, it is set to point to an allocated array of size N, where
@@ -116361,8 +119983,8 @@ SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
 **      PRIMARY KEY, or
 **
 **   4) No parent key columns were provided explicitly as part of the
-**      foreign key definition, and the PRIMARY KEY of the parent table 
-**      consists of a different number of columns to the child key in 
+**      foreign key definition, and the PRIMARY KEY of the parent table
+**      consists of a different number of columns to the child key in
 **      the child table.
 **
 ** then non-zero is returned, and a "foreign key mismatch" error loaded
@@ -116386,9 +120008,9 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
   assert( !paiCol || *paiCol==0 );
   assert( pParse );
 
-  /* If this is a non-composite (single column) foreign key, check if it 
-  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
-  ** and *paiCol set to zero and return early. 
+  /* If this is a non-composite (single column) foreign key, check if it
+  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
+  ** and *paiCol set to zero and return early.
   **
   ** Otherwise, for a composite foreign key (more than one column), allocate
   ** space for the aiCol array (returned via output parameter *paiCol).
@@ -116397,7 +120019,7 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
   if( nCol==1 ){
     /* The FK maps to the IPK if any of the following are true:
     **
-    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
+    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
     **      mapped to the primary key of table pParent, or
     **   2) The FK is explicitly mapped to a column declared as INTEGER
     **      PRIMARY KEY.
@@ -116414,14 +120036,14 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
   }
 
   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
-    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){ 
+    if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
       ** of columns. If each indexed column corresponds to a foreign key
       ** column of pFKey, then this index is a winner.  */
 
       if( zKey==0 ){
-        /* If zKey is NULL, then this foreign key is implicitly mapped to 
-        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
+        /* If zKey is NULL, then this foreign key is implicitly mapped to
+        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
         ** identified by the test.  */
         if( IsPrimaryKeyIndex(pIdx) ){
           if( aiCol ){
@@ -116479,15 +120101,15 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
 }
 
 /*
-** This function is called when a row is inserted into or deleted from the 
-** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
+** This function is called when a row is inserted into or deleted from the
+** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
 ** on the child table of pFKey, this function is invoked twice for each row
 ** affected - once to "delete" the old row, and then again to "insert" the
 ** new row.
 **
 ** Each time it is called, this function generates VDBE code to locate the
-** row in the parent table that corresponds to the row being inserted into 
-** or deleted from the child table. If the parent row can be found, no 
+** row in the parent table that corresponds to the row being inserted into
+** or deleted from the child table. If the parent row can be found, no
 ** special action is taken. Otherwise, if the parent row can *not* be
 ** found in the parent table:
 **
@@ -116501,7 +120123,7 @@ SQLITE_PRIVATE int sqlite3FkLocateIndex(
 **
 **   DELETE      deferred    Decrement the "deferred constraint counter".
 **
-** These operations are identified in the comment at the top of this file 
+** These operations are identified in the comment at the top of this file
 ** (fkey.c) as "I.1" and "D.1".
 */
 static void fkLookupParent(
@@ -116523,22 +120145,22 @@ static void fkLookupParent(
   sqlite3VdbeVerifyAbortable(v,
     (!pFKey->isDeferred
       && !(pParse->db->flags & SQLITE_DeferFKs)
-      && !pParse->pToplevel 
+      && !pParse->pToplevel
       && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
 
   /* If nIncr is less than zero, then check at runtime if there are any
   ** outstanding constraints to resolve. If there are not, there is no need
   ** to check if deleting this row resolves any outstanding violations.
   **
-  ** Check if any of the key columns in the child table row are NULL. If 
-  ** any are, then the constraint is considered satisfied. No need to 
+  ** Check if any of the key columns in the child table row are NULL. If
+  ** any are, then the constraint is considered satisfied. No need to
   ** search for a matching row in the parent table.  */
   if( nIncr<0 ){
     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
     VdbeCoverage(v);
   }
   for(i=0; i<pFKey->nCol; i++){
-    int iReg = aiCol[i] + regData + 1;
+    int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
   }
 
@@ -116548,16 +120170,17 @@ static void fkLookupParent(
       ** column of the parent table (table pTab).  */
       int iMustBeInt;               /* Address of MustBeInt instruction */
       int regTemp = sqlite3GetTempReg(pParse);
-  
-      /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
+
+      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
       ** apply the affinity of the parent key). If this fails, then there
       ** is no matching parent key. Before using MustBeInt, make a copy of
       ** the value. Otherwise, the value inserted into the child key column
       ** will have INTEGER affinity applied to it, which may not be correct.  */
-      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
+      sqlite3VdbeAddOp2(v, OP_SCopy,
+        sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
       VdbeCoverage(v);
-  
+
       /* If the parent table is the same as the child table, and we are about
       ** to increment the constraint-counter (i.e. this is an INSERT operation),
       ** then check if the row being inserted matches itself. If so, do not
@@ -116566,7 +120189,7 @@ static void fkLookupParent(
         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
       }
-  
+
       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
       sqlite3VdbeGoto(v, iOk);
@@ -116577,19 +120200,21 @@ static void fkLookupParent(
       int nCol = pFKey->nCol;
       int regTemp = sqlite3GetTempRange(pParse, nCol);
       int regRec = sqlite3GetTempReg(pParse);
-  
+
       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
       for(i=0; i<nCol; i++){
-        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
+        sqlite3VdbeAddOp2(v, OP_Copy,
+               sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
+               regTemp+i);
       }
-  
+
       /* If the parent table is the same as the child table, and we are about
       ** to increment the constraint-counter (i.e. this is an INSERT operation),
       ** then check if the row being inserted matches itself. If so, do not
-      ** increment the constraint-counter. 
+      ** increment the constraint-counter.
       **
-      ** If any of the parent-key values are NULL, then the row cannot match 
+      ** If any of the parent-key values are NULL, then the row cannot match
       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
       ** of the parent-key values are NULL (at this point it is known that
       ** none of the child key values are).
@@ -116597,8 +120222,11 @@ static void fkLookupParent(
       if( pTab==pFKey->pFrom && nIncr==1 ){
         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
         for(i=0; i<nCol; i++){
-          int iChild = aiCol[i]+1+regData;
-          int iParent = pIdx->aiColumn[i]+1+regData;
+          int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
+                              +1+regData;
+          int iParent = 1+regData;
+          iParent += sqlite3TableColumnToStorage(pIdx->pTable,
+                                                 pIdx->aiColumn[i]);
           assert( pIdx->aiColumn[i]>=0 );
           assert( aiCol[i]!=pTab->iPKey );
           if( pIdx->aiColumn[i]==pTab->iPKey ){
@@ -116610,19 +120238,19 @@ static void fkLookupParent(
         }
         sqlite3VdbeGoto(v, iOk);
       }
-  
+
       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
                         sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
-  
+
       sqlite3ReleaseTempReg(pParse, regRec);
       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
     }
   }
 
   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
-   && !pParse->pToplevel 
-   && !pParse->isMultiWrite 
+   && !pParse->pToplevel
+   && !pParse->isMultiWrite
   ){
     /* Special case: If this is an INSERT statement that will insert exactly
     ** one row into the table, raise a constraint immediately instead of
@@ -116666,7 +120294,7 @@ static Expr *exprTableRegister(
   if( pExpr ){
     if( iCol>=0 && iCol!=pTab->iPKey ){
       pCol = &pTab->aCol[iCol];
-      pExpr->iTable = regBase + iCol + 1;
+      pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
       pExpr->affExpr = pCol->affinity;
       zColl = pCol->zColl;
       if( zColl==0 ) zColl = db->pDfltColl->zName;
@@ -116700,7 +120328,7 @@ static Expr *exprTableColumn(
 
 /*
 ** This function is called to generate code executed when a row is deleted
-** from the parent table of foreign key constraint pFKey and, if pFKey is 
+** from the parent table of foreign key constraint pFKey and, if pFKey is
 ** deferred, when a row is inserted into the same table. When generating
 ** code for an SQL UPDATE operation, this function may be called twice -
 ** once to "delete" the old row and once to "insert" the new row.
@@ -116727,7 +120355,7 @@ static Expr *exprTableColumn(
 **
 **   INSERT      deferred    Decrement the "deferred constraint counter".
 **
-** These operations are identified in the comment at the top of this file 
+** These operations are identified in the comment at the top of this file
 ** (fkey.c) as "I.2" and "D.2".
 */
 static void fkScanChildren(
@@ -116770,7 +120398,7 @@ static void fkScanChildren(
     Expr *pLeft;                  /* Value from parent table row */
     Expr *pRight;                 /* Column ref to child table */
     Expr *pEq;                    /* Expression (pLeft = pRight) */
-    i16 iCol;                     /* Index of column in child table */ 
+    i16 iCol;                     /* Index of column in child table */
     const char *zCol;             /* Name of column in child table */
 
     iCol = pIdx ? pIdx->aiColumn[i] : -1;
@@ -116792,7 +120420,7 @@ static void fkScanChildren(
   **
   ** The first form is used for rowid tables.  The second form is used
   ** for WITHOUT ROWID tables. In the second form, the *parent* key is
-  ** (a,b,...). Either the parent or primary key could be used to 
+  ** (a,b,...). Either the parent or primary key could be used to
   ** uniquely identify the current row, but the parent key is more convenient
   ** as the required values have already been loaded into registers
   ** by the caller.
@@ -116841,7 +120469,7 @@ static void fkScanChildren(
   /* Clean up the WHERE clause constructed above. */
   sqlite3ExprDelete(db, pWhere);
   if( iFkIfZero ){
-    sqlite3VdbeJumpHere(v, iFkIfZero);
+    sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);
   }
 }
 
@@ -116864,7 +120492,7 @@ SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
 }
 
 /*
-** The second argument is a Trigger structure allocated by the 
+** The second argument is a Trigger structure allocated by the
 ** fkActionTrigger() routine. This function deletes the Trigger structure
 ** and all of its sub-components.
 **
@@ -116892,7 +120520,7 @@ static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
 **
 **   (a) The table is the parent table of a FK constraint, or
 **   (b) The table is the child table of a deferred FK constraint and it is
-**       determined at runtime that there are outstanding deferred FK 
+**       determined at runtime that there are outstanding deferred FK
 **       constraint violations in the database,
 **
 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
@@ -116909,7 +120537,7 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa
     assert( pTab->pSelect==0 );   /* Not a view */
     if( sqlite3FkReferences(pTab)==0 ){
       /* Search for a deferred foreign key constraint for which this table
-      ** is the child table. If one cannot be found, return without 
+      ** is the child table. If one cannot be found, return without
       ** generating any VDBE code. If one can be found, then jump over
       ** the entire DELETE if there are no outstanding deferred constraints
       ** when this statement is run.  */
@@ -116926,10 +120554,10 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa
     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
     pParse->disableTriggers = 0;
 
-    /* If the DELETE has generated immediate foreign key constraint 
+    /* If the DELETE has generated immediate foreign key constraint
     ** violations, halt the VDBE and return an error at this point, before
     ** any modifications to the schema are made. This is because statement
-    ** transactions are not able to rollback schema changes.  
+    ** transactions are not able to rollback schema changes.
     **
     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
     ** the statement transaction will not be rolled back even if FK
@@ -116953,7 +120581,7 @@ SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTa
 /*
 ** The second argument points to an FKey object representing a foreign key
 ** for which pTab is the child table. An UPDATE statement against pTab
-** is currently being processed. For each column of the table that is 
+** is currently being processed. For each column of the table that is
 ** actually updated, the corresponding element in the aChange[] array
 ** is zero or greater (if a column is unmodified the corresponding element
 ** is set to -1). If the rowid column is modified by the UPDATE statement
@@ -116980,7 +120608,7 @@ static int fkChildIsModified(
 /*
 ** The second argument points to an FKey object representing a foreign key
 ** for which pTab is the parent table. An UPDATE statement against pTab
-** is currently being processed. For each column of the table that is 
+** is currently being processed. For each column of the table that is
 ** actually updated, the corresponding element in the aChange[] array
 ** is zero or greater (if a column is unmodified the corresponding element
 ** is set to -1). If the rowid column is modified by the UPDATE statement
@@ -116990,9 +120618,9 @@ static int fkChildIsModified(
 ** parent key for FK constraint *p are modified.
 */
 static int fkParentIsModified(
-  Table *pTab, 
-  FKey *p, 
-  int *aChange, 
+  Table *pTab,
+  FKey *p,
+  int *aChange,
   int bChngRowid
 ){
   int i;
@@ -117033,7 +120661,7 @@ static int isSetNullAction(Parse *pParse, FKey *pFKey){
 
 /*
 ** This function is called when inserting, deleting or updating a row of
-** table pTab to generate VDBE code to perform foreign key constraint 
+** table pTab to generate VDBE code to perform foreign key constraint
 ** processing for the operation.
 **
 ** For a DELETE operation, parameter regOld is passed the index of the
@@ -117049,11 +120677,11 @@ static int isSetNullAction(Parse *pParse, FKey *pFKey){
 ** For an UPDATE operation, this function is called twice. Once before
 ** the original record is deleted from the table using the calling convention
 ** described for DELETE. Then again after the original record is deleted
-** but before the new record is inserted using the INSERT convention. 
+** but before the new record is inserted using the INSERT convention.
 */
 SQLITE_PRIVATE void sqlite3FkCheck(
   Parse *pParse,                  /* Parse context */
-  Table *pTab,                    /* Row is being deleted from this table */ 
+  Table *pTab,                    /* Row is being deleted from this table */
   int regOld,                     /* Previous row data is stored here */
   int regNew,                     /* New row data is stored here */
   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
@@ -117085,16 +120713,16 @@ SQLITE_PRIVATE void sqlite3FkCheck(
     int i;
     int bIgnore = 0;
 
-    if( aChange 
+    if( aChange
      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
-     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
+     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
     ){
       continue;
     }
 
-    /* Find the parent table of this foreign key. Also find a unique index 
-    ** on the parent key columns in the parent table. If either of these 
-    ** schema items cannot be located, set an error in pParse and return 
+    /* Find the parent table of this foreign key. Also find a unique index
+    ** on the parent key columns in the parent table. If either of these
+    ** schema items cannot be located, set an error in pParse and return
     ** early.  */
     if( pParse->disableTriggers ){
       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
@@ -117115,7 +120743,9 @@ SQLITE_PRIVATE void sqlite3FkCheck(
         Vdbe *v = sqlite3GetVdbe(pParse);
         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
         for(i=0; i<pFKey->nCol; i++){
-          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
+          int iFromCol, iReg;
+          iFromCol = pFKey->aCol[i].iFrom;
+          iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
         }
         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
@@ -117136,7 +120766,7 @@ SQLITE_PRIVATE void sqlite3FkCheck(
       }
       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
 #ifndef SQLITE_OMIT_AUTHORIZATION
-      /* Request permission to read the parent key columns. If the 
+      /* Request permission to read the parent key columns. If the
       ** authorization callback returns SQLITE_IGNORE, behave as if any
       ** values read from the parent table are NULL. */
       if( db->xAuth ){
@@ -117148,24 +120778,24 @@ SQLITE_PRIVATE void sqlite3FkCheck(
 #endif
     }
 
-    /* Take a shared-cache advisory read-lock on the parent table. Allocate 
-    ** a cursor to use to search the unique index on the parent key columns 
+    /* Take a shared-cache advisory read-lock on the parent table. Allocate
+    ** a cursor to use to search the unique index on the parent key columns
     ** in the parent table.  */
     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
     pParse->nTab++;
 
     if( regOld!=0 ){
       /* A row is being removed from the child table. Search for the parent.
-      ** If the parent does not exist, removing the child row resolves an 
+      ** If the parent does not exist, removing the child row resolves an
       ** outstanding foreign key constraint violation. */
       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
     }
     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
       /* A row is being added to the child table. If a parent row cannot
-      ** be found, adding the child row has violated the FK constraint. 
+      ** be found, adding the child row has violated the FK constraint.
       **
       ** If this operation is being performed as part of a trigger program
-      ** that is actually a "SET NULL" action belonging to this very 
+      ** that is actually a "SET NULL" action belonging to this very
       ** foreign key, then omit this scan altogether. As all child key
       ** values are guaranteed to be NULL, it is not possible for adding
       ** this row to cause an FK violation.  */
@@ -117186,8 +120816,8 @@ SQLITE_PRIVATE void sqlite3FkCheck(
       continue;
     }
 
-    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
-     && !pParse->pToplevel && !pParse->isMultiWrite 
+    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
+     && !pParse->pToplevel && !pParse->isMultiWrite
     ){
       assert( regOld==0 && regNew!=0 );
       /* Inserting a single row into a parent table cannot cause (or fix)
@@ -117210,7 +120840,7 @@ SQLITE_PRIVATE void sqlite3FkCheck(
       pItem->zName = pFKey->pFrom->zName;
       pItem->pTab->nTabRef++;
       pItem->iCursor = pParse->nTab++;
-  
+
       if( regNew!=0 ){
         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
       }
@@ -117229,10 +120859,10 @@ SQLITE_PRIVATE void sqlite3FkCheck(
         **
         ** Note 2: At first glance it may seem like SQLite could simply omit
         ** all OP_FkCounter related scans when either CASCADE or SET NULL
-        ** applies. The trouble starts if the CASCADE or SET NULL action 
-        ** trigger causes other triggers or action rules attached to the 
+        ** applies. The trouble starts if the CASCADE or SET NULL action
+        ** trigger causes other triggers or action rules attached to the
         ** child table to fire. In these cases the fk constraint counters
-        ** might be set incorrectly if any OP_FkCounter related scans are 
+        ** might be set incorrectly if any OP_FkCounter related scans are
         ** omitted.  */
         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
           sqlite3MayAbort(pParse);
@@ -117248,7 +120878,7 @@ SQLITE_PRIVATE void sqlite3FkCheck(
 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
 
 /*
-** This function is called before generating code to update or delete a 
+** This function is called before generating code to update or delete a
 ** row contained in table pTab.
 */
 SQLITE_PRIVATE u32 sqlite3FkOldmask(
@@ -117278,17 +120908,17 @@ SQLITE_PRIVATE u32 sqlite3FkOldmask(
 
 
 /*
-** This function is called before generating code to update or delete a 
+** This function is called before generating code to update or delete a
 ** row contained in table pTab. If the operation is a DELETE, then
 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
 ** to an array of size N, where N is the number of columns in table pTab.
-** If the i'th column is not modified by the UPDATE, then the corresponding 
+** If the i'th column is not modified by the UPDATE, then the corresponding
 ** entry in the aChange[] array is set to -1. If the column is modified,
 ** the value is 0 or greater. Parameter chngRowid is set to true if the
 ** UPDATE statement modifies the rowid fields of the table.
 **
 ** If any foreign key processing will be required, this function returns
-** non-zero. If there is no foreign key related processing, this function 
+** non-zero. If there is no foreign key related processing, this function
 ** returns zero.
 **
 ** For an UPDATE, this function returns 2 if:
@@ -117308,8 +120938,8 @@ SQLITE_PRIVATE int sqlite3FkRequired(
   int eRet = 0;
   if( pParse->db->flags&SQLITE_ForeignKeys ){
     if( !aChange ){
-      /* A DELETE operation. Foreign key processing is required if the 
-      ** table in question is either the child or parent table for any 
+      /* A DELETE operation. Foreign key processing is required if the
+      ** table in question is either the child or parent table for any
       ** foreign key constraint.  */
       eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
     }else{
@@ -117338,7 +120968,7 @@ SQLITE_PRIVATE int sqlite3FkRequired(
 }
 
 /*
-** This function is called when an UPDATE or DELETE operation is being 
+** This function is called when an UPDATE or DELETE operation is being
 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
 ** If the current operation is an UPDATE, then the pChanges parameter is
 ** passed a pointer to the list of columns being modified. If it is a
@@ -117350,7 +120980,7 @@ SQLITE_PRIVATE int sqlite3FkRequired(
 ** returned (these actions require no special handling by the triggers
 ** sub-system, code for them is created by fkScanChildren()).
 **
-** For example, if pFKey is the foreign key and pTab is table "p" in 
+** For example, if pFKey is the foreign key and pTab is table "p" in
 ** the following schema:
 **
 **   CREATE TABLE p(pk PRIMARY KEY);
@@ -117363,7 +120993,7 @@ SQLITE_PRIVATE int sqlite3FkRequired(
 **   END;
 **
 ** The returned pointer is cached as part of the foreign key object. It
-** is eventually freed along with the rest of the foreign key object by 
+** is eventually freed along with the rest of the foreign key object by
 ** sqlite3FkDelete().
 */
 static Trigger *fkActionTrigger(
@@ -117419,7 +121049,7 @@ static Trigger *fkActionTrigger(
       ** that the affinity and collation sequence associated with the
       ** parent table are used for the comparison. */
       pEq = sqlite3PExpr(pParse, TK_EQ,
-          sqlite3PExpr(pParse, TK_DOT, 
+          sqlite3PExpr(pParse, TK_DOT,
             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
@@ -117433,24 +121063,32 @@ static Trigger *fkActionTrigger(
       */
       if( pChanges ){
         pEq = sqlite3PExpr(pParse, TK_IS,
-            sqlite3PExpr(pParse, TK_DOT, 
+            sqlite3PExpr(pParse, TK_DOT,
               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
-            sqlite3PExpr(pParse, TK_DOT, 
+            sqlite3PExpr(pParse, TK_DOT,
               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
             );
         pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
       }
-  
+
       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
         Expr *pNew;
         if( action==OE_Cascade ){
-          pNew = sqlite3PExpr(pParse, TK_DOT, 
+          pNew = sqlite3PExpr(pParse, TK_DOT,
             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
         }else if( action==OE_SetDflt ){
-          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
+          Column *pCol = pFKey->pFrom->aCol + iFromCol;
+          Expr *pDflt;
+          if( pCol->colFlags & COLFLAG_GENERATED ){
+            testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+            testcase( pCol->colFlags & COLFLAG_STORED );
+            pDflt = 0;
+          }else{
+            pDflt = pCol->pDflt;
+          }
           if( pDflt ){
             pNew = sqlite3ExprDup(db, pDflt, 0);
           }else{
@@ -117470,7 +121108,7 @@ static Trigger *fkActionTrigger(
 
     if( action==OE_Restrict ){
       Token tFrom;
-      Expr *pRaise; 
+      Expr *pRaise;
 
       tFrom.z = zFrom;
       tFrom.n = nFrom;
@@ -117478,7 +121116,7 @@ static Trigger *fkActionTrigger(
       if( pRaise ){
         pRaise->affExpr = OE_Abort;
       }
-      pSelect = sqlite3SelectNew(pParse, 
+      pSelect = sqlite3SelectNew(pParse,
           sqlite3ExprListAppend(pParse, 0, pRaise),
           sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
           pWhere,
@@ -117488,9 +121126,9 @@ static Trigger *fkActionTrigger(
     }
 
     /* Disable lookaside memory allocation */
-    db->lookaside.bDisable++;
+    DisableLookaside;
 
-    pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
+    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
         sizeof(Trigger) +         /* struct Trigger */
         sizeof(TriggerStep) +     /* Single step in trigger program */
         nFrom + 1                 /* Space for pStep->zTarget */
@@ -117499,7 +121137,7 @@ static Trigger *fkActionTrigger(
       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
       pStep->zTarget = (char *)&pStep[1];
       memcpy((char *)pStep->zTarget, zFrom, nFrom);
-  
+
       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
@@ -117510,7 +121148,7 @@ static Trigger *fkActionTrigger(
     }
 
     /* Re-enable the lookaside buffer, if it was disabled earlier. */
-    db->lookaside.bDisable--;
+    EnableLookaside;
 
     sqlite3ExprDelete(db, pWhere);
     sqlite3ExprDelete(db, pWhen);
@@ -117525,13 +121163,14 @@ static Trigger *fkActionTrigger(
 
     switch( action ){
       case OE_Restrict:
-        pStep->op = TK_SELECT; 
+        pStep->op = TK_SELECT;
         break;
-      case OE_Cascade: 
-        if( !pChanges ){ 
-          pStep->op = TK_DELETE; 
-          break; 
+      case OE_Cascade:
+        if( !pChanges ){
+          pStep->op = TK_DELETE;
+          break;
         }
+        /* no break */ deliberate_fall_through
       default:
         pStep->op = TK_UPDATE;
     }
@@ -117557,9 +121196,9 @@ SQLITE_PRIVATE void sqlite3FkActions(
   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
   int bChngRowid                  /* True if rowid is UPDATEd */
 ){
-  /* If foreign-key support is enabled, iterate through all FKs that 
-  ** refer to table pTab. If there is an action associated with the FK 
-  ** for this operation (either update or delete), invoke the associated 
+  /* If foreign-key support is enabled, iterate through all FKs that
+  ** refer to table pTab. If there is an action associated with the FK
+  ** for this operation (either update or delete), invoke the associated
   ** trigger sub-program.  */
   if( pParse->db->flags&SQLITE_ForeignKeys ){
     FKey *pFKey;                  /* Iterator variable */
@@ -117639,7 +121278,7 @@ SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
 /* #include "sqliteInt.h" */
 
 /*
-** Generate code that will 
+** Generate code that will
 **
 **   (1) acquire a lock for table pTab then
 **   (2) open pTab as cursor iCur.
@@ -117656,12 +121295,13 @@ SQLITE_PRIVATE void sqlite3OpenTable(
 ){
   Vdbe *v;
   assert( !IsVirtual(pTab) );
-  v = sqlite3GetVdbe(pParse);
+  assert( pParse->pVdbe!=0 );
+  v = pParse->pVdbe;
   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
-  sqlite3TableLock(pParse, iDb, pTab->tnum, 
+  sqlite3TableLock(pParse, iDb, pTab->tnum,
                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
   if( HasRowid(pTab) ){
-    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
+    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
     VdbeComment((v, "%s", pTab->zName));
   }else{
     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
@@ -117675,7 +121315,7 @@ SQLITE_PRIVATE void sqlite3OpenTable(
 
 /*
 ** Return a pointer to the column affinity string associated with index
-** pIdx. A column affinity string has one character for each column in 
+** pIdx. A column affinity string has one character for each column in
 ** the table, according to the affinity of the column:
 **
 **  Character      Column affinity
@@ -117728,7 +121368,7 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
     }
     pIdx->zColAff[n] = 0;
   }
+
   return pIdx->zColAff;
 }
 
@@ -117753,7 +121393,7 @@ SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
 **  'E'            REAL
 */
 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
-  int i;
+  int i, j;
   char *zColAff = pTab->zColAff;
   if( zColAff==0 ){
     sqlite3 *db = sqlite3VdbeDb(v);
@@ -117763,13 +121403,15 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
       return;
     }
 
-    for(i=0; i<pTab->nCol; i++){
+    for(i=j=0; i<pTab->nCol; i++){
       assert( pTab->aCol[i].affinity!=0 );
-      zColAff[i] = pTab->aCol[i].affinity;
+      if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
+        zColAff[j++] = pTab->aCol[i].affinity;
+      }
     }
     do{
-      zColAff[i--] = 0;
-    }while( i>=0 && zColAff[i]<=SQLITE_AFF_BLOB );
+      zColAff[j--] = 0;
+    }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
     pTab->zColAff = zColAff;
   }
   assert( zColAff!=0 );
@@ -117785,9 +121427,9 @@ SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
 
 /*
 ** Return non-zero if the table pTab in database iDb or any of its indices
-** have been opened at any point in the VDBE program. This is used to see if 
-** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
-** run without using a temporary table for the results of the SELECT. 
+** have been opened at any point in the VDBE program. This is used to see if
+** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
+** run without using a temporary table for the results of the SELECT.
 */
 static int readsTable(Parse *p, int iDb, Table *pTab){
   Vdbe *v = sqlite3GetVdbe(p);
@@ -117802,7 +121444,7 @@ static int readsTable(Parse *p, int iDb, Table *pTab){
     assert( pOp!=0 );
     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
       Index *pIndex;
-      int tnum = pOp->p2;
+      Pgno tnum = pOp->p2;
       if( tnum==pTab->tnum ){
         return 1;
       }
@@ -117823,6 +121465,119 @@ static int readsTable(Parse *p, int iDb, Table *pTab){
   return 0;
 }
 
+/* This walker callback will compute the union of colFlags flags for all
+** referenced columns in a CHECK constraint or generated column expression.
+*/
+static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
+  if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
+    assert( pExpr->iColumn < pWalker->u.pTab->nCol );
+    pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
+  }
+  return WRC_Continue;
+}
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/*
+** All regular columns for table pTab have been puts into registers
+** starting with iRegStore.  The registers that correspond to STORED
+** or VIRTUAL columns have not yet been initialized.  This routine goes
+** back and computes the values for those columns based on the previously
+** computed normal columns.
+*/
+SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
+  Parse *pParse,    /* Parsing context */
+  int iRegStore,    /* Register holding the first column */
+  Table *pTab       /* The table */
+){
+  int i;
+  Walker w;
+  Column *pRedo;
+  int eProgress;
+  VdbeOp *pOp;
+
+  assert( pTab->tabFlags & TF_HasGenerated );
+  testcase( pTab->tabFlags & TF_HasVirtual );
+  testcase( pTab->tabFlags & TF_HasStored );
+
+  /* Before computing generated columns, first go through and make sure
+  ** that appropriate affinity has been applied to the regular columns
+  */
+  sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
+  if( (pTab->tabFlags & TF_HasStored)!=0
+   && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity
+  ){
+    /* Change the OP_Affinity argument to '@' (NONE) for all stored
+    ** columns.  '@' is the no-op affinity and those columns have not
+    ** yet been computed. */
+    int ii, jj;
+    char *zP4 = pOp->p4.z;
+    assert( zP4!=0 );
+    assert( pOp->p4type==P4_DYNAMIC );
+    for(ii=jj=0; zP4[jj]; ii++){
+      if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
+        continue;
+      }
+      if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
+        zP4[jj] = SQLITE_AFF_NONE;
+      }
+      jj++;
+    }
+  }
+
+  /* Because there can be multiple generated columns that refer to one another,
+  ** this is a two-pass algorithm.  On the first pass, mark all generated
+  ** columns as "not available".
+  */
+  for(i=0; i<pTab->nCol; i++){
+    if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+      testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
+      testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
+      pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
+    }
+  }
+
+  w.u.pTab = pTab;
+  w.xExprCallback = exprColumnFlagUnion;
+  w.xSelectCallback = 0;
+  w.xSelectCallback2 = 0;
+
+  /* On the second pass, compute the value of each NOT-AVAILABLE column.
+  ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
+  ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
+  ** they are needed.
+  */
+  pParse->iSelfTab = -iRegStore;
+  do{
+    eProgress = 0;
+    pRedo = 0;
+    for(i=0; i<pTab->nCol; i++){
+      Column *pCol = pTab->aCol + i;
+      if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
+        int x;
+        pCol->colFlags |= COLFLAG_BUSY;
+        w.eCode = 0;
+        sqlite3WalkExpr(&w, pCol->pDflt);
+        pCol->colFlags &= ~COLFLAG_BUSY;
+        if( w.eCode & COLFLAG_NOTAVAIL ){
+          pRedo = pCol;
+          continue;
+        }
+        eProgress = 1;
+        assert( pCol->colFlags & COLFLAG_GENERATED );
+        x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
+        sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);
+        pCol->colFlags &= ~COLFLAG_NOTAVAIL;
+      }
+    }
+  }while( pRedo && eProgress );
+  if( pRedo ){
+    sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName);
+  }
+  pParse->iSelfTab = 0;
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
+
 #ifndef SQLITE_OMIT_AUTOINCREMENT
 /*
 ** Locate or create an AutoincInfo structure associated with table pTab
@@ -117894,7 +121649,7 @@ static int autoIncBegin(
 
 /*
 ** This routine generates code that will initialize all of the
-** register used by the autoincrement tracker.  
+** register used by the autoincrement tracker.
 */
 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
@@ -117923,7 +121678,7 @@ SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
       /* 8  */ {OP_Goto,    0, 11, 0},
       /* 9  */ {OP_Next,    0,  2, 0},
       /* 10 */ {OP_Integer, 0,  0, 0},
-      /* 11 */ {OP_Close,   0,  0, 0} 
+      /* 11 */ {OP_Close,   0,  0, 0}
     };
     VdbeOp *aOp;
     pDb = &db->aDb[p->iDb];
@@ -118130,7 +121885,7 @@ SQLITE_PRIVATE void sqlite3Insert(
   Parse *pParse,        /* Parser context */
   SrcList *pTabList,    /* Name of table into which we are inserting */
   Select *pSelect,      /* A SELECT statement to use as the data source */
-  IdList *pColumn,      /* Column names corresponding to IDLIST. */
+  IdList *pColumn,      /* Column names corresponding to IDLIST, or NULL. */
   int onError,          /* How to handle constraint errors */
   Upsert *pUpsert       /* ON CONFLICT clauses for upsert, or NULL */
 ){
@@ -118155,6 +121910,7 @@ SQLITE_PRIVATE void sqlite3Insert(
   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
   u8 bIdListInOrder;    /* True if IDLIST is in table order */
   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
+  int iRegStore;        /* Register in which to store next column */
 
   /* Register allocations */
   int regFromSelect = 0;/* Base register for data coming from SELECT */
@@ -118262,8 +122018,8 @@ SQLITE_PRIVATE void sqlite3Insert(
   */
   regAutoinc = autoIncBegin(pParse, iDb, pTab);
 
-  /* Allocate registers for holding the rowid of the new row,
-  ** the content of the new row, and the assembled row record.
+  /* Allocate a block registers to hold the rowid and the values
+  ** for all columns of the new row.
   */
   regRowid = regIns = pParse->nMem+1;
   pParse->nMem += pTab->nCol + 1;
@@ -118274,7 +122030,7 @@ SQLITE_PRIVATE void sqlite3Insert(
   regData = regRowid+1;
 
   /* If the INSERT statement included an IDLIST term, then make sure
-  ** all elements of the IDLIST really are columns of the table and 
+  ** all elements of the IDLIST really are columns of the table and
   ** remember the column indices.
   **
   ** If the table has an INTEGER PRIMARY KEY column and that column
@@ -118282,9 +122038,17 @@ SQLITE_PRIVATE void sqlite3Insert(
   ** the index into IDLIST of the primary key column.  ipkColumn is
   ** the index of the primary key as it appears in IDLIST, not as
   ** is appears in the original table.  (The index of the INTEGER
-  ** PRIMARY KEY in the original table is pTab->iPKey.)
+  ** PRIMARY KEY in the original table is pTab->iPKey.)  After this
+  ** loop, if ipkColumn==(-1), that means that integer primary key
+  ** is unspecified, and hence the table is either WITHOUT ROWID or
+  ** it will automatically generated an integer primary key.
+  **
+  ** bIdListInOrder is true if the columns in IDLIST are in storage
+  ** order.  This enables an optimization that avoids shuffling the
+  ** columns into storage order.  False negatives are harmless,
+  ** but false positives will cause database corruption.
   */
-  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
+  bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
   if( pColumn ){
     for(i=0; i<pColumn->nId; i++){
       pColumn->a[i].idx = -1;
@@ -118297,6 +122061,14 @@ SQLITE_PRIVATE void sqlite3Insert(
           if( j==pTab->iPKey ){
             ipkColumn = i;  assert( !withoutRowid );
           }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+          if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
+            sqlite3ErrorMsg(pParse,
+               "cannot INSERT into generated column \"%s\"",
+               pTab->aCol[j].zName);
+            goto insert_cleanup;
+          }
+#endif
           break;
         }
       }
@@ -118346,7 +122118,7 @@ SQLITE_PRIVATE void sqlite3Insert(
     ** the destination table (template 3).
     **
     ** A temp table must be used if the table being updated is also one
-    ** of the tables being read by the SELECT statement.  Also use a 
+    ** of the tables being read by the SELECT statement.  Also use a
     ** temp table in the case of row triggers.
     */
     if( pTrigger || readsTable(pParse, iDb, pTab) ){
@@ -118382,7 +122154,7 @@ SQLITE_PRIVATE void sqlite3Insert(
       sqlite3ReleaseTempReg(pParse, regTempRowid);
     }
   }else{
-    /* This is the case if the data for the INSERT is coming from a 
+    /* This is the case if the data for the INSERT is coming from a
     ** single-row VALUES clause
     */
     NameContext sNC;
@@ -118401,21 +122173,34 @@ SQLITE_PRIVATE void sqlite3Insert(
   }
 
   /* If there is no IDLIST term but the table has an integer primary
-  ** key, the set the ipkColumn variable to the integer primary key 
+  ** key, the set the ipkColumn variable to the integer primary key
   ** column index in the original table definition.
   */
   if( pColumn==0 && nColumn>0 ){
     ipkColumn = pTab->iPKey;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
+      testcase( pTab->tabFlags & TF_HasVirtual );
+      testcase( pTab->tabFlags & TF_HasStored );
+      for(i=ipkColumn-1; i>=0; i--){
+        if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+          testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
+          testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
+          ipkColumn--;
+        }
+      }
+    }
+#endif
   }
 
   /* Make sure the number of columns in the source data matches the number
   ** of columns to be inserted into the table.
   */
   for(i=0; i<pTab->nCol; i++){
-    nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
+    if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
   }
   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
-    sqlite3ErrorMsg(pParse, 
+    sqlite3ErrorMsg(pParse,
        "table %S has %d columns but %d values were supplied",
        pTabList, 0, pTab->nCol-nHidden, nColumn);
     goto insert_cleanup;
@@ -118424,7 +122209,7 @@ SQLITE_PRIVATE void sqlite3Insert(
     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
     goto insert_cleanup;
   }
-    
+
   /* Initialize the count of rows to be inserted
   */
   if( (db->flags & SQLITE_CountRows)!=0
@@ -118458,6 +122243,10 @@ SQLITE_PRIVATE void sqlite3Insert(
               pTab->zName);
       goto insert_cleanup;
     }
+    if( pTab->pSelect ){
+      sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
+      goto insert_cleanup;
+    }
     if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
       goto insert_cleanup;
     }
@@ -118495,10 +122284,91 @@ SQLITE_PRIVATE void sqlite3Insert(
     **         goto C
     **      D: ...
     */
+    sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
     VdbeCoverage(v);
+    if( ipkColumn>=0 ){
+      /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
+      ** SELECT, go ahead and copy the value into the rowid slot now, so that
+      ** the value does not get overwritten by a NULL at tag-20191021-002. */
+      sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
+    }
+  }
+
+  /* Compute data for ordinary columns of the new entry.  Values
+  ** are written in storage order into registers starting with regData.
+  ** Only ordinary columns are computed in this loop. The rowid
+  ** (if there is one) is computed later and generated columns are
+  ** computed after the rowid since they might depend on the value
+  ** of the rowid.
+  */
+  nHidden = 0;
+  iRegStore = regData;  assert( regData==regRowid+1 );
+  for(i=0; i<pTab->nCol; i++, iRegStore++){
+    int k;
+    u32 colFlags;
+    assert( i>=nHidden );
+    if( i==pTab->iPKey ){
+      /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
+      ** using the rowid. So put a NULL in the IPK slot of the record to avoid
+      ** using excess space.  The file format definition requires this extra
+      ** NULL - we cannot optimize further by skipping the column completely */
+      sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
+      continue;
+    }
+    if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
+      nHidden++;
+      if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
+        /* Virtual columns do not participate in OP_MakeRecord.  So back up
+        ** iRegStore by one slot to compensate for the iRegStore++ in the
+        ** outer for() loop */
+        iRegStore--;
+        continue;
+      }else if( (colFlags & COLFLAG_STORED)!=0 ){
+        /* Stored columns are computed later.  But if there are BEFORE
+        ** triggers, the slots used for stored columns will be OP_Copy-ed
+        ** to a second block of registers, so the register needs to be
+        ** initialized to NULL to avoid an uninitialized register read */
+        if( tmask & TRIGGER_BEFORE ){
+          sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
+        }
+        continue;
+      }else if( pColumn==0 ){
+        /* Hidden columns that are not explicitly named in the INSERT
+        ** get there default value */
+        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+        continue;
+      }
+    }
+    if( pColumn ){
+      for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}
+      if( j>=pColumn->nId ){
+        /* A column not named in the insert column list gets its
+        ** default value */
+        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+        continue;
+      }
+      k = j;
+    }else if( nColumn==0 ){
+      /* This is INSERT INTO ... DEFAULT VALUES.  Load the default value. */
+      sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
+      continue;
+    }else{
+      k = i - nHidden;
+    }
+
+    if( useTempTable ){
+      sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
+    }else if( pSelect ){
+      if( regFromSelect!=regData ){
+        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
+      }
+    }else{
+      sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);
+    }
   }
 
+
   /* Run the BEFORE and INSTEAD OF triggers, if there are any
   */
   endOfLoop = sqlite3VdbeMakeLabel(pParse);
@@ -118533,25 +122403,21 @@ SQLITE_PRIVATE void sqlite3Insert(
     */
     assert( !IsVirtual(pTab) );
 
-    /* Create the new column data
-    */
-    for(i=j=0; i<pTab->nCol; i++){
-      if( pColumn ){
-        for(j=0; j<pColumn->nId; j++){
-          if( pColumn->a[j].idx==i ) break;
-        }
-      }
-      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
-            || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
-        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
-      }else if( useTempTable ){
-        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
-      }else{
-        assert( pSelect==0 ); /* Otherwise useTempTable is true */
-        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
-      }
-      if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
+    /* Copy the new data already generated. */
+    assert( pTab->nNVCol>0 );
+    sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
+
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    /* Compute the new value for generated columns after all other
+    ** columns have already been computed.  This must be done after
+    ** computing the ROWID in case one of the generated columns
+    ** refers to the ROWID. */
+    if( pTab->tabFlags & TF_HasGenerated ){
+      testcase( pTab->tabFlags & TF_HasVirtual );
+      testcase( pTab->tabFlags & TF_HasStored );
+      sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
     }
+#endif
 
     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
     ** do not attempt any conversions before assembling the record.
@@ -118563,25 +122429,23 @@ SQLITE_PRIVATE void sqlite3Insert(
     }
 
     /* Fire BEFORE or INSTEAD OF triggers */
-    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
+    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
 
     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
   }
 
-  /* Compute the content of the next row to insert into a range of
-  ** registers beginning at regIns.
-  */
   if( !isView ){
     if( IsVirtual(pTab) ){
       /* The row that the VUpdate opcode will delete: none */
       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
     }
     if( ipkColumn>=0 ){
+      /* Compute the new rowid */
       if( useTempTable ){
         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
       }else if( pSelect ){
-        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
+        /* Rowid already initialized at tag-20191021-001 */
       }else{
         Expr *pIpk = pList->a[ipkColumn].pExpr;
         if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
@@ -118614,45 +122478,15 @@ SQLITE_PRIVATE void sqlite3Insert(
     }
     autoIncStep(pParse, regAutoinc, regRowid);
 
-    /* Compute data for all columns of the new entry, beginning
-    ** with the first column.
-    */
-    nHidden = 0;
-    for(i=0; i<pTab->nCol; i++){
-      int iRegStore = regRowid+1+i;
-      if( i==pTab->iPKey ){
-        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
-        ** Whenever this column is read, the rowid will be substituted
-        ** in its place.  Hence, fill this column with a NULL to avoid
-        ** taking up data space with information that will never be used.
-        ** As there may be shallow copies of this value, make it a soft-NULL */
-        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
-        continue;
-      }
-      if( pColumn==0 ){
-        if( IsHiddenColumn(&pTab->aCol[i]) ){
-          j = -1;
-          nHidden++;
-        }else{
-          j = i - nHidden;
-        }
-      }else{
-        for(j=0; j<pColumn->nId; j++){
-          if( pColumn->a[j].idx==i ) break;
-        }
-      }
-      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
-        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
-      }else if( useTempTable ){
-        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
-      }else if( pSelect ){
-        if( regFromSelect!=regData ){
-          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
-        }
-      }else{
-        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
-      }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    /* Compute the new value for generated columns after all other
+    ** columns have already been computed.  This must be done after
+    ** computing the ROWID in case one of the generated columns
+    ** is derived from the INTEGER PRIMARY KEY. */
+    if( pTab->tabFlags & TF_HasGenerated ){
+      sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
     }
+#endif
 
     /* Generate code to check constraints and generate index keys and
     ** do the insertion.
@@ -118678,13 +122512,11 @@ SQLITE_PRIVATE void sqlite3Insert(
       ** constraints or (b) there are no triggers and this table is not a
       ** parent table in a foreign key constraint. It is safe to set the
       ** flag in the second case as if any REPLACE constraint is hit, an
-      ** OP_Delete or OP_IdxDelete instruction will be executed on each 
+      ** OP_Delete or OP_IdxDelete instruction will be executed on each
       ** cursor that is disturbed. And these instructions both clear the
       ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
       ** functionality.  */
-      bUseSeek = (isReplace==0 || (pTrigger==0 &&
-          ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
-      ));
+      bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
           regIns, aRegIdx, 0, appendFlag, bUseSeek
       );
@@ -118699,7 +122531,7 @@ SQLITE_PRIVATE void sqlite3Insert(
 
   if( pTrigger ){
     /* Code AFTER triggers */
-    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
+    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
         pTab, regData-2-pTab->nCol, onError, endOfLoop);
   }
 
@@ -118713,6 +122545,15 @@ SQLITE_PRIVATE void sqlite3Insert(
     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
   }else if( pSelect ){
     sqlite3VdbeGoto(v, addrCont);
+#ifdef SQLITE_DEBUG
+    /* If we are jumping back to an OP_Yield that is preceded by an
+    ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
+    ** OP_ReleaseReg will be included in the loop. */
+    if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
+      assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
+      sqlite3VdbeChangeP5(v, 1);
+    }
+#endif
     sqlite3VdbeJumpHere(v, addrInsTop);
   }
 
@@ -118726,7 +122567,7 @@ insert_end:
   }
 
   /*
-  ** Return the number of rows inserted. If this routine is 
+  ** Return the number of rows inserted. If this routine is
   ** generating code because of a call to sqlite3NestedParse(), do not
   ** invoke the callback function.
   */
@@ -118759,7 +122600,7 @@ insert_cleanup:
 #endif
 
 /*
-** Meanings of bits in of pWalker->eCode for 
+** Meanings of bits in of pWalker->eCode for
 ** sqlite3ExprReferencesUpdatedColumn()
 */
 #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
@@ -118935,7 +122776,6 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   int ix;              /* Index loop counter */
   int nCol;            /* Number of columns */
   int onError;         /* Conflict resolution strategy */
-  int addr1;           /* Address of jump instruction */
   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
   Index *pUpIdx = 0;   /* Index to which to apply the upsert */
@@ -118945,16 +122785,23 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
   int upsertJump = 0;    /* Address of Goto that jumps into upsert subroutine */
   int ipkTop = 0;        /* Top of the IPK uniqueness check */
   int ipkBottom = 0;     /* OP_Goto at the end of the IPK uniqueness check */
+  /* Variables associated with retesting uniqueness constraints after
+  ** replace triggers fire have run */
+  int regTrigCnt;       /* Register used to count replace trigger invocations */
+  int addrRecheck = 0;  /* Jump here to recheck all uniqueness constraints */
+  int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
+  Trigger *pTrigger;    /* List of DELETE triggers on the table pTab */
+  int nReplaceTrig = 0; /* Number of replace triggers coded */
 
   isUpdate = regOldData!=0;
   db = pParse->db;
-  v = sqlite3GetVdbe(pParse);
+  v = pParse->pVdbe;
   assert( v!=0 );
   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   nCol = pTab->nCol;
-  
+
   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
-  ** normal rowid tables.  nPkField is the number of key fields in the 
+  ** normal rowid tables.  nPkField is the number of key fields in the
   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
   ** number of fields in the true primary key of the table. */
   if( HasRowid(pTab) ){
@@ -118971,63 +122818,103 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 
   /* Test all NOT NULL constraints.
   */
-  for(i=0; i<nCol; i++){
-    if( i==pTab->iPKey ){
-      continue;        /* ROWID is never NULL */
-    }
-    if( aiChng && aiChng[i]<0 ){
-      /* Don't bother checking for NOT NULL on columns that do not change */
-      continue;
-    }
-    onError = pTab->aCol[i].notNull;
-    if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
-    if( overrideError!=OE_Default ){
-      onError = overrideError;
-    }else if( onError==OE_Default ){
-      onError = OE_Abort;
-    }
-    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
-      onError = OE_Abort;
-    }
-    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
-        || onError==OE_Ignore || onError==OE_Replace );
-    addr1 = 0;
-    switch( onError ){
-      case OE_Replace: {
-        assert( onError==OE_Replace );
-        addr1 = sqlite3VdbeMakeLabel(pParse);
-        sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
-          VdbeCoverage(v);
-        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
-        sqlite3VdbeAddOp2(v, OP_NotNull, regNewData+1+i, addr1);
-          VdbeCoverage(v);
-        onError = OE_Abort;
-        /* Fall through into the OE_Abort case to generate code that runs
-        ** if both the input and the default value are NULL */
-      }
-      case OE_Abort:
-        sqlite3MayAbort(pParse);
-        /* Fall through */
-      case OE_Rollback:
-      case OE_Fail: {
-        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
-                                    pTab->aCol[i].zName);
-        sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
-                          regNewData+1+i);
-        sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
-        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
-        VdbeCoverage(v);
-        if( addr1 ) sqlite3VdbeResolveLabel(v, addr1);
-        break;
-      }
-      default: {
-        assert( onError==OE_Ignore );
-        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
-        VdbeCoverage(v);
-        break;
+  if( pTab->tabFlags & TF_HasNotNull ){
+    int b2ndPass = 0;         /* True if currently running 2nd pass */
+    int nSeenReplace = 0;     /* Number of ON CONFLICT REPLACE operations */
+    int nGenerated = 0;       /* Number of generated columns with NOT NULL */
+    while(1){  /* Make 2 passes over columns. Exit loop via "break" */
+      for(i=0; i<nCol; i++){
+        int iReg;                        /* Register holding column value */
+        Column *pCol = &pTab->aCol[i];   /* The column to check for NOT NULL */
+        int isGenerated;                 /* non-zero if column is generated */
+        onError = pCol->notNull;
+        if( onError==OE_None ) continue; /* No NOT NULL on this column */
+        if( i==pTab->iPKey ){
+          continue;        /* ROWID is never NULL */
+        }
+        isGenerated = pCol->colFlags & COLFLAG_GENERATED;
+        if( isGenerated && !b2ndPass ){
+          nGenerated++;
+          continue;        /* Generated columns processed on 2nd pass */
+        }
+        if( aiChng && aiChng[i]<0 && !isGenerated ){
+          /* Do not check NOT NULL on columns that do not change */
+          continue;
+        }
+        if( overrideError!=OE_Default ){
+          onError = overrideError;
+        }else if( onError==OE_Default ){
+          onError = OE_Abort;
+        }
+        if( onError==OE_Replace ){
+          if( b2ndPass        /* REPLACE becomes ABORT on the 2nd pass */
+           || pCol->pDflt==0  /* REPLACE is ABORT if no DEFAULT value */
+          ){
+            testcase( pCol->colFlags & COLFLAG_VIRTUAL );
+            testcase( pCol->colFlags & COLFLAG_STORED );
+            testcase( pCol->colFlags & COLFLAG_GENERATED );
+            onError = OE_Abort;
+          }else{
+            assert( !isGenerated );
+          }
+        }else if( b2ndPass && !isGenerated ){
+          continue;
+        }
+        assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
+            || onError==OE_Ignore || onError==OE_Replace );
+        testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
+        iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
+        switch( onError ){
+          case OE_Replace: {
+            int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
+            VdbeCoverage(v);
+            assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
+            nSeenReplace++;
+            sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg);
+            sqlite3VdbeJumpHere(v, addr1);
+            break;
+          }
+          case OE_Abort:
+            sqlite3MayAbort(pParse);
+            /* no break */ deliberate_fall_through
+          case OE_Rollback:
+          case OE_Fail: {
+            char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
+                                        pCol->zName);
+            sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
+                              onError, iReg);
+            sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
+            sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
+            VdbeCoverage(v);
+            break;
+          }
+          default: {
+            assert( onError==OE_Ignore );
+            sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
+            VdbeCoverage(v);
+            break;
+          }
+        } /* end switch(onError) */
+      } /* end loop i over columns */
+      if( nGenerated==0 && nSeenReplace==0 ){
+        /* If there are no generated columns with NOT NULL constraints
+        ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
+        ** pass is sufficient */
+        break;
+      }
+      if( b2ndPass ) break;  /* Never need more than 2 passes */
+      b2ndPass = 1;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+      if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
+        /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
+        ** first pass, recomputed values for all generated columns, as
+        ** those values might depend on columns affected by the REPLACE.
+        */
+        sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
       }
-    }
-  }
+#endif
+    } /* end of 2-pass loop */
+  } /* end if( has-not-null-constraints ) */
 
   /* Test all CHECK constraints
   */
@@ -119038,6 +122925,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
     for(i=0; i<pCheck->nExpr; i++){
       int allOk;
+      Expr *pCopy;
       Expr *pExpr = pCheck->a[i].pExpr;
       if( aiChng
        && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
@@ -119046,14 +122934,22 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         ** updated so there is no point it verifying the check constraint */
         continue;
       }
+      if( bAffinityDone==0 ){
+        sqlite3TableAffinity(v, pTab, regNewData+1);
+        bAffinityDone = 1;
+      }
       allOk = sqlite3VdbeMakeLabel(pParse);
       sqlite3VdbeVerifyAbortable(v, onError);
-      sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
+      pCopy = sqlite3ExprDup(db, pExpr, 0);
+      if( !db->mallocFailed ){
+        sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
+      }
+      sqlite3ExprDelete(db, pCopy);
       if( onError==OE_Ignore ){
         sqlite3VdbeGoto(v, ignoreDest);
       }else{
-        char *zName = pCheck->a[i].zName;
-        if( zName==0 ) zName = pTab->zName;
+        char *zName = pCheck->a[i].zEName;
+        assert( zName!=0 || pParse->db->mallocFailed );
         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
                               onError, zName, P4_TRANSIENT,
@@ -119109,6 +123005,50 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     }
   }
 
+  /* Determine if it is possible that triggers (either explicitly coded
+  ** triggers or FK resolution actions) might run as a result of deletes
+  ** that happen when OE_Replace conflict resolution occurs. (Call these
+  ** "replace triggers".)  If any replace triggers run, we will need to
+  ** recheck all of the uniqueness constraints after they have all run.
+  ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
+  **
+  ** If replace triggers are a possibility, then
+  **
+  **   (1) Allocate register regTrigCnt and initialize it to zero.
+  **       That register will count the number of replace triggers that
+  **       fire.  Constraint recheck only occurs if the number is positive.
+  **   (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
+  **   (3) Initialize addrRecheck and lblRecheckOk
+  **
+  ** The uniqueness rechecking code will create a series of tests to run
+  ** in a second pass.  The addrRecheck and lblRecheckOk variables are
+  ** used to link together these tests which are separated from each other
+  ** in the generate bytecode.
+  */
+  if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
+    /* There are not DELETE triggers nor FK constraints.  No constraint
+    ** rechecks are needed. */
+    pTrigger = 0;
+    regTrigCnt = 0;
+  }else{
+    if( db->flags&SQLITE_RecTriggers ){
+      pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
+      regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
+    }else{
+      pTrigger = 0;
+      regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
+    }
+    if( regTrigCnt ){
+      /* Replace triggers might exist.  Allocate the counter and
+      ** initialize it to zero. */
+      regTrigCnt = ++pParse->nMem;
+      sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
+      VdbeComment((v, "trigger count"));
+      lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
+      addrRecheck = lblRecheckOk;
+    }
+  }
+
   /* If rowid is changing, make sure the new rowid does not previously
   ** exist in the table.
   */
@@ -119164,7 +123104,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     switch( onError ){
       default: {
         onError = OE_Abort;
-        /* Fall thru into the next case */
+        /* no break */ deliberate_fall_through
       }
       case OE_Rollback:
       case OE_Abort:
@@ -119182,10 +123122,10 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         ** the triggers and remove both the table and index b-tree entries.
         **
         ** Otherwise, if there are no triggers or the recursive-triggers
-        ** flag is not set, but the table has one or more indexes, call 
-        ** GenerateRowIndexDelete(). This removes the index b-tree entries 
-        ** only. The table b-tree entry will be replaced by the new entry 
-        ** when it is inserted.  
+        ** flag is not set, but the table has one or more indexes, call
+        ** GenerateRowIndexDelete(). This removes the index b-tree entries
+        ** only. The table b-tree entry will be replaced by the new entry
+        ** when it is inserted.
         **
         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
         ** also invoke MultiWrite() to indicate that this VDBE may require
@@ -119198,14 +123138,12 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         ** to run without a statement journal if there are no indexes on the
         ** table.
         */
-        Trigger *pTrigger = 0;
-        if( db->flags&SQLITE_RecTriggers ){
-          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
-        }
-        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
+        if( regTrigCnt ){
           sqlite3MultiWrite(pParse);
           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
                                    regNewData, 1, 0, OE_Replace, 1, -1);
+          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
+          nReplaceTrig++;
         }else{
 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
           assert( HasRowid(pTab) );
@@ -119227,7 +123165,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 #ifndef SQLITE_OMIT_UPSERT
       case OE_Update: {
         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
-        /* Fall through */
+        /* no break */ deliberate_fall_through
       }
 #endif
       case OE_Ignore: {
@@ -119255,6 +123193,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     int regR;            /* Range of registers holding conflicting PK */
     int iThisCur;        /* Cursor for this UNIQUE index */
     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
+    int addrConflictCk;  /* First opcode in the conflict check logic */
 
     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
     if( pUpIdx==pIdx ){
@@ -119269,7 +123208,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
       sqlite3TableAffinity(v, pTab, regNewData+1);
       bAffinityDone = 1;
     }
-    VdbeNoopComment((v, "uniqueness check for %s", pIdx->zName));
+    VdbeNoopComment((v, "prep index %s", pIdx->zName));
     iThisCur = iIdxCur+ix;
 
 
@@ -119294,14 +123233,15 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
         pParse->iSelfTab = 0;
         VdbeComment((v, "%s column %d", pIdx->zName, i));
+      }else if( iField==XN_ROWID || iField==pTab->iPKey ){
+        x = regNewData;
+        sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
+        VdbeComment((v, "rowid"));
       }else{
-        if( iField==XN_ROWID || iField==pTab->iPKey ){
-          x = regNewData;
-        }else{
-          x = iField + regNewData + 1;
-        }
-        sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
-        VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
+        testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
+        x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
+        sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
+        VdbeComment((v, "%s", pTab->aCol[iField].zName));
       }
     }
     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
@@ -119311,8 +123251,9 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
       sqlite3SetMakeRecordP5(v, pIdx->pTable);
     }
 #endif
+    sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
 
-    /* In an UPDATE operation, if this index is the PRIMARY KEY index 
+    /* In an UPDATE operation, if this index is the PRIMARY KEY index
     ** of a WITHOUT ROWID table and there has been no change the
     ** primary key, then no collision is possible.  The collision detection
     ** logic below can all be skipped. */
@@ -119323,7 +123264,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 
     /* Find out what action to take in case there is a uniqueness conflict */
     onError = pIdx->onError;
-    if( onError==OE_None ){ 
+    if( onError==OE_None ){
       sqlite3VdbeResolveLabel(v, addrUniqueOk);
       continue;  /* pIdx is not a UNIQUE index */
     }
@@ -119351,7 +123292,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     **
     ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
     ** must be explicitly deleted in order to ensure any pre-update hook
-    ** is invoked.  */ 
+    ** is invoked.  */
 #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
     if( (ix==0 && pIdx->pNext==0)                   /* Condition 3 */
      && pPk==pIdx                                   /* Condition 2 */
@@ -119368,8 +123309,9 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 
     /* Check to see if the new index entry will be unique */
     sqlite3VdbeVerifyAbortable(v, onError);
-    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
-                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
+    addrConflictCk =
+      sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
+                           regIdx, pIdx->nKeyCol); VdbeCoverage(v);
 
     /* Generate code to handle collisions */
     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
@@ -119390,14 +123332,14 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         if( pIdx!=pPk ){
           for(i=0; i<pPk->nKeyCol; i++){
             assert( pPk->aiColumn[i]>=0 );
-            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
+            x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
             VdbeComment((v, "%s.%s", pTab->zName,
                          pTab->aCol[pPk->aiColumn[i]].zName));
           }
         }
         if( isUpdate ){
-          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
+          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
           ** table, only conflict if the new PRIMARY KEY values are actually
           ** different from the old.
           **
@@ -119407,7 +123349,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
           int op = OP_Ne;
           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
-  
+
           for(i=0; i<pPk->nKeyCol; i++){
             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
             x = pPk->aiColumn[i];
@@ -119416,7 +123358,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
               addrJump = addrUniqueOk;
               op = OP_Eq;
             }
-            sqlite3VdbeAddOp4(v, op, 
+            x = sqlite3TableColumnToStorage(pTab, x);
+            sqlite3VdbeAddOp4(v, op,
                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
             );
             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
@@ -119443,7 +123386,7 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
 #ifndef SQLITE_OMIT_UPSERT
       case OE_Update: {
         sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
-        /* Fall through */
+        /* no break */ deliberate_fall_through
       }
 #endif
       case OE_Ignore: {
@@ -119452,17 +123395,73 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
         break;
       }
       default: {
-        Trigger *pTrigger = 0;
+        int nConflictCk;   /* Number of opcodes in conflict check logic */
+
         assert( onError==OE_Replace );
-        if( db->flags&SQLITE_RecTriggers ){
-          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
-        }
-        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
+        nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
+        assert( nConflictCk>0 );
+        testcase( nConflictCk>1 );
+        if( regTrigCnt ){
           sqlite3MultiWrite(pParse);
+          nReplaceTrig++;
+        }
+        if( pTrigger && isUpdate ){
+          sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
         }
         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
             regR, nPkField, 0, OE_Replace,
             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
+        if( pTrigger && isUpdate ){
+          sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
+        }
+        if( regTrigCnt ){
+          int addrBypass;  /* Jump destination to bypass recheck logic */
+
+          sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
+          addrBypass = sqlite3VdbeAddOp0(v, OP_Goto);  /* Bypass recheck */
+          VdbeComment((v, "bypass recheck"));
+
+          /* Here we insert code that will be invoked after all constraint
+          ** checks have run, if and only if one or more replace triggers
+          ** fired. */
+          sqlite3VdbeResolveLabel(v, lblRecheckOk);
+          lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
+          if( pIdx->pPartIdxWhere ){
+            /* Bypass the recheck if this partial index is not defined
+            ** for the current row */
+            sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
+            VdbeCoverage(v);
+          }
+          /* Copy the constraint check code from above, except change
+          ** the constraint-ok jump destination to be the address of
+          ** the next retest block */
+          while( nConflictCk>0 ){
+            VdbeOp x;    /* Conflict check opcode to copy */
+            /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
+            ** Hence, make a complete copy of the opcode, rather than using
+            ** a pointer to the opcode. */
+            x = *sqlite3VdbeGetOp(v, addrConflictCk);
+            if( x.opcode!=OP_IdxRowid ){
+              int p2;      /* New P2 value for copied conflict check opcode */
+              const char *zP4;
+              if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
+                p2 = lblRecheckOk;
+              }else{
+                p2 = x.p2;
+              }
+              zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
+              sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
+              sqlite3VdbeChangeP5(v, x.p5);
+              VdbeCoverageIf(v, p2!=x.p2);
+            }
+            nConflictCk--;
+            addrConflictCk++;
+          }
+          /* If the retest fails, issue an abort */
+          sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
+
+          sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
+        }
         seenReplace = 1;
         break;
       }
@@ -119483,10 +123482,30 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
     sqlite3VdbeJumpHere(v, ipkBottom);
   }
 
+  /* Recheck all uniqueness constraints after replace triggers have run */
+  testcase( regTrigCnt!=0 && nReplaceTrig==0 );
+  assert( regTrigCnt!=0 || nReplaceTrig==0 );
+  if( nReplaceTrig ){
+    sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
+    if( !pPk ){
+      if( isUpdate ){
+        sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
+        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
+        VdbeCoverage(v);
+      }
+      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
+      VdbeCoverage(v);
+      sqlite3RowidConstraint(pParse, OE_Abort, pTab);
+    }else{
+      sqlite3VdbeGoto(v, addrRecheck);
+    }
+    sqlite3VdbeResolveLabel(v, lblRecheckOk);
+  }
+
   /* Generate the table record */
   if( HasRowid(pTab) ){
     int regRec = aRegIdx[ix];
-    sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nCol, regRec);
+    sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
     sqlite3SetMakeRecordP5(v, pTab);
     if( !bAffinityDone ){
       sqlite3TableAffinity(v, pTab, 0);
@@ -119549,10 +123568,14 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion(
        || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
   );
 
-  v = sqlite3GetVdbe(pParse);
+  v = pParse->pVdbe;
   assert( v!=0 );
   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
+    /* All REPLACE indexes are at the end of the list */
+    assert( pIdx->onError!=OE_Replace
+         || pIdx->pNext==0
+         || pIdx->pNext->onError==OE_Replace );
     if( aRegIdx[i]==0 ) continue;
     if( pIdx->pPartIdxWhere ){
       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
@@ -119567,7 +123590,7 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion(
       if( update_flags==0 ){
         int r = sqlite3GetTempReg(pParse);
         sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
-        sqlite3VdbeAddOp4(v, OP_Insert, 
+        sqlite3VdbeAddOp4(v, OP_Insert,
             iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
         );
         sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
@@ -119646,7 +123669,7 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
     return 0;
   }
   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
-  v = sqlite3GetVdbe(pParse);
+  v = pParse->pVdbe;
   assert( v!=0 );
   if( iBase<0 ) iBase = pParse->nTab;
   iDataCur = iBase++;
@@ -119703,7 +123726,7 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){
   int i;
   assert( pDest && pSrc );
   assert( pDest->pTable!=pSrc->pTable );
-  if( pDest->nKeyCol!=pSrc->nKeyCol ){
+  if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
     return 0;   /* Different number of columns */
   }
   if( pDest->onError!=pSrc->onError ){
@@ -119740,7 +123763,7 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){
 **
 **     INSERT INTO tab1 SELECT * FROM tab2;
 **
-** The xfer optimization transfers raw records from tab2 over to tab1.  
+** The xfer optimization transfers raw records from tab2 over to tab1.
 ** Columns are not decoded and reassembled, which greatly improves
 ** performance.  Raw index records are transferred in the same way.
 **
@@ -119851,7 +123874,7 @@ static int xferOptimization(
     return 0;   /* FROM clause does not contain a real table */
   }
   if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
-    testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
+    testcase( pSrc!=pDest ); /* Possible due to bad sqlite_schema.rootpage */
     return 0;   /* tab1 and tab2 may not be the same table */
   }
   if( HasRowid(pDest)!=HasRowid(pSrc) ){
@@ -119875,12 +123898,45 @@ static int xferOptimization(
     Column *pDestCol = &pDest->aCol[i];
     Column *pSrcCol = &pSrc->aCol[i];
 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
-    if( (db->mDbFlags & DBFLAG_Vacuum)==0 
-     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 
+    if( (db->mDbFlags & DBFLAG_Vacuum)==0
+     && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
     ){
       return 0;    /* Neither table may have __hidden__ columns */
     }
 #endif
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    /* Even if tables t1 and t2 have identical schemas, if they contain
+    ** generated columns, then this statement is semantically incorrect:
+    **
+    **     INSERT INTO t2 SELECT * FROM t1;
+    **
+    ** The reason is that generated column values are returned by the
+    ** the SELECT statement on the right but the INSERT statement on the
+    ** left wants them to be omitted.
+    **
+    ** Nevertheless, this is a useful notational shorthand to tell SQLite
+    ** to do a bulk transfer all of the content from t1 over to t2.
+    **
+    ** We could, in theory, disable this (except for internal use by the
+    ** VACUUM command where it is actually needed).  But why do that?  It
+    ** seems harmless enough, and provides a useful service.
+    */
+    if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
+        (pSrcCol->colFlags & COLFLAG_GENERATED) ){
+      return 0;    /* Both columns have the same generated-column type */
+    }
+    /* But the transfer is only allowed if both the source and destination
+    ** tables have the exact same expressions for generated columns.
+    ** This requirement could be relaxed for VIRTUAL columns, I suppose.
+    */
+    if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
+      if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){
+        testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
+        testcase( pDestCol->colFlags & COLFLAG_STORED );
+        return 0;  /* Different generator expressions */
+      }
+    }
+#endif
     if( pDestCol->affinity!=pSrcCol->affinity ){
       return 0;    /* Affinity must be the same on all columns */
     }
@@ -119891,10 +123947,10 @@ static int xferOptimization(
       return 0;    /* tab2 must be NOT NULL if tab1 is */
     }
     /* Default values for second and subsequent columns need to match. */
-    if( i>0 ){
+    if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
-      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
+      if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
                                        pSrcCol->pDflt->u.zToken)!=0)
       ){
@@ -119928,7 +123984,7 @@ static int xferOptimization(
 #ifndef SQLITE_OMIT_FOREIGN_KEY
   /* Disallow the transfer optimization if the destination table constains
   ** any foreign key constraints.  This is more restrictive than necessary.
-  ** But the main beneficiary of the transfer optimization is the VACUUM 
+  ** But the main beneficiary of the transfer optimization is the VACUUM
   ** command, and the VACUUM command disables foreign key constraints.  So
   ** the extra complication to make this rule less restrictive is probably
   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
@@ -119975,7 +124031,7 @@ static int xferOptimization(
     **     (If the destination is not initially empty, the rowid fields
     **     of index entries might need to change.)
     **
-    ** (2) The destination has a unique index.  (The xfer optimization 
+    ** (2) The destination has a unique index.  (The xfer optimization
     **     is unable to test uniqueness.)
     **
     ** (3) onError is something other than OE_Abort and OE_Rollback.
@@ -120002,14 +124058,13 @@ static int xferOptimization(
       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
     }
-    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
     if( db->mDbFlags & DBFLAG_Vacuum ){
       sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
-      insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
-                           OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
+      insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
     }else{
       insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
     }
+    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
                       (char*)pDest, P4_TABLE);
     sqlite3VdbeChangeP5(v, insFlags);
@@ -120034,19 +124089,18 @@ static int xferOptimization(
     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
     VdbeComment((v, "%s", pDestIdx->zName));
     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
-    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
     if( db->mDbFlags & DBFLAG_Vacuum ){
       /* This INSERT command is part of a VACUUM operation, which guarantees
       ** that the destination table is empty. If all indexed columns use
       ** collation sequence BINARY, then it can also be assumed that the
-      ** index will be populated by inserting keys in strictly sorted 
+      ** index will be populated by inserting keys in strictly sorted
       ** order. In this case, instead of seeking within the b-tree as part
       ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
-      ** OP_IdxInsert to seek to the point within the b-tree where each key 
+      ** OP_IdxInsert to seek to the point within the b-tree where each key
       ** should be inserted. This is faster.
       **
       ** If any of the indexed columns use a collation sequence other than
-      ** BINARY, this optimization is disabled. This is because the user 
+      ** BINARY, this optimization is disabled. This is because the user
       ** might change the definition of a collation sequence and then run
       ** a VACUUM command. In that case keys may not be written in strictly
       ** sorted order.  */
@@ -120058,10 +124112,10 @@ static int xferOptimization(
         idxInsFlags = OPFLAG_USESEEKRESULT;
         sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
       }
-    }
-    if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
+    }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
       idxInsFlags |= OPFLAG_NCHANGE;
     }
+    sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
     sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
     sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
@@ -120155,7 +124209,7 @@ SQLITE_API int sqlite3_exec(
       rc = sqlite3_step(pStmt);
 
       /* Invoke the callback function if required */
-      if( xCallback && (SQLITE_ROW==rc || 
+      if( xCallback && (SQLITE_ROW==rc ||
           (SQLITE_DONE==rc && !callbackIsInit
                            && db->flags&SQLITE_NullCallback)) ){
         if( !callbackIsInit ){
@@ -120264,7 +124318,7 @@ exec_out:
 ** This header file defines the SQLite interface for use by
 ** shared libraries that want to be imported as extensions into
 ** an SQLite instance.  Shared libraries that intend to be loaded
-** as extensions by SQLite should #include this file instead of 
+** as extensions by SQLite should #include this file instead of
 ** sqlite3.h.
 */
 #ifndef SQLITE3EXT_H
@@ -120576,6 +124630,19 @@ struct sqlite3_api_routines {
   int (*value_frombind)(sqlite3_value*);
   /* Version 3.30.0 and later */
   int (*drop_modules)(sqlite3*,const char**);
+  /* Version 3.31.0 and later */
+  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
+  const char *(*uri_key)(const char*,int);
+  const char *(*filename_database)(const char*);
+  const char *(*filename_journal)(const char*);
+  const char *(*filename_wal)(const char*);
+  /* Version 3.32.0 and later */
+  char *(*create_filename)(const char*,const char*,const char*,
+                           int,const char**);
+  void (*free_filename)(char*);
+  sqlite3_file *(*database_file_object)(const char*);
+  /* Version 3.34.0 and later */
+  int (*txn_state)(sqlite3*,const char*);
 };
 
 /*
@@ -120872,21 +124939,33 @@ typedef int (*sqlite3_loadext_entry)(
 /* Version 3.26.0 and later */
 #define sqlite3_normalized_sql         sqlite3_api->normalized_sql
 /* Version 3.28.0 and later */
-#define sqlite3_stmt_isexplain         sqlite3_api->isexplain
-#define sqlite3_value_frombind         sqlite3_api->frombind
+#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain
+#define sqlite3_value_frombind         sqlite3_api->value_frombind
 /* Version 3.30.0 and later */
 #define sqlite3_drop_modules           sqlite3_api->drop_modules
+/* Version 3.31.0 and later */
+#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64
+#define sqlite3_uri_key                sqlite3_api->uri_key
+#define sqlite3_filename_database      sqlite3_api->filename_database
+#define sqlite3_filename_journal       sqlite3_api->filename_journal
+#define sqlite3_filename_wal           sqlite3_api->filename_wal
+/* Version 3.32.0 and later */
+#define sqlite3_create_filename        sqlite3_api->create_filename
+#define sqlite3_free_filename          sqlite3_api->free_filename
+#define sqlite3_database_file_object   sqlite3_api->database_file_object
+/* Version 3.34.0 and later */
+#define sqlite3_txn_state              sqlite3_api->txn_state
 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
 
 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
-  /* This case when the file really is being compiled as a loadable 
+  /* This case when the file really is being compiled as a loadable
   ** extension */
 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
 # define SQLITE_EXTENSION_INIT3     \
     extern const sqlite3_api_routines *sqlite3_api;
 #else
-  /* This case when the file is being statically linked into the 
+  /* This case when the file is being statically linked into the
   ** application */
 # define SQLITE_EXTENSION_INIT1     /*no-op*/
 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
@@ -121191,8 +125270,8 @@ static const sqlite3_api_routines sqlite3Apis = {
   sqlite3_memory_highwater,
   sqlite3_memory_used,
 #ifdef SQLITE_MUTEX_OMIT
-  0, 
-  0, 
+  0,
+  0,
   0,
   0,
   0,
@@ -121361,8 +125440,28 @@ static const sqlite3_api_routines sqlite3Apis = {
 #else
   0,
 #endif
+  /* Version 3.31.0 and later */
+  sqlite3_hard_heap_limit64,
+  sqlite3_uri_key,
+  sqlite3_filename_database,
+  sqlite3_filename_journal,
+  sqlite3_filename_wal,
+  /* Version 3.32.0 and later */
+  sqlite3_create_filename,
+  sqlite3_free_filename,
+  sqlite3_database_file_object,
+  /* Version 3.34.0 and later */
+  sqlite3_txn_state,
 };
 
+/* True if x is the directory separator character
+*/
+#if SQLITE_OS_WIN
+# define DirSep(X)  ((X)=='/'||(X)=='\\')
+#else
+# define DirSep(X)  ((X)=='/')
+#endif
+
 /*
 ** Attempt to load an SQLite extension library contained in the file
 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
@@ -121371,7 +125470,7 @@ static const sqlite3_api_routines sqlite3Apis = {
 **
 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
 **
-** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
+** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
 ** error message text.  The calling function should free this memory
 ** by calling sqlite3DbFree(db, ).
 */
@@ -121395,7 +125494,7 @@ static int sqlite3LoadExtension(
   /* Shared library endings to try if zFile cannot be loaded as written */
   static const char *const azEndings[] = {
 #if defined(_WIN32) || defined(__CYGWIN__)
-     "dll"   
+     "dll"
 #elif defined(__APPLE__)
      "dylib"
 #else
@@ -121444,7 +125543,7 @@ static int sqlite3LoadExtension(
     if( pzErrMsg ){
       *pzErrMsg = zErrmsg = sqlite3Malloc(nMsg);
       if( zErrmsg ){
-        sqlite3_snprintf(nMsg, zErrmsg, 
+        sqlite3_snprintf(nMsg, zErrmsg,
             "unable to open shared library [%s]", zFile);
         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
       }
@@ -121456,9 +125555,9 @@ static int sqlite3LoadExtension(
   /* If no entry point was specified and the default legacy
   ** entry point name "sqlite3_extension_init" was not found, then
   ** construct an entry point name "sqlite3_X_init" where the X is
-  ** replaced by the lowercase value of every ASCII alphabetic 
+  ** replaced by the lowercase value of every ASCII alphabetic
   ** character in the filename after the last "/" upto the first ".",
-  ** and eliding the first three characters if they are "lib".  
+  ** and eliding the first three characters if they are "lib".
   ** Examples:
   **
   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
@@ -121473,7 +125572,7 @@ static int sqlite3LoadExtension(
       return SQLITE_NOMEM_BKPT;
     }
     memcpy(zAltEntry, "sqlite3_", 8);
-    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
+    for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
     iFile++;
     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
@@ -121573,12 +125672,12 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
 ** The following object holds the list of automatically loaded
 ** extensions.
 **
-** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
+** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MAIN
 ** mutex must be held while accessing this list.
 */
 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
 static SQLITE_WSD struct sqlite3AutoExtList {
-  u32 nExt;              /* Number of entries in aExt[] */          
+  u32 nExt;              /* Number of entries in aExt[] */
   void (**aExt)(void);   /* Pointers to the extension init functions */
 } sqlite3Autoext = { 0, 0 };
 
@@ -121615,7 +125714,7 @@ SQLITE_API int sqlite3_auto_extension(
   {
     u32 i;
 #if SQLITE_THREADSAFE
-    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
     wsdAutoextInit;
     sqlite3_mutex_enter(mutex);
@@ -121653,7 +125752,7 @@ SQLITE_API int sqlite3_cancel_auto_extension(
   void (*xInit)(void)
 ){
 #if SQLITE_THREADSAFE
-  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
   int i;
   int n = 0;
@@ -121680,7 +125779,7 @@ SQLITE_API void sqlite3_reset_auto_extension(void){
 #endif
   {
 #if SQLITE_THREADSAFE
-    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
     wsdAutoextInit;
     sqlite3_mutex_enter(mutex);
@@ -121710,7 +125809,7 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
   for(i=0; go; i++){
     char *zErrmsg;
 #if SQLITE_THREADSAFE
-    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
 #endif
 #ifdef SQLITE_OMIT_LOAD_EXTENSION
     const sqlite3_api_routines *pThunk = 0;
@@ -121765,7 +125864,7 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
 ** object.  This ensures that the aPragmaName[] table is arranged in
 ** lexicographical order to facility a binary search of the pragma name.
-** Do not edit pragma.h directly.  Edit and rerun the script in at 
+** Do not edit pragma.h directly.  Edit and rerun the script in at
 ** ../tool/mkpragmatab.tcl. */
 /************** Include pragma.h in the middle of pragma.c *******************/
 /************** Begin file pragma.h ******************************************/
@@ -121776,50 +125875,51 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
 */
 
 /* The various pragma types */
-#define PragTyp_HEADER_VALUE                   0
-#define PragTyp_AUTO_VACUUM                    1
-#define PragTyp_FLAG                           2
-#define PragTyp_BUSY_TIMEOUT                   3
-#define PragTyp_CACHE_SIZE                     4
-#define PragTyp_CACHE_SPILL                    5
-#define PragTyp_CASE_SENSITIVE_LIKE            6
-#define PragTyp_COLLATION_LIST                 7
-#define PragTyp_COMPILE_OPTIONS                8
-#define PragTyp_DATA_STORE_DIRECTORY           9
-#define PragTyp_DATABASE_LIST                 10
-#define PragTyp_DEFAULT_CACHE_SIZE            11
-#define PragTyp_ENCODING                      12
-#define PragTyp_FOREIGN_KEY_CHECK             13
-#define PragTyp_FOREIGN_KEY_LIST              14
-#define PragTyp_FUNCTION_LIST                 15
-#define PragTyp_INCREMENTAL_VACUUM            16
-#define PragTyp_INDEX_INFO                    17
-#define PragTyp_INDEX_LIST                    18
-#define PragTyp_INTEGRITY_CHECK               19
-#define PragTyp_JOURNAL_MODE                  20
-#define PragTyp_JOURNAL_SIZE_LIMIT            21
-#define PragTyp_LOCK_PROXY_FILE               22
-#define PragTyp_LOCKING_MODE                  23
-#define PragTyp_PAGE_COUNT                    24
-#define PragTyp_MMAP_SIZE                     25
-#define PragTyp_MODULE_LIST                   26
-#define PragTyp_OPTIMIZE                      27
-#define PragTyp_PAGE_SIZE                     28
-#define PragTyp_PRAGMA_LIST                   29
-#define PragTyp_SECURE_DELETE                 30
-#define PragTyp_SHRINK_MEMORY                 31
-#define PragTyp_SOFT_HEAP_LIMIT               32
-#define PragTyp_SYNCHRONOUS                   33
-#define PragTyp_TABLE_INFO                    34
-#define PragTyp_TEMP_STORE                    35
-#define PragTyp_TEMP_STORE_DIRECTORY          36
-#define PragTyp_THREADS                       37
-#define PragTyp_WAL_AUTOCHECKPOINT            38
-#define PragTyp_WAL_CHECKPOINT                39
-#define PragTyp_ACTIVATE_EXTENSIONS           40
-#define PragTyp_KEY                           41
-#define PragTyp_LOCK_STATUS                   42
-#define PragTyp_STATS                         43
+#define PragTyp_ACTIVATE_EXTENSIONS            0
+#define PragTyp_ANALYSIS_LIMIT                 1
+#define PragTyp_HEADER_VALUE                   2
+#define PragTyp_AUTO_VACUUM                    3
+#define PragTyp_FLAG                           4
+#define PragTyp_BUSY_TIMEOUT                   5
+#define PragTyp_CACHE_SIZE                     6
+#define PragTyp_CACHE_SPILL                    7
+#define PragTyp_CASE_SENSITIVE_LIKE            8
+#define PragTyp_COLLATION_LIST                 9
+#define PragTyp_COMPILE_OPTIONS               10
+#define PragTyp_DATA_STORE_DIRECTORY          11
+#define PragTyp_DATABASE_LIST                 12
+#define PragTyp_DEFAULT_CACHE_SIZE            13
+#define PragTyp_ENCODING                      14
+#define PragTyp_FOREIGN_KEY_CHECK             15
+#define PragTyp_FOREIGN_KEY_LIST              16
+#define PragTyp_FUNCTION_LIST                 17
+#define PragTyp_HARD_HEAP_LIMIT               18
+#define PragTyp_INCREMENTAL_VACUUM            19
+#define PragTyp_INDEX_INFO                    20
+#define PragTyp_INDEX_LIST                    21
+#define PragTyp_INTEGRITY_CHECK               22
+#define PragTyp_JOURNAL_MODE                  23
+#define PragTyp_JOURNAL_SIZE_LIMIT            24
+#define PragTyp_LOCK_PROXY_FILE               25
+#define PragTyp_LOCKING_MODE                  26
+#define PragTyp_PAGE_COUNT                    27
+#define PragTyp_MMAP_SIZE                     28
+#define PragTyp_MODULE_LIST                   29
+#define PragTyp_OPTIMIZE                      30
+#define PragTyp_PAGE_SIZE                     31
+#define PragTyp_PRAGMA_LIST                   32
+#define PragTyp_SECURE_DELETE                 33
+#define PragTyp_SHRINK_MEMORY                 34
+#define PragTyp_SOFT_HEAP_LIMIT               35
+#define PragTyp_SYNCHRONOUS                   36
+#define PragTyp_TABLE_INFO                    37
+#define PragTyp_TEMP_STORE                    38
+#define PragTyp_TEMP_STORE_DIRECTORY          39
+#define PragTyp_THREADS                       40
+#define PragTyp_WAL_AUTOCHECKPOINT            41
+#define PragTyp_WAL_CHECKPOINT                42
+#define PragTyp_LOCK_STATUS                   43
+#define PragTyp_STATS                         44
 
 /* Property flags associated with various pragma. */
 #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
@@ -121837,56 +125937,60 @@ SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
 */
 static const char *const pragCName[] = {
   /*   0 */ "id",          /* Used by: foreign_key_list */
-  /*   1 */ "seq",        
-  /*   2 */ "table",      
-  /*   3 */ "from",       
-  /*   4 */ "to",         
-  /*   5 */ "on_update",  
-  /*   6 */ "on_delete",  
-  /*   7 */ "match",      
+  /*   1 */ "seq",
+  /*   2 */ "table",
+  /*   3 */ "from",
+  /*   4 */ "to",
+  /*   5 */ "on_update",
+  /*   6 */ "on_delete",
+  /*   7 */ "match",
   /*   8 */ "cid",         /* Used by: table_xinfo */
-  /*   9 */ "name",       
-  /*  10 */ "type",       
-  /*  11 */ "notnull",    
-  /*  12 */ "dflt_value", 
-  /*  13 */ "pk",         
-  /*  14 */ "hidden",     
+  /*   9 */ "name",
+  /*  10 */ "type",
+  /*  11 */ "notnull",
+  /*  12 */ "dflt_value",
+  /*  13 */ "pk",
+  /*  14 */ "hidden",
                            /* table_info reuses 8 */
   /*  15 */ "seqno",       /* Used by: index_xinfo */
-  /*  16 */ "cid",        
-  /*  17 */ "name",       
-  /*  18 */ "desc",       
-  /*  19 */ "coll",       
-  /*  20 */ "key",        
-  /*  21 */ "tbl",         /* Used by: stats */
-  /*  22 */ "idx",        
-  /*  23 */ "wdth",       
-  /*  24 */ "hght",       
-  /*  25 */ "flgs",       
-  /*  26 */ "seq",         /* Used by: index_list */
-  /*  27 */ "name",       
-  /*  28 */ "unique",     
-  /*  29 */ "origin",     
-  /*  30 */ "partial",    
-  /*  31 */ "table",       /* Used by: foreign_key_check */
-  /*  32 */ "rowid",      
-  /*  33 */ "parent",     
-  /*  34 */ "fkid",       
+  /*  16 */ "cid",
+  /*  17 */ "name",
+  /*  18 */ "desc",
+  /*  19 */ "coll",
+  /*  20 */ "key",
+  /*  21 */ "name",        /* Used by: function_list */
+  /*  22 */ "builtin",
+  /*  23 */ "type",
+  /*  24 */ "enc",
+  /*  25 */ "narg",
+  /*  26 */ "flags",
+  /*  27 */ "tbl",         /* Used by: stats */
+  /*  28 */ "idx",
+  /*  29 */ "wdth",
+  /*  30 */ "hght",
+  /*  31 */ "flgs",
+  /*  32 */ "seq",         /* Used by: index_list */
+  /*  33 */ "name",
+  /*  34 */ "unique",
+  /*  35 */ "origin",
+  /*  36 */ "partial",
+  /*  37 */ "table",       /* Used by: foreign_key_check */
+  /*  38 */ "rowid",
+  /*  39 */ "parent",
+  /*  40 */ "fkid",
                            /* index_info reuses 15 */
-  /*  35 */ "seq",         /* Used by: database_list */
-  /*  36 */ "name",       
-  /*  37 */ "file",       
-  /*  38 */ "busy",        /* Used by: wal_checkpoint */
-  /*  39 */ "log",        
-  /*  40 */ "checkpointed",
-  /*  41 */ "name",        /* Used by: function_list */
-  /*  42 */ "builtin",    
-                           /* collation_list reuses 26 */
-  /*  43 */ "database",    /* Used by: lock_status */
-  /*  44 */ "status",     
-  /*  45 */ "cache_size",  /* Used by: default_cache_size */
+  /*  41 */ "seq",         /* Used by: database_list */
+  /*  42 */ "name",
+  /*  43 */ "file",
+  /*  44 */ "busy",        /* Used by: wal_checkpoint */
+  /*  45 */ "log",
+  /*  46 */ "checkpointed",
+                           /* collation_list reuses 32 */
+  /*  47 */ "database",    /* Used by: lock_status */
+  /*  48 */ "status",
+  /*  49 */ "cache_size",  /* Used by: default_cache_size */
                            /* module_list pragma_list reuses 9 */
-  /*  46 */ "timeout",     /* Used by: busy_timeout */
+  /*  50 */ "timeout",     /* Used by: busy_timeout */
 };
 
 /* Definitions of all built-in pragmas */
@@ -121899,13 +126003,18 @@ typedef struct PragmaName {
   u64 iArg;                /* Extra argument */
 } PragmaName;
 static const PragmaName aPragmaName[] = {
-#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
+#if defined(SQLITE_ENABLE_CEROD)
  {/* zName:     */ "activate_extensions",
   /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
   /* ePragFlg:  */ 0,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
 #endif
+ {/* zName:     */ "analysis_limit",
+  /* ePragTyp:  */ PragTyp_ANALYSIS_LIMIT,
+  /* ePragFlg:  */ PragFlg_Result0,
+  /* ColNames:  */ 0, 0,
+  /* iArg:      */ 0 },
 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  {/* zName:     */ "application_id",
   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
@@ -121932,7 +126041,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "busy_timeout",
   /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 46, 1,
+  /* ColNames:  */ 50, 1,
   /* iArg:      */ 0 },
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  {/* zName:     */ "cache_size",
@@ -121971,7 +126080,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "collation_list",
   /* ePragTyp:  */ PragTyp_COLLATION_LIST,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 26, 2,
+  /* ColNames:  */ 32, 2,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
@@ -122006,14 +126115,14 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "database_list",
   /* ePragTyp:  */ PragTyp_DATABASE_LIST,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
-  /* ColNames:  */ 35, 3,
+  /* ColNames:  */ 41, 3,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  {/* zName:     */ "default_cache_size",
   /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
-  /* ColNames:  */ 45, 1,
+  /* ColNames:  */ 49, 1,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
@@ -122042,8 +126151,8 @@ static const PragmaName aPragmaName[] = {
 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  {/* zName:     */ "foreign_key_check",
   /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
-  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0,
-  /* ColNames:  */ 31, 4,
+  /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1|PragFlg_SchemaOpt,
+  /* ColNames:  */ 37, 4,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
@@ -122086,22 +126195,15 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "function_list",
   /* ePragTyp:  */ PragTyp_FUNCTION_LIST,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 41, 2,
+  /* ColNames:  */ 21, 6,
   /* iArg:      */ 0 },
 #endif
 #endif
-#if defined(SQLITE_HAS_CODEC)
- {/* zName:     */ "hexkey",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ 2 },
- {/* zName:     */ "hexrekey",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
+ {/* zName:     */ "hard_heap_limit",
+  /* ePragTyp:  */ PragTyp_HARD_HEAP_LIMIT,
+  /* ePragFlg:  */ PragFlg_Result0,
   /* ColNames:  */ 0, 0,
-  /* iArg:      */ 3 },
-#endif
+  /* iArg:      */ 0 },
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
 #if !defined(SQLITE_OMIT_CHECK)
  {/* zName:     */ "ignore_check_constraints",
@@ -122127,7 +126229,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "index_list",
   /* ePragTyp:  */ PragTyp_INDEX_LIST,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
-  /* ColNames:  */ 26, 5,
+  /* ColNames:  */ 32, 5,
   /* iArg:      */ 0 },
  {/* zName:     */ "index_xinfo",
   /* ePragTyp:  */ PragTyp_INDEX_INFO,
@@ -122154,24 +126256,12 @@ static const PragmaName aPragmaName[] = {
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
 #endif
-#if defined(SQLITE_HAS_CODEC)
- {/* zName:     */ "key",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ 0 },
-#endif
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  {/* zName:     */ "legacy_alter_table",
   /* ePragTyp:  */ PragTyp_FLAG,
   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ SQLITE_LegacyAlter },
- {/* zName:     */ "legacy_file_format",
-  /* ePragTyp:  */ PragTyp_FLAG,
-  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ SQLITE_LegacyFileFmt },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  {/* zName:     */ "lock_proxy_file",
@@ -122184,7 +126274,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "lock_status",
   /* ePragTyp:  */ PragTyp_LOCK_STATUS,
   /* ePragFlg:  */ PragFlg_Result0,
-  /* ColNames:  */ 43, 2,
+  /* ColNames:  */ 47, 2,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
@@ -122273,15 +126363,6 @@ static const PragmaName aPragmaName[] = {
   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ SQLITE_RecTriggers },
-#endif
-#if defined(SQLITE_HAS_CODEC)
- {/* zName:     */ "rekey",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ 1 },
-#endif
-#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  {/* zName:     */ "reverse_unordered_selects",
   /* ePragTyp:  */ PragTyp_FLAG,
   /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
@@ -122332,7 +126413,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "stats",
   /* ePragTyp:  */ PragTyp_STATS,
   /* ePragFlg:  */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
-  /* ColNames:  */ 21, 5,
+  /* ColNames:  */ 27, 5,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
@@ -122366,23 +126447,18 @@ static const PragmaName aPragmaName[] = {
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
 #endif
-#if defined(SQLITE_HAS_CODEC)
- {/* zName:     */ "textkey",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ 4 },
- {/* zName:     */ "textrekey",
-  /* ePragTyp:  */ PragTyp_KEY,
-  /* ePragFlg:  */ 0,
-  /* ColNames:  */ 0, 0,
-  /* iArg:      */ 5 },
-#endif
  {/* zName:     */ "threads",
   /* ePragTyp:  */ PragTyp_THREADS,
   /* ePragFlg:  */ PragFlg_Result0,
   /* ColNames:  */ 0, 0,
   /* iArg:      */ 0 },
+#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
+ {/* zName:     */ "trusted_schema",
+  /* ePragTyp:  */ PragTyp_FLAG,
+  /* ePragFlg:  */ PragFlg_Result0|PragFlg_NoColumns1,
+  /* ColNames:  */ 0, 0,
+  /* iArg:      */ SQLITE_TrustedSchema },
+#endif
 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  {/* zName:     */ "user_version",
   /* ePragTyp:  */ PragTyp_HEADER_VALUE,
@@ -122428,7 +126504,7 @@ static const PragmaName aPragmaName[] = {
  {/* zName:     */ "wal_checkpoint",
   /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
   /* ePragFlg:  */ PragFlg_NeedSchema,
-  /* ColNames:  */ 38, 3,
+  /* ColNames:  */ 44, 3,
   /* iArg:      */ 0 },
 #endif
 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
@@ -122439,14 +126515,14 @@ static const PragmaName aPragmaName[] = {
   /* iArg:      */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
 #endif
 };
-/* Number of pragmas: 65 on by default, 81 total. */
+/* Number of pragmas: 67 on by default, 77 total. */
 
 /************** End of pragma.h **********************************************/
 /************** Continuing where we left off in pragma.c *********************/
 
 /*
 ** Interpret the given string as a safety level.  Return 0 for OFF,
-** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
+** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or
 ** unrecognized string argument.  The FULL and EXTRA option is disallowed
 ** if the omitFull parameter it 1.
 **
@@ -122505,7 +126581,7 @@ static int getLockingMode(const char *z){
 /*
 ** Interpret the given string as an auto-vacuum mode value.
 **
-** The following strings, "none", "full" and "incremental" are 
+** The following strings, "none", "full" and "incremental" are
 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
 */
 static int getAutoVacuum(const char *z){
@@ -122545,7 +126621,9 @@ static int getTempStore(const char *z){
 static int invalidateTempStorage(Parse *pParse){
   sqlite3 *db = pParse->db;
   if( db->aDb[1].pBt!=0 ){
-    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
+    if( !db->autoCommit
+     || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
+    ){
       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
         "from within a transaction");
       return SQLITE_ERROR;
@@ -122657,7 +126735,7 @@ static const char *actionName(u8 action){
     case OE_SetDflt:  zName = "SET DEFAULT";     break;
     case OE_Cascade:  zName = "CASCADE";         break;
     case OE_Restrict: zName = "RESTRICT";        break;
-    default:          zName = "NO ACTION";  
+    default:          zName = "NO ACTION";
                       assert( action==OE_None ); break;
   }
   return zName;
@@ -122710,6 +126788,55 @@ static const PragmaName *pragmaLocate(const char *zName){
 }
 
 /*
+** Create zero or more entries in the output for the SQL functions
+** defined by FuncDef p.
+*/
+static void pragmaFunclistLine(
+  Vdbe *v,               /* The prepared statement being created */
+  FuncDef *p,            /* A particular function definition */
+  int isBuiltin,         /* True if this is a built-in function */
+  int showInternFuncs    /* True if showing internal functions */
+){
+  for(; p; p=p->pNext){
+    const char *zType;
+    static const u32 mask =
+        SQLITE_DETERMINISTIC |
+        SQLITE_DIRECTONLY |
+        SQLITE_SUBTYPE |
+        SQLITE_INNOCUOUS |
+        SQLITE_FUNC_INTERNAL
+    ;
+    static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
+
+    assert( SQLITE_FUNC_ENCMASK==0x3 );
+    assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
+    assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
+    assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
+
+    if( p->xSFunc==0 ) continue;
+    if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
+     && showInternFuncs==0
+    ){
+      continue;
+    }
+    if( p->xValue!=0 ){
+      zType = "w";
+    }else if( p->xFinalize!=0 ){
+      zType = "a";
+    }else{
+      zType = "s";
+    }
+    sqlite3VdbeMultiLoad(v, 1, "sissii",
+       p->zName, isBuiltin,
+       zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
+       p->nArg,
+       (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
+    );
+  }
+}
+
+
+/*
 ** Helper subroutine for PRAGMA integrity_check:
 **
 ** Generate code to output a single-column result row with a value of the
@@ -122726,7 +126853,7 @@ static int integrityCheckResultRow(Vdbe *v){
 }
 
 /*
-** Process a pragma statement.  
+** Process a pragma statement.
 **
 ** Pragmas are of this form:
 **
@@ -122741,7 +126868,7 @@ static int integrityCheckResultRow(Vdbe *v){
 ** id and pId2 is any empty string.
 */
 SQLITE_PRIVATE void sqlite3Pragma(
-  Parse *pParse, 
+  Parse *pParse,
   Token *pId1,        /* First part of [schema.]id field */
   Token *pId2,        /* Second part of [schema.]id field, or NULL */
   Token *pValue,      /* Token for <value>, or NULL */
@@ -122769,8 +126896,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
   if( iDb<0 ) return;
   pDb = &db->aDb[iDb];
 
-  /* If the temp database has been explicitly named as part of the 
-  ** pragma, make sure it is open. 
+  /* If the temp database has been explicitly named as part of the
+  ** pragma, make sure it is open.
   */
   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
     return;
@@ -122838,7 +126965,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   }
 
   /* Register the result column names for pragmas that return results */
-  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 
+  if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
    && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
   ){
     setPragmaResultColumnNames(v, pPragma);
@@ -122846,7 +126973,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
 
   /* Jump to the appropriate pragma handler */
   switch( pPragma->ePragTyp ){
-  
+
 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   /*
   **  PRAGMA [schema.]default_cache_size
@@ -122920,7 +127047,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       ** buffer that the pager module resizes using sqlite3_realloc().
       */
       db->nextPagesize = sqlite3Atoi(zRight);
-      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
+      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
         sqlite3OomFault(db);
       }
     }
@@ -122962,7 +127089,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   **  PRAGMA [schema.]max_page_count=N
   **
   ** The first form reports the current setting for the
-  ** maximum number of pages in the database file.  The 
+  ** maximum number of pages in the database file.  The
   ** second form attempts to change this setting.  Both
   ** forms return the current setting.
   **
@@ -122976,13 +127103,19 @@ SQLITE_PRIVATE void sqlite3Pragma(
   */
   case PragTyp_PAGE_COUNT: {
     int iReg;
+    i64 x = 0;
     sqlite3CodeVerifySchema(pParse, iDb);
     iReg = ++pParse->nMem;
     if( sqlite3Tolower(zLeft[0])=='p' ){
       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
     }else{
-      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
-                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
+      if( zRight && sqlite3DecOrHexToI64(zRight,&x)==0 ){
+        if( x<0 ) x = 0;
+        else if( x>0xfffffffe ) x = 0xfffffffe;
+      }else{
+        x = 0;
+      }
+      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, (int)x);
     }
     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
     break;
@@ -123123,7 +127256,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       */
       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
-        /* When setting the auto_vacuum mode to either "full" or 
+        /* When setting the auto_vacuum mode to either "full" or
         ** "incremental", write the value of meta[6] in the database
         ** file. Before writing to meta[6], check that meta[3] indicates
         ** that this really is an auto-vacuum capable database.
@@ -123225,7 +127358,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
     if( !zRight ){
       returnSingleInt(v,
-         (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
+         (db->flags & SQLITE_CacheSpill)==0 ? 0 :
             sqlite3BtreeSetSpillSize(pDb->pBt,0));
     }else{
       int size = 1;
@@ -123399,7 +127532,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       Pager *pPager = sqlite3BtreePager(pDb->pBt);
       char *proxy_file_path = NULL;
       sqlite3_file *pFile = sqlite3PagerFile(pPager);
-      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
+      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
                            &proxy_file_path);
       returnSingleText(v, proxy_file_path);
     }else{
@@ -123407,10 +127540,10 @@ SQLITE_PRIVATE void sqlite3Pragma(
       sqlite3_file *pFile = sqlite3PagerFile(pPager);
       int res;
       if( zRight[0] ){
-        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
+        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
                                      zRight);
       } else {
-        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
+        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
                                      NULL);
       }
       if( res!=SQLITE_OK ){
@@ -123420,8 +127553,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
     }
     break;
   }
-#endif /* SQLITE_ENABLE_LOCKING_STYLE */      
-    
+#endif /* SQLITE_ENABLE_LOCKING_STYLE */
+
   /*
   **   PRAGMA [schema.]synchronous
   **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
@@ -123436,7 +127569,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       returnSingleInt(v, pDb->safety_level-1);
     }else{
       if( !db->autoCommit ){
-        sqlite3ErrorMsg(pParse, 
+        sqlite3ErrorMsg(pParse,
             "Safety level may not be changed inside a transaction");
       }else if( iDb!=1 ){
         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
@@ -123476,7 +127609,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
       }
 
-      /* Many of the flag-pragmas modify the code generated by the SQL 
+      /* Many of the flag-pragmas modify the code generated by the SQL
       ** compiler (eg. count_changes). So add an opcode to expire all
       ** compiled SQL statements after modifying a pragma value.
       */
@@ -123503,21 +127636,29 @@ SQLITE_PRIVATE void sqlite3Pragma(
   */
   case PragTyp_TABLE_INFO: if( zRight ){
     Table *pTab;
+    sqlite3CodeVerifyNamedSchema(pParse, zDb);
     pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
     if( pTab ){
-      int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
       int i, k;
       int nHidden = 0;
       Column *pCol;
       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
       pParse->nMem = 7;
-      sqlite3CodeVerifySchema(pParse, iTabDb);
       sqlite3ViewGetColumnNames(pParse, pTab);
       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
-        int isHidden = IsHiddenColumn(pCol);
-        if( isHidden && pPragma->iArg==0 ){
-          nHidden++;
-          continue;
+        int isHidden = 0;
+        if( pCol->colFlags & COLFLAG_NOINSERT ){
+          if( pPragma->iArg==0 ){
+            nHidden++;
+            continue;
+          }
+          if( pCol->colFlags & COLFLAG_VIRTUAL ){
+            isHidden = 2;  /* GENERATED ALWAYS AS ... VIRTUAL */
+          }else if( pCol->colFlags & COLFLAG_STORED ){
+            isHidden = 3;  /* GENERATED ALWAYS AS ... STORED */
+          }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
+            isHidden = 1;  /* HIDDEN */
+          }
         }
         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
           k = 0;
@@ -123526,13 +127667,13 @@ SQLITE_PRIVATE void sqlite3Pragma(
         }else{
           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
         }
-        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
+        assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );
         sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
                i-nHidden,
                pCol->zName,
                sqlite3ColumnType(pCol,""),
                pCol->notNull ? 1 : 0,
-               pCol->pDflt ? pCol->pDflt->u.zToken : 0,
+               pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,
                k,
                isHidden);
       }
@@ -123664,16 +127805,16 @@ SQLITE_PRIVATE void sqlite3Pragma(
     int i;
     HashElem *j;
     FuncDef *p;
-    pParse->nMem = 2;
+    int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
+    pParse->nMem = 6;
     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
-        if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue;
-        sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
+        pragmaFunclistLine(v, p, 1, showInternFunc);
       }
     }
     for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
       p = (FuncDef*)sqliteHashData(j);
-      sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
+      pragmaFunclistLine(v, p, 0, showInternFunc);
     }
   }
   break;
@@ -123710,7 +127851,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       pFK = pTab->pFKey;
       if( pFK ){
         int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
-        int i = 0; 
+        int i = 0;
         pParse->nMem = 8;
         sqlite3CodeVerifySchema(pParse, iTabDb);
         while(pFK){
@@ -123759,7 +127900,6 @@ SQLITE_PRIVATE void sqlite3Pragma(
     regRow = ++pParse->nMem;
     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
     while( k ){
-      int iTabDb;
       if( zRight ){
         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
         k = 0;
@@ -123768,23 +127908,24 @@ SQLITE_PRIVATE void sqlite3Pragma(
         k = sqliteHashNext(k);
       }
       if( pTab==0 || pTab->pFKey==0 ) continue;
-      iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
-      sqlite3CodeVerifySchema(pParse, iTabDb);
-      sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
+      iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
+      zDb = db->aDb[iDb].zDbSName;
+      sqlite3CodeVerifySchema(pParse, iDb);
+      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
-      sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
+      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
       sqlite3VdbeLoadString(v, regResult, pTab->zName);
       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
         if( pParent==0 ) continue;
         pIdx = 0;
-        sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
+        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
         if( x==0 ){
           if( pIdx==0 ){
-            sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
+            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
           }else{
-            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
+            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
           }
         }else{
@@ -123802,13 +127943,13 @@ SQLITE_PRIVATE void sqlite3Pragma(
         aiCols = 0;
         if( pParent ){
           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
-          assert( x==0 );
+          assert( x==0 || db->mallocFailed );
         }
         addrOk = sqlite3VdbeMakeLabel(pParse);
 
         /* Generate code to read the child key values into registers
-        ** regRow..regRow+n. If any of the child key values are NULL, this 
-        ** row cannot cause an FK violation. Jump directly to addrOk in 
+        ** regRow..regRow+n. If any of the child key values are NULL, this
+        ** row cannot cause an FK violation. Jump directly to addrOk in
         ** this case. */
         for(j=0; j<pFK->nCol; j++){
           int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
@@ -123827,7 +127968,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
           int jmp = sqlite3VdbeCurrentAddr(v)+2;
           sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
           sqlite3VdbeGoto(v, addrOk);
-          assert( pFK->nCol==1 );
+          assert( pFK->nCol==1 || db->mallocFailed );
         }
 
         /* Generate code to report an FK violation to the caller. */
@@ -123873,13 +128014,26 @@ SQLITE_PRIVATE void sqlite3Pragma(
   **
   ** Verify the integrity of the database.
   **
-  ** The "quick_check" is reduced version of 
+  ** The "quick_check" is reduced version of
   ** integrity_check designed to detect most database corruption
   ** without the overhead of cross-checking indexes.  Quick_check
   ** is linear time wherease integrity_check is O(NlogN).
+  **
+  ** The maximum nubmer of errors is 100 by default.  A different default
+  ** can be specified using a numeric parameter N.
+  **
+  ** Or, the parameter N can be the name of a table.  In that case, only
+  ** the one table named is verified.  The freelist is only verified if
+  ** the named table is "sqlite_schema" (or one of its aliases).
+  **
+  ** All schemas are checked by default.  To check just a single
+  ** schema, use the form:
+  **
+  **      PRAGMA schema.integrity_check;
   */
   case PragTyp_INTEGRITY_CHECK: {
     int i, j, addr, mxErr;
+    Table *pObjTab = 0;     /* Check only this one table, if not NULL */
 
     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
 
@@ -123902,9 +128056,13 @@ SQLITE_PRIVATE void sqlite3Pragma(
     /* Set the maximum error count */
     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
     if( zRight ){
-      sqlite3GetInt32(zRight, &mxErr);
-      if( mxErr<=0 ){
-        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
+      if( sqlite3GetInt32(zRight, &mxErr) ){
+        if( mxErr<=0 ){
+          mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
+        }
+      }else{
+        pObjTab = sqlite3LocateTable(pParse, 0, zRight,
+                      iDb>=0 ? db->aDb[iDb].zDbSName : 0);
       }
     }
     sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
@@ -123933,15 +128091,21 @@ SQLITE_PRIVATE void sqlite3Pragma(
         Table *pTab = sqliteHashData(x);  /* Current table */
         Index *pIdx;                      /* An index on pTab */
         int nIdx;                         /* Number of indexes on pTab */
+        if( pObjTab && pObjTab!=pTab ) continue;
         if( HasRowid(pTab) ) cnt++;
         for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
         if( nIdx>mxIdx ) mxIdx = nIdx;
       }
+      if( cnt==0 ) continue;
+      if( pObjTab ) cnt++;
       aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
       if( aRoot==0 ) break;
-      for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
+      cnt = 0;
+      if( pObjTab ) aRoot[++cnt] = 0;
+      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
         Table *pTab = sqliteHashData(x);
         Index *pIdx;
+        if( pObjTab && pObjTab!=pTab ) continue;
         if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
           aRoot[++cnt] = pIdx->tnum;
@@ -123975,11 +128139,12 @@ SQLITE_PRIVATE void sqlite3Pragma(
         int r1 = -1;
 
         if( pTab->tnum<1 ) continue;  /* Skip VIEWs or VIRTUAL TABLEs */
+        if( pObjTab && pObjTab!=pTab ) continue;
         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
                                    1, 0, &iDataCur, &iIdxCur);
         /* reg[7] counts the number of entries in the table.
-        ** reg[8+i] counts the number of entries in the i-th index 
+        ** reg[8+i] counts the number of entries in the i-th index
         */
         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
@@ -123991,7 +128156,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
         if( !isQuick ){
           /* Sanity check on record header decoding */
-          sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
+          sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
         }
         /* Verify that all NOT NULL columns really are NOT NULL */
@@ -124001,7 +128166,9 @@ SQLITE_PRIVATE void sqlite3Pragma(
           if( j==pTab->iPKey ) continue;
           if( pTab->aCol[j].notNull==0 ) continue;
           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
-          sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+          if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
+            sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
+          }
           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
                               pTab->aCol[j].zName);
@@ -124021,7 +128188,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
             for(k=pCheck->nExpr-1; k>0; k--){
               sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
             }
-            sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, 
+            sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
                 SQLITE_JUMPIFNULL);
             sqlite3VdbeResolveLabel(v, addrCkFault);
             pParse->iSelfTab = 0;
@@ -124083,7 +128250,6 @@ SQLITE_PRIVATE void sqlite3Pragma(
         }
         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
         sqlite3VdbeJumpHere(v, loopTop-1);
-#ifndef SQLITE_OMIT_BTREECOUNT
         if( !isQuick ){
           sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
@@ -124097,8 +128263,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
             sqlite3VdbeJumpHere(v, addr);
           }
         }
-#endif /* SQLITE_OMIT_BTREECOUNT */
-      } 
+      }
     }
     {
       static const int iLn = VDBE_OFFSET_LINENO(2);
@@ -124140,7 +128305,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   ** encoding that will be used for the main database file if a new file
   ** is created. If an existing main database file is opened, then the
   ** default text encoding for the existing database is used.
-  ** 
+  **
   ** In all cases new databases created using the ATTACH command are
   ** created to use the same default text encoding as the main database. If
   ** the main database has not been initialized and/or created when ATTACH
@@ -124178,14 +128343,12 @@ SQLITE_PRIVATE void sqlite3Pragma(
       ** will be overwritten when the schema is next loaded. If it does not
       ** already exists, it will be created to use the new encoding value.
       */
-      if( 
-        !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
-        DbHasProperty(db, 0, DB_Empty) 
-      ){
+      if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
-            SCHEMA_ENC(db) = ENC(db) =
-                pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
+            u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
+            SCHEMA_ENC(db) = enc;
+            sqlite3SetTextEncoding(db, enc);
             break;
           }
         }
@@ -124248,6 +128411,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       aOp[1].p1 = iDb;
       aOp[1].p2 = iCookie;
       aOp[1].p3 = sqlite3Atoi(zRight);
+      aOp[1].p5 = 1;
     }else{
       /* Read the specified cookie value */
       static const VdbeOpList readCookie[] = {
@@ -124324,8 +128488,8 @@ SQLITE_PRIVATE void sqlite3Pragma(
     if( zRight ){
       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
     }
-    returnSingleInt(v, 
-       db->xWalCallback==sqlite3WalDefaultHook ? 
+    returnSingleInt(v,
+       db->xWalCallback==sqlite3WalDefaultHook ?
            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
   }
   break;
@@ -124365,7 +128529,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   **    0x0002    Run ANALYZE on tables that might benefit.  On by default.
   **              See below for additional information.
   **
-  **    0x0004    (Not yet implemented) Record usage and performance 
+  **    0x0004    (Not yet implemented) Record usage and performance
   **              information from the current session in the
   **              database file so that it will be available to "optimize"
   **              pragmas run by future database connections.
@@ -124376,7 +128540,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   ** The default MASK is and always shall be 0xfffe.  0xfffe means perform all
   ** of the optimizations listed above except Debug Mode, including new
   ** optimizations that have not yet been invented.  If new optimizations are
-  ** ever added that should be off by default, those off-by-default 
+  ** ever added that should be off by default, those off-by-default
   ** optimizations will have bitmasks of 0x10000 or larger.
   **
   ** DETERMINATION OF WHEN TO RUN ANALYZE
@@ -124437,7 +128601,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
         }
         if( szThreshold ){
           sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
-          sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, 
+          sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
                          sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
           VdbeCoverage(v);
         }
@@ -124495,6 +128659,27 @@ SQLITE_PRIVATE void sqlite3Pragma(
   }
 
   /*
+  **   PRAGMA hard_heap_limit
+  **   PRAGMA hard_heap_limit = N
+  **
+  ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
+  ** limit.  The hard heap limit can be activated or lowered by this
+  ** pragma, but not raised or deactivated.  Only the
+  ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
+  ** the hard heap limit.  This allows an application to set a heap limit
+  ** constraint that cannot be relaxed by an untrusted SQL script.
+  */
+  case PragTyp_HARD_HEAP_LIMIT: {
+    sqlite3_int64 N;
+    if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
+      sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
+      if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
+    }
+    returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
+    break;
+  }
+
+  /*
   **   PRAGMA threads
   **   PRAGMA threads = N
   **
@@ -124513,6 +128698,25 @@ SQLITE_PRIVATE void sqlite3Pragma(
     break;
   }
 
+  /*
+  **   PRAGMA analysis_limit
+  **   PRAGMA analysis_limit = N
+  **
+  ** Configure the maximum number of rows that ANALYZE will examine
+  ** in each index that it looks at.  Return the new limit.
+  */
+  case PragTyp_ANALYSIS_LIMIT: {
+    sqlite3_int64 N;
+    if( zRight
+     && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
+     && N>=0
+    ){
+      db->nAnalysisLimit = (int)(N&0x7fffffff);
+    }
+    returnSingleInt(v, db->nAnalysisLimit);
+    break;
+  }
+
 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   /*
   ** Report the current state of file logs for all databases
@@ -124531,7 +128735,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
       pBt = db->aDb[i].pBt;
       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
         zState = "closed";
-      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, 
+      }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
          zState = azLockName[j];
       }
@@ -124541,59 +128745,11 @@ SQLITE_PRIVATE void sqlite3Pragma(
   }
 #endif
 
-#ifdef SQLITE_HAS_CODEC
-  /* Pragma        iArg
-  ** ----------   ------
-  **  key           0
-  **  rekey         1
-  **  hexkey        2
-  **  hexrekey      3
-  **  textkey       4
-  **  textrekey     5
-  */
-  case PragTyp_KEY: {
-    if( zRight ){
-      char zBuf[40];
-      const char *zKey = zRight;
-      int n;
-      if( pPragma->iArg==2 || pPragma->iArg==3 ){
-        u8 iByte;
-        int i;
-        for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){
-          iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
-          if( (i&1)!=0 ) zBuf[i/2] = iByte;
-        }
-        zKey = zBuf;
-        n = i/2;
-      }else{
-        n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
-      }
-      if( (pPragma->iArg & 1)==0 ){
-        rc = sqlite3_key_v2(db, zDb, zKey, n);
-      }else{
-        rc = sqlite3_rekey_v2(db, zDb, zKey, n);
-      }
-      if( rc==SQLITE_OK && n!=0 ){
-        sqlite3VdbeSetNumCols(v, 1);
-        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC);
-        returnSingleText(v, "ok");
-      }
-    }
-    break;
-  }
-#endif
-#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
+#if defined(SQLITE_ENABLE_CEROD)
   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
-#ifdef SQLITE_HAS_CODEC
-    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
-      sqlite3_activate_see(&zRight[4]);
-    }
-#endif
-#ifdef SQLITE_ENABLE_CEROD
     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
       sqlite3_activate_cerod(&zRight[6]);
     }
-#endif
   }
   break;
 #endif
@@ -124603,7 +128759,7 @@ SQLITE_PRIVATE void sqlite3Pragma(
   /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
   ** purpose is to execute assert() statements to verify that if the
   ** PragFlg_NoColumns1 flag is set and the caller specified an argument
-  ** to the PRAGMA, the implementation has not added any OP_ResultRow 
+  ** to the PRAGMA, the implementation has not added any OP_ResultRow
   ** instructions to the VM.  */
   if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
     sqlite3VdbeVerifyNoResultRow(v);
@@ -124634,7 +128790,7 @@ struct PragmaVtabCursor {
   char *azArg[2];           /* Value of the argument and schema */
 };
 
-/* 
+/*
 ** Pragma virtual table module xConnect method.
 */
 static int pragmaVtabConnect(
@@ -124696,7 +128852,7 @@ static int pragmaVtabConnect(
   return rc;
 }
 
-/* 
+/*
 ** Pragma virtual table module xDisconnect method.
 */
 static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
@@ -124794,11 +128950,11 @@ static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
   return rc;
 }
 
-/* 
+/*
 ** Pragma virtual table module xFilter method.
 */
 static int pragmaVtabFilter(
-  sqlite3_vtab_cursor *pVtabCursor, 
+  sqlite3_vtab_cursor *pVtabCursor,
   int idxNum, const char *idxStr,
   int argc, sqlite3_value **argv
 ){
@@ -124853,11 +129009,11 @@ static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
 }
 
 /* The xColumn method simply returns the corresponding column from
-** the PRAGMA.  
+** the PRAGMA.
 */
 static int pragmaVtabColumn(
-  sqlite3_vtab_cursor *pVtabCursor, 
-  sqlite3_context *ctx, 
+  sqlite3_vtab_cursor *pVtabCursor,
+  sqlite3_context *ctx,
   int i
 ){
   PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
@@ -124870,7 +129026,7 @@ static int pragmaVtabColumn(
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** Pragma virtual table module xRowid method.
 */
 static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
@@ -125021,7 +129177,7 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
   assert( argc==5 );
   UNUSED_PARAMETER2(NotUsed, argc);
   assert( sqlite3_mutex_held(db->mutex) );
-  DbClearProperty(db, iDb, DB_Empty);
+  db->mDbFlags |= DBFLAG_EncodingFixed;
   pData->nInitRow++;
   if( db->mallocFailed ){
     corruptSchema(pData, argv[1], 0);
@@ -125045,7 +129201,13 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
 
     assert( db->init.busy );
     db->init.iDb = iDb;
-    db->init.newTnum = sqlite3Atoi(argv[3]);
+    if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
+     || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
+    ){
+      if( sqlite3Config.bExtraSchemaChecks ){
+        corruptSchema(pData, argv[1], "invalid rootpage");
+      }
+    }
     db->init.orphanTrigger = 0;
     db->init.azInit = argv;
     pStmt = 0;
@@ -125078,12 +129240,17 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char
     */
     Index *pIndex;
     pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
-    if( pIndex==0
-     || sqlite3GetInt32(argv[3],&pIndex->tnum)==0
+    if( pIndex==0 ){
+      corruptSchema(pData, argv[1], "orphan index");
+    }else
+    if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
      || pIndex->tnum<2
+     || pIndex->tnum>pData->mxPage
      || sqlite3IndexHasDuplicateRootPage(pIndex)
     ){
-      corruptSchema(pData, argv[1], pIndex?"invalid rootpage":"orphan index");
+      if( sqlite3Config.bExtraSchemaChecks ){
+        corruptSchema(pData, argv[1], "invalid rootpage");
+      }
     }
   }
   return 0;
@@ -125107,8 +129274,9 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   char const *azArg[6];
   int meta[5];
   InitData initData;
-  const char *zMasterName;
+  const char *zSchemaTabName;
   int openedTransaction = 0;
+  int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
 
   assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
   assert( iDb>=0 && iDb<db->nDb );
@@ -125118,13 +129286,13 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
 
   db->init.busy = 1;
 
-  /* Construct the in-memory representation schema tables (sqlite_master or
-  ** sqlite_temp_master) by invoking the parser directly.  The appropriate
+  /* Construct the in-memory representation schema tables (sqlite_schema or
+  ** sqlite_temp_schema) by invoking the parser directly.  The appropriate
   ** table name will be inserted automatically by the parser so we can just
   ** use the abbreviation "x" here.  The parser will also automatically tag
   ** the schema table as read-only. */
   azArg[0] = "table";
-  azArg[1] = zMasterName = SCHEMA_TABLE(iDb);
+  azArg[1] = zSchemaTabName = SCHEMA_TABLE(iDb);
   azArg[2] = azArg[1];
   azArg[3] = "1";
   azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
@@ -125136,7 +129304,9 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   initData.pzErrMsg = pzErrMsg;
   initData.mInitFlags = mFlags;
   initData.nInitRow = 0;
+  initData.mxPage = 0;
   sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
+  db->mDbFlags &= mask;
   if( initData.rc ){
     rc = initData.rc;
     goto error_out;
@@ -125153,10 +129323,10 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   }
 
   /* If there is not already a read-only (or read-write) transaction opened
-  ** on the b-tree database, open one now. If a transaction is opened, it 
+  ** on the b-tree database, open one now. If a transaction is opened, it
   ** will be closed before this function returns.  */
   sqlite3BtreeEnter(pDb->pBt);
-  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
+  if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
     if( rc!=SQLITE_OK ){
       sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
@@ -125196,27 +129366,25 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   ** as sqlite3.enc.
   */
   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
-    if( iDb==0 ){
-#ifndef SQLITE_OMIT_UTF16
+    if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
       u8 encoding;
+#ifndef SQLITE_OMIT_UTF16
       /* If opening the main database, set ENC(db). */
       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
       if( encoding==0 ) encoding = SQLITE_UTF8;
-      ENC(db) = encoding;
 #else
-      ENC(db) = SQLITE_UTF8;
+      encoding = SQLITE_UTF8;
 #endif
+      sqlite3SetTextEncoding(db, encoding);
     }else{
       /* If opening an attached database, the encoding much match ENC(db) */
-      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
+      if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
             " text encoding as main database");
         rc = SQLITE_ERROR;
         goto initone_error_out;
       }
     }
-  }else{
-    DbSetProperty(db, iDb, DB_Empty);
   }
   pDb->pSchema->enc = ENC(db);
 
@@ -125259,11 +129427,12 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   /* Read the schema information out of the schema tables
   */
   assert( db->init.busy );
+  initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
   {
     char *zSql;
-    zSql = sqlite3MPrintf(db, 
+    zSql = sqlite3MPrintf(db,
         "SELECT*FROM\"%w\".%s ORDER BY rowid",
-        db->aDb[iDb].zDbSName, zMasterName);
+        db->aDb[iDb].zDbSName, zSchemaTabName);
 #ifndef SQLITE_OMIT_AUTHORIZATION
     {
       sqlite3_xauth xAuth;
@@ -125289,11 +129458,11 @@ SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFl
   }
   if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
     /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
-    ** the schema loaded, even if errors occurred. In this situation the 
+    ** the schema loaded, even if errors occurred. In this situation the
     ** current sqlite3_prepare() operation will fail, but the following one
     ** will attempt to compile the supplied statement against whatever subset
     ** of the schema was loaded before the error occurred. The primary
-    ** purpose of this is to allow access to the sqlite_master table
+    ** purpose of this is to allow access to the sqlite_schema table
     ** even when its contents have been corrupted.
     */
     DbSetProperty(db, iDb, DB_SchemaLoaded);
@@ -125328,13 +129497,12 @@ error_out:
 ** error occurs, write an error message into *pzErrMsg.
 **
 ** After a database is initialized, the DB_SchemaLoaded bit is set
-** bit is set in the flags field of the Db structure. If the database
-** file was of zero-length, then the DB_Empty flag is also set.
+** bit is set in the flags field of the Db structure.
 */
 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
   int i, rc;
   int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
-  
+
   assert( sqlite3_mutex_held(db->mutex) );
   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
   assert( db->init.busy==0 );
@@ -125399,9 +129567,9 @@ static void schemaIsValid(Parse *pParse){
     if( pBt==0 ) continue;
 
     /* If there is not already a read-only (or read-write) transaction opened
-    ** on the b-tree database, open one now. If a transaction is opened, it 
+    ** on the b-tree database, open one now. If a transaction is opened, it
     ** will be closed immediately after reading the meta-value. */
-    if( !sqlite3BtreeIsInReadTrans(pBt) ){
+    if( sqlite3BtreeTxnState(pBt)==SQLITE_TXN_NONE ){
       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
         sqlite3OomFault(db);
@@ -125410,7 +129578,7 @@ static void schemaIsValid(Parse *pParse){
       openedTransaction = 1;
     }
 
-    /* Read the schema cookie from the database. If it does not match the 
+    /* Read the schema cookie from the database. If it does not match the
     ** value stored as part of the in-memory schema representation,
     ** set Parse.rc to SQLITE_SCHEMA. */
     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
@@ -125435,17 +129603,18 @@ static void schemaIsValid(Parse *pParse){
 ** attached database is returned.
 */
 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
-  int i = -1000000;
+  int i = -32768;
 
-  /* If pSchema is NULL, then return -1000000. This happens when code in 
+  /* If pSchema is NULL, then return -32768. This happens when code in
   ** expr.c is trying to resolve a reference to a transient table (i.e. one
-  ** created by a sub-select). In this case the return value of this 
+  ** created by a sub-select). In this case the return value of this
   ** function should never be used.
   **
-  ** We return -1000000 instead of the more usual -1 simply because using
-  ** -1000000 as the incorrect index into db->aDb[] is much 
+  ** We return -32768 instead of the more usual -1 simply because using
+  ** -32768 as the incorrect index into db->aDb[] is much
   ** more likely to cause a segfault than -1 (of course there are assert()
-  ** statements too, but it never hurts to play the odds).
+  ** statements too, but it never hurts to play the odds) and
+  ** -32768 will still fit into a 16-bit signed integer.
   */
   assert( sqlite3_mutex_held(db->mutex) );
   if( pSchema ){
@@ -125461,15 +129630,31 @@ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
 }
 
 /*
+** Deallocate a single AggInfo object
+*/
+static void agginfoFree(sqlite3 *db, AggInfo *p){
+  sqlite3DbFree(db, p->aCol);
+  sqlite3DbFree(db, p->aFunc);
+  sqlite3DbFree(db, p);
+}
+
+/*
 ** Free all memory allocations in the pParse object
 */
 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
   sqlite3 *db = pParse->db;
+  AggInfo *pThis = pParse->pAggList;
+  while( pThis ){
+    AggInfo *pNext = pThis->pNext;
+    agginfoFree(db, pThis);
+    pThis = pNext;
+  }
   sqlite3DbFree(db, pParse->aLabel);
   sqlite3ExprListDelete(db, pParse->pConstExpr);
   if( db ){
     assert( db->lookaside.bDisable >= pParse->disableLookaside );
     db->lookaside.bDisable -= pParse->disableLookaside;
+    db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
   }
   pParse->disableLookaside = 0;
 }
@@ -125503,7 +129688,7 @@ static int sqlite3Prepare(
   */
   if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
     sParse.disableLookaside++;
-    db->lookaside.bDisable++;
+    DisableLookaside;
   }
   sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
 
@@ -125522,24 +129707,26 @@ static int sqlite3Prepare(
   ** This thread is currently holding mutexes on all Btrees (because
   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
   ** is not possible for another thread to start a new schema change
-  ** while this routine is running.  Hence, we do not need to hold 
-  ** locks on the schema, we just need to make sure nobody else is 
+  ** while this routine is running.  Hence, we do not need to hold
+  ** locks on the schema, we just need to make sure nobody else is
   ** holding them.
   **
   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
   ** but it does *not* override schema lock detection, so this all still
   ** works even if READ_UNCOMMITTED is set.
   */
-  for(i=0; i<db->nDb; i++) {
-    Btree *pBt = db->aDb[i].pBt;
-    if( pBt ){
-      assert( sqlite3BtreeHoldsMutex(pBt) );
-      rc = sqlite3BtreeSchemaLocked(pBt);
-      if( rc ){
-        const char *zDb = db->aDb[i].zDbSName;
-        sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
-        testcase( db->flags & SQLITE_ReadUncommit );
-        goto end_prepare;
+  if( !db->noSharedCache ){
+    for(i=0; i<db->nDb; i++) {
+      Btree *pBt = db->aDb[i].pBt;
+      if( pBt ){
+        assert( sqlite3BtreeHoldsMutex(pBt) );
+        rc = sqlite3BtreeSchemaLocked(pBt);
+        if( rc ){
+          const char *zDb = db->aDb[i].zDbSName;
+          sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
+          testcase( db->flags & SQLITE_ReadUncommit );
+          goto end_prepare;
+        }
       }
     }
   }
@@ -125570,48 +129757,24 @@ static int sqlite3Prepare(
   }
   assert( 0==sParse.nQueryLoop );
 
-  if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
+  if( sParse.rc==SQLITE_DONE ){
+    sParse.rc = SQLITE_OK;
+  }
   if( sParse.checkSchema ){
     schemaIsValid(&sParse);
   }
-  if( db->mallocFailed ){
-    sParse.rc = SQLITE_NOMEM_BKPT;
-  }
   if( pzTail ){
     *pzTail = sParse.zTail;
   }
-  rc = sParse.rc;
-
-#ifndef SQLITE_OMIT_EXPLAIN
-  /* Justification for the ALWAYS(): The only way for rc to be SQLITE_OK and
-  ** sParse.pVdbe to be NULL is if the input SQL is an empty string, but in
-  ** that case, sParse.explain will be false. */
-  if( sParse.explain && rc==SQLITE_OK && ALWAYS(sParse.pVdbe) ){
-    static const char * const azColName[] = {
-       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
-       "id", "parent", "notused", "detail"
-    };
-    int iFirst, mx;
-    if( sParse.explain==2 ){
-      sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
-      iFirst = 8;
-      mx = 12;
-    }else{
-      sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
-      iFirst = 0;
-      mx = 8;
-    }
-    for(i=iFirst; i<mx; i++){
-      sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
-                            azColName[i], SQLITE_STATIC);
-    }
-  }
-#endif
 
   if( db->init.busy==0 ){
     sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
   }
-  if( rc!=SQLITE_OK || db->mallocFailed ){
+  if( db->mallocFailed ){
+    sParse.rc = SQLITE_NOMEM_BKPT;
+  }
+  rc = sParse.rc;
+  if( rc!=SQLITE_OK ){
     if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe);
     assert(!(*ppStmt));
   }else{
@@ -125669,6 +129832,7 @@ static int sqlite3LockAndPrepare(
   sqlite3BtreeLeaveAll(db);
   rc = sqlite3ApiExit(db, rc);
   assert( (rc&db->errMask)==rc );
+  db->busyHandler.nBusy = 0;
   sqlite3_mutex_leave(db->mutex);
   return rc;
 }
@@ -125679,7 +129843,7 @@ static int sqlite3LockAndPrepare(
 **
 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
 ** if the statement cannot be recompiled because another connection has
-** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
+** locked the sqlite3_schema table, return SQLITE_LOCKED. If any other error
 ** occurs, return SQLITE_SCHEMA.
 */
 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
@@ -125780,7 +129944,7 @@ SQLITE_API int sqlite3_prepare_v3(
 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
 */
 static int sqlite3Prepare16(
-  sqlite3 *db,              /* Database handle. */ 
+  sqlite3 *db,              /* Database handle. */
   const void *zSql,         /* UTF-16 encoded SQL statement. */
   int nBytes,               /* Length of zSql in bytes. */
   u32 prepFlags,            /* Zero or more SQLITE_PREPARE_* flags */
@@ -125823,7 +129987,7 @@ static int sqlite3Prepare16(
     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
   }
-  sqlite3DbFree(db, zSql8); 
+  sqlite3DbFree(db, zSql8);
   rc = sqlite3ApiExit(db, rc);
   sqlite3_mutex_leave(db->mutex);
   return rc;
@@ -125838,7 +130002,7 @@ static int sqlite3Prepare16(
 ** occurs.
 */
 SQLITE_API int sqlite3_prepare16(
-  sqlite3 *db,              /* Database handle. */ 
+  sqlite3 *db,              /* Database handle. */
   const void *zSql,         /* UTF-16 encoded SQL statement. */
   int nBytes,               /* Length of zSql in bytes. */
   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
@@ -125850,7 +130014,7 @@ SQLITE_API int sqlite3_prepare16(
   return rc;
 }
 SQLITE_API int sqlite3_prepare16_v2(
-  sqlite3 *db,              /* Database handle. */ 
+  sqlite3 *db,              /* Database handle. */
   const void *zSql,         /* UTF-16 encoded SQL statement. */
   int nBytes,               /* Length of zSql in bytes. */
   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
@@ -125862,7 +130026,7 @@ SQLITE_API int sqlite3_prepare16_v2(
   return rc;
 }
 SQLITE_API int sqlite3_prepare16_v3(
-  sqlite3 *db,              /* Database handle. */ 
+  sqlite3 *db,              /* Database handle. */
   const void *zSql,         /* UTF-16 encoded SQL statement. */
   int nBytes,               /* Length of zSql in bytes. */
   unsigned int prepFlags,   /* Zero or more SQLITE_PREPARE_* flags */
@@ -125898,20 +130062,6 @@ SQLITE_API int sqlite3_prepare16_v3(
 /* #include "sqliteInt.h" */
 
 /*
-** Trace output macros
-*/
-#if SELECTTRACE_ENABLED
-/***/ int sqlite3SelectTrace = 0;
-# define SELECTTRACE(K,P,S,X)  \
-  if(sqlite3SelectTrace&(K))   \
-    sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
-    sqlite3DebugPrintf X
-#else
-# define SELECTTRACE(K,P,S,X)
-#endif
-
-
-/*
 ** An instance of the following object is used to record information about
 ** how to process the DISTINCT keyword, to simplify passing that information
 ** into the selectInnerLoop() routine.
@@ -125967,7 +130117,10 @@ struct SortCtx {
 
 /*
 ** Delete all the content of a Select structure.  Deallocate the structure
-** itself only if bFree is true.
+** itself depending on the value of bFree
+**
+** If bFree==1, call sqlite3DbFree() on the p object.
+** If bFree==0, Leave the first Select object unfreed
 */
 static void clearSelect(sqlite3 *db, Select *p, int bFree){
   while( p ){
@@ -125983,7 +130136,6 @@ static void clearSelect(sqlite3 *db, Select *p, int bFree){
     if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
       sqlite3WindowListDelete(db, p->pWinDefn);
     }
-    assert( p->pWin==0 );
 #endif
     if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
     if( bFree ) sqlite3DbFreeNN(db, p);
@@ -125998,6 +130150,7 @@ static void clearSelect(sqlite3 *db, Select *p, int bFree){
 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
   pDest->eDest = (u8)eDest;
   pDest->iSDParm = iParm;
+  pDest->iSDParm2 = 0;
   pDest->zAffSdst = 0;
   pDest->iSdst = 0;
   pDest->nSdst = 0;
@@ -126019,9 +130172,9 @@ SQLITE_PRIVATE Select *sqlite3SelectNew(
   u32 selFlags,         /* Flag parameters, such as SF_Distinct */
   Expr *pLimit          /* LIMIT value.  NULL means not used */
 ){
-  Select *pNew;
+  Select *pNew, *pAllocated;
   Select standin;
-  pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
+  pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
   if( pNew==0 ){
     assert( pParse->db->mallocFailed );
     pNew = &standin;
@@ -126055,12 +130208,11 @@ SQLITE_PRIVATE Select *sqlite3SelectNew(
 #endif
   if( pParse->db->mallocFailed ) {
     clearSelect(pParse->db, pNew, pNew!=&standin);
-    pNew = 0;
+    pAllocated = 0;
   }else{
     assert( pNew->pSrc!=0 || pParse->nErr>0 );
   }
-  assert( pNew!=&standin );
-  return pNew;
+  return pAllocated;
 }
 
 
@@ -126122,7 +130274,7 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p
   for(i=0; i<3 && apAll[i]; i++){
     p = apAll[i];
     for(j=0; j<ArraySize(aKeyword); j++){
-      if( p->n==aKeyword[j].nChar 
+      if( p->n==aKeyword[j].nChar
           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
         jointype |= aKeyword[j].code;
         break;
@@ -126144,9 +130296,9 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p
     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
        "%T %T%s%T", pA, pB, zSp, pC);
     jointype = JT_INNER;
-  }else if( (jointype & JT_OUTER)!=0 
+  }else if( (jointype & JT_OUTER)!=0
          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
-    sqlite3ErrorMsg(pParse, 
+    sqlite3ErrorMsg(pParse,
       "RIGHT and FULL OUTER JOINs are not currently supported");
     jointype = JT_INNER;
   }
@@ -126159,15 +130311,17 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p
 */
 static int columnIndex(Table *pTab, const char *zCol){
   int i;
-  for(i=0; i<pTab->nCol; i++){
-    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
+  u8 h = sqlite3StrIHash(zCol);
+  Column *pCol;
+  for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
+    if( pCol->hName==h && sqlite3StrICmp(pCol->zName, zCol)==0 ) return i;
   }
   return -1;
 }
 
 /*
 ** Search the first N tables in pSrc, from left to right, looking for a
-** table that has a column named zCol.  
+** table that has a column named zCol.
 **
 ** When found, set *piTab and *piCol to the table index and column index
 ** of the matching column and return TRUE.
@@ -126179,7 +130333,8 @@ static int tableAndColumnIndex(
   int N,               /* Number of tables in pSrc->a[] to search */
   const char *zCol,    /* Name of the column we are looking for */
   int *piTab,          /* Write index of pSrc->a[] here */
-  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
+  int *piCol,          /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
+  int bIgnoreHidden    /* True to ignore hidden columns */
 ){
   int i;               /* For looping over tables in pSrc */
   int iCol;            /* Index of column matching zCol */
@@ -126187,7 +130342,9 @@ static int tableAndColumnIndex(
   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
   for(i=0; i<N; i++){
     iCol = columnIndex(pSrc->a[i].pTab, zCol);
-    if( iCol>=0 ){
+    if( iCol>=0
+     && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
+    ){
       if( piTab ){
         *piTab = i;
         *piCol = iCol;
@@ -126205,7 +130362,7 @@ static int tableAndColumnIndex(
 **
 **    (tab1.col1 = tab2.col2)
 **
-** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
+** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
 ** column iColRight of tab2.
 */
@@ -126268,7 +130425,7 @@ static void addWhereTerm(
 ** after the t1 loop and rows with t1.x!=5 will never appear in
 ** the output, which is incorrect.
 */
-static void setJoinExpr(Expr *p, int iTable){
+SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
   while( p ){
     ExprSetProperty(p, EP_FromJoin);
     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
@@ -126277,15 +130434,15 @@ static void setJoinExpr(Expr *p, int iTable){
     if( p->op==TK_FUNCTION && p->x.pList ){
       int i;
       for(i=0; i<p->x.pList->nExpr; i++){
-        setJoinExpr(p->x.pList->a[i].pExpr, iTable);
+        sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
       }
     }
-    setJoinExpr(p->pLeft, iTable);
+    sqlite3SetJoinExpr(p->pLeft, iTable);
     p = p->pRight;
-  } 
+  }
 }
 
-/* Undo the work of setJoinExpr().  In the expression tree p, convert every
+/* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
 ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
 ** an ordinary term that omits the EP_FromJoin mark.
 **
@@ -126305,7 +130462,7 @@ static void unsetJoinExpr(Expr *p, int iTable){
     }
     unsetJoinExpr(p->pLeft, iTable);
     p = p->pRight;
-  } 
+  }
 }
 
 /*
@@ -126352,10 +130509,11 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){
         int iLeft;     /* Matching left table */
         int iLeftCol;  /* Matching column in the left table */
 
+        if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
         zName = pRightTab->aCol[j].zName;
-        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
+        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){
           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
-                       isOuter, &p->pWhere);
+                isOuter, &p->pWhere);
         }
       }
     }
@@ -126372,13 +130530,13 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){
     ** an AND operator.
     */
     if( pRight->pOn ){
-      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
+      if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
       p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
       pRight->pOn = 0;
     }
 
     /* Create extra terms on the WHERE clause for each column named
-    ** in the USING clause.  Example: If the two tables to be joined are 
+    ** in the USING clause.  Example: If the two tables to be joined are
     ** A and B and the USING clause names X, Y, and Z, then add this
     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
     ** Report an error if any column mentioned in the USING clause is
@@ -126395,7 +130553,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){
         zName = pList->a[j].zName;
         iRightCol = columnIndex(pRightTab, zName);
         if( iRightCol<0
-         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
+         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0)
         ){
           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
             "not present in both tables", zName);
@@ -126499,7 +130657,7 @@ static void pushOntoSorter(
   **       case regData==regOrigData.
   **   (3) Some output columns are omitted from the sort record due to
   **       the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
-  **       SQLITE_ECEL_OMITREF optimization, or due to the 
+  **       SQLITE_ECEL_OMITREF optimization, or due to the
   **       SortCtx.pDeferredRowLoad optimiation.  In any of these cases
   **       regOrigData is 0 to prevent this routine from trying to copy
   **       values that might not yet exist.
@@ -126537,7 +130695,7 @@ static void pushOntoSorter(
     pParse->nMem += pSort->nOBSat;
     nKey = nExpr - pSort->nOBSat + bSeq;
     if( bSeq ){
-      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
+      addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
     }else{
       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
     }
@@ -126552,6 +130710,7 @@ static void pushOntoSorter(
     testcase( pKI->nAllField > pKI->nKeyField+2 );
     pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
                                            pKI->nAllField-pKI->nKeyField-1);
+    pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
     addrJmp = sqlite3VdbeCurrentAddr(v);
     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
     pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
@@ -126570,10 +130729,10 @@ static void pushOntoSorter(
     /* At this point the values for the new sorter entry are stored
     ** in an array of registers. They need to be composed into a record
     ** and inserted into the sorter if either (a) there are currently
-    ** less than LIMIT+OFFSET items or (b) the new record is smaller than 
+    ** less than LIMIT+OFFSET items or (b) the new record is smaller than
     ** the largest record currently in the sorter. If (b) is true and there
     ** are already LIMIT+OFFSET items in the sorter, delete the largest
-    ** entry before inserting the new one. This way there are never more 
+    ** entry before inserting the new one. This way there are never more
     ** than LIMIT+OFFSET items in the sorter.
     **
     ** If the new record does not need to be inserted into the sorter,
@@ -126652,8 +130811,8 @@ static void codeDistinct(
 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
 /*
 ** This function is called as part of inner-loop generation for a SELECT
-** statement with an ORDER BY that is not optimized by an index. It 
-** determines the expressions, if any, that the sorter-reference 
+** statement with an ORDER BY that is not optimized by an index. It
+** determines the expressions, if any, that the sorter-reference
 ** optimization should be used for. The sorter-reference optimization
 ** is used for SELECT queries like:
 **
@@ -126663,11 +130822,11 @@ static void codeDistinct(
 ** storing values read from that column in the sorter records, the PK of
 ** the row from table t1 is stored instead. Then, as records are extracted from
 ** the sorter to return to the user, the required value of bigblob is
-** retrieved directly from table t1. If the values are very large, this 
+** retrieved directly from table t1. If the values are very large, this
 ** can be more efficient than storing them directly in the sorter records.
 **
-** The ExprList_item.bSorterRef flag is set for each expression in pEList 
-** for which the sorter-reference optimization should be enabled. 
+** The ExprList_item.bSorterRef flag is set for each expression in pEList
+** for which the sorter-reference optimization should be enabled.
 ** Additionally, the pSort->aDefer[] array is populated with entries
 ** for all cursors required to evaluate all selected expressions. Finally.
 ** output variable (*ppExtra) is set to an expression list containing
@@ -126736,7 +130895,7 @@ static void selectExprDefer(
 **
 ** If srcTab is negative, then the p->pEList expressions
 ** are evaluated in order to get the data for this row.  If srcTab is
-** zero or more, then data is pulled from srcTab and p->pEList is used only 
+** zero or more, then data is pulled from srcTab and p->pEList is used only
 ** to get the number of columns and the collation sequence for each column.
 */
 static void selectInnerLoop(
@@ -126800,7 +130959,7 @@ static void selectInnerLoop(
   if( srcTab>=0 ){
     for(i=0; i<nResultCol; i++){
       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
-      VdbeComment((v, "%s", p->pEList->a[i].zName));
+      VdbeComment((v, "%s", p->pEList->a[i].zEName));
     }
   }else if( eDest!=SRT_Exists ){
 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
@@ -126818,8 +130977,8 @@ static void selectInnerLoop(
     }
     if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
       /* For each expression in p->pEList that is a copy of an expression in
-      ** the ORDER BY clause (pSort->pOrderBy), set the associated 
-      ** iOrderByCol value to one more than the index of the ORDER BY 
+      ** the ORDER BY clause (pSort->pOrderBy), set the associated
+      ** iOrderByCol value to one more than the index of the ORDER BY
       ** expression within the sort-key that pushOntoSorter() will generate.
       ** This allows the p->pEList field to be omitted from the sorted record,
       ** saving space and CPU cycles.  */
@@ -126835,7 +130994,7 @@ static void selectInnerLoop(
       selectExprDefer(pParse, pSort, p->pEList, &pExtra);
       if( pExtra && pParse->db->mallocFailed==0 ){
         /* If there are any extra PK columns to add to the sorter records,
-        ** allocate extra memory cells and adjust the OpenEphemeral 
+        ** allocate extra memory cells and adjust the OpenEphemeral
         ** instruction to account for the larger records. This is only
         ** required if there are one or more WITHOUT ROWID tables with
         ** composite primary keys in the SortCtx.aDefer[] array.  */
@@ -126865,8 +131024,9 @@ static void selectInnerLoop(
       testcase( eDest==SRT_Mem );
       testcase( eDest==SRT_Coroutine );
       testcase( eDest==SRT_Output );
-      assert( eDest==SRT_Set || eDest==SRT_Mem 
-           || eDest==SRT_Coroutine || eDest==SRT_Output );
+      assert( eDest==SRT_Set || eDest==SRT_Mem
+           || eDest==SRT_Coroutine || eDest==SRT_Output
+           || eDest==SRT_Upfrom );
     }
     sRowLoadInfo.regResult = regResult;
     sRowLoadInfo.ecelFlags = ecelFlags;
@@ -126876,7 +131036,7 @@ static void selectInnerLoop(
     if( pExtra ) nResultCol += pExtra->nExpr;
 #endif
     if( p->iLimit
-     && (ecelFlags & SQLITE_ECEL_OMITREF)!=0 
+     && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
      && nPrefixReg>0
     ){
       assert( pSort!=0 );
@@ -126914,6 +131074,7 @@ static void selectInnerLoop(
         pOp->opcode = OP_Null;
         pOp->p1 = 1;
         pOp->p2 = regPrev;
+        pOp = 0;  /* Ensure pOp is not used after sqlite3VdbeAddOp() */
 
         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
         for(i=0; i<nResultCol; i++){
@@ -127014,6 +131175,30 @@ static void selectInnerLoop(
       break;
     }
 
+    case SRT_Upfrom: {
+      if( pSort ){
+        pushOntoSorter(
+            pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
+      }else{
+        int i2 = pDest->iSDParm2;
+        int r1 = sqlite3GetTempReg(pParse);
+
+        /* If the UPDATE FROM join is an aggregate that matches no rows, it
+        ** might still be trying to return one row, because that is what
+        ** aggregates do.  Don't record that empty row in the output table. */
+        sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
+
+        sqlite3VdbeAddOp3(v, OP_MakeRecord,
+                          regResult+(i2<0), nResultCol-(i2<0), r1);
+        if( i2<0 ){
+          sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
+        }else{
+          sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
+        }
+      }
+      break;
+    }
+
 #ifndef SQLITE_OMIT_SUBQUERY
     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
     ** then there should be a single item on the stack.  Write this
@@ -127030,7 +131215,7 @@ static void selectInnerLoop(
       }else{
         int r1 = sqlite3GetTempReg(pParse);
         assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
-        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol, 
+        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
             r1, pDest->zAffSdst, nResultCol);
         sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
         sqlite3ReleaseTempReg(pParse, r1);
@@ -127038,6 +131223,7 @@ static void selectInnerLoop(
       break;
     }
 
+
     /* If any row exist in the result set, record that fact and abort.
     */
     case SRT_Exists: {
@@ -127047,7 +131233,7 @@ static void selectInnerLoop(
     }
 
     /* If this is a scalar select that is part of an expression, then
-    ** store the results in the appropriate memory cell or array of 
+    ** store the results in the appropriate memory cell or array of
     ** memory cells and break out of the scan loop.
     */
     case SRT_Mem: {
@@ -127102,7 +131288,7 @@ static void selectInnerLoop(
         /* If the destination is DistQueue, then cursor (iParm+1) is open
         ** on a second ephemeral index that holds all values every previously
         ** added to the queue. */
-        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
+        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
                                         regResult, nResultCol);
         VdbeCoverage(v);
       }
@@ -127355,7 +131541,7 @@ static void generateSortTail(
     if( pSort->labelBkOut ){
       addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
     }
-    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, 
+    sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
         nKey+1+nColumn+nRefKey);
     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
@@ -127388,7 +131574,7 @@ static void generateSortTail(
       sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
       if( HasRowid(pTab) ){
         sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
-        sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr, 
+        sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
             sqlite3VdbeCurrentAddr(v)+1, regKey);
       }else{
         int k;
@@ -127420,7 +131606,7 @@ static void generateSortTail(
         iRead = iCol--;
       }
       sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
-      VdbeComment((v, "%s", aOutEx[i].zName?aOutEx[i].zName : aOutEx[i].zSpan));
+      VdbeComment((v, "%s", aOutEx[i].zEName));
     }
   }
   switch( eDest ){
@@ -127445,8 +131631,19 @@ static void generateSortTail(
       break;
     }
 #endif
+    case SRT_Upfrom: {
+      int i2 = pDest->iSDParm2;
+      int r1 = sqlite3GetTempReg(pParse);
+      sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
+      if( i2<0 ){
+        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
+      }else{
+        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
+      }
+      break;
+    }
     default: {
-      assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
+      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
       testcase( eDest==SRT_Output );
       testcase( eDest==SRT_Coroutine );
       if( eDest==SRT_Output ){
@@ -127488,14 +131685,14 @@ static void generateSortTail(
 ** original CREATE TABLE statement if the expression is a column. The
 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
 ** is considered a column can be complex in the presence of subqueries. The
-** result-set expression in all of the following SELECT statements is 
+** result-set expression in all of the following SELECT statements is
 ** considered a column by this function.
 **
 **   SELECT col FROM tbl;
 **   SELECT (SELECT col FROM tbl;
 **   SELECT (SELECT col FROM tbl);
 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
-** 
+**
 ** The declaration type for any expression other than a column is NULL.
 **
 ** This routine has either 3 or 6 parameters depending on whether or not
@@ -127507,7 +131704,7 @@ static void generateSortTail(
 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
 #endif
 static const char *columnTypeImpl(
-  NameContext *pNC, 
+  NameContext *pNC,
 #ifndef SQLITE_ENABLE_COLUMN_METADATA
   Expr *pExpr
 #else
@@ -127550,19 +131747,19 @@ static const char *columnTypeImpl(
       if( pTab==0 ){
         /* At one time, code such as "SELECT new.x" within a trigger would
         ** cause this condition to run.  Since then, we have restructured how
-        ** trigger code is generated and so this condition is no longer 
+        ** trigger code is generated and so this condition is no longer
         ** possible. However, it can still be true for statements like
         ** the following:
         **
         **   CREATE TABLE t1(col INTEGER);
         **   SELECT (SELECT t1.col) FROM FROM t1;
         **
-        ** when columnType() is called on the expression "t1.col" in the 
+        ** when columnType() is called on the expression "t1.col" in the
         ** sub-select. In this case, set the column type to NULL, even
         ** though it should really be "INTEGER".
         **
         ** This is not a problem, as the column type of "t1.col" is never
-        ** used. When columnType() is called on the expression 
+        ** used. When columnType() is called on the expression
         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
         ** branch below.  */
         break;
@@ -127576,7 +131773,7 @@ static const char *columnTypeImpl(
         */
         if( iCol>=0 && iCol<pS->pEList->nExpr ){
           /* If iCol is less than zero, then the expression requests the
-          ** rowid of the sub-select or view. This expression is legal (see 
+          ** rowid of the sub-select or view. This expression is legal (see
           ** test case misc2.2.2) - it always evaluates to NULL.
           */
           NameContext sNC;
@@ -127584,7 +131781,7 @@ static const char *columnTypeImpl(
           sNC.pSrcList = pS->pSrc;
           sNC.pNext = pNC;
           sNC.pParse = pNC->pParse;
-          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol); 
+          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
         }
       }else{
         /* A real table or a CTE table */
@@ -127628,13 +131825,13 @@ static const char *columnTypeImpl(
       sNC.pSrcList = pS->pSrc;
       sNC.pNext = pNC;
       sNC.pParse = pNC->pParse;
-      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); 
+      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
       break;
     }
 #endif
   }
 
-#ifdef SQLITE_ENABLE_COLUMN_METADATA  
+#ifdef SQLITE_ENABLE_COLUMN_METADATA
   if( pzOrigDb ){
     assert( pzOrigTab && pzOrigCol );
     *pzOrigDb = zOrigDb;
@@ -127670,7 +131867,7 @@ static void generateColumnTypes(
     const char *zOrigCol = 0;
     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
 
-    /* The vdbe must make its own copy of the column-type and other 
+    /* The vdbe must make its own copy of the column-type and other
     ** column specific strings, in case the schema is reset before this
     ** virtual machine is deleted.
     */
@@ -127754,9 +131951,9 @@ static void generateColumnNames(
     assert( p!=0 );
     assert( p->op!=TK_AGG_COLUMN );  /* Agg processing has not run yet */
     assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
-    if( pEList->a[i].zName ){
+    if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){
       /* An AS clause always takes first priority */
-      char *zName = pEList->a[i].zName;
+      char *zName = pEList->a[i].zEName;
       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
     }else if( srcName && p->op==TK_COLUMN ){
       const char *zCol;
@@ -127778,7 +131975,7 @@ static void generateColumnNames(
         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
       }
     }else{
-      const char *z = pEList->a[i].zSpan;
+      const char *z = pEList->a[i].zEName;
       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
     }
@@ -127822,6 +132019,7 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
   char *zName;                /* Column name */
   int nName;                  /* Size of name in zName[] */
   Hash ht;                    /* Hash table of column names */
+  Table *pTab;
 
   sqlite3HashInit(&ht);
   if( pEList ){
@@ -127840,19 +132038,17 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
     /* Get an appropriate name for the column
     */
-    if( (zName = pEList->a[i].zName)!=0 ){
+    if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){
       /* If the column contains an "AS <name>" phrase, use <name> as the name */
     }else{
       Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
-      while( pColExpr->op==TK_DOT ){
+      while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
         pColExpr = pColExpr->pRight;
         assert( pColExpr!=0 );
       }
-      if( pColExpr->op==TK_COLUMN ){
+      if( pColExpr->op==TK_COLUMN && (pTab = pColExpr->y.pTab)!=0 ){
         /* For columns use the column name name */
         int iCol = pColExpr->iColumn;
-        Table *pTab = pColExpr->y.pTab;
-        assert( pTab!=0 );
         if( iCol<0 ) iCol = pTab->iPKey;
         zName = iCol>=0 ? pTab->aCol[iCol].zName : (char *)"rowid";
       }else if( pColExpr->op==TK_ID ){
@@ -127860,10 +132056,10 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
         zName = pColExpr->u.zToken;
       }else{
         /* Use the original text of the column expression as its name */
-        zName = pEList->a[i].zSpan;
+        zName = pEList->a[i].zEName;
       }
     }
-    if( zName ){
+    if( zName && !sqlite3IsTrueOrFalse(zName) ){
       zName = sqlite3DbStrDup(db, zName);
     }else{
       zName = sqlite3MPrintf(db,"column%d",i+1);
@@ -127883,6 +132079,7 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
     }
     pCol->zName = zName;
+    pCol->hName = sqlite3StrIHash(zName);
     sqlite3ColumnPropertiesFromName(0, pCol);
     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
       sqlite3OomFault(db);
@@ -127904,7 +132101,7 @@ SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
 /*
 ** Add type and collation information to a column list based on
 ** a SELECT statement.
-** 
+**
 ** The column list presumably came from selectColumnNamesFromExprList().
 ** The column list has only names, not types or collations.  This
 ** routine goes through and adds the types and collations.
@@ -128012,9 +132209,9 @@ SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
 ** Compute the iLimit and iOffset fields of the SELECT based on the
 ** pLimit expressions.  pLimit->pLeft and pLimit->pRight hold the expressions
 ** that appear in the original SQL statement after the LIMIT and OFFSET
-** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
-** are the integer memory register numbers for counters used to compute 
-** the limit and offset.  If there is no limit and/or offset, then 
+** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
+** are the integer memory register numbers for counters used to compute
+** the limit and offset.  If there is no limit and/or offset, then
 ** iLimit and iOffset are negative.
 **
 ** This routine changes the values of iLimit and iOffset only if
@@ -128040,7 +132237,7 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
 
   if( p->iLimit ) return;
 
-  /* 
+  /*
   ** "LIMIT -1" always shows all rows.  There is some
   ** controversy about what the correct behavior should be.
   ** The current implementation interprets "LIMIT 0" to mean
@@ -128168,7 +132365,7 @@ static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
 ** that have ever been inserted into Queue and causes duplicates to be
 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
-** 
+**
 ** If the query has an ORDER BY, then entries in the Queue table are kept in
 ** ORDER BY order and the first entry is extracted for each cycle.  Without
 ** an ORDER BY, the Queue table is just a FIFO.
@@ -128189,6 +132386,7 @@ static void generateWithRecursiveQuery(
   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
   Select *pSetup = p->pPrior;   /* The setup query */
+  Select *pFirstRec;            /* Left-most recursive term */
   int addrTop;                  /* Top of the loop */
   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
   int iCurrent = 0;             /* The Current table */
@@ -128264,7 +132462,25 @@ static void generateWithRecursiveQuery(
   /* Detach the ORDER BY clause from the compound SELECT */
   p->pOrderBy = 0;
 
+  /* Figure out how many elements of the compound SELECT are part of the
+  ** recursive query.  Make sure no recursive elements use aggregate
+  ** functions.  Mark the recursive elements as UNION ALL even if they
+  ** are really UNION because the distinctness will be enforced by the
+  ** iDistinct table.  pFirstRec is left pointing to the left-most
+  ** recursive term of the CTE.
+  */
+  pFirstRec = p;
+  for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
+    if( pFirstRec->selFlags & SF_Aggregate ){
+      sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
+      goto end_of_recursive_query;
+    }
+    pFirstRec->op = TK_ALL;
+    if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
+  }
+
   /* Store the results of the setup-query in Queue. */
+  pSetup = pFirstRec->pPrior;
   pSetup->pNext = 0;
   ExplainQueryPlan((pParse, 1, "SETUP"));
   rc = sqlite3Select(pParse, pSetup, &destQueue);
@@ -128297,15 +132513,11 @@ static void generateWithRecursiveQuery(
   /* Execute the recursive SELECT taking the single row in Current as
   ** the value for the recursive-table. Store the results in the Queue.
   */
-  if( p->selFlags & SF_Aggregate ){
-    sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
-  }else{
-    p->pPrior = 0;
-    ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
-    sqlite3Select(pParse, p, &destQueue);
-    assert( p->pPrior==0 );
-    p->pPrior = pSetup;
-  }
+  pFirstRec->pPrior = 0;
+  ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
+  sqlite3Select(pParse, p, &destQueue);
+  assert( pFirstRec->pPrior==0 );
+  pFirstRec->pPrior = pSetup;
 
   /* Keep running the loop until the Queue is empty */
   sqlite3VdbeGoto(v, addrTop);
@@ -128355,6 +132567,9 @@ static int multiSelectValues(
     assert( p->selFlags & SF_Values );
     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
+#ifndef SQLITE_OMIT_WINDOWFUNC
+    if( p->pWin ) return -1;
+#endif
     if( p->pPrior==0 ) break;
     assert( p->pPrior->pNext==p );
     p = p->pPrior;
@@ -128372,13 +132587,23 @@ static int multiSelectValues(
 }
 
 /*
+** Return true if the SELECT statement which is known to be the recursive
+** part of a recursive CTE still has its anchor terms attached.  If the
+** anchor terms have already been removed, then return false.
+*/
+static int hasAnchor(Select *p){
+  while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
+  return p!=0;
+}
+
+/*
 ** This routine is called to process a compound query form from
 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
 ** INTERSECT
 **
 ** "p" points to the right-most of the two queries.  the query on the
 ** left is p->pPrior.  The left query could also be a compound query
-** in which case this routine will be called recursively. 
+** in which case this routine will be called recursively.
 **
 ** The results of the total query are to be written into a destination
 ** of type eDest with parameter iParm.
@@ -128445,7 +132670,8 @@ static int multiSelect(
   */
   if( p->selFlags & SF_MultiValue ){
     rc = multiSelectValues(pParse, p, &dest);
-    goto multi_select_end;
+    if( rc>=0 ) goto multi_select_end;
+    rc = SQLITE_OK;
   }
 
   /* Make sure all SELECTs in the statement have the same number of elements
@@ -128455,7 +132681,7 @@ static int multiSelect(
   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
 
 #ifndef SQLITE_OMIT_CTE
-  if( p->selFlags & SF_Recursive ){
+  if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
     generateWithRecursiveQuery(pParse, p, &dest);
   }else
 #endif
@@ -128507,7 +132733,7 @@ static int multiSelect(
         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
         if( pPrior->pLimit
          && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
-         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
+         && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
         ){
           p->nSelectRow = sqlite3LogEst((u64)nLimit);
         }
@@ -128524,7 +132750,7 @@ static int multiSelect(
         Expr *pLimit;    /* Saved values of p->nLimit  */
         int addr;
         SelectDest uniondest;
-  
+
         testcase( p->op==TK_EXCEPT );
         testcase( p->op==TK_UNION );
         priorOp = SRT_Union;
@@ -128546,7 +132772,8 @@ static int multiSelect(
           findRightmost(p)->selFlags |= SF_UsesEphemeral;
           assert( p->pEList );
         }
-  
+
+
         /* Code the SELECT statements to our left
         */
         assert( !pPrior->pOrderBy );
@@ -128555,7 +132782,7 @@ static int multiSelect(
         if( rc ){
           goto multi_select_end;
         }
-  
+
         /* Code the current SELECT statement
         */
         if( p->op==TK_EXCEPT ){
@@ -128572,9 +132799,7 @@ static int multiSelect(
                           selectOpName(p->op)));
         rc = sqlite3Select(pParse, p, &uniondest);
         testcase( rc!=SQLITE_OK );
-        /* Query flattening in sqlite3Select() might refill p->pOrderBy.
-        ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
-        sqlite3ExprListDelete(db, p->pOrderBy);
+        assert( p->pOrderBy==0 );
         pDelete = p->pPrior;
         p->pPrior = pPrior;
         p->pOrderBy = 0;
@@ -128585,14 +132810,14 @@ static int multiSelect(
         p->pLimit = pLimit;
         p->iLimit = 0;
         p->iOffset = 0;
-  
+
         /* Convert the data in the temporary table into whatever form
         ** it is that we currently need.
         */
         assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
-        if( dest.eDest!=priorOp ){
+        assert( p->pEList || db->mallocFailed );
+        if( dest.eDest!=priorOp && db->mallocFailed==0 ){
           int iCont, iBreak, iStart;
-          assert( p->pEList );
           iBreak = sqlite3VdbeMakeLabel(pParse);
           iCont = sqlite3VdbeMakeLabel(pParse);
           computeLimitRegisters(pParse, p, iBreak);
@@ -128614,7 +132839,7 @@ static int multiSelect(
         int addr;
         SelectDest intersectdest;
         int r1;
-  
+
         /* INTERSECT is different from the others since it requires
         ** two temporary tables.  Hence it has its own case.  Begin
         ** by allocating the tables we will need.
@@ -128622,13 +132847,13 @@ static int multiSelect(
         tab1 = pParse->nTab++;
         tab2 = pParse->nTab++;
         assert( p->pOrderBy==0 );
-  
+
         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
         assert( p->addrOpenEphm[0] == -1 );
         p->addrOpenEphm[0] = addr;
         findRightmost(p)->selFlags |= SF_UsesEphemeral;
         assert( p->pEList );
-  
+
         /* Code the SELECTs to our left into temporary table "tab1".
         */
         sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
@@ -128636,7 +132861,7 @@ static int multiSelect(
         if( rc ){
           goto multi_select_end;
         }
-  
+
         /* Code the current SELECT into temporary table "tab2"
         */
         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
@@ -128657,10 +132882,11 @@ static int multiSelect(
         }
         sqlite3ExprDelete(db, p->pLimit);
         p->pLimit = pLimit;
-  
+
         /* Generate code to take the intersection of the two temporary
         ** tables.
         */
+        if( rc ) break;
         assert( p->pEList );
         iBreak = sqlite3VdbeMakeLabel(pParse);
         iCont = sqlite3VdbeMakeLabel(pParse);
@@ -128681,15 +132907,16 @@ static int multiSelect(
         break;
       }
     }
-  
+
   #ifndef SQLITE_OMIT_EXPLAIN
     if( p->pNext==0 ){
       ExplainQueryPlanPop(pParse);
     }
   #endif
   }
-  
-  /* Compute collating sequences used by 
+  if( pParse->nErr ) goto multi_select_end;
+
+  /* Compute collating sequences used by
   ** temporary tables needed to implement the compound select.
   ** Attach the KeyInfo structure to all temporary tables.
   **
@@ -128795,7 +133022,7 @@ static int generateOutputSubroutine(
   addr = sqlite3VdbeCurrentAddr(v);
   iContinue = sqlite3VdbeMakeLabel(pParse);
 
-  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
+  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
   */
   if( regPrev ){
     int addr1, addr2;
@@ -128837,7 +133064,7 @@ static int generateOutputSubroutine(
       int r1;
       testcase( pIn->nSdst>1 );
       r1 = sqlite3GetTempReg(pParse);
-      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, 
+      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
           r1, pDest->zAffSdst, pIn->nSdst);
       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
                            pIn->iSdst, pIn->nSdst);
@@ -128877,7 +133104,7 @@ static int generateOutputSubroutine(
     ** SRT_Output.  This routine is never called with any other
     ** destination other than the ones handled above or SRT_Output.
     **
-    ** For SRT_Output, results are stored in a sequence of registers.  
+    ** For SRT_Output, results are stored in a sequence of registers.
     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
     ** return the next row of result.
     */
@@ -128934,7 +133161,7 @@ static int generateOutputSubroutine(
 **
 **    EofB:    Called when data is exhausted from selectB.
 **
-** The implementation of the latter five subroutines depend on which 
+** The implementation of the latter five subroutines depend on which
 ** <operator> is used:
 **
 **
@@ -129026,7 +133253,7 @@ static int multiSelectOrderBy(
   sqlite3 *db;          /* Database connection */
   ExprList *pOrderBy;   /* The ORDER BY clause */
   int nOrderBy;         /* Number of terms in the ORDER BY clause */
-  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
+  u32 *aPermute;        /* Mapping from ORDER BY terms to result set columns */
 
   assert( p->pOrderBy!=0 );
   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
@@ -129039,7 +133266,7 @@ static int multiSelectOrderBy(
 
   /* Patch up the ORDER BY clause
   */
-  op = p->op;  
+  op = p->op;
   pPrior = p->pPrior;
   assert( pPrior->pOrderBy==0 );
   pOrderBy = p->pOrderBy;
@@ -129075,7 +133302,7 @@ static int multiSelectOrderBy(
   ** to the right and the left are evaluated, they use the correct
   ** collation.
   */
-  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
+  aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
   if( aPermute ){
     struct ExprList_item *pItem;
     aPermute[0] = nOrderBy;
@@ -129115,7 +133342,7 @@ static int multiSelectOrderBy(
       }
     }
   }
+
   /* Separate the left and the right query from one another
   */
   p->pPrior = 0;
@@ -129160,7 +133387,7 @@ static int multiSelectOrderBy(
   sqlite3VdbeEndCoroutine(v, regAddrA);
   sqlite3VdbeJumpHere(v, addr1);
 
-  /* Generate a coroutine to evaluate the SELECT statement on 
+  /* Generate a coroutine to evaluate the SELECT statement on
   ** the right - the "B" select
   */
   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
@@ -129169,7 +133396,7 @@ static int multiSelectOrderBy(
   savedLimit = p->iLimit;
   savedOffset = p->iOffset;
   p->iLimit = regLimitB;
-  p->iOffset = 0;  
+  p->iOffset = 0;
   ExplainQueryPlan((pParse, 1, "RIGHT"));
   sqlite3Select(pParse, p, &destB);
   p->iLimit = savedLimit;
@@ -129183,7 +133410,7 @@ static int multiSelectOrderBy(
   addrOutA = generateOutputSubroutine(pParse,
                  p, &destA, pDest, regOutA,
                  regPrev, pKeyDup, labelEnd);
-  
+
   /* Generate a subroutine that outputs the current row of the B
   ** select as the next output row of the compound select.
   */
@@ -129200,7 +133427,7 @@ static int multiSelectOrderBy(
   */
   if( op==TK_EXCEPT || op==TK_INTERSECT ){
     addrEofA_noB = addrEofA = labelEnd;
-  }else{  
+  }else{
     VdbeNoopComment((v, "eof-A subroutine"));
     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
@@ -129215,7 +133442,7 @@ static int multiSelectOrderBy(
   if( op==TK_INTERSECT ){
     addrEofB = addrEofA;
     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
-  }else{  
+  }else{
     VdbeNoopComment((v, "eof-B subroutine"));
     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
@@ -129310,13 +133537,13 @@ static void substSelect(SubstContext*, Select*, int);
 /*
 ** Scan through the expression pExpr.  Replace every reference to
 ** a column in table number iTable with a copy of the iColumn-th
-** entry in pEList.  (But leave references to the ROWID column 
+** entry in pEList.  (But leave references to the ROWID column
 ** unchanged.)
 **
 ** This routine is part of the flattening procedure.  A subquery
 ** whose result set is defined by pEList appears as entry in the
 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
-** FORM clause entry is iTable.  This routine makes the necessary 
+** FORM clause entry is iTable.  This routine makes the necessary
 ** changes to pExpr so that it refers directly to the source table
 ** of the subquery rather the result set of the subquery.
 */
@@ -129348,6 +133575,7 @@ static Expr *substExpr(
           ifNullRow.op = TK_IF_NULL_ROW;
           ifNullRow.pLeft = pCopy;
           ifNullRow.iTable = pSubst->iNewTable;
+          ifNullRow.flags = EP_IfNullRow;
           pCopy = &ifNullRow;
         }
         testcase( ExprHasProperty(pCopy, EP_Subquery) );
@@ -129356,8 +133584,7 @@ static Expr *substExpr(
           ExprSetProperty(pNew, EP_CanBeNull);
         }
         if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
-          pNew->iRightJoinTable = pExpr->iRightJoinTable;
-          ExprSetProperty(pNew, EP_FromJoin);
+          sqlite3SetJoinExpr(pNew, pExpr->iRightJoinTable);
         }
         sqlite3ExprDelete(db, pExpr);
         pExpr = pNew;
@@ -129367,7 +133594,7 @@ static Expr *substExpr(
         if( pExpr ){
           if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
             CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
-            pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr, 
+            pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
                 (pColl ? pColl->zName : "BINARY")
             );
           }
@@ -129436,6 +133663,38 @@ static void substSelect(
 
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
 /*
+** pSelect is a SELECT statement and pSrcItem is one item in the FROM
+** clause of that SELECT.
+**
+** This routine scans the entire SELECT statement and recomputes the
+** pSrcItem->colUsed mask.
+*/
+static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
+  struct SrcList_item *pItem;
+  if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
+  pItem = pWalker->u.pSrcItem;
+  if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
+  if( pExpr->iColumn<0 ) return WRC_Continue;
+  pItem->colUsed |= sqlite3ExprColUsed(pExpr);
+  return WRC_Continue;
+}
+static void recomputeColumnsUsed(
+  Select *pSelect,                 /* The complete SELECT statement */
+  struct SrcList_item *pSrcItem    /* Which FROM clause item to recompute */
+){
+  Walker w;
+  if( NEVER(pSrcItem->pTab==0) ) return;
+  memset(&w, 0, sizeof(w));
+  w.xExprCallback = recomputeColumnsUsedExpr;
+  w.xSelectCallback = sqlite3SelectWalkNoop;
+  w.u.pSrcItem = pSrcItem;
+  pSrcItem->colUsed = 0;
+  sqlite3WalkSelect(&w, pSelect);
+}
+#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
+
+#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
+/*
 ** This routine attempts to flatten subqueries as a performance optimization.
 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
 **
@@ -129457,7 +133716,7 @@ static void substSelect(
 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
 **
 ** The code generated for this simplification gives the same result
-** but only has to scan the data once.  And because indices might 
+** but only has to scan the data once.  And because indices might
 ** exist on the table t1, a complete scan of the data might be
 ** avoided.
 **
@@ -129479,11 +133738,12 @@ static void substSelect(
 **        (3b) the FROM clause of the subquery may not contain a virtual
 **             table and
 **        (3c) the outer query may not be an aggregate.
+**        (3d) the outer query may not be DISTINCT.
 **
 **   (4)  The subquery can not be DISTINCT.
 **
 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
-**        sub-queries that were excluded from this optimization. Restriction 
+**        sub-queries that were excluded from this optimization. Restriction
 **        (4) has since been expanded to exclude all DISTINCT subqueries.
 **
 **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
@@ -129500,7 +133760,7 @@ static void substSelect(
 **
 **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
 **        accidently carried the comment forward until 2014-09-15.  Original
-**        constraint: "If the subquery is aggregate then the outer query 
+**        constraint: "If the subquery is aggregate then the outer query
 **        may not use LIMIT."
 **
 **  (11)  The subquery and the outer query may not both have ORDER BY clauses.
@@ -129518,7 +133778,7 @@ static void substSelect(
 **
 **  (16)  If the outer query is aggregate, then the subquery may not
 **        use ORDER BY.  (Ticket #2942)  This used to not matter
-**        until we introduced the group_concat() function.  
+**        until we introduced the group_concat() function.
 **
 **  (17)  If the subquery is a compound select, then
 **        (17a) all compound operators must be a UNION ALL, and
@@ -129529,6 +133789,7 @@ static void substSelect(
 **              (17d1) aggregate, or
 **              (17d2) DISTINCT, or
 **              (17d3) a join.
+**        (17e) the subquery may not contain window functions
 **
 **        The parent and sub-query may contain WHERE clauses. Subject to
 **        rules (11), (13) and (14), they may also contain ORDER BY,
@@ -129544,7 +133805,7 @@ static void substSelect(
 **        syntax error and return a detailed message.
 **
 **  (18)  If the sub-query is a compound select, then all terms of the
-**        ORDER BY clause of the parent must be simple references to 
+**        ORDER BY clause of the parent must be simple references to
 **        columns of the sub-query.
 **
 **  (19)  If the subquery uses LIMIT then the outer query may not
@@ -129568,7 +133829,7 @@ static void substSelect(
 **        recursive queries in multiSelect().
 **
 **  (**)  We no longer attempt to flatten aggregate subqueries.  Was:
-**        The subquery may not be an aggregate that uses the built-in min() or 
+**        The subquery may not be an aggregate that uses the built-in min() or
 **        or max() functions.  (Without this restriction, a query like:
 **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
 **        return the value X for which Y was maximal.)
@@ -129602,11 +133863,12 @@ static int flattenSubquery(
   SrcList *pSubSrc;   /* The FROM clause of the subquery */
   int iParent;        /* VDBE cursor number of the pSub result set temp table */
   int iNewParent = -1;/* Replacement table for iParent */
-  int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */    
+  int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
   int i;              /* Loop counter */
   Expr *pWhere;                    /* The WHERE clause */
   struct SrcList_item *pSubitem;   /* The subquery */
   sqlite3 *db = pParse->db;
+  Walker w;                        /* Walker to persist agginfo data */
 
   /* Check to see if flattening is permitted.  Return 0 if not.
   */
@@ -129675,8 +133937,11 @@ static int flattenSubquery(
   */
   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
     isLeftJoin = 1;
-    if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
-      /*  (3a)             (3c)     (3b) */
+    if( pSubSrc->nSrc>1                   /* (3a) */
+     || isAgg                             /* (3b) */
+     || IsVirtual(pSubSrc->a[0].pTab)     /* (3c) */
+     || (p->selFlags & SF_Distinct)!=0    /* (3d) */
+    ){
       return 0;
     }
   }
@@ -129684,7 +133949,7 @@ static int flattenSubquery(
   else if( iFrom>0 && !isAgg ){
     /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
     ** every reference to any result column from subquery in a join, even
-    ** though they are not necessary.  This will stress-test the OP_IfNullRow 
+    ** though they are not necessary.  This will stress-test the OP_IfNullRow
     ** opcode. */
     isLeftJoin = -1;
   }
@@ -129710,6 +133975,9 @@ static int flattenSubquery(
       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0    /* (17b) */
        || (pSub1->pPrior && pSub1->op!=TK_ALL)                 /* (17a) */
        || pSub1->pSrc->nSrc<1                                  /* (17c) */
+#ifndef SQLITE_OMIT_WINDOWFUNC
+       || pSub1->pWin                                          /* (17e) */
+#endif
       ){
         return 0;
       }
@@ -129744,13 +134012,13 @@ static int flattenSubquery(
   pParse->zAuthContext = zSavedAuthContext;
 
   /* If the sub-query is a compound SELECT statement, then (by restrictions
-  ** 17 and 18 above) it must be a UNION ALL and the parent query must 
+  ** 17 and 18 above) it must be a UNION ALL and the parent query must
   ** be of the form:
   **
-  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
+  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
   **
   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
-  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
+  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
   ** OFFSET clauses and joins them to the left-hand-side of the original
   ** using UNION ALL operators. In this case N is the number of simple
   ** select statements in the compound sub-query.
@@ -129803,7 +134071,7 @@ static int flattenSubquery(
     if( db->mallocFailed ) return 1;
   }
 
-  /* Begin flattening the iFrom-th entry of the FROM clause 
+  /* Begin flattening the iFrom-th entry of the FROM clause
   ** in the outer query.
   */
   pSub = pSub1 = pSubitem->pSelect;
@@ -129901,10 +134169,10 @@ static int flattenSubquery(
       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
     }
     pSrc->a[iFrom].fg.jointype = jointype;
-  
-    /* Now begin substituting subquery result set expressions for 
+
+    /* Now begin substituting subquery result set expressions for
     ** references to the iParent in the outer query.
-    ** 
+    **
     ** Example:
     **
     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
@@ -129914,7 +134182,7 @@ static int flattenSubquery(
     ** We look at every expression in the outer query and every place we see
     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
     */
-    if( pSub->pOrderBy ){
+    if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
       /* At this point, any non-zero iOrderByCol values indicate that the
       ** ORDER BY column expression is identical to the iOrderByCol'th
       ** expression returned by SELECT statement pSub. Since these values
@@ -129936,9 +134204,15 @@ static int flattenSubquery(
     pWhere = pSub->pWhere;
     pSub->pWhere = 0;
     if( isLeftJoin>0 ){
-      setJoinExpr(pWhere, iNewParent);
+      sqlite3SetJoinExpr(pWhere, iNewParent);
+    }
+    if( pWhere ){
+      if( pParent->pWhere ){
+        pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
+      }else{
+        pParent->pWhere = pWhere;
+      }
     }
-    pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
     if( db->mallocFailed==0 ){
       SubstContext x;
       x.pParse = pParse;
@@ -129948,12 +134222,12 @@ static int flattenSubquery(
       x.pEList = pSub->pEList;
       substSelect(&x, pParent, 0);
     }
-  
+
     /* The flattened query is a compound if either the inner or the
     ** outer query is a compound. */
     pParent->selFlags |= pSub->selFlags & SF_Compound;
     assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
-  
+
     /*
     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
     **
@@ -129964,11 +134238,19 @@ static int flattenSubquery(
       pParent->pLimit = pSub->pLimit;
       pSub->pLimit = 0;
     }
+
+    /* Recompute the SrcList_item.colUsed masks for the flattened
+    ** tables. */
+    for(i=0; i<nSubSrc; i++){
+      recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
+    }
   }
 
   /* Finially, delete what is left of the subquery and return
   ** success.
   */
+  sqlite3AggInfoPersistWalkerInit(&w, pParse);
+  sqlite3WalkSelect(&w,pSub1);
   sqlite3SelectDelete(db, pSub1);
 
 #if SELECTTRACE_ENABLED
@@ -129996,23 +134278,35 @@ struct WhereConst {
 
 /*
 ** Add a new entry to the pConst object.  Except, do not add duplicate
-** pColumn entires.
+** pColumn entires.  Also, do not add if doing so would not be appropriate.
+**
+** The caller guarantees the pColumn is a column and pValue is a constant.
+** This routine has to do some additional checks before completing the
+** insert.
 */
 static void constInsert(
-  WhereConst *pConst,      /* The WhereConst into which we are inserting */
-  Expr *pColumn,           /* The COLUMN part of the constraint */
-  Expr *pValue             /* The VALUE part of the constraint */
+  WhereConst *pConst,  /* The WhereConst into which we are inserting */
+  Expr *pColumn,       /* The COLUMN part of the constraint */
+  Expr *pValue,        /* The VALUE part of the constraint */
+  Expr *pExpr          /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
 ){
   int i;
   assert( pColumn->op==TK_COLUMN );
+  assert( sqlite3ExprIsConstant(pValue) );
+
+  if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
+  if( sqlite3ExprAffinity(pValue)!=0 ) return;
+  if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
+    return;
+  }
 
   /* 2018-10-25 ticket [cf5ed20f]
   ** Make sure the same pColumn is not inserted more than once */
   for(i=0; i<pConst->nConst; i++){
-    const Expr *pExpr = pConst->apExpr[i*2];
-    assert( pExpr->op==TK_COLUMN );
-    if( pExpr->iTable==pColumn->iTable
-     && pExpr->iColumn==pColumn->iColumn
+    const Expr *pE2 = pConst->apExpr[i*2];
+    assert( pE2->op==TK_COLUMN );
+    if( pE2->iTable==pColumn->iTable
+     && pE2->iColumn==pColumn->iColumn
     ){
       return;  /* Already present.  Return without doing anything. */
     }
@@ -130024,7 +134318,6 @@ static void constInsert(
   if( pConst->apExpr==0 ){
     pConst->nConst = 0;
   }else{
-    if( ExprHasProperty(pValue, EP_FixedCol) ) pValue = pValue->pLeft;
     pConst->apExpr[pConst->nConst*2-2] = pColumn;
     pConst->apExpr[pConst->nConst*2-1] = pValue;
   }
@@ -130050,19 +134343,11 @@ static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
   pLeft = pExpr->pLeft;
   assert( pRight!=0 );
   assert( pLeft!=0 );
-  if( pRight->op==TK_COLUMN
-   && !ExprHasProperty(pRight, EP_FixedCol)
-   && sqlite3ExprIsConstant(pLeft)
-   && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
-  ){
-    constInsert(pConst, pRight, pLeft);
-  }else
-  if( pLeft->op==TK_COLUMN
-   && !ExprHasProperty(pLeft, EP_FixedCol)
-   && sqlite3ExprIsConstant(pRight)
-   && sqlite3IsBinary(sqlite3BinaryCompareCollSeq(pConst->pParse,pLeft,pRight))
-  ){
-    constInsert(pConst, pLeft, pRight);
+  if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
+    constInsert(pConst,pRight,pLeft,pExpr);
+  }
+  if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
+    constInsert(pConst,pLeft,pRight,pExpr);
   }
 }
 
@@ -130076,7 +134361,11 @@ static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
   int i;
   WhereConst *pConst;
   if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
-  if( ExprHasProperty(pExpr, EP_FixedCol) ) return WRC_Continue;
+  if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){
+    testcase( ExprHasProperty(pExpr, EP_FixedCol) );
+    testcase( ExprHasProperty(pExpr, EP_FromJoin) );
+    return WRC_Continue;
+  }
   pConst = pWalker->u.pConst;
   for(i=0; i<pConst->nConst; i++){
     Expr *pColumn = pConst->apExpr[i*2];
@@ -130098,10 +134387,9 @@ static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
 ** The WHERE-clause constant propagation optimization.
 **
 ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
-** CONSTANT=COLUMN that must be tree (in other words, if the terms top-level
-** AND-connected terms that are not part of a ON clause from a LEFT JOIN)
-** then throughout the query replace all other occurrences of COLUMN
-** with CONSTANT within the WHERE clause.
+** CONSTANT=COLUMN that are top-level AND-connected terms that are not
+** part of a ON clause from a LEFT JOIN, then throughout the query
+** replace all other occurrences of COLUMN with CONSTANT.
 **
 ** For example, the query:
 **
@@ -130156,7 +134444,7 @@ static int propagateConstants(
       sqlite3DbFree(x.pParse->db, x.apExpr);
       nChng += x.nChng;
     }
-  }while( x.nChng );  
+  }while( x.nChng );
   return nChng;
 }
 
@@ -130207,8 +134495,8 @@ static int propagateConstants(
 **       But if the (b2=2) term were to be pushed down into the bb subquery,
 **       then the (1,1,NULL) row would be suppressed.
 **
-**   (6) The inner query features one or more window-functions (since 
-**       changes to the WHERE clause of the inner query could change the 
+**   (6) The inner query features one or more window-functions (since
+**       changes to the WHERE clause of the inner query could change the
 **       window over which window functions are calculated).
 **
 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
@@ -130223,11 +134511,14 @@ static int pushDownWhereTerms(
 ){
   Expr *pNew;
   int nChng = 0;
+  Select *pSel;
   if( pWhere==0 ) return 0;
   if( pSubq->selFlags & SF_Recursive ) return 0;  /* restriction (2) */
 
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  if( pSubq->pWin ) return 0;    /* restriction (6) */
+  for(pSel=pSubq; pSel; pSel=pSel->pPrior){
+    if( pSel->pWin ) return 0;    /* restriction (6) */
+  }
 #endif
 
 #ifdef SQLITE_DEBUG
@@ -130236,7 +134527,7 @@ static int pushDownWhereTerms(
   ** in the future.
   */
   {
-    Select *pX;  
+    Select *pX;
     for(pX=pSubq; pX; pX=pX->pPrior){
       assert( (pX->selFlags & (SF_Recursive))==0 );
     }
@@ -130286,7 +134577,7 @@ static int pushDownWhereTerms(
 
 /*
 ** The pFunc is the only aggregate function in the query.  Check to see
-** if the query is a candidate for the min/max optimization. 
+** if the query is a candidate for the min/max optimization.
 **
 ** If the query is a candidate for the min/max optimization, then set
 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
@@ -130305,7 +134596,7 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   ExprList *pEList = pFunc->x.pList;    /* Arguments to agg function */
   const char *zFunc;                    /* Name of aggregate function pFunc */
   ExprList *pOrderBy;
-  u8 sortFlags;
+  u8 sortFlags = 0;
 
   assert( *ppMinMax==0 );
   assert( pFunc->op==TK_AGG_FUNCTION );
@@ -130316,7 +134607,9 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
   zFunc = pFunc->u.zToken;
   if( sqlite3StrICmp(zFunc, "min")==0 ){
     eRet = WHERE_ORDERBY_MIN;
-    sortFlags = KEYINFO_ORDER_BIGNULL;
+    if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
+      sortFlags = KEYINFO_ORDER_BIGNULL;
+    }
   }else if( sqlite3StrICmp(zFunc, "max")==0 ){
     eRet = WHERE_ORDERBY_MAX;
     sortFlags = KEYINFO_ORDER_DESC;
@@ -130331,7 +134624,7 @@ static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
 
 /*
 ** The select statement passed as the first argument is an aggregate query.
-** The second argument is the associated aggregate-info object. This 
+** The second argument is the associated aggregate-info object. This
 ** function tests if the SELECT is of the form:
 **
 **   SELECT count(*) FROM <tbl>
@@ -130346,7 +134639,7 @@ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
 
   assert( !p->pGroupBy );
 
-  if( p->pWhere || p->pEList->nExpr!=1 
+  if( p->pWhere || p->pEList->nExpr!=1
    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
   ){
     return 0;
@@ -130367,8 +134660,8 @@ static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
 /*
 ** If the source-list item passed as an argument was augmented with an
 ** INDEXED BY clause, then try to locate the specified index. If there
-** was such a clause and the named index cannot be found, return 
-** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
+** was such a clause and the named index cannot be found, return
+** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
 ** pFrom->pIndex and return SQLITE_OK.
 */
 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
@@ -130376,8 +134669,8 @@ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pF
     Table *pTab = pFrom->pTab;
     char *zIndexedBy = pFrom->u1.zIndexedBy;
     Index *pIdx;
-    for(pIdx=pTab->pIndex; 
-        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 
+    for(pIdx=pTab->pIndex;
+        pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
         pIdx=pIdx->pNext
     );
     if( !pIdx ){
@@ -130390,7 +134683,7 @@ SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pF
   return SQLITE_OK;
 }
 /*
-** Detect compound SELECT statements that use an ORDER BY clause with 
+** Detect compound SELECT statements that use an ORDER BY clause with
 ** an alternative collating sequence.
 **
 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
@@ -130425,6 +134718,14 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
   if( pX==0 ) return WRC_Continue;
   a = p->pOrderBy->a;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+  /* If iOrderByCol is already non-zero, then it has already been matched
+  ** to a result column of the SELECT statement. This occurs when the
+  ** SELECT is rewritten for window-functions processing and then passed
+  ** to sqlite3SelectPrep() and similar a second time. The rewriting done
+  ** by this function is not required in this case. */
+  if( a[0].u.x.iOrderByCol ) return WRC_Continue;
+#endif
   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
     if( a[i].pExpr->flags & EP_Collate ) break;
   }
@@ -130450,6 +134751,9 @@ static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
   p->pPrior = 0;
   p->pNext = 0;
   p->pWith = 0;
+#ifndef SQLITE_OMIT_WINDOWFUNC
+  p->pWinDefn = 0;
+#endif
   p->selFlags &= ~SF_Compound;
   assert( (p->selFlags & SF_Converted)==0 );
   p->selFlags |= SF_Converted;
@@ -130474,9 +134778,9 @@ static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
 
 #ifndef SQLITE_OMIT_CTE
 /*
-** Argument pWith (which may be NULL) points to a linked list of nested 
-** WITH contexts, from inner to outermost. If the table identified by 
-** FROM clause element pItem is really a common-table-expression (CTE) 
+** Argument pWith (which may be NULL) points to a linked list of nested
+** WITH contexts, from inner to outermost. If the table identified by
+** FROM clause element pItem is really a common-table-expression (CTE)
 ** then return a pointer to the CTE definition for that table. Otherwise
 ** return NULL.
 **
@@ -130511,7 +134815,7 @@ static struct Cte *searchWith(
 ** onto the top of the stack. If argument bFree is true, then this
 ** WITH clause will never be popped from the stack. In this case it
 ** should be freed along with the Parse object. In other cases, when
-** bFree==0, the With object will be freed along with the SELECT 
+** bFree==0, the With object will be freed along with the SELECT
 ** statement with which it is associated.
 */
 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
@@ -130525,7 +134829,7 @@ SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
 }
 
 /*
-** This function checks if argument pFrom refers to a CTE declared by 
+** This function checks if argument pFrom refers to a CTE declared by
 ** a WITH clause on the stack currently maintained by the parser. And,
 ** if currently processing a CTE expression, if it is a recursive
 ** reference to the current CTE.
@@ -130540,7 +134844,7 @@ SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
 ** parser and some error code other than SQLITE_OK returned.
 */
 static int withExpand(
-  Walker *pWalker, 
+  Walker *pWalker,
   struct SrcList_item *pFrom
 ){
   Parse *pParse = pWalker->pParse;
@@ -130549,6 +134853,9 @@ static int withExpand(
   With *pWith;                    /* WITH clause that pCte belongs to */
 
   assert( pFrom->pTab==0 );
+  if( pParse->nErr ){
+    return SQLITE_ERROR;
+  }
 
   pCte = searchWith(pParse->pWith, pFrom, &pWith);
   if( pCte ){
@@ -130556,8 +134863,10 @@ static int withExpand(
     ExprList *pEList;
     Select *pSel;
     Select *pLeft;                /* Left-most SELECT statement */
+    Select *pRecTerm;             /* Left-most recursive term */
     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
     With *pSavedWith;             /* Initial value of pParse->pWith */
+    int iRecTab = -1;             /* Cursor for recursive table */
 
     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
     ** recursive reference to CTE pCte. Leave an error in pParse and return
@@ -130582,44 +134891,48 @@ static int withExpand(
     assert( pFrom->pSelect );
 
     /* Check if this is a recursive CTE. */
-    pSel = pFrom->pSelect;
+    pRecTerm = pSel = pFrom->pSelect;
     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
-    if( bMayRecursive ){
+    while( bMayRecursive && pRecTerm->op==pSel->op ){
       int i;
-      SrcList *pSrc = pFrom->pSelect->pSrc;
+      SrcList *pSrc = pRecTerm->pSrc;
+      assert( pRecTerm->pPrior!=0 );
       for(i=0; i<pSrc->nSrc; i++){
         struct SrcList_item *pItem = &pSrc->a[i];
-        if( pItem->zDatabase==0 
-         && pItem->zName!=0 
+        if( pItem->zDatabase==0
+         && pItem->zName!=0
          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
-          ){
+        ){
           pItem->pTab = pTab;
-          pItem->fg.isRecursive = 1;
           pTab->nTabRef++;
-          pSel->selFlags |= SF_Recursive;
+          pItem->fg.isRecursive = 1;
+          if( pRecTerm->selFlags & SF_Recursive ){
+            sqlite3ErrorMsg(pParse,
+               "multiple references to recursive table: %s", pCte->zName
+            );
+            return SQLITE_ERROR;
+          }
+          pRecTerm->selFlags |= SF_Recursive;
+          if( iRecTab<0 ) iRecTab = pParse->nTab++;
+          pItem->iCursor = iRecTab;
         }
       }
+      if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
+      pRecTerm = pRecTerm->pPrior;
     }
 
-    /* Only one recursive reference is permitted. */ 
-    if( pTab->nTabRef>2 ){
-      sqlite3ErrorMsg(
-          pParse, "multiple references to recursive table: %s", pCte->zName
-      );
-      return SQLITE_ERROR;
-    }
-    assert( pTab->nTabRef==1 || 
-            ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
-
     pCte->zCteErr = "circular reference: %s";
     pSavedWith = pParse->pWith;
     pParse->pWith = pWith;
-    if( bMayRecursive ){
-      Select *pPrior = pSel->pPrior;
-      assert( pPrior->pWith==0 );
-      pPrior->pWith = pSel->pWith;
-      sqlite3WalkSelect(pWalker, pPrior);
-      pPrior->pWith = 0;
+    if( pSel->selFlags & SF_Recursive ){
+      assert( pRecTerm!=0 );
+      assert( (pRecTerm->selFlags & SF_Recursive)==0 );
+      assert( pRecTerm->pNext!=0 );
+      assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
+      assert( pRecTerm->pWith==0 );
+      pRecTerm->pWith = pSel->pWith;
+      sqlite3WalkSelect(pWalker, pRecTerm);
+      pRecTerm->pWith = 0;
     }else{
       sqlite3WalkSelect(pWalker, pSel);
     }
@@ -130657,19 +134970,19 @@ static int withExpand(
 
 #ifndef SQLITE_OMIT_CTE
 /*
-** If the SELECT passed as the second argument has an associated WITH 
+** If the SELECT passed as the second argument has an associated WITH
 ** clause, pop it from the stack stored as part of the Parse object.
 **
 ** This function is used as the xSelectCallback2() callback by
 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
-** names and other FROM clause elements. 
+** names and other FROM clause elements.
 */
 static void selectPopWith(Walker *pWalker, Select *p){
   Parse *pParse = pWalker->pParse;
   if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
     With *pWith = findRightmost(p)->pWith;
     if( pWith!=0 ){
-      assert( pParse->pWith==pWith );
+      assert( pParse->pWith==pWith || pParse->nErr );
       pParse->pWith = pWith->pOuter;
     }
   }
@@ -130714,7 +135027,7 @@ SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFr
 **    (1)  Make sure VDBE cursor numbers have been assigned to every
 **         element of the FROM clause.
 **
-**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
+**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
 **         defines FROM clause.  When views appear in the FROM clause,
 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
 **         that implements the view.  A copy is made of the view's SELECT
@@ -130770,8 +135083,8 @@ static int selectExpander(Walker *pWalker, Select *p){
   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
     Table *pTab;
     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
-    if( pFrom->fg.isRecursive ) continue;
-    assert( pFrom->pTab==0 );
+    if( pFrom->pTab ) continue;
+    assert( pFrom->fg.isRecursive==0 );
 #ifndef SQLITE_OMIT_CTE
     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
     if( pFrom->pTab ) {} else
@@ -130800,7 +135113,7 @@ static int selectExpander(Walker *pWalker, Select *p){
       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
         return WRC_Abort;
       }
-#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
+#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
       if( IsVirtual(pTab) || pTab->pSelect ){
         i16 nCol;
         u8 eCodeOrig = pWalker->eCode;
@@ -130808,8 +135121,18 @@ static int selectExpander(Walker *pWalker, Select *p){
         assert( pFrom->pSelect==0 );
         if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
           sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
-              pTab->zName);
+            pTab->zName);
+        }
+#ifndef SQLITE_OMIT_VIRTUALTABLE
+        if( IsVirtual(pTab)
+         && pFrom->fg.fromDDL
+         && ALWAYS(pTab->pVTable!=0)
+         && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
+        ){
+          sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
+                                  pTab->zName);
         }
+#endif
         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
         nCol = pTab->nCol;
         pTab->nCol = -1;
@@ -130829,7 +135152,7 @@ static int selectExpander(Walker *pWalker, Select *p){
 
   /* Process NATURAL keywords, and ON and USING clauses of joins.
   */
-  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
+  if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){
     return WRC_Abort;
   }
 
@@ -130876,10 +135199,9 @@ static int selectExpander(Walker *pWalker, Select *p){
         */
         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
         if( pNew ){
-          pNew->a[pNew->nExpr-1].zName = a[k].zName;
-          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
-          a[k].zName = 0;
-          a[k].zSpan = 0;
+          pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
+          pNew->a[pNew->nExpr-1].eEName = a[k].eEName;
+          a[k].zEName = 0;
         }
         a[k].pExpr = 0;
       }else{
@@ -130918,7 +135240,7 @@ static int selectExpander(Walker *pWalker, Select *p){
 
             assert( zName );
             if( zTName && pSub
-             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
+             && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0
             ){
               continue;
             }
@@ -130928,7 +135250,7 @@ static int selectExpander(Walker *pWalker, Select *p){
             ** bit set.
             */
             if( (p->selFlags & SF_IncludeHidden)==0
-             && IsHiddenColumn(&pTab->aCol[j]) 
+             && IsHiddenColumn(&pTab->aCol[j])
             ){
               continue;
             }
@@ -130936,9 +135258,9 @@ static int selectExpander(Walker *pWalker, Select *p){
 
             if( i>0 && zTName==0 ){
               if( (pFrom->fg.jointype & JT_NATURAL)!=0
-                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
+                && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)
               ){
-                /* In a NATURAL join, omit the join columns from the 
+                /* In a NATURAL join, omit the join columns from the
                 ** table to the right of the join */
                 continue;
               }
@@ -130969,17 +135291,18 @@ static int selectExpander(Walker *pWalker, Select *p){
             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
             sqlite3TokenInit(&sColname, zColname);
             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
-            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
+            if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
+              sqlite3DbFree(db, pX->zEName);
               if( pSub ){
-                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
-                testcase( pX->zSpan==0 );
+                pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);
+                testcase( pX->zEName==0 );
               }else{
-                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
+                pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
                                            zSchemaName, zTabName, zColname);
-                testcase( pX->zSpan==0 );
+                testcase( pX->zEName==0 );
               }
-              pX->bSpanIsTab = 1;
+              pX->eEName = ENAME_TAB;
             }
             sqlite3DbFree(db, zToFree);
           }
@@ -131008,29 +135331,6 @@ static int selectExpander(Walker *pWalker, Select *p){
   return WRC_Continue;
 }
 
-/*
-** No-op routine for the parse-tree walker.
-**
-** When this routine is the Walker.xExprCallback then expression trees
-** are walked without any actions being taken at each node.  Presumably,
-** when this routine is used for Walker.xExprCallback then 
-** Walker.xSelectCallback is set to do something useful for every 
-** subquery in the parser tree.
-*/
-SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
-  UNUSED_PARAMETER2(NotUsed, NotUsed2);
-  return WRC_Continue;
-}
-
-/*
-** No-op routine for the parse-tree walker for SELECT statements.
-** subquery in the parser tree.
-*/
-SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
-  UNUSED_PARAMETER2(NotUsed, NotUsed2);
-  return WRC_Continue;
-}
-
 #if SQLITE_DEBUG
 /*
 ** Always assert.  This xSelectCallback2 implementation proves that the
@@ -131172,6 +135472,7 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   struct AggInfo_func *pFunc;
   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
   if( nReg==0 ) return;
+  if( pParse->nErr || pParse->db->mallocFailed ) return;
 #ifdef SQLITE_DEBUG
   /* Verify that all AggInfo registers are within the range specified by
   ** AggInfo.mnReg..AggInfo.mxReg */
@@ -131188,7 +135489,7 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
     if( pFunc->iDistinct>=0 ){
-      Expr *pE = pFunc->pExpr;
+      Expr *pE = pFunc->pFExpr;
       assert( !ExprHasProperty(pE, EP_xIsSelect) );
       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
@@ -131212,8 +135513,8 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
   int i;
   struct AggInfo_func *pF;
   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
-    ExprList *pList = pF->pExpr->x.pList;
-    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
+    ExprList *pList = pF->pFExpr->x.pList;
+    assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
     sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
     sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
   }
@@ -131242,22 +135543,26 @@ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
     int nArg;
     int addrNext = 0;
     int regAgg;
-    ExprList *pList = pF->pExpr->x.pList;
-    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
-    assert( !IsWindowFunc(pF->pExpr) );
-    if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){
-      Expr *pFilter = pF->pExpr->y.pWin->pFilter;
-      if( pAggInfo->nAccumulator 
-       && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL) 
+    ExprList *pList = pF->pFExpr->x.pList;
+    assert( !ExprHasProperty(pF->pFExpr, EP_xIsSelect) );
+    assert( !IsWindowFunc(pF->pFExpr) );
+    if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
+      Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
+      if( pAggInfo->nAccumulator
+       && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
+       && regAcc
       ){
+        /* If regAcc==0, there there exists some min() or max() function
+        ** without a FILTER clause that will ensure the magnet registers
+        ** are populated. */
         if( regHit==0 ) regHit = ++pParse->nMem;
-        /* If this is the first row of the group (regAcc==0), clear the
+        /* If this is the first row of the group (regAcc contains 0), clear the
         ** "magnet" register regHit so that the accumulator registers
-        ** are populated if the FILTER clause jumps over the the 
+        ** are populated if the FILTER clause jumps over the the
         ** invocation of min() or max() altogether. Or, if this is not
-        ** the first row (regAcc==1), set the magnet register so that the
-        ** accumulators are not populated unless the min()/max() is invoked and
-        ** indicates that they should be.  */
+        ** the first row (regAcc contains 1), set the magnet register so that
+        ** the accumulators are not populated unless the min()/max() is invoked
+        ** and indicates that they should be.  */
         sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
       }
       addrNext = sqlite3VdbeMakeLabel(pParse);
@@ -131272,7 +135577,7 @@ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
       regAgg = 0;
     }
     if( pF->iDistinct>=0 ){
-      if( addrNext==0 ){ 
+      if( addrNext==0 ){
         addrNext = sqlite3VdbeMakeLabel(pParse);
       }
       testcase( nArg==0 );  /* Error condition */
@@ -131308,12 +135613,12 @@ static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
   }
   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
-    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
+    sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem);
   }
 
   pAggInfo->directMode = 0;
   if( addrHitTest ){
-    sqlite3VdbeJumpHere(v, addrHitTest);
+    sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
   }
 }
 
@@ -131343,10 +135648,10 @@ static void explainSimpleCount(
 /*
 ** sqlite3WalkExpr() callback used by havingToWhere().
 **
-** If the node passed to the callback is a TK_AND node, return 
+** If the node passed to the callback is a TK_AND node, return
 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
 **
-** Otherwise, return WRC_Prune. In this case, also check if the 
+** Otherwise, return WRC_Prune. In this case, also check if the
 ** sub-expression matches the criteria for being moved to the WHERE
 ** clause. If so, add it to the WHERE clause and replace the sub-expression
 ** within the HAVING expression with a constant "1".
@@ -131426,7 +135731,7 @@ static struct SrcList_item *isSelfJoinView(
       continue;
     }
     if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
-     || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1) 
+     || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
     ){
       /* The view was modified by some other optimization such as
       ** pushDownWhereTerms() */
@@ -131525,7 +135830,7 @@ static int countOfViewOptimization(Parse *pParse, Select *p){
 #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
 
 /*
-** Generate code for the SELECT statement given in the p argument.  
+** Generate code for the SELECT statement given in the p argument.
 **
 ** The results are returned according to the SelectDest structure.
 ** See comments in sqliteInt.h for further information.
@@ -131551,10 +135856,10 @@ SQLITE_PRIVATE int sqlite3Select(
   Expr *pWhere;          /* The WHERE clause.  May be NULL */
   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   Expr *pHaving;         /* The HAVING clause.  May be NULL */
+  AggInfo *pAggInfo = 0; /* Aggregate information */
   int rc = 1;            /* Value to return from this function */
   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
-  AggInfo sAggInfo;      /* Information used by aggregate queries */
   int iEnd;              /* Address of the end of the query */
   sqlite3 *db;           /* The database connection */
   ExprList *pMinMaxOrderBy = 0;  /* Added ORDER BY for min/max queries */
@@ -131566,7 +135871,6 @@ SQLITE_PRIVATE int sqlite3Select(
     return 1;
   }
   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
-  memset(&sAggInfo, 0, sizeof(sAggInfo));
 #if SELECTTRACE_ENABLED
   SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
   if( sqlite3SelectTrace & 0x100 ){
@@ -131578,16 +135882,15 @@ SQLITE_PRIVATE int sqlite3Select(
   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
-  if( IgnorableOrderby(pDest) ){
-    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
-           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
-           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
-           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
-    /* If ORDER BY makes no difference in the output then neither does
-    ** DISTINCT so it can be removed too. */
+  if( IgnorableDistinct(pDest) ){
+    assert(pDest->eDest==SRT_Exists     || pDest->eDest==SRT_Union ||
+           pDest->eDest==SRT_Except     || pDest->eDest==SRT_Discard ||
+           pDest->eDest==SRT_DistQueue  || pDest->eDest==SRT_DistFifo );
+    /* All of these destinations are also able to ignore the ORDER BY clause */
     sqlite3ExprListDelete(db, p->pOrderBy);
     p->pOrderBy = 0;
     p->selFlags &= ~SF_Distinct;
+    p->selFlags |= SF_NoopOrderBy;
   }
   sqlite3SelectPrep(pParse, p, 0);
   if( pParse->nErr || db->mallocFailed ){
@@ -131601,16 +135904,36 @@ SQLITE_PRIVATE int sqlite3Select(
   }
 #endif
 
+  /* If the SF_UpdateFrom flag is set, then this function is being called
+  ** as part of populating the temp table for an UPDATE...FROM statement.
+  ** In this case, it is an error if the target object (pSrc->a[0]) name
+  ** or alias is duplicated within FROM clause (pSrc->a[1..n]).  */
+  if( p->selFlags & SF_UpdateFrom ){
+    struct SrcList_item *p0 = &p->pSrc->a[0];
+    for(i=1; i<p->pSrc->nSrc; i++){
+      struct SrcList_item *p1 = &p->pSrc->a[i];
+      if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
+        sqlite3ErrorMsg(pParse,
+            "target object/alias may not appear in FROM clause: %s",
+            p0->zAlias ? p0->zAlias : p0->pTab->zName
+        );
+        goto select_end;
+      }
+    }
+  }
+
   if( pDest->eDest==SRT_Output ){
     generateColumnNames(pParse, p);
   }
 
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  if( sqlite3WindowRewrite(pParse, p) ){
+  rc = sqlite3WindowRewrite(pParse, p);
+  if( rc ){
+    assert( db->mallocFailed || pParse->nErr>0 );
     goto select_end;
   }
 #if SELECTTRACE_ENABLED
-  if( sqlite3SelectTrace & 0x108 ){
+  if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
     SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
     sqlite3TreeViewSelect(0, p, 0);
   }
@@ -131621,7 +135944,7 @@ SQLITE_PRIVATE int sqlite3Select(
   memset(&sSort, 0, sizeof(sSort));
   sSort.pOrderBy = p->pOrderBy;
 
-  /* Try to various optimizations (flattening subqueries, and strength
+  /* Try to do various optimizations (flattening subqueries, and strength
   ** reduction of join operators) in the FROM clause up into the main query
   */
 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
@@ -131630,6 +135953,11 @@ SQLITE_PRIVATE int sqlite3Select(
     Select *pSub = pItem->pSelect;
     Table *pTab = pItem->pTab;
 
+    /* The expander should have already created transient Table objects
+    ** even for FROM clause elements such as subqueries that do not correspond
+    ** to a real table */
+    assert( pTab!=0 );
+
     /* Convert LEFT JOIN into JOIN if there are terms of the right table
     ** of the LEFT JOIN used in the WHERE clause.
     */
@@ -131849,7 +136177,7 @@ SQLITE_PRIVATE int sqlite3Select(
       ** set on each invocation.
       */
       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
-     
+
       pItem->regReturn = ++pParse->nMem;
       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
       VdbeComment((v, "%s", pItem->pTab->zName));
@@ -131925,7 +136253,7 @@ SQLITE_PRIVATE int sqlite3Select(
   }
 #endif
 
-  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
+  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
   ** if the select-list is the same as the ORDER BY list, then this query
   ** can be rewritten as a GROUP BY. In other words, this:
   **
@@ -131935,16 +136263,20 @@ SQLITE_PRIVATE int sqlite3Select(
   **
   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
   **
-  ** The second form is preferred as a single index (or temp-table) may be 
-  ** used for both the ORDER BY and DISTINCT processing. As originally 
-  ** written the query must use a temp-table for at least one of the ORDER 
+  ** The second form is preferred as a single index (or temp-table) may be
+  ** used for both the ORDER BY and DISTINCT processing. As originally
+  ** written the query must use a temp-table for at least one of the ORDER
   ** BY and DISTINCT, and an index or separate temp-table for the other.
   */
-  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
+  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
+#ifndef SQLITE_OMIT_WINDOWFUNC
+   && p->pWin==0
+#endif
   ){
     p->selFlags &= ~SF_Distinct;
     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
+    p->selFlags |= SF_Aggregate;
     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
     ** original setting of the SF_Distinct flag, not the current setting */
@@ -132017,9 +136349,9 @@ SQLITE_PRIVATE int sqlite3Select(
     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
                    | (p->selFlags & SF_FixedLimit);
 #ifndef SQLITE_OMIT_WINDOWFUNC
-    Window *pWin = p->pWin;      /* Master window object (or NULL) */
+    Window *pWin = p->pWin;      /* Main window object (or NULL) */
     if( pWin ){
-      sqlite3WindowCodeInit(pParse, pWin);
+      sqlite3WindowCodeInit(pParse, p);
     }
 #endif
     assert( WHERE_USE_LIMIT==SF_FixedLimit );
@@ -132044,7 +136376,7 @@ SQLITE_PRIVATE int sqlite3Select(
       }
     }
 
-    /* If sorting index that was created by a prior OP_OpenEphemeral 
+    /* If sorting index that was created by a prior OP_OpenEphemeral
     ** instruction ended up not being needed, then change the OP_OpenEphemeral
     ** into an OP_Noop.
     */
@@ -132116,8 +136448,8 @@ SQLITE_PRIVATE int sqlite3Select(
       if( p->nSelectRow>66 ) p->nSelectRow = 66;
 
       /* If there is both a GROUP BY and an ORDER BY clause and they are
-      ** identical, then it may be possible to disable the ORDER BY clause 
-      ** on the grounds that the GROUP BY will cause elements to come out 
+      ** identical, then it may be possible to disable the ORDER BY clause
+      ** on the grounds that the GROUP BY will cause elements to come out
       ** in the correct order. It also may not - the GROUP BY might use a
       ** database index that causes rows to be grouped together as required
       ** but not actually sorted. Either way, record the fact that the
@@ -132127,8 +136459,8 @@ SQLITE_PRIVATE int sqlite3Select(
         int ii;
         /* The GROUP BY processing doesn't care whether rows are delivered in
         ** ASC or DESC order - only that each group is returned contiguously.
-        ** So set the ASC/DESC flags in the GROUP BY to match those in the 
-        ** ORDER BY to maximize the chances of rows being delivered in an 
+        ** So set the ASC/DESC flags in the GROUP BY to match those in the
+        ** ORDER BY to maximize the chances of rows being delivered in an
         ** order that makes the ORDER BY redundant.  */
         for(ii=0; ii<pGroupBy->nExpr; ii++){
           u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
@@ -132150,14 +136482,21 @@ SQLITE_PRIVATE int sqlite3Select(
     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
     ** SELECT statement.
     */
+    pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
+    if( pAggInfo==0 ){
+      goto select_end;
+    }
+    pAggInfo->pNext = pParse->pAggList;
+    pParse->pAggList = pAggInfo;
+    pAggInfo->selId = p->selId;
     memset(&sNC, 0, sizeof(sNC));
     sNC.pParse = pParse;
     sNC.pSrcList = pTabList;
-    sNC.uNC.pAggInfo = &sAggInfo;
+    sNC.uNC.pAggInfo = pAggInfo;
     VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
-    sAggInfo.mnReg = pParse->nMem+1;
-    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
-    sAggInfo.pGroupBy = pGroupBy;
+    pAggInfo->mnReg = pParse->nMem+1;
+    pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
+    pAggInfo->pGroupBy = pGroupBy;
     sqlite3ExprAnalyzeAggList(&sNC, pEList);
     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
     if( pHaving ){
@@ -132170,14 +136509,14 @@ SQLITE_PRIVATE int sqlite3Select(
       }
       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
     }
-    sAggInfo.nAccumulator = sAggInfo.nColumn;
-    if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
-      minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
+    pAggInfo->nAccumulator = pAggInfo->nColumn;
+    if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
+      minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
     }else{
       minMaxFlag = WHERE_ORDERBY_NORMAL;
     }
-    for(i=0; i<sAggInfo.nFunc; i++){
-      Expr *pExpr = sAggInfo.aFunc[i].pExpr;
+    for(i=0; i<pAggInfo->nFunc; i++){
+      Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
       sNC.ncFlags |= NC_InAggFunc;
       sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
@@ -132189,22 +136528,22 @@ SQLITE_PRIVATE int sqlite3Select(
 #endif
       sNC.ncFlags &= ~NC_InAggFunc;
     }
-    sAggInfo.mxReg = pParse->nMem;
+    pAggInfo->mxReg = pParse->nMem;
     if( db->mallocFailed ) goto select_end;
 #if SELECTTRACE_ENABLED
     if( sqlite3SelectTrace & 0x400 ){
       int ii;
-      SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
+      SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
       sqlite3TreeViewSelect(0, p, 0);
-      for(ii=0; ii<sAggInfo.nColumn; ii++){
+      for(ii=0; ii<pAggInfo->nColumn; ii++){
         sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
-            ii, sAggInfo.aCol[ii].iMem);
-        sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
+            ii, pAggInfo->aCol[ii].iMem);
+        sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
       }
-      for(ii=0; ii<sAggInfo.nFunc; ii++){
+      for(ii=0; ii<pAggInfo->nFunc; ii++){
         sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
-            ii, sAggInfo.aFunc[ii].iMem);
-        sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
+            ii, pAggInfo->aFunc[ii].iMem);
+        sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
       }
     }
 #endif
@@ -132227,12 +136566,13 @@ SQLITE_PRIVATE int sqlite3Select(
       /* If there is a GROUP BY clause we might need a sorting index to
       ** implement it.  Allocate that sorting index now.  If it turns out
       ** that we do not need it after all, the OP_SorterOpen instruction
-      ** will be converted into a Noop.  
+      ** will be converted into a Noop.
       */
-      sAggInfo.sortingIdx = pParse->nTab++;
-      pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
-      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
-          sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
+      pAggInfo->sortingIdx = pParse->nTab++;
+      pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
+                                            0, pAggInfo->nColumn);
+      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
+          pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
           0, (char*)pKeyInfo, P4_KEYINFO);
 
       /* Initialize memory locations used by GROUP BY aggregate processing
@@ -132279,7 +136619,7 @@ SQLITE_PRIVATE int sqlite3Select(
         int nCol;
         int nGroupBy;
 
-        explainTempTable(pParse, 
+        explainTempTable(pParse,
             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
                     "DISTINCT" : "GROUP BY");
 
@@ -132287,8 +136627,8 @@ SQLITE_PRIVATE int sqlite3Select(
         nGroupBy = pGroupBy->nExpr;
         nCol = nGroupBy;
         j = nGroupBy;
-        for(i=0; i<sAggInfo.nColumn; i++){
-          if( sAggInfo.aCol[i].iSorterColumn>=j ){
+        for(i=0; i<pAggInfo->nColumn; i++){
+          if( pAggInfo->aCol[i].iSorterColumn>=j ){
             nCol++;
             j++;
           }
@@ -132296,8 +136636,8 @@ SQLITE_PRIVATE int sqlite3Select(
         regBase = sqlite3GetTempRange(pParse, nCol);
         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
         j = nGroupBy;
-        for(i=0; i<sAggInfo.nColumn; i++){
-          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
+        for(i=0; i<pAggInfo->nColumn; i++){
+          struct AggInfo_col *pCol = &pAggInfo->aCol[i];
           if( pCol->iSorterColumn>=j ){
             int r1 = j + regBase;
             sqlite3ExprCodeGetColumnOfTable(v,
@@ -132307,16 +136647,16 @@ SQLITE_PRIVATE int sqlite3Select(
         }
         regRecord = sqlite3GetTempReg(pParse);
         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
-        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
+        sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
         sqlite3ReleaseTempReg(pParse, regRecord);
         sqlite3ReleaseTempRange(pParse, regBase, nCol);
         sqlite3WhereEnd(pWInfo);
-        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
+        pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
         sortOut = sqlite3GetTempReg(pParse);
         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
-        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
+        sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
-        sAggInfo.useSortingIdx = 1;
+        pAggInfo->useSortingIdx = 1;
       }
 
       /* If the index or temporary table used by the GROUP BY sort
@@ -132324,9 +136664,9 @@ SQLITE_PRIVATE int sqlite3Select(
       ** clause, cancel the ephemeral table open coded earlier.
       **
       ** This is an optimization - the correct answer should result regardless.
-      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 
+      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
       ** disable this optimization for testing purposes.  */
-      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 
+      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
       ){
         sSort.pOrderBy = 0;
@@ -132340,14 +136680,14 @@ SQLITE_PRIVATE int sqlite3Select(
       */
       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
       if( groupBySort ){
-        sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
+        sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
                           sortOut, sortPTab);
       }
       for(j=0; j<pGroupBy->nExpr; j++){
         if( groupBySort ){
           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
         }else{
-          sAggInfo.directMode = 1;
+          pAggInfo->directMode = 1;
           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
         }
       }
@@ -132377,14 +136717,14 @@ SQLITE_PRIVATE int sqlite3Select(
       ** the current row
       */
       sqlite3VdbeJumpHere(v, addr1);
-      updateAccumulator(pParse, iUseFlag, &sAggInfo);
+      updateAccumulator(pParse, iUseFlag, pAggInfo);
       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
       VdbeComment((v, "indicate data in accumulator"));
 
       /* End of the loop
       */
       if( groupBySort ){
-        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
+        sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx, addrTopOfLoop);
         VdbeCoverage(v);
       }else{
         sqlite3WhereEnd(pWInfo);
@@ -132417,7 +136757,7 @@ SQLITE_PRIVATE int sqlite3Select(
       VdbeCoverage(v);
       VdbeComment((v, "Groupby result generator entry point"));
       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
-      finalizeAggFunctions(pParse, &sAggInfo);
+      finalizeAggFunctions(pParse, pAggInfo);
       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
       selectInnerLoop(pParse, p, -1, &sSort,
                       &sDistinct, pDest,
@@ -132428,16 +136768,15 @@ SQLITE_PRIVATE int sqlite3Select(
       /* Generate a subroutine that will reset the group-by accumulator
       */
       sqlite3VdbeResolveLabel(v, addrReset);
-      resetAccumulator(pParse, &sAggInfo);
+      resetAccumulator(pParse, pAggInfo);
       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
       VdbeComment((v, "indicate accumulator empty"));
       sqlite3VdbeAddOp1(v, OP_Return, regReset);
-     
+
     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
     else {
-#ifndef SQLITE_OMIT_BTREECOUNT
       Table *pTab;
-      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
+      if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
         /* If isSimpleCount() returns a pointer to a Table structure, then
         ** the SQL statement is of the form:
         **
@@ -132456,7 +136795,7 @@ SQLITE_PRIVATE int sqlite3Select(
         Index *pIdx;                         /* Iterator variable */
         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
         Index *pBest = 0;                    /* Best index found so far */
-        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
+        Pgno iRoot = pTab->tnum;             /* Root page of scanned b-tree */
 
         sqlite3CodeVerifySchema(pParse, iDb);
         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
@@ -132467,17 +136806,19 @@ SQLITE_PRIVATE int sqlite3Select(
         **
         ** (2013-10-03) Do not count the entries in a partial index.
         **
-        ** In practice the KeyInfo structure will not be used. It is only 
+        ** In practice the KeyInfo structure will not be used. It is only
         ** passed to keep OP_OpenRead happy.
         */
         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
-        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
-          if( pIdx->bUnordered==0
-           && pIdx->szIdxRow<pTab->szTabRow
-           && pIdx->pPartIdxWhere==0
-           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
-          ){
-            pBest = pIdx;
+        if( !p->pSrc->a[0].fg.notIndexed ){
+          for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
+            if( pIdx->bUnordered==0
+             && pIdx->szIdxRow<pTab->szTabRow
+             && pIdx->pPartIdxWhere==0
+             && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
+            ){
+              pBest = pIdx;
+            }
           }
         }
         if( pBest ){
@@ -132486,17 +136827,16 @@ SQLITE_PRIVATE int sqlite3Select(
         }
 
         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
-        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
+        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
         if( pKeyInfo ){
           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
         }
-        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
+        sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);
         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
         explainSimpleCount(pParse, pTab, pBest);
-      }else
-#endif /* SQLITE_OMIT_BTREECOUNT */
-      {
+      }else{
         int regAcc = 0;           /* "populate accumulators" flag */
+        int addrSkip;
 
         /* If there are accumulator registers but no min() or max() functions
         ** without FILTER clauses, allocate register regAcc. Register regAcc
@@ -132505,14 +136845,18 @@ SQLITE_PRIVATE int sqlite3Select(
         ** that the accumulator registers are (a) updated only once if
         ** there are no min() or max functions or (b) always updated for the
         ** first row visited by the aggregate, so that they are updated at
-        ** least once even if the FILTER clause means the min() or max() 
+        ** least once even if the FILTER clause means the min() or max()
         ** function visits zero rows.  */
-        if( sAggInfo.nAccumulator ){
-          for(i=0; i<sAggInfo.nFunc; i++){
-            if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue;
-            if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
+        if( pAggInfo->nAccumulator ){
+          for(i=0; i<pAggInfo->nFunc; i++){
+            if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
+              continue;
+            }
+            if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
+              break;
+            }
           }
-          if( i==sAggInfo.nFunc ){
+          if( i==pAggInfo->nFunc ){
             regAcc = ++pParse->nMem;
             sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
           }
@@ -132523,7 +136867,7 @@ SQLITE_PRIVATE int sqlite3Select(
         ** of output.
         */
         assert( p->pGroupBy==0 );
-        resetAccumulator(pParse, &sAggInfo);
+        resetAccumulator(pParse, pAggInfo);
 
         /* If this query is a candidate for the min/max optimization, then
         ** minMaxFlag will have been previously set to either
@@ -132539,24 +136883,23 @@ SQLITE_PRIVATE int sqlite3Select(
         if( pWInfo==0 ){
           goto select_end;
         }
-        updateAccumulator(pParse, regAcc, &sAggInfo);
+        updateAccumulator(pParse, regAcc, pAggInfo);
         if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
-        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
-          sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
-          VdbeComment((v, "%s() by index",
-                (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
+        addrSkip = sqlite3WhereOrderByLimitOptLabel(pWInfo);
+        if( addrSkip!=sqlite3WhereContinueLabel(pWInfo) ){
+          sqlite3VdbeGoto(v, addrSkip);
         }
         sqlite3WhereEnd(pWInfo);
-        finalizeAggFunctions(pParse, &sAggInfo);
+        finalizeAggFunctions(pParse, pAggInfo);
       }
 
       sSort.pOrderBy = 0;
       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
-      selectInnerLoop(pParse, p, -1, 0, 0, 
+      selectInnerLoop(pParse, p, -1, 0, 0,
                       pDest, addrEnd, addrEnd);
     }
     sqlite3VdbeResolveLabel(v, addrEnd);
-    
+
   } /* endif aggregate query */
 
   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
@@ -132586,8 +136929,25 @@ SQLITE_PRIVATE int sqlite3Select(
   */
 select_end:
   sqlite3ExprListDelete(db, pMinMaxOrderBy);
-  sqlite3DbFree(db, sAggInfo.aCol);
-  sqlite3DbFree(db, sAggInfo.aFunc);
+#ifdef SQLITE_DEBUG
+  if( pAggInfo && !db->mallocFailed ){
+    for(i=0; i<pAggInfo->nColumn; i++){
+      Expr *pExpr = pAggInfo->aCol[i].pCExpr;
+      assert( pExpr!=0 || db->mallocFailed );
+      if( pExpr==0 ) continue;
+      assert( pExpr->pAggInfo==pAggInfo );
+      assert( pExpr->iAgg==i );
+    }
+    for(i=0; i<pAggInfo->nFunc; i++){
+      Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
+      assert( pExpr!=0 || db->mallocFailed );
+      if( pExpr==0 ) continue;
+      assert( pExpr->pAggInfo==pAggInfo );
+      assert( pExpr->iAgg==i );
+    }
+  }
+#endif
+
 #if SELECTTRACE_ENABLED
   SELECTTRACE(0x1,pParse,p,("end processing\n"));
   if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
@@ -132711,7 +137071,7 @@ malloc_failed:
 ** at the conclusion of the call.
 **
 ** The result that is written to ***pazResult is held in memory obtained
-** from malloc().  But the caller cannot free this memory directly.  
+** from malloc().  But the caller cannot free this memory directly.
 ** Instead, the entire table should be passed to sqlite3_free_table() when
 ** the calling procedure is finished using it.
 */
@@ -132829,6 +137189,7 @@ SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerS
     sqlite3SelectDelete(db, pTmp->pSelect);
     sqlite3IdListDelete(db, pTmp->pIdList);
     sqlite3UpsertDelete(db, pTmp->pUpsert);
+    sqlite3SrcListDelete(db, pTmp->pFrom);
     sqlite3DbFree(db, pTmp->zSpan);
 
     sqlite3DbFree(db, pTmp);
@@ -132836,7 +137197,7 @@ SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerS
 }
 
 /*
-** Given table pTab, return a list of all the triggers attached to 
+** Given table pTab, return a list of all the triggers attached to
 ** the table. The list is connected by Trigger.pNext pointers.
 **
 ** All of the triggers on pTab that are in the same database as pTab
@@ -132863,7 +137224,7 @@ SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
       Trigger *pTrig = (Trigger *)sqliteHashData(p);
       if( pTrig->pTabSchema==pTab->pSchema
-       && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
+       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
       ){
         pTrig->pNext = (pList ? pList : pTab->pTrigger);
         pList = pTrig;
@@ -132931,7 +137292,7 @@ SQLITE_PRIVATE void sqlite3BeginTrigger(
   **                                                 ^^^^^^^^
   **
   ** To maintain backwards compatibility, ignore the database
-  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
+  ** name on pTableName if we are reparsing out of the schema table
   */
   if( db->init.busy && iDb!=1 ){
     sqlite3DbFree(db, pTableName->a[0].zDatabase);
@@ -132959,22 +137320,11 @@ SQLITE_PRIVATE void sqlite3BeginTrigger(
   pTab = sqlite3SrcListLookup(pParse, pTableName);
   if( !pTab ){
     /* The table does not exist. */
-    if( db->init.iDb==1 ){
-      /* Ticket #3810.
-      ** Normally, whenever a table is dropped, all associated triggers are
-      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
-      ** and the table is dropped by a different database connection, the
-      ** trigger is not visible to the database connection that does the
-      ** drop so the trigger cannot be dropped.  This results in an
-      ** "orphaned trigger" - a trigger whose associated table is missing.
-      */
-      db->init.orphanTrigger = 1;
-    }
-    goto trigger_cleanup;
+    goto trigger_orphan_error;
   }
   if( IsVirtual(pTab) ){
     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
-    goto trigger_cleanup;
+    goto trigger_orphan_error;
   }
 
   /* Check that the trigger name is not reserved and that no trigger of the
@@ -133010,14 +137360,14 @@ SQLITE_PRIVATE void sqlite3BeginTrigger(
   ** of triggers.
   */
   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
-    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
+    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
-    goto trigger_cleanup;
+    goto trigger_orphan_error;
   }
   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
         " trigger on table: %S", pTableName, 0);
-    goto trigger_cleanup;
+    goto trigger_orphan_error;
   }
 
 #ifndef SQLITE_OMIT_AUTHORIZATION
@@ -133077,6 +137427,23 @@ trigger_cleanup:
   }else{
     assert( pParse->pNewTrigger==pTrigger );
   }
+  return;
+
+trigger_orphan_error:
+  if( db->init.iDb==1 ){
+    /* Ticket #3810.
+    ** Normally, whenever a table is dropped, all associated triggers are
+    ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
+    ** and the table is dropped by a different database connection, the
+    ** trigger is not visible to the database connection that does the
+    ** drop so the trigger cannot be dropped.  This results in an
+    ** "orphaned trigger" - a trigger whose associated table is missing.
+    **
+    ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
+    */
+    db->init.orphanTrigger = 1;
+  }
+  goto trigger_cleanup;
 }
 
 /*
@@ -133106,8 +137473,8 @@ SQLITE_PRIVATE void sqlite3FinishTrigger(
   }
   sqlite3TokenInit(&nameToken, pTrig->zName);
   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
-  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
-   || sqlite3FixExpr(&sFix, pTrig->pWhen) 
+  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
+   || sqlite3FixExpr(&sFix, pTrig->pWhen)
   ){
     goto triggerfinish_cleanup;
   }
@@ -133121,21 +137488,22 @@ SQLITE_PRIVATE void sqlite3FinishTrigger(
 #endif
 
   /* if we are not initializing,
-  ** build the sqlite_master entry
+  ** build the sqlite_schema entry
   */
   if( !db->init.busy ){
     Vdbe *v;
     char *z;
 
-    /* Make an entry in the sqlite_master table */
+    /* Make an entry in the sqlite_schema table */
     v = sqlite3GetVdbe(pParse);
     if( v==0 ) goto triggerfinish_cleanup;
     sqlite3BeginWriteOperation(pParse, 0, iDb);
     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
     testcase( z==0 );
     sqlite3NestedParse(pParse,
-       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
-       db->aDb[iDb].zDbSName, MASTER_NAME, zName,
+       "INSERT INTO %Q." DFLT_SCHEMA_TABLE
+       " VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
+       db->aDb[iDb].zDbSName, zName,
        pTrig->table, z);
     sqlite3DbFree(db, z);
     sqlite3ChangeCookie(pParse, iDb);
@@ -133175,14 +137543,14 @@ static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
   int i;
   if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
   return z;
-}    
+}
 
 /*
 ** Turn a SELECT statement (that the pSelect parameter points to) into
 ** a trigger step.  Return a pointer to a TriggerStep structure.
 **
 ** The parser calls this routine when it finds a SELECT statement in
-** body of a TRIGGER.  
+** body of a TRIGGER.
 */
 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
   sqlite3 *db,                /* Database connection */
@@ -133288,6 +137656,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
   Parse *pParse,          /* Parser */
   Token *pTableName,   /* Name of the table to be updated */
+  SrcList *pFrom,
   ExprList *pEList,    /* The SET clause: list of column and new values */
   Expr *pWhere,        /* The WHERE clause */
   u8 orconf,           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
@@ -133302,16 +137671,20 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
     if( IN_RENAME_OBJECT ){
       pTriggerStep->pExprList = pEList;
       pTriggerStep->pWhere = pWhere;
+      pTriggerStep->pFrom = pFrom;
       pEList = 0;
       pWhere = 0;
+      pFrom = 0;
     }else{
       pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
       pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
+      pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
     }
     pTriggerStep->orconf = orconf;
   }
   sqlite3ExprListDelete(db, pEList);
   sqlite3ExprDelete(db, pWhere);
+  sqlite3SrcListDelete(db, pFrom);
   return pTriggerStep;
 }
 
@@ -133344,7 +137717,7 @@ SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
   return pTriggerStep;
 }
 
-/* 
+/*
 ** Recursively delete a Trigger structure
 */
 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
@@ -133358,7 +137731,7 @@ SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
 }
 
 /*
-** This function is called to drop a trigger from the database schema. 
+** This function is called to drop a trigger from the database schema.
 **
 ** This may be called directly from the parser and therefore identifies
 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
@@ -133383,7 +137756,7 @@ SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr)
   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
   for(i=OMIT_TEMPDB; i<db->nDb; i++){
     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
-    if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
+    if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
     assert( sqlite3SchemaMutexHeld(db, j, 0) );
     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
     if( pTrigger ) break;
@@ -133413,7 +137786,7 @@ static Table *tableOfTrigger(Trigger *pTrigger){
 
 
 /*
-** Drop a trigger given a pointer to that trigger. 
+** Drop a trigger given a pointer to that trigger.
 */
 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   Table   *pTable;
@@ -133442,8 +137815,8 @@ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
   */
   if( (v = sqlite3GetVdbe(pParse))!=0 ){
     sqlite3NestedParse(pParse,
-       "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
-       db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
+       "DELETE FROM %Q." DFLT_SCHEMA_TABLE " WHERE name=%Q AND type='trigger'",
+       db->aDb[iDb].zDbSName, pTrigger->zName
     );
     sqlite3ChangeCookie(pParse, iDb);
     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
@@ -133465,8 +137838,12 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const ch
       Table *pTab = tableOfTrigger(pTrigger);
       if( pTab ){
         Trigger **pp;
-        for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
-        *pp = (*pp)->pNext;
+        for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
+          if( *pp==pTrigger ){
+            *pp = (*pp)->pNext;
+            break;
+          }
+        }
       }
     }
     sqlite3DeleteTrigger(db, pTrigger);
@@ -133487,14 +137864,14 @@ static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
   int e;
   if( pIdList==0 || NEVER(pEList==0) ) return 1;
   for(e=0; e<pEList->nExpr; e++){
-    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
+    if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
   }
-  return 0; 
+  return 0;
 }
 
 /*
 ** Return a list of all triggers on table pTab if there exists at least
-** one trigger that must be fired when an operation of type 'op' is 
+** one trigger that must be fired when an operation of type 'op' is
 ** performed on the table, and, if that operation is an UPDATE, if at
 ** least one of the columns in pChanges is being modified.
 */
@@ -133534,37 +137911,40 @@ SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
 ** trigger is in TEMP in which case it can refer to any other database it
 ** wants.
 */
-static SrcList *targetSrcList(
+SQLITE_PRIVATE SrcList *sqlite3TriggerStepSrc(
   Parse *pParse,       /* The parsing context */
   TriggerStep *pStep   /* The trigger containing the target token */
 ){
   sqlite3 *db = pParse->db;
-  int iDb;             /* Index of the database to use */
-  SrcList *pSrc;       /* SrcList to be returned */
-
+  SrcList *pSrc;                  /* SrcList to be returned */
+  char *zName = sqlite3DbStrDup(db, pStep->zTarget);
   pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
+  assert( pSrc==0 || pSrc->nSrc==1 );
+  assert( zName || pSrc==0 );
   if( pSrc ){
-    assert( pSrc->nSrc>0 );
-    pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
-    iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
-    if( iDb==0 || iDb>=2 ){
-      const char *zDb;
-      assert( iDb<db->nDb );
-      zDb = db->aDb[iDb].zDbSName;
-      pSrc->a[pSrc->nSrc-1].zDatabase =  sqlite3DbStrDup(db, zDb);
+    Schema *pSchema = pStep->pTrig->pSchema;
+    pSrc->a[0].zName = zName;
+    if( pSchema!=db->aDb[1].pSchema ){
+      pSrc->a[0].pSchema = pSchema;
     }
+    if( pStep->pFrom ){
+      SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
+      pSrc = sqlite3SrcListAppendList(pParse, pSrc, pDup);
+    }
+  }else{
+    sqlite3DbFree(db, zName);
   }
   return pSrc;
 }
 
 /*
-** Generate VDBE code for the statements inside the body of a single 
+** Generate VDBE code for the statements inside the body of a single
 ** trigger.
 */
 static int codeTriggerProgram(
   Parse *pParse,            /* The parser context */
   TriggerStep *pStepList,   /* List of statements inside the trigger body */
-  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
+  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
 ){
   TriggerStep *pStep;
   Vdbe *v = pParse->pVdbe;
@@ -133600,27 +137980,27 @@ static int codeTriggerProgram(
 
     switch( pStep->op ){
       case TK_UPDATE: {
-        sqlite3Update(pParse, 
-          targetSrcList(pParse, pStep),
-          sqlite3ExprListDup(db, pStep->pExprList, 0), 
-          sqlite3ExprDup(db, pStep->pWhere, 0), 
+        sqlite3Update(pParse,
+          sqlite3TriggerStepSrc(pParse, pStep),
+          sqlite3ExprListDup(db, pStep->pExprList, 0),
+          sqlite3ExprDup(db, pStep->pWhere, 0),
           pParse->eOrconf, 0, 0, 0
         );
         break;
       }
       case TK_INSERT: {
-        sqlite3Insert(pParse, 
-          targetSrcList(pParse, pStep),
-          sqlite3SelectDup(db, pStep->pSelect, 0), 
-          sqlite3IdListDup(db, pStep->pIdList), 
+        sqlite3Insert(pParse,
+          sqlite3TriggerStepSrc(pParse, pStep),
+          sqlite3SelectDup(db, pStep->pSelect, 0),
+          sqlite3IdListDup(db, pStep->pIdList),
           pParse->eOrconf,
           sqlite3UpsertDup(db, pStep->pUpsert)
         );
         break;
       }
       case TK_DELETE: {
-        sqlite3DeleteFrom(pParse, 
-          targetSrcList(pParse, pStep),
+        sqlite3DeleteFrom(pParse,
+          sqlite3TriggerStepSrc(pParse, pStep),
           sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
         );
         break;
@@ -133633,7 +138013,7 @@ static int codeTriggerProgram(
         sqlite3SelectDelete(db, pSelect);
         break;
       }
-    } 
+    }
     if( pStep->op!=TK_SELECT ){
       sqlite3VdbeAddOp0(v, OP_ResetCount);
     }
@@ -133678,7 +138058,7 @@ static void transferParseError(Parse *pTo, Parse *pFrom){
 }
 
 /*
-** Create and populate a new TriggerPrg object with a sub-program 
+** Create and populate a new TriggerPrg object with a sub-program
 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
 */
 static TriggerPrg *codeRowTrigger(
@@ -133701,7 +138081,7 @@ static TriggerPrg *codeRowTrigger(
   assert( pTop->pVdbe );
 
   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
-  ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
+  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
   ** list of the top-level Parse object sooner rather than later.  */
   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
   if( !pPrg ) return 0;
@@ -133715,7 +138095,7 @@ static TriggerPrg *codeRowTrigger(
   pPrg->aColmask[0] = 0xffffffff;
   pPrg->aColmask[1] = 0xffffffff;
 
-  /* Allocate and populate a new Parse context to use for coding the 
+  /* Allocate and populate a new Parse context to use for coding the
   ** trigger sub-program.  */
   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
   if( !pSubParse ) return 0;
@@ -133731,7 +138111,7 @@ static TriggerPrg *codeRowTrigger(
 
   v = sqlite3GetVdbe(pSubParse);
   if( v ){
-    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
+    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
       pTrigger->zName, onErrorText(orconf),
       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
@@ -133741,19 +138121,19 @@ static TriggerPrg *codeRowTrigger(
     ));
 #ifndef SQLITE_OMIT_TRACE
     if( pTrigger->zName ){
-      sqlite3VdbeChangeP4(v, -1, 
+      sqlite3VdbeChangeP4(v, -1,
         sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
       );
     }
 #endif
 
     /* If one was specified, code the WHEN clause. If it evaluates to false
-    ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
+    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
     ** OP_Halt inserted at the end of the program.  */
     if( pTrigger->pWhen ){
       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
-      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
-       && db->mallocFailed==0 
+      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
+       && db->mallocFailed==0
       ){
         iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
@@ -133790,7 +138170,7 @@ static TriggerPrg *codeRowTrigger(
 
   return pPrg;
 }
-    
+
 /*
 ** Return a pointer to a TriggerPrg object containing the sub-program for
 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
@@ -133812,8 +138192,8 @@ static TriggerPrg *getRowTrigger(
   ** process of being coded). If this is the case, then an entry with
   ** a matching TriggerPrg.pTrigger field will be present somewhere
   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
-  for(pPrg=pRoot->pTriggerPrg; 
-      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
+  for(pPrg=pRoot->pTriggerPrg;
+      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
       pPrg=pPrg->pNext
   );
 
@@ -133826,7 +138206,7 @@ static TriggerPrg *getRowTrigger(
 }
 
 /*
-** Generate code for the trigger program associated with trigger p on 
+** Generate code for the trigger program associated with trigger p on
 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
 ** function are the same as those described in the header function for
 ** sqlite3CodeRowTrigger()
@@ -133844,7 +138224,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
   pPrg = getRowTrigger(pParse, p, pTab, orconf);
   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
 
-  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
+  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
   ** is a pointer to the sub-vdbe containing the trigger program.  */
   if( pPrg ){
     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
@@ -133873,7 +138253,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
 ** If there are no triggers that fire at the specified time for the specified
 ** operation on pTab, this function is a no-op.
 **
-** The reg argument is the address of the first in an array of registers 
+** The reg argument is the address of the first in an array of registers
 ** that contain the values substituted for the new.* and old.* references
 ** in the trigger program. If N is the number of columns in table pTab
 ** (a copy of pTab->nCol), then registers are populated as follows:
@@ -133890,12 +138270,12 @@ SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
 **   reg+N+N+1      NEW.* value of right-most column of pTab
 **
 ** For ON DELETE triggers, the registers containing the NEW.* values will
-** never be accessed by the trigger program, so they are not allocated or 
-** populated by the caller (there is no data to populate them with anyway). 
+** never be accessed by the trigger program, so they are not allocated or
+** populated by the caller (there is no data to populate them with anyway).
 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
 ** are never accessed, and so are not allocated by the caller. So, for an
 ** ON INSERT trigger, the value passed to this function as parameter reg
-** is not a readable register, although registers (reg+N) through 
+** is not a readable register, although registers (reg+N) through
 ** (reg+N+N+1) are.
 **
 ** Parameter orconf is the default conflict resolution algorithm for the
@@ -133927,12 +138307,12 @@ SQLITE_PRIVATE void sqlite3CodeRowTrigger(
     ** or else it must be a TEMP trigger. */
     assert( p->pSchema!=0 );
     assert( p->pTabSchema!=0 );
-    assert( p->pSchema==p->pTabSchema 
+    assert( p->pSchema==p->pTabSchema
          || p->pSchema==pParse->db->aDb[1].pSchema );
 
     /* Determine whether we should code this trigger */
-    if( p->op==op 
-     && p->tr_tm==tr_tm 
+    if( p->op==op
+     && p->tr_tm==tr_tm
      && checkColumnOverlap(p->pColumns, pChanges)
     ){
       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
@@ -133941,9 +138321,9 @@ SQLITE_PRIVATE void sqlite3CodeRowTrigger(
 }
 
 /*
-** Triggers may access values stored in the old.* or new.* pseudo-table. 
-** This function returns a 32-bit bitmask indicating which columns of the 
-** old.* or new.* tables actually are used by triggers. This information 
+** Triggers may access values stored in the old.* or new.* pseudo-table.
+** This function returns a 32-bit bitmask indicating which columns of the
+** old.* or new.* tables actually are used by triggers. This information
 ** may be used by the caller, for example, to avoid having to load the entire
 ** old.* record into memory when executing an UPDATE or DELETE command.
 **
@@ -133953,7 +138333,7 @@ SQLITE_PRIVATE void sqlite3CodeRowTrigger(
 ** are more than 32 columns in the table, and at least one of the columns
 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
 **
-** It is not possible to determine if the old.rowid or new.rowid column is 
+** It is not possible to determine if the old.rowid or new.rowid column is
 ** accessed by triggers. The caller must always assume that it is.
 **
 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
@@ -134030,10 +138410,10 @@ static void updateVirtualTable(
 
 /*
 ** The most recently coded instruction was an OP_Column to retrieve the
-** i-th column of table pTab. This routine sets the P4 parameter of the 
+** i-th column of table pTab. This routine sets the P4 parameter of the
 ** OP_Column to the default value, if any.
 **
-** The default value of a column is specified by a DEFAULT clause in the 
+** The default value of a column is specified by a DEFAULT clause in the
 ** column definition. This was either supplied by the user when the table
 ** was created, or added later to the table definition by an ALTER TABLE
 ** command. If the latter, then the row-records in the table btree on disk
@@ -134042,21 +138422,21 @@ static void updateVirtualTable(
 ** If the former, then all row-records are guaranteed to include a value
 ** for the column and the P4 value is not required.
 **
-** Column definitions created by an ALTER TABLE command may only have 
+** Column definitions created by an ALTER TABLE command may only have
 ** literal default values specified: a number, null or a string. (If a more
-** complicated default expression value was provided, it is evaluated 
+** complicated default expression value was provided, it is evaluated
 ** when the ALTER TABLE is executed and one of the literal values written
-** into the sqlite_master table.)
+** into the sqlite_schema table.)
 **
 ** Therefore, the P4 parameter is only required if the default value for
 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
 ** function is capable of transforming these types of expressions into
 ** sqlite3_value objects.
 **
-** If parameter iReg is not negative, code an OP_RealAffinity instruction
-** on register iReg. This is used when an equivalent integer value is 
-** stored in place of an 8-byte floating point value in order to save 
-** space.
+** If column as REAL affinity and the table is an ordinary b-tree table
+** (not a virtual table) then the value might have been stored as an
+** integer.  In that case, add an OP_RealAffinity opcode to make sure
+** it has been converted into REAL.
 */
 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
   assert( pTab!=0 );
@@ -134066,14 +138446,14 @@ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
     Column *pCol = &pTab->aCol[i];
     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
     assert( i<pTab->nCol );
-    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
+    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
                          pCol->affinity, &pValue);
     if( pValue ){
       sqlite3VdbeAppendP4(v, pValue, P4_MEM);
     }
   }
 #ifndef SQLITE_OMIT_FLOATING_POINT
-  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
+  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
     sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
   }
 #endif
@@ -134131,11 +138511,148 @@ static int indexWhereClauseMightChange(
 }
 
 /*
+** Allocate and return a pointer to an expression of type TK_ROW with
+** Expr.iColumn set to value (iCol+1). The resolver will modify the
+** expression to be a TK_COLUMN reading column iCol of the first
+** table in the source-list (pSrc->a[0]).
+*/
+static Expr *exprRowColumn(Parse *pParse, int iCol){
+  Expr *pRet = sqlite3PExpr(pParse, TK_ROW, 0, 0);
+  if( pRet ) pRet->iColumn = iCol+1;
+  return pRet;
+}
+
+/*
+** Assuming both the pLimit and pOrderBy parameters are NULL, this function
+** generates VM code to run the query:
+**
+**   SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
+**
+** and write the results to the ephemeral table already opened as cursor
+** iEph. None of pChanges, pTabList or pWhere are modified or consumed by
+** this function, they must be deleted by the caller.
+**
+** Or, if pLimit and pOrderBy are not NULL, and pTab is not a view:
+**
+**   SELECT <other-columns>, pChanges FROM pTabList
+**   WHERE pWhere
+**   GROUP BY <other-columns>
+**   ORDER BY pOrderBy LIMIT pLimit
+**
+** If pTab is a view, the GROUP BY clause is omitted.
+**
+** Exactly how results are written to table iEph, and exactly what
+** the <other-columns> in the query above are is determined by the type
+** of table pTabList->a[0].pTab.
+**
+** If the table is a WITHOUT ROWID table, then argument pPk must be its
+** PRIMARY KEY. In this case <other-columns> are the primary key columns
+** of the table, in order. The results of the query are written to ephemeral
+** table iEph as index keys, using OP_IdxInsert.
+**
+** If the table is actually a view, then <other-columns> are all columns of
+** the view. The results are written to the ephemeral table iEph as records
+** with automatically assigned integer keys.
+**
+** If the table is a virtual or ordinary intkey table, then <other-columns>
+** is its rowid. For a virtual table, the results are written to iEph as
+** records with automatically assigned integer keys For intkey tables, the
+** rowid value in <other-columns> is used as the integer key, and the
+** remaining fields make up the table record.
+*/
+static void updateFromSelect(
+  Parse *pParse,                  /* Parse context */
+  int iEph,                       /* Cursor for open eph. table */
+  Index *pPk,                     /* PK if table 0 is WITHOUT ROWID */
+  ExprList *pChanges,             /* List of expressions to return */
+  SrcList *pTabList,              /* List of tables to select from */
+  Expr *pWhere,                   /* WHERE clause for query */
+  ExprList *pOrderBy,             /* ORDER BY clause */
+  Expr *pLimit                    /* LIMIT clause */
+){
+  int i;
+  SelectDest dest;
+  Select *pSelect = 0;
+  ExprList *pList = 0;
+  ExprList *pGrp = 0;
+  Expr *pLimit2 = 0;
+  ExprList *pOrderBy2 = 0;
+  sqlite3 *db = pParse->db;
+  Table *pTab = pTabList->a[0].pTab;
+  SrcList *pSrc;
+  Expr *pWhere2;
+  int eDest;
+
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+  if( pOrderBy && pLimit==0 ) {
+    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on UPDATE");
+    return;
+  }
+  pOrderBy2 = sqlite3ExprListDup(db, pOrderBy, 0);
+  pLimit2 = sqlite3ExprDup(db, pLimit, 0);
+#else
+  UNUSED_PARAMETER(pOrderBy);
+  UNUSED_PARAMETER(pLimit);
+#endif
+
+  pSrc = sqlite3SrcListDup(db, pTabList, 0);
+  pWhere2 = sqlite3ExprDup(db, pWhere, 0);
+
+  assert( pTabList->nSrc>1 );
+  if( pSrc ){
+    pSrc->a[0].iCursor = -1;
+    pSrc->a[0].pTab->nTabRef--;
+    pSrc->a[0].pTab = 0;
+  }
+  if( pPk ){
+    for(i=0; i<pPk->nKeyCol; i++){
+      Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+      if( pLimit ){
+        pGrp = sqlite3ExprListAppend(pParse, pGrp, sqlite3ExprDup(db, pNew, 0));
+      }
+#endif
+      pList = sqlite3ExprListAppend(pParse, pList, pNew);
+    }
+    eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
+  }else if( pTab->pSelect ){
+    for(i=0; i<pTab->nCol; i++){
+      pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
+    }
+    eDest = SRT_Table;
+  }else{
+    eDest = IsVirtual(pTab) ? SRT_Table : SRT_Upfrom;
+    pList = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
+#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
+    if( pLimit ){
+      pGrp = sqlite3ExprListAppend(pParse, 0, sqlite3PExpr(pParse,TK_ROW,0,0));
+    }
+#endif
+  }
+  if( ALWAYS(pChanges) ){
+    for(i=0; i<pChanges->nExpr; i++){
+      pList = sqlite3ExprListAppend(pParse, pList,
+          sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
+      );
+    }
+  }
+  pSelect = sqlite3SelectNew(pParse, pList,
+      pSrc, pWhere2, pGrp, 0, pOrderBy2, SF_UpdateFrom|SF_IncludeHidden, pLimit2
+  );
+  sqlite3SelectDestInit(&dest, eDest, iEph);
+  dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
+  sqlite3Select(pParse, pSelect, &dest);
+  sqlite3SelectDelete(db, pSelect);
+}
+
+/*
 ** Process an UPDATE statement.
 **
-**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
-**          \_______/ \________/     \______/       \________________/
-*            onError   pTabList      pChanges             pWhere
+**   UPDATE OR IGNORE tbl SET a=b, c=d FROM tbl2... WHERE e<5 AND f NOT NULL;
+**          \_______/ \_/     \______/      \_____/       \________________/
+**           onError   |      pChanges         |                pWhere
+**                     \_______________________/
+**                               pTabList
 */
 SQLITE_PRIVATE void sqlite3Update(
   Parse *pParse,         /* The parser context */
@@ -134147,10 +138664,10 @@ SQLITE_PRIVATE void sqlite3Update(
   Expr *pLimit,          /* LIMIT clause. May be null */
   Upsert *pUpsert        /* ON CONFLICT clause, or null */
 ){
-  int i, j;              /* Loop counters */
+  int i, j, k;           /* Loop counters */
   Table *pTab;           /* The table to be updated */
   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
-  WhereInfo *pWInfo;     /* Information about the WHERE clause */
+  WhereInfo *pWInfo = 0; /* Information about the WHERE clause */
   Vdbe *v;               /* The virtual database engine */
   Index *pIdx;           /* For looping over indices */
   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
@@ -134169,6 +138686,7 @@ SQLITE_PRIVATE void sqlite3Update(
   u8 chngRowid;          /* Rowid changed in a normal table */
   u8 chngKey;            /* Either chngPk or chngRowid */
   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
+  int iRowidExpr = -1;   /* Index of "rowid=" (or IPK) assignment in pChanges */
   AuthContext sContext;  /* The authorization context */
   NameContext sNC;       /* The name-context to resolve expressions in */
   int iDb;               /* Database containing the table being updated */
@@ -134191,6 +138709,8 @@ SQLITE_PRIVATE void sqlite3Update(
   int iPk = 0;           /* First of nPk cells holding PRIMARY KEY value */
   i16 nPk = 0;           /* Number of components of the PRIMARY KEY */
   int bReplace = 0;      /* True if REPLACE conflict resolution might happen */
+  int bFinishSeek = 1;   /* The OP_FinishSeek opcode is needed */
+  int nChangeFrom = 0;   /* If there is a FROM, pChanges->nExpr, else 0 */
 
   /* Register Allocations */
   int regRowCount = 0;   /* A count of rows changed */
@@ -134206,9 +138726,8 @@ SQLITE_PRIVATE void sqlite3Update(
   if( pParse->nErr || db->mallocFailed ){
     goto update_cleanup;
   }
-  assert( pTabList->nSrc==1 );
 
-  /* Locate the table which we want to update. 
+  /* Locate the table which we want to update.
   */
   pTab = sqlite3SrcListLookup(pParse, pTabList);
   if( pTab==0 ) goto update_cleanup;
@@ -134231,8 +138750,15 @@ SQLITE_PRIVATE void sqlite3Update(
 # define isView 0
 #endif
 
+  /* If there was a FROM clause, set nChangeFrom to the number of expressions
+  ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
+  ** clause if this function is being called to generate code for part of
+  ** an UPSERT statement.  */
+  nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
+  assert( nChangeFrom==0 || pUpsert==0 );
+
 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
-  if( !isView ){
+  if( !isView && nChangeFrom==0 ){
     pWhere = sqlite3LimitWhere(
         pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
     );
@@ -134276,7 +138802,7 @@ SQLITE_PRIVATE void sqlite3Update(
   }
   pTabList->a[0].iCursor = iDataCur;
 
-  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
+  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
   ** Initialize aXRef[] and aToOpen[] to their default values.
   */
   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
@@ -134294,6 +138820,10 @@ SQLITE_PRIVATE void sqlite3Update(
   sNC.uNC.pUpsert = pUpsert;
   sNC.ncFlags = NC_UUpsert;
 
+  /* Begin generating code. */
+  v = sqlite3GetVdbe(pParse);
+  if( v==0 ) goto update_cleanup;
+
   /* Resolve the column names in all the expressions of the
   ** of the UPDATE statement.  Also find the column index
   ** for each column to be updated in the pChanges array.  For each
@@ -134302,28 +138832,42 @@ SQLITE_PRIVATE void sqlite3Update(
   */
   chngRowid = chngPk = 0;
   for(i=0; i<pChanges->nExpr; i++){
-    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
+    /* If this is an UPDATE with a FROM clause, do not resolve expressions
+    ** here. The call to sqlite3Select() below will do that. */
+    if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
       goto update_cleanup;
     }
     for(j=0; j<pTab->nCol; j++){
-      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
+      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){
         if( j==pTab->iPKey ){
           chngRowid = 1;
           pRowidExpr = pChanges->a[i].pExpr;
+          iRowidExpr = i;
         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
           chngPk = 1;
         }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+        else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
+          testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
+          testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
+          sqlite3ErrorMsg(pParse,
+             "cannot UPDATE generated column \"%s\"",
+             pTab->aCol[j].zName);
+          goto update_cleanup;
+        }
+#endif
         aXRef[j] = i;
         break;
       }
     }
     if( j>=pTab->nCol ){
-      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
+      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
         j = -1;
         chngRowid = 1;
         pRowidExpr = pChanges->a[i].pExpr;
+        iRowidExpr = i;
       }else{
-        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
+        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
         pParse->checkSchema = 1;
         goto update_cleanup;
       }
@@ -134347,7 +138891,34 @@ SQLITE_PRIVATE void sqlite3Update(
   assert( chngPk==0 || chngPk==1 );
   chngKey = chngRowid + chngPk;
 
-  /* The SET expressions are not actually used inside the WHERE loop.  
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  /* Mark generated columns as changing if their generator expressions
+  ** reference any changing column.  The actual aXRef[] value for
+  ** generated expressions is not used, other than to check to see that it
+  ** is non-negative, so the value of aXRef[] for generated columns can be
+  ** set to any non-negative number.  We use 99999 so that the value is
+  ** obvious when looking at aXRef[] in a symbolic debugger.
+  */
+  if( pTab->tabFlags & TF_HasGenerated ){
+    int bProgress;
+    testcase( pTab->tabFlags & TF_HasVirtual );
+    testcase( pTab->tabFlags & TF_HasStored );
+    do{
+      bProgress = 0;
+      for(i=0; i<pTab->nCol; i++){
+        if( aXRef[i]>=0 ) continue;
+        if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
+        if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,
+                                               aXRef, chngRowid) ){
+          aXRef[i] = 99999;
+          bProgress = 1;
+        }
+      }
+    }while( bProgress );
+  }
+#endif
+
+  /* The SET expressions are not actually used inside the WHERE loop.
   ** So reset the colUsed mask. Unless this is a virtual table. In that
   ** case, set all bits of the colUsed mask (to ensure that the virtual
   ** table implementation makes all columns available).
@@ -134386,14 +138957,11 @@ SQLITE_PRIVATE void sqlite3Update(
   }
   aRegIdx[nAllIdx] = ++pParse->nMem;  /* Register storing the table record */
   if( bReplace ){
-    /* If REPLACE conflict resolution might be invoked, open cursors on all 
+    /* If REPLACE conflict resolution might be invoked, open cursors on all
     ** indexes in case they are needed to delete records.  */
     memset(aToOpen, 1, nIdx+1);
   }
 
-  /* Begin generating code. */
-  v = sqlite3GetVdbe(pParse);
-  if( v==0 ) goto update_cleanup;
   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
   sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
 
@@ -134427,8 +138995,8 @@ SQLITE_PRIVATE void sqlite3Update(
   ** an ephemeral table.
   */
 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
-  if( isView ){
-    sqlite3MaterializeView(pParse, pTab, 
+  if( nChangeFrom==0 && isView ){
+    sqlite3MaterializeView(pParse, pTab,
         pWhere, pOrderBy, pLimit, iDataCur
     );
     pOrderBy = 0;
@@ -134439,7 +139007,7 @@ SQLITE_PRIVATE void sqlite3Update(
   /* Resolve the column names in all the expressions in the
   ** WHERE clause.
   */
-  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
+  if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pWhere) ){
     goto update_cleanup;
   }
 
@@ -134466,122 +139034,153 @@ SQLITE_PRIVATE void sqlite3Update(
     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   }
 
-  if( HasRowid(pTab) ){
+  if( nChangeFrom==0 && HasRowid(pTab) ){
     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
+    iEph = pParse->nTab++;
+    addrOpen = sqlite3VdbeAddOp3(v, OP_OpenEphemeral, iEph, 0, regRowSet);
   }else{
-    assert( pPk!=0 );
-    nPk = pPk->nKeyCol;
+    assert( pPk!=0 || HasRowid(pTab) );
+    nPk = pPk ? pPk->nKeyCol : 0;
     iPk = pParse->nMem+1;
     pParse->nMem += nPk;
+    pParse->nMem += nChangeFrom;
     regKey = ++pParse->nMem;
     if( pUpsert==0 ){
+      int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
       iEph = pParse->nTab++;
-        sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
-      addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
-      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
+      if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
+      addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nEphCol);
+      if( pPk ){
+        KeyInfo *pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pPk);
+        if( pKeyInfo ){
+          pKeyInfo->nAllField = nEphCol;
+          sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
+        }
+      }
+      if( nChangeFrom ){
+        updateFromSelect(
+            pParse, iEph, pPk, pChanges, pTabList, pWhere, pOrderBy, pLimit
+        );
+#ifndef SQLITE_OMIT_SUBQUERY
+        if( isView ) iDataCur = iEph;
+#endif
+      }
     }
   }
-  
-  if( pUpsert ){
-    /* If this is an UPSERT, then all cursors have already been opened by
-    ** the outer INSERT and the data cursor should be pointing at the row
-    ** that is to be updated.  So bypass the code that searches for the
-    ** row(s) to be updated.
-    */
-    pWInfo = 0;
-    eOnePass = ONEPASS_SINGLE;
-    sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
+
+  if( nChangeFrom ){
+    sqlite3MultiWrite(pParse);
+    eOnePass = ONEPASS_OFF;
+    nKey = nPk;
+    regKey = iPk;
   }else{
-    /* Begin the database scan. 
-    **
-    ** Do not consider a single-pass strategy for a multi-row update if
-    ** there are any triggers or foreign keys to process, or rows may
-    ** be deleted as a result of REPLACE conflict handling. Any of these
-    ** things might disturb a cursor being used to scan through the table
-    ** or index, causing a single-pass approach to malfunction.  */
-    flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
-    if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
-      flags |= WHERE_ONEPASS_MULTIROW;
-    }
-    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
-    if( pWInfo==0 ) goto update_cleanup;
-  
-    /* A one-pass strategy that might update more than one row may not
-    ** be used if any column of the index used for the scan is being
-    ** updated. Otherwise, if there is an index on "b", statements like
-    ** the following could create an infinite loop:
-    **
-    **   UPDATE t1 SET b=b+1 WHERE b>?
-    **
-    ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
-    ** strategy that uses an index for which one or more columns are being
-    ** updated.  */
-    eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
-    if( eOnePass!=ONEPASS_SINGLE ){
-      sqlite3MultiWrite(pParse);
-      if( eOnePass==ONEPASS_MULTI ){
-        int iCur = aiCurOnePass[1];
-        if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
-          eOnePass = ONEPASS_OFF;
+    if( pUpsert ){
+      /* If this is an UPSERT, then all cursors have already been opened by
+      ** the outer INSERT and the data cursor should be pointing at the row
+      ** that is to be updated.  So bypass the code that searches for the
+      ** row(s) to be updated.
+      */
+      pWInfo = 0;
+      eOnePass = ONEPASS_SINGLE;
+      sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
+      bFinishSeek = 0;
+    }else{
+      /* Begin the database scan.
+      **
+      ** Do not consider a single-pass strategy for a multi-row update if
+      ** there are any triggers or foreign keys to process, or rows may
+      ** be deleted as a result of REPLACE conflict handling. Any of these
+      ** things might disturb a cursor being used to scan through the table
+      ** or index, causing a single-pass approach to malfunction.  */
+      flags = WHERE_ONEPASS_DESIRED;
+      if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
+        flags |= WHERE_ONEPASS_MULTIROW;
+      }
+      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags,iIdxCur);
+      if( pWInfo==0 ) goto update_cleanup;
+
+      /* A one-pass strategy that might update more than one row may not
+      ** be used if any column of the index used for the scan is being
+      ** updated. Otherwise, if there is an index on "b", statements like
+      ** the following could create an infinite loop:
+      **
+      **   UPDATE t1 SET b=b+1 WHERE b>?
+      **
+      ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
+      ** strategy that uses an index for which one or more columns are being
+      ** updated.  */
+      eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
+      bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
+      if( eOnePass!=ONEPASS_SINGLE ){
+        sqlite3MultiWrite(pParse);
+        if( eOnePass==ONEPASS_MULTI ){
+          int iCur = aiCurOnePass[1];
+          if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
+            eOnePass = ONEPASS_OFF;
+          }
+          assert( iCur!=iDataCur || !HasRowid(pTab) );
         }
-        assert( iCur!=iDataCur || !HasRowid(pTab) );
       }
     }
-  }
 
-  if( HasRowid(pTab) ){
-    /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
-    ** mode, write the rowid into the FIFO. In either of the one-pass modes,
-    ** leave it in register regOldRowid.  */
-    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
-    if( eOnePass==ONEPASS_OFF ){
-      /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */
-      aRegIdx[nAllIdx] = ++pParse->nMem;
-      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
-    }
-  }else{
-    /* Read the PK of the current row into an array of registers. In
-    ** ONEPASS_OFF mode, serialize the array into a record and store it in
-    ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
-    ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table 
-    ** is not required) and leave the PK fields in the array of registers.  */
-    for(i=0; i<nPk; i++){
-      assert( pPk->aiColumn[i]>=0 );
-      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
-    }
-    if( eOnePass ){
-      if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
-      nKey = nPk;
-      regKey = iPk;
+    if( HasRowid(pTab) ){
+      /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
+      ** mode, write the rowid into the FIFO. In either of the one-pass modes,
+      ** leave it in register regOldRowid.  */
+      sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
+      if( eOnePass==ONEPASS_OFF ){
+        aRegIdx[nAllIdx] = ++pParse->nMem;
+        sqlite3VdbeAddOp3(v, OP_Insert, iEph, regRowSet, regOldRowid);
+      }else{
+        if( ALWAYS(addrOpen) ) sqlite3VdbeChangeToNoop(v, addrOpen);
+      }
     }else{
-      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
-                        sqlite3IndexAffinityStr(db, pPk), nPk);
-      sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
+      /* Read the PK of the current row into an array of registers. In
+      ** ONEPASS_OFF mode, serialize the array into a record and store it in
+      ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
+      ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
+      ** is not required) and leave the PK fields in the array of registers.  */
+      for(i=0; i<nPk; i++){
+        assert( pPk->aiColumn[i]>=0 );
+        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
+                                        pPk->aiColumn[i], iPk+i);
+      }
+      if( eOnePass ){
+        if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
+        nKey = nPk;
+        regKey = iPk;
+      }else{
+        sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
+                          sqlite3IndexAffinityStr(db, pPk), nPk);
+        sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
+      }
     }
   }
 
   if( pUpsert==0 ){
-    if( eOnePass!=ONEPASS_MULTI ){
+    if( nChangeFrom==0 && eOnePass!=ONEPASS_MULTI ){
       sqlite3WhereEnd(pWInfo);
     }
-  
+
     if( !isView ){
       int addrOnce = 0;
-  
+
       /* Open every index that needs updating. */
       if( eOnePass!=ONEPASS_OFF ){
         if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
         if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
       }
-  
+
       if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
         addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
       }
       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
                                  aToOpen, 0, 0);
-      if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
+      if( addrOnce ){
+        sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
+      }
     }
-  
+
     /* Top of the update loop */
     if( eOnePass!=ONEPASS_OFF ){
       if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
@@ -134595,15 +139194,35 @@ SQLITE_PRIVATE void sqlite3Update(
       sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
       VdbeCoverageIf(v, pPk==0);
       VdbeCoverageIf(v, pPk!=0);
-    }else if( pPk ){
+    }else if( pPk || nChangeFrom ){
       labelContinue = sqlite3VdbeMakeLabel(pParse);
       sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
-      addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
-      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
-      VdbeCoverage(v);
+      addrTop = sqlite3VdbeCurrentAddr(v);
+      if( nChangeFrom ){
+        if( !isView ){
+          if( pPk ){
+            for(i=0; i<nPk; i++){
+              sqlite3VdbeAddOp3(v, OP_Column, iEph, i, iPk+i);
+            }
+            sqlite3VdbeAddOp4Int(
+                v, OP_NotFound, iDataCur, labelContinue, iPk, nPk
+            ); VdbeCoverage(v);
+          }else{
+            sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
+            sqlite3VdbeAddOp3(
+                v, OP_NotExists, iDataCur, labelContinue, regOldRowid
+            ); VdbeCoverage(v);
+          }
+        }
+      }else{
+        sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
+        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey,0);
+        VdbeCoverage(v);
+      }
     }else{
-      labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
-                               regOldRowid);
+      sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
+      labelContinue = sqlite3VdbeMakeLabel(pParse);
+      addrTop = sqlite3VdbeAddOp2(v, OP_Rowid, iEph, regOldRowid);
       VdbeCoverage(v);
       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
       VdbeCoverage(v);
@@ -134616,7 +139235,12 @@ SQLITE_PRIVATE void sqlite3Update(
   ** already populated.  */
   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
   if( chngRowid ){
-    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
+    assert( iRowidExpr>=0 );
+    if( nChangeFrom==0 ){
+      sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
+    }else{
+      sqlite3VdbeAddOp3(v, OP_Column, iEph, iRowidExpr, regNewRowid);
+    }
     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
   }
 
@@ -134624,18 +139248,20 @@ SQLITE_PRIVATE void sqlite3Update(
   ** information is needed */
   if( chngPk || hasFK || pTrigger ){
     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
-    oldmask |= sqlite3TriggerColmask(pParse, 
+    oldmask |= sqlite3TriggerColmask(pParse,
         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
     );
     for(i=0; i<pTab->nCol; i++){
+      u32 colFlags = pTab->aCol[i].colFlags;
+      k = sqlite3TableColumnToStorage(pTab, i) + regOld;
       if( oldmask==0xffffffff
        || (i<32 && (oldmask & MASKBIT32(i))!=0)
-       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
+       || (colFlags & COLFLAG_PRIMKEY)!=0
       ){
         testcase(  oldmask!=0xffffffff && i==31 );
-        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
+        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
       }else{
-        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
+        sqlite3VdbeAddOp2(v, OP_Null, 0, k);
       }
     }
     if( chngRowid==0 && pPk==0 ){
@@ -134651,71 +139277,98 @@ SQLITE_PRIVATE void sqlite3Update(
   ** If there are one or more BEFORE triggers, then do not populate the
   ** registers associated with columns that are (a) not modified by
   ** this UPDATE statement and (b) not accessed by new.* references. The
-  ** values for registers not modified by the UPDATE must be reloaded from 
-  ** the database after the BEFORE triggers are fired anyway (as the trigger 
+  ** values for registers not modified by the UPDATE must be reloaded from
+  ** the database after the BEFORE triggers are fired anyway (as the trigger
   ** may have modified them). So not loading those that are not going to
   ** be used eliminates some redundant opcodes.
   */
   newmask = sqlite3TriggerColmask(
       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
   );
-  for(i=0; i<pTab->nCol; i++){
+  for(i=0, k=regNew; i<pTab->nCol; i++, k++){
     if( i==pTab->iPKey ){
-      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
+      sqlite3VdbeAddOp2(v, OP_Null, 0, k);
+    }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
+      if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
     }else{
       j = aXRef[i];
       if( j>=0 ){
-        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
+        if( nChangeFrom ){
+          int nOff = (isView ? pTab->nCol : nPk);
+          assert( eOnePass==ONEPASS_OFF );
+          sqlite3VdbeAddOp3(v, OP_Column, iEph, nOff+j, k);
+        }else{
+          sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
+        }
       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
-        /* This branch loads the value of a column that will not be changed 
+        /* This branch loads the value of a column that will not be changed
         ** into a register. This is done if there are no BEFORE triggers, or
         ** if there are one or more BEFORE triggers that use this value via
         ** a new.* reference in a trigger program.
         */
         testcase( i==31 );
         testcase( i==32 );
-        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
+        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
+        bFinishSeek = 0;
       }else{
-        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
+        sqlite3VdbeAddOp2(v, OP_Null, 0, k);
       }
     }
   }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+  if( pTab->tabFlags & TF_HasGenerated ){
+    testcase( pTab->tabFlags & TF_HasVirtual );
+    testcase( pTab->tabFlags & TF_HasStored );
+    sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
+  }
+#endif
 
   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   ** verified. One could argue that this is wrong.
   */
   if( tmask&TRIGGER_BEFORE ){
     sqlite3TableAffinity(v, pTab, regNew);
-    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
+    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
 
-    /* The row-trigger may have deleted the row being updated. In this
-    ** case, jump to the next row. No updates or AFTER triggers are 
-    ** required. This behavior - what happens when the row being updated
-    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
-    ** documentation.
-    */
-    if( pPk ){
-      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
-      VdbeCoverage(v);
-    }else{
-      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
-      VdbeCoverage(v);
-    }
+    if( !isView ){
+      /* The row-trigger may have deleted the row being updated. In this
+      ** case, jump to the next row. No updates or AFTER triggers are
+      ** required. This behavior - what happens when the row being updated
+      ** is deleted or renamed by a BEFORE trigger - is left undefined in the
+      ** documentation.
+      */
+      if( pPk ){
+        sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
+        VdbeCoverage(v);
+      }else{
+        sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
+        VdbeCoverage(v);
+      }
 
-    /* After-BEFORE-trigger-reload-loop:
-    ** If it did not delete it, the BEFORE trigger may still have modified 
-    ** some of the columns of the row being updated. Load the values for 
-    ** all columns not modified by the update statement into their registers
-    ** in case this has happened. Only unmodified columns are reloaded.
-    ** The values computed for modified columns use the values before the
-    ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
-    ** for an example.
-    */
-    for(i=0; i<pTab->nCol; i++){
-      if( aXRef[i]<0 && i!=pTab->iPKey ){
-        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
+      /* After-BEFORE-trigger-reload-loop:
+      ** If it did not delete it, the BEFORE trigger may still have modified
+      ** some of the columns of the row being updated. Load the values for
+      ** all columns not modified by the update statement into their registers
+      ** in case this has happened. Only unmodified columns are reloaded.
+      ** The values computed for modified columns use the values before the
+      ** BEFORE trigger runs.  See test case trigger1-18.0 (added 2018-04-26)
+      ** for an example.
+      */
+      for(i=0, k=regNew; i<pTab->nCol; i++, k++){
+        if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
+          if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
+        }else if( aXRef[i]<0 && i!=pTab->iPKey ){
+          sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
+        }
+      }
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+      if( pTab->tabFlags & TF_HasGenerated ){
+        testcase( pTab->tabFlags & TF_HasVirtual );
+        testcase( pTab->tabFlags & TF_HasStored );
+        sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
       }
+#endif
     }
   }
 
@@ -134746,11 +139399,20 @@ SQLITE_PRIVATE void sqlite3Update(
     /* Delete the index entries associated with the current record.  */
     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
 
+    /* We must run the OP_FinishSeek opcode to resolve a prior
+    ** OP_DeferredSeek if there is any possibility that there have been
+    ** no OP_Column opcodes since the OP_DeferredSeek was issued.  But
+    ** we want to avoid the OP_FinishSeek if possible, as running it
+    ** costs CPU cycles. */
+    if( bFinishSeek ){
+      sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
+    }
+
     /* If changing the rowid value, or if there are foreign key constraints
     ** to process, delete the old record. Otherwise, add a noop OP_Delete
     ** to invoke the pre-update hook.
     **
-    ** That (regNew==regnewRowid+1) is true is also important for the 
+    ** That (regNew==regnewRowid+1) is true is also important for the
     ** pre-update hook. If the caller invokes preupdate_new(), the returned
     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
     ** is the column index supplied by the user.
@@ -134777,29 +139439,29 @@ SQLITE_PRIVATE void sqlite3Update(
     if( hasFK ){
       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
     }
-  
+
     /* Insert the new index entries and the new record. */
     sqlite3CompleteInsertion(
-        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx, 
-        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0), 
+        pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
+        OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
         0, 0
     );
 
     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
     ** handle rows (possibly in other tables) that refer via a foreign key
-    ** to the row just updated. */ 
+    ** to the row just updated. */
     if( hasFK ){
       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
     }
   }
 
-  /* Increment the row counter 
+  /* Increment the row counter
   */
   if( regRowCount ){
     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
   }
 
-  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
+  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
 
   /* Repeat the above with the next record to be updated, until
@@ -134810,11 +139472,9 @@ SQLITE_PRIVATE void sqlite3Update(
   }else if( eOnePass==ONEPASS_MULTI ){
     sqlite3VdbeResolveLabel(v, labelContinue);
     sqlite3WhereEnd(pWInfo);
-  }else if( pPk ){
+  }else{
     sqlite3VdbeResolveLabel(v, labelContinue);
     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
-  }else{
-    sqlite3VdbeGoto(v, labelContinue);
   }
   sqlite3VdbeResolveLabel(v, labelBreak);
 
@@ -134860,8 +139520,8 @@ update_cleanup:
 /*
 ** Generate code for an UPDATE of a virtual table.
 **
-** There are two possible strategies - the default and the special 
-** "onepass" strategy. Onepass is only used if the virtual table 
+** There are two possible strategies - the default and the special
+** "onepass" strategy. Onepass is only used if the virtual table
 ** implementation indicates that pWhere may match at most one row.
 **
 ** The default strategy is to create an ephemeral table that contains
@@ -134893,7 +139553,7 @@ static void updateVirtualTable(
   int i;                    /* Loop counter */
   sqlite3 *db = pParse->db; /* Database connection */
   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
-  WhereInfo *pWInfo;
+  WhereInfo *pWInfo = 0;
   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
   int regArg;                     /* First register in VUpdate arg array */
   int regRec;                     /* Register in which to assemble record */
@@ -134911,73 +139571,115 @@ static void updateVirtualTable(
   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
   regArg = pParse->nMem + 1;
   pParse->nMem += nArg;
-  regRec = ++pParse->nMem;
-  regRowid = ++pParse->nMem;
+  if( pSrc->nSrc>1 ){
+    Index *pPk = 0;
+    Expr *pRow;
+    ExprList *pList;
+    if( HasRowid(pTab) ){
+      if( pRowid ){
+        pRow = sqlite3ExprDup(db, pRowid, 0);
+      }else{
+        pRow = sqlite3PExpr(pParse, TK_ROW, 0, 0);
+      }
+    }else{
+      i16 iPk;      /* PRIMARY KEY column */
+      pPk = sqlite3PrimaryKeyIndex(pTab);
+      assert( pPk!=0 );
+      assert( pPk->nKeyCol==1 );
+      iPk = pPk->aiColumn[0];
+      if( aXRef[iPk]>=0 ){
+        pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
+      }else{
+        pRow = exprRowColumn(pParse, iPk);
+      }
+    }
+    pList = sqlite3ExprListAppend(pParse, 0, pRow);
 
-  /* Start scanning the virtual table */
-  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
-  if( pWInfo==0 ) return;
+    for(i=0; i<pTab->nCol; i++){
+      if( aXRef[i]>=0 ){
+        pList = sqlite3ExprListAppend(pParse, pList,
+          sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
+        );
+      }else{
+        pList = sqlite3ExprListAppend(pParse, pList, exprRowColumn(pParse, i));
+      }
+    }
 
-  /* Populate the argument registers. */
-  for(i=0; i<pTab->nCol; i++){
-    if( aXRef[i]>=0 ){
-      sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
-    }else{
-      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
-      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
+    updateFromSelect(pParse, ephemTab, pPk, pList, pSrc, pWhere, 0, 0);
+    sqlite3ExprListDelete(db, pList);
+    eOnePass = ONEPASS_OFF;
+  }else{
+    regRec = ++pParse->nMem;
+    regRowid = ++pParse->nMem;
+
+    /* Start scanning the virtual table */
+    pWInfo = sqlite3WhereBegin(pParse, pSrc,pWhere,0,0,WHERE_ONEPASS_DESIRED,0);
+    if( pWInfo==0 ) return;
+
+    /* Populate the argument registers. */
+    for(i=0; i<pTab->nCol; i++){
+      assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
+      if( aXRef[i]>=0 ){
+        sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
+      }else{
+        sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
+        sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* For sqlite3_vtab_nochange() */
+      }
     }
-  }
-  if( HasRowid(pTab) ){
-    sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
-    if( pRowid ){
-      sqlite3ExprCode(pParse, pRowid, regArg+1);
+    if( HasRowid(pTab) ){
+      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
+      if( pRowid ){
+        sqlite3ExprCode(pParse, pRowid, regArg+1);
+      }else{
+        sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
+      }
     }else{
-      sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
+      Index *pPk;   /* PRIMARY KEY index */
+      i16 iPk;      /* PRIMARY KEY column */
+      pPk = sqlite3PrimaryKeyIndex(pTab);
+      assert( pPk!=0 );
+      assert( pPk->nKeyCol==1 );
+      iPk = pPk->aiColumn[0];
+      sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
+      sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
     }
-  }else{
-    Index *pPk;   /* PRIMARY KEY index */
-    i16 iPk;      /* PRIMARY KEY column */
-    pPk = sqlite3PrimaryKeyIndex(pTab);
-    assert( pPk!=0 );
-    assert( pPk->nKeyCol==1 );
-    iPk = pPk->aiColumn[0];
-    sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
-    sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
-  }
 
-  eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
+    eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
 
-  /* There is no ONEPASS_MULTI on virtual tables */
-  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
+    /* There is no ONEPASS_MULTI on virtual tables */
+    assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
 
-  if( eOnePass ){
-    /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
-    ** above. */
-    sqlite3VdbeChangeToNoop(v, addr);
-    sqlite3VdbeAddOp1(v, OP_Close, iCsr);
-  }else{
-    /* Create a record from the argument register contents and insert it into
-    ** the ephemeral table. */
-    sqlite3MultiWrite(pParse);
-    sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
-#ifdef SQLITE_DEBUG
-    /* Signal an assert() within OP_MakeRecord that it is allowed to
-    ** accept no-change records with serial_type 10 */
-    sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
+    if( eOnePass ){
+      /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
+      ** above. */
+      sqlite3VdbeChangeToNoop(v, addr);
+      sqlite3VdbeAddOp1(v, OP_Close, iCsr);
+    }else{
+      /* Create a record from the argument register contents and insert it into
+      ** the ephemeral table. */
+      sqlite3MultiWrite(pParse);
+      sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
+#if defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_NULL_TRIM)
+      /* Signal an assert() within OP_MakeRecord that it is allowed to
+      ** accept no-change records with serial_type 10 */
+      sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
 #endif
-    sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
-    sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
+      sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
+      sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
+    }
   }
 
 
   if( eOnePass==ONEPASS_OFF ){
     /* End the virtual table scan */
-    sqlite3WhereEnd(pWInfo);
+    if( pSrc->nSrc==1 ){
+      sqlite3WhereEnd(pWInfo);
+    }
 
     /* Begin scannning through the ephemeral table. */
     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
 
-    /* Extract arguments from the current row of the ephemeral table and 
+    /* Extract arguments from the current row of the ephemeral table and
     ** invoke the VUpdate method.  */
     for(i=0; i<nArg; i++){
       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
@@ -135111,11 +139813,11 @@ SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
   rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
   if( rc ) return rc;
 
-  /* Check to see if the conflict target matches the rowid. */  
+  /* Check to see if the conflict target matches the rowid. */
   pTab = pTabList->a[0].pTab;
   pTarget = pUpsert->pUpsertTarget;
   iCursor = pTabList->a[0].iCursor;
-  if( HasRowid(pTab) 
+  if( HasRowid(pTab)
    && pTarget->nExpr==1
    && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
    && pTerm->iColumn==XN_ROWID
@@ -135230,7 +139932,7 @@ SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
       for(i=0; i<nPk; i++){
         int k;
         assert( pPk->aiColumn[i]>=0 );
-        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
+        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
         sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
         VdbeComment((v, "%s.%s", pIdx->zName,
                     pTab->aCol[pPk->aiColumn[i]].zName));
@@ -135238,8 +139940,9 @@ SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
       sqlite3VdbeVerifyAbortable(v, OE_Abort);
       i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
       VdbeCoverage(v);
-      sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0, 
+      sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
             "corrupt database", P4_STATIC);
+      sqlite3MayAbort(pParse);
       sqlite3VdbeJumpHere(v, i);
     }
   }
@@ -135306,7 +140009,7 @@ static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
     assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
     /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
     ** or INSERT.  Historically there have been attacks that first
-    ** corrupt the sqlite_master.sql field with other kinds of statements
+    ** corrupt the sqlite_schema.sql field with other kinds of statements
     ** then run VACUUM to get those statements to execute at inappropriate
     ** times. */
     if( zSubSql
@@ -135448,7 +140151,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
     zOut = "";
   }
 
-  /* Save the current value of the database flags so that it can be 
+  /* Save the current value of the database flags so that it can be
   ** restored before returning. Then set the writable-schema flag, and
   ** disable CHECK and foreign key constraints.  */
   saved_flags = db->flags;
@@ -135498,18 +140201,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
     }
     db->mDbFlags |= DBFLAG_VacuumInto;
   }
-  nRes = sqlite3BtreeGetOptimalReserve(pMain);
-
-  /* A VACUUM cannot change the pagesize of an encrypted database. */
-#ifdef SQLITE_HAS_CODEC
-  if( db->nextPagesize ){
-    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
-    int nKey;
-    char *zKey;
-    sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
-    if( nKey ) db->nextPagesize = 0;
-  }
-#endif
+  nRes = sqlite3BtreeGetRequestedReserve(pMain);
 
   sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
   sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
@@ -135548,14 +140240,14 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
   */
   db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
   rc = execSqlF(db, pzErrMsg,
-      "SELECT sql FROM \"%w\".sqlite_master"
+      "SELECT sql FROM \"%w\".sqlite_schema"
       " WHERE type='table'AND name<>'sqlite_sequence'"
       " AND coalesce(rootpage,1)>0",
       zDbMain
   );
   if( rc!=SQLITE_OK ) goto end_of_vacuum;
   rc = execSqlF(db, pzErrMsg,
-      "SELECT sql FROM \"%w\".sqlite_master"
+      "SELECT sql FROM \"%w\".sqlite_schema"
       " WHERE type='index'",
       zDbMain
   );
@@ -135569,7 +140261,7 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
   rc = execSqlF(db, pzErrMsg,
       "SELECT'INSERT INTO vacuum_db.'||quote(name)"
       "||' SELECT*FROM\"%w\".'||quote(name)"
-      "FROM vacuum_db.sqlite_master "
+      "FROM vacuum_db.sqlite_schema "
       "WHERE type='table'AND coalesce(rootpage,1)>0",
       zDbMain
   );
@@ -135580,18 +140272,18 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
   /* Copy the triggers, views, and virtual tables from the main database
   ** over to the temporary database.  None of these objects has any
   ** associated storage, so all we have to do is copy their entries
-  ** from the SQLITE_MASTER table.
+  ** from the schema table.
   */
   rc = execSqlF(db, pzErrMsg,
-      "INSERT INTO vacuum_db.sqlite_master"
-      " SELECT*FROM \"%w\".sqlite_master"
+      "INSERT INTO vacuum_db.sqlite_schema"
+      " SELECT*FROM \"%w\".sqlite_schema"
       " WHERE type IN('view','trigger')"
       " OR(type='table'AND rootpage=0)",
       zDbMain
   );
   if( rc ) goto end_of_vacuum;
 
-  /* At this point, there is a write transaction open on both the 
+  /* At this point, there is a write transaction open on both the
   ** vacuum database and the main database. Assuming no error occurs,
   ** both transactions are closed by this block - the main database
   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
@@ -135615,8 +140307,8 @@ SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
     };
 
-    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
-    assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );
+    assert( SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pTemp) );
+    assert( pOut!=0 || SQLITE_TXN_WRITE==sqlite3BtreeTxnState(pMain) );
 
     /* Copy Btree meta values */
     for(i=0; i<ArraySize(aCopy); i+=2){
@@ -135653,7 +140345,7 @@ end_of_vacuum:
   db->nChange = saved_nChange;
   db->nTotalChange = saved_nTotalChange;
   db->mTrace = saved_mTrace;
-  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
+  sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
 
   /* Currently there is an SQL level transaction open on the vacuum
   ** database. No locks are held on any other files (since the main file
@@ -135671,7 +140363,7 @@ end_of_vacuum:
   }
 
   /* This both clears the schemas and reduces the size of the db->aDb[]
-  ** array. */ 
+  ** array. */
   sqlite3ResetAllSchemasOfConnection(db);
 
   return rc;
@@ -135700,7 +140392,7 @@ end_of_vacuum:
 /*
 ** Before a virtual table xCreate() or xConnect() method is invoked, the
 ** sqlite3.pVtabCtx member variable is set to point to an instance of
-** this struct allocated on the stack. It is used by the implementation of 
+** this struct allocated on the stack. It is used by the implementation of
 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
 ** are invoked only from within xCreate and xConnect methods.
 */
@@ -135858,7 +140550,7 @@ SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){
 /*
 ** Lock the virtual table so that it cannot be disconnected.
 ** Locks nest.  Every lock should have a corresponding unlock.
-** If an unlock is omitted, resources leaks will occur.  
+** If an unlock is omitted, resources leaks will occur.
 **
 ** If a disconnect is attempted while a virtual table is locked,
 ** the disconnect is deferred until all locks have been removed.
@@ -135870,7 +140562,7 @@ SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
 
 /*
 ** pTab is a pointer to a Table structure representing a virtual-table.
-** Return a pointer to the VTable object used by connection db to access 
+** Return a pointer to the VTable object used by connection db to access
 ** this virtual-table, if one has been created, or NULL otherwise.
 */
 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
@@ -135905,7 +140597,7 @@ SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
 /*
 ** Table p is a virtual table. This function moves all elements in the
 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
-** database connections to be disconnected at the next opportunity. 
+** database connections to be disconnected at the next opportunity.
 ** Except, if argument db is not NULL, then the entry associated with
 ** connection db is left in the p->pVTable list.
 */
@@ -135914,8 +140606,8 @@ static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
   VTable *pVTable = p->pVTable;
   p->pVTable = 0;
 
-  /* Assert that the mutex (if any) associated with the BtShared database 
-  ** that contains table p is held by the caller. See header comments 
+  /* Assert that the mutex (if any) associated with the BtShared database
+  ** that contains table p is held by the caller. See header comments
   ** above function sqlite3VtabUnlockList() for an explanation of why
   ** this makes it safe to access the sqlite3.pDisconnect list of any
   ** database connection that may have an entry in the p->pVTable list.
@@ -135971,7 +140663,7 @@ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
 **
 ** This function may only be called when the mutexes associated with all
-** shared b-tree databases opened using connection db are held by the 
+** shared b-tree databases opened using connection db are held by the
 ** caller. This is done to protect the sqlite3.pDisconnect list. The
 ** sqlite3.pDisconnect list is accessed only as follows:
 **
@@ -135984,17 +140676,17 @@ SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
 **      or, if the virtual table is stored in a non-sharable database, then
 **      the database handle mutex is held.
 **
-** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
+** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
 ** by multiple threads. It is thread-safe.
 */
 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
   VTable *p = db->pDisconnect;
-  db->pDisconnect = 0;
 
   assert( sqlite3BtreeHoldsAllMutexes(db) );
   assert( sqlite3_mutex_held(db->mutex) );
 
   if( p ){
+    db->pDisconnect = 0;
     sqlite3ExpirePreparedStatements(db, 0);
     do {
       VTable *pNext = p->pNext;
@@ -136010,12 +140702,12 @@ SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
 ** record.
 **
 ** Since it is a virtual-table, the Table structure contains a pointer
-** to the head of a linked list of VTable structures. Each VTable 
+** to the head of a linked list of VTable structures. Each VTable
 ** structure is associated with a single sqlite3* user of the schema.
-** The reference count of the VTable structure associated with database 
-** connection db is decremented immediately (which may lead to the 
+** The reference count of the VTable structure associated with database
+** connection db is decremented immediately (which may lead to the
 ** structure being xDisconnected and free). Any other VTable structures
-** in the list are moved to the sqlite3.pDisconnect list of the associated 
+** in the list are moved to the sqlite3.pDisconnect list of the associated
 ** database connection.
 */
 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
@@ -136089,13 +140781,13 @@ SQLITE_PRIVATE void sqlite3VtabBeginParse(
 #ifndef SQLITE_OMIT_AUTHORIZATION
   /* Creating a virtual table invokes the authorization callback twice.
   ** The first invocation, to obtain permission to INSERT a row into the
-  ** sqlite_master table, has already been made by sqlite3StartTable().
+  ** sqlite_schema table, has already been made by sqlite3StartTable().
   ** The second call, to obtain permission to create the table, is made now.
   */
   if( pTable->azModuleArg ){
     int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
     assert( iDb>=0 ); /* The database the table is being created in */
-    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
+    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
             pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
   }
 #endif
@@ -136127,12 +140819,12 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
   addArgumentToVtab(pParse);
   pParse->sArg.z = 0;
   if( pTab->nModuleArg<1 ) return;
-  
+
   /* If the CREATE VIRTUAL TABLE statement is being entered for the
   ** first time (in other words if the virtual table is actually being
-  ** created now instead of just being read out of sqlite_master) then
+  ** created now instead of just being read out of sqlite_schema) then
   ** do additional initialization work and store the statement text
-  ** in the sqlite_master table.
+  ** in the sqlite_schema table.
   */
   if( !db->init.busy ){
     char *zStmt;
@@ -136141,45 +140833,47 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
     int iReg;
     Vdbe *v;
 
+    sqlite3MayAbort(pParse);
+
     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
     if( pEnd ){
       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
     }
     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
 
-    /* A slot for the record has already been allocated in the 
-    ** SQLITE_MASTER table.  We just need to update that slot with all
-    ** the information we've collected.  
+    /* A slot for the record has already been allocated in the
+    ** schema table.  We just need to update that slot with all
+    ** the information we've collected.
     **
     ** The VM register number pParse->regRowid holds the rowid of an
-    ** entry in the sqlite_master table tht was created for this vtab
+    ** entry in the sqlite_schema table tht was created for this vtab
     ** by sqlite3StartTable().
     */
     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
     sqlite3NestedParse(pParse,
-      "UPDATE %Q.%s "
+      "UPDATE %Q." DFLT_SCHEMA_TABLE " "
          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
        "WHERE rowid=#%d",
-      db->aDb[iDb].zDbSName, MASTER_NAME,
+      db->aDb[iDb].zDbSName,
       pTab->zName,
       pTab->zName,
       zStmt,
       pParse->regRowid
     );
-    sqlite3DbFree(db, zStmt);
     v = sqlite3GetVdbe(pParse);
     sqlite3ChangeCookie(pParse, iDb);
 
     sqlite3VdbeAddOp0(v, OP_Expire);
-    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
+    zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
+    sqlite3DbFree(db, zStmt);
 
     iReg = ++pParse->nMem;
     sqlite3VdbeLoadString(v, iReg, pTab->zName);
     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
   }
 
-  /* If we are rereading the sqlite_master table create the in-memory
+  /* If we are rereading the sqlite_schema table create the in-memory
   ** record of the table. The xConnect() method is not called until
   ** the first time the virtual table is used in an SQL statement. This
   ** allows a schema that contains virtual tables to be loaded before
@@ -136230,7 +140924,7 @@ SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
 ** to this procedure.
 */
 static int vtabCallConstructor(
-  sqlite3 *db, 
+  sqlite3 *db,
   Table *pTab,
   Module *pMod,
   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
@@ -136249,7 +140943,7 @@ static int vtabCallConstructor(
   /* Check that the virtual-table is not already being initialized */
   for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
     if( pCtx->pTab==pTab ){
-      *pzErr = sqlite3MPrintf(db, 
+      *pzErr = sqlite3MPrintf(db,
           "vtable constructor called recursively: %s", pTab->zName
       );
       return SQLITE_LOCKED;
@@ -136269,6 +140963,7 @@ static int vtabCallConstructor(
   }
   pVTable->db = db;
   pVTable->pMod = pMod;
+  pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
 
   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   pTab->azModuleArg[1] = (char *)db->aDb[iDb].zDbSName;
@@ -136308,9 +141003,9 @@ static int vtabCallConstructor(
       rc = SQLITE_ERROR;
     }else{
       int iCol;
-      u8 oooHidden = 0;
+      u16 oooHidden = 0;
       /* If everything went according to plan, link the new VTable structure
-      ** into the linked list headed by pTab->pVTable. Then loop through the 
+      ** into the linked list headed by pTab->pVTable. Then loop through the
       ** columns of the table to see if any of them contain the token "hidden".
       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
       ** the type string.  */
@@ -136355,7 +141050,7 @@ static int vtabCallConstructor(
 
 /*
 ** This function is invoked by the parser to call the xConnect() method
-** of the virtual table pTab. If an error occurs, an error code is returned 
+** of the virtual table pTab. If an error occurs, an error code is returned
 ** and an error left in pParse.
 **
 ** This call is a no-op if table pTab is not a virtual table.
@@ -136426,7 +141121,7 @@ static void addToVTrans(sqlite3 *db, VTable *pVTab){
 
 /*
 ** This function is invoked by the vdbe to call the xCreate method
-** of the virtual table named zTab in database iDb. 
+** of the virtual table named zTab in database iDb.
 **
 ** If an error occurs, *pzErr is set to point to an English language
 ** description of the error and an SQLITE_XXX error code is returned.
@@ -136445,8 +141140,8 @@ SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab,
   zMod = pTab->azModuleArg[0];
   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
 
-  /* If the module has been registered and includes a Create method, 
-  ** invoke it now. If the module has not been registered, return an 
+  /* If the module has been registered and includes a Create method,
+  ** invoke it now. If the module has not been registered, return an
   ** error. Otherwise, do nothing.
   */
   if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
@@ -136499,7 +141194,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
   sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
   sParse.db = db;
   sParse.nQueryLoop = 1;
-  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr) 
+  if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
    && sParse.pNewTable
    && !db->mallocFailed
    && !sParse.pNewTable->pSelect
@@ -136574,7 +141269,8 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab
     }
     p = vtabDisconnectAll(db, pTab);
     xDestroy = p->pMod->pModule->xDestroy;
-    assert( xDestroy!=0 );  /* Checked before the virtual table is created */
+    if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
+    assert( xDestroy!=0 );
     pTab->nTabRef++;
     rc = xDestroy(p->pVtab);
     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
@@ -136596,7 +141292,7 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab
 ** called is identified by the second argument, "offset", which is
 ** the offset of the method to call in the sqlite3_module structure.
 **
-** The array is cleared after invoking the callbacks. 
+** The array is cleared after invoking the callbacks.
 */
 static void callFinaliser(sqlite3 *db, int offset){
   int i;
@@ -136645,7 +141341,7 @@ SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
 }
 
 /*
-** Invoke the xRollback method of all virtual tables in the 
+** Invoke the xRollback method of all virtual tables in the
 ** sqlite3.aVTrans array. Then clear the array itself.
 */
 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
@@ -136654,7 +141350,7 @@ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
 }
 
 /*
-** Invoke the xCommit method of all virtual tables in the 
+** Invoke the xCommit method of all virtual tables in the
 ** sqlite3.aVTrans array. Then clear the array itself.
 */
 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
@@ -136676,7 +141372,7 @@ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
 
   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
   ** than zero, then this function is being called from within a
-  ** virtual module xSync() callback. It is illegal to write to 
+  ** virtual module xSync() callback. It is illegal to write to
   ** virtual module tables in this case, so return SQLITE_LOCKED.
   */
   if( sqlite3VtabInSync(db) ){
@@ -136684,7 +141380,7 @@ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
   }
   if( !pVTab ){
     return SQLITE_OK;
-  } 
+  }
   pModule = pVTab->pVtab->pModule;
 
   if( pModule->xBegin ){
@@ -136697,7 +141393,7 @@ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
       }
     }
 
-    /* Invoke the xBegin method. If successful, add the vtab to the 
+    /* Invoke the xBegin method. If successful, add the vtab to the
     ** sqlite3.aVTrans[] array. */
     rc = growVTrans(db);
     if( rc==SQLITE_OK ){
@@ -136721,11 +141417,11 @@ SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
 ** as the second argument to the virtual table method invoked.
 **
 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
-** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
+** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
 ** an open transaction is invoked.
 **
-** If any virtual table method returns an error code other than SQLITE_OK, 
+** If any virtual table method returns an error code other than SQLITE_OK,
 ** processing is abandoned and the error returned to the caller of this
 ** function immediately. If all calls to virtual table methods are successful,
 ** SQLITE_OK is returned.
@@ -136774,7 +141470,7 @@ SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
 ** This routine is used to allow virtual table implementations to
 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
 **
-** Return either the pDef argument (indicating no change) or a 
+** Return either the pDef argument (indicating no change) or a
 ** new FuncDef structure that is marked as ephemeral using the
 ** SQLITE_FUNC_EPHEM flag.
 */
@@ -136803,7 +141499,7 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
   assert( pVtab->pModule!=0 );
   pMod = (sqlite3_module *)pVtab->pModule;
   if( pMod->xFindFunction==0 ) return pDef;
+
   /* Call the xFindFunction method on the virtual table implementation
   ** to see if the implementation wants to overload this function.
   **
@@ -136921,7 +141617,7 @@ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
   Table *pTab = pMod->pEpoTab;
   if( pTab!=0 ){
     /* Mark the table as Ephemeral prior to deleting it, so that the
-    ** sqlite3DeleteTable() routine will know that it is not stored in 
+    ** sqlite3DeleteTable() routine will know that it is not stored in
     ** the schema. */
     pTab->tabFlags |= TF_Ephemeral;
     sqlite3DeleteTable(db, pTab);
@@ -136937,8 +141633,8 @@ SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
 ** within an xUpdate method.
 */
 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
-  static const unsigned char aMap[] = { 
-    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
+  static const unsigned char aMap[] = {
+    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
   };
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
@@ -136950,35 +141646,45 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
 }
 
 /*
-** Call from within the xCreate() or xConnect() methods to provide 
+** Call from within the xCreate() or xConnect() methods to provide
 ** the SQLite core with additional information about the behavior
 ** of the virtual table being implemented.
 */
 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
   va_list ap;
   int rc = SQLITE_OK;
+  VtabCtx *p;
 
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
 #endif
   sqlite3_mutex_enter(db->mutex);
-  va_start(ap, op);
-  switch( op ){
-    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
-      VtabCtx *p = db->pVtabCtx;
-      if( !p ){
-        rc = SQLITE_MISUSE_BKPT;
-      }else{
-        assert( p->pTab==0 || IsVirtual(p->pTab) );
+  p = db->pVtabCtx;
+  if( !p ){
+    rc = SQLITE_MISUSE_BKPT;
+  }else{
+    assert( p->pTab==0 || IsVirtual(p->pTab) );
+    va_start(ap, op);
+    switch( op ){
+      case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
         p->pVTable->bConstraint = (u8)va_arg(ap, int);
+        break;
+      }
+      case SQLITE_VTAB_INNOCUOUS: {
+        p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
+        break;
+      }
+      case SQLITE_VTAB_DIRECTONLY: {
+        p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
+        break;
+      }
+      default: {
+        rc = SQLITE_MISUSE_BKPT;
+        break;
       }
-      break;
     }
-    default:
-      rc = SQLITE_MISUSE_BKPT;
-      break;
+    va_end(ap);
   }
-  va_end(ap);
 
   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
   sqlite3_mutex_leave(db->mutex);
@@ -137030,19 +141736,6 @@ SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
 #ifndef SQLITE_WHEREINT_H
 #define SQLITE_WHEREINT_H
 
-/*
-** Trace output macros
-*/
-#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
-/***/ extern int sqlite3WhereTrace;
-#endif
-#if defined(SQLITE_DEBUG) \
-    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
-# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
-# define WHERETRACE_ENABLED 1
-#else
-# define WHERETRACE(K,X)
-#endif
 
 /* Forward references
 */
@@ -137167,7 +141860,7 @@ struct WhereLoop {
 
 /* This object holds the prerequisites and the cost of running a
 ** subquery on one operand of an OR operator in the WHERE clause.
-** See WhereOrSet for additional information 
+** See WhereOrSet for additional information
 */
 struct WhereOrCost {
   Bitmask prereq;     /* Prerequisites */
@@ -137219,7 +141912,7 @@ struct WherePath {
 ** clause subexpression is separated from the others by AND operators,
 ** usually, or sometimes subexpressions separated by OR.
 **
-** All WhereTerms are collected into a single WhereClause structure.  
+** All WhereTerms are collected into a single WhereClause structure.
 ** The following identity holds:
 **
 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
@@ -137274,9 +141967,11 @@ struct WhereTerm {
   u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
-  int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
   union {
-    int leftColumn;         /* Column number of X in "X <op> <expr>" */
+    struct {
+      int leftColumn;         /* Column number of X in "X <op> <expr>" */
+      int iField;             /* Field in (?,?,?) IN (SELECT...) vector */
+    } x;                    /* Opcode other than OP_OR or OP_AND */
     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
   } u;
@@ -137287,24 +141982,29 @@ struct WhereTerm {
 /*
 ** Allowed values of WhereTerm.wtFlags
 */
-#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
-#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
-#define TERM_CODED      0x04   /* This term is already coded */
-#define TERM_COPIED     0x08   /* Has a child */
-#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
-#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
-#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
+#define TERM_DYNAMIC    0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */
+#define TERM_VIRTUAL    0x0002 /* Added by the optimizer.  Do not code */
+#define TERM_CODED      0x0004 /* This term is already coded */
+#define TERM_COPIED     0x0008 /* Has a child */
+#define TERM_ORINFO     0x0010 /* Need to free the WhereTerm.u.pOrInfo object */
+#define TERM_ANDINFO    0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */
+#define TERM_OR_OK      0x0040 /* Used during OR-clause processing */
 #ifdef SQLITE_ENABLE_STAT4
-#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
+#  define TERM_VNULL    0x0080 /* Manufactured x>NULL or x<=NULL term */
 #else
-#  define TERM_VNULL    0x00   /* Disabled if not using stat4 */
+#  define TERM_VNULL    0x0000 /* Disabled if not using stat4 */
 #endif
-#define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
-#define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
-#define TERM_LIKE       0x400  /* The original LIKE operator */
-#define TERM_IS         0x800  /* Term.pExpr is an IS operator */
+#define TERM_LIKEOPT    0x0100 /* Virtual terms from the LIKE optimization */
+#define TERM_LIKECOND   0x0200 /* Conditionally this LIKE operator term */
+#define TERM_LIKE       0x0400 /* The original LIKE operator */
+#define TERM_IS         0x0800 /* Term.pExpr is an IS operator */
 #define TERM_VARSELECT  0x1000 /* Term.pExpr contains a correlated sub-query */
-#define TERM_NOPARTIDX  0x2000 /* Not for use to enable a partial index */
+#define TERM_HEURTRUTH  0x2000 /* Heuristic truthProb used */
+#ifdef SQLITE_ENABLE_STAT4
+#  define TERM_HIGHTRUTH  0x4000 /* Term excludes few rows */
+#else
+#  define TERM_HIGHTRUTH  0      /* Only used with STAT4 */
+#endif
 
 /*
 ** An instance of the WhereScan object is used as an iterator for locating
@@ -137372,8 +142072,8 @@ struct WhereAndInfo {
 ** An instance of the following structure keeps track of a mapping
 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
 **
-** The VDBE cursor numbers are small integers contained in 
-** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
+** The VDBE cursor numbers are small integers contained in
+** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
 ** clause, the cursor numbers might not begin with 0 and they might
 ** contain gaps in the numbering sequence.  But we want to make maximum
 ** use of the bits in our bitmasks.  This structure provides a mapping
@@ -137419,13 +142119,16 @@ struct WhereLoopBuilder {
   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
   int nRecValid;            /* Number of valid fields currently in pRec */
 #endif
-  unsigned int bldFlags;    /* SQLITE_BLDF_* flags */
+  unsigned char bldFlags1;  /* First set of SQLITE_BLDF_* flags */
+  unsigned char bldFlags2;  /* Second set of SQLITE_BLDF_* flags */
   unsigned int iPlanLimit;  /* Search limiter */
 };
 
 /* Allowed values for WhereLoopBuider.bldFlags */
-#define SQLITE_BLDF_INDEXED  0x0001   /* An index is used */
-#define SQLITE_BLDF_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
+#define SQLITE_BLDF1_INDEXED  0x0001   /* An index is used */
+#define SQLITE_BLDF1_UNIQUE   0x0002   /* All keys of a UNIQUE index used */
+
+#define SQLITE_BLDF2_2NDPASS  0x0004   /* Second builder pass needed */
 
 /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
 ** index+constraint combinations the query planner will consider for a
@@ -137448,6 +142151,20 @@ struct WhereLoopBuilder {
 #endif
 
 /*
+** Each instance of this object records a change to a single node
+** in an expression tree to cause that node to point to a column
+** of an index rather than an expression or a virtual column.  All
+** such transformations need to be undone at the end of WHERE clause
+** processing.
+*/
+typedef struct WhereExprMod WhereExprMod;
+struct WhereExprMod {
+  WhereExprMod *pNext;  /* Next translation on a list of them all */
+  Expr *pExpr;          /* The Expr node that was transformed */
+  Expr orig;            /* Original value of the Expr node */
+};
+
+/*
 ** The WHERE clause processing routine has two halves.  The
 ** first part does the start of the WHERE loop and the second
 ** half does the tail of the WHERE loop.  An instance of
@@ -137463,23 +142180,26 @@ struct WhereInfo {
   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
   ExprList *pResultSet;     /* Result set of the query */
   Expr *pWhere;             /* The complete WHERE clause */
-  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
   int iContinue;            /* Jump here to continue with next record */
   int iBreak;               /* Jump here to break out of the loop */
   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
+  LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
   u8 nLevel;                /* Number of nested loop */
   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
-  u8 sorted;                /* True if really sorted (not just grouped) */
   u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
-  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
-  u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
+  unsigned bDeferredSeek :1;   /* Uses OP_DeferredSeek */
+  unsigned untestedTerms :1;   /* Not all WHERE terms resolved by outer loop */
+  unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
+  unsigned sorted :1;          /* True if really sorted (not just grouped) */
+  LogEst nRowOut;           /* Estimated number of output rows */
   int iTop;                 /* The very beginning of the WHERE loop */
+  int iEndWhere;            /* End of the WHERE clause itself */
   WhereLoop *pLoops;        /* List of all WhereLoop objects */
+  WhereExprMod *pExprMods;  /* Expression modifications */
   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
-  LogEst nRowOut;           /* Estimated number of output rows */
   WhereClause sWC;          /* Decomposition of the WHERE clause */
   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
   WhereLevel a[1];          /* Information about each nest loop in WHERE */
@@ -137493,6 +142213,8 @@ struct WhereInfo {
 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
 #ifdef WHERETRACE_ENABLED
 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
+SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC);
 #endif
 SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
   WhereClause *pWC,     /* The WHERE clause to be searched */
@@ -137603,6 +142325,7 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereC
 #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
 #define WHERE_IN_EARLYOUT  0x00040000  /* Perhaps quit IN loops early */
 #define WHERE_BIGNULL_SORT 0x00080000  /* Column nEq of index is BIGNULL */
+#define WHERE_IN_SEEKSCAN  0x00100000  /* Seek-scan optimization for IN */
 
 #endif /* !defined(SQLITE_WHEREINT_H) */
 
@@ -137660,7 +142383,7 @@ static void explainAppendTerm(
 }
 
 /*
-** Argument pLevel describes a strategy for scanning table pTab. This 
+** Argument pLevel describes a strategy for scanning table pTab. This
 ** function appends text to pStr that describes the subset of table
 ** rows scanned by the strategy in the form of an SQL expression.
 **
@@ -137701,7 +142424,7 @@ static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
 /*
 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
-** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
+** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
 ** is added to the output to describe the table scan strategy in pLevel.
 **
 ** If an OP_Explain opcode is added to the VM, its address is returned.
@@ -137784,7 +142507,7 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
         assert( flags&WHERE_TOP_LIMIT);
         zRangeOp = "<";
       }
-      sqlite3_str_appendf(&str, 
+      sqlite3_str_appendf(&str,
           " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
     }
 #ifndef SQLITE_OMIT_VIRTUALTABLE
@@ -137813,11 +142536,11 @@ SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
 /*
 ** Configure the VM passed as the first argument with an
-** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 
-** implement level pLvl. Argument pSrclist is a pointer to the FROM 
+** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
+** implement level pLvl. Argument pSrclist is a pointer to the FROM
 ** clause that the scan reads data from.
 **
-** If argument addrExplain is not 0, it must be the address of an 
+** If argument addrExplain is not 0, it must be the address of an
 ** OP_Explain instruction that describes the same loop.
 */
 SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
@@ -137873,7 +142596,7 @@ SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
 **
 ** Only the parent term was in the original WHERE clause.  The child1
 ** and child2 terms were added by the LIKE optimization.  If both of
-** the virtual child terms are valid, then testing of the parent can be 
+** the virtual child terms are valid, then testing of the parent can be
 ** skipped.
 **
 ** Usually the parent term is marked as TERM_CODED.  But if the parent
@@ -137905,7 +142628,7 @@ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
 
 /*
 ** Code an OP_Affinity opcode to apply the column affinity string zAff
-** to the n registers starting at base. 
+** to the n registers starting at base.
 **
 ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
 ** are no-ops) at the beginning and end of zAff are ignored.  If all entries
@@ -137942,7 +142665,7 @@ static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
 }
 
 /*
-** Expression pRight, which is the RHS of a comparison operation, is 
+** Expression pRight, which is the RHS of a comparison operation, is
 ** either a vector of n elements or, if n==1, a scalar expression.
 ** Before the comparison operation, affinity zAff is to be applied
 ** to the pRight values. This function modifies characters within the
@@ -138004,7 +142727,8 @@ static Expr *removeUnindexableInClauseTerms(
   Expr *pX              /* The IN expression to be reduced */
 ){
   sqlite3 *db = pParse->db;
-  Expr *pNew = sqlite3ExprDup(db, pX, 0);
+  Expr *pNew;
+  pNew = sqlite3ExprDup(db, pX, 0);
   if( db->mallocFailed==0 ){
     ExprList *pOrigRhs = pNew->x.pSelect->pEList;  /* Original unmodified RHS */
     ExprList *pOrigLhs = pNew->pLeft->x.pList;     /* Original unmodified LHS */
@@ -138015,7 +142739,7 @@ static Expr *removeUnindexableInClauseTerms(
 
     for(i=iEq; i<pLoop->nLTerm; i++){
       if( pLoop->aLTerm[i]->pExpr==pX ){
-        int iField = pLoop->aLTerm[i]->iField - 1;
+        int iField = pLoop->aLTerm[i]->u.x.iField - 1;
         if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
         pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
         pOrigRhs->a[iField].pExpr = 0;
@@ -138039,12 +142763,12 @@ static Expr *removeUnindexableInClauseTerms(
     }
     pSelect = pNew->x.pSelect;
     if( pSelect->pOrderBy ){
-      /* If the SELECT statement has an ORDER BY clause, zero the 
-      ** iOrderByCol variables. These are set to non-zero when an 
-      ** ORDER BY term exactly matches one of the terms of the 
+      /* If the SELECT statement has an ORDER BY clause, zero the
+      ** iOrderByCol variables. These are set to non-zero when an
+      ** ORDER BY term exactly matches one of the terms of the
       ** result-set. Since the result-set of the SELECT statement may
-      ** have been modified or reordered, these variables are no longer 
-      ** set correctly.  Since setting them is just an optimization, 
+      ** have been modified or reordered, these variables are no longer
+      ** set correctly.  Since setting them is just an optimization,
       ** it's easiest just to zero them here.  */
       ExprList *pOrderBy = pSelect->pOrderBy;
       for(i=0; i<pOrderBy->nExpr; i++){
@@ -138065,7 +142789,7 @@ static Expr *removeUnindexableInClauseTerms(
 
 /*
 ** Generate code for a single equality term of the WHERE clause.  An equality
-** term can be either X=expr or X IN (...).   pTerm is the term to be 
+** term can be either X=expr or X IN (...).   pTerm is the term to be
 ** coded.
 **
 ** The current value for the constraint is left in a register, the index
@@ -138158,6 +142882,9 @@ static int codeEqualityTerm(
     if( pLevel->u.in.nIn==0 ){
       pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
     }
+    if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
+      pLoop->wsFlags |= WHERE_IN_EARLYOUT;
+    }
 
     i = pLevel->u.in.nIn;
     pLevel->u.in.nIn += nEq;
@@ -138181,10 +142908,9 @@ static int codeEqualityTerm(
           if( i==iEq ){
             pIn->iCur = iTab;
             pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
-            if( iEq>0 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
+            if( iEq>0 ){
               pIn->iBase = iReg - i;
               pIn->nPrefix = i;
-              pLoop->wsFlags |= WHERE_IN_EARLYOUT;
             }else{
               pIn->nPrefix = 0;
             }
@@ -138194,6 +142920,14 @@ static int codeEqualityTerm(
           pIn++;
         }
       }
+      testcase( iEq>0
+                && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
+                && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
+      if( iEq>0
+       && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
+      ){
+        sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
+      }
     }else{
       pLevel->u.in.nIn = 0;
     }
@@ -138211,7 +142945,7 @@ static int codeEqualityTerm(
 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
 ** The index has as many as three equality constraints, but in this
-** example, the third "c" value is an inequality.  So only two 
+** example, the third "c" value is an inequality.  So only two
 ** constraints are coded.  This routine will generate code to evaluate
 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
 ** in consecutive registers and the index of the first register is returned.
@@ -138301,7 +143035,7 @@ static int codeAllEqualityTerms(
       testcase( pIdx->aiColumn[j]==XN_EXPR );
       VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
     }
-  }    
+  }
 
   /* Evaluate the equality constraints
   */
@@ -138310,7 +143044,7 @@ static int codeAllEqualityTerms(
     int r1;
     pTerm = pLoop->aLTerm[j];
     assert( pTerm!=0 );
-    /* The following testcase is true for indices with redundant columns. 
+    /* The following testcase is true for indices with redundant columns.
     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
     testcase( pTerm->wtFlags & TERM_VIRTUAL );
@@ -138326,8 +143060,8 @@ static int codeAllEqualityTerms(
     if( pTerm->eOperator & WO_IN ){
       if( pTerm->pExpr->flags & EP_xIsSelect ){
         /* No affinity ever needs to be (or should be) applied to a value
-        ** from the RHS of an "? IN (SELECT ...)" expression. The 
-        ** sqlite3FindInIndex() routine has already ensured that the 
+        ** from the RHS of an "? IN (SELECT ...)" expression. The
+        ** sqlite3FindInIndex() routine has already ensured that the
         ** affinity of the comparison has been applied to the value.  */
         if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
       }
@@ -138354,7 +143088,7 @@ static int codeAllEqualityTerms(
 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
 /*
 ** If the most recently coded instruction is a constant range constraint
-** (a string literal) that originated from the LIKE optimization, then 
+** (a string literal) that originated from the LIKE optimization, then
 ** set P3 and P5 on the OP_String opcode so that the string will be cast
 ** to a BLOB at appropriate times.
 **
@@ -138379,7 +143113,7 @@ static void whereLikeOptimizationStringFixup(
     assert( pLevel->iLikeRepCntr>0 );
     pOp = sqlite3VdbeGetOp(v, -1);
     assert( pOp!=0 );
-    assert( pOp->opcode==OP_String8 
+    assert( pOp->opcode==OP_String8
             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
     pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
     pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
@@ -138412,7 +143146,7 @@ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
   assert( pHint->pIdx!=0 );
   if( pExpr->op==TK_COLUMN
    && pExpr->iTable==pHint->iTabCur
-   && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
+   && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
   ){
     pWalker->eCode = 1;
   }
@@ -138422,7 +143156,7 @@ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
 /*
 ** Test whether or not expression pExpr, which was part of a WHERE clause,
 ** should be included in the cursor-hint for a table that is on the rhs
-** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 
+** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
 ** expression is not suitable.
 **
 ** An expression is unsuitable if it might evaluate to non NULL even if
@@ -138435,9 +143169,9 @@ static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
 **   CASE WHEN col THEN 0 ELSE 1 END
 */
 static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
-  if( pExpr->op==TK_IS 
-   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 
-   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 
+  if( pExpr->op==TK_IS
+   || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
+   || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
   ){
     pWalker->eCode = 1;
   }else if( pExpr->op==TK_FUNCTION ){
@@ -138458,10 +143192,10 @@ static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
 ** that accesses any table other than the one identified by
 ** CCurHint.iTabCur, then do the following:
 **
-**   1) allocate a register and code an OP_Column instruction to read 
+**   1) allocate a register and code an OP_Column instruction to read
 **      the specified column into the new register, and
 **
-**   2) transform the expression node to a TK_REGISTER node that reads 
+**   2) transform the expression node to a TK_REGISTER node that reads
 **      from the newly populated register.
 **
 ** Also, if the node is a TK_COLUMN that does access the table idenified
@@ -138480,7 +143214,7 @@ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
       pExpr->iTable = reg;
     }else if( pHint->pIdx!=0 ){
       pExpr->iTable = pHint->iIdxCur;
-      pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
+      pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
       assert( pExpr->iColumn>=0 );
     }
   }else if( pExpr->op==TK_AGG_FUNCTION ){
@@ -138489,7 +143223,7 @@ static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
     ** the parent context. Do not walk the function arguments in this case.
     **
     ** todo: It should be possible to replace this node with a TK_REGISTER
-    ** expression, as the result of the expression must be stored in a 
+    ** expression, as the result of the expression must be stored in a
     ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
     rc = WRC_Prune;
   }
@@ -138532,18 +143266,18 @@ static void codeCursorHint(
     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
     if( pTerm->prereqAll & pLevel->notReady ) continue;
 
-    /* Any terms specified as part of the ON(...) clause for any LEFT 
+    /* Any terms specified as part of the ON(...) clause for any LEFT
     ** JOIN for which the current table is not the rhs are omitted
-    ** from the cursor-hint. 
+    ** from the cursor-hint.
     **
-    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 
+    ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
     ** that were specified as part of the WHERE clause must be excluded.
     ** This is to address the following:
     **
     **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
     **
     ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
-    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 
+    ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
     ** pushed down to the cursor, this row is filtered out, causing
     ** SQLite to synthesize a row of NULL values. Which does match the
     ** WHERE clause, and so the query returns a row. Which is incorrect.
@@ -138556,7 +143290,7 @@ static void codeCursorHint(
     */
     if( pTabItem->fg.jointype & JT_LEFT ){
       Expr *pExpr = pTerm->pExpr;
-      if( !ExprHasProperty(pExpr, EP_FromJoin) 
+      if( !ExprHasProperty(pExpr, EP_FromJoin)
        || pExpr->iRightJoinTable!=pTabItem->iCursor
       ){
         sWalker.eCode = 0;
@@ -138594,7 +143328,7 @@ static void codeCursorHint(
   if( pExpr!=0 ){
     sWalker.xExprCallback = codeCursorHintFixExpr;
     sqlite3WalkExpr(&sWalker, pExpr);
-    sqlite3VdbeAddOp4(v, OP_CursorHint, 
+    sqlite3VdbeAddOp4(v, OP_CursorHint,
                       (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
                       (const char*)pExpr, P4_EXPR);
   }
@@ -138606,7 +143340,7 @@ static void codeCursorHint(
 /*
 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
-** function generates code to do a deferred seek of cursor iCur to the 
+** function generates code to do a deferred seek of cursor iCur to the
 ** rowid stored in register iRowid.
 **
 ** Normally, this is just:
@@ -138616,8 +143350,8 @@ static void codeCursorHint(
 ** However, if the scan currently being coded is a branch of an OR-loop and
 ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
 ** is set to iIdxCur and P4 is set to point to an array of integers
-** containing one entry for each column of the table cursor iCur is open 
-** on. For each table column, if the column is the i'th column of the 
+** containing one entry for each column of the table cursor iCur is open
+** on. For each table column, if the column is the i'th column of the
 ** index, then the corresponding array entry is set to (i+1). If the column
 ** does not appear in the index at all, the array entry is set to 0.
 */
@@ -138632,19 +143366,24 @@ static void codeDeferredSeek(
 
   assert( iIdxCur>0 );
   assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
-  
+
+  pWInfo->bDeferredSeek = 1;
   sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
   if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
    && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
   ){
     int i;
     Table *pTab = pIdx->pTable;
-    int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
+    u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
     if( ai ){
       ai[0] = pTab->nCol;
       for(i=0; i<pIdx->nColumn-1; i++){
+        int x1, x2;
         assert( pIdx->aiColumn[i]<pTab->nCol );
-        if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
+        x1 = pIdx->aiColumn[i];
+        x2 = sqlite3TableColumnToStorage(pTab, x1);
+        testcase( x1!=x2 );
+        if( x1>=0 ) ai[x2+1] = i+1;
       }
       sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
     }
@@ -138695,8 +143434,24 @@ typedef struct IdxExprTrans {
   int iTabCur;       /* The cursor of the corresponding table */
   int iIdxCur;       /* The cursor for the index */
   int iIdxCol;       /* The column for the index */
+  int iTabCol;       /* The column for the table */
+  WhereInfo *pWInfo; /* Complete WHERE clause information */
+  sqlite3 *db;       /* Database connection (for malloc()) */
 } IdxExprTrans;
 
+/*
+** Preserve pExpr on the WhereETrans list of the WhereInfo.
+*/
+static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){
+  WhereExprMod *pNew;
+  pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew));
+  if( pNew==0 ) return;
+  pNew->pNext = pTrans->pWInfo->pExprMods;
+  pTrans->pWInfo->pExprMods = pNew;
+  pNew->pExpr = pExpr;
+  memcpy(&pNew->orig, pExpr, sizeof(*pExpr));
+}
+
 /* The walker node callback used to transform matching expressions into
 ** a reference to an index column for an index on an expression.
 **
@@ -138706,21 +143461,49 @@ typedef struct IdxExprTrans {
 static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
   IdxExprTrans *pX = p->u.pIdxTrans;
   if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
+    preserveExpr(pX, pExpr);
     pExpr->affExpr = sqlite3ExprAffinity(pExpr);
     pExpr->op = TK_COLUMN;
     pExpr->iTable = pX->iIdxCur;
     pExpr->iColumn = pX->iIdxCol;
     pExpr->y.pTab = 0;
+    testcase( ExprHasProperty(pExpr, EP_Skip) );
+    testcase( ExprHasProperty(pExpr, EP_Unlikely) );
+    ExprClearProperty(pExpr, EP_Skip|EP_Unlikely);
     return WRC_Prune;
   }else{
     return WRC_Continue;
   }
 }
 
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+/* A walker node callback that translates a column reference to a table
+** into a corresponding column reference of an index.
+*/
+static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){
+  if( pExpr->op==TK_COLUMN ){
+    IdxExprTrans *pX = p->u.pIdxTrans;
+    if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){
+      assert( pExpr->y.pTab!=0 );
+      preserveExpr(pX, pExpr);
+      pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);
+      pExpr->iTable = pX->iIdxCur;
+      pExpr->iColumn = pX->iIdxCol;
+      pExpr->y.pTab = 0;
+    }
+  }
+  return WRC_Continue;
+}
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+
 /*
 ** For an indexes on expression X, locate every instance of expression X
 ** in pExpr and change that subexpression into a reference to the appropriate
 ** column of the index.
+**
+** 2019-10-24: Updated to also translate references to a VIRTUAL column in
+** the table into references to the corresponding (stored) column of the
+** index.
 */
 static void whereIndexExprTrans(
   Index *pIdx,      /* The Index */
@@ -138730,20 +143513,48 @@ static void whereIndexExprTrans(
 ){
   int iIdxCol;               /* Column number of the index */
   ExprList *aColExpr;        /* Expressions that are indexed */
+  Table *pTab;
   Walker w;
   IdxExprTrans x;
   aColExpr = pIdx->aColExpr;
-  if( aColExpr==0 ) return;  /* Not an index on expressions */
+  if( aColExpr==0 && !pIdx->bHasVCol ){
+    /* The index does not reference any expressions or virtual columns
+    ** so no translations are needed. */
+    return;
+  }
+  pTab = pIdx->pTable;
   memset(&w, 0, sizeof(w));
-  w.xExprCallback = whereIndexExprTransNode;
   w.u.pIdxTrans = &x;
   x.iTabCur = iTabCur;
   x.iIdxCur = iIdxCur;
-  for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
-    if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
-    assert( aColExpr->a[iIdxCol].pExpr!=0 );
+  x.pWInfo = pWInfo;
+  x.db = pWInfo->pParse->db;
+  for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){
+    i16 iRef = pIdx->aiColumn[iIdxCol];
+    if( iRef==XN_EXPR ){
+      assert( aColExpr->a[iIdxCol].pExpr!=0 );
+      x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
+      if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue;
+      w.xExprCallback = whereIndexExprTransNode;
+#ifndef SQLITE_OMIT_GENERATED_COLUMNS
+    }else if( iRef>=0
+       && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0
+       && (pTab->aCol[iRef].zColl==0
+           || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0)
+    ){
+      /* Check to see if there are direct references to generated columns
+      ** that are contained in the index.  Pulling the generated column
+      ** out of the index is an optimization only - the main table is always
+      ** available if the index cannot be used.  To avoid unnecessary
+      ** complication, omit this optimization if the collating sequence for
+      ** the column is non-standard */
+      x.iTabCol = iRef;
+      w.xExprCallback = whereIndexExprTransColumn;
+#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
+    }else{
+      continue;
+    }
     x.iIdxCol = iIdxCol;
-    x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
     sqlite3WalkExpr(&w, pWInfo->pWhere);
     sqlite3WalkExprList(&w, pWInfo->pOrderBy);
     sqlite3WalkExprList(&w, pWInfo->pResultSet);
@@ -138815,6 +143626,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
   bRev = (pWInfo->revMask>>iLevel)&1;
   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
+#ifdef WHERETRACE_ENABLED /* 0x20800 */
+  if( sqlite3WhereTrace & 0x800 ){
+    sqlite3DebugPrintf("Coding level %d of %d:  notReady=%llx  iFrom=%d\n",
+       iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
+    sqlite3WhereLoopPrint(pLoop, pWC);
+  }
+  if( sqlite3WhereTrace & 0x20000 ){
+    if( iLevel==0 ){
+      sqlite3DebugPrintf("WHERE clause being coded:\n");
+      sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
+    }
+    sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
+    sqlite3WhereClausePrint(pWC);
+  }
+#endif
 
   /* Create labels for the "break" and "continue" instructions
   ** for the current loop.  Jump to addrBrk to break out of a loop.
@@ -138888,15 +143714,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
                       pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
     VdbeCoverage(v);
     pLoop->u.vtab.needFree = 0;
+    /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
+    ** the u.vtab.idxStr.  NULL it out to prevent a use-after-free */
+    if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
     pLevel->p1 = iCur;
     pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
     iIn = pLevel->u.in.nIn;
     for(j=nConstraint-1; j>=0; j--){
       pTerm = pLoop->aLTerm[j];
+      if( (pTerm->eOperator & WO_IN)!=0 ) iIn--;
       if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
         disableTerm(pLevel, pTerm);
-      }else if( (pTerm->eOperator & WO_IN)!=0 ){
+      }else if( (pTerm->eOperator & WO_IN)!=0
+        && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1
+      ){
         Expr *pCompare;  /* The comparison operator */
         Expr *pRight;    /* RHS of the comparison */
         VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
@@ -138907,8 +143739,8 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         ** encoding of the value in the register, so it *must* be reloaded. */
         assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
         if( !db->mallocFailed ){
-          assert( iIn>0 );
-          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
+          assert( iIn>=0 && iIn<pLevel->u.in.nIn );
+          pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
           assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
           assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
           assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
@@ -138916,7 +143748,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
           sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
         }
 
-        /* Generate code that will continue to the next row if 
+        /* Generate code that will continue to the next row if
         ** the IN constraint is not satisfied */
         pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
         assert( pCompare!=0 || db->mallocFailed );
@@ -138925,13 +143757,16 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
           pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
           if( pRight ){
             pRight->iTable = iReg+j+2;
-            sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
+            sqlite3ExprIfFalse(
+                pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
+            );
           }
           pCompare->pLeft = 0;
           sqlite3ExprDelete(db, pCompare);
         }
       }
     }
+    assert( iIn==0 || db->mallocFailed );
     /* These registers need to be preserved in case there is an IN operator
     ** loop.  So we could deallocate the registers here (and potentially
     ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
@@ -138991,7 +143826,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       int r1, rTemp;        /* Registers for holding the start boundary */
       int op;               /* Cursor seek operation */
 
-      /* The following constant maps TK_xx codes into corresponding 
+      /* The following constant maps TK_xx codes into corresponding
       ** seek opcodes.  It depends on a particular ordering of TK_xx
       */
       const u8 aMoveOp[] = {
@@ -139047,8 +143882,8 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       testcase( pEnd->wtFlags & TERM_VIRTUAL );
       memEndValue = ++pParse->nMem;
       codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
-      if( 0==sqlite3ExprIsVector(pX->pRight) 
-       && (pX->op==TK_LT || pX->op==TK_GT) 
+      if( 0==sqlite3ExprIsVector(pX->pRight)
+       && (pX->op==TK_LT || pX->op==TK_GT)
       ){
         testOp = bRev ? OP_Le : OP_Ge;
       }else{
@@ -139076,14 +143911,14 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   }else if( pLoop->wsFlags & WHERE_INDEXED ){
     /* Case 4: A scan using an index.
     **
-    **         The WHERE clause may contain zero or more equality 
+    **         The WHERE clause may contain zero or more equality
     **         terms ("==" or "IN" operators) that refer to the N
     **         left-most columns of the index. It may also contain
     **         inequality constraints (>, <, >= or <=) on the indexed
-    **         column that immediately follows the N equalities. Only 
+    **         column that immediately follows the N equalities. Only
     **         the right-most column can be an inequality - the rest must
-    **         use the "==" and "IN" operators. For example, if the 
-    **         index is on (x,y,z), then the following clauses are all 
+    **         use the "==" and "IN" operators. For example, if the
+    **         index is on (x,y,z), then the following clauses are all
     **         optimized:
     **
     **            x=5
@@ -139104,7 +143939,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     **         This case is also used when there are no WHERE clause
     **         constraints but an index is selected anyway, in order
     **         to force the output order to conform to an ORDER BY.
-    */  
+    */
     static const u8 aStartOp[] = {
       0,
       0,
@@ -139140,20 +143975,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
     int omitTable;               /* True if we use the index only */
     int regBignull = 0;          /* big-null flag register */
+    int addrSeekScan = 0;        /* Opcode of the OP_SeekScan, if any */
 
     pIdx = pLoop->u.btree.pIndex;
     iIdxCur = pLevel->iIdxCur;
     assert( nEq>=pLoop->nSkip );
 
-    /* Find any inequality constraint terms for the start and end 
-    ** of the range. 
+    /* Find any inequality constraint terms for the start and end
+    ** of the range.
     */
     j = nEq;
     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
       pRangeStart = pLoop->aLTerm[j++];
       nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
       /* Like optimization range constraints always occur in pairs */
-      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 
+      assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
     }
     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
@@ -139186,7 +144022,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
 
     /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
-    ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS 
+    ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
     ** FIRST). In both cases separate ordered scans are made of those
     ** index entries for which the column is null and for those for which
     ** it is not. For an ASC sort, the non-NULL entries are scanned first.
@@ -139197,15 +144033,18 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     ){
       assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
       assert( pRangeEnd==0 && pRangeStart==0 );
-      assert( pLoop->nSkip==0 );
+      testcase( pLoop->nSkip>0 );
       nExtraReg = 1;
       bSeekPastNull = 1;
       pLevel->regBignull = regBignull = ++pParse->nMem;
+      if( pLevel->iLeftJoin ){
+        sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
+      }
       pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
     }
 
     /* If we are doing a reverse order scan on an ascending index, or
-    ** a forward order scan on a descending index, interchange the 
+    ** a forward order scan on a descending index, interchange the
     ** start and end terms (pRangeStart and pRangeEnd).
     */
     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
@@ -139250,7 +144089,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       }
       if( zStartAff ){
         updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
-      }  
+      }
       nConstraint += nBtm;
       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
       if( sqlite3ExprIsVector(pRight)==0 ){
@@ -139275,9 +144114,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       ** above has already left the cursor sitting on the correct row,
       ** so no further seeking is needed */
     }else{
-      if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
-        sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
-      }
       if( regBignull ){
         sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
         VdbeComment((v, "NULL-scan pass ctr"));
@@ -139285,6 +144121,20 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
 
       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
       assert( op!=0 );
+      if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
+        assert( regBignull==0 );
+        /* TUNING:  The OP_SeekScan opcode seeks to reduce the number
+        ** of expensive seek operations by replacing a single seek with
+        ** 1 or more step operations.  The question is, how many steps
+        ** should we try before giving up and going with a seek.  The cost
+        ** of a seek is proportional to the logarithm of the of the number
+        ** of entries in the tree, so basing the number of steps to try
+        ** on the estimated number of rows in the btree seems like a good
+        ** guess. */
+        addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan,
+                                         (pIdx->aiRowLogEst[0]+9)/10);
+        VdbeCoverage(v);
+      }
       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
       VdbeCoverage(v);
       VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
@@ -139301,7 +144151,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         assert( bStopAtNull==startEq );
         sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
         op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
-        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, 
+        sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
                              nConstraint-startEq);
         VdbeCoverage(v);
         VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
@@ -139367,6 +144217,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
+      if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan);
     }
     if( regBignull ){
       /* During a NULL-scan, check to see if we have reached the end of
@@ -139386,63 +144237,66 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
     }
 
-    if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
-      sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
+    if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
+      sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq);
     }
 
     /* Seek the table cursor, if required */
-    omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
+    omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
     if( omitTable ){
       /* pIdx is a covering index.  No need to access the main table. */
     }else if( HasRowid(pIdx->pTable) ){
-      if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
-          (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE) 
-       && (pWInfo->eOnePass==ONEPASS_SINGLE)
-      )){
-        iRowidReg = ++pParse->nMem;
-        sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
-        sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
-        VdbeCoverage(v);
-      }else{
-        codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
-      }
+      codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
     }else if( iCur!=iIdxCur ){
       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
       for(j=0; j<pPk->nKeyCol; j++){
-        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
+        k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
       }
       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
     }
 
-    /* If pIdx is an index on one or more expressions, then look through
-    ** all the expressions in pWInfo and try to transform matching expressions
-    ** into reference to index columns.
-    **
-    ** Do not do this for the RHS of a LEFT JOIN. This is because the 
-    ** expression may be evaluated after OP_NullRow has been executed on
-    ** the cursor. In this case it is important to do the full evaluation,
-    ** as the result of the expression may not be NULL, even if all table
-    ** column values are.  https://www.sqlite.org/src/info/7fa8049685b50b5a
-    **
-    ** Also, do not do this when processing one index an a multi-index
-    ** OR clause, since the transformation will become invalid once we
-    ** move forward to the next index.
-    ** https://sqlite.org/src/info/4e8e4857d32d401f
-    */
-    if( pLevel->iLeftJoin==0 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
-      whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
-    }
+    if( pLevel->iLeftJoin==0 ){
+      /* If pIdx is an index on one or more expressions, then look through
+      ** all the expressions in pWInfo and try to transform matching expressions
+      ** into reference to index columns.  Also attempt to translate references
+      ** to virtual columns in the table into references to (stored) columns
+      ** of the index.
+      **
+      ** Do not do this for the RHS of a LEFT JOIN. This is because the
+      ** expression may be evaluated after OP_NullRow has been executed on
+      ** the cursor. In this case it is important to do the full evaluation,
+      ** as the result of the expression may not be NULL, even if all table
+      ** column values are.  https://www.sqlite.org/src/info/7fa8049685b50b5a
+      **
+      ** Also, do not do this when processing one index an a multi-index
+      ** OR clause, since the transformation will become invalid once we
+      ** move forward to the next index.
+      ** https://sqlite.org/src/info/4e8e4857d32d401f
+      */
+      if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
+        whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
+      }
 
-    /* If a partial index is driving the loop, try to eliminate WHERE clause
-    ** terms from the query that must be true due to the WHERE clause of
-    ** the partial index
-    */
-    if( pIdx->pPartIdxWhere ){
-      whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
+      /* If a partial index is driving the loop, try to eliminate WHERE clause
+      ** terms from the query that must be true due to the WHERE clause of
+      ** the partial index.
+      **
+      ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
+      ** for a LEFT JOIN.
+      */
+      if( pIdx->pPartIdxWhere ){
+        whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
+      }
+    }else{
+      testcase( pIdx->pPartIdxWhere );
+      /* The following assert() is not a requirement, merely an observation:
+      ** The OR-optimization doesn't work for the right hand table of
+      ** a LEFT JOIN: */
+      assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 );
     }
 
     /* Record the instruction used to terminate the loop. */
@@ -139520,7 +144374,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     int iRetInit;                             /* Address of regReturn init */
     int untestedTerms = 0;             /* Some terms not completely tested */
     int ii;                            /* Loop counter */
-    u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
     Table *pTab = pTabItem->pTab;
 
@@ -139554,15 +144407,15 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       pOrTab = pWInfo->pTabList;
     }
 
-    /* Initialize the rowset register to contain NULL. An SQL NULL is 
+    /* Initialize the rowset register to contain NULL. An SQL NULL is
     ** equivalent to an empty rowset.  Or, create an ephemeral index
     ** capable of holding primary keys in the case of a WITHOUT ROWID.
     **
-    ** Also initialize regReturn to contain the address of the instruction 
+    ** Also initialize regReturn to contain the address of the instruction
     ** immediately following the OP_Return at the bottom of the loop. This
     ** is required in a few obscure LEFT JOIN cases where control jumps
-    ** over the top of the loop into the body of it. In this case the 
-    ** correct response for the end-of-loop code (the OP_Return) is to 
+    ** over the top of the loop into the body of it. In this case the
+    ** correct response for the end-of-loop code (the OP_Return) is to
     ** fall through to the next instruction, just as an OP_Next does if
     ** called on an uninitialized cursor.
     */
@@ -139587,7 +144440,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     **
     ** Actually, each subexpression is converted to "xN AND w" where w is
     ** the "interesting" terms of z - terms that did not originate in the
-    ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
+    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
     ** indices.
     **
     ** This optimization also only applies if the (x1 OR x2 OR ...) term
@@ -139611,7 +144464,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         /* The extra 0x10000 bit on the opcode is masked off and does not
         ** become part of the new Expr.op.  However, it does make the
         ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
-        ** prevents sqlite3PExpr() from implementing AND short-circuit 
+        ** prevents sqlite3PExpr() from implementing AND short-circuit
         ** optimization, which we do not want here. */
         pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
       }
@@ -139621,7 +144474,6 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     ** eliminating duplicates from other WHERE clauses, the action for each
     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
     */
-    wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
     ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
     for(ii=0; ii<pOrWc->nTerm; ii++){
       WhereTerm *pOrTerm = &pOrWc->a[ii];
@@ -139629,9 +144481,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
         int jmp1 = 0;                   /* Address of jump operation */
-        assert( (pTabItem[0].fg.jointype & JT_LEFT)==0 
-             || ExprHasProperty(pOrExpr, EP_FromJoin) 
-        );
+        testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
+               && !ExprHasProperty(pOrExpr, EP_FromJoin)
+        ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
         if( pAndExpr ){
           pAndExpr->pLeft = pOrExpr;
           pOrExpr = pAndExpr;
@@ -139640,7 +144492,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
-                                      wctrlFlags, iCovCur);
+                                      WHERE_OR_SUBCLAUSE, iCovCur);
         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
         if( pSubWInfo ){
           WhereLoop *pSubLoop;
@@ -139671,7 +144523,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
               r = sqlite3GetTempRange(pParse, nPk);
               for(iPk=0; iPk<nPk; iPk++){
                 int iCol = pPk->aiColumn[iPk];
-                sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, r+iPk);
+                sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
               }
 
               /* Check if the temp table already contains this key. If so,
@@ -139682,9 +144534,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
               **
               ** Use some of the same optimizations as OP_RowSetTest: If iSet
               ** is zero, assume that the key cannot already be present in
-              ** the temp table. And if iSet is -1, assume that there is no 
-              ** need to insert the key into the temp table, as it will never 
-              ** be tested for.  */ 
+              ** the temp table. And if iSet is -1, assume that there is no
+              ** need to insert the key into the temp table, as it will never
+              ** be tested for.  */
               if( iSet ){
                 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
                 VdbeCoverage(v);
@@ -139723,8 +144575,8 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
           ** If the call to sqlite3WhereBegin() above resulted in a scan that
           ** uses an index, and this is either the first OR-connected term
           ** processed or the index is the same as that used by all previous
-          ** terms, set pCov to the candidate covering index. Otherwise, set 
-          ** pCov to NULL to indicate that no candidate covering index will 
+          ** terms, set pCov to the candidate covering index. Otherwise, set
+          ** pCov to NULL to indicate that no candidate covering index will
           ** be available.
           */
           pSubLoop = pSubWInfo->a[0].pWLoop;
@@ -139738,6 +144590,9 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
           }else{
             pCov = 0;
           }
+          if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){
+            pWInfo->bDeferredSeek = 1;
+          }
 
           /* Finish the loop through table entries that match term pOrTerm. */
           sqlite3WhereEnd(pSubWInfo);
@@ -139796,7 +144651,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   **
   ** iLoop==1: Code only expressions that are entirely covered by pIdx.
   ** iLoop==2: Code remaining expressions that do not contain correlated
-  **           sub-queries.  
+  **           sub-queries.
   ** iLoop==3: Code all remaining expressions.
   **
   ** An effort is made to skip unnecessary iterations of the loop.
@@ -139821,7 +144676,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
       if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
         continue;
       }
-      
+
       if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
         iNext = 2;
         continue;
@@ -139853,6 +144708,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
         VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
                          pWC->nTerm-j, pTerm, iLoop));
       }
+      if( sqlite3WhereTrace & 0x800 ){
+        sqlite3DebugPrintf("Coding auxiliary constraint:\n");
+        sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
+      }
 #endif
       sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
       if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
@@ -139876,15 +144735,21 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
     if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
     if( pTerm->leftCursor!=iCur ) continue;
-    if( pLevel->iLeftJoin ) continue;
+    if( pTabItem->fg.jointype & JT_LEFT ) continue;
     pE = pTerm->pExpr;
+#ifdef WHERETRACE_ENABLED /* 0x800 */
+    if( sqlite3WhereTrace & 0x800 ){
+      sqlite3DebugPrintf("Coding transitive constraint:\n");
+      sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
+    }
+#endif
     assert( !ExprHasProperty(pE, EP_FromJoin) );
     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
-    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
+    pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
                     WO_EQ|WO_IN|WO_IS, 0);
     if( pAlt==0 ) continue;
     if( pAlt->wtFlags & (TERM_CODED) ) continue;
-    if( (pAlt->eOperator & WO_IN) 
+    if( (pAlt->eOperator & WO_IN)
      && (pAlt->pExpr->flags & EP_xIsSelect)
      && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
     ){
@@ -139900,7 +144765,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
   }
 
   /* For a LEFT OUTER JOIN, generate code that will record the fact that
-  ** at least one row of the right table has matched the left table.  
+  ** at least one row of the right table has matched the left table.
   */
   if( pLevel->iLeftJoin ){
     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
@@ -139920,6 +144785,17 @@ SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
     }
   }
 
+#ifdef WHERETRACE_ENABLED /* 0x20800 */
+  if( sqlite3WhereTrace & 0x20000 ){
+    sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
+                       iLevel);
+    sqlite3WhereClausePrint(pWC);
+  }
+  if( sqlite3WhereTrace & 0x800 ){
+    sqlite3DebugPrintf("End Coding level %d:  notReady=%llx\n",
+       iLevel, (u64)pLevel->notReady);
+  }
+#endif
   return pLevel->notReady;
 }
 
@@ -140036,39 +144912,14 @@ static int allowedOp(int op){
 /*
 ** Commute a comparison operator.  Expressions of the form "X op Y"
 ** are converted into "Y op X".
-**
-** If left/right precedence rules come into play when determining the
-** collating sequence, then COLLATE operators are adjusted to ensure
-** that the collating sequence does not change.  For example:
-** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
-** the left hand side of a comparison overrides any collation sequence 
-** attached to the right. For the same reason the EP_Collate flag
-** is not commuted.
-**
-** The return value is extra flags that are added to the WhereTerm object
-** after it is commuted.  The only extra flag ever added is TERM_NOPARTIDX
-** which prevents the term from being used to enable a partial index if
-** COLLATE changes have been made.
 */
 static u16 exprCommute(Parse *pParse, Expr *pExpr){
-  u16 expRight = (pExpr->pRight->flags & EP_Collate);
-  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
-  u16 wtFlags = 0;
-  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
-  if( expRight==expLeft ){
-    /* Either X and Y both have COLLATE operator or neither do */
-    if( expRight ){
-      /* Both X and Y have COLLATE operators.  Make sure X is always
-      ** used by clearing the EP_Collate flag from Y. */
-      pExpr->pRight->flags &= ~EP_Collate;
-      wtFlags |= TERM_NOPARTIDX;
-    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
-      /* Neither X nor Y have COLLATE operators, but X has a non-default
-      ** collating sequence.  So add the EP_Collate marker on X to cause
-      ** it to be searched first. */
-      pExpr->pLeft->flags |= EP_Collate;
-      wtFlags |= TERM_NOPARTIDX;
-    }
+  if( pExpr->pLeft->op==TK_VECTOR
+   || pExpr->pRight->op==TK_VECTOR
+   || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
+      sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
+  ){
+    pExpr->flags ^= EP_Commuted;
   }
   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
   if( pExpr->op>=TK_GT ){
@@ -140079,7 +144930,7 @@ static u16 exprCommute(Parse *pParse, Expr *pExpr){
     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
   }
-  return wtFlags;
+  return 0;
 }
 
 /*
@@ -140213,8 +145064,8 @@ static int isLikeOrGlob(
         **    2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
         **    2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
         */
-        if( pLeft->op!=TK_COLUMN 
-         || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
+        if( pLeft->op!=TK_COLUMN
+         || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
          || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */
         ){
           int isNum;
@@ -140249,7 +145100,7 @@ static int isLikeOrGlob(
           ** function, then no OP_Variable will be added to the program.
           ** This causes problems for the sqlite3_bind_parameter_name()
           ** API. To work around them, add a dummy OP_Variable here.
-          */ 
+          */
           int r1 = sqlite3GetTempReg(pParse);
           sqlite3ExprCodeTarget(pParse, pRight, r1);
           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
@@ -140286,7 +145137,7 @@ static int isLikeOrGlob(
 **      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
 **
 ** In every case, "column" must be a column of a virtual table.  If there
-** is a match, set *ppLeft to the "column" expression, set *ppRight to the 
+** is a match, set *ppLeft to the "column" expression, set *ppRight to the
 ** "expr" expression (even though in forms (6) and (8) the column is on the
 ** right and the expression is on the left).  Also set *peOp2 to the
 ** appropriate virtual table operator.  The return value is 1 or 2 if there
@@ -140329,7 +145180,8 @@ static int isAuxiliaryVtabOperator(
     **       MATCH(expression,vtab_column)
     */
     pCol = pList->a[1].pExpr;
-    if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
+    testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
+    if( ExprIsVtab(pCol) ){
       for(i=0; i<ArraySize(aOp); i++){
         if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
           *peOp2 = aOp[i].eOp2;
@@ -140351,7 +145203,8 @@ static int isAuxiliaryVtabOperator(
     ** with function names in an arbitrary case.
     */
     pCol = pList->a[0].pExpr;
-    if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
+    testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
+    if( ExprIsVtab(pCol) ){
       sqlite3_vtab *pVtab;
       sqlite3_module *pMod;
       void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
@@ -140374,10 +145227,12 @@ static int isAuxiliaryVtabOperator(
     int res = 0;
     Expr *pLeft = pExpr->pLeft;
     Expr *pRight = pExpr->pRight;
-    if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
+    testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );
+    if( ExprIsVtab(pLeft) ){
       res++;
     }
-    if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
+    testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );
+    if( pRight && ExprIsVtab(pRight) ){
       res++;
       SWAP(Expr*, pLeft, pRight);
     }
@@ -140445,7 +145300,7 @@ static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
 **
 ** The following is NOT generated:
 **
-**    x<y OR x>y    -->     x!=y     
+**    x<y OR x>y    -->     x!=y
 */
 static void whereCombineDisjuncts(
   SrcList *pSrc,         /* the FROM clause */
@@ -140542,10 +145397,10 @@ static void whereCombineDisjuncts(
 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
 **
 ** A subterm is "indexable" if it is of the form
-** "T.C <op> <expr>" where C is any column of table T and 
+** "T.C <op> <expr>" where C is any column of table T and
 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
 ** A subterm is also indexable if it is an AND of two or more
-** subsubterms at least one of which is indexable.  Indexable AND 
+** subsubterms at least one of which is indexable.  Indexable AND
 ** subterms have their eOperator set to WO_AND and they have
 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
 **
@@ -140636,7 +145491,7 @@ static void exprAnalyzeOrTerm(
         if( !db->mallocFailed ){
           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
             assert( pAndTerm->pExpr );
-            if( allowedOp(pAndTerm->pExpr->op) 
+            if( allowedOp(pAndTerm->pExpr->op)
              || pAndTerm->eOperator==WO_AUX
             ){
               b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
@@ -140739,14 +145594,14 @@ static void exprAnalyzeOrTerm(
                                             pOrTerm->leftCursor))==0 ){
           /* This term must be of the form t1.a==t2.b where t2 is in the
           ** chngToIN set but t1 is not.  This term will be either preceded
-          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
+          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
           ** and use its inversion. */
           testcase( pOrTerm->wtFlags & TERM_COPIED );
           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
           continue;
         }
-        iColumn = pOrTerm->u.leftColumn;
+        iColumn = pOrTerm->u.x.leftColumn;
         iCursor = pOrTerm->leftCursor;
         pLeft = pOrTerm->pExpr->pLeft;
         break;
@@ -140768,7 +145623,7 @@ static void exprAnalyzeOrTerm(
         assert( pOrTerm->eOperator & WO_EQ );
         if( pOrTerm->leftCursor!=iCursor ){
           pOrTerm->wtFlags &= ~TERM_OR_OK;
-        }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR 
+        }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
                && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
         )){
           okToChngToIN = 0;
@@ -140790,7 +145645,7 @@ static void exprAnalyzeOrTerm(
     }
 
     /* At this point, okToChngToIN is true if original pTerm satisfies
-    ** case 1.  In that case, construct a new virtual term that is 
+    ** case 1.  In that case, construct a new virtual term that is
     ** pTerm converted into an IN operator.
     */
     if( okToChngToIN ){
@@ -140803,7 +145658,7 @@ static void exprAnalyzeOrTerm(
         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
         assert( pOrTerm->eOperator & WO_EQ );
         assert( pOrTerm->leftCursor==iCursor );
-        assert( pOrTerm->u.leftColumn==iColumn );
+        assert( pOrTerm->u.x.leftColumn==iColumn );
         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
         pLeft = pOrTerm->pExpr->pLeft;
@@ -140857,7 +145712,7 @@ static int termIsEquivalence(Parse *pParse, Expr *pExpr){
   ){
     return 0;
   }
-  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
+  pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
   if( sqlite3IsBinary(pColl) ) return 1;
   return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
 }
@@ -140935,8 +145790,8 @@ static int exprMightBeIndexed(
   Expr *pExpr,           /* An operand of a comparison operator */
   int op                 /* The specific comparison operator */
 ){
-  /* If this expression is a vector to the left or right of a 
-  ** inequality constraint (>, <, >= or <=), perform the processing 
+  /* If this expression is a vector to the left or right of a
+  ** inequality constraint (>, <, >= or <=), perform the processing
   ** on the first element of the vector.  */
   assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
   assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
@@ -141039,25 +145894,25 @@ static void exprAnalyze(
     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
 
-    if( pTerm->iField>0 ){
+    if( pTerm->u.x.iField>0 ){
       assert( op==TK_IN );
       assert( pLeft->op==TK_VECTOR );
-      pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
+      pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
     }
 
     if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
       pTerm->leftCursor = aiCurCol[0];
-      pTerm->u.leftColumn = aiCurCol[1];
+      pTerm->u.x.leftColumn = aiCurCol[1];
       pTerm->eOperator = operatorMask(op) & opMask;
     }
     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
-    if( pRight 
+    if( pRight
      && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
     ){
       WhereTerm *pNew;
       Expr *pDup;
       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
-      assert( pTerm->iField==0 );
+      assert( pTerm->u.x.iField==0 );
       if( pTerm->leftCursor>=0 ){
         int idxNew;
         pDup = sqlite3ExprDup(db, pExpr, 0);
@@ -141083,7 +145938,7 @@ static void exprAnalyze(
       }
       pNew->wtFlags |= exprCommute(pParse, pDup);
       pNew->leftCursor = aiCurCol[0];
-      pNew->u.leftColumn = aiCurCol[1];
+      pNew->u.x.leftColumn = aiCurCol[1];
       testcase( (prereqLeft | extraRight) != prereqLeft );
       pNew->prereqRight = prereqLeft | extraRight;
       pNew->prereqAll = prereqAll;
@@ -141116,7 +145971,7 @@ static void exprAnalyze(
     for(i=0; i<2; i++){
       Expr *pNewExpr;
       int idxNew;
-      pNewExpr = sqlite3PExpr(pParse, ops[i], 
+      pNewExpr = sqlite3PExpr(pParse, ops[i],
                              sqlite3ExprDup(db, pExpr->pLeft, 0),
                              sqlite3ExprDup(db, pList->a[i].pExpr, 0));
       transferJoinMarkings(pNewExpr, pExpr);
@@ -141154,7 +146009,7 @@ static void exprAnalyze(
   ** bound is made all lowercase so that the bounds also work when comparing
   ** BLOBs.
   */
-  if( pWC->op==TK_AND 
+  if( pWC->op==TK_AND
    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
   ){
     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
@@ -141190,7 +146045,7 @@ static void exprAnalyze(
       if( noCase ){
         /* The point is to increment the last character before the first
         ** wildcard.  But if we increment '@', that will push it into the
-        ** alphabetic range where case conversions will mess up the 
+        ** alphabetic range where case conversions will mess up the
         ** inequality.  To avoid this, make sure to also run the full
         ** LIKE on all candidate expressions by clearing the isComplete flag
         */
@@ -141246,17 +146101,18 @@ static void exprAnalyze(
       prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
       if( (prereqExpr & prereqColumn)==0 ){
         Expr *pNewExpr;
-        pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
+        pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
             0, sqlite3ExprDup(db, pRight, 0));
         if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
           ExprSetProperty(pNewExpr, EP_FromJoin);
+          pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;
         }
         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
         testcase( idxNew==0 );
         pNewTerm = &pWC->a[idxNew];
         pNewTerm->prereqRight = prereqExpr;
         pNewTerm->leftCursor = pLeft->iTable;
-        pNewTerm->u.leftColumn = pLeft->iColumn;
+        pNewTerm->u.x.leftColumn = pLeft->iColumn;
         pNewTerm->eOperator = WO_AUX;
         pNewTerm->eMatchOp = eOp2;
         markTermAsChild(pWC, idxNew, idxTerm);
@@ -141276,11 +146132,11 @@ static void exprAnalyze(
   **
   ** This is only required if at least one side of the comparison operation
   ** is not a sub-select.  */
-  if( pWC->op==TK_AND 
+  if( pWC->op==TK_AND
   && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
   && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
   && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
-  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 
+  && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
     || (pExpr->pRight->flags & EP_xIsSelect)==0)
   ){
     int i;
@@ -141302,21 +146158,25 @@ static void exprAnalyze(
 
   /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
   ** a virtual term for each vector component. The expression object
-  ** used by each such virtual term is pExpr (the full vector IN(...) 
-  ** expression). The WhereTerm.iField variable identifies the index within
+  ** used by each such virtual term is pExpr (the full vector IN(...)
+  ** expression). The WhereTerm.u.x.iField variable identifies the index within
   ** the vector on the LHS that the virtual term represents.
   **
-  ** This only works if the RHS is a simple SELECT, not a compound
+  ** This only works if the RHS is a simple SELECT (not a compound) that does
+  ** not use window functions.
   */
-  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
+  if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->u.x.iField==0
    && pExpr->pLeft->op==TK_VECTOR
    && pExpr->x.pSelect->pPrior==0
+#ifndef SQLITE_OMIT_WINDOWFUNC
+   && pExpr->x.pSelect->pWin==0
+#endif
   ){
     int i;
     for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
       int idxNew;
       idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
-      pWC->a[idxNew].iField = i+1;
+      pWC->a[idxNew].u.x.iField = i+1;
       exprAnalyze(pSrc, pWC, idxNew);
       markTermAsChild(pWC, idxNew, idxTerm);
     }
@@ -141351,7 +146211,7 @@ static void exprAnalyze(
       pNewTerm = &pWC->a[idxNew];
       pNewTerm->prereqRight = 0;
       pNewTerm->leftCursor = pLeft->iTable;
-      pNewTerm->u.leftColumn = pLeft->iColumn;
+      pNewTerm->u.x.leftColumn = pLeft->iColumn;
       pNewTerm->eOperator = WO_GT;
       markTermAsChild(pWC, idxNew, idxTerm);
       pTerm = &pWC->a[idxTerm];
@@ -141394,6 +146254,7 @@ static void exprAnalyze(
 SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
   Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
   pWC->op = op;
+  assert( pE2!=0 || pExpr==0 );
   if( pE2==0 ) return;
   if( pE2->op!=op ){
     whereClauseInsert(pWC, pExpr, 0);
@@ -141468,9 +146329,10 @@ SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
   }
 #ifndef SQLITE_OMIT_WINDOWFUNC
-  if( p->op==TK_FUNCTION && p->y.pWin ){
+  if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
+    mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
   }
 #endif
   return mask;
@@ -141491,7 +146353,7 @@ SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprLis
 
 
 /*
-** Call exprAnalyze on all terms in a WHERE clause.  
+** Call exprAnalyze on all terms in a WHERE clause.
 **
 ** Note that exprAnalyze() might add new virtual terms onto the
 ** end of the WHERE clause.  We do not want to analyze these new
@@ -141510,7 +146372,7 @@ SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
 
 /*
 ** For table-valued-functions, transform the function arguments into
-** new WHERE clause terms.  
+** new WHERE clause terms.
 **
 ** Each function argument translates into an equality constraint against
 ** a HIDDEN column in the table.
@@ -141543,9 +146405,12 @@ SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
     pColRef->iTable = pItem->iCursor;
     pColRef->iColumn = k++;
     pColRef->y.pTab = pTab;
-    pRhs = sqlite3PExpr(pParse, TK_UPLUS, 
+    pRhs = sqlite3PExpr(pParse, TK_UPLUS,
         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
+    if( pItem->fg.jointype & JT_LEFT ){
+      sqlite3SetJoinExpr(pTerm, pItem->iCursor);
+    }
     whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
   }
 }
@@ -141591,12 +146456,6 @@ struct HiddenIndexInfo {
 /* Forward declaration of methods */
 static int whereLoopResize(sqlite3*, WhereLoop*, int);
 
-/* Test variable that can be set to enable WHERE tracing */
-#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
-/***/ int sqlite3WhereTrace = 0;
-#endif
-
-
 /*
 ** Return the estimated number of output rows from a WHERE clause
 */
@@ -141613,8 +146472,12 @@ SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
 }
 
 /*
-** Return TRUE if the WHERE clause returns rows in ORDER BY order.
-** Return FALSE if the output needs to be sorted.
+** Return the number of ORDER BY terms that are satisfied by the
+** WHERE clause.  A return of 0 means that the output must be
+** completely sorted.  A return equal to the number of ORDER BY
+** terms means that no sorting is needed at all.  A return that
+** is positive but less than the number of ORDER BY terms means that
+** block sorting is required.
 */
 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
   return pWInfo->nOBSat;
@@ -141638,7 +146501,7 @@ SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
 ** be the continuation for the inner-most loop.
 **
 ** It is always safe for this routine to return the continuation of the
-** inner-most loop, in the sense that a correct answer will result.  
+** inner-most loop, in the sense that a correct answer will result.
 ** Returning the continuation the second inner loop is an optimization
 ** that might make the code run a little faster, but should not change
 ** the final answer.
@@ -141646,7 +146509,7 @@ SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
 SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
   WhereLevel *pInner;
   if( !pWInfo->bOrderedInnerLoop ){
-    /* The ORDER BY LIMIT optimization does not apply.  Jump to the 
+    /* The ORDER BY LIMIT optimization does not apply.  Jump to the
     ** continuation of the inner-most loop. */
     return pWInfo->iContinue;
   }
@@ -141674,10 +146537,10 @@ SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
 
 /*
 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
-** operate directly on the rowis returned by a WHERE clause.  Return
+** operate directly on the rowids returned by a WHERE clause.  Return
 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
 ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
-** optimization can be used on multiple 
+** optimization can be used on multiple
 **
 ** If the ONEPASS optimization is used (if this routine returns true)
 ** then also write the indices of open cursors used by ONEPASS
@@ -141702,6 +146565,14 @@ SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
 }
 
 /*
+** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
+** the data cursor to the row selected by the index cursor.
+*/
+SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
+  return pWInfo->bDeferredSeek;
+}
+
+/*
 ** Move the content of pSrc into pDest
 */
 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
@@ -141778,6 +146649,16 @@ static void createMask(WhereMaskSet *pMaskSet, int iCursor){
 }
 
 /*
+** If the right-hand branch of the expression is a TK_COLUMN, then return
+** a pointer to the right-hand branch.  Otherwise, return NULL.
+*/
+static Expr *whereRightSubexprIsColumn(Expr *p){
+  p = sqlite3ExprSkipCollateAndLikely(p->pRight);
+  if( ALWAYS(p!=0) && p->op==TK_COLUMN ) return p;
+  return 0;
+}
+
+/*
 ** Advance to the next WhereTerm that matches according to the criteria
 ** established when the pScan object was initialized by whereScanInit().
 ** Return NULL if there are no more matching WhereTerms.
@@ -141799,7 +146680,7 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
     do{
       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
         if( pTerm->leftCursor==iCur
-         && pTerm->u.leftColumn==iColumn
+         && pTerm->u.x.leftColumn==iColumn
          && (iColumn!=XN_EXPR
              || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
                                        pScan->pIdxExpr,iCur)==0)
@@ -141807,8 +146688,7 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
         ){
           if( (pTerm->eOperator & WO_EQUIV)!=0
            && pScan->nEquiv<ArraySize(pScan->aiCur)
-           && (pX = sqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op
-               ==TK_COLUMN
+           && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
           ){
             int j;
             for(j=0; j<pScan->nEquiv; j++){
@@ -141833,8 +146713,7 @@ static WhereTerm *whereScanNext(WhereScan *pScan){
                 continue;
               }
               assert(pX->pLeft);
-              pColl = sqlite3BinaryCompareCollSeq(pParse,
-                                                  pX->pLeft, pX->pRight);
+              pColl = sqlite3ExprCompareCollSeq(pParse, pX);
               if( pColl==0 ) pColl = pParse->db->pDfltColl;
               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
                 continue;
@@ -141940,7 +146819,7 @@ static WhereTerm *whereScanInit(
 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
 ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
 **
-** If pIdx!=0 then it must be one of the indexes of table iCur.  
+** If pIdx!=0 then it must be one of the indexes of table iCur.
 ** Search for terms matching the iColumn-th column of pIdx
 ** rather than the iColumn-th column of table iCur.
 **
@@ -142005,7 +146884,8 @@ static int findIndexCol(
 
   for(i=0; i<pList->nExpr; i++){
     Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
-    if( p->op==TK_COLUMN
+    if( ALWAYS(p!=0)
+     && p->op==TK_COLUMN
      && p->iColumn==pIdx->aiColumn[iCol]
      && p->iTable==iBase
     ){
@@ -142053,22 +146933,23 @@ static int isDistinctRedundant(
 ){
   Table *pTab;
   Index *pIdx;
-  int i;                          
+  int i;
   int iBase;
 
   /* If there is more than one table or sub-select in the FROM clause of
-  ** this query, then it will not be possible to show that the DISTINCT 
+  ** this query, then it will not be possible to show that the DISTINCT
   ** clause is redundant. */
   if( pTabList->nSrc!=1 ) return 0;
   iBase = pTabList->a[0].iCursor;
   pTab = pTabList->a[0].pTab;
 
-  /* If any of the expressions is an IPK column on table iBase, then return 
+  /* If any of the expressions is an IPK column on table iBase, then return
   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
   ** current SELECT is a correlated sub-query.
   */
   for(i=0; i<pDistinct->nExpr; i++){
     Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
+    if( NEVER(p==0) ) continue;
     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
   }
 
@@ -142114,7 +146995,7 @@ static LogEst estLog(LogEst N){
 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
 **
 ** This routine runs over generated VDBE code and translates OP_Column
-** opcodes into OP_Copy when the table is being accessed via co-routine 
+** opcodes into OP_Copy when the table is being accessed via co-routine
 ** instead of via table lookup.
 **
 ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
@@ -142160,7 +147041,7 @@ static void translateColumnToCopy(
 ** are no-ops.
 */
 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
-static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
+static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
   int i;
   if( !sqlite3WhereTrace ) return;
   for(i=0; i<p->nConstraint; i++){
@@ -142178,7 +147059,7 @@ static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
        p->aOrderBy[i].desc);
   }
 }
-static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
+static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
   int i;
   if( !sqlite3WhereTrace ) return;
   for(i=0; i<p->nConstraint; i++){
@@ -142194,8 +147075,8 @@ static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
 }
 #else
-#define TRACE_IDX_INPUTS(A)
-#define TRACE_IDX_OUTPUTS(A)
+#define whereTraceIndexInfoInputs(A)
+#define whereTraceIndexInfoOutputs(A)
 #endif
 
 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
@@ -142212,7 +147093,7 @@ static int termCanDriveIndex(
   char aff;
   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
   if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
-  if( (pSrc->fg.jointype & JT_LEFT) 
+  if( (pSrc->fg.jointype & JT_LEFT)
    && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
    && (pTerm->eOperator & WO_IS)
   ){
@@ -142222,8 +147103,8 @@ static int termCanDriveIndex(
     return 0;
   }
   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
-  if( pTerm->u.leftColumn<0 ) return 0;
-  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
+  if( pTerm->u.x.leftColumn<0 ) return 0;
+  aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
   testcase( pTerm->pExpr->op==TK_IS );
   return 1;
@@ -142294,7 +147175,7 @@ static void constructAutomaticIndex(
                                 sqlite3ExprDup(pParse->db, pExpr, 0));
     }
     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
-      int iCol = pTerm->u.leftColumn;
+      int iCol = pTerm->u.x.leftColumn;
       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
       testcase( iCol==BMS );
       testcase( iCol==BMS-1 );
@@ -142347,15 +147228,16 @@ static void constructAutomaticIndex(
   idxCols = 0;
   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
-      int iCol = pTerm->u.leftColumn;
+      int iCol = pTerm->u.x.leftColumn;
       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
       testcase( iCol==BMS-1 );
       testcase( iCol==BMS );
       if( (idxCols & cMask)==0 ){
         Expr *pX = pTerm->pExpr;
         idxCols |= cMask;
-        pIdx->aiColumn[n] = pTerm->u.leftColumn;
-        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
+        pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
+        pColl = sqlite3ExprCompareCollSeq(pParse, pX);
+        assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
         pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
         n++;
       }
@@ -142424,11 +147306,11 @@ static void constructAutomaticIndex(
     pTabItem->fg.viaCoroutine = 0;
   }else{
     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
+    sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   }
-  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
   sqlite3VdbeJumpHere(v, addrTop);
   sqlite3ReleaseTempReg(pParse, regRecord);
-  
+
   /* Jump here when skipping the initialization */
   sqlite3VdbeJumpHere(v, addrInit);
 
@@ -142439,7 +147321,7 @@ end_auto_index_create:
 
 #ifndef SQLITE_OMIT_VIRTUALTABLE
 /*
-** Allocate and populate an sqlite3_index_info structure. It is the 
+** Allocate and populate an sqlite3_index_info structure. It is the
 ** responsibility of the caller to eventually release the structure
 ** by passing the pointer returned by this function to sqlite3_free().
 */
@@ -142474,11 +147356,11 @@ static sqlite3_index_info *allocateIndexInfo(
     testcase( pTerm->eOperator & WO_ALL );
     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
     if( pTerm->wtFlags & TERM_VNULL ) continue;
-    assert( pTerm->u.leftColumn>=(-1) );
+    assert( pTerm->u.x.leftColumn>=(-1) );
     nTerm++;
   }
 
-  /* If the ORDER BY clause contains only columns in the current 
+  /* If the ORDER BY clause contains only columns in the current
   ** virtual table then allocate space for the aOrderBy part of
   ** the sqlite3_index_info structure.
   */
@@ -142504,23 +147386,14 @@ static sqlite3_index_info *allocateIndexInfo(
     sqlite3ErrorMsg(pParse, "out of memory");
     return 0;
   }
-
-  /* Initialize the structure.  The sqlite3_index_info structure contains
-  ** many fields that are declared "const" to prevent xBestIndex from
-  ** changing them.  We have to do some funky casting in order to
-  ** initialize those fields.
-  */
   pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
   pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
-  *(int*)&pIdxInfo->nConstraint = nTerm;
-  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
-  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
-  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
-  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
-                                                                   pUsage;
-
+  pIdxInfo->nOrderBy = nOrderBy;
+  pIdxInfo->aConstraint = pIdxCons;
+  pIdxInfo->aOrderBy = pIdxOrderBy;
+  pIdxInfo->aConstraintUsage = pUsage;
   pHidden->pWC = pWC;
   pHidden->pParse = pParse;
   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
@@ -142534,22 +147407,17 @@ static sqlite3_index_info *allocateIndexInfo(
     testcase( pTerm->eOperator & WO_ALL );
     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
     if( pTerm->wtFlags & TERM_VNULL ) continue;
+
+    /* tag-20191211-002: WHERE-clause constraints are not useful to the
+    ** right-hand table of a LEFT JOIN.  See tag-20191211-001 for the
+    ** equivalent restriction for ordinary tables. */
     if( (pSrc->fg.jointype & JT_LEFT)!=0
      && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
-     && (pTerm->eOperator & (WO_IS|WO_ISNULL))
     ){
-      /* An "IS" term in the WHERE clause where the virtual table is the rhs
-      ** of a LEFT JOIN. Do not pass this term to the virtual table
-      ** implementation, as this can lead to incorrect results from SQL such
-      ** as:
-      **
-      **   "LEFT JOIN vtab WHERE vtab.col IS NULL"  */
-      testcase( pTerm->eOperator & WO_ISNULL );
-      testcase( pTerm->eOperator & WO_IS );
       continue;
     }
-    assert( pTerm->u.leftColumn>=(-1) );
-    pIdxCons[j].iColumn = pTerm->u.leftColumn;
+    assert( pTerm->u.x.leftColumn>=(-1) );
+    pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
     pIdxCons[j].iTermOffset = i;
     op = pTerm->eOperator & WO_ALL;
     if( op==WO_IN ) op = WO_EQ;
@@ -142574,9 +147442,10 @@ static sqlite3_index_info *allocateIndexInfo(
       assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
 
       if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
-       && sqlite3ExprIsVector(pTerm->pExpr->pRight) 
+       && sqlite3ExprIsVector(pTerm->pExpr->pRight)
       ){
-        if( i<16 ) mNoOmit |= (1 << i);
+        testcase( j!=i );
+        if( j<16 ) mNoOmit |= (1 << j);
         if( op==WO_LT ) pIdxCons[j].op = WO_LE;
         if( op==WO_GT ) pIdxCons[j].op = WO_GE;
       }
@@ -142584,6 +147453,7 @@ static sqlite3_index_info *allocateIndexInfo(
 
     j++;
   }
+  pIdxInfo->nConstraint = j;
   for(i=0; i<nOrderBy; i++){
     Expr *pExpr = pOrderBy->a[i].pExpr;
     pIdxOrderBy[i].iColumn = pExpr->iColumn;
@@ -142614,9 +147484,9 @@ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
   int rc;
 
-  TRACE_IDX_INPUTS(p);
+  whereTraceIndexInfoInputs(p);
   rc = pVtab->pModule->xBestIndex(pVtab, p);
-  TRACE_IDX_OUTPUTS(p);
+  whereTraceIndexInfoOutputs(p);
 
   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
     if( rc==SQLITE_NOMEM ){
@@ -142644,8 +147514,8 @@ static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
 ** Return the index of the sample that is the smallest sample that
 ** is greater than or equal to pRec. Note that this index is not an index
 ** into the aSample[] array - it is an index into a virtual set of samples
-** based on the contents of aSample[] and the number of fields in record 
-** pRec. 
+** based on the contents of aSample[] and the number of fields in record
+** pRec.
 */
 static int whereKeyStats(
   Parse *pParse,              /* Database connection */
@@ -142681,38 +147551,38 @@ static int whereKeyStats(
   ** consider prefixes of those samples. For example, if the set of samples
   ** in aSample is:
   **
-  **     aSample[0] = (a, 5) 
-  **     aSample[1] = (a, 10) 
-  **     aSample[2] = (b, 5) 
-  **     aSample[3] = (c, 100) 
+  **     aSample[0] = (a, 5)
+  **     aSample[1] = (a, 10)
+  **     aSample[2] = (b, 5)
+  **     aSample[3] = (c, 100)
   **     aSample[4] = (c, 105)
   **
-  ** Then the search space should ideally be the samples above and the 
-  ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 
+  ** Then the search space should ideally be the samples above and the
+  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
   ** the code actually searches this set:
   **
-  **     0: (a) 
-  **     1: (a, 5) 
-  **     2: (a, 10) 
-  **     3: (a, 10) 
-  **     4: (b) 
-  **     5: (b, 5) 
-  **     6: (c) 
-  **     7: (c, 100) 
+  **     0: (a)
+  **     1: (a, 5)
+  **     2: (a, 10)
+  **     3: (a, 10)
+  **     4: (b)
+  **     5: (b, 5)
+  **     6: (c)
+  **     7: (c, 100)
   **     8: (c, 105)
   **     9: (c, 105)
   **
   ** For each sample in the aSample[] array, N samples are present in the
-  ** effective sample array. In the above, samples 0 and 1 are based on 
+  ** effective sample array. In the above, samples 0 and 1 are based on
   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
   **
   ** Often, sample i of each block of N effective samples has (i+1) fields.
   ** Except, each sample may be extended to ensure that it is greater than or
-  ** equal to the previous sample in the array. For example, in the above, 
-  ** sample 2 is the first sample of a block of N samples, so at first it 
-  ** appears that it should be 1 field in size. However, that would make it 
-  ** smaller than sample 1, so the binary search would not work. As a result, 
-  ** it is extended to two fields. The duplicates that this creates do not 
+  ** equal to the previous sample in the array. For example, in the above,
+  ** sample 2 is the first sample of a block of N samples, so at first it
+  ** appears that it should be 1 field in size. However, that would make it
+  ** smaller than sample 1, so the binary search would not work. As a result,
+  ** it is extended to two fields. The duplicates that this creates do not
   ** cause any problems.
   */
   nField = pRec->nField;
@@ -142726,7 +147596,7 @@ static int whereKeyStats(
     iSamp = iTest / nField;
     if( iSamp>0 ){
       /* The proposed effective sample is a prefix of sample aSample[iSamp].
-      ** Specifically, the shortest prefix of at least (1 + iTest%nField) 
+      ** Specifically, the shortest prefix of at least (1 + iTest%nField)
       ** fields that is greater than the previous effective sample.  */
       for(n=(iTest % nField) + 1; n<nField; n++){
         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
@@ -142761,8 +147631,8 @@ static int whereKeyStats(
       assert( i<pIdx->nSample );
       assert( iCol==nField-1 );
       pRec->nField = nField;
-      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 
-           || pParse->db->mallocFailed 
+      assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
+           || pParse->db->mallocFailed
       );
     }else{
       /* Unless i==pIdx->nSample, indicating that pRec is larger than
@@ -142770,7 +147640,7 @@ static int whereKeyStats(
       ** (iCol+1) field prefix of sample i.  */
       assert( i<=pIdx->nSample && i>=0 );
       pRec->nField = iCol+1;
-      assert( i==pIdx->nSample 
+      assert( i==pIdx->nSample
            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
            || pParse->db->mallocFailed );
 
@@ -142798,7 +147668,7 @@ static int whereKeyStats(
     aStat[0] = aSample[i].anLt[iCol];
     aStat[1] = aSample[i].anEq[iCol];
   }else{
-    /* At this point, the (iCol+1) field prefix of aSample[i] is the first 
+    /* At this point, the (iCol+1) field prefix of aSample[i] is the first
     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
     ** is larger than all samples in the array. */
     tRowcnt iUpper, iGap;
@@ -142830,7 +147700,7 @@ static int whereKeyStats(
 
 /*
 ** If it is not NULL, pTerm is a term that provides an upper or lower
-** bound on a range scan. Without considering pTerm, it is estimated 
+** bound on a range scan. Without considering pTerm, it is estimated
 ** that the scan will visit nNew rows. This function returns the number
 ** estimated to be visited after taking pTerm into account.
 **
@@ -142868,18 +147738,18 @@ SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCo
 
 
 #ifdef SQLITE_ENABLE_STAT4
-/* 
+/*
 ** This function is called to estimate the number of rows visited by a
 ** range-scan on a skip-scan index. For example:
 **
 **   CREATE INDEX i1 ON t1(a, b, c);
 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
 **
-** Value pLoop->nOut is currently set to the estimated number of rows 
-** visited for scanning (a=? AND b=?). This function reduces that estimate 
+** Value pLoop->nOut is currently set to the estimated number of rows
+** visited for scanning (a=? AND b=?). This function reduces that estimate
 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
-** on the stat4 data for the index. this scan will be peformed multiple 
-** times (once for each (a,b) combination that matches a=?) is dealt with 
+** on the stat4 data for the index. this scan will be peformed multiple
+** times (once for each (a,b) combination that matches a=?) is dealt with
 ** by the caller.
 **
 ** It does this by scanning through all stat4 samples, comparing values
@@ -142900,7 +147770,7 @@ SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCo
 ** estimate of the number of rows delivered remains unchanged), *pbDone
 ** is left as is.
 **
-** If an error occurs, an SQLite error code is returned. Otherwise, 
+** If an error occurs, an SQLite error code is returned. Otherwise,
 ** SQLITE_OK.
 */
 static int whereRangeSkipScanEst(
@@ -142918,7 +147788,7 @@ static int whereRangeSkipScanEst(
   int rc = SQLITE_OK;
   u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
   CollSeq *pColl;
-  
+
   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
   sqlite3_value *pVal = 0;        /* Value extracted from record */
@@ -142950,7 +147820,7 @@ static int whereRangeSkipScanEst(
     nDiff = (nUpper - nLower);
     if( nDiff<=0 ) nDiff = 1;
 
-    /* If there is both an upper and lower bound specified, and the 
+    /* If there is both an upper and lower bound specified, and the
     ** comparisons indicate that they are close together, use the fallback
     ** method (assume that the scan visits 1/64 of the rows) for estimating
     ** the number of rows visited. Otherwise, estimate the number of rows
@@ -142997,7 +147867,7 @@ static int whereRangeSkipScanEst(
 **
 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
 **
-** then nEq is set to 1 (as the range restricted column, b, is the second 
+** then nEq is set to 1 (as the range restricted column, b, is the second
 ** left-most column of the index). Or, if the query is:
 **
 **   ... FROM t1 WHERE a > ? AND a < ? ...
@@ -143005,13 +147875,13 @@ static int whereRangeSkipScanEst(
 ** then nEq is set to 0.
 **
 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
-** number of rows that the index scan is expected to visit without 
-** considering the range constraints. If nEq is 0, then *pnOut is the number of 
+** number of rows that the index scan is expected to visit without
+** considering the range constraints. If nEq is 0, then *pnOut is the number of
 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
 ** to account for the range constraints pLower and pUpper.
-** 
+**
 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
-** used, a single range inequality reduces the search space by a factor of 4. 
+** used, a single range inequality reduces the search space by a factor of 4.
 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
 ** rows visited by a factor of 64.
 */
@@ -143039,7 +147909,7 @@ static int whereRangeScanEst(
       int nBtm = pLoop->u.btree.nBtm;
       int nTop = pLoop->u.btree.nTop;
 
-      /* Variable iLower will be set to the estimate of the number of rows in 
+      /* Variable iLower will be set to the estimate of the number of rows in
       ** the index that are less than the lower bound of the range query. The
       ** lower bound being the concatenation of $P and $L, where $P is the
       ** key-prefix formed by the nEq values matched against the nEq left-most
@@ -143048,7 +147918,7 @@ static int whereRangeScanEst(
       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
       ** is not a simple variable or literal value), the lower bound of the
       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
-      ** if $L is available, whereKeyStats() is called for both ($P) and 
+      ** if $L is available, whereKeyStats() is called for both ($P) and
       ** ($P:$L) and the larger of the two returned values is used.
       **
       ** Similarly, iUpper is to be set to the estimate of the number of rows
@@ -143072,7 +147942,7 @@ static int whereRangeScanEst(
         iLower = 0;
         iUpper = p->nRowEst0;
       }else{
-        /* Note: this call could be optimized away - since the same values must 
+        /* Note: this call could be optimized away - since the same values must
         ** have been requested when testing key $P in whereEqualScanEst().  */
         whereKeyStats(pParse, p, pRec, 0, a);
         iLower = a[0];
@@ -143160,7 +148030,7 @@ static int whereRangeScanEst(
   ** reduced by an additional 75%. This means that, by default, an open-ended
   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
-  ** match 1/64 of the index. */ 
+  ** match 1/64 of the index. */
   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
     nNew -= 20;
   }
@@ -143187,7 +148057,7 @@ static int whereRangeScanEst(
 ** for that index.  When pExpr==NULL that means the constraint is
 ** "x IS NULL" instead of "x=VALUE".
 **
-** Write the estimated row count into *pnRow and return SQLITE_OK. 
+** Write the estimated row count into *pnRow and return SQLITE_OK.
 ** If unable to make an estimate, leave *pnRow unchanged and return
 ** non-zero.
 **
@@ -143238,7 +148108,7 @@ static int whereEqualScanEst(
   WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
                    p->zName, nEq-1, (int)a[1]));
   *pnRow = a[1];
-  
+
   return rc;
 }
 #endif /* SQLITE_ENABLE_STAT4 */
@@ -143251,7 +148121,7 @@ static int whereEqualScanEst(
 **
 **        WHERE x IN (1,2,3,4)
 **
-** Write the estimated row count into *pnRow and return SQLITE_OK. 
+** Write the estimated row count into *pnRow and return SQLITE_OK.
 ** If unable to make an estimate, leave *pnRow unchanged and return
 ** non-zero.
 **
@@ -143297,34 +148167,42 @@ static int whereInScanEst(
 /*
 ** Print the content of a WhereTerm object
 */
-static void whereTermPrint(WhereTerm *pTerm, int iTerm){
+SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
   if( pTerm==0 ){
     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
   }else{
-    char zType[4];
+    char zType[8];
     char zLeft[50];
-    memcpy(zType, "...", 4);
+    memcpy(zType, "....", 5);
     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
+    if( pTerm->wtFlags & TERM_CODED  ) zType[3] = 'C';
     if( pTerm->eOperator & WO_SINGLE ){
       sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
-                       pTerm->leftCursor, pTerm->u.leftColumn);
+                       pTerm->leftCursor, pTerm->u.x.leftColumn);
     }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
-      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", 
+      sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
                        pTerm->u.pOrInfo->indexable);
     }else{
       sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
     }
     sqlite3DebugPrintf(
-       "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
-       iTerm, pTerm, zType, zLeft, pTerm->truthProb,
-       pTerm->eOperator, pTerm->wtFlags);
-    if( pTerm->iField ){
-      sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
-    }else{
-      sqlite3DebugPrintf("\n");
+       "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
+       iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
+    /* The 0x10000 .wheretrace flag causes extra information to be
+    ** shown about each Term */
+    if( sqlite3WhereTrace & 0x10000 ){
+      sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
+        pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
+    }
+    if( pTerm->u.x.iField ){
+      sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
+    }
+    if( pTerm->iParent>=0 ){
+      sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
     }
+    sqlite3DebugPrintf("\n");
     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
   }
 }
@@ -143337,7 +148215,7 @@ static void whereTermPrint(WhereTerm *pTerm, int iTerm){
 SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
   int i;
   for(i=0; i<pWC->nTerm; i++){
-    whereTermPrint(&pWC->a[i], i);
+    sqlite3WhereTermPrint(&pWC->a[i], i);
   }
 }
 #endif
@@ -143346,7 +148224,7 @@ SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
 /*
 ** Print a WhereLoop object for debugging purposes
 */
-static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
+SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
   WhereInfo *pWInfo = pWC->pWInfo;
   int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
@@ -143371,7 +148249,7 @@ static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
   }else{
     char *z;
     if( p->u.vtab.idxStr ){
-      z = sqlite3_mprintf("(%d,\"%s\",%x)",
+      z = sqlite3_mprintf("(%d,\"%s\",%#x)",
                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
     }else{
       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
@@ -143388,7 +148266,7 @@ static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
     int i;
     for(i=0; i<p->nLTerm; i++){
-      whereTermPrint(p->aLTerm[i], i);
+      sqlite3WhereTermPrint(p->aLTerm[i], i);
     }
   }
 }
@@ -143492,6 +148370,7 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
     pWInfo->pLoops = p->pNextLoop;
     whereLoopDelete(db, p);
   }
+  assert( pWInfo->pExprMods==0 );
   sqlite3DbFreeNN(db, pWInfo);
 }
 
@@ -143506,7 +148385,7 @@ static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
 **
 ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
 ** If X is a proper subset of Y then Y is a better choice and ought
-** to have a lower cost.  This routine returns TRUE when that cost 
+** to have a lower cost.  This routine returns TRUE when that cost
 ** relationship is inverted and needs to be adjusted.  Constraint (4)
 ** was added because if X uses skip-scan less than Y it still might
 ** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)
@@ -143533,7 +148412,7 @@ static int whereLoopCheaperProperSubset(
     }
     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
   }
-  if( (pX->wsFlags&WHERE_IDX_ONLY)!=0 
+  if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
    && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
     return 0;  /* Constraint (5) */
   }
@@ -143560,7 +148439,7 @@ static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
     if( p->iTab!=pTemplate->iTab ) continue;
     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
     if( whereLoopCheaperProperSubset(p, pTemplate) ){
-      /* Adjust pTemplate cost downward so that it is cheaper than its 
+      /* Adjust pTemplate cost downward so that it is cheaper than its
       ** subset p. */
       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
@@ -143606,7 +148485,7 @@ static WhereLoop **whereLoopFindLesser(
     /* In the current implementation, the rSetup value is either zero
     ** or the cost of building an automatic index (NlogN) and the NlogN
     ** is the same for compatible WhereLoops. */
-    assert( p->rSetup==0 || pTemplate->rSetup==0 
+    assert( p->rSetup==0 || pTemplate->rSetup==0
                  || p->rSetup==pTemplate->rSetup );
 
     /* whereLoopAddBtree() always generates and inserts the automatic index
@@ -143671,7 +148550,7 @@ static WhereLoop **whereLoopFindLesser(
 **
 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
 ** still might overwrite similar loops with the new template if the
-** new template is better.  Loops may be overwritten if the following 
+** new template is better.  Loops may be overwritten if the following
 ** conditions are met:
 **
 **    (1)  They have the same iTab.
@@ -143693,21 +148572,23 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
   }
   pBuilder->iPlanLimit--;
 
+  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
+
   /* If pBuilder->pOrSet is defined, then only keep track of the costs
   ** and prereqs.
   */
   if( pBuilder->pOrSet!=0 ){
     if( pTemplate->nLTerm ){
-#if WHERETRACE_ENABLED
+#ifdef WHERETRACE_ENABLED
       u16 n = pBuilder->pOrSet->n;
       int x =
 #endif
       whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
                                     pTemplate->nOut);
-#if WHERETRACE_ENABLED /* 0x8 */
+#ifdef WHERETRACE_ENABLED /* 0x8 */
       if( sqlite3WhereTrace & 0x8 ){
         sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
-        whereLoopPrint(pTemplate, pBuilder->pWC);
+        sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
       }
 #endif
     }
@@ -143716,19 +148597,18 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
 
   /* Look for an existing WhereLoop to replace with pTemplate
   */
-  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
 
   if( ppPrev==0 ){
     /* There already exists a WhereLoop on the list that is better
     ** than pTemplate, so just ignore pTemplate */
-#if WHERETRACE_ENABLED /* 0x8 */
+#ifdef WHERETRACE_ENABLED /* 0x8 */
     if( sqlite3WhereTrace & 0x8 ){
       sqlite3DebugPrintf("   skip: ");
-      whereLoopPrint(pTemplate, pBuilder->pWC);
+      sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
     }
 #endif
-    return SQLITE_OK;  
+    return SQLITE_OK;
   }else{
     p = *ppPrev;
   }
@@ -143737,16 +148617,16 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
   ** WhereLoop and insert it.
   */
-#if WHERETRACE_ENABLED /* 0x8 */
+#ifdef WHERETRACE_ENABLED /* 0x8 */
   if( sqlite3WhereTrace & 0x8 ){
     if( p!=0 ){
       sqlite3DebugPrintf("replace: ");
-      whereLoopPrint(p, pBuilder->pWC);
+      sqlite3WhereLoopPrint(p, pBuilder->pWC);
       sqlite3DebugPrintf("   with: ");
     }else{
       sqlite3DebugPrintf("    add: ");
     }
-    whereLoopPrint(pTemplate, pBuilder->pWC);
+    sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
   }
 #endif
   if( p==0 ){
@@ -143767,10 +148647,10 @@ static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
       pToDel = *ppTail;
       if( pToDel==0 ) break;
       *ppTail = pToDel->pNextLoop;
-#if WHERETRACE_ENABLED /* 0x8 */
+#ifdef WHERETRACE_ENABLED /* 0x8 */
       if( sqlite3WhereTrace & 0x8 ){
         sqlite3DebugPrintf(" delete: ");
-        whereLoopPrint(pToDel, pBuilder->pWC);
+        sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
       }
 #endif
       whereLoopDelete(db, pToDel);
@@ -143846,7 +148726,9 @@ static void whereLoopOutputAdjust(
         /* In the absence of explicit truth probabilities, use heuristics to
         ** guess a reasonable truth probability. */
         pLoop->nOut--;
-        if( pTerm->eOperator&(WO_EQ|WO_IS) ){
+        if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
+         && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */
+        ){
           Expr *pRight = pTerm->pExpr->pRight;
           int k = 0;
           testcase( pTerm->pExpr->op==TK_IS );
@@ -143855,7 +148737,10 @@ static void whereLoopOutputAdjust(
           }else{
             k = 20;
           }
-          if( iReduce<k ) iReduce = k;
+          if( iReduce<k ){
+            pTerm->wtFlags |= TERM_HEURTRUTH;
+            iReduce = k;
+          }
         }
       }
     }
@@ -143863,7 +148748,7 @@ static void whereLoopOutputAdjust(
   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
 }
 
-/* 
+/*
 ** Term pTerm is a vector range comparison operation. The first comparison
 ** in the vector can be optimized using column nEq of the index. This
 ** function returns the total number of vector elements that can be used
@@ -143892,7 +148777,7 @@ static int whereRangeVectorLen(
 
   nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
   for(i=1; i<nCmp; i++){
-    /* Test if comparison i of pTerm is compatible with column (i+nEq) 
+    /* Test if comparison i of pTerm is compatible with column (i+nEq)
     ** of the index. If not, exit the loop.  */
     char aff;                     /* Comparison affinity */
     char idxaff = 0;              /* Indexed columns affinity */
@@ -143909,9 +148794,9 @@ static int whereRangeVectorLen(
     ** the right column of the right source table. And that the sort
     ** order of the index column is the same as the sort order of the
     ** leftmost index column.  */
-    if( pLhs->op!=TK_COLUMN 
-     || pLhs->iTable!=iCur 
-     || pLhs->iColumn!=pIdx->aiColumn[i+nEq] 
+    if( pLhs->op!=TK_COLUMN
+     || pLhs->iTable!=iCur
+     || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
      || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
     ){
       break;
@@ -143940,15 +148825,15 @@ static int whereRangeVectorLen(
 #endif
 
 /*
-** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 
+** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
 ** index pIndex. Try to match one more.
 **
-** When this function is called, pBuilder->pNew->nOut contains the 
-** number of rows expected to be visited by filtering using the nEq 
-** terms only. If it is modified, this value is restored before this 
+** When this function is called, pBuilder->pNew->nOut contains the
+** number of rows expected to be visited by filtering using the nEq
+** terms only. If it is modified, this value is restored before this
 ** function returns.
 **
-** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is 
+** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
 ** a fake index used for the INTEGER PRIMARY KEY.
 */
 static int whereLoopAddBtreeIndex(
@@ -143979,8 +148864,9 @@ static int whereLoopAddBtreeIndex(
 
   pNew = pBuilder->pNew;
   if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
-  WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
-                     pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
+  WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
+                     pProbe->pTable->zName,pProbe->zName,
+                     pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
 
   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
@@ -144026,9 +148912,9 @@ static int whereLoopAddBtreeIndex(
     ** to mix with a lower range bound from some other source */
     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
 
-    /* Do not allow constraints from the WHERE clause to be used by the
-    ** right table of a LEFT JOIN.  Only constraints in the ON clause are
-    ** allowed */
+    /* tag-20191211-001:  Do not allow constraints from the WHERE clause to
+    ** be used by the right table of a LEFT JOIN.  Only constraints in the
+    ** ON clause are allowed.  See tag-20191211-002 for the vtab equivalent. */
     if( (pSrc->fg.jointype & JT_LEFT)!=0
      && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
     ){
@@ -144036,9 +148922,9 @@ static int whereLoopAddBtreeIndex(
     }
 
     if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
-      pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
+      pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
     }else{
-      pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
+      pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
     }
     pNew->wsFlags = saved_wsFlags;
     pNew->u.btree.nEq = saved_nEq;
@@ -144050,9 +148936,9 @@ static int whereLoopAddBtreeIndex(
     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
 
     assert( nInMul==0
-        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 
-        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 
-        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 
+        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
+        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
+        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
     );
 
     if( eOp & WO_IN ){
@@ -144074,12 +148960,12 @@ static int whereLoopAddBtreeIndex(
         /* "x IN (value, value, ...)" */
         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
       }
-      if( pProbe->hasStat1 ){
+      if( pProbe->hasStat1 && rLogSize>=10 ){
         LogEst M, logK, safetyMargin;
         /* Let:
         **   N = the total number of rows in the table
         **   K = the number of entries on the RHS of the IN operator
-        **   M = the number of rows in the table that match terms to the 
+        **   M = the number of rows in the table that match terms to the
         **       to the left in the same index.  If the IN operator is on
         **       the left-most index column, M==N.
         **
@@ -144093,7 +148979,8 @@ static int whereLoopAddBtreeIndex(
         ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
         ** with the index, as using an index has better worst-case behavior.
         ** If we do not have real sqlite_stat1 data, always prefer to use
-        ** the index.
+        ** the index.  Do not bother with this optimization on very small
+        ** tables (less than 2 rows) as it is pointless in that case.
         */
         M = pProbe->aiRowLogEst[saved_nEq];
         logK = estLog(nIn);
@@ -144102,7 +148989,7 @@ static int whereLoopAddBtreeIndex(
           WHERETRACE(0x40,
             ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
              saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
-          continue;
+          pNew->wsFlags |= WHERE_IN_SEEKSCAN;
         }else{
           WHERETRACE(0x40,
             ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
@@ -144114,11 +149001,11 @@ static int whereLoopAddBtreeIndex(
       int iCol = pProbe->aiColumn[saved_nEq];
       pNew->wsFlags |= WHERE_COLUMN_EQ;
       assert( saved_nEq==pNew->u.btree.nEq );
-      if( iCol==XN_ROWID 
+      if( iCol==XN_ROWID
        || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
       ){
-        if( iCol==XN_ROWID || pProbe->uniqNotNull 
-         || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ) 
+        if( iCol==XN_ROWID || pProbe->uniqNotNull
+         || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
         ){
           pNew->wsFlags |= WHERE_ONEROW;
         }else{
@@ -144163,7 +149050,7 @@ static int whereLoopAddBtreeIndex(
 
     /* At this point pNew->nOut is set to the number of rows expected to
     ** be visited by the index scan before considering term pTerm, or the
-    ** values of nIn and nInMul. In other words, assuming that all 
+    ** values of nIn and nInMul. In other words, assuming that all
     ** "x IN(...)" terms are replaced with "x = ?". This block updates
     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
     assert( pNew->nOut==saved_nOut );
@@ -144184,8 +149071,8 @@ static int whereLoopAddBtreeIndex(
       }else{
 #ifdef SQLITE_ENABLE_STAT4
         tRowcnt nOut = 0;
-        if( nInMul==0 
-         && pProbe->nSample 
+        if( nInMul==0
+         && pProbe->nSample
          && pNew->u.btree.nEq<=pProbe->nSampleCol
          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
          && OptimizationEnabled(db, SQLITE_Stat4)
@@ -144203,6 +149090,27 @@ static int whereLoopAddBtreeIndex(
           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
           if( nOut ){
             pNew->nOut = sqlite3LogEst(nOut);
+            if( nEq==1
+             /* TUNING: Mark terms as "low selectivity" if they seem likely
+             ** to be true for half or more of the rows in the table.
+             ** See tag-202002240-1 */
+             && pNew->nOut+10 > pProbe->aiRowLogEst[0]
+            ){
+#ifdef WHERETRACE_ENABLED /* 0x01 */
+              if( sqlite3WhereTrace & 0x01 ){
+                sqlite3DebugPrintf(
+                   "STAT4 determines term has low selectivity:\n");
+                sqlite3WhereTermPrint(pTerm, 999);
+              }
+#endif
+              pTerm->wtFlags |= TERM_HIGHTRUTH;
+              if( pTerm->wtFlags & TERM_HEURTRUTH ){
+                /* If the term has previously been used with an assumption of
+                ** higher selectivity, then set the flag to rerun the
+                ** loop computations. */
+                pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
+              }
+            }
             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
             pNew->nOut -= nIn;
           }
@@ -144212,8 +149120,8 @@ static int whereLoopAddBtreeIndex(
         {
           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
           if( eOp & WO_ISNULL ){
-            /* TUNING: If there is no likelihood() value, assume that a 
-            ** "col IS NULL" expression matches twice as many rows 
+            /* TUNING: If there is no likelihood() value, assume that a
+            ** "col IS NULL" expression matches twice as many rows
             ** as (col=?). */
             pNew->nOut += 10;
           }
@@ -144266,18 +149174,20 @@ static int whereLoopAddBtreeIndex(
 
   /* Consider using a skip-scan if there are no WHERE clause constraints
   ** available for the left-most terms of the index, and if the average
-  ** number of repeats in the left-most terms is at least 18. 
+  ** number of repeats in the left-most terms is at least 18.
   **
   ** The magic number 18 is selected on the basis that scanning 17 rows
   ** is almost always quicker than an index seek (even though if the index
   ** contains fewer than 2^17 rows we assume otherwise in other parts of
-  ** the code). And, even if it is not, it should not be too much slower. 
+  ** the code). And, even if it is not, it should not be too much slower.
   ** On the other hand, the extra seeks could end up being significantly
   ** more expensive.  */
   assert( 42==sqlite3LogEst(18) );
   if( saved_nEq==saved_nSkip
    && saved_nEq+1<pProbe->nKeyCol
+   && saved_nEq==pNew->nLTerm
    && pProbe->noSkipScan==0
+   && pProbe->hasStat1!=0
    && OptimizationEnabled(db, SQLITE_SkipScan)
    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
@@ -144325,6 +149235,7 @@ static int indexMightHelpWithOrderBy(
   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
   for(ii=0; ii<pOB->nExpr; ii++){
     Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
+    if( NEVER(pExpr==0) ) continue;
     if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
       if( pExpr->iColumn<0 ) return 1;
       for(jj=0; jj<pIndex->nKeyCol; jj++){
@@ -144345,21 +149256,26 @@ static int indexMightHelpWithOrderBy(
 /* Check to see if a partial index with pPartIndexWhere can be used
 ** in the current query.  Return true if it can be and false if not.
 */
-static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
+static int whereUsablePartialIndex(
+  int iTab,             /* The table for which we want an index */
+  int isLeft,           /* True if iTab is the right table of a LEFT JOIN */
+  WhereClause *pWC,     /* The WHERE clause of the query */
+  Expr *pWhere          /* The WHERE clause from the partial index */
+){
   int i;
   WhereTerm *pTerm;
   Parse *pParse = pWC->pWInfo->pParse;
   while( pWhere->op==TK_AND ){
-    if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
+    if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0;
     pWhere = pWhere->pRight;
   }
   if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
     Expr *pExpr;
-    if( pTerm->wtFlags & TERM_NOPARTIDX ) continue;
     pExpr = pTerm->pExpr;
     if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
-     && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab) 
+     && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin))
+     && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
     ){
       return 1;
     }
@@ -144381,18 +149297,18 @@ static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
 **     cost = nRow * K                      // scan of covering index
 **     cost = nRow * (K+3.0)                // scan of non-covering index
 **
-** where K is a value between 1.1 and 3.0 set based on the relative 
+** where K is a value between 1.1 and 3.0 set based on the relative
 ** estimated average size of the index and table records.
 **
 ** For an index scan, where nVisit is the number of index rows visited
-** by the scan, and nSeek is the number of seek operations required on 
+** by the scan, and nSeek is the number of seek operations required on
 ** the index b-tree:
 **
 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
 **
-** Normally, nSeek is 1. nSeek values greater than 1 come about if the 
-** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 
+** Normally, nSeek is 1. nSeek values greater than 1 come about if the
+** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
 **
 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
@@ -144422,7 +149338,7 @@ static int whereLoopAddBtree(
   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
   WhereClause *pWC;           /* The parsed WHERE clause */
   Table *pTab;                /* Table being queried */
-  
+
   pNew = pBuilder->pNew;
   pWInfo = pBuilder->pWInfo;
   pTabList = pWInfo->pTabList;
@@ -144516,13 +149432,16 @@ static int whereLoopAddBtree(
   }
 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
 
-  /* Loop over all indices. If there was an INDEXED BY clause, then only 
+  /* Loop over all indices. If there was an INDEXED BY clause, then only
   ** consider index pProbe.  */
-  for(; rc==SQLITE_OK && pProbe; 
+  for(; rc==SQLITE_OK && pProbe;
       pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
   ){
+    int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0;
     if( pProbe->pPartIdxWhere!=0
-     && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
+     && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC,
+                                 pProbe->pPartIdxWhere)
+    ){
       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
       continue;  /* Partial index inappropriate for this query */
     }
@@ -144539,6 +149458,7 @@ static int whereLoopAddBtree(
     pNew->nOut = rSize;
     pNew->u.btree.pIndex = pProbe;
     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
+
     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
     if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
@@ -144547,8 +149467,23 @@ static int whereLoopAddBtree(
 
       /* Full table scan */
       pNew->iSortIdx = b ? iSortIdx : 0;
-      /* TUNING: Cost of full table scan is (N*3.0). */
+      /* TUNING: Cost of full table scan is 3.0*N.  The 3.0 factor is an
+      ** extra cost designed to discourage the use of full table scans,
+      ** since index lookups have better worst-case performance if our
+      ** stat guesses are wrong.  Reduce the 3.0 penalty slightly
+      ** (to 2.75) if we have valid STAT4 information for the table.
+      ** At 2.75, a full table scan is preferred over using an index on
+      ** a column with just two distinct values where each value has about
+      ** an equal number of appearances.  Without STAT4 data, we still want
+      ** to use an index in that case, since the constraint might be for
+      ** the scarcer of the two values, and in that case an index lookup is
+      ** better.
+      */
+#ifdef SQLITE_ENABLE_STAT4
+      pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
+#else
       pNew->rRun = rSize + 16;
+#endif
       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
       whereLoopOutputAdjust(pWC, pNew, rSize);
       rc = whereLoopInsert(pBuilder, pNew);
@@ -144568,6 +149503,7 @@ static int whereLoopAddBtree(
       if( b
        || !HasRowid(pTab)
        || pProbe->pPartIdxWhere!=0
+       || pSrc->fg.isIndexedBy
        || ( m==0
          && pProbe->bUnordered==0
          && (pProbe->szIdxRow<pTab->szTabRow)
@@ -144606,7 +149542,7 @@ static int whereLoopAddBtree(
               if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
             }
           }
-          
+
           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
         }
         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
@@ -144617,9 +149553,9 @@ static int whereLoopAddBtree(
       }
     }
 
-    pBuilder->bldFlags = 0;
+    pBuilder->bldFlags1 = 0;
     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
-    if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
+    if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
       /* If a non-unique index is used, or if a prefix of the key for
       ** unique index is used (making the index functionally non-unique)
       ** then the sqlite_stat1 data becomes important for scoring the
@@ -144681,13 +149617,13 @@ static int whereLoopAddVirtualOne(
   *pbIn = 0;
   pNew->prereq = mPrereq;
 
-  /* Set the usable flag on the subset of constraints identified by 
+  /* Set the usable flag on the subset of constraints identified by
   ** arguments mUsable and mExclude. */
   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
   for(i=0; i<nConstraint; i++, pIdxCons++){
     WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
     pIdxCons->usable = 0;
-    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 
+    if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
      && (pTerm->eOperator & mExclude)==0
     ){
       pIdxCons->usable = 1;
@@ -144749,7 +149685,14 @@ static int whereLoopAddVirtualOne(
       if( iTerm>mxTerm ) mxTerm = iTerm;
       testcase( iTerm==15 );
       testcase( iTerm==16 );
-      if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
+      if( pUsage[i].omit ){
+        if( i<16 && ((1<<i)&mNoOmit)==0 ){
+          testcase( i!=iTerm );
+          pNew->u.vtab.omitMask |= 1<<iTerm;
+        }else{
+          testcase( i!=iTerm );
+        }
+      }
       if( (pTerm->eOperator & WO_IN)!=0 ){
         /* A virtual table that is constrained by an IN clause may not
         ** consume the ORDER BY clause because (1) the order of IN terms
@@ -144762,7 +149705,6 @@ static int whereLoopAddVirtualOne(
       }
     }
   }
-  pNew->u.vtab.omitMask &= ~mNoOmit;
 
   pNew->nLTerm = mxTerm+1;
   for(i=0; i<=mxTerm; i++){
@@ -144819,7 +149761,7 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int
     int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
     Expr *pX = pHidden->pWC->a[iTerm].pExpr;
     if( pX->pLeft ){
-      pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
+      pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
     }
     zRet = (pC ? pC->zName : sqlite3StrBINARY);
   }
@@ -144835,8 +149777,8 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int
 ** entries that occur before the virtual table in the FROM clause and are
 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
 ** mUnusable mask contains all FROM clause entries that occur after the
-** virtual table and are separated from it by at least one LEFT or 
-** CROSS JOIN. 
+** virtual table and are separated from it by at least one LEFT or
+** CROSS JOIN.
 **
 ** For example, if the query were:
 **
@@ -144844,9 +149786,9 @@ SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int
 **
 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
 **
-** All the tables in mPrereq must be scanned before the current virtual 
-** table. So any terms for which all prerequisites are satisfied by 
-** mPrereq may be specified as "usable" in all calls to xBestIndex. 
+** All the tables in mPrereq must be scanned before the current virtual
+** table. So any terms for which all prerequisites are satisfied by
+** mPrereq may be specified as "usable" in all calls to xBestIndex.
 ** Conversely, all tables in mUnusable must be scanned after the current
 ** virtual table, so any terms for which the prerequisites overlap with
 ** mUnusable should always be configured as "not-usable" for xBestIndex.
@@ -144875,7 +149817,7 @@ static int whereLoopAddVirtual(
   pNew = pBuilder->pNew;
   pSrc = &pWInfo->pTabList->a[pNew->iTab];
   assert( IsVirtual(pSrc->pTab) );
-  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy, 
+  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
       &mNoOmit);
   if( p==0 ) return SQLITE_NOMEM_BKPT;
   pNew->rSetup = 0;
@@ -144895,7 +149837,7 @@ static int whereLoopAddVirtual(
 
   /* If the call to xBestIndex() with all terms enabled produced a plan
   ** that does not require any source tables (IOW: a plan with mBest==0)
-  ** and does not use an IN(...) operator, then there is no point in making 
+  ** and does not use an IN(...) operator, then there is no point in making
   ** any further calls to xBestIndex() since they will all return the same
   ** result (if the xBestIndex() implementation is sane). */
   if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
@@ -144918,7 +149860,7 @@ static int whereLoopAddVirtual(
       }
     }
 
-    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 
+    /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
     ** in the set of terms that apply to the current virtual table.  */
     while( rc==SQLITE_OK ){
       int i;
@@ -144975,8 +149917,8 @@ static int whereLoopAddVirtual(
 ** btrees or virtual tables.
 */
 static int whereLoopAddOr(
-  WhereLoopBuilder *pBuilder, 
-  Bitmask mPrereq, 
+  WhereLoopBuilder *pBuilder,
+  Bitmask mPrereq,
   Bitmask mUnusable
 ){
   WhereInfo *pWInfo = pBuilder->pWInfo;
@@ -144989,7 +149931,7 @@ static int whereLoopAddOr(
   WhereLoopBuilder sSubBuild;
   WhereOrSet sSum, sCur;
   struct SrcList_item *pItem;
-  
+
   pWC = pBuilder->pWC;
   pWCEnd = pWC->a + pWC->nTerm;
   pNew = pBuilder->pNew;
@@ -144999,14 +149941,14 @@ static int whereLoopAddOr(
 
   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
     if( (pTerm->eOperator & WO_OR)!=0
-     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
+     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
     ){
       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
       WhereTerm *pOrTerm;
       int once = 1;
       int i, j;
-    
+
       sSubBuild = *pBuilder;
       sSubBuild.pOrderBy = 0;
       sSubBuild.pOrSet = &sCur;
@@ -145027,7 +149969,7 @@ static int whereLoopAddOr(
         }
         sCur.n = 0;
 #ifdef WHERETRACE_ENABLED
-        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 
+        WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
         if( sqlite3WhereTrace & 0x400 ){
           sqlite3WhereClausePrint(sSubBuild.pWC);
@@ -145044,7 +149986,8 @@ static int whereLoopAddOr(
         if( rc==SQLITE_OK ){
           rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
         }
-        assert( rc==SQLITE_OK || sCur.n==0 );
+        assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 );
+        testcase( rc==SQLITE_DONE );
         if( sCur.n==0 ){
           sSum.n = 0;
           break;
@@ -145074,8 +150017,8 @@ static int whereLoopAddOr(
         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
         ** of all sub-scans required by the OR-scan. However, due to rounding
         ** errors, it may be that the cost of the OR-scan is equal to its
-        ** most expensive sub-scan. Add the smallest possible penalty 
-        ** (equivalent to multiplying the cost by 1.07) to ensure that 
+        ** most expensive sub-scan. Add the smallest possible penalty
+        ** (equivalent to multiplying the cost by 1.07) to ensure that
         ** this does not happen. Otherwise, for WHERE clauses such as the
         ** following where there is an index on "y":
         **
@@ -145095,7 +150038,7 @@ static int whereLoopAddOr(
 }
 
 /*
-** Add all WhereLoop objects for all tables 
+** Add all WhereLoop objects for all tables
 */
 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
   WhereInfo *pWInfo = pBuilder->pWInfo;
@@ -145108,7 +150051,6 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
   sqlite3 *db = pWInfo->pParse->db;
   int rc = SQLITE_OK;
   WhereLoop *pNew;
-  u8 priorJointype = 0;
 
   /* Loop over the tables in the join, from left to right */
   pNew = pBuilder->pNew;
@@ -145119,12 +150061,13 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
     pNew->iTab = iTab;
     pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
     pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
-    if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
+    if( (pItem->fg.jointype & (JT_LEFT|JT_CROSS))!=0 ){
       /* This condition is true when pItem is the FROM clause term on the
       ** right-hand-side of a LEFT or CROSS JOIN.  */
       mPrereq = mPrior;
+    }else{
+      mPrereq = 0;
     }
-    priorJointype = pItem->fg.jointype;
 #ifndef SQLITE_OMIT_VIRTUALTABLE
     if( IsVirtual(pItem->pTab) ){
       struct SrcList_item *p;
@@ -145162,17 +150105,17 @@ static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
 ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
 ** parameters) to see if it outputs rows in the requested ORDER BY
 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
-** 
+**
 **   N>0:   N terms of the ORDER BY clause are satisfied
 **   N==0:  No terms of the ORDER BY clause are satisfied
-**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   
+**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
 **
 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
 ** strict.  With GROUP BY and DISTINCT the only requirement is that
 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
 ** and DISTINCT do not require rows to appear in any particular order as long
 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
-** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
+** the pOrderBy terms can be matched in any order.  With ORDER BY, the
 ** pOrderBy terms must be matched in strict left-to-right order.
 */
 static i8 wherePathSatisfiesOrderBy(
@@ -145222,7 +150165,7 @@ static i8 wherePathSatisfiesOrderBy(
   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
   ** is not order-distinct. To be order-distinct is not quite the same as being
-  ** UNIQUE since a UNIQUE column or index can have multiple rows that 
+  ** UNIQUE since a UNIQUE column or index can have multiple rows that
   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
   **
@@ -145242,7 +150185,9 @@ static i8 wherePathSatisfiesOrderBy(
   orderDistinctMask = 0;
   ready = 0;
   eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
-  if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
+  if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
+    eqOpMask |= WO_IN;
+  }
   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
     if( iLoop>0 ) ready |= pLoop->maskSelf;
     if( iLoop<nLoop ){
@@ -145252,7 +150197,9 @@ static i8 wherePathSatisfiesOrderBy(
       pLoop = pLast;
     }
     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
-      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
+      if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){
+        obSat = obDone;
+      }
       break;
     }else if( wctrlFlags & WHERE_DISTINCTBY ){
       pLoop->u.btree.nDistinctCol = 0;
@@ -145267,22 +150214,27 @@ static i8 wherePathSatisfiesOrderBy(
     for(i=0; i<nOrderBy; i++){
       if( MASKBIT(i) & obSat ) continue;
       pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
+      if( NEVER(pOBExpr==0) ) continue;
       if( pOBExpr->op!=TK_COLUMN ) continue;
       if( pOBExpr->iTable!=iCur ) continue;
       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
                        ~ready, eqOpMask, 0);
       if( pTerm==0 ) continue;
       if( pTerm->eOperator==WO_IN ){
-        /* IN terms are only valid for sorting in the ORDER BY LIMIT 
+        /* IN terms are only valid for sorting in the ORDER BY LIMIT
         ** optimization, and then only if they are actually used
         ** by the query plan */
-        assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
+        assert( wctrlFlags &
+               (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
         for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
         if( j>=pLoop->nLTerm ) continue;
       }
       if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
-        if( sqlite3ExprCollSeqMatch(pWInfo->pParse, 
-                  pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
+        Parse *pParse = pWInfo->pParse;
+        CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
+        CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
+        assert( pColl1 );
+        if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
           continue;
         }
         testcase( pTerm->pExpr->op==TK_IS );
@@ -145315,7 +150267,7 @@ static i8 wherePathSatisfiesOrderBy(
       for(j=0; j<nColumn; j++){
         u8 bOnce = 1; /* True to run the ORDER BY search loop */
 
-        assert( j>=pLoop->u.btree.nEq 
+        assert( j>=pLoop->u.btree.nEq
             || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
         );
         if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
@@ -145327,7 +150279,7 @@ static i8 wherePathSatisfiesOrderBy(
           ** the loop need to be marked as not order-distinct because it can
           ** have repeated NULL rows.
           **
-          ** If the current term is a column of an ((?,?) IN (SELECT...)) 
+          ** If the current term is a column of an ((?,?) IN (SELECT...))
           ** expression for which the SELECT returns more than one column,
           ** check that it is the only column used by this loop. Otherwise,
           ** if it is one of two or more, none of the columns can be
@@ -145340,7 +150292,7 @@ static i8 wherePathSatisfiesOrderBy(
               testcase( isOrderDistinct );
               isOrderDistinct = 0;
             }
-            continue;  
+            continue;
           }else if( ALWAYS(eOp & WO_IN) ){
             /* ALWAYS() justification: eOp is an equality operator due to the
             ** j<pLoop->u.btree.nEq constraint above.  Any equality other
@@ -145381,7 +150333,7 @@ static i8 wherePathSatisfiesOrderBy(
         }
 
         /* Find the ORDER BY term that corresponds to the j-th column
-        ** of the index and mark that ORDER BY term off 
+        ** of the index and mark that ORDER BY term off
         */
         isMatch = 0;
         for(i=0; bOnce && i<nOrderBy; i++){
@@ -145389,6 +150341,7 @@ static i8 wherePathSatisfiesOrderBy(
           pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
           testcase( wctrlFlags & WHERE_GROUPBY );
           testcase( wctrlFlags & WHERE_DISTINCTBY );
+          if( NEVER(pOBExpr==0) ) continue;
           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
           if( iColumn>=XN_ROWID ){
             if( pOBExpr->op!=TK_COLUMN ) continue;
@@ -145521,7 +150474,7 @@ static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
 #endif
 
 /*
-** Return the cost of sorting nRow rows, assuming that the keys have 
+** Return the cost of sorting nRow rows, assuming that the keys have
 ** nOrderby columns and that the first nSorted columns are already in
 ** order.
 */
@@ -145531,28 +150484,36 @@ static LogEst whereSortingCost(
   int nOrderBy,
   int nSorted
 ){
-  /* TUNING: Estimated cost of a full external sort, where N is 
+  /* TUNING: Estimated cost of a full external sort, where N is
   ** the number of rows to sort is:
   **
   **   cost = (3.0 * N * log(N)).
-  ** 
-  ** Or, if the order-by clause has X terms but only the last Y 
-  ** terms are out of order, then block-sorting will reduce the 
+  **
+  ** Or, if the order-by clause has X terms but only the last Y
+  ** terms are out of order, then block-sorting will reduce the
   ** sorting cost to:
   **
   **   cost = (3.0 * N * log(N)) * (Y/X)
   **
   ** The (Y/X) term is implemented using stack variable rScale
-  ** below.  */
+  ** below.
+  */
   LogEst rScale, rSortCost;
   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
   rSortCost = nRow + rScale + 16;
 
   /* Multiple by log(M) where M is the number of output rows.
-  ** Use the LIMIT for M if it is smaller */
+  ** Use the LIMIT for M if it is smaller.  Or if this sort is for
+  ** a DISTINCT operator, M will be the number of distinct output
+  ** rows, so fudge it downwards a bit.
+  */
   if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
     nRow = pWInfo->iLimit;
+  }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
+    /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
+    ** reduces the number of output rows by a factor of 2 */
+    if( nRow>10 ) nRow -= 10;  assert( 10==sqlite3LogEst(2) );
   }
   rSortCost += estLog(nRow);
   return rSortCost;
@@ -145630,7 +150591,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
     ** space for the aSortCost[] array. Each element of the aSortCost array
     ** is either zero - meaning it has not yet been initialized - or the
     ** cost of sorting nRowEst rows of data where the first X terms of
-    ** the ORDER BY clause are already in order, where X is the array 
+    ** the ORDER BY clause are already in order, where X is the array
     ** index.  */
     aSortCost = (LogEst*)pX;
     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
@@ -145651,7 +150612,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
     ** in this case the query may return a maximum of one row, the results
     ** are already in the requested order. Set isOrdered to nOrderBy to
     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
-    ** -1, indicating that the result set may or may not be ordered, 
+    ** -1, indicating that the result set may or may not be ordered,
     ** depending on the loops added to the current plan.  */
     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
   }
@@ -145681,7 +150642,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
           continue;
         }
 
-        /* At this point, pWLoop is a candidate to be the next loop. 
+        /* At this point, pWLoop is a candidate to be the next loop.
         ** Compute its cost */
         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
@@ -145708,7 +150669,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
 
           WHERETRACE(0x002,
               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
-               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
+               aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
                rUnsorted, rCost));
         }else{
           rCost = rUnsorted;
@@ -145773,11 +150734,11 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
           ** same set of loops and has the same isOrdered setting as the
           ** candidate path.  Check to see if the candidate should replace
           ** pTo or if the candidate should be skipped.
-          ** 
+          **
           ** The conditional is an expanded vector comparison equivalent to:
           **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
           */
-          if( pTo->rCost<rCost 
+          if( pTo->rCost<rCost
            || (pTo->rCost==rCost
                && (pTo->nRow<nOut
                    || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
@@ -145828,8 +150789,8 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
           mxCost = aTo[0].rCost;
           mxUnsorted = aTo[0].nRow;
           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
-            if( pTo->rCost>mxCost 
-             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
+            if( pTo->rCost>mxCost
+             || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
             ){
               mxCost = pTo->rCost;
               mxUnsorted = pTo->rUnsorted;
@@ -145868,7 +150829,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
     sqlite3DbFreeNN(db, pSpace);
     return SQLITE_ERROR;
   }
-  
+
   /* Find the lowest cost path.  pFrom will be left pointing to that path */
   pFrom = aFrom;
   for(ii=1; ii<nFrom; ii++){
@@ -145907,7 +150868,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
         pWInfo->nOBSat = 0;
         if( nLoop>0 ){
           u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
-          if( (wsFlags & WHERE_ONEROW)==0 
+          if( (wsFlags & WHERE_ONEROW)==0
            && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
           ){
             Bitmask m = 0;
@@ -145921,13 +150882,18 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
             }
           }
         }
+      }else if( nLoop
+            && pWInfo->nOBSat==1
+            && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
+            ){
+        pWInfo->bOrderedInnerLoop = 1;
       }
     }
     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
     ){
       Bitmask revMask = 0;
-      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 
+      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
       );
       assert( pWInfo->sorted==0 );
@@ -145954,7 +150920,7 @@ static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
 ** times for the common case.
 **
 ** Return non-zero on success, if this query can be handled by this
-** no-frills query planner.  Return zero if this query needs the 
+** no-frills query planner.  Return zero if this query needs the
 ** general-purpose query planner.
 */
 static int whereShortCut(WhereLoopBuilder *pBuilder){
@@ -145994,8 +150960,8 @@ static int whereShortCut(WhereLoopBuilder *pBuilder){
       int opMask;
       assert( pLoop->aLTermSpace==pLoop->aLTerm );
       if( !IsUniqueIndex(pIdx)
-       || pIdx->pPartIdxWhere!=0 
-       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
+       || pIdx->pPartIdxWhere!=0
+       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
       ) continue;
       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
       for(j=0; j<pIdx->nKeyCol; j++){
@@ -146048,8 +151014,8 @@ static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
 }
 
 /*
-** Return true if the expression contains no non-deterministic SQL 
-** functions. Do not consider non-deterministic SQL functions that are 
+** Return true if the expression contains no non-deterministic SQL
+** functions. Do not consider non-deterministic SQL functions that are
 ** part of sub-select statements.
 */
 static int exprIsDeterministic(Expr *p){
@@ -146062,6 +151028,28 @@ static int exprIsDeterministic(Expr *p){
   return w.eCode;
 }
 
+
+#ifdef WHERETRACE_ENABLED
+/*
+** Display all WhereLoops in pWInfo
+*/
+static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
+  if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
+    WhereLoop *p;
+    int i;
+    static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
+                                           "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
+    for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
+      p->cId = zLabel[i%(sizeof(zLabel)-1)];
+      sqlite3WhereLoopPrint(p, pWC);
+    }
+  }
+}
+# define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
+#else
+# define WHERETRACE_ALL_LOOPS(W,C)
+#endif
+
 /*
 ** Generate the beginning of the loop used for WHERE clause processing.
 ** The return value is a pointer to an opaque structure that contains
@@ -146142,7 +151130,7 @@ static int exprIsDeterministic(Expr *p){
 ** if there is one.  If there is no ORDER BY clause or if this routine
 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
 **
-** The iIdxCur parameter is the cursor number of an index.  If 
+** The iIdxCur parameter is the cursor number of an index.  If
 ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
 ** to use for OR clause processing.  The WHERE clause should use this
 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
@@ -146175,8 +151163,8 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
 
   assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
-        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
-     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 
+        (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
+     && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
   ));
 
   /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
@@ -146199,7 +151187,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   }
 
   /* The number of tables in the FROM clause is limited by the number of
-  ** bits in a Bitmask 
+  ** bits in a Bitmask
   */
   testcase( pTabList->nSrc==BMS );
   if( pTabList->nSrc>BMS ){
@@ -146207,7 +151195,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
     return 0;
   }
 
-  /* This function normally generates a nested loop for all tables in 
+  /* This function normally generates a nested loop for all tables in
   ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
   ** only generate code for the first table in pTabList and assume that
   ** any cursors associated with subsequent tables are uninitialized.
@@ -146239,7 +151227,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   pWInfo->wctrlFlags = wctrlFlags;
   pWInfo->iLimit = iAuxArg;
   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
-  memset(&pWInfo->nOBSat, 0, 
+  memset(&pWInfo->nOBSat, 0,
          offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
   memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
   assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
@@ -146259,7 +151247,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   initMaskSet(pMaskSet);
   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
-    
+
   /* Special case: No FROM clause
   */
   if( nTabList==0 ){
@@ -146299,14 +151287,14 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
     }
   #endif
   }
-  
+
   /* Analyze all of the subexpressions. */
   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
   if( db->mallocFailed ) goto whereBeginError;
 
   /* Special case: WHERE terms that do not refer to any tables in the join
   ** (constant expressions). Evaluate each such term, and jump over all the
-  ** generated code if the result is not true.  
+  ** generated code if the result is not true.
   **
   ** Do not do this if the expression contains non-deterministic functions
   ** that are not within a sub-select. This is not strictly required, but
@@ -146355,6 +151343,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
     }
   }
   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
+    sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
     sqlite3WhereClausePrint(sWLB.pWC);
   }
 #endif
@@ -146362,20 +151351,29 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
     rc = whereLoopAddAll(&sWLB);
     if( rc ) goto whereBeginError;
-  
-#ifdef WHERETRACE_ENABLED
-    if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
-      WhereLoop *p;
-      int i;
-      static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
-                                             "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
-      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
-        p->cId = zLabel[i%(sizeof(zLabel)-1)];
-        whereLoopPrint(p, sWLB.pWC);
-      }
-    }
-#endif
-  
+
+#ifdef SQLITE_ENABLE_STAT4
+    /* If one or more WhereTerm.truthProb values were used in estimating
+    ** loop parameters, but then those truthProb values were subsequently
+    ** changed based on STAT4 information while computing subsequent loops,
+    ** then we need to rerun the whole loop building process so that all
+    ** loops will be built using the revised truthProb values. */
+    if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
+      WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
+      WHERETRACE(0xffff,
+           ("**** Redo all loop computations due to"
+            " TERM_HIGHTRUTH changes ****\n"));
+      while( pWInfo->pLoops ){
+        WhereLoop *p = pWInfo->pLoops;
+        pWInfo->pLoops = p->pNextLoop;
+        whereLoopDelete(db, p);
+      }
+      rc = whereLoopAddAll(&sWLB);
+      if( rc ) goto whereBeginError;
+    }
+#endif
+    WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
+
     wherePathSolver(pWInfo, 0);
     if( db->mallocFailed ) goto whereBeginError;
     if( pWInfo->pOrderBy ){
@@ -146411,7 +151409,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
     }
     sqlite3DebugPrintf("\n");
     for(ii=0; ii<pWInfo->nLevel; ii++){
-      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
+      sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
     }
   }
 #endif
@@ -146422,7 +151420,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   **   1) The query must not be an aggregate.
   **   2) The table must be the RHS of a LEFT JOIN.
   **   3) Either the query must be DISTINCT, or else the ON or USING clause
-  **      must contain a constraint that limits the scan of the table to 
+  **      must contain a constraint that limits the scan of the table to
   **      at most a single row.
   **   4) The table must not be referenced by any part of the query apart
   **      from its own USING or ON clause.
@@ -146435,15 +151433,15 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
   **
   ** then table t2 can be omitted from the following:
   **
-  **     SELECT v1, v3 FROM t1 
-  **       LEFT JOIN t2 USING (t1.ipk=t2.ipk)
-  **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
+  **     SELECT v1, v3 FROM t1
+  **       LEFT JOIN t2 ON (t1.ipk=t2.ipk)
+  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
   **
   ** or from:
   **
-  **     SELECT DISTINCT v1, v3 FROM t1 
+  **     SELECT DISTINCT v1, v3 FROM t1
   **       LEFT JOIN t2
-  **       LEFT JOIN t3 USING (t1.ipk=t3.ipk)
+  **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
   */
   notReady = ~(Bitmask)0;
   if( pWInfo->nLevel>=2
@@ -146493,7 +151491,13 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
       nTabList--;
     }
   }
+#if defined(WHERETRACE_ENABLED)
+  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
+    sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
+    sqlite3WhereClausePrint(sWLB.pWC);
+  }
   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
+#endif
   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
 
   /* If the caller is an UPDATE or DELETE statement that is requesting
@@ -146570,7 +151574,13 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
       assert( pTabItem->iCursor==pLevel->iTabCur );
       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
-      if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
+      if( pWInfo->eOnePass==ONEPASS_OFF
+       && pTab->nCol<BMS
+       && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
+      ){
+        /* If we know that only a prefix of the record will be used,
+        ** it is advantageous to reduce the "column count" field in
+        ** the P4 operand of the OP_OpenRead/Write opcode. */
         Bitmask b = pTabItem->colUsed;
         int n = 0;
         for(; b; b=b>>1, n++){}
@@ -146630,10 +151640,11 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
          && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
+         && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
          && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
         ){
-          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
+          sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
         }
         VdbeComment((v, "%s", pIx->zName));
 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
@@ -146687,6 +151698,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
 
   /* Done. */
   VdbeModuleComment((v, "Begin WHERE-core"));
+  pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
   return pWInfo;
 
   /* Jump here if malloc fails */
@@ -146719,7 +151731,7 @@ whereBeginError:
 #endif
 
 /*
-** Generate the end of the WHERE loop.  See comments on 
+** Generate the end of the WHERE loop.  See comments on
 ** sqlite3WhereBegin() for additional information.
 */
 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
@@ -146730,6 +151742,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   WhereLoop *pLoop;
   SrcList *pTabList = pWInfo->pTabList;
   sqlite3 *db = pParse->db;
+  int iEnd = sqlite3VdbeCurrentAddr(v);
 
   /* Generate loop termination code.
   */
@@ -146790,11 +151803,28 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
         if( pIn->eEndLoopOp!=OP_Noop ){
           if( pIn->nPrefix ){
-            assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
-            sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
-                              sqlite3VdbeCurrentAddr(v)+2,
-                              pIn->iBase, pIn->nPrefix);
-            VdbeCoverage(v);
+            int bEarlyOut =
+                (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
+                 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
+            if( pLevel->iLeftJoin ){
+              /* For LEFT JOIN queries, cursor pIn->iCur may not have been
+              ** opened yet. This occurs for WHERE clauses such as
+              ** "a = ? AND b IN (...)", where the index is on (a, b). If
+              ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
+              ** never have been coded, but the body of the loop run to
+              ** return the null-row. So, if the cursor is not open yet,
+              ** jump over the OP_Next or OP_Prev instruction about to
+              ** be coded.  */
+              sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
+                  sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
+              VdbeCoverage(v);
+            }
+            if( bEarlyOut ){
+              sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
+                  sqlite3VdbeCurrentAddr(v)+2,
+                  pIn->iBase, pIn->nPrefix);
+              VdbeCoverage(v);
+            }
           }
           sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
           VdbeCoverage(v);
@@ -146826,8 +151856,8 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
         assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
       }
-      if( (ws & WHERE_INDEXED) 
-       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx) 
+      if( (ws & WHERE_INDEXED)
+       || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
       ){
         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
       }
@@ -146850,7 +151880,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
   assert( pWInfo->nLevel<=pTabList->nSrc );
   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
     int k, last;
-    VdbeOp *pOp;
+    VdbeOp *pOp, *pLastOp;
     Index *pIdx = 0;
     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
     Table *pTab = pTabItem->pTab;
@@ -146883,7 +151913,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
       }
       if( (ws & WHERE_INDEXED)!=0
-       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 
+       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
       ){
         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
@@ -146895,7 +151925,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
     ** from the index instead of from the table where possible.  In some cases
     ** this optimization prevents the table from ever being read, which can
     ** yield a significant performance boost.
-    ** 
+    **
     ** Calls to the code generator in between sqlite3WhereBegin and
     ** sqlite3WhereEnd will have created code that references the table
     ** directly.  This loop scans all that code looking for opcodes
@@ -146908,20 +151938,31 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
       pIdx = pLevel->u.pCovidx;
     }
     if( pIdx
-     && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
      && !db->mallocFailed
     ){
-      last = sqlite3VdbeCurrentAddr(v);
-      k = pLevel->addrBody;
+      if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
+        last = iEnd;
+      }else{
+        last = pWInfo->iEndWhere;
+      }
+      k = pLevel->addrBody + 1;
 #ifdef SQLITE_DEBUG
       if( db->flags & SQLITE_VdbeAddopTrace ){
         printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
       }
+      /* Proof that the "+1" on the k value above is safe */
+      pOp = sqlite3VdbeGetOp(v, k - 1);
+      assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
+      assert( pOp->opcode!=OP_Rowid  || pOp->p1!=pLevel->iTabCur );
+      assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
 #endif
       pOp = sqlite3VdbeGetOp(v, k);
-      for(; k<last; k++, pOp++){
-        if( pOp->p1!=pLevel->iTabCur ) continue;
-        if( pOp->opcode==OP_Column
+      pLastOp = pOp + (last - k);
+      assert( pOp<pLastOp );
+      do{
+        if( pOp->p1!=pLevel->iTabCur ){
+          /* no-op */
+        }else if( pOp->opcode==OP_Column
 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
          || pOp->opcode==OP_Offset
 #endif
@@ -146932,14 +151973,17 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
             x = pPk->aiColumn[x];
             assert( x>=0 );
+          }else{
+            testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
+            x = sqlite3StorageColumnToTable(pTab,x);
           }
-          x = sqlite3ColumnOfIndex(pIdx, x);
+          x = sqlite3TableColumnToIndex(pIdx, x);
           if( x>=0 ){
             pOp->p2 = x;
             pOp->p1 = pLevel->iIdxCur;
             OpcodeRewriteTrace(db, k, pOp);
           }
-          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 
+          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
               || pWInfo->eOnePass );
         }else if( pOp->opcode==OP_Rowid ){
           pOp->p1 = pLevel->iIdxCur;
@@ -146949,13 +151993,24 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
           pOp->p1 = pLevel->iIdxCur;
           OpcodeRewriteTrace(db, k, pOp);
         }
-      }
+#ifdef SQLITE_DEBUG
+        k++;
+#endif
+      }while( (++pOp)<pLastOp );
 #ifdef SQLITE_DEBUG
       if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
 #endif
     }
   }
 
+  /* Undo all Expr node modifications */
+  while( pWInfo->pExprMods ){
+    WhereExprMod *p = pWInfo->pExprMods;
+    pWInfo->pExprMods = p->pNext;
+    memcpy(p->pExpr, &p->orig, sizeof(p->orig));
+    sqlite3DbFree(db, p);
+  }
+
   /* Final cleanup
   */
   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
@@ -147007,12 +152062,12 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 **   (in this case max()) to process rows sorted in order of (c, d), which
 **   makes things easier for obvious reasons. More generally:
 **
-**     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to 
+**     * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
 **       the sub-query.
 **
 **     * ORDER BY, LIMIT and OFFSET remain part of the parent query.
 **
-**     * Terminals from each of the expression trees that make up the 
+**     * Terminals from each of the expression trees that make up the
 **       select-list and ORDER BY expressions in the parent query are
 **       selected by the sub-query. For the purposes of the transformation,
 **       terminals are column references and aggregate functions.
@@ -147021,14 +152076,14 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 **   the same window declaration (the OVER bit), then a single scan may
 **   be used to process more than one window function. For example:
 **
-**     SELECT max(b) OVER (PARTITION BY c ORDER BY d), 
-**            min(e) OVER (PARTITION BY c ORDER BY d) 
+**     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
+**            min(e) OVER (PARTITION BY c ORDER BY d)
 **     FROM t1;
 **
 **   is transformed in the same way as the example above. However:
 **
-**     SELECT max(b) OVER (PARTITION BY c ORDER BY d), 
-**            min(e) OVER (PARTITION BY a ORDER BY b) 
+**     SELECT max(b) OVER (PARTITION BY c ORDER BY d),
+**            min(e) OVER (PARTITION BY a ORDER BY b)
 **     FROM t1;
 **
 **   Must be transformed to:
@@ -147081,15 +152136,15 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 **     first_value(expr)
 **     last_value(expr)
 **     nth_value(expr, N)
-**   
-**   These are the same built-in window functions supported by Postgres. 
+**
+**   These are the same built-in window functions supported by Postgres.
 **   Although the behaviour of aggregate window functions (functions that
 **   can be used as either aggregates or window funtions) allows them to
 **   be implemented using an API, built-in window functions are much more
-**   esoteric. Additionally, some window functions (e.g. nth_value()) 
+**   esoteric. Additionally, some window functions (e.g. nth_value())
 **   may only be implemented by caching the entire partition in memory.
 **   As such, some built-in window functions use the same API as aggregate
-**   window functions and some are implemented directly using VDBE 
+**   window functions and some are implemented directly using VDBE
 **   instructions. Additionally, for those functions that use the API, the
 **   window frame is sometimes modified before the SELECT statement is
 **   rewritten. For example, regardless of the specified window frame, the
@@ -147101,7 +152156,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 **
 **   As well as some of the built-in window functions, aggregate window
 **   functions min() and max() are implemented using VDBE instructions if
-**   the start of the window frame is declared as anything other than 
+**   the start of the window frame is declared as anything other than
 **   UNBOUNDED PRECEDING.
 */
 
@@ -147112,7 +152167,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
 **   ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
 */
 static void row_numberStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147140,10 +152195,10 @@ struct CallCount {
 ** Implementation of built-in window function dense_rank(). Assumes that
 ** the window frame has been set to:
 **
-**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
+**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
 */
 static void dense_rankStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147175,7 +152230,7 @@ struct NthValueCtx {
   sqlite3_value *pValue;
 };
 static void nth_valueStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147228,7 +152283,7 @@ static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
 #define nth_valueValueFunc noopValueFunc
 
 static void first_valueStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147259,10 +152314,10 @@ static void first_valueFinalizeFunc(sqlite3_context *pCtx){
 ** Implementation of built-in window function rank(). Assumes that
 ** the window frame has been set to:
 **
-**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW 
+**   RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
 */
 static void rankStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147293,7 +152348,7 @@ static void rankValueFunc(sqlite3_context *pCtx){
 **   GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
 */
 static void percent_rankStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147306,7 +152361,7 @@ static void percent_rankStepFunc(
   }
 }
 static void percent_rankInvFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147338,7 +152393,7 @@ static void percent_rankValueFunc(sqlite3_context *pCtx){
 **   GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
 */
 static void cume_distStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147351,7 +152406,7 @@ static void cume_distStepFunc(
   }
 }
 static void cume_distInvFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147387,7 +152442,7 @@ struct NtileCtx {
 **   ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
 */
 static void ntileStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147407,7 +152462,7 @@ static void ntileStepFunc(
   }
 }
 static void ntileInvFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147453,7 +152508,7 @@ struct LastValueCtx {
 ** Implementation of last_value().
 */
 static void last_valueStepFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147471,7 +152526,7 @@ static void last_valueStepFunc(
   }
 }
 static void last_valueInvFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nArg,
   sqlite3_value **apArg
 ){
@@ -147624,7 +152679,7 @@ static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
 **     of this file), pWin is updated here.
 */
 SQLITE_PRIVATE void sqlite3WindowUpdate(
-  Parse *pParse, 
+  Parse *pParse,
   Window *pList,                  /* List of named windows for this SELECT */
   Window *pWin,                   /* Window frame to update */
   FuncDef *pFunc                  /* Window function definition */
@@ -147644,17 +152699,17 @@ SQLITE_PRIVATE void sqlite3WindowUpdate(
     sqlite3WindowChain(pParse, pWin, pList);
   }
   if( (pWin->eFrmType==TK_RANGE)
-   && (pWin->pStart || pWin->pEnd) 
+   && (pWin->pStart || pWin->pEnd)
    && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
   ){
-    sqlite3ErrorMsg(pParse, 
+    sqlite3ErrorMsg(pParse,
       "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
     );
   }else
   if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
     sqlite3 *db = pParse->db;
     if( pWin->pFilter ){
-      sqlite3ErrorMsg(pParse, 
+      sqlite3ErrorMsg(pParse,
           "FILTER clause may only be used with aggregate window functions"
       );
     }else{
@@ -147664,14 +152719,14 @@ SQLITE_PRIVATE void sqlite3WindowUpdate(
         int eStart;
         int eEnd;
       } aUp[] = {
-        { row_numberName,   TK_ROWS,   TK_UNBOUNDED, TK_CURRENT }, 
-        { dense_rankName,   TK_RANGE,  TK_UNBOUNDED, TK_CURRENT }, 
-        { rankName,         TK_RANGE,  TK_UNBOUNDED, TK_CURRENT }, 
-        { percent_rankName, TK_GROUPS, TK_CURRENT,   TK_UNBOUNDED }, 
-        { cume_distName,    TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED }, 
-        { ntileName,        TK_ROWS,   TK_CURRENT,   TK_UNBOUNDED }, 
-        { leadName,         TK_ROWS,   TK_UNBOUNDED, TK_UNBOUNDED }, 
-        { lagName,          TK_ROWS,   TK_UNBOUNDED, TK_CURRENT }, 
+        { row_numberName,   TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
+        { dense_rankName,   TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
+        { rankName,         TK_RANGE,  TK_UNBOUNDED, TK_CURRENT },
+        { percent_rankName, TK_GROUPS, TK_CURRENT,   TK_UNBOUNDED },
+        { cume_distName,    TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
+        { ntileName,        TK_ROWS,   TK_CURRENT,   TK_UNBOUNDED },
+        { leadName,         TK_ROWS,   TK_UNBOUNDED, TK_UNBOUNDED },
+        { lagName,          TK_ROWS,   TK_UNBOUNDED, TK_CURRENT },
       };
       int i;
       for(i=0; i<ArraySize(aUp); i++){
@@ -147709,7 +152764,7 @@ struct WindowRewrite {
 
 /*
 ** Callback function used by selectWindowRewriteEList(). If necessary,
-** this function appends to the output expression-list and updates 
+** this function appends to the output expression-list and updates
 ** expression (*ppExpr) in place.
 */
 static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
@@ -147750,13 +152805,27 @@ static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
           }
         }
       }
-      /* Fall through.  */
+      /* no break */ deliberate_fall_through
 
     case TK_AGG_FUNCTION:
     case TK_COLUMN: {
-      Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
-      p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
+      int iCol = -1;
       if( p->pSub ){
+        int i;
+        for(i=0; i<p->pSub->nExpr; i++){
+          if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
+            iCol = i;
+            break;
+          }
+        }
+      }
+      if( iCol<0 ){
+        Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
+        if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
+        p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
+      }
+      if( p->pSub ){
+        int f = pExpr->flags & EP_Collate;
         assert( ExprHasProperty(pExpr, EP_Static)==0 );
         ExprSetProperty(pExpr, EP_Static);
         sqlite3ExprDelete(pParse->db, pExpr);
@@ -147764,11 +152833,12 @@ static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
         memset(pExpr, 0, sizeof(Expr));
 
         pExpr->op = TK_COLUMN;
-        pExpr->iColumn = p->pSub->nExpr-1;
+        pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
         pExpr->iTable = p->pWin->iEphCsr;
         pExpr->y.pTab = p->pTab;
+        pExpr->flags = f;
       }
-
+      if( pParse->db->mallocFailed ) return WRC_Abort;
       break;
     }
 
@@ -147797,16 +152867,16 @@ static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
 **
 **   * TK_COLUMN,
 **   * aggregate function, or
-**   * window function with a Window object that is not a member of the 
+**   * window function with a Window object that is not a member of the
 **     Window list passed as the second argument (pWin).
 **
 ** Append the node to output expression-list (*ppSub). And replace it
-** with a TK_COLUMN that reads the (N-1)th element of table 
+** with a TK_COLUMN that reads the (N-1)th element of table
 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
 ** appending the new one.
 */
 static void selectWindowRewriteEList(
-  Parse *pParse, 
+  Parse *pParse,
   Window *pWin,
   SrcList *pSrc,
   ExprList *pEList,               /* Rewrite expressions in this list */
@@ -147850,9 +152920,18 @@ static ExprList *exprListAppendList(
     int nInit = pList ? pList->nExpr : 0;
     for(i=0; i<pAppend->nExpr; i++){
       Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
-      if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
-        pDup->op = TK_NULL;
-        pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
+      assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
+      if( bIntToNull && pDup ){
+        int iDummy;
+        Expr *pSub;
+        for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
+          assert( pSub );
+        }
+        if( sqlite3ExprIsInteger(pSub, &iDummy) ){
+          pSub->op = TK_NULL;
+          pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
+          pSub->u.zToken = 0;
+        }
       }
       pList = sqlite3ExprListAppend(pParse, pList, pDup);
       if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
@@ -147862,15 +152941,32 @@ static ExprList *exprListAppendList(
 }
 
 /*
+** When rewriting a query, if the new subquery in the FROM clause
+** contains TK_AGG_FUNCTION nodes that refer to an outer query,
+** then we have to increase the Expr->op2 values of those nodes
+** due to the extra subquery layer that was added.
+**
+** See also the incrAggDepth() routine in resolve.c
+*/
+static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
+  if( pExpr->op==TK_AGG_FUNCTION
+   && pExpr->op2>=pWalker->walkerDepth
+  ){
+    pExpr->op2++;
+  }
+  return WRC_Continue;
+}
+
+/*
 ** If the SELECT statement passed as the second argument does not invoke
-** any SQL window functions, this function is a no-op. Otherwise, it 
+** any SQL window functions, this function is a no-op. Otherwise, it
 ** rewrites the SELECT statement so that window function xStep functions
 ** are invoked in the correct order as described under "SELECT REWRITING"
 ** at the top of this file.
 */
 SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
   int rc = SQLITE_OK;
-  if( p->pWin && p->pPrior==0 ){
+  if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
     Vdbe *v = sqlite3GetVdbe(pParse);
     sqlite3 *db = pParse->db;
     Select *pSub = 0;             /* The subquery */
@@ -147881,25 +152977,31 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     ExprList *pSort = 0;
 
     ExprList *pSublist = 0;       /* Expression list for sub-query */
-    Window *pMWin = p->pWin;      /* Master window object */
+    Window *pMWin = p->pWin;      /* Main window object */
     Window *pWin;                 /* Window object iterator */
     Table *pTab;
+    Walker w;
+
+    u32 selFlags = p->selFlags;
 
     pTab = sqlite3DbMallocZero(db, sizeof(Table));
     if( pTab==0 ){
-      return SQLITE_NOMEM;
+      return sqlite3ErrorToParser(db, SQLITE_NOMEM);
     }
+    sqlite3AggInfoPersistWalkerInit(&w, pParse);
+    sqlite3WalkSelect(&w, p);
 
     p->pSrc = 0;
     p->pWhere = 0;
     p->pGroupBy = 0;
     p->pHaving = 0;
     p->selFlags &= ~SF_Aggregate;
+    p->selFlags |= SF_WinRewrite;
 
     /* Create the ORDER BY clause for the sub-select. This is the concatenation
     ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
     ** redundant, remove the ORDER BY from the parent SELECT.  */
-    pSort = sqlite3ExprListDup(db, pMWin->pPartition, 0);
+    pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
     pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
     if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
       int nSave = pSort->nExpr;
@@ -147921,8 +153023,8 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
     pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
 
-    /* Append the PARTITION BY and ORDER BY expressions to the to the 
-    ** sub-select expression list. They are required to figure out where 
+    /* Append the PARTITION BY and ORDER BY expressions to the to the
+    ** sub-select expression list. They are required to figure out where
     ** boundaries for partitions and sets of peer rows lie.  */
     pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
     pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
@@ -147953,11 +153055,11 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     /* If there is no ORDER BY or PARTITION BY clause, and the window
     ** function accepts zero arguments, and there are no other columns
     ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
-    ** that pSublist is still NULL here. Add a constant expression here to 
-    ** keep everything legal in this case. 
+    ** that pSublist is still NULL here. Add a constant expression here to
+    ** keep everything legal in this case.
     */
     if( pSublist==0 ){
-      pSublist = sqlite3ExprListAppend(pParse, 0, 
+      pSublist = sqlite3ExprListAppend(pParse, 0,
         sqlite3Expr(db, TK_INTEGER, "0")
       );
     }
@@ -147965,6 +153067,9 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     pSub = sqlite3SelectNew(
         pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
     );
+    SELECTTRACE(1,pParse,pSub,
+       ("New window-function subquery in FROM clause of (%u/%p)\n",
+       p->selId, p));
     p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
     if( p->pSrc ){
       Table *pTab2;
@@ -147972,18 +153077,23 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
       sqlite3SrcListAssignCursors(pParse, p->pSrc);
       pSub->selFlags |= SF_Expanded;
       pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
+      pSub->selFlags |= (selFlags & SF_Aggregate);
       if( pTab2==0 ){
+        /* Might actually be some other kind of error, but in that case
+        ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
+        ** the correct error message regardless. */
         rc = SQLITE_NOMEM;
       }else{
         memcpy(pTab, pTab2, sizeof(Table));
         pTab->tabFlags |= TF_Ephemeral;
         p->pSrc->a[0].pTab = pTab;
         pTab = pTab2;
+        memset(&w, 0, sizeof(w));
+        w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
+        w.xSelectCallback = sqlite3WalkerDepthIncrease;
+        w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
+        sqlite3WalkSelect(&w, pSub);
       }
-      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, pSublist->nExpr);
-      sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
-      sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
-      sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
     }else{
       sqlite3SelectDelete(db, pSub);
     }
@@ -147991,6 +153101,12 @@ SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
     sqlite3DbFree(db, pTab);
   }
 
+  if( rc ){
+    if( pParse->nErr==0 ){
+      assert( pParse->db->mallocFailed );
+      sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
+    }
+  }
   return rc;
 }
 
@@ -148126,10 +153242,10 @@ windowAllocErr:
 ** equivalent nul-terminated string.
 */
 SQLITE_PRIVATE Window *sqlite3WindowAssemble(
-  Parse *pParse, 
-  Window *pWin, 
-  ExprList *pPartition, 
-  ExprList *pOrderBy, 
+  Parse *pParse,
+  Window *pWin,
+  ExprList *pPartition,
+  ExprList *pOrderBy,
   Token *pBase
 ){
   if( pWin ){
@@ -148167,7 +153283,7 @@ SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pLis
         zErr = "frame specification";
       }
       if( zErr ){
-        sqlite3ErrorMsg(pParse, 
+        sqlite3ErrorMsg(pParse,
             "cannot override %s of window: %s", zErr, pWin->zBase
         );
       }else{
@@ -148210,8 +153326,8 @@ SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
 ** SELECT, or (b) the windows already linked use a compatible window frame.
 */
 SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
-  if( 0==pSel->pWin 
-   || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0)
+  if( pSel!=0
+   && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
   ){
     pWin->pNextWin = pSel->pWin;
     if( pSel->pWin ){
@@ -148223,20 +153339,29 @@ SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
 }
 
 /*
-** Return 0 if the two window objects are identical, or non-zero otherwise.
-** Identical window objects can be processed in a single scan.
+** Return 0 if the two window objects are identical, 1 if they are
+** different, or 2 if it cannot be determined if the objects are identical
+** or not. Identical window objects can be processed in a single scan.
 */
 SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
+  int res;
+  if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
   if( p1->eFrmType!=p2->eFrmType ) return 1;
   if( p1->eStart!=p2->eStart ) return 1;
   if( p1->eEnd!=p2->eEnd ) return 1;
   if( p1->eExclude!=p2->eExclude ) return 1;
   if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
   if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
-  if( sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1) ) return 1;
-  if( sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1) ) return 1;
+  if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
+    return res;
+  }
+  if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
+    return res;
+  }
   if( bFilter ){
-    if( sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1) ) return 1;
+    if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
+      return res;
+    }
   }
   return 0;
 }
@@ -148247,10 +153372,17 @@ SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, i
 ** to begin iterating through the sub-query results. It is used to allocate
 ** and initialize registers and cursors used by sqlite3WindowCodeStep().
 */
-SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Window *pMWin){
+SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
+  int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
+  Window *pMWin = pSelect->pWin;
   Window *pWin;
   Vdbe *v = sqlite3GetVdbe(pParse);
 
+  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
+  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
+  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
+  sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
+
   /* Allocate registers to use for PARTITION BY values, if any. Initialize
   ** said registers to NULL.  */
   if( pMWin->pPartition ){
@@ -148387,7 +153519,7 @@ struct WindowCsrAndReg {
 };
 
 /*
-** A single instance of this structure is allocated on the stack by 
+** A single instance of this structure is allocated on the stack by
 ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
 ** routines. This is to reduce the number of arguments required by each
 ** helper function.
@@ -148434,7 +153566,7 @@ struct WindowCsrAndReg {
 **
 **   Each cursor (start, current and end) consists of a VDBE cursor
 **   (WindowCsrAndReg.csr) and an array of registers (starting at
-**   WindowCodeArg.reg) that always contains a copy of the peer values 
+**   WindowCodeArg.reg) that always contains a copy of the peer values
 **   read from the corresponding cursor.
 **
 **   Depending on the window-frame in question, all three cursors may not
@@ -148478,8 +153610,8 @@ static void windowReadPeerValues(
 }
 
 /*
-** Generate VM code to invoke either xStep() (if bInverse is 0) or 
-** xInverse (if bInverse is non-zero) for each window function in the 
+** Generate VM code to invoke either xStep() (if bInverse is 0) or
+** xInverse (if bInverse is non-zero) for each window function in the
 ** linked list starting at pMWin. Or, for built-in window functions
 ** that do not use the standard function API, generate the required
 ** inline VM code.
@@ -148516,7 +153648,7 @@ static void windowAggStep(
 
     /* All OVER clauses in the same window function aggregate step must
     ** be the same. */
-    assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)==0 );
+    assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
 
     for(i=0; i<nArg; i++){
       if( i!=1 || pFunc->zName!=nth_valueName ){
@@ -148528,7 +153660,7 @@ static void windowAggStep(
     regArg = reg;
 
     if( pMWin->regStartRowid==0
-     && (pFunc->funcFlags & SQLITE_FUNC_MINMAX) 
+     && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
      && (pWin->eStart!=TK_UNBOUNDED)
     ){
       int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
@@ -148563,7 +153695,7 @@ static void windowAggStep(
         VdbeCoverage(v);
         sqlite3ReleaseTempReg(pParse, regTmp);
       }
-      
+
       if( pWin->bExprArgs ){
         int iStart = sqlite3VdbeCurrentAddr(v);
         VdbeOp *pOp, *pEnd;
@@ -148585,7 +153717,7 @@ static void windowAggStep(
         pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
         sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
       }
-      sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep, 
+      sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
                         bInverse, regArg, pWin->regAccum);
       sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
       sqlite3VdbeChangeP5(v, (u8)nArg);
@@ -148618,7 +153750,7 @@ static void windowAggFinal(WindowCodeArg *p, int bFin){
 
   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
     if( pMWin->regStartRowid==0
-     && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX) 
+     && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
      && (pWin->eStart!=TK_UNBOUNDED)
     ){
       sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
@@ -148774,7 +153906,7 @@ static void windowReturnOneRow(WindowCodeArg *p){
         int lbl = sqlite3VdbeMakeLabel(pParse);
         int tmpReg = sqlite3GetTempReg(pParse);
         sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
-  
+
         if( pFunc->zName==nth_valueName ){
           sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
           windowCheckValue(pParse, tmpReg, 2);
@@ -148796,7 +153928,7 @@ static void windowReturnOneRow(WindowCodeArg *p){
         int lbl = sqlite3VdbeMakeLabel(pParse);
         int tmpReg = sqlite3GetTempReg(pParse);
         int iEph = pMWin->iEphCsr;
-  
+
         if( nArg<3 ){
           sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
         }else{
@@ -148813,7 +153945,7 @@ static void windowReturnOneRow(WindowCodeArg *p){
           sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
           sqlite3ReleaseTempReg(pParse, tmpReg2);
         }
-  
+
         sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
         VdbeCoverage(v);
         sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
@@ -148838,6 +153970,7 @@ static int windowInitAccum(Parse *pParse, Window *pMWin){
   Window *pWin;
   for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
     FuncDef *pFunc = pWin->pFunc;
+    assert( pWin->regAccum );
     sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
     nArg = MAX(nArg, windowArgCount(pWin));
     if( pMWin->regStartRowid==0 ){
@@ -148858,7 +153991,7 @@ static int windowInitAccum(Parse *pParse, Window *pMWin){
   return regArg;
 }
 
-/* 
+/*
 ** Return true if the current frame should be cached in the ephemeral table,
 ** even if there are no xInverse() calls required.
 */
@@ -148882,9 +154015,9 @@ static int windowCacheFrame(Window *pMWin){
 ** regOld and regNew are each the first register in an array of size
 ** pOrderBy->nExpr. This function generates code to compare the two
 ** arrays of registers using the collation sequences and other comparison
-** parameters specified by pOrderBy. 
+** parameters specified by pOrderBy.
 **
-** If the two arrays are not equal, the contents of regNew is copied to 
+** If the two arrays are not equal, the contents of regNew is copied to
 ** regOld and control falls through. Otherwise, if the contents of the arrays
 ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
 */
@@ -148901,7 +154034,7 @@ static void windowIfNewPeer(
     KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
     sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
     sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
-    sqlite3VdbeAddOp3(v, OP_Jump, 
+    sqlite3VdbeAddOp3(v, OP_Jump,
       sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
     );
     VdbeCoverageEqNe(v);
@@ -148935,7 +154068,7 @@ static void windowIfNewPeer(
 ** or subtraction is a a copy of csr1.peerVal.
 */
 static void windowCodeRangeTest(
-  WindowCodeArg *p, 
+  WindowCodeArg *p,
   int op,                         /* OP_Ge, OP_Gt, or OP_Le */
   int csr1,                       /* Cursor number for cursor 1 */
   int regVal,                     /* Register containing non-negative number */
@@ -148990,8 +154123,8 @@ static void windowCodeRangeTest(
   sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
   sqlite3VdbeJumpHere(v, addrGe);
 
-  /* If the BIGNULL flag is set for the ORDER BY, then it is required to 
-  ** consider NULL values to be larger than all other values, instead of 
+  /* If the BIGNULL flag is set for the ORDER BY, then it is required to
+  ** consider NULL values to be larger than all other values, instead of
   ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
   ** (and adding that capability causes a performance regression), so
   ** instead if the BIGNULL flag is set then cases where either reg1 or
@@ -149006,23 +154139,23 @@ static void windowCodeRangeTest(
   **     if( op==OP_Le ) goto lbl;
   **   }
   **
-  ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is 
+  ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
   ** not taken, control jumps over the comparison operator coded below this
   ** block.  */
   if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
     /* This block runs if reg1 contains a NULL. */
     int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
     switch( op ){
-      case OP_Ge: 
-        sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl); 
+      case OP_Ge:
+        sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
         break;
-      case OP_Gt: 
-        sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl); 
-        VdbeCoverage(v); 
+      case OP_Gt:
+        sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
+        VdbeCoverage(v);
         break;
-      case OP_Le: 
-        sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); 
-        VdbeCoverage(v); 
+      case OP_Le:
+        sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
+        VdbeCoverage(v);
         break;
       default: assert( op==OP_Lt ); /* no-op */ break;
     }
@@ -149055,7 +154188,7 @@ static void windowCodeRangeTest(
 
 /*
 ** Helper function for sqlite3WindowCodeStep(). Each call to this function
-** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE 
+** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
 ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
 ** details.
 */
@@ -149114,8 +154247,8 @@ static int windowCodeOp(
   addrContinue = sqlite3VdbeCurrentAddr(v);
 
   /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
-  ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the 
-  ** start cursor does not advance past the end cursor within the 
+  ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
+  ** start cursor does not advance past the end cursor within the
   ** temporary table. It otherwise might, if (a>b).  */
   if( pMWin->eStart==pMWin->eEnd && regCountdown
    && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
@@ -149216,6 +154349,10 @@ SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
       pNew->eStart = p->eStart;
       pNew->eExclude = p->eExclude;
       pNew->regResult = p->regResult;
+      pNew->regAccum = p->regAccum;
+      pNew->iArgCol = p->iArgCol;
+      pNew->iEphCsr = p->iEphCsr;
+      pNew->bExprArgs = p->bExprArgs;
       pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
       pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
       pNew->pOwner = pOwner;
@@ -149244,11 +154381,11 @@ SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
 }
 
 /*
-** Return true if it can be determined at compile time that expression 
-** pExpr evaluates to a value that, when cast to an integer, is greater 
+** Return true if it can be determined at compile time that expression
+** pExpr evaluates to a value that, when cast to an integer, is greater
 ** than zero. False otherwise.
 **
-** If an OOM error occurs, this function sets the Parse.db.mallocFailed 
+** If an OOM error occurs, this function sets the Parse.db.mallocFailed
 ** flag and returns zero.
 */
 static int windowExprGtZero(Parse *pParse, Expr *pExpr){
@@ -149264,11 +154401,11 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){
 }
 
 /*
-** sqlite3WhereBegin() has already been called for the SELECT statement 
+** sqlite3WhereBegin() has already been called for the SELECT statement
 ** passed as the second argument when this function is invoked. It generates
-** code to populate the Window.regResult register for each window function 
+** code to populate the Window.regResult register for each window function
 ** and invoke the sub-routine at instruction addrGosub once for each row.
-** sqlite3WhereEnd() is always called before returning. 
+** sqlite3WhereEnd() is always called before returning.
 **
 ** This function handles several different types of window frames, which
 ** require slightly different processing. The following pseudo code is
@@ -149283,17 +154420,17 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){
 **         Gosub flush
 **       }
 **       Insert new row into eph table.
-**       
+**
 **       if( first row of partition ){
 **         // Rewind three cursors, all open on the eph table.
 **         Rewind(csrEnd);
 **         Rewind(csrStart);
 **         Rewind(csrCurrent);
-**       
+**
 **         regEnd = <expr2>          // FOLLOWING expression
 **         regStart = <expr1>        // PRECEDING expression
 **       }else{
-**         // First time this branch is taken, the eph table contains two 
+**         // First time this branch is taken, the eph table contains two
 **         // rows. The first row in the partition, which all three cursors
 **         // currently point to, and the following row.
 **         AGGSTEP
@@ -149322,17 +154459,17 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){
 **               with arguments read from the current row of cursor csrEnd, then
 **               step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
 **
-**   RETURN_ROW: return a row to the caller based on the contents of the 
-**               current row of csrCurrent and the current state of all 
+**   RETURN_ROW: return a row to the caller based on the contents of the
+**               current row of csrCurrent and the current state of all
 **               aggregates. Then step cursor csrCurrent forward one row.
 **
-**   AGGINVERSE: invoke the aggregate xInverse() function for each window 
+**   AGGINVERSE: invoke the aggregate xInverse() function for each window
 **               functions with arguments read from the current row of cursor
 **               csrStart. Then step csrStart forward one row.
 **
 ** There are two other ROWS window frames that are handled significantly
 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
-** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special 
+** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
 ** cases because they change the order in which the three cursors (csrStart,
 ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
 ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
@@ -149482,15 +154619,15 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){
 **           regEnd = <expr2>
 **           regStart = <expr1>
 **         }else if( new group ){
-**           ... 
+**           ...
 **         }
 **       }
 **
-**   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or 
+**   2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
 **      AGGINVERSE step processes the current row of the relevant cursor and
 **      all subsequent rows belonging to the same group.
 **
-** RANGE window frames are a little different again. As for GROUPS, the 
+** RANGE window frames are a little different again. As for GROUPS, the
 ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
 ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
 ** basic cases:
@@ -149527,7 +154664,7 @@ static int windowExprGtZero(Parse *pParse, Expr *pExpr){
 **         }
 **       }
 **
-** In the above notation, "csr.key" means the current value of the ORDER BY 
+** In the above notation, "csr.key" means the current value of the ORDER BY
 ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
 ** or <expr PRECEDING) read from cursor csr.
 **
@@ -149627,11 +154764,11 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   int regStart = 0;               /* Value of <expr> PRECEDING */
   int regEnd = 0;                 /* Value of <expr> FOLLOWING */
 
-  assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT 
-       || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED 
+  assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
+       || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
   );
-  assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT 
-       || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING 
+  assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
+       || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
   );
   assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
        || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
@@ -149653,9 +154790,9 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   s.end.csr = s.current.csr+3;
 
   /* Figure out when rows may be deleted from the ephemeral table. There
-  ** are four options - they may never be deleted (eDelete==0), they may 
+  ** are four options - they may never be deleted (eDelete==0), they may
   ** be deleted as soon as they are no longer part of the window frame
-  ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row 
+  ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
   ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
   ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
   switch( pMWin->eStart ){
@@ -149703,7 +154840,7 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   }
 
   /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
-  ** registers to store copies of the ORDER BY expressions (peer values) 
+  ** registers to store copies of the ORDER BY expressions (peer values)
   ** for the main loop, and for each cursor (start, current and end). */
   if( pMWin->eFrmType!=TK_ROWS ){
     int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
@@ -149724,7 +154861,7 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
   sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
 
   /* An input row has just been read into an array of registers starting
-  ** at regNew. If the window has a PARTITION clause, this block generates 
+  ** at regNew. If the window has a PARTITION clause, this block generates
   ** VM code to check if the input row is the start of a new partition.
   ** If so, it does an OP_Gosub to an address to be filled in later. The
   ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
@@ -149928,8 +155065,10 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
 
 /************** End of window.c **********************************************/
 /************** Begin file parse.c *******************************************/
+/* This file is automatically generated by Lemon from input grammar
+** source file "parse.y". */
 /*
-** 2000-05-29
+** 2001-09-15
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
@@ -149939,22 +155078,15 @@ SQLITE_PRIVATE void sqlite3WindowCodeStep(
 **    May you share freely, never taking more than you give.
 **
 *************************************************************************
-** Driver template for the LEMON parser generator.
-**
-** The "lemon" program processes an LALR(1) input grammar file, then uses
-** this template to construct a parser.  The "lemon" program inserts text
-** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
-** interstitial "-" characters) contained in this template is changed into
-** the value of the %name directive from the grammar.  Otherwise, the content
-** of this template is copied straight through into the generate parser
-** source file.
+** This file contains SQLite's SQL parser.
 **
-** The following is the concatenation of all %include directives from the
-** input grammar file:
+** The canonical source code to this file ("parse.y") is a Lemon grammar
+** file that specifies the input grammar and actions to take while parsing.
+** That input file is processed by Lemon to generate a C-language
+** implementation of a parser for the given grammer.  You might be reading
+** this comment as part of the translated C-code.  Edits should be made
+** to the original parse.y sources.
 */
-/* #include <stdio.h> */
-/* #include <assert.h> */
-/************ Begin %include sections from the grammar ************************/
 
 /* #include "sqliteInt.h" */
 
@@ -150012,8 +155144,9 @@ struct FrameBound     { int eType; Expr *pExpr; };
 ** shared across database connections.
 */
 static void disableLookaside(Parse *pParse){
+  sqlite3 *db = pParse->db;
   pParse->disableLookaside++;
-  pParse->db->lookaside.bDisable++;
+  DisableLookaside;
 }
 
 
@@ -150031,7 +155164,7 @@ static void disableLookaside(Parse *pParse){
         pLoop->pNext = pNext;
         pLoop->selFlags |= SF_Compound;
       }
-      if( (p->selFlags & SF_MultiValue)==0 && 
+      if( (p->selFlags & SF_MultiValue)==0 &&
         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
         cnt>mxSelect
       ){
@@ -150052,6 +155185,7 @@ static void disableLookaside(Parse *pParse){
       p->op = (u8)op;
       p->affExpr = 0;
       p->flags = EP_Leaf;
+      ExprClearVVAProperties(p);
       p->iAgg = -1;
       p->pLeft = p->pRight = 0;
       p->x.pList = 0;
@@ -150068,7 +155202,7 @@ static void disableLookaside(Parse *pParse){
       }
 #if SQLITE_MAX_EXPR_DEPTH>0
       p->nHeight = 1;
-#endif  
+#endif
       if( IN_RENAME_OBJECT ){
         return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
       }
@@ -150115,11 +155249,191 @@ static void disableLookaside(Parse *pParse){
 # error too many tokens in the grammar
 #endif
 /**************** End of %include directives **********************************/
-/* These constants specify the various numeric values for terminal symbols
-** in a format understandable to "makeheaders".  This section is blank unless
-** "lemon" is run with the "-m" command-line option.
-***************** Begin makeheaders token definitions *************************/
-/**************** End makeheaders token definitions ***************************/
+/* These constants specify the various numeric values for terminal symbols.
+***************** Begin token definitions *************************************/
+#ifndef TK_SEMI
+#define TK_SEMI                            1
+#define TK_EXPLAIN                         2
+#define TK_QUERY                           3
+#define TK_PLAN                            4
+#define TK_BEGIN                           5
+#define TK_TRANSACTION                     6
+#define TK_DEFERRED                        7
+#define TK_IMMEDIATE                       8
+#define TK_EXCLUSIVE                       9
+#define TK_COMMIT                         10
+#define TK_END                            11
+#define TK_ROLLBACK                       12
+#define TK_SAVEPOINT                      13
+#define TK_RELEASE                        14
+#define TK_TO                             15
+#define TK_TABLE                          16
+#define TK_CREATE                         17
+#define TK_IF                             18
+#define TK_NOT                            19
+#define TK_EXISTS                         20
+#define TK_TEMP                           21
+#define TK_LP                             22
+#define TK_RP                             23
+#define TK_AS                             24
+#define TK_WITHOUT                        25
+#define TK_COMMA                          26
+#define TK_ABORT                          27
+#define TK_ACTION                         28
+#define TK_AFTER                          29
+#define TK_ANALYZE                        30
+#define TK_ASC                            31
+#define TK_ATTACH                         32
+#define TK_BEFORE                         33
+#define TK_BY                             34
+#define TK_CASCADE                        35
+#define TK_CAST                           36
+#define TK_CONFLICT                       37
+#define TK_DATABASE                       38
+#define TK_DESC                           39
+#define TK_DETACH                         40
+#define TK_EACH                           41
+#define TK_FAIL                           42
+#define TK_OR                             43
+#define TK_AND                            44
+#define TK_IS                             45
+#define TK_MATCH                          46
+#define TK_LIKE_KW                        47
+#define TK_BETWEEN                        48
+#define TK_IN                             49
+#define TK_ISNULL                         50
+#define TK_NOTNULL                        51
+#define TK_NE                             52
+#define TK_EQ                             53
+#define TK_GT                             54
+#define TK_LE                             55
+#define TK_LT                             56
+#define TK_GE                             57
+#define TK_ESCAPE                         58
+#define TK_ID                             59
+#define TK_COLUMNKW                       60
+#define TK_DO                             61
+#define TK_FOR                            62
+#define TK_IGNORE                         63
+#define TK_INITIALLY                      64
+#define TK_INSTEAD                        65
+#define TK_NO                             66
+#define TK_KEY                            67
+#define TK_OF                             68
+#define TK_OFFSET                         69
+#define TK_PRAGMA                         70
+#define TK_RAISE                          71
+#define TK_RECURSIVE                      72
+#define TK_REPLACE                        73
+#define TK_RESTRICT                       74
+#define TK_ROW                            75
+#define TK_ROWS                           76
+#define TK_TRIGGER                        77
+#define TK_VACUUM                         78
+#define TK_VIEW                           79
+#define TK_VIRTUAL                        80
+#define TK_WITH                           81
+#define TK_NULLS                          82
+#define TK_FIRST                          83
+#define TK_LAST                           84
+#define TK_CURRENT                        85
+#define TK_FOLLOWING                      86
+#define TK_PARTITION                      87
+#define TK_PRECEDING                      88
+#define TK_RANGE                          89
+#define TK_UNBOUNDED                      90
+#define TK_EXCLUDE                        91
+#define TK_GROUPS                         92
+#define TK_OTHERS                         93
+#define TK_TIES                           94
+#define TK_GENERATED                      95
+#define TK_ALWAYS                         96
+#define TK_REINDEX                        97
+#define TK_RENAME                         98
+#define TK_CTIME_KW                       99
+#define TK_ANY                            100
+#define TK_BITAND                         101
+#define TK_BITOR                          102
+#define TK_LSHIFT                         103
+#define TK_RSHIFT                         104
+#define TK_PLUS                           105
+#define TK_MINUS                          106
+#define TK_STAR                           107
+#define TK_SLASH                          108
+#define TK_REM                            109
+#define TK_CONCAT                         110
+#define TK_COLLATE                        111
+#define TK_BITNOT                         112
+#define TK_ON                             113
+#define TK_INDEXED                        114
+#define TK_STRING                         115
+#define TK_JOIN_KW                        116
+#define TK_CONSTRAINT                     117
+#define TK_DEFAULT                        118
+#define TK_NULL                           119
+#define TK_PRIMARY                        120
+#define TK_UNIQUE                         121
+#define TK_CHECK                          122
+#define TK_REFERENCES                     123
+#define TK_AUTOINCR                       124
+#define TK_INSERT                         125
+#define TK_DELETE                         126
+#define TK_UPDATE                         127
+#define TK_SET                            128
+#define TK_DEFERRABLE                     129
+#define TK_FOREIGN                        130
+#define TK_DROP                           131
+#define TK_UNION                          132
+#define TK_ALL                            133
+#define TK_EXCEPT                         134
+#define TK_INTERSECT                      135
+#define TK_SELECT                         136
+#define TK_VALUES                         137
+#define TK_DISTINCT                       138
+#define TK_DOT                            139
+#define TK_FROM                           140
+#define TK_JOIN                           141
+#define TK_USING                          142
+#define TK_ORDER                          143
+#define TK_GROUP                          144
+#define TK_HAVING                         145
+#define TK_LIMIT                          146
+#define TK_WHERE                          147
+#define TK_INTO                           148
+#define TK_NOTHING                        149
+#define TK_FLOAT                          150
+#define TK_BLOB                           151
+#define TK_INTEGER                        152
+#define TK_VARIABLE                       153
+#define TK_CASE                           154
+#define TK_WHEN                           155
+#define TK_THEN                           156
+#define TK_ELSE                           157
+#define TK_INDEX                          158
+#define TK_ALTER                          159
+#define TK_ADD                            160
+#define TK_WINDOW                         161
+#define TK_OVER                           162
+#define TK_FILTER                         163
+#define TK_COLUMN                         164
+#define TK_AGG_FUNCTION                   165
+#define TK_AGG_COLUMN                     166
+#define TK_TRUEFALSE                      167
+#define TK_ISNOT                          168
+#define TK_FUNCTION                       169
+#define TK_UMINUS                         170
+#define TK_UPLUS                          171
+#define TK_TRUTH                          172
+#define TK_REGISTER                       173
+#define TK_VECTOR                         174
+#define TK_SELECT_COLUMN                  175
+#define TK_IF_NULL_ROW                    176
+#define TK_ASTERISK                       177
+#define TK_SPAN                           178
+#define TK_SPACE                          179
+#define TK_ILLEGAL                        180
+#endif
+/**************** End token definitions ***************************************/
 
 /* The next sections is a series of control #defines.
 ** various aspects of the generated parser.
@@ -150144,7 +155458,7 @@ static void disableLookaside(Parse *pParse){
 **                       the minor type might be the name of the identifier.
 **                       Each non-terminal can have a different minor type.
 **                       Terminal symbols all have the same minor type, though.
-**                       This macros defines the minor type for terminal 
+**                       This macros defines the minor type for terminal
 **                       symbols.
 **    YYMINORTYPE        is the data type used for all minor types.
 **                       This is typically a union of many types, one of
@@ -150177,28 +155491,28 @@ static void disableLookaside(Parse *pParse){
 #endif
 /************* Begin control #defines *****************************************/
 #define YYCODETYPE unsigned short int
-#define YYNOCODE 307
+#define YYNOCODE 310
 #define YYACTIONTYPE unsigned short int
-#define YYWILDCARD 98
+#define YYWILDCARD 100
 #define sqlite3ParserTOKENTYPE Token
 typedef union {
   int yyinit;
   sqlite3ParserTOKENTYPE yy0;
-  const char* yy8;
-  Select* yy25;
-  int yy32;
-  Expr* yy46;
-  struct FrameBound yy57;
-  u8 yy118;
-  ExprList* yy138;
-  Upsert* yy288;
-  With* yy297;
-  IdList* yy406;
-  Window* yy455;
-  struct {int value; int mask;} yy495;
-  TriggerStep* yy527;
-  struct TrigEvent yy572;
-  SrcList* yy609;
+  SrcList* yy47;
+  u8 yy58;
+  struct FrameBound yy77;
+  With* yy131;
+  int yy192;
+  Expr* yy202;
+  struct {int value; int mask;} yy207;
+  struct TrigEvent yy230;
+  ExprList* yy242;
+  Window* yy303;
+  Upsert* yy318;
+  const char* yy436;
+  TriggerStep* yy447;
+  Select* yy539;
+  IdList* yy600;
 } YYMINORTYPE;
 #ifndef YYSTACKDEPTH
 #define YYSTACKDEPTH 100
@@ -150214,17 +155528,18 @@ typedef union {
 #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
 #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
 #define YYFALLBACK 1
-#define YYNSTATE             547
-#define YYNRULE              381
-#define YYNTOKEN             179
-#define YY_MAX_SHIFT         546
-#define YY_MIN_SHIFTREDUCE   794
-#define YY_MAX_SHIFTREDUCE   1174
-#define YY_ERROR_ACTION      1175
-#define YY_ACCEPT_ACTION     1176
-#define YY_NO_ACTION         1177
-#define YY_MIN_REDUCE        1178
-#define YY_MAX_REDUCE        1558
+#define YYNSTATE             557
+#define YYNRULE              385
+#define YYNRULE_WITH_ACTION  325
+#define YYNTOKEN             181
+#define YY_MAX_SHIFT         556
+#define YY_MIN_SHIFTREDUCE   807
+#define YY_MAX_SHIFTREDUCE   1191
+#define YY_ERROR_ACTION      1192
+#define YY_ACCEPT_ACTION     1193
+#define YY_NO_ACTION         1194
+#define YY_MIN_REDUCE        1195
+#define YY_MAX_REDUCE        1579
 /************* End control #defines *******************************************/
 #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
 
@@ -150244,7 +155559,7 @@ typedef union {
 /* Next are the tables used to determine what action to take based on the
 ** current state and lookahead token.  These tables are used to implement
 ** functions that take a state number and lookahead value and return an
-** action integer.  
+** action integer.
 **
 ** Suppose the action integer is N.  Then the action is determined as
 ** follows
@@ -150291,579 +155606,594 @@ typedef union {
 **  yy_default[]       Default action for each state.
 **
 *********** Begin parsing tables **********************************************/
-#define YY_ACTTAB_COUNT (1918)
+#define YY_ACTTAB_COUNT (1974)
 static const YYACTIONTYPE yy_action[] = {
- /*     0 */   541,  343,  541, 1245, 1224,  541,   12,  541,  112,  109,
- /*    10 */   209,  541, 1245,  541, 1209,  466,  112,  109,  209,  390,
- /*    20 */   342,  466,   42,   42,   42,   42,  449,   42,   42,   70,
- /*    30 */    70,  926, 1212,   70,   70,   70,   70, 1447,  407,  927,
- /*    40 */   535,  535,  535,  119,  120,  110, 1152, 1152,  995,  998,
- /*    50 */   988,  988,  117,  117,  118,  118,  118,  118,  429,  390,
- /*    60 */  1502,  546,    2, 1180, 1446,  523,  141, 1522,  289,  523,
- /*    70 */   134,  523,   95,  259,  499, 1219,  189, 1258,  522,  498,
- /*    80 */   488,  441,  296,  119,  120,  110, 1152, 1152,  995,  998,
- /*    90 */   988,  988,  117,  117,  118,  118,  118,  118,  270,  116,
- /*   100 */   116,  116,  116,  115,  115,  114,  114,  114,  113,  422,
- /*   110 */   264,  264,  264,  264,  427, 1483,  356, 1485,  123,  355,
- /*   120 */  1483,  512, 1098,  538, 1038,  538, 1103,  390, 1103,  239,
- /*   130 */   206,  112,  109,  209,   96, 1098,  380,  219, 1098,  116,
- /*   140 */   116,  116,  116,  115,  115,  114,  114,  114,  113,  422,
- /*   150 */   484,  119,  120,  110, 1152, 1152,  995,  998,  988,  988,
- /*   160 */   117,  117,  118,  118,  118,  118,  357,  426, 1411,  264,
- /*   170 */   264,  114,  114,  114,  113,  422,  887,  121,  420,  420,
- /*   180 */   420,  886,  538,  116,  116,  116,  116,  115,  115,  114,
- /*   190 */   114,  114,  113,  422,  212,  419,  418,  390,  447,  387,
- /*   200 */   386,  118,  118,  118,  118,  111,  177,  116,  116,  116,
- /*   210 */   116,  115,  115,  114,  114,  114,  113,  422,  112,  109,
- /*   220 */   209,  119,  120,  110, 1152, 1152,  995,  998,  988,  988,
- /*   230 */   117,  117,  118,  118,  118,  118,  390,  442,  316, 1167,
- /*   240 */  1159,   80, 1159, 1131,  518,   79,  116,  116,  116,  116,
- /*   250 */   115,  115,  114,  114,  114,  113,  422,  518,  432,  422,
- /*   260 */   119,  120,  110, 1152, 1152,  995,  998,  988,  988,  117,
- /*   270 */   117,  118,  118,  118,  118,  432,  431,  116,  116,  116,
- /*   280 */   116,  115,  115,  114,  114,  114,  113,  422,  115,  115,
- /*   290 */   114,  114,  114,  113,  422, 1131, 1131, 1132, 1133, 1098,
- /*   300 */   258,  258,  192,  390,  412,  375, 1172,  330,  118,  118,
- /*   310 */   118,  118, 1098,  538,  378, 1098,  116,  116,  116,  116,
- /*   320 */   115,  115,  114,  114,  114,  113,  422,  119,  120,  110,
- /*   330 */  1152, 1152,  995,  998,  988,  988,  117,  117,  118,  118,
- /*   340 */   118,  118,  390,  358,  449,  432,  833,  238, 1131, 1132,
- /*   350 */  1133,  519, 1470,  116,  116,  116,  116,  115,  115,  114,
- /*   360 */   114,  114,  113,  422, 1131, 1471,  119,  120,  110, 1152,
- /*   370 */  1152,  995,  998,  988,  988,  117,  117,  118,  118,  118,
- /*   380 */   118, 1173,   82,  116,  116,  116,  116,  115,  115,  114,
- /*   390 */   114,  114,  113,  422,  409,  112,  109,  209,  161,  449,
- /*   400 */   250,  267,  340,  482,  335,  481,  236,  955, 1131,  390,
- /*   410 */   892, 1525,  333,  826,  856,  162,  274, 1131, 1132, 1133,
- /*   420 */   342,  169,  116,  116,  116,  116,  115,  115,  114,  114,
- /*   430 */   114,  113,  422,  119,  120,  110, 1152, 1152,  995,  998,
- /*   440 */   988,  988,  117,  117,  118,  118,  118,  118,  390,  442,
- /*   450 */   316, 1506, 1116, 1180,  161,  288,  532,  315,  289,  887,
- /*   460 */   134, 1131, 1132, 1133,  886,  541,  143, 1258,  288,  532,
- /*   470 */   297,  275,  119,  120,  110, 1152, 1152,  995,  998,  988,
- /*   480 */   988,  117,  117,  118,  118,  118,  118,   70,   70,  116,
- /*   490 */   116,  116,  116,  115,  115,  114,  114,  114,  113,  422,
- /*   500 */   264,  264,   12,  264,  264,  399, 1131,  487, 1477, 1098,
- /*   510 */   204,  486,    6,  538, 1262,  390,  538, 1478,  829,  976,
- /*   520 */   508,    6, 1098,  504,   95, 1098,  538,  219,  116,  116,
- /*   530 */   116,  116,  115,  115,  114,  114,  114,  113,  422,  119,
- /*   540 */   120,  110, 1152, 1152,  995,  998,  988,  988,  117,  117,
- /*   550 */   118,  118,  118,  118,  390, 1343,  975,  426,  960, 1131,
- /*   560 */  1132, 1133,  231,  516, 1477,  479,  476,  475,    6,  113,
- /*   570 */   422,  829,  966,  298,  507,  474,  965,  456,  119,  120,
- /*   580 */   110, 1152, 1152,  995,  998,  988,  988,  117,  117,  118,
- /*   590 */   118,  118,  118,  399,  541,  116,  116,  116,  116,  115,
- /*   600 */   115,  114,  114,  114,  113,  422,  202,  965,  965,  967,
- /*   610 */   231,  975, 1131,  479,  476,  475,   13,   13,  955, 1131,
- /*   620 */   838,  390, 1211,  474,  403,  183,  451,  966,  466,  162,
- /*   630 */   401,  965, 1250, 1250,  116,  116,  116,  116,  115,  115,
- /*   640 */   114,  114,  114,  113,  422,  119,  120,  110, 1152, 1152,
- /*   650 */   995,  998,  988,  988,  117,  117,  118,  118,  118,  118,
- /*   660 */   390,  271,  965,  965,  967, 1131, 1132, 1133,  315,  437,
- /*   670 */   301, 1410, 1131, 1132, 1133,  178, 1475,  138,  162,   32,
- /*   680 */     6, 1131,  288,  532,  119,  120,  110, 1152, 1152,  995,
- /*   690 */   998,  988,  988,  117,  117,  118,  118,  118,  118,  913,
- /*   700 */   394,  116,  116,  116,  116,  115,  115,  114,  114,  114,
- /*   710 */   113,  422, 1131,  433,  821,  541, 1131,  265,  265,  985,
- /*   720 */   985,  996,  999,  328, 1059,   93,  524,    5,  342,  541,
- /*   730 */   538,  288,  532, 1526, 1131, 1132, 1133,   70,   70, 1060,
- /*   740 */   116,  116,  116,  116,  115,  115,  114,  114,  114,  113,
- /*   750 */   422,   70,   70, 1499, 1061,  541,   98, 1248, 1248,  264,
- /*   760 */   264,  912,  375, 1080, 1131, 1131, 1132, 1133,  821, 1131,
- /*   770 */  1132, 1133,  538,  523,  140,  867,  390,   13,   13,  460,
- /*   780 */   192,  193,  525,  457,  323,  868,  326,  284,  369,  434,
- /*   790 */   989,  406,  383, 1081, 1552,  101,  390, 1552,    3,  399,
- /*   800 */   119,  120,  110, 1152, 1152,  995,  998,  988,  988,  117,
- /*   810 */   117,  118,  118,  118,  118,  390,  455, 1131, 1132, 1133,
- /*   820 */   119,  120,  110, 1152, 1152,  995,  998,  988,  988,  117,
- /*   830 */   117,  118,  118,  118,  118, 1131, 1358, 1416, 1173,  119,
- /*   840 */   108,  110, 1152, 1152,  995,  998,  988,  988,  117,  117,
- /*   850 */   118,  118,  118,  118, 1416, 1418,  116,  116,  116,  116,
- /*   860 */   115,  115,  114,  114,  114,  113,  422,  272,  539, 1079,
- /*   870 */   881,  881,  341, 1496,  313,  466,  116,  116,  116,  116,
- /*   880 */   115,  115,  114,  114,  114,  113,  422,  541, 1131, 1132,
- /*   890 */  1133,  541,  364,  541,  360,  116,  116,  116,  116,  115,
- /*   900 */   115,  114,  114,  114,  113,  422,  390,  264,  264,   13,
- /*   910 */    13,  273, 1131,   13,   13,   13,   13,  308, 1257,  390,
- /*   920 */   538, 1081, 1553,  408, 1416, 1553,  500,  277,  455,  186,
- /*   930 */  1256,  120,  110, 1152, 1152,  995,  998,  988,  988,  117,
- /*   940 */   117,  118,  118,  118,  118,  110, 1152, 1152,  995,  998,
- /*   950 */   988,  988,  117,  117,  118,  118,  118,  118,  105,  533,
- /*   960 */   541,    4, 1343,  264,  264, 1131, 1132, 1133, 1043, 1043,
- /*   970 */   463,  799,  800,  801,  540,  536,  538,  242,  305,  811,
- /*   980 */   307,  466,   69,   69,  455, 1357,  116,  116,  116,  116,
- /*   990 */   115,  115,  114,  114,  114,  113,  422, 1079,  423,  116,
- /*  1000 */   116,  116,  116,  115,  115,  114,  114,  114,  113,  422,
- /*  1010 */   530,  541, 1150,  192,  354,  105,  533,  541,    4,  501,
- /*  1020 */   162,  341, 1496,  314, 1253,  389, 1554,  376,    9,  466,
- /*  1030 */   242,  404,  536,   13,   13,  503,  975,  847,  440,   70,
- /*  1040 */    70,  363,  103,  103,    8,  343,  278,  187,  278,  104,
- /*  1050 */  1131,  423,  543,  542, 1343,  423,  965,  306, 1343, 1176,
- /*  1060 */     1,    1,  546,    2, 1180, 1150, 1150,  530,  480,  289,
- /*  1070 */    30,  134,  321,  288,  532,  285,  848, 1018, 1258,  276,
- /*  1080 */  1476,  510,  414, 1198,    6,  207,  509,  965,  965,  967,
- /*  1090 */   968,   27,  453,  975,  419,  418,  234,  233,  232,  103,
- /*  1100 */   103,   31, 1156, 1131, 1132, 1133,  104, 1158,  423,  543,
- /*  1110 */   542,  264,  264,  965, 1403, 1157,  264,  264, 1474, 1150,
- /*  1120 */   541,  216,    6,  405,  538, 1201,  396,  462,  410,  538,
- /*  1130 */   541,  489,  362,  541,  261,  541, 1343,  911,  219, 1159,
- /*  1140 */   471, 1159,   50,   50,  965,  965,  967,  968,   27, 1501,
- /*  1150 */  1120,  425,   70,   70,  268,   70,   70,   13,   13,  373,
- /*  1160 */   373,  372,  253,  370,  264,  264,  808,  235,  426,  105,
- /*  1170 */   533,  520,    4,  287,  491,  514,  497,  538,  490,  213,
- /*  1180 */  1059,  294,  494,  388, 1131,  454,  536,  342,  417,  293,
- /*  1190 */   526,  421,  339, 1040,  513, 1060,  107, 1040,   16,   16,
- /*  1200 */  1473, 1098,  338, 1109,    6,  415, 1149,  264,  264,  423,
- /*  1210 */  1061,  102,  515,  100, 1098,  264,  264, 1098,  926,  215,
- /*  1220 */   538,  530,  911,  264,  264,  208,  927,  154,  538,  461,
- /*  1230 */   156,  529,  395,  142,  218,  510,  538, 1131, 1132, 1133,
- /*  1240 */   511,  139, 1135,   38,  214,  534,  396,  975,  333, 1458,
- /*  1250 */   911, 1109,  541,  103,  103,  105,  533,  541,    4,  541,
- /*  1260 */   104,  428,  423,  543,  542,  541,  506,  965,  521,  541,
- /*  1270 */  1076,  541,  536,  377,   54,   54,  288,  532,  391,   55,
- /*  1280 */    55,   15,   15,  288,  532,   17,  136,   44,   44, 1455,
- /*  1290 */   541,   56,   56,   57,   57,  423, 1135,  291,  965,  965,
- /*  1300 */   967,  968,   27,  397,  163,  541,  430,  530,  263,  206,
- /*  1310 */   208,  521,   58,   58,  235,  444,  846,  845,  197,  105,
- /*  1320 */   533,  510,    4, 1037,  443, 1037,  509,   59,   59,  312,
- /*  1330 */   853,  854,   95,  975,  541,  911,  536,  952,  836,  103,
- /*  1340 */   103,  105,  533,  541,    4, 1025,  104,  541,  423,  543,
- /*  1350 */   542, 1120,  425,  965,  541,  268,   60,   60,  536,  423,
- /*  1360 */   373,  373,  372,  253,  370,   61,   61,  808,  969,   45,
- /*  1370 */    45,  530,  541, 1036, 1281, 1036,   46,   46,  541,  395,
- /*  1380 */   213,  423,  294,  266,  965,  965,  967,  968,   27,  292,
- /*  1390 */   293,  295,  836,  530,   48,   48, 1294,  975, 1293, 1025,
- /*  1400 */    49,   49,  436,  103,  103,  891,  957,  541, 1461,  241,
- /*  1410 */   104,  309,  423,  543,  542,  929,  930,  965,  448,  975,
- /*  1420 */   215,  241,  969, 1228,  541,  103,  103, 1435,  154,   62,
- /*  1430 */    62,  156,  104, 1434,  423,  543,  542,   97,  533,  965,
- /*  1440 */     4,  541,  458,  541,  318,  214,   63,   63,  965,  965,
- /*  1450 */   967,  968,   27,  541,  536,  450, 1290,  322,  241,  541,
- /*  1460 */   325,  327,  329,   64,   64,   14,   14, 1241,  541, 1227,
- /*  1470 */   965,  965,  967,  968,   27,   65,   65,  423,  541,  391,
- /*  1480 */   541,  125,  125,  541,  288,  532,  541, 1490,  541,  530,
- /*  1490 */    66,   66,  317,  528,  541,   95,  472, 1225, 1515,  237,
- /*  1500 */    51,   51,   67,   67,  334,   68,   68,  430,   52,   52,
- /*  1510 */   149,  149, 1226,  344,  345,  975,  150,  150, 1302,  467,
- /*  1520 */   331,  103,  103,   95,  541, 1342, 1277,  541,  104,  541,
- /*  1530 */   423,  543,  542, 1288,  541,  965,  268,  283,  527, 1348,
- /*  1540 */  1208,  373,  373,  372,  253,  370,   75,   75,  808,   53,
- /*  1550 */    53,   71,   71,  541, 1200,  541,  126,  126,  541, 1021,
- /*  1560 */   541,  213,  237,  294,  541, 1189,  965,  965,  967,  968,
- /*  1570 */    27,  293,  541, 1188,  541,   72,   72,  127,  127, 1190,
- /*  1580 */   128,  128,  124,  124, 1509,  541,  148,  148,  541,  256,
- /*  1590 */   195,  541, 1274,  541,  147,  147,  132,  132,  541,   11,
- /*  1600 */   541,  215,  541,  199,  347,  349,  351,  131,  131,  154,
- /*  1610 */   129,  129,  156,  130,  130,   74,   74,  541,  374,  300,
- /*  1620 */    76,   76,   73,   73,   43,   43,  214,  435,  211, 1335,
- /*  1630 */   304,  920,  884,  819,  241,  107,  137,  311,  885,   47,
- /*  1640 */    47,  107,  477,  382,  203,  452,  337, 1407, 1224, 1406,
- /*  1650 */   353,  190,  531,  191,  367,  198, 1512, 1167,  245,  165,
- /*  1660 */   391, 1454, 1452, 1164,   78,  288,  532, 1412,   81,  398,
- /*  1670 */    82,  446,  175,  122,  521,  159, 1332,   35, 1327,  299,
- /*  1680 */   167, 1324,  302,   93,  303,  438,  170,  171,  430,  172,
- /*  1690 */   173,  470,  439,  221,  379,  459, 1338,  445,  179,  225,
- /*  1700 */  1401,   87,  381,   36, 1423,  465,  320,  257,  227,  184,
- /*  1710 */   468,  324,  228,  384, 1191,  229,  483,  411, 1244, 1243,
- /*  1720 */  1242, 1235, 1216,  838,  385, 1215,  204,  336, 1495, 1214,
- /*  1730 */   413,  502, 1285, 1234, 1524,  281,  282,   92,  346,  493,
- /*  1740 */   496, 1286,  348,  243, 1284,  350,  244, 1283, 1481, 1480,
- /*  1750 */   416,   10, 1309,  361, 1387,  352,   99,   94,  286,  505,
- /*  1760 */   251, 1308, 1197,   34,  544, 1126,  252,  254,  255, 1267,
- /*  1770 */  1266,  359,  194,  365,  545,  366, 1186,  392, 1181, 1439,
- /*  1780 */   151, 1440, 1438, 1437,  152,  393,  135,  279,  200,  201,
- /*  1790 */   795,   77,  424,  153,  196,  164,  290,  210,  269,  133,
- /*  1800 */  1035, 1033,  166,  155,  949,  217,  220,  870,  168,  310,
- /*  1810 */  1049,  953,  174,  402,  157,  400,   83,  176,   84,   85,
- /*  1820 */    86,  158, 1052,  223,  222, 1048,  144,   18,  224, 1041,
- /*  1830 */   241,  319,  180, 1161,  226,  464,  181,   37,  810,  469,
- /*  1840 */   338,  230,  473,  849,  182,   88,  478,   19,  160,  332,
- /*  1850 */    20,   89,  280,  145,   90,  485,  492, 1114,  146, 1001,
- /*  1860 */   205, 1084,   39,   91, 1085,   40,  495,  260,  262,  919,
- /*  1870 */   185,  914,  107,  240, 1104,    7, 1100, 1102, 1108, 1088,
- /*  1880 */    33,   21, 1016,   22,   23,   24,   25,  517, 1107,   26,
- /*  1890 */   188,   95, 1002, 1000, 1004, 1058, 1005, 1057,  247,  246,
- /*  1900 */    28,   41,  880,  970,  820,  106,   29,  248,  537,  368,
- /*  1910 */   249, 1517,  371, 1121, 1177, 1177, 1177, 1516,
+ /*     0 */   550, 1226,  550,  455, 1264,  550, 1243,  550,  114,  111,
+ /*    10 */   211,  550, 1541,  550, 1264,  527,  114,  111,  211,  396,
+ /*    20 */  1236,  348,   42,   42,   42,   42, 1229,   42,   42,   71,
+ /*    30 */    71,  941, 1228,   71,   71,   71,   71, 1466, 1497,  942,
+ /*    40 */   824,  457,    6,  121,  122,  112, 1169, 1169, 1010, 1013,
+ /*    50 */  1003, 1003,  119,  119,  120,  120,  120,  120, 1547,  396,
+ /*    60 */  1362, 1521,  556,    2, 1197,  194,  532,  440,  143,  291,
+ /*    70 */   532,  136,  532,  375,  261,  508,  272,  389, 1277,  531,
+ /*    80 */   507,  497,  164,  121,  122,  112, 1169, 1169, 1010, 1013,
+ /*    90 */  1003, 1003,  119,  119,  120,  120,  120,  120, 1362,  446,
+ /*   100 */  1518,  118,  118,  118,  118,  117,  117,  116,  116,  116,
+ /*   110 */   115,  428,  266,  266,  266,  266, 1502,  362, 1504,  439,
+ /*   120 */   361, 1502,  521,  528, 1489,  547, 1118,  547, 1118,  396,
+ /*   130 */   409,  241,  208,  114,  111,  211,   98,  290,  541,  221,
+ /*   140 */  1033,  118,  118,  118,  118,  117,  117,  116,  116,  116,
+ /*   150 */   115,  428, 1146,  121,  122,  112, 1169, 1169, 1010, 1013,
+ /*   160 */  1003, 1003,  119,  119,  120,  120,  120,  120,  410,  432,
+ /*   170 */   117,  117,  116,  116,  116,  115,  428, 1422,  472,  123,
+ /*   180 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
+ /*   190 */   428,  116,  116,  116,  115,  428,  544,  544,  544,  396,
+ /*   200 */   509,  120,  120,  120,  120,  113, 1055, 1146, 1147, 1148,
+ /*   210 */  1055,  118,  118,  118,  118,  117,  117,  116,  116,  116,
+ /*   220 */   115,  428, 1465,  121,  122,  112, 1169, 1169, 1010, 1013,
+ /*   230 */  1003, 1003,  119,  119,  120,  120,  120,  120,  396,  448,
+ /*   240 */   320,   83,  467,   81,  363,  386, 1146,   80,  118,  118,
+ /*   250 */   118,  118,  117,  117,  116,  116,  116,  115,  428,  179,
+ /*   260 */   438,  428,  121,  122,  112, 1169, 1169, 1010, 1013, 1003,
+ /*   270 */  1003,  119,  119,  120,  120,  120,  120,  438,  437,  266,
+ /*   280 */   266,  118,  118,  118,  118,  117,  117,  116,  116,  116,
+ /*   290 */   115,  428,  547, 1113,  907,  510, 1146,  114,  111,  211,
+ /*   300 */  1435, 1146, 1147, 1148,  206,  495, 1113,  396,  453, 1113,
+ /*   310 */   549,  334,  120,  120,  120,  120,  298, 1435, 1437,   17,
+ /*   320 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
+ /*   330 */   428,  121,  122,  112, 1169, 1169, 1010, 1013, 1003, 1003,
+ /*   340 */   119,  119,  120,  120,  120,  120,  396, 1362,  438, 1146,
+ /*   350 */   486, 1146, 1147, 1148, 1000, 1000, 1011, 1014,  449,  118,
+ /*   360 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  428,
+ /*   370 */   121,  122,  112, 1169, 1169, 1010, 1013, 1003, 1003,  119,
+ /*   380 */   119,  120,  120,  120,  120, 1058, 1058,  469, 1435,  118,
+ /*   390 */   118,  118,  118,  117,  117,  116,  116,  116,  115,  428,
+ /*   400 */  1146,  455,  550, 1430, 1146, 1147, 1148,  233,  970, 1146,
+ /*   410 */   485,  482,  481,  171,  364,  396,  164,  411,  418,  846,
+ /*   420 */   480,  164,  185,  338,   71,   71, 1247, 1004,  118,  118,
+ /*   430 */   118,  118,  117,  117,  116,  116,  116,  115,  428,  121,
+ /*   440 */   122,  112, 1169, 1169, 1010, 1013, 1003, 1003,  119,  119,
+ /*   450 */   120,  120,  120,  120,  396, 1146, 1147, 1148,  839,   12,
+ /*   460 */   318,  513,  163,  360, 1146, 1147, 1148,  114,  111,  211,
+ /*   470 */   512,  290,  541,  550,  276,  180,  290,  541,  121,  122,
+ /*   480 */   112, 1169, 1169, 1010, 1013, 1003, 1003,  119,  119,  120,
+ /*   490 */   120,  120,  120,  349,  488,   71,   71,  118,  118,  118,
+ /*   500 */   118,  117,  117,  116,  116,  116,  115,  428, 1146,  209,
+ /*   510 */   415,  527, 1146, 1113, 1575,  382,  252,  269,  346,  491,
+ /*   520 */   341,  490,  238,  396,  517,  368, 1113, 1131,  337, 1113,
+ /*   530 */   191,  413,  286,   32,  461,  447,  118,  118,  118,  118,
+ /*   540 */   117,  117,  116,  116,  116,  115,  428,  121,  122,  112,
+ /*   550 */  1169, 1169, 1010, 1013, 1003, 1003,  119,  119,  120,  120,
+ /*   560 */   120,  120,  396, 1146, 1147, 1148,  991, 1146, 1147, 1148,
+ /*   570 */  1146,  233,  496, 1496,  485,  482,  481,    6,  163,  550,
+ /*   580 */   516,  550,  115,  428,  480,    5,  121,  122,  112, 1169,
+ /*   590 */  1169, 1010, 1013, 1003, 1003,  119,  119,  120,  120,  120,
+ /*   600 */   120,   13,   13,   13,   13,  118,  118,  118,  118,  117,
+ /*   610 */   117,  116,  116,  116,  115,  428,  407,  506,  412,  550,
+ /*   620 */  1490,  548, 1146,  896,  896, 1146, 1147, 1148, 1477, 1146,
+ /*   630 */   275,  396,  812,  813,  814,  975,  426,  426,  426,   16,
+ /*   640 */    16,   55,   55, 1246,  118,  118,  118,  118,  117,  117,
+ /*   650 */   116,  116,  116,  115,  428,  121,  122,  112, 1169, 1169,
+ /*   660 */  1010, 1013, 1003, 1003,  119,  119,  120,  120,  120,  120,
+ /*   670 */   396, 1193,    1,    1,  556,    2, 1197, 1146, 1147, 1148,
+ /*   680 */   194,  291,  902,  136, 1146, 1147, 1148,  901,  525, 1496,
+ /*   690 */  1277,    3,  384,    6,  121,  122,  112, 1169, 1169, 1010,
+ /*   700 */  1013, 1003, 1003,  119,  119,  120,  120,  120,  120,  862,
+ /*   710 */   550,  928,  550,  118,  118,  118,  118,  117,  117,  116,
+ /*   720 */   116,  116,  115,  428,  266,  266, 1096, 1573, 1146,  555,
+ /*   730 */  1573, 1197,   13,   13,   13,   13,  291,  547,  136,  396,
+ /*   740 */   489,  425,  424,  970,  348, 1277,  472,  414,  863,  279,
+ /*   750 */   140,  221,  118,  118,  118,  118,  117,  117,  116,  116,
+ /*   760 */   116,  115,  428,  121,  122,  112, 1169, 1169, 1010, 1013,
+ /*   770 */  1003, 1003,  119,  119,  120,  120,  120,  120,  550,  266,
+ /*   780 */   266,  432,  396, 1146, 1147, 1148, 1176,  834, 1176,  472,
+ /*   790 */   435,  145,  547, 1150,  405,  318,  443,  304,  842, 1494,
+ /*   800 */    71,   71,  416,    6, 1094,  477,  221,  100,  112, 1169,
+ /*   810 */  1169, 1010, 1013, 1003, 1003,  119,  119,  120,  120,  120,
+ /*   820 */   120,  118,  118,  118,  118,  117,  117,  116,  116,  116,
+ /*   830 */   115,  428,  237, 1429,  550,  455,  432,  287,  990,  550,
+ /*   840 */   236,  235,  234,  834,   97,  533,  433, 1269, 1269, 1150,
+ /*   850 */   498,  311,  434,  842,  981,  550,   71,   71,  980, 1245,
+ /*   860 */   550,   51,   51,  300,  118,  118,  118,  118,  117,  117,
+ /*   870 */   116,  116,  116,  115,  428,  194,  103,   70,   70,  266,
+ /*   880 */   266,  550,   71,   71,  266,  266,   30,  395,  348,  980,
+ /*   890 */   980,  982,  547,  532, 1113,  332,  396,  547,  499,  401,
+ /*   900 */  1474,  195,  534,   13,   13, 1362,  240, 1113,  277,  280,
+ /*   910 */  1113,  280,  308,  461,  310,  337,  396,   31,  188,  423,
+ /*   920 */   121,  122,  112, 1169, 1169, 1010, 1013, 1003, 1003,  119,
+ /*   930 */   119,  120,  120,  120,  120,  142,  396,  369,  461,  990,
+ /*   940 */   121,  122,  112, 1169, 1169, 1010, 1013, 1003, 1003,  119,
+ /*   950 */   119,  120,  120,  120,  120,  981,  327, 1146,  330,  980,
+ /*   960 */   121,  110,  112, 1169, 1169, 1010, 1013, 1003, 1003,  119,
+ /*   970 */   119,  120,  120,  120,  120,  468,  381, 1189,  118,  118,
+ /*   980 */   118,  118,  117,  117,  116,  116,  116,  115,  428, 1146,
+ /*   990 */   980,  980,  982,  309,    9,  370,  244,  366,  118,  118,
+ /*  1000 */   118,  118,  117,  117,  116,  116,  116,  115,  428,  317,
+ /*  1010 */   550,  348, 1146, 1147, 1148,  299,  290,  541,  118,  118,
+ /*  1020 */   118,  118,  117,  117,  116,  116,  116,  115,  428, 1267,
+ /*  1030 */  1267, 1167,   13,   13,  278,  425,  424,  472,  396,  927,
+ /*  1040 */   260,  260,  289, 1173, 1146, 1147, 1148,  189, 1175,  266,
+ /*  1050 */   266,  472,  394,  547, 1190,  550, 1174,  263,  144,  493,
+ /*  1060 */   926,  550,  547,  122,  112, 1169, 1169, 1010, 1013, 1003,
+ /*  1070 */  1003,  119,  119,  120,  120,  120,  120,   71,   71, 1146,
+ /*  1080 */  1176, 1276, 1176,   13,   13,  902, 1074, 1167,  550,  472,
+ /*  1090 */   901,  107,  542, 1495,    4, 1272, 1113,    6,  529, 1053,
+ /*  1100 */    12, 1075, 1096, 1574,  316,  459, 1574,  524,  545, 1113,
+ /*  1110 */    56,   56, 1113, 1493,  427, 1362, 1076,    6,  349,  285,
+ /*  1120 */   118,  118,  118,  118,  117,  117,  116,  116,  116,  115,
+ /*  1130 */   428,  429, 1275,  325, 1146, 1147, 1148,  882,  266,  266,
+ /*  1140 */  1281,  107,  542,  539,    4, 1492,  293,  883, 1215,    6,
+ /*  1150 */   210,  547,  547,  164,  294,  500,  420,  204,  545,  267,
+ /*  1160 */   267, 1218,  402,  515,  503,  204,  266,  266,  400,  535,
+ /*  1170 */     8,  990,  547,  523,  550,  926,  462,  105,  105,  547,
+ /*  1180 */  1094,  429,  266,  266,  106,  421,  429,  552,  551,  266,
+ /*  1190 */   266,  980,  522,  539, 1377,  547,   15,   15,  266,  266,
+ /*  1200 */   460, 1124,  547,  266,  266, 1074, 1376,  519,  290,  541,
+ /*  1210 */   550,  547,  518,   97,  448,  320,  547,  550,  926,  125,
+ /*  1220 */  1075,  990,  980,  980,  982,  983,   27,  105,  105,  405,
+ /*  1230 */   347, 1515,   44,   44,  106, 1076,  429,  552,  551,   57,
+ /*  1240 */    57,  980,  347, 1515,  107,  542,  550,    4,  466,  405,
+ /*  1250 */   214, 1124,  463,  297,  381, 1095,  538, 1313,  550,  543,
+ /*  1260 */   402,  545,  290,  541,  104,  244,  102,  530,   58,   58,
+ /*  1270 */   550,  199,  980,  980,  982,  983,   27, 1520, 1135,  431,
+ /*  1280 */    59,   59,  270,  237,  429,  138,   95,  379,  379,  378,
+ /*  1290 */   255,  376,   60,   60,  821, 1184,  539,  550,  273,  550,
+ /*  1300 */  1167, 1312,  393,  392,  550,  442,  550,  215,  210,  296,
+ /*  1310 */   519,  853,  550,  265,  208,  520, 1480,  295,  274,   61,
+ /*  1320 */    61,   62,   62,  312,  990,  109,   45,   45,   46,   46,
+ /*  1330 */   105,  105, 1190,  926,   47,   47,  345,  106,  550,  429,
+ /*  1340 */   552,  551, 1546,  550,  980,  871,  344,  217,  550,  941,
+ /*  1350 */   401,  107,  542,  218,    4,  156, 1167,  942,  158,  550,
+ /*  1360 */    49,   49, 1166,  550,  268,   50,   50,  550,  545, 1454,
+ /*  1370 */    63,   63,  550, 1453,  216,  980,  980,  982,  983,   27,
+ /*  1380 */   450,   64,   64,  550,  464,   65,   65,  550,  322,   14,
+ /*  1390 */    14,  429, 1309,  550,   66,   66, 1091,  550,  141,  383,
+ /*  1400 */    38,  550,  967,  539,  326,  127,  127,  550,  397,   67,
+ /*  1410 */    67,  550,  329,  290,  541,   52,   52,  519,  550,   68,
+ /*  1420 */    68,  849,  518,   69,   69,  403,  165,  861,  860,   53,
+ /*  1430 */    53,  990,  315,  151,  151,   97,  436,  105,  105,  331,
+ /*  1440 */   152,  152,  530, 1052,  106, 1052,  429,  552,  551, 1135,
+ /*  1450 */   431,  980, 1036,  270,  972,  239,  333,  243,  379,  379,
+ /*  1460 */   378,  255,  376,  944,  945,  821, 1300,  550,  220,  550,
+ /*  1470 */   107,  542,  550,    4,  550, 1260,  199,  849,  215, 1040,
+ /*  1480 */   296, 1534,  980,  980,  982,  983,   27,  545,  295,   76,
+ /*  1490 */    76,   54,   54,  984,   72,   72,  128,  128,  868,  869,
+ /*  1500 */   107,  542,  550,    4, 1051,  550, 1051,  537,  473,  550,
+ /*  1510 */   429,  550,  454, 1244,  550,  243,  550,  545,  217,  550,
+ /*  1520 */   456,  197,  539,  243,   73,   73,  156,  129,  129,  158,
+ /*  1530 */   340,  130,  130,  126,  126, 1040,  150,  150,  149,  149,
+ /*  1540 */   429,  134,  134,  321,  478,  216,   97,  239,  335,  984,
+ /*  1550 */   990,   97,  539,  350,  351,  550,  105,  105,  906,  935,
+ /*  1560 */   550,  899,  243,  106,  109,  429,  552,  551,  550, 1509,
+ /*  1570 */   980,  832,   99,  542,  139,    4,  550,  133,  133,  397,
+ /*  1580 */   990, 1321,  131,  131,  290,  541,  105,  105, 1361,  545,
+ /*  1590 */   132,  132, 1296,  106, 1307,  429,  552,  551,   75,   75,
+ /*  1600 */   980,  980,  980,  982,  983,   27,  550,  436,  900, 1293,
+ /*  1610 */   536,  109,  429, 1367,  550, 1225, 1217, 1206,  258,  550,
+ /*  1620 */   353,  550, 1205,   11,  539, 1207, 1528,  355,   77,   77,
+ /*  1630 */   380,  980,  980,  982,  983,   27,   74,   74,  357,  213,
+ /*  1640 */   303,   43,   43,   48,   48,  441,  314,  201,  307, 1354,
+ /*  1650 */   319,  359,  990,  458,  483, 1243,  343,  192,  105,  105,
+ /*  1660 */  1426, 1425,  193,  540,  205,  106, 1531,  429,  552,  551,
+ /*  1670 */  1184,  167,  980,  270,  247, 1473, 1471, 1181,  379,  379,
+ /*  1680 */   378,  255,  376,  200,  373,  821,  404,   83,   79,   82,
+ /*  1690 */  1431,  452,  177,  124,  530, 1346,   95,  301,  215,  302,
+ /*  1700 */   296,  161,  169,  980,  980,  982,  983,   27,  295, 1343,
+ /*  1710 */   305,  306,  444,  445, 1351,  172,   35,  173,  174,  175,
+ /*  1720 */   476,  223,  387,  385,   36,  451,  465, 1357,  181,  388,
+ /*  1730 */    88,  471,  227, 1420,  186,  474,  259, 1442,  217,  229,
+ /*  1740 */   230,  324,  328,  390,  492,  231,  156, 1263, 1208,  158,
+ /*  1750 */   417, 1254,   90,  853, 1262, 1261,  206,  419, 1514,  511,
+ /*  1760 */  1304,   94, 1545,  352,  354,  216, 1305, 1303,  283, 1233,
+ /*  1770 */   284,  391, 1232, 1544,  342, 1231, 1543,  356,  245, 1302,
+ /*  1780 */  1253,  502,  505,  358,  246, 1500, 1499,  422,   10,  367,
+ /*  1790 */   101, 1328, 1327,  514, 1406,   96,  253, 1214,   34,  397,
+ /*  1800 */   553, 1141,  254,  365,  290,  541,  256,  257,  554, 1286,
+ /*  1810 */   372,  196, 1285,  371, 1203, 1198,  153, 1458,  137, 1459,
+ /*  1820 */   154, 1457,  281, 1456,  155,  808,  430,  436,  202,  398,
+ /*  1830 */   203,   78,  288,  198,  292,  212,  271, 1050,  135, 1048,
+ /*  1840 */   964,  157,  219,  168,  170,  885,  313, 1064,  222,  176,
+ /*  1850 */   968,  159,  406,   84,  408,  178,   85,   86,   87,  160,
+ /*  1860 */  1067,  224, 1063,  225,  146,  166,  399,   18,  226,  323,
+ /*  1870 */  1056, 1178,  470,  243,  182,  228,  183,   37,  823,  475,
+ /*  1880 */   344,  232,  479,  487,  184,   89,   19,  851,  336,   20,
+ /*  1890 */   339,  484,   91,  282,  162,  147,  864,   92,  494,   93,
+ /*  1900 */  1129,  148, 1016, 1099,   39,  501, 1100,   40,  504,  207,
+ /*  1910 */   262,  264,  934,  187,  929,  109, 1119, 1115, 1117,    7,
+ /*  1920 */   242, 1103,   33, 1123,   21,  526,   22,   23,   24, 1122,
+ /*  1930 */    25,  190,   97,   26, 1031, 1017, 1015, 1019, 1073, 1020,
+ /*  1940 */  1072,  249,  248,   28,   41,  895,  985,  833,  108,   29,
+ /*  1950 */   377,  546,  250,  374, 1137, 1136, 1194, 1194,  251, 1194,
+ /*  1960 */  1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194, 1194,
+ /*  1970 */  1194, 1194, 1536, 1535,
 };
 static const YYCODETYPE yy_lookahead[] = {
- /*     0 */   187,  187,  187,  216,  217,  187,  206,  187,  264,  265,
- /*    10 */   266,  187,  225,  187,  209,  187,  264,  265,  266,   19,
- /*    20 */   187,  187,  209,  210,  209,  210,  187,  209,  210,  209,
- /*    30 */   210,   31,  209,  209,  210,  209,  210,  285,  224,   39,
- /*    40 */   203,  204,  205,   43,   44,   45,   46,   47,   48,   49,
- /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  230,   19,
- /*    60 */   181,  182,  183,  184,  230,  245,  233,  208,  189,  245,
- /*    70 */   191,  245,   26,  206,  254,  216,  276,  198,  254,  198,
- /*    80 */   254,  281,  187,   43,   44,   45,   46,   47,   48,   49,
- /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  259,   99,
- /*   100 */   100,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   110 */   231,  232,  231,  232,  286,  302,  303,  302,   22,  304,
- /*   120 */   302,  303,   76,  244,   11,  244,   86,   19,   88,  248,
- /*   130 */   249,  264,  265,  266,   26,   89,  198,  258,   92,   99,
- /*   140 */   100,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   150 */   105,   43,   44,   45,   46,   47,   48,   49,   50,   51,
- /*   160 */    52,   53,   54,   55,   56,   57,  212,  288,  273,  231,
- /*   170 */   232,  105,  106,  107,  108,  109,  131,   69,  203,  204,
- /*   180 */   205,  136,  244,   99,  100,  101,  102,  103,  104,  105,
- /*   190 */   106,  107,  108,  109,   15,  103,  104,   19,  260,  103,
- /*   200 */   104,   54,   55,   56,   57,   58,   22,   99,  100,  101,
- /*   210 */   102,  103,  104,  105,  106,  107,  108,  109,  264,  265,
- /*   220 */   266,   43,   44,   45,   46,   47,   48,   49,   50,   51,
- /*   230 */    52,   53,   54,   55,   56,   57,   19,  124,  125,   60,
- /*   240 */   148,   24,  150,   59,  187,   67,   99,  100,  101,  102,
- /*   250 */   103,  104,  105,  106,  107,  108,  109,  187,  187,  109,
- /*   260 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   270 */    53,   54,   55,   56,   57,  204,  205,   99,  100,  101,
- /*   280 */   102,  103,  104,  105,  106,  107,  108,  109,  103,  104,
- /*   290 */   105,  106,  107,  108,  109,   59,  112,  113,  114,   76,
- /*   300 */   231,  232,  187,   19,   19,   22,   23,   23,   54,   55,
- /*   310 */    56,   57,   89,  244,  199,   92,   99,  100,  101,  102,
- /*   320 */   103,  104,  105,  106,  107,  108,  109,   43,   44,   45,
- /*   330 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
- /*   340 */    56,   57,   19,  212,  187,  274,   23,   26,  112,  113,
- /*   350 */   114,  294,  295,   99,  100,  101,  102,  103,  104,  105,
- /*   360 */   106,  107,  108,  109,   59,  295,   43,   44,   45,   46,
- /*   370 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
- /*   380 */    57,   98,  146,   99,  100,  101,  102,  103,  104,  105,
- /*   390 */   106,  107,  108,  109,  109,  264,  265,  266,  187,  187,
- /*   400 */   115,  116,  117,  118,  119,  120,  121,   73,   59,   19,
- /*   410 */   105,   23,  127,   23,   26,   81,  259,  112,  113,  114,
- /*   420 */   187,   72,   99,  100,  101,  102,  103,  104,  105,  106,
- /*   430 */   107,  108,  109,   43,   44,   45,   46,   47,   48,   49,
- /*   440 */    50,   51,   52,   53,   54,   55,   56,   57,   19,  124,
- /*   450 */   125,  182,   23,  184,  187,  134,  135,  123,  189,  131,
- /*   460 */   191,  112,  113,  114,  136,  187,  233,  198,  134,  135,
- /*   470 */   198,  259,   43,   44,   45,   46,   47,   48,   49,   50,
- /*   480 */    51,   52,   53,   54,   55,   56,   57,  209,  210,   99,
- /*   490 */   100,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*   500 */   231,  232,  206,  231,  232,  187,   59,  296,  297,   76,
- /*   510 */   160,  161,  301,  244,  232,   19,  244,  297,   59,   23,
- /*   520 */    87,  301,   89,  245,   26,   92,  244,  258,   99,  100,
- /*   530 */   101,  102,  103,  104,  105,  106,  107,  108,  109,   43,
- /*   540 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
- /*   550 */    54,   55,   56,   57,   19,  187,   97,  288,   23,  112,
- /*   560 */   113,  114,  115,  296,  297,  118,  119,  120,  301,  108,
- /*   570 */   109,  112,  113,  255,  141,  128,  117,  281,   43,   44,
- /*   580 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
- /*   590 */    55,   56,   57,  187,  187,   99,  100,  101,  102,  103,
- /*   600 */   104,  105,  106,  107,  108,  109,   26,  148,  149,  150,
- /*   610 */   115,   97,   59,  118,  119,  120,  209,  210,   73,   59,
- /*   620 */   122,   19,  209,  128,  256,   72,  187,  113,  187,   81,
- /*   630 */   223,  117,  227,  228,   99,  100,  101,  102,  103,  104,
- /*   640 */   105,  106,  107,  108,  109,   43,   44,   45,   46,   47,
- /*   650 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
- /*   660 */    19,  255,  148,  149,  150,  112,  113,  114,  123,  124,
- /*   670 */   125,  230,  112,  113,  114,   22,  297,   22,   81,   22,
- /*   680 */   301,   59,  134,  135,   43,   44,   45,   46,   47,   48,
- /*   690 */    49,   50,   51,   52,   53,   54,   55,   56,   57,  139,
- /*   700 */   192,   99,  100,  101,  102,  103,  104,  105,  106,  107,
- /*   710 */   108,  109,   59,  116,   59,  187,   59,  231,  232,   46,
- /*   720 */    47,   48,   49,   16,   12,  145,  198,   22,  187,  187,
- /*   730 */   244,  134,  135,  222,  112,  113,  114,  209,  210,   27,
- /*   740 */    99,  100,  101,  102,  103,  104,  105,  106,  107,  108,
- /*   750 */   109,  209,  210,  187,   42,  187,  154,  227,  228,  231,
- /*   760 */   232,  139,   22,   23,   59,  112,  113,  114,  113,  112,
- /*   770 */   113,  114,  244,  245,  233,   63,   19,  209,  210,  271,
- /*   780 */   187,   24,  254,  275,   77,   73,   79,  245,  195,  260,
- /*   790 */   117,  223,  199,   22,   23,  154,   19,   26,   22,  187,
- /*   800 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   810 */    53,   54,   55,   56,   57,   19,  187,  112,  113,  114,
- /*   820 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   830 */    53,   54,   55,   56,   57,   59,  263,  187,   98,   43,
- /*   840 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
- /*   850 */    54,   55,   56,   57,  204,  205,   99,  100,  101,  102,
- /*   860 */   103,  104,  105,  106,  107,  108,  109,  255,  130,   98,
- /*   870 */   132,  133,  299,  300,  198,  187,   99,  100,  101,  102,
- /*   880 */   103,  104,  105,  106,  107,  108,  109,  187,  112,  113,
- /*   890 */   114,  187,  241,  187,  243,   99,  100,  101,  102,  103,
- /*   900 */   104,  105,  106,  107,  108,  109,   19,  231,  232,  209,
- /*   910 */   210,  282,   59,  209,  210,  209,  210,   16,  230,   19,
- /*   920 */   244,   22,   23,  223,  274,   26,   19,  223,  187,  223,
- /*   930 */   198,   44,   45,   46,   47,   48,   49,   50,   51,   52,
- /*   940 */    53,   54,   55,   56,   57,   45,   46,   47,   48,   49,
- /*   950 */    50,   51,   52,   53,   54,   55,   56,   57,   19,   20,
- /*   960 */   187,   22,  187,  231,  232,  112,  113,  114,  123,  124,
- /*   970 */   125,    7,    8,    9,  187,   36,  244,   24,   77,   21,
- /*   980 */    79,  187,  209,  210,  187,  263,   99,  100,  101,  102,
- /*   990 */   103,  104,  105,  106,  107,  108,  109,   98,   59,   99,
- /*  1000 */   100,  101,  102,  103,  104,  105,  106,  107,  108,  109,
- /*  1010 */    71,  187,   59,  187,  187,   19,   20,  187,   22,  112,
- /*  1020 */    81,  299,  300,  282,  230,  199,  291,  292,   22,  187,
- /*  1030 */    24,  256,   36,  209,  210,  187,   97,   35,   80,  209,
- /*  1040 */   210,  268,  103,  104,   48,  187,  220,  223,  222,  110,
- /*  1050 */    59,  112,  113,  114,  187,   59,  117,  156,  187,  179,
- /*  1060 */   180,  181,  182,  183,  184,   59,  113,   71,   66,  189,
- /*  1070 */    22,  191,  230,  134,  135,  245,   74,  119,  198,  282,
- /*  1080 */   297,   85,  224,  198,  301,  187,   90,  148,  149,  150,
- /*  1090 */   151,  152,   19,   97,  103,  104,  123,  124,  125,  103,
- /*  1100 */   104,   53,  111,  112,  113,  114,  110,  116,  112,  113,
- /*  1110 */   114,  231,  232,  117,  156,  124,  231,  232,  297,  113,
- /*  1120 */   187,   24,  301,  256,  244,  201,  202,  256,  126,  244,
- /*  1130 */   187,  198,  187,  187,   23,  187,  187,   26,  258,  148,
- /*  1140 */    19,  150,  209,  210,  148,  149,  150,  151,  152,    0,
- /*  1150 */     1,    2,  209,  210,    5,  209,  210,  209,  210,   10,
- /*  1160 */    11,   12,   13,   14,  231,  232,   17,   46,  288,   19,
- /*  1170 */    20,  223,   22,  236,  198,   66,  187,  244,  245,   30,
- /*  1180 */    12,   32,  198,  246,   59,  112,   36,  187,  245,   40,
- /*  1190 */   198,  245,  117,   29,   85,   27,   26,   33,  209,  210,
- /*  1200 */   297,   76,  127,   94,  301,  256,   26,  231,  232,   59,
- /*  1210 */    42,  153,   87,  155,   89,  231,  232,   92,   31,   70,
- /*  1220 */   244,   71,   26,  231,  232,  114,   39,   78,  244,   65,
- /*  1230 */    81,   63,  111,  233,  137,   85,  244,  112,  113,  114,
- /*  1240 */    90,   22,   59,   24,   95,  201,  202,   97,  127,  187,
- /*  1250 */   139,  142,  187,  103,  104,   19,   20,  187,   22,  187,
- /*  1260 */   110,  187,  112,  113,  114,  187,  141,  117,  141,  187,
- /*  1270 */    23,  187,   36,   26,  209,  210,  134,  135,  129,  209,
- /*  1280 */   210,  209,  210,  134,  135,   22,  159,  209,  210,  187,
- /*  1290 */   187,  209,  210,  209,  210,   59,  113,  187,  148,  149,
- /*  1300 */   150,  151,  152,  289,  290,  187,  157,   71,  248,  249,
- /*  1310 */   114,  141,  209,  210,   46,  125,  116,  117,  138,   19,
- /*  1320 */    20,   85,   22,  148,   61,  150,   90,  209,  210,   23,
- /*  1330 */     7,    8,   26,   97,  187,  139,   36,  147,   59,  103,
- /*  1340 */   104,   19,   20,  187,   22,   59,  110,  187,  112,  113,
- /*  1350 */   114,    1,    2,  117,  187,    5,  209,  210,   36,   59,
- /*  1360 */    10,   11,   12,   13,   14,  209,  210,   17,   59,  209,
- /*  1370 */   210,   71,  187,  148,  250,  150,  209,  210,  187,  111,
- /*  1380 */    30,   59,   32,   22,  148,  149,  150,  151,  152,  187,
- /*  1390 */    40,  187,  113,   71,  209,  210,  187,   97,  187,  113,
- /*  1400 */   209,  210,  187,  103,  104,  105,   23,  187,  187,   26,
- /*  1410 */   110,  187,  112,  113,  114,   83,   84,  117,   23,   97,
- /*  1420 */    70,   26,  113,  218,  187,  103,  104,  187,   78,  209,
- /*  1430 */   210,   81,  110,  187,  112,  113,  114,   19,   20,  117,
- /*  1440 */    22,  187,  187,  187,  187,   95,  209,  210,  148,  149,
- /*  1450 */   150,  151,  152,  187,   36,   23,  187,  187,   26,  187,
- /*  1460 */   187,  187,  187,  209,  210,  209,  210,  187,  187,  218,
- /*  1470 */   148,  149,  150,  151,  152,  209,  210,   59,  187,  129,
- /*  1480 */   187,  209,  210,  187,  134,  135,  187,  306,  187,   71,
- /*  1490 */   209,  210,   23,  228,  187,   26,   23,  187,  137,   26,
- /*  1500 */   209,  210,  209,  210,  187,  209,  210,  157,  209,  210,
- /*  1510 */   209,  210,  218,  187,  187,   97,  209,  210,  187,  278,
- /*  1520 */    23,  103,  104,   26,  187,  187,  187,  187,  110,  187,
- /*  1530 */   112,  113,  114,  187,  187,  117,    5,  247,  187,  187,
- /*  1540 */   187,   10,   11,   12,   13,   14,  209,  210,   17,  209,
- /*  1550 */   210,  209,  210,  187,  187,  187,  209,  210,  187,   23,
- /*  1560 */   187,   30,   26,   32,  187,  187,  148,  149,  150,  151,
- /*  1570 */   152,   40,  187,  187,  187,  209,  210,  209,  210,  187,
- /*  1580 */   209,  210,  209,  210,  187,  187,  209,  210,  187,  277,
- /*  1590 */   234,  187,  247,  187,  209,  210,  209,  210,  187,  235,
- /*  1600 */   187,   70,  187,  207,  247,  247,  247,  209,  210,   78,
- /*  1610 */   209,  210,   81,  209,  210,  209,  210,  187,  185,  238,
- /*  1620 */   209,  210,  209,  210,  209,  210,   95,  251,  287,  238,
- /*  1630 */   251,   23,   23,   23,   26,   26,   26,  283,   23,  209,
- /*  1640 */   210,   26,  213,  238,  221,  283,  212,  212,  217,  212,
- /*  1650 */   251,  241,  270,  241,  237,  235,  190,   60,  137,  287,
- /*  1660 */   129,  194,  194,   38,  284,  134,  135,  273,  284,  194,
- /*  1670 */   146,  111,   22,  144,  141,   43,  262,  261,  242,  241,
- /*  1680 */   226,  242,  241,  145,  238,   18,  229,  229,  157,  229,
- /*  1690 */   229,   18,  194,  193,  238,  194,  226,  238,  226,  193,
- /*  1700 */   238,  153,  262,  261,  280,   62,  279,  194,  193,   22,
- /*  1710 */   214,  194,  193,  214,  194,  193,  111,   64,  211,  211,
- /*  1720 */   211,  219,  211,  122,  214,  213,  160,  211,  300,  211,
- /*  1730 */   109,  140,  253,  219,  211,  272,  272,  111,  252,  214,
- /*  1740 */   214,  253,  252,  194,  253,  252,   91,  253,  305,  305,
- /*  1750 */    82,   22,  257,  194,  267,  252,  153,  143,  269,  142,
- /*  1760 */    25,  257,  197,   26,  196,   13,  188,  188,    6,  242,
- /*  1770 */   242,  241,  240,  239,  186,  238,  186,  293,  186,  206,
- /*  1780 */   200,  206,  206,  206,  200,  293,  215,  215,  207,  207,
- /*  1790 */     4,  206,    3,  200,   22,  290,  158,   15,   96,   16,
- /*  1800 */    23,   23,  146,  126,  135,   24,  140,   20,  138,   16,
- /*  1810 */     1,  147,  138,   37,  126,   61,   53,  146,   53,   53,
- /*  1820 */    53,  126,  112,  137,   34,    1,    5,   22,  111,   68,
- /*  1830 */    26,  156,   68,   75,  137,   41,  111,   24,   20,   19,
- /*  1840 */   127,  121,   67,   28,   22,   22,   67,   22,   37,   23,
- /*  1850 */    22,   22,   67,   23,  145,   22,   24,   23,   23,   23,
- /*  1860 */   137,   23,   22,   26,   23,   22,   24,   23,   23,  112,
- /*  1870 */    22,  139,   26,   34,   75,   44,   88,   86,   75,   23,
- /*  1880 */    22,   34,   23,   34,   34,   34,   34,   24,   93,   34,
- /*  1890 */    26,   26,   23,   23,   23,   23,   11,   23,   22,   26,
- /*  1900 */    22,   22,  131,   23,   23,   22,   22,  137,   26,   23,
- /*  1910 */   137,  137,   15,    1,  307,  307,  307,  137,  307,  307,
- /*  1920 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1930 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1940 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1950 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1960 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1970 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1980 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  1990 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2000 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2010 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2020 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2030 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2040 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2050 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2060 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2070 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2080 */   307,  307,  307,  307,  307,  307,  307,  307,  307,  307,
- /*  2090 */   307,  307,  307,  307,  307,  307,  307,
+ /*     0 */   189,  211,  189,  189,  218,  189,  220,  189,  267,  268,
+ /*    10 */   269,  189,  210,  189,  228,  189,  267,  268,  269,   19,
+ /*    20 */   218,  189,  211,  212,  211,  212,  211,  211,  212,  211,
+ /*    30 */   212,   31,  211,  211,  212,  211,  212,  288,  300,   39,
+ /*    40 */    21,  189,  304,   43,   44,   45,   46,   47,   48,   49,
+ /*    50 */    50,   51,   52,   53,   54,   55,   56,   57,  225,   19,
+ /*    60 */   189,  183,  184,  185,  186,  189,  248,  263,  236,  191,
+ /*    70 */   248,  193,  248,  197,  208,  257,  262,  201,  200,  257,
+ /*    80 */   200,  257,   81,   43,   44,   45,   46,   47,   48,   49,
+ /*    90 */    50,   51,   52,   53,   54,   55,   56,   57,  189,   80,
+ /*   100 */   189,  101,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   110 */   110,  111,  234,  235,  234,  235,  305,  306,  305,  118,
+ /*   120 */   307,  305,  306,  297,  298,  247,   86,  247,   88,   19,
+ /*   130 */   259,  251,  252,  267,  268,  269,   26,  136,  137,  261,
+ /*   140 */   121,  101,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   150 */   110,  111,   59,   43,   44,   45,   46,   47,   48,   49,
+ /*   160 */    50,   51,   52,   53,   54,   55,   56,   57,  259,  291,
+ /*   170 */   105,  106,  107,  108,  109,  110,  111,  158,  189,   69,
+ /*   180 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*   190 */   111,  107,  108,  109,  110,  111,  205,  206,  207,   19,
+ /*   200 */    19,   54,   55,   56,   57,   58,   29,  114,  115,  116,
+ /*   210 */    33,  101,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   220 */   110,  111,  233,   43,   44,   45,   46,   47,   48,   49,
+ /*   230 */    50,   51,   52,   53,   54,   55,   56,   57,   19,  126,
+ /*   240 */   127,  148,   65,   24,  214,  200,   59,   67,  101,  102,
+ /*   250 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   22,
+ /*   260 */   189,  111,   43,   44,   45,   46,   47,   48,   49,   50,
+ /*   270 */    51,   52,   53,   54,   55,   56,   57,  206,  207,  234,
+ /*   280 */   235,  101,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   290 */   110,  111,  247,   76,  107,  114,   59,  267,  268,  269,
+ /*   300 */   189,  114,  115,  116,  162,  163,   89,   19,  263,   92,
+ /*   310 */   189,   23,   54,   55,   56,   57,  189,  206,  207,   22,
+ /*   320 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*   330 */   111,   43,   44,   45,   46,   47,   48,   49,   50,   51,
+ /*   340 */    52,   53,   54,   55,   56,   57,   19,  189,  277,   59,
+ /*   350 */    23,  114,  115,  116,   46,   47,   48,   49,   61,  101,
+ /*   360 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
+ /*   370 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
+ /*   380 */    53,   54,   55,   56,   57,  125,  126,  127,  277,  101,
+ /*   390 */   102,  103,  104,  105,  106,  107,  108,  109,  110,  111,
+ /*   400 */    59,  189,  189,  276,  114,  115,  116,  117,   73,   59,
+ /*   410 */   120,  121,  122,   72,  214,   19,   81,  259,   19,   23,
+ /*   420 */   130,   81,   72,   24,  211,  212,  221,  119,  101,  102,
+ /*   430 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   43,
+ /*   440 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
+ /*   450 */    54,   55,   56,   57,   19,  114,  115,  116,   23,  208,
+ /*   460 */   125,  248,  189,  189,  114,  115,  116,  267,  268,  269,
+ /*   470 */   189,  136,  137,  189,  262,   22,  136,  137,   43,   44,
+ /*   480 */    45,   46,   47,   48,   49,   50,   51,   52,   53,   54,
+ /*   490 */    55,   56,   57,  189,   95,  211,  212,  101,  102,  103,
+ /*   500 */   104,  105,  106,  107,  108,  109,  110,  111,   59,  189,
+ /*   510 */   111,  189,   59,   76,  294,  295,  117,  118,  119,  120,
+ /*   520 */   121,  122,  123,   19,   87,  189,   89,   23,  129,   92,
+ /*   530 */   279,  227,  248,   22,  189,  284,  101,  102,  103,  104,
+ /*   540 */   105,  106,  107,  108,  109,  110,  111,   43,   44,   45,
+ /*   550 */    46,   47,   48,   49,   50,   51,   52,   53,   54,   55,
+ /*   560 */    56,   57,   19,  114,  115,  116,   23,  114,  115,  116,
+ /*   570 */    59,  117,  299,  300,  120,  121,  122,  304,  189,  189,
+ /*   580 */   143,  189,  110,  111,  130,   22,   43,   44,   45,   46,
+ /*   590 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   600 */    57,  211,  212,  211,  212,  101,  102,  103,  104,  105,
+ /*   610 */   106,  107,  108,  109,  110,  111,  226,  189,  226,  189,
+ /*   620 */   298,  132,   59,  134,  135,  114,  115,  116,  189,   59,
+ /*   630 */   285,   19,    7,    8,    9,   23,  205,  206,  207,  211,
+ /*   640 */   212,  211,  212,  221,  101,  102,  103,  104,  105,  106,
+ /*   650 */   107,  108,  109,  110,  111,   43,   44,   45,   46,   47,
+ /*   660 */    48,   49,   50,   51,   52,   53,   54,   55,   56,   57,
+ /*   670 */    19,  181,  182,  183,  184,  185,  186,  114,  115,  116,
+ /*   680 */   189,  191,  133,  193,  114,  115,  116,  138,  299,  300,
+ /*   690 */   200,   22,  201,  304,   43,   44,   45,   46,   47,   48,
+ /*   700 */    49,   50,   51,   52,   53,   54,   55,   56,   57,   35,
+ /*   710 */   189,  141,  189,  101,  102,  103,  104,  105,  106,  107,
+ /*   720 */   108,  109,  110,  111,  234,  235,   22,   23,   59,  184,
+ /*   730 */    26,  186,  211,  212,  211,  212,  191,  247,  193,   19,
+ /*   740 */    66,  105,  106,   73,  189,  200,  189,  226,   74,  226,
+ /*   750 */    22,  261,  101,  102,  103,  104,  105,  106,  107,  108,
+ /*   760 */   109,  110,  111,   43,   44,   45,   46,   47,   48,   49,
+ /*   770 */    50,   51,   52,   53,   54,   55,   56,   57,  189,  234,
+ /*   780 */   235,  291,   19,  114,  115,  116,  150,   59,  152,  189,
+ /*   790 */   233,  236,  247,   59,  189,  125,  126,  127,   59,  300,
+ /*   800 */   211,  212,  128,  304,  100,   19,  261,  156,   45,   46,
+ /*   810 */    47,   48,   49,   50,   51,   52,   53,   54,   55,   56,
+ /*   820 */    57,  101,  102,  103,  104,  105,  106,  107,  108,  109,
+ /*   830 */   110,  111,   46,  233,  189,  189,  291,  248,   99,  189,
+ /*   840 */   125,  126,  127,  115,   26,  200,  289,  230,  231,  115,
+ /*   850 */   200,   16,  189,  114,  115,  189,  211,  212,  119,  221,
+ /*   860 */   189,  211,  212,  258,  101,  102,  103,  104,  105,  106,
+ /*   870 */   107,  108,  109,  110,  111,  189,  156,  211,  212,  234,
+ /*   880 */   235,  189,  211,  212,  234,  235,   22,  201,  189,  150,
+ /*   890 */   151,  152,  247,  248,   76,   16,   19,  247,  248,  113,
+ /*   900 */   189,   24,  257,  211,  212,  189,   26,   89,  262,  223,
+ /*   910 */    92,  225,   77,  189,   79,  129,   19,   53,  226,  248,
+ /*   920 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
+ /*   930 */    53,   54,   55,   56,   57,  236,   19,  271,  189,   99,
+ /*   940 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
+ /*   950 */    53,   54,   55,   56,   57,  115,   77,   59,   79,  119,
+ /*   960 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
+ /*   970 */    53,   54,   55,   56,   57,  259,   22,   23,  101,  102,
+ /*   980 */   103,  104,  105,  106,  107,  108,  109,  110,  111,   59,
+ /*   990 */   150,  151,  152,  158,   22,  244,   24,  246,  101,  102,
+ /*  1000 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  285,
+ /*  1010 */   189,  189,  114,  115,  116,  200,  136,  137,  101,  102,
+ /*  1020 */   103,  104,  105,  106,  107,  108,  109,  110,  111,  230,
+ /*  1030 */   231,   59,  211,  212,  285,  105,  106,  189,   19,  141,
+ /*  1040 */   234,  235,  239,  113,  114,  115,  116,  226,  118,  234,
+ /*  1050 */   235,  189,  249,  247,  100,  189,  126,   23,  236,  107,
+ /*  1060 */    26,  189,  247,   44,   45,   46,   47,   48,   49,   50,
+ /*  1070 */    51,   52,   53,   54,   55,   56,   57,  211,  212,   59,
+ /*  1080 */   150,  233,  152,  211,  212,  133,   12,  115,  189,  189,
+ /*  1090 */   138,   19,   20,  300,   22,  233,   76,  304,  226,   11,
+ /*  1100 */   208,   27,   22,   23,  200,   19,   26,   87,   36,   89,
+ /*  1110 */   211,  212,   92,  300,  248,  189,   42,  304,  189,  250,
+ /*  1120 */   101,  102,  103,  104,  105,  106,  107,  108,  109,  110,
+ /*  1130 */   111,   59,  200,  233,  114,  115,  116,   63,  234,  235,
+ /*  1140 */   235,   19,   20,   71,   22,  300,  189,   73,  200,  304,
+ /*  1150 */   116,  247,  247,   81,  189,  200,  227,   26,   36,  234,
+ /*  1160 */   235,  203,  204,  143,  200,   26,  234,  235,  194,  200,
+ /*  1170 */    48,   99,  247,   66,  189,  141,  284,  105,  106,  247,
+ /*  1180 */   100,   59,  234,  235,  112,  259,  114,  115,  116,  234,
+ /*  1190 */   235,  119,   85,   71,  266,  247,  211,  212,  234,  235,
+ /*  1200 */   114,   94,  247,  234,  235,   12,  266,   85,  136,  137,
+ /*  1210 */   189,  247,   90,   26,  126,  127,  247,  189,   26,   22,
+ /*  1220 */    27,   99,  150,  151,  152,  153,  154,  105,  106,  189,
+ /*  1230 */   302,  303,  211,  212,  112,   42,  114,  115,  116,  211,
+ /*  1240 */   212,  119,  302,  303,   19,   20,  189,   22,  274,  189,
+ /*  1250 */    15,  144,  278,  189,   22,   23,   63,  189,  189,  203,
+ /*  1260 */   204,   36,  136,  137,  155,   24,  157,  143,  211,  212,
+ /*  1270 */   189,  140,  150,  151,  152,  153,  154,    0,    1,    2,
+ /*  1280 */   211,  212,    5,   46,   59,  161,  147,   10,   11,   12,
+ /*  1290 */    13,   14,  211,  212,   17,   60,   71,  189,  258,  189,
+ /*  1300 */    59,  189,  105,  106,  189,  189,  189,   30,  116,   32,
+ /*  1310 */    85,  124,  189,  251,  252,   90,  189,   40,  258,  211,
+ /*  1320 */   212,  211,  212,  189,   99,   26,  211,  212,  211,  212,
+ /*  1330 */   105,  106,  100,  141,  211,  212,  119,  112,  189,  114,
+ /*  1340 */   115,  116,   23,  189,  119,   26,  129,   70,  189,   31,
+ /*  1350 */   113,   19,   20,   24,   22,   78,  115,   39,   81,  189,
+ /*  1360 */   211,  212,   26,  189,   22,  211,  212,  189,   36,  189,
+ /*  1370 */   211,  212,  189,  189,   97,  150,  151,  152,  153,  154,
+ /*  1380 */   127,  211,  212,  189,  189,  211,  212,  189,  189,  211,
+ /*  1390 */   212,   59,  189,  189,  211,  212,   23,  189,   22,   26,
+ /*  1400 */    24,  189,  149,   71,  189,  211,  212,  189,  131,  211,
+ /*  1410 */   212,  189,  189,  136,  137,  211,  212,   85,  189,  211,
+ /*  1420 */   212,   59,   90,  211,  212,  292,  293,  118,  119,  211,
+ /*  1430 */   212,   99,   23,  211,  212,   26,  159,  105,  106,  189,
+ /*  1440 */   211,  212,  143,  150,  112,  152,  114,  115,  116,    1,
+ /*  1450 */     2,  119,   23,    5,   23,   26,  189,   26,   10,   11,
+ /*  1460 */    12,   13,   14,   83,   84,   17,  253,  189,  139,  189,
+ /*  1470 */    19,   20,  189,   22,  189,  189,  140,  115,   30,   59,
+ /*  1480 */    32,  139,  150,  151,  152,  153,  154,   36,   40,  211,
+ /*  1490 */   212,  211,  212,   59,  211,  212,  211,  212,    7,    8,
+ /*  1500 */    19,   20,  189,   22,  150,  189,  152,  231,  281,  189,
+ /*  1510 */    59,  189,   23,  189,  189,   26,  189,   36,   70,  189,
+ /*  1520 */    23,  237,   71,   26,  211,  212,   78,  211,  212,   81,
+ /*  1530 */   189,  211,  212,  211,  212,  115,  211,  212,  211,  212,
+ /*  1540 */    59,  211,  212,   23,   23,   97,   26,   26,   23,  115,
+ /*  1550 */    99,   26,   71,  189,  189,  189,  105,  106,  107,   23,
+ /*  1560 */   189,   23,   26,  112,   26,  114,  115,  116,  189,  309,
+ /*  1570 */   119,   23,   19,   20,   26,   22,  189,  211,  212,  131,
+ /*  1580 */    99,  189,  211,  212,  136,  137,  105,  106,  189,   36,
+ /*  1590 */   211,  212,  189,  112,  189,  114,  115,  116,  211,  212,
+ /*  1600 */   119,  150,  151,  152,  153,  154,  189,  159,   23,  250,
+ /*  1610 */   189,   26,   59,  189,  189,  189,  189,  189,  280,  189,
+ /*  1620 */   250,  189,  189,  238,   71,  189,  189,  250,  211,  212,
+ /*  1630 */   187,  150,  151,  152,  153,  154,  211,  212,  250,  290,
+ /*  1640 */   240,  211,  212,  211,  212,  254,  286,  209,  254,  241,
+ /*  1650 */   240,  254,   99,  286,  215,  220,  214,  244,  105,  106,
+ /*  1660 */   214,  214,  244,  273,  224,  112,  192,  114,  115,  116,
+ /*  1670 */    60,  290,  119,    5,  139,  196,  196,   38,   10,   11,
+ /*  1680 */    12,   13,   14,  238,  240,   17,  196,  148,  287,  287,
+ /*  1690 */   276,  113,   22,  146,  143,  245,  147,  244,   30,  241,
+ /*  1700 */    32,   43,  229,  150,  151,  152,  153,  154,   40,  245,
+ /*  1710 */   244,  241,   18,  196,  265,  232,  264,  232,  232,  232,
+ /*  1720 */    18,  195,  265,  241,  264,  241,  196,  229,  229,  241,
+ /*  1730 */   155,   62,  195,  241,   22,  216,  196,  283,   70,  195,
+ /*  1740 */   195,  282,  196,  216,  113,  195,   78,  213,  196,   81,
+ /*  1750 */    64,  222,   22,  124,  213,  213,  162,  111,  303,  142,
+ /*  1760 */   256,  113,  219,  255,  255,   97,  256,  256,  275,  213,
+ /*  1770 */   275,  216,  215,  219,  213,  213,  213,  255,  196,  256,
+ /*  1780 */   222,  216,  216,  255,   91,  308,  308,   82,   22,  196,
+ /*  1790 */   155,  260,  260,  144,  270,  145,   25,  199,   26,  131,
+ /*  1800 */   198,   13,  190,  244,  136,  137,  190,    6,  188,  245,
+ /*  1810 */   241,  243,  245,  242,  188,  188,  202,  208,  217,  208,
+ /*  1820 */   202,  208,  217,  208,  202,    4,    3,  159,  209,  296,
+ /*  1830 */   209,  208,  272,   22,  160,   15,   98,   23,   16,   23,
+ /*  1840 */   137,  128,   24,  148,  140,   20,   16,    1,  142,  140,
+ /*  1850 */   149,  128,   61,   53,   37,  148,   53,   53,   53,  128,
+ /*  1860 */   114,   34,    1,  139,    5,  293,  296,   22,  113,  158,
+ /*  1870 */    68,   75,   41,   26,   68,  139,  113,   24,   20,   19,
+ /*  1880 */   129,  123,   67,   96,   22,   22,   22,   59,   23,   22,
+ /*  1890 */    24,   67,   22,   67,   37,   23,   28,  147,   22,   26,
+ /*  1900 */    23,   23,   23,   23,   22,   24,   23,   22,   24,  139,
+ /*  1910 */    23,   23,  114,   22,  141,   26,   75,   88,   86,   44,
+ /*  1920 */    34,   23,   22,   75,   34,   24,   34,   34,   34,   93,
+ /*  1930 */    34,   26,   26,   34,   23,   23,   23,   23,   23,   11,
+ /*  1940 */    23,   22,   26,   22,   22,  133,   23,   23,   22,   22,
+ /*  1950 */    15,   26,  139,   23,    1,    1,  310,  310,  139,  310,
+ /*  1960 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  1970 */   310,  310,  139,  139,  310,  310,  310,  310,  310,  310,
+ /*  1980 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  1990 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2000 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2010 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2020 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2030 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2040 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2050 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2060 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2070 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2080 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2090 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2100 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2110 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2120 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2130 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2140 */   310,  310,  310,  310,  310,  310,  310,  310,  310,  310,
+ /*  2150 */   310,  310,  310,  310,  310,
 };
-#define YY_SHIFT_COUNT    (546)
+#define YY_SHIFT_COUNT    (556)
 #define YY_SHIFT_MIN      (0)
-#define YY_SHIFT_MAX      (1912)
+#define YY_SHIFT_MAX      (1954)
 static const unsigned short int yy_shift_ofst[] = {
- /*     0 */  1350, 1149, 1531,  939,  939,  548,  996, 1150, 1236, 1322,
- /*    10 */  1322, 1322,  334,    0,    0,  178,  777, 1322, 1322, 1322,
- /*    20 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
- /*    30 */   991,  991, 1125, 1125,  447,  597,  548,  548,  548,  548,
- /*    40 */   548,  548,   40,  108,  217,  284,  323,  390,  429,  496,
- /*    50 */   535,  602,  641,  757,  777,  777,  777,  777,  777,  777,
- /*    60 */   777,  777,  777,  777,  777,  777,  777,  777,  777,  777,
- /*    70 */   777,  777,  796,  777,  887,  900,  900, 1300, 1322, 1322,
- /*    80 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
- /*    90 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
- /*   100 */  1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
- /*   110 */  1418, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322, 1322,
- /*   120 */  1322, 1322, 1322, 1322,  147,  254,  254,  254,  254,  254,
- /*   130 */    84,  185,   66,  853,  958, 1121,  853,   92,   92,  853,
- /*   140 */   321,  321,  321,  321,  325,  350,  350,  461,  150, 1918,
- /*   150 */  1918,  285,  285,  285,  236,  184,  349,  184,  184,  712,
- /*   160 */   712,  433,  553,  771,  899,  853,  853,  853,  853,  853,
- /*   170 */   853,  853,  853,  853,  853,  853,  853,  853,  853,  853,
- /*   180 */   853,  853,  853,  853,  853,  853,   46,   46,  853,  113,
- /*   190 */   223,  223, 1183, 1183, 1127, 1142, 1918, 1918, 1918,  459,
- /*   200 */   514,  514,  653,  495,  657,  305,  705,  560,  622,  776,
- /*   210 */   853,  853,  853,  853,  853,  853,  853,  853,  853,  545,
- /*   220 */   853,  853,  853,  853,  853,  853,  853,  853,  853,  853,
- /*   230 */   853,  853, 1002, 1002, 1002,  853,  853,  853,  853, 1111,
- /*   240 */   853,  853,  853, 1006, 1109,  853,  853, 1168,  853,  853,
- /*   250 */   853,  853,  853,  853,  853,  853,  845, 1164,  738,  953,
- /*   260 */   953,  953,  953, 1196,  738,  738,   45,   96,  964,  179,
- /*   270 */   580,  907,  907, 1073,  580,  580, 1073,  498,  388, 1268,
- /*   280 */  1187, 1187, 1187,  907, 1170, 1170, 1058, 1180,  328, 1219,
- /*   290 */  1597, 1521, 1521, 1625, 1625, 1521, 1524, 1560, 1650, 1529,
- /*   300 */  1533, 1632, 1529, 1533, 1538, 1667, 1667, 1667, 1667, 1521,
- /*   310 */  1673, 1538, 1538, 1560, 1650, 1632, 1632, 1538, 1521, 1673,
- /*   320 */  1548, 1643, 1521, 1673, 1687, 1521, 1673, 1521, 1673, 1687,
- /*   330 */  1605, 1605, 1605, 1653, 1687, 1605, 1601, 1605, 1653, 1605,
- /*   340 */  1605, 1566, 1687, 1621, 1621, 1687, 1591, 1626, 1591, 1626,
- /*   350 */  1591, 1626, 1591, 1626, 1521, 1655, 1655, 1668, 1668, 1529,
- /*   360 */  1533, 1729, 1521, 1603, 1529, 1614, 1617, 1538, 1735, 1737,
- /*   370 */  1752, 1752, 1762, 1762, 1762, 1918, 1918, 1918, 1918, 1918,
- /*   380 */  1918, 1918, 1918, 1918, 1918, 1918, 1918, 1918, 1918, 1918,
- /*   390 */   673,  901,  283,  740,  707,  973,  655, 1247, 1048, 1097,
- /*   400 */  1190, 1306, 1263, 1383, 1395, 1432, 1469, 1473, 1497, 1279,
- /*   410 */  1200, 1323, 1075, 1286, 1536, 1608, 1332, 1609, 1175, 1225,
- /*   420 */  1610, 1615, 1309, 1361, 1786, 1789, 1772, 1638, 1782, 1702,
- /*   430 */  1783, 1777, 1778, 1669, 1656, 1677, 1781, 1670, 1787, 1666,
- /*   440 */  1793, 1809, 1674, 1664, 1688, 1754, 1776, 1671, 1763, 1765,
- /*   450 */  1766, 1767, 1695, 1710, 1790, 1686, 1824, 1821, 1805, 1717,
- /*   460 */  1675, 1761, 1804, 1764, 1758, 1794, 1697, 1725, 1813, 1818,
- /*   470 */  1820, 1713, 1720, 1822, 1775, 1823, 1825, 1826, 1828, 1779,
- /*   480 */  1815, 1829, 1785, 1811, 1830, 1709, 1833, 1834, 1835, 1836,
- /*   490 */  1837, 1838, 1840, 1832, 1841, 1843, 1842, 1723, 1844, 1845,
- /*   500 */  1757, 1839, 1848, 1732, 1846, 1847, 1849, 1850, 1851, 1788,
- /*   510 */  1799, 1791, 1831, 1803, 1795, 1852, 1856, 1858, 1863, 1864,
- /*   520 */  1865, 1855, 1859, 1846, 1869, 1870, 1871, 1872, 1873, 1874,
- /*   530 */  1876, 1885, 1878, 1879, 1880, 1881, 1883, 1884, 1882, 1771,
- /*   540 */  1770, 1773, 1774, 1780, 1886, 1897, 1912,
+ /*     0 */  1448, 1277, 1668, 1072, 1072,  340, 1122, 1225, 1332, 1481,
+ /*    10 */  1481, 1481,  335,    0,    0,  180,  897, 1481, 1481, 1481,
+ /*    20 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /*    30 */   930,  930, 1020, 1020,  290,    1,  340,  340,  340,  340,
+ /*    40 */   340,  340,   40,  110,  219,  288,  327,  396,  435,  504,
+ /*    50 */   543,  612,  651,  720,  877,  897,  897,  897,  897,  897,
+ /*    60 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
+ /*    70 */   897,  897,  897,  917,  897, 1019,  763,  763, 1451, 1481,
+ /*    80 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /*    90 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /*   100 */  1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /*   110 */  1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
+ /*   120 */  1481, 1481, 1481, 1481, 1481, 1481,  147,  258,  258,  258,
+ /*   130 */   258,  258,   79,   65,   84,  449,   19,  786,  449,  636,
+ /*   140 */   636,  449,  880,  880,  880,  880,  113,  142,  142,  472,
+ /*   150 */   150, 1974, 1974,  399,  399,  399,   93,  237,  341,  237,
+ /*   160 */   237, 1074, 1074,  437,  350,  704, 1080,  449,  449,  449,
+ /*   170 */   449,  449,  449,  449,  449,  449,  449,  449,  449,  449,
+ /*   180 */   449,  449,  449,  449,  449,  449,  449,  449,  818,  818,
+ /*   190 */   449, 1088,  217,  217,  734,  734, 1124, 1126, 1974, 1974,
+ /*   200 */  1974,  739,  840,  840,  453,  454,  511,  187,  563,  570,
+ /*   210 */   898,  669,  449,  449,  449,  449,  449,  449,  449,  449,
+ /*   220 */   449,  670,  449,  449,  449,  449,  449,  449,  449,  449,
+ /*   230 */   449,  449,  449,  449,  674,  674,  674,  449,  449,  449,
+ /*   240 */   449, 1034,  449,  449,  449,  972, 1107,  449,  449, 1193,
+ /*   250 */   449,  449,  449,  449,  449,  449,  449,  449,  260,  177,
+ /*   260 */   489, 1241, 1241, 1241, 1241, 1192,  489,  489,  952, 1197,
+ /*   270 */   625, 1235, 1131,  181,  181, 1086, 1139, 1131, 1086, 1187,
+ /*   280 */  1319, 1237, 1318, 1318, 1318,  181, 1299, 1299, 1109, 1336,
+ /*   290 */   549, 1376, 1610, 1535, 1535, 1639, 1639, 1535, 1539, 1578,
+ /*   300 */  1670, 1547, 1551, 1549, 1658, 1547, 1551, 1549, 1694, 1694,
+ /*   310 */  1694, 1694, 1535, 1702, 1549, 1549, 1578, 1670, 1658, 1549,
+ /*   320 */  1658, 1549, 1535, 1702, 1575, 1669, 1535, 1702, 1712, 1535,
+ /*   330 */  1702, 1535, 1702, 1712, 1631, 1631, 1631, 1686, 1730, 1730,
+ /*   340 */  1712, 1631, 1629, 1631, 1686, 1631, 1631, 1594, 1712, 1646,
+ /*   350 */  1646, 1712, 1617, 1648, 1617, 1648, 1617, 1648, 1617, 1648,
+ /*   360 */  1535, 1693, 1693, 1705, 1705, 1547, 1551, 1766, 1535, 1635,
+ /*   370 */  1547, 1650, 1649, 1549, 1771, 1772, 1788, 1788, 1801, 1801,
+ /*   380 */  1801, 1974, 1974, 1974, 1974, 1974, 1974, 1974, 1974, 1974,
+ /*   390 */  1974, 1974, 1974, 1974, 1974, 1974,  308,  835,  954, 1232,
+ /*   400 */   879,  715,  728, 1373,  864, 1329, 1253, 1409,  297, 1431,
+ /*   410 */  1489, 1497, 1520, 1521, 1525, 1362, 1309, 1491, 1217, 1420,
+ /*   420 */  1429, 1536, 1380, 1538, 1293, 1354, 1548, 1585, 1434, 1342,
+ /*   430 */  1821, 1823, 1811, 1674, 1820, 1738, 1822, 1814, 1816, 1703,
+ /*   440 */  1695, 1713, 1818, 1704, 1825, 1706, 1830, 1846, 1709, 1701,
+ /*   450 */  1723, 1791, 1817, 1707, 1800, 1803, 1804, 1805, 1731, 1746,
+ /*   460 */  1827, 1724, 1861, 1859, 1845, 1755, 1711, 1802, 1847, 1806,
+ /*   470 */  1796, 1831, 1736, 1763, 1853, 1858, 1860, 1751, 1758, 1862,
+ /*   480 */  1815, 1863, 1864, 1865, 1867, 1824, 1828, 1866, 1787, 1868,
+ /*   490 */  1870, 1826, 1857, 1872, 1750, 1876, 1877, 1878, 1879, 1873,
+ /*   500 */  1880, 1882, 1881, 1883, 1885, 1884, 1770, 1887, 1888, 1798,
+ /*   510 */  1886, 1891, 1773, 1889, 1890, 1892, 1893, 1894, 1829, 1841,
+ /*   520 */  1832, 1875, 1848, 1836, 1896, 1898, 1900, 1901, 1905, 1906,
+ /*   530 */  1899, 1911, 1889, 1912, 1913, 1914, 1915, 1916, 1917, 1919,
+ /*   540 */  1928, 1921, 1922, 1923, 1924, 1926, 1927, 1925, 1812, 1813,
+ /*   550 */  1819, 1833, 1834, 1930, 1935, 1953, 1954,
 };
-#define YY_REDUCE_COUNT (389)
-#define YY_REDUCE_MIN   (-256)
-#define YY_REDUCE_MAX   (1593)
+#define YY_REDUCE_COUNT (395)
+#define YY_REDUCE_MIN   (-262)
+#define YY_REDUCE_MAX   (1627)
 static const short yy_reduce_ofst[] = {
- /*     0 */   880, -121,  269,  528,  933, -119, -187, -185, -182, -180,
- /*    10 */  -176, -174,  -62,  -46,  131, -248, -133,  407,  568,  700,
- /*    20 */   704,  278,  706,  824,  542,  830,  948,  773,  943,  946,
- /*    30 */    71,  650,  211,  267,  826,  272,  676,  732,  885,  976,
- /*    40 */   984,  992, -256, -256, -256, -256, -256, -256, -256, -256,
- /*    50 */  -256, -256, -256, -256, -256, -256, -256, -256, -256, -256,
- /*    60 */  -256, -256, -256, -256, -256, -256, -256, -256, -256, -256,
- /*    70 */  -256, -256, -256, -256, -256, -256, -256,  989, 1065, 1070,
- /*    80 */  1072, 1078, 1082, 1084, 1103, 1118, 1147, 1156, 1160, 1167,
- /*    90 */  1185, 1191, 1220, 1237, 1254, 1256, 1266, 1272, 1281, 1291,
- /*   100 */  1293, 1296, 1299, 1301, 1307, 1337, 1340, 1342, 1347, 1366,
- /*   110 */  1368, 1371, 1373, 1377, 1385, 1387, 1398, 1401, 1404, 1406,
- /*   120 */  1411, 1413, 1415, 1430, -256, -256, -256, -256, -256, -256,
- /*   130 */  -256, -256, -256, -172,  508, -213,   57, -163,  -25,  593,
- /*   140 */    69,  486,   69,  486, -200,  573,  722, -256, -256, -256,
- /*   150 */  -256, -141, -141, -141, -105, -161, -167,  157,  212,  405,
- /*   160 */   530,  220,  233,  735,  735,  115,  318,  406,  612,  541,
- /*   170 */  -166,  441,  688,  794,  629,  368,  741,  775,  867,  797,
- /*   180 */   871,  842, -186, 1000,  858,  949,  379,  783,   70,  296,
- /*   190 */   821,  903,  924, 1044,  651,  282, 1014, 1060,  937, -195,
- /*   200 */  -177,  413,  439,  511,  566,  787,  827,  848,  898,  945,
- /*   210 */  1062, 1074, 1102, 1110, 1202, 1204, 1209, 1211, 1215,  529,
- /*   220 */  1221, 1224, 1240, 1246, 1255, 1257, 1269, 1270, 1273, 1274,
- /*   230 */  1275, 1280, 1205, 1251, 1294, 1310, 1317, 1326, 1327, 1124,
- /*   240 */  1331, 1338, 1339, 1290, 1181, 1346, 1351, 1265, 1352,  787,
- /*   250 */  1353, 1367, 1378, 1386, 1392, 1397, 1241, 1312, 1356, 1345,
- /*   260 */  1357, 1358, 1359, 1124, 1356, 1356, 1364, 1396, 1433, 1341,
- /*   270 */  1381, 1376, 1379, 1354, 1391, 1405, 1362, 1429, 1423, 1431,
- /*   280 */  1434, 1435, 1437, 1399, 1410, 1412, 1382, 1417, 1420, 1466,
- /*   290 */  1372, 1467, 1468, 1380, 1384, 1475, 1394, 1414, 1416, 1436,
- /*   300 */  1438, 1454, 1439, 1441, 1446, 1457, 1458, 1460, 1461, 1498,
- /*   310 */  1500, 1456, 1459, 1440, 1442, 1470, 1472, 1462, 1501, 1506,
- /*   320 */  1424, 1427, 1513, 1515, 1496, 1517, 1519, 1520, 1522, 1499,
- /*   330 */  1507, 1508, 1509, 1502, 1510, 1511, 1512, 1516, 1514, 1518,
- /*   340 */  1523, 1428, 1525, 1463, 1464, 1526, 1479, 1486, 1488, 1490,
- /*   350 */  1491, 1493, 1494, 1503, 1549, 1443, 1444, 1495, 1504, 1527,
- /*   360 */  1530, 1487, 1559, 1489, 1528, 1532, 1534, 1537, 1565, 1568,
- /*   370 */  1578, 1579, 1588, 1590, 1592, 1484, 1492, 1505, 1580, 1573,
- /*   380 */  1575, 1576, 1577, 1584, 1571, 1572, 1581, 1582, 1585, 1593,
+ /*     0 */   490, -122,  545,  645,  650, -120, -189, -187, -184, -182,
+ /*    10 */  -178, -176,   45,   30,  200, -251, -134,  390,  392,  521,
+ /*    20 */   523,  213,  692,  821,  284,  589,  872,  666,  671,  866,
+ /*    30 */    71,  111,  273,  389,  686,  815,  904,  932,  948,  955,
+ /*    40 */   964,  969, -259, -259, -259, -259, -259, -259, -259, -259,
+ /*    50 */  -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
+ /*    60 */  -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
+ /*    70 */  -259, -259, -259, -259, -259, -259, -259, -259,  428,  430,
+ /*    80 */   899,  985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115,
+ /*    90 */  1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194,
+ /*   100 */  1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283,
+ /*   110 */  1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371,
+ /*   120 */  1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259,
+ /*   130 */  -259, -259, -259, -259, -259,  557,  974, -214, -174,   -9,
+ /*   140 */   431, -124,  806,  925,  806,  925,  251,  928,  940, -259,
+ /*   150 */  -259, -259, -259, -198, -198, -198,  127, -186, -168,  212,
+ /*   160 */   646,  617,  799, -262,  555,  220,  220,  491,  605, 1040,
+ /*   170 */  1060,  699,  -11,  600,  848,  862,  345, -129,  724,  -91,
+ /*   180 */   158,  749,  716,  900,  304,  822,  929,  926,  499,  793,
+ /*   190 */   322,  892,  813,  845,  958, 1056,  751,  905, 1133, 1062,
+ /*   200 */   803, -210, -185, -179, -148, -167,  -89,  121,  274,  281,
+ /*   210 */   320,  336,  439,  663,  711,  957,  965, 1064, 1068, 1112,
+ /*   220 */  1116, -196, 1127, 1134, 1180, 1184, 1195, 1199, 1203, 1215,
+ /*   230 */  1223, 1250, 1267, 1286,  205,  422,  638, 1324, 1341, 1364,
+ /*   240 */  1365, 1213, 1392, 1399, 1403,  869, 1260, 1405, 1421, 1276,
+ /*   250 */  1424,  121, 1426, 1427, 1428, 1433, 1436, 1437, 1227, 1338,
+ /*   260 */  1284, 1359, 1370, 1377, 1388, 1213, 1284, 1284, 1385, 1438,
+ /*   270 */  1443, 1349, 1400, 1391, 1394, 1360, 1408, 1410, 1367, 1439,
+ /*   280 */  1440, 1435, 1442, 1446, 1447, 1397, 1413, 1418, 1390, 1444,
+ /*   290 */  1445, 1474, 1381, 1479, 1480, 1401, 1402, 1490, 1414, 1449,
+ /*   300 */  1452, 1450, 1453, 1458, 1473, 1464, 1466, 1470, 1483, 1485,
+ /*   310 */  1486, 1487, 1517, 1526, 1482, 1484, 1457, 1460, 1498, 1488,
+ /*   320 */  1499, 1492, 1530, 1537, 1454, 1459, 1540, 1544, 1519, 1546,
+ /*   330 */  1545, 1552, 1550, 1527, 1534, 1541, 1542, 1529, 1543, 1554,
+ /*   340 */  1555, 1556, 1557, 1561, 1558, 1562, 1563, 1455, 1565, 1493,
+ /*   350 */  1495, 1566, 1504, 1508, 1510, 1509, 1511, 1522, 1523, 1528,
+ /*   360 */  1582, 1477, 1478, 1531, 1532, 1564, 1559, 1524, 1593, 1560,
+ /*   370 */  1567, 1568, 1571, 1569, 1598, 1602, 1612, 1616, 1620, 1626,
+ /*   380 */  1627, 1533, 1570, 1572, 1614, 1609, 1611, 1613, 1615, 1618,
+ /*   390 */  1601, 1605, 1619, 1621, 1623, 1622,
 };
 static const YYACTIONTYPE yy_default[] = {
- /*     0 */  1558, 1558, 1558, 1396, 1175, 1282, 1175, 1175, 1175, 1396,
- /*    10 */  1396, 1396, 1175, 1312, 1312, 1449, 1206, 1175, 1175, 1175,
- /*    20 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1395, 1175, 1175,
- /*    30 */  1175, 1175, 1479, 1479, 1175, 1175, 1175, 1175, 1175, 1175,
- /*    40 */  1175, 1175, 1175, 1321, 1175, 1175, 1175, 1175, 1175, 1397,
- /*    50 */  1398, 1175, 1175, 1175, 1448, 1450, 1413, 1331, 1330, 1329,
- /*    60 */  1328, 1431, 1299, 1326, 1319, 1323, 1391, 1392, 1390, 1394,
- /*    70 */  1398, 1397, 1175, 1322, 1362, 1376, 1361, 1175, 1175, 1175,
- /*    80 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*    90 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   100 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   110 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   120 */  1175, 1175, 1175, 1175, 1370, 1375, 1381, 1374, 1371, 1364,
- /*   130 */  1363, 1365, 1366, 1175, 1196, 1246, 1175, 1175, 1175, 1175,
- /*   140 */  1467, 1466, 1175, 1175, 1206, 1356, 1355, 1367, 1368, 1378,
- /*   150 */  1377, 1456, 1514, 1513, 1414, 1175, 1175, 1175, 1175, 1175,
- /*   160 */  1175, 1479, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   170 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   180 */  1175, 1175, 1175, 1175, 1175, 1175, 1479, 1479, 1175, 1206,
- /*   190 */  1479, 1479, 1202, 1202, 1306, 1175, 1462, 1282, 1273, 1175,
- /*   200 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   210 */  1175, 1175, 1175, 1453, 1451, 1175, 1175, 1175, 1175, 1175,
- /*   220 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   230 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   240 */  1175, 1175, 1175, 1278, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   250 */  1175, 1175, 1175, 1175, 1175, 1508, 1175, 1426, 1260, 1278,
- /*   260 */  1278, 1278, 1278, 1280, 1261, 1259, 1272, 1207, 1182, 1550,
- /*   270 */  1325, 1301, 1301, 1547, 1325, 1325, 1547, 1221, 1528, 1218,
- /*   280 */  1312, 1312, 1312, 1301, 1306, 1306, 1393, 1279, 1272, 1175,
- /*   290 */  1550, 1287, 1287, 1549, 1549, 1287, 1414, 1334, 1340, 1320,
- /*   300 */  1306, 1249, 1320, 1306, 1325, 1255, 1255, 1255, 1255, 1287,
- /*   310 */  1193, 1325, 1325, 1334, 1340, 1249, 1249, 1325, 1287, 1193,
- /*   320 */  1430, 1544, 1287, 1193, 1404, 1287, 1193, 1287, 1193, 1404,
- /*   330 */  1247, 1247, 1247, 1236, 1404, 1247, 1221, 1247, 1236, 1247,
- /*   340 */  1247, 1497, 1404, 1408, 1408, 1404, 1305, 1300, 1305, 1300,
- /*   350 */  1305, 1300, 1305, 1300, 1287, 1489, 1489, 1315, 1315, 1320,
- /*   360 */  1306, 1399, 1287, 1175, 1320, 1318, 1316, 1325, 1199, 1239,
- /*   370 */  1511, 1511, 1507, 1507, 1507, 1555, 1555, 1462, 1523, 1206,
- /*   380 */  1206, 1206, 1206, 1523, 1223, 1223, 1207, 1207, 1206, 1523,
- /*   390 */  1175, 1175, 1175, 1175, 1175, 1175, 1518, 1175, 1415, 1291,
- /*   400 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   410 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   420 */  1175, 1175, 1175, 1345, 1175, 1178, 1459, 1175, 1175, 1457,
- /*   430 */  1175, 1175, 1175, 1175, 1175, 1175, 1292, 1175, 1175, 1175,
- /*   440 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   450 */  1175, 1175, 1175, 1175, 1175, 1546, 1175, 1175, 1175, 1175,
- /*   460 */  1175, 1175, 1429, 1428, 1175, 1175, 1289, 1175, 1175, 1175,
- /*   470 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   480 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   490 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   500 */  1175, 1175, 1175, 1175, 1317, 1175, 1175, 1175, 1175, 1175,
- /*   510 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1494,
- /*   520 */  1307, 1175, 1175, 1537, 1175, 1175, 1175, 1175, 1175, 1175,
- /*   530 */  1175, 1175, 1175, 1175, 1175, 1175, 1175, 1175, 1532, 1263,
- /*   540 */  1347, 1175, 1346, 1350, 1175, 1187, 1175,
+ /*     0 */  1579, 1579, 1579, 1415, 1192, 1301, 1192, 1192, 1192, 1415,
+ /*    10 */  1415, 1415, 1192, 1331, 1331, 1468, 1223, 1192, 1192, 1192,
+ /*    20 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1414, 1192, 1192,
+ /*    30 */  1192, 1192, 1498, 1498, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*    40 */  1192, 1192, 1192, 1340, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*    50 */  1416, 1417, 1192, 1192, 1192, 1467, 1469, 1432, 1350, 1349,
+ /*    60 */  1348, 1347, 1450, 1318, 1345, 1338, 1342, 1410, 1411, 1409,
+ /*    70 */  1413, 1417, 1416, 1192, 1341, 1381, 1395, 1380, 1192, 1192,
+ /*    80 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*    90 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   100 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   110 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   120 */  1192, 1192, 1192, 1192, 1192, 1192, 1389, 1394, 1400, 1393,
+ /*   130 */  1390, 1383, 1382, 1384, 1385, 1192, 1213, 1265, 1192, 1192,
+ /*   140 */  1192, 1192, 1486, 1485, 1192, 1192, 1223, 1375, 1374, 1386,
+ /*   150 */  1387, 1397, 1396, 1475, 1533, 1532, 1433, 1192, 1192, 1192,
+ /*   160 */  1192, 1192, 1192, 1498, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   170 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   180 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1498, 1498,
+ /*   190 */  1192, 1223, 1498, 1498, 1219, 1219, 1325, 1192, 1481, 1301,
+ /*   200 */  1292, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   210 */  1192, 1192, 1192, 1192, 1192, 1472, 1470, 1192, 1192, 1192,
+ /*   220 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   230 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   240 */  1192, 1192, 1192, 1192, 1192, 1297, 1192, 1192, 1192, 1192,
+ /*   250 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1527, 1192, 1445,
+ /*   260 */  1279, 1297, 1297, 1297, 1297, 1299, 1280, 1278, 1291, 1224,
+ /*   270 */  1199, 1571, 1298, 1320, 1320, 1568, 1344, 1298, 1568, 1240,
+ /*   280 */  1549, 1235, 1331, 1331, 1331, 1320, 1325, 1325, 1412, 1298,
+ /*   290 */  1291, 1192, 1571, 1306, 1306, 1570, 1570, 1306, 1433, 1353,
+ /*   300 */  1359, 1339, 1325, 1344, 1268, 1339, 1325, 1344, 1274, 1274,
+ /*   310 */  1274, 1274, 1306, 1210, 1344, 1344, 1353, 1359, 1268, 1344,
+ /*   320 */  1268, 1344, 1306, 1210, 1449, 1565, 1306, 1210, 1423, 1306,
+ /*   330 */  1210, 1306, 1210, 1423, 1266, 1266, 1266, 1255, 1192, 1192,
+ /*   340 */  1423, 1266, 1240, 1266, 1255, 1266, 1266, 1516, 1423, 1427,
+ /*   350 */  1427, 1423, 1324, 1319, 1324, 1319, 1324, 1319, 1324, 1319,
+ /*   360 */  1306, 1508, 1508, 1334, 1334, 1339, 1325, 1418, 1306, 1192,
+ /*   370 */  1339, 1337, 1335, 1344, 1216, 1258, 1530, 1530, 1526, 1526,
+ /*   380 */  1526, 1576, 1576, 1481, 1542, 1223, 1223, 1223, 1223, 1542,
+ /*   390 */  1242, 1242, 1224, 1224, 1223, 1542, 1192, 1192, 1192, 1192,
+ /*   400 */  1192, 1192, 1537, 1192, 1434, 1310, 1192, 1192, 1192, 1192,
+ /*   410 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   420 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1364,
+ /*   430 */  1192, 1195, 1478, 1192, 1192, 1476, 1192, 1192, 1192, 1192,
+ /*   440 */  1192, 1192, 1311, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   450 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   460 */  1192, 1567, 1192, 1192, 1192, 1192, 1192, 1192, 1448, 1447,
+ /*   470 */  1192, 1192, 1308, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   480 */  1192, 1192, 1192, 1192, 1192, 1192, 1238, 1192, 1192, 1192,
+ /*   490 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   500 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   510 */  1192, 1192, 1192, 1336, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   520 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1192, 1513, 1326,
+ /*   530 */  1192, 1192, 1558, 1192, 1192, 1192, 1192, 1192, 1192, 1192,
+ /*   540 */  1192, 1192, 1192, 1192, 1192, 1192, 1192, 1553, 1282, 1366,
+ /*   550 */  1192, 1365, 1369, 1192, 1204, 1192, 1192,
 };
 /********** End of lemon-generated parsing tables *****************************/
 
-/* The next table maps tokens (terminal symbols) into fallback tokens.  
+/* The next table maps tokens (terminal symbols) into fallback tokens.
 ** If a construct like the following:
-** 
+**
 **      %fallback ID X Y Z.
 **
 ** appears in the grammar, then ID becomes a fallback token for X, Y,
@@ -150972,6 +156302,8 @@ static const YYCODETYPE yyFallback[] = {
    59,  /*     GROUPS => ID */
    59,  /*     OTHERS => ID */
    59,  /*       TIES => ID */
+   59,  /*  GENERATED => ID */
+   59,  /*     ALWAYS => ID */
    59,  /*    REINDEX => ID */
    59,  /*     RENAME => ID */
    59,  /*   CTIME_KW => ID */
@@ -151109,15 +156441,16 @@ typedef struct yyParser yyParser;
 
 #ifndef NDEBUG
 /* #include <stdio.h> */
+/* #include <assert.h> */
 static FILE *yyTraceFILE = 0;
 static char *yyTracePrompt = 0;
 #endif /* NDEBUG */
 
 #ifndef NDEBUG
-/* 
+/*
 ** Turn parser tracing on by giving a stream to which to write the trace
 ** and a prompt to preface each trace message.  Tracing is turned off
-** by making either argument NULL 
+** by making either argument NULL
 **
 ** Inputs:
 ** <ul>
@@ -151142,7 +156475,7 @@ SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
 #if defined(YYCOVERAGE) || !defined(NDEBUG)
 /* For tracing shifts, the names of all terminals and nonterminals
 ** are required.  The following table supplies these names */
-static const char *const yyTokenName[] = { 
+static const char *const yyTokenName[] = {
   /*    0 */ "$",
   /*    1 */ "SEMI",
   /*    2 */ "EXPLAIN",
@@ -151238,218 +156571,221 @@ static const char *const yyTokenName[] = {
   /*   92 */ "GROUPS",
   /*   93 */ "OTHERS",
   /*   94 */ "TIES",
-  /*   95 */ "REINDEX",
-  /*   96 */ "RENAME",
-  /*   97 */ "CTIME_KW",
-  /*   98 */ "ANY",
-  /*   99 */ "BITAND",
-  /*  100 */ "BITOR",
-  /*  101 */ "LSHIFT",
-  /*  102 */ "RSHIFT",
-  /*  103 */ "PLUS",
-  /*  104 */ "MINUS",
-  /*  105 */ "STAR",
-  /*  106 */ "SLASH",
-  /*  107 */ "REM",
-  /*  108 */ "CONCAT",
-  /*  109 */ "COLLATE",
-  /*  110 */ "BITNOT",
-  /*  111 */ "ON",
-  /*  112 */ "INDEXED",
-  /*  113 */ "STRING",
-  /*  114 */ "JOIN_KW",
-  /*  115 */ "CONSTRAINT",
-  /*  116 */ "DEFAULT",
-  /*  117 */ "NULL",
-  /*  118 */ "PRIMARY",
-  /*  119 */ "UNIQUE",
-  /*  120 */ "CHECK",
-  /*  121 */ "REFERENCES",
-  /*  122 */ "AUTOINCR",
-  /*  123 */ "INSERT",
-  /*  124 */ "DELETE",
-  /*  125 */ "UPDATE",
-  /*  126 */ "SET",
-  /*  127 */ "DEFERRABLE",
-  /*  128 */ "FOREIGN",
-  /*  129 */ "DROP",
-  /*  130 */ "UNION",
-  /*  131 */ "ALL",
-  /*  132 */ "EXCEPT",
-  /*  133 */ "INTERSECT",
-  /*  134 */ "SELECT",
-  /*  135 */ "VALUES",
-  /*  136 */ "DISTINCT",
-  /*  137 */ "DOT",
-  /*  138 */ "FROM",
-  /*  139 */ "JOIN",
-  /*  140 */ "USING",
-  /*  141 */ "ORDER",
-  /*  142 */ "GROUP",
-  /*  143 */ "HAVING",
-  /*  144 */ "LIMIT",
-  /*  145 */ "WHERE",
-  /*  146 */ "INTO",
-  /*  147 */ "NOTHING",
-  /*  148 */ "FLOAT",
-  /*  149 */ "BLOB",
-  /*  150 */ "INTEGER",
-  /*  151 */ "VARIABLE",
-  /*  152 */ "CASE",
-  /*  153 */ "WHEN",
-  /*  154 */ "THEN",
-  /*  155 */ "ELSE",
-  /*  156 */ "INDEX",
-  /*  157 */ "ALTER",
-  /*  158 */ "ADD",
-  /*  159 */ "WINDOW",
-  /*  160 */ "OVER",
-  /*  161 */ "FILTER",
-  /*  162 */ "COLUMN",
-  /*  163 */ "AGG_FUNCTION",
-  /*  164 */ "AGG_COLUMN",
-  /*  165 */ "TRUEFALSE",
-  /*  166 */ "ISNOT",
-  /*  167 */ "FUNCTION",
-  /*  168 */ "UMINUS",
-  /*  169 */ "UPLUS",
-  /*  170 */ "TRUTH",
-  /*  171 */ "REGISTER",
-  /*  172 */ "VECTOR",
-  /*  173 */ "SELECT_COLUMN",
-  /*  174 */ "IF_NULL_ROW",
-  /*  175 */ "ASTERISK",
-  /*  176 */ "SPAN",
-  /*  177 */ "SPACE",
-  /*  178 */ "ILLEGAL",
-  /*  179 */ "input",
-  /*  180 */ "cmdlist",
-  /*  181 */ "ecmd",
-  /*  182 */ "cmdx",
-  /*  183 */ "explain",
-  /*  184 */ "cmd",
-  /*  185 */ "transtype",
-  /*  186 */ "trans_opt",
-  /*  187 */ "nm",
-  /*  188 */ "savepoint_opt",
-  /*  189 */ "create_table",
-  /*  190 */ "create_table_args",
-  /*  191 */ "createkw",
-  /*  192 */ "temp",
-  /*  193 */ "ifnotexists",
-  /*  194 */ "dbnm",
-  /*  195 */ "columnlist",
-  /*  196 */ "conslist_opt",
-  /*  197 */ "table_options",
-  /*  198 */ "select",
-  /*  199 */ "columnname",
-  /*  200 */ "carglist",
-  /*  201 */ "typetoken",
-  /*  202 */ "typename",
-  /*  203 */ "signed",
-  /*  204 */ "plus_num",
-  /*  205 */ "minus_num",
-  /*  206 */ "scanpt",
-  /*  207 */ "scantok",
-  /*  208 */ "ccons",
-  /*  209 */ "term",
-  /*  210 */ "expr",
-  /*  211 */ "onconf",
-  /*  212 */ "sortorder",
-  /*  213 */ "autoinc",
-  /*  214 */ "eidlist_opt",
-  /*  215 */ "refargs",
-  /*  216 */ "defer_subclause",
-  /*  217 */ "refarg",
-  /*  218 */ "refact",
-  /*  219 */ "init_deferred_pred_opt",
-  /*  220 */ "conslist",
-  /*  221 */ "tconscomma",
-  /*  222 */ "tcons",
-  /*  223 */ "sortlist",
-  /*  224 */ "eidlist",
-  /*  225 */ "defer_subclause_opt",
-  /*  226 */ "orconf",
-  /*  227 */ "resolvetype",
-  /*  228 */ "raisetype",
-  /*  229 */ "ifexists",
-  /*  230 */ "fullname",
-  /*  231 */ "selectnowith",
-  /*  232 */ "oneselect",
-  /*  233 */ "wqlist",
-  /*  234 */ "multiselect_op",
-  /*  235 */ "distinct",
-  /*  236 */ "selcollist",
-  /*  237 */ "from",
-  /*  238 */ "where_opt",
-  /*  239 */ "groupby_opt",
-  /*  240 */ "having_opt",
-  /*  241 */ "orderby_opt",
-  /*  242 */ "limit_opt",
-  /*  243 */ "window_clause",
-  /*  244 */ "values",
-  /*  245 */ "nexprlist",
-  /*  246 */ "sclp",
-  /*  247 */ "as",
-  /*  248 */ "seltablist",
-  /*  249 */ "stl_prefix",
-  /*  250 */ "joinop",
-  /*  251 */ "indexed_opt",
-  /*  252 */ "on_opt",
-  /*  253 */ "using_opt",
-  /*  254 */ "exprlist",
-  /*  255 */ "xfullname",
-  /*  256 */ "idlist",
-  /*  257 */ "nulls",
-  /*  258 */ "with",
-  /*  259 */ "setlist",
-  /*  260 */ "insert_cmd",
-  /*  261 */ "idlist_opt",
-  /*  262 */ "upsert",
-  /*  263 */ "filter_over",
-  /*  264 */ "likeop",
-  /*  265 */ "between_op",
-  /*  266 */ "in_op",
-  /*  267 */ "paren_exprlist",
-  /*  268 */ "case_operand",
-  /*  269 */ "case_exprlist",
-  /*  270 */ "case_else",
-  /*  271 */ "uniqueflag",
-  /*  272 */ "collate",
-  /*  273 */ "vinto",
-  /*  274 */ "nmnum",
-  /*  275 */ "trigger_decl",
-  /*  276 */ "trigger_cmd_list",
-  /*  277 */ "trigger_time",
-  /*  278 */ "trigger_event",
-  /*  279 */ "foreach_clause",
-  /*  280 */ "when_clause",
-  /*  281 */ "trigger_cmd",
-  /*  282 */ "trnm",
-  /*  283 */ "tridxby",
-  /*  284 */ "database_kw_opt",
-  /*  285 */ "key_opt",
-  /*  286 */ "add_column_fullname",
-  /*  287 */ "kwcolumn_opt",
-  /*  288 */ "create_vtab",
-  /*  289 */ "vtabarglist",
-  /*  290 */ "vtabarg",
-  /*  291 */ "vtabargtoken",
-  /*  292 */ "lp",
-  /*  293 */ "anylist",
-  /*  294 */ "windowdefn_list",
-  /*  295 */ "windowdefn",
-  /*  296 */ "window",
-  /*  297 */ "frame_opt",
-  /*  298 */ "part_opt",
-  /*  299 */ "filter_clause",
-  /*  300 */ "over_clause",
-  /*  301 */ "range_or_rows",
-  /*  302 */ "frame_bound",
-  /*  303 */ "frame_bound_s",
-  /*  304 */ "frame_bound_e",
-  /*  305 */ "frame_exclude_opt",
-  /*  306 */ "frame_exclude",
+  /*   95 */ "GENERATED",
+  /*   96 */ "ALWAYS",
+  /*   97 */ "REINDEX",
+  /*   98 */ "RENAME",
+  /*   99 */ "CTIME_KW",
+  /*  100 */ "ANY",
+  /*  101 */ "BITAND",
+  /*  102 */ "BITOR",
+  /*  103 */ "LSHIFT",
+  /*  104 */ "RSHIFT",
+  /*  105 */ "PLUS",
+  /*  106 */ "MINUS",
+  /*  107 */ "STAR",
+  /*  108 */ "SLASH",
+  /*  109 */ "REM",
+  /*  110 */ "CONCAT",
+  /*  111 */ "COLLATE",
+  /*  112 */ "BITNOT",
+  /*  113 */ "ON",
+  /*  114 */ "INDEXED",
+  /*  115 */ "STRING",
+  /*  116 */ "JOIN_KW",
+  /*  117 */ "CONSTRAINT",
+  /*  118 */ "DEFAULT",
+  /*  119 */ "NULL",
+  /*  120 */ "PRIMARY",
+  /*  121 */ "UNIQUE",
+  /*  122 */ "CHECK",
+  /*  123 */ "REFERENCES",
+  /*  124 */ "AUTOINCR",
+  /*  125 */ "INSERT",
+  /*  126 */ "DELETE",
+  /*  127 */ "UPDATE",
+  /*  128 */ "SET",
+  /*  129 */ "DEFERRABLE",
+  /*  130 */ "FOREIGN",
+  /*  131 */ "DROP",
+  /*  132 */ "UNION",
+  /*  133 */ "ALL",
+  /*  134 */ "EXCEPT",
+  /*  135 */ "INTERSECT",
+  /*  136 */ "SELECT",
+  /*  137 */ "VALUES",
+  /*  138 */ "DISTINCT",
+  /*  139 */ "DOT",
+  /*  140 */ "FROM",
+  /*  141 */ "JOIN",
+  /*  142 */ "USING",
+  /*  143 */ "ORDER",
+  /*  144 */ "GROUP",
+  /*  145 */ "HAVING",
+  /*  146 */ "LIMIT",
+  /*  147 */ "WHERE",
+  /*  148 */ "INTO",
+  /*  149 */ "NOTHING",
+  /*  150 */ "FLOAT",
+  /*  151 */ "BLOB",
+  /*  152 */ "INTEGER",
+  /*  153 */ "VARIABLE",
+  /*  154 */ "CASE",
+  /*  155 */ "WHEN",
+  /*  156 */ "THEN",
+  /*  157 */ "ELSE",
+  /*  158 */ "INDEX",
+  /*  159 */ "ALTER",
+  /*  160 */ "ADD",
+  /*  161 */ "WINDOW",
+  /*  162 */ "OVER",
+  /*  163 */ "FILTER",
+  /*  164 */ "COLUMN",
+  /*  165 */ "AGG_FUNCTION",
+  /*  166 */ "AGG_COLUMN",
+  /*  167 */ "TRUEFALSE",
+  /*  168 */ "ISNOT",
+  /*  169 */ "FUNCTION",
+  /*  170 */ "UMINUS",
+  /*  171 */ "UPLUS",
+  /*  172 */ "TRUTH",
+  /*  173 */ "REGISTER",
+  /*  174 */ "VECTOR",
+  /*  175 */ "SELECT_COLUMN",
+  /*  176 */ "IF_NULL_ROW",
+  /*  177 */ "ASTERISK",
+  /*  178 */ "SPAN",
+  /*  179 */ "SPACE",
+  /*  180 */ "ILLEGAL",
+  /*  181 */ "input",
+  /*  182 */ "cmdlist",
+  /*  183 */ "ecmd",
+  /*  184 */ "cmdx",
+  /*  185 */ "explain",
+  /*  186 */ "cmd",
+  /*  187 */ "transtype",
+  /*  188 */ "trans_opt",
+  /*  189 */ "nm",
+  /*  190 */ "savepoint_opt",
+  /*  191 */ "create_table",
+  /*  192 */ "create_table_args",
+  /*  193 */ "createkw",
+  /*  194 */ "temp",
+  /*  195 */ "ifnotexists",
+  /*  196 */ "dbnm",
+  /*  197 */ "columnlist",
+  /*  198 */ "conslist_opt",
+  /*  199 */ "table_options",
+  /*  200 */ "select",
+  /*  201 */ "columnname",
+  /*  202 */ "carglist",
+  /*  203 */ "typetoken",
+  /*  204 */ "typename",
+  /*  205 */ "signed",
+  /*  206 */ "plus_num",
+  /*  207 */ "minus_num",
+  /*  208 */ "scanpt",
+  /*  209 */ "scantok",
+  /*  210 */ "ccons",
+  /*  211 */ "term",
+  /*  212 */ "expr",
+  /*  213 */ "onconf",
+  /*  214 */ "sortorder",
+  /*  215 */ "autoinc",
+  /*  216 */ "eidlist_opt",
+  /*  217 */ "refargs",
+  /*  218 */ "defer_subclause",
+  /*  219 */ "generated",
+  /*  220 */ "refarg",
+  /*  221 */ "refact",
+  /*  222 */ "init_deferred_pred_opt",
+  /*  223 */ "conslist",
+  /*  224 */ "tconscomma",
+  /*  225 */ "tcons",
+  /*  226 */ "sortlist",
+  /*  227 */ "eidlist",
+  /*  228 */ "defer_subclause_opt",
+  /*  229 */ "orconf",
+  /*  230 */ "resolvetype",
+  /*  231 */ "raisetype",
+  /*  232 */ "ifexists",
+  /*  233 */ "fullname",
+  /*  234 */ "selectnowith",
+  /*  235 */ "oneselect",
+  /*  236 */ "wqlist",
+  /*  237 */ "multiselect_op",
+  /*  238 */ "distinct",
+  /*  239 */ "selcollist",
+  /*  240 */ "from",
+  /*  241 */ "where_opt",
+  /*  242 */ "groupby_opt",
+  /*  243 */ "having_opt",
+  /*  244 */ "orderby_opt",
+  /*  245 */ "limit_opt",
+  /*  246 */ "window_clause",
+  /*  247 */ "values",
+  /*  248 */ "nexprlist",
+  /*  249 */ "sclp",
+  /*  250 */ "as",
+  /*  251 */ "seltablist",
+  /*  252 */ "stl_prefix",
+  /*  253 */ "joinop",
+  /*  254 */ "indexed_opt",
+  /*  255 */ "on_opt",
+  /*  256 */ "using_opt",
+  /*  257 */ "exprlist",
+  /*  258 */ "xfullname",
+  /*  259 */ "idlist",
+  /*  260 */ "nulls",
+  /*  261 */ "with",
+  /*  262 */ "setlist",
+  /*  263 */ "insert_cmd",
+  /*  264 */ "idlist_opt",
+  /*  265 */ "upsert",
+  /*  266 */ "filter_over",
+  /*  267 */ "likeop",
+  /*  268 */ "between_op",
+  /*  269 */ "in_op",
+  /*  270 */ "paren_exprlist",
+  /*  271 */ "case_operand",
+  /*  272 */ "case_exprlist",
+  /*  273 */ "case_else",
+  /*  274 */ "uniqueflag",
+  /*  275 */ "collate",
+  /*  276 */ "vinto",
+  /*  277 */ "nmnum",
+  /*  278 */ "trigger_decl",
+  /*  279 */ "trigger_cmd_list",
+  /*  280 */ "trigger_time",
+  /*  281 */ "trigger_event",
+  /*  282 */ "foreach_clause",
+  /*  283 */ "when_clause",
+  /*  284 */ "trigger_cmd",
+  /*  285 */ "trnm",
+  /*  286 */ "tridxby",
+  /*  287 */ "database_kw_opt",
+  /*  288 */ "key_opt",
+  /*  289 */ "add_column_fullname",
+  /*  290 */ "kwcolumn_opt",
+  /*  291 */ "create_vtab",
+  /*  292 */ "vtabarglist",
+  /*  293 */ "vtabarg",
+  /*  294 */ "vtabargtoken",
+  /*  295 */ "lp",
+  /*  296 */ "anylist",
+  /*  297 */ "windowdefn_list",
+  /*  298 */ "windowdefn",
+  /*  299 */ "window",
+  /*  300 */ "frame_opt",
+  /*  301 */ "part_opt",
+  /*  302 */ "filter_clause",
+  /*  303 */ "over_clause",
+  /*  304 */ "range_or_rows",
+  /*  305 */ "frame_bound",
+  /*  306 */ "frame_bound_s",
+  /*  307 */ "frame_bound_e",
+  /*  308 */ "frame_exclude_opt",
+  /*  309 */ "frame_exclude",
 };
 #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
 
@@ -151500,344 +156836,348 @@ static const char *const yyRuleName[] = {
  /*  40 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  /*  41 */ "ccons ::= defer_subclause",
  /*  42 */ "ccons ::= COLLATE ID|STRING",
- /*  43 */ "autoinc ::=",
- /*  44 */ "autoinc ::= AUTOINCR",
- /*  45 */ "refargs ::=",
- /*  46 */ "refargs ::= refargs refarg",
- /*  47 */ "refarg ::= MATCH nm",
- /*  48 */ "refarg ::= ON INSERT refact",
- /*  49 */ "refarg ::= ON DELETE refact",
- /*  50 */ "refarg ::= ON UPDATE refact",
- /*  51 */ "refact ::= SET NULL",
- /*  52 */ "refact ::= SET DEFAULT",
- /*  53 */ "refact ::= CASCADE",
- /*  54 */ "refact ::= RESTRICT",
- /*  55 */ "refact ::= NO ACTION",
- /*  56 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
- /*  57 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
- /*  58 */ "init_deferred_pred_opt ::=",
- /*  59 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
- /*  60 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
- /*  61 */ "conslist_opt ::=",
- /*  62 */ "tconscomma ::= COMMA",
- /*  63 */ "tcons ::= CONSTRAINT nm",
- /*  64 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
- /*  65 */ "tcons ::= UNIQUE LP sortlist RP onconf",
- /*  66 */ "tcons ::= CHECK LP expr RP onconf",
- /*  67 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
- /*  68 */ "defer_subclause_opt ::=",
- /*  69 */ "onconf ::=",
- /*  70 */ "onconf ::= ON CONFLICT resolvetype",
- /*  71 */ "orconf ::=",
- /*  72 */ "orconf ::= OR resolvetype",
- /*  73 */ "resolvetype ::= IGNORE",
- /*  74 */ "resolvetype ::= REPLACE",
- /*  75 */ "cmd ::= DROP TABLE ifexists fullname",
- /*  76 */ "ifexists ::= IF EXISTS",
- /*  77 */ "ifexists ::=",
- /*  78 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
- /*  79 */ "cmd ::= DROP VIEW ifexists fullname",
- /*  80 */ "cmd ::= select",
- /*  81 */ "select ::= WITH wqlist selectnowith",
- /*  82 */ "select ::= WITH RECURSIVE wqlist selectnowith",
- /*  83 */ "select ::= selectnowith",
- /*  84 */ "selectnowith ::= selectnowith multiselect_op oneselect",
- /*  85 */ "multiselect_op ::= UNION",
- /*  86 */ "multiselect_op ::= UNION ALL",
- /*  87 */ "multiselect_op ::= EXCEPT|INTERSECT",
- /*  88 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
- /*  89 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
- /*  90 */ "values ::= VALUES LP nexprlist RP",
- /*  91 */ "values ::= values COMMA LP nexprlist RP",
- /*  92 */ "distinct ::= DISTINCT",
- /*  93 */ "distinct ::= ALL",
- /*  94 */ "distinct ::=",
- /*  95 */ "sclp ::=",
- /*  96 */ "selcollist ::= sclp scanpt expr scanpt as",
- /*  97 */ "selcollist ::= sclp scanpt STAR",
- /*  98 */ "selcollist ::= sclp scanpt nm DOT STAR",
- /*  99 */ "as ::= AS nm",
- /* 100 */ "as ::=",
- /* 101 */ "from ::=",
- /* 102 */ "from ::= FROM seltablist",
- /* 103 */ "stl_prefix ::= seltablist joinop",
- /* 104 */ "stl_prefix ::=",
- /* 105 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
- /* 106 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
- /* 107 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
- /* 108 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
- /* 109 */ "dbnm ::=",
- /* 110 */ "dbnm ::= DOT nm",
- /* 111 */ "fullname ::= nm",
- /* 112 */ "fullname ::= nm DOT nm",
- /* 113 */ "xfullname ::= nm",
- /* 114 */ "xfullname ::= nm DOT nm",
- /* 115 */ "xfullname ::= nm DOT nm AS nm",
- /* 116 */ "xfullname ::= nm AS nm",
- /* 117 */ "joinop ::= COMMA|JOIN",
- /* 118 */ "joinop ::= JOIN_KW JOIN",
- /* 119 */ "joinop ::= JOIN_KW nm JOIN",
- /* 120 */ "joinop ::= JOIN_KW nm nm JOIN",
- /* 121 */ "on_opt ::= ON expr",
- /* 122 */ "on_opt ::=",
- /* 123 */ "indexed_opt ::=",
- /* 124 */ "indexed_opt ::= INDEXED BY nm",
- /* 125 */ "indexed_opt ::= NOT INDEXED",
- /* 126 */ "using_opt ::= USING LP idlist RP",
- /* 127 */ "using_opt ::=",
- /* 128 */ "orderby_opt ::=",
- /* 129 */ "orderby_opt ::= ORDER BY sortlist",
- /* 130 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
- /* 131 */ "sortlist ::= expr sortorder nulls",
- /* 132 */ "sortorder ::= ASC",
- /* 133 */ "sortorder ::= DESC",
- /* 134 */ "sortorder ::=",
- /* 135 */ "nulls ::= NULLS FIRST",
- /* 136 */ "nulls ::= NULLS LAST",
- /* 137 */ "nulls ::=",
- /* 138 */ "groupby_opt ::=",
- /* 139 */ "groupby_opt ::= GROUP BY nexprlist",
- /* 140 */ "having_opt ::=",
- /* 141 */ "having_opt ::= HAVING expr",
- /* 142 */ "limit_opt ::=",
- /* 143 */ "limit_opt ::= LIMIT expr",
- /* 144 */ "limit_opt ::= LIMIT expr OFFSET expr",
- /* 145 */ "limit_opt ::= LIMIT expr COMMA expr",
- /* 146 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt",
- /* 147 */ "where_opt ::=",
- /* 148 */ "where_opt ::= WHERE expr",
- /* 149 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt orderby_opt limit_opt",
- /* 150 */ "setlist ::= setlist COMMA nm EQ expr",
- /* 151 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
- /* 152 */ "setlist ::= nm EQ expr",
- /* 153 */ "setlist ::= LP idlist RP EQ expr",
- /* 154 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
- /* 155 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
- /* 156 */ "upsert ::=",
- /* 157 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
- /* 158 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
- /* 159 */ "upsert ::= ON CONFLICT DO NOTHING",
- /* 160 */ "insert_cmd ::= INSERT orconf",
- /* 161 */ "insert_cmd ::= REPLACE",
- /* 162 */ "idlist_opt ::=",
- /* 163 */ "idlist_opt ::= LP idlist RP",
- /* 164 */ "idlist ::= idlist COMMA nm",
- /* 165 */ "idlist ::= nm",
- /* 166 */ "expr ::= LP expr RP",
- /* 167 */ "expr ::= ID|INDEXED",
- /* 168 */ "expr ::= JOIN_KW",
- /* 169 */ "expr ::= nm DOT nm",
- /* 170 */ "expr ::= nm DOT nm DOT nm",
- /* 171 */ "term ::= NULL|FLOAT|BLOB",
- /* 172 */ "term ::= STRING",
- /* 173 */ "term ::= INTEGER",
- /* 174 */ "expr ::= VARIABLE",
- /* 175 */ "expr ::= expr COLLATE ID|STRING",
- /* 176 */ "expr ::= CAST LP expr AS typetoken RP",
- /* 177 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
- /* 178 */ "expr ::= ID|INDEXED LP STAR RP",
- /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
- /* 180 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
- /* 181 */ "term ::= CTIME_KW",
- /* 182 */ "expr ::= LP nexprlist COMMA expr RP",
- /* 183 */ "expr ::= expr AND expr",
- /* 184 */ "expr ::= expr OR expr",
- /* 185 */ "expr ::= expr LT|GT|GE|LE expr",
- /* 186 */ "expr ::= expr EQ|NE expr",
- /* 187 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
- /* 188 */ "expr ::= expr PLUS|MINUS expr",
- /* 189 */ "expr ::= expr STAR|SLASH|REM expr",
- /* 190 */ "expr ::= expr CONCAT expr",
- /* 191 */ "likeop ::= NOT LIKE_KW|MATCH",
- /* 192 */ "expr ::= expr likeop expr",
- /* 193 */ "expr ::= expr likeop expr ESCAPE expr",
- /* 194 */ "expr ::= expr ISNULL|NOTNULL",
- /* 195 */ "expr ::= expr NOT NULL",
- /* 196 */ "expr ::= expr IS expr",
- /* 197 */ "expr ::= expr IS NOT expr",
- /* 198 */ "expr ::= NOT expr",
- /* 199 */ "expr ::= BITNOT expr",
- /* 200 */ "expr ::= PLUS|MINUS expr",
- /* 201 */ "between_op ::= BETWEEN",
- /* 202 */ "between_op ::= NOT BETWEEN",
- /* 203 */ "expr ::= expr between_op expr AND expr",
- /* 204 */ "in_op ::= IN",
- /* 205 */ "in_op ::= NOT IN",
- /* 206 */ "expr ::= expr in_op LP exprlist RP",
- /* 207 */ "expr ::= LP select RP",
- /* 208 */ "expr ::= expr in_op LP select RP",
- /* 209 */ "expr ::= expr in_op nm dbnm paren_exprlist",
- /* 210 */ "expr ::= EXISTS LP select RP",
- /* 211 */ "expr ::= CASE case_operand case_exprlist case_else END",
- /* 212 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
- /* 213 */ "case_exprlist ::= WHEN expr THEN expr",
- /* 214 */ "case_else ::= ELSE expr",
- /* 215 */ "case_else ::=",
- /* 216 */ "case_operand ::= expr",
- /* 217 */ "case_operand ::=",
- /* 218 */ "exprlist ::=",
- /* 219 */ "nexprlist ::= nexprlist COMMA expr",
- /* 220 */ "nexprlist ::= expr",
- /* 221 */ "paren_exprlist ::=",
- /* 222 */ "paren_exprlist ::= LP exprlist RP",
- /* 223 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
- /* 224 */ "uniqueflag ::= UNIQUE",
- /* 225 */ "uniqueflag ::=",
- /* 226 */ "eidlist_opt ::=",
- /* 227 */ "eidlist_opt ::= LP eidlist RP",
- /* 228 */ "eidlist ::= eidlist COMMA nm collate sortorder",
- /* 229 */ "eidlist ::= nm collate sortorder",
- /* 230 */ "collate ::=",
- /* 231 */ "collate ::= COLLATE ID|STRING",
- /* 232 */ "cmd ::= DROP INDEX ifexists fullname",
- /* 233 */ "cmd ::= VACUUM vinto",
- /* 234 */ "cmd ::= VACUUM nm vinto",
- /* 235 */ "vinto ::= INTO expr",
- /* 236 */ "vinto ::=",
- /* 237 */ "cmd ::= PRAGMA nm dbnm",
- /* 238 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
- /* 239 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
- /* 240 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
- /* 241 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
- /* 242 */ "plus_num ::= PLUS INTEGER|FLOAT",
- /* 243 */ "minus_num ::= MINUS INTEGER|FLOAT",
- /* 244 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
- /* 245 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
- /* 246 */ "trigger_time ::= BEFORE|AFTER",
- /* 247 */ "trigger_time ::= INSTEAD OF",
- /* 248 */ "trigger_time ::=",
- /* 249 */ "trigger_event ::= DELETE|INSERT",
- /* 250 */ "trigger_event ::= UPDATE",
- /* 251 */ "trigger_event ::= UPDATE OF idlist",
- /* 252 */ "when_clause ::=",
- /* 253 */ "when_clause ::= WHEN expr",
- /* 254 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
- /* 255 */ "trigger_cmd_list ::= trigger_cmd SEMI",
- /* 256 */ "trnm ::= nm DOT nm",
- /* 257 */ "tridxby ::= INDEXED BY nm",
- /* 258 */ "tridxby ::= NOT INDEXED",
- /* 259 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
- /* 260 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
- /* 261 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
- /* 262 */ "trigger_cmd ::= scanpt select scanpt",
- /* 263 */ "expr ::= RAISE LP IGNORE RP",
- /* 264 */ "expr ::= RAISE LP raisetype COMMA nm RP",
- /* 265 */ "raisetype ::= ROLLBACK",
- /* 266 */ "raisetype ::= ABORT",
- /* 267 */ "raisetype ::= FAIL",
- /* 268 */ "cmd ::= DROP TRIGGER ifexists fullname",
- /* 269 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
- /* 270 */ "cmd ::= DETACH database_kw_opt expr",
- /* 271 */ "key_opt ::=",
- /* 272 */ "key_opt ::= KEY expr",
- /* 273 */ "cmd ::= REINDEX",
- /* 274 */ "cmd ::= REINDEX nm dbnm",
- /* 275 */ "cmd ::= ANALYZE",
- /* 276 */ "cmd ::= ANALYZE nm dbnm",
- /* 277 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
- /* 278 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
- /* 279 */ "add_column_fullname ::= fullname",
- /* 280 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
- /* 281 */ "cmd ::= create_vtab",
- /* 282 */ "cmd ::= create_vtab LP vtabarglist RP",
- /* 283 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
- /* 284 */ "vtabarg ::=",
- /* 285 */ "vtabargtoken ::= ANY",
- /* 286 */ "vtabargtoken ::= lp anylist RP",
- /* 287 */ "lp ::= LP",
- /* 288 */ "with ::= WITH wqlist",
- /* 289 */ "with ::= WITH RECURSIVE wqlist",
- /* 290 */ "wqlist ::= nm eidlist_opt AS LP select RP",
- /* 291 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
- /* 292 */ "windowdefn_list ::= windowdefn",
- /* 293 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
- /* 294 */ "windowdefn ::= nm AS LP window RP",
- /* 295 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
- /* 296 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
- /* 297 */ "window ::= ORDER BY sortlist frame_opt",
- /* 298 */ "window ::= nm ORDER BY sortlist frame_opt",
- /* 299 */ "window ::= frame_opt",
- /* 300 */ "window ::= nm frame_opt",
- /* 301 */ "frame_opt ::=",
- /* 302 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
- /* 303 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
- /* 304 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
- /* 305 */ "frame_bound_s ::= frame_bound",
- /* 306 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
- /* 307 */ "frame_bound_e ::= frame_bound",
- /* 308 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
- /* 309 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
- /* 310 */ "frame_bound ::= CURRENT ROW",
- /* 311 */ "frame_exclude_opt ::=",
- /* 312 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
- /* 313 */ "frame_exclude ::= NO OTHERS",
- /* 314 */ "frame_exclude ::= CURRENT ROW",
- /* 315 */ "frame_exclude ::= GROUP|TIES",
- /* 316 */ "window_clause ::= WINDOW windowdefn_list",
- /* 317 */ "filter_over ::= filter_clause over_clause",
- /* 318 */ "filter_over ::= over_clause",
- /* 319 */ "filter_over ::= filter_clause",
- /* 320 */ "over_clause ::= OVER LP window RP",
- /* 321 */ "over_clause ::= OVER nm",
- /* 322 */ "filter_clause ::= FILTER LP WHERE expr RP",
- /* 323 */ "input ::= cmdlist",
- /* 324 */ "cmdlist ::= cmdlist ecmd",
- /* 325 */ "cmdlist ::= ecmd",
- /* 326 */ "ecmd ::= SEMI",
- /* 327 */ "ecmd ::= cmdx SEMI",
- /* 328 */ "ecmd ::= explain cmdx",
- /* 329 */ "trans_opt ::=",
- /* 330 */ "trans_opt ::= TRANSACTION",
- /* 331 */ "trans_opt ::= TRANSACTION nm",
- /* 332 */ "savepoint_opt ::= SAVEPOINT",
- /* 333 */ "savepoint_opt ::=",
- /* 334 */ "cmd ::= create_table create_table_args",
- /* 335 */ "columnlist ::= columnlist COMMA columnname carglist",
- /* 336 */ "columnlist ::= columnname carglist",
- /* 337 */ "nm ::= ID|INDEXED",
- /* 338 */ "nm ::= STRING",
- /* 339 */ "nm ::= JOIN_KW",
- /* 340 */ "typetoken ::= typename",
- /* 341 */ "typename ::= ID|STRING",
- /* 342 */ "signed ::= plus_num",
- /* 343 */ "signed ::= minus_num",
- /* 344 */ "carglist ::= carglist ccons",
- /* 345 */ "carglist ::=",
- /* 346 */ "ccons ::= NULL onconf",
- /* 347 */ "conslist_opt ::= COMMA conslist",
- /* 348 */ "conslist ::= conslist tconscomma tcons",
- /* 349 */ "conslist ::= tcons",
- /* 350 */ "tconscomma ::=",
- /* 351 */ "defer_subclause_opt ::= defer_subclause",
- /* 352 */ "resolvetype ::= raisetype",
- /* 353 */ "selectnowith ::= oneselect",
- /* 354 */ "oneselect ::= values",
- /* 355 */ "sclp ::= selcollist COMMA",
- /* 356 */ "as ::= ID|STRING",
- /* 357 */ "expr ::= term",
- /* 358 */ "likeop ::= LIKE_KW|MATCH",
- /* 359 */ "exprlist ::= nexprlist",
- /* 360 */ "nmnum ::= plus_num",
- /* 361 */ "nmnum ::= nm",
- /* 362 */ "nmnum ::= ON",
- /* 363 */ "nmnum ::= DELETE",
- /* 364 */ "nmnum ::= DEFAULT",
- /* 365 */ "plus_num ::= INTEGER|FLOAT",
- /* 366 */ "foreach_clause ::=",
- /* 367 */ "foreach_clause ::= FOR EACH ROW",
- /* 368 */ "trnm ::= nm",
- /* 369 */ "tridxby ::=",
- /* 370 */ "database_kw_opt ::= DATABASE",
- /* 371 */ "database_kw_opt ::=",
- /* 372 */ "kwcolumn_opt ::=",
- /* 373 */ "kwcolumn_opt ::= COLUMNKW",
- /* 374 */ "vtabarglist ::= vtabarg",
- /* 375 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
- /* 376 */ "vtabarg ::= vtabarg vtabargtoken",
- /* 377 */ "anylist ::=",
- /* 378 */ "anylist ::= anylist LP anylist RP",
- /* 379 */ "anylist ::= anylist ANY",
- /* 380 */ "with ::=",
+ /*  43 */ "generated ::= LP expr RP",
+ /*  44 */ "generated ::= LP expr RP ID",
+ /*  45 */ "autoinc ::=",
+ /*  46 */ "autoinc ::= AUTOINCR",
+ /*  47 */ "refargs ::=",
+ /*  48 */ "refargs ::= refargs refarg",
+ /*  49 */ "refarg ::= MATCH nm",
+ /*  50 */ "refarg ::= ON INSERT refact",
+ /*  51 */ "refarg ::= ON DELETE refact",
+ /*  52 */ "refarg ::= ON UPDATE refact",
+ /*  53 */ "refact ::= SET NULL",
+ /*  54 */ "refact ::= SET DEFAULT",
+ /*  55 */ "refact ::= CASCADE",
+ /*  56 */ "refact ::= RESTRICT",
+ /*  57 */ "refact ::= NO ACTION",
+ /*  58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
+ /*  59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
+ /*  60 */ "init_deferred_pred_opt ::=",
+ /*  61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
+ /*  62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
+ /*  63 */ "conslist_opt ::=",
+ /*  64 */ "tconscomma ::= COMMA",
+ /*  65 */ "tcons ::= CONSTRAINT nm",
+ /*  66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
+ /*  67 */ "tcons ::= UNIQUE LP sortlist RP onconf",
+ /*  68 */ "tcons ::= CHECK LP expr RP onconf",
+ /*  69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
+ /*  70 */ "defer_subclause_opt ::=",
+ /*  71 */ "onconf ::=",
+ /*  72 */ "onconf ::= ON CONFLICT resolvetype",
+ /*  73 */ "orconf ::=",
+ /*  74 */ "orconf ::= OR resolvetype",
+ /*  75 */ "resolvetype ::= IGNORE",
+ /*  76 */ "resolvetype ::= REPLACE",
+ /*  77 */ "cmd ::= DROP TABLE ifexists fullname",
+ /*  78 */ "ifexists ::= IF EXISTS",
+ /*  79 */ "ifexists ::=",
+ /*  80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
+ /*  81 */ "cmd ::= DROP VIEW ifexists fullname",
+ /*  82 */ "cmd ::= select",
+ /*  83 */ "select ::= WITH wqlist selectnowith",
+ /*  84 */ "select ::= WITH RECURSIVE wqlist selectnowith",
+ /*  85 */ "select ::= selectnowith",
+ /*  86 */ "selectnowith ::= selectnowith multiselect_op oneselect",
+ /*  87 */ "multiselect_op ::= UNION",
+ /*  88 */ "multiselect_op ::= UNION ALL",
+ /*  89 */ "multiselect_op ::= EXCEPT|INTERSECT",
+ /*  90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
+ /*  91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
+ /*  92 */ "values ::= VALUES LP nexprlist RP",
+ /*  93 */ "values ::= values COMMA LP nexprlist RP",
+ /*  94 */ "distinct ::= DISTINCT",
+ /*  95 */ "distinct ::= ALL",
+ /*  96 */ "distinct ::=",
+ /*  97 */ "sclp ::=",
+ /*  98 */ "selcollist ::= sclp scanpt expr scanpt as",
+ /*  99 */ "selcollist ::= sclp scanpt STAR",
+ /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR",
+ /* 101 */ "as ::= AS nm",
+ /* 102 */ "as ::=",
+ /* 103 */ "from ::=",
+ /* 104 */ "from ::= FROM seltablist",
+ /* 105 */ "stl_prefix ::= seltablist joinop",
+ /* 106 */ "stl_prefix ::=",
+ /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
+ /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
+ /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
+ /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
+ /* 111 */ "dbnm ::=",
+ /* 112 */ "dbnm ::= DOT nm",
+ /* 113 */ "fullname ::= nm",
+ /* 114 */ "fullname ::= nm DOT nm",
+ /* 115 */ "xfullname ::= nm",
+ /* 116 */ "xfullname ::= nm DOT nm",
+ /* 117 */ "xfullname ::= nm DOT nm AS nm",
+ /* 118 */ "xfullname ::= nm AS nm",
+ /* 119 */ "joinop ::= COMMA|JOIN",
+ /* 120 */ "joinop ::= JOIN_KW JOIN",
+ /* 121 */ "joinop ::= JOIN_KW nm JOIN",
+ /* 122 */ "joinop ::= JOIN_KW nm nm JOIN",
+ /* 123 */ "on_opt ::= ON expr",
+ /* 124 */ "on_opt ::=",
+ /* 125 */ "indexed_opt ::=",
+ /* 126 */ "indexed_opt ::= INDEXED BY nm",
+ /* 127 */ "indexed_opt ::= NOT INDEXED",
+ /* 128 */ "using_opt ::= USING LP idlist RP",
+ /* 129 */ "using_opt ::=",
+ /* 130 */ "orderby_opt ::=",
+ /* 131 */ "orderby_opt ::= ORDER BY sortlist",
+ /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
+ /* 133 */ "sortlist ::= expr sortorder nulls",
+ /* 134 */ "sortorder ::= ASC",
+ /* 135 */ "sortorder ::= DESC",
+ /* 136 */ "sortorder ::=",
+ /* 137 */ "nulls ::= NULLS FIRST",
+ /* 138 */ "nulls ::= NULLS LAST",
+ /* 139 */ "nulls ::=",
+ /* 140 */ "groupby_opt ::=",
+ /* 141 */ "groupby_opt ::= GROUP BY nexprlist",
+ /* 142 */ "having_opt ::=",
+ /* 143 */ "having_opt ::= HAVING expr",
+ /* 144 */ "limit_opt ::=",
+ /* 145 */ "limit_opt ::= LIMIT expr",
+ /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr",
+ /* 147 */ "limit_opt ::= LIMIT expr COMMA expr",
+ /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt",
+ /* 149 */ "where_opt ::=",
+ /* 150 */ "where_opt ::= WHERE expr",
+ /* 151 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt orderby_opt limit_opt",
+ /* 152 */ "setlist ::= setlist COMMA nm EQ expr",
+ /* 153 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
+ /* 154 */ "setlist ::= nm EQ expr",
+ /* 155 */ "setlist ::= LP idlist RP EQ expr",
+ /* 156 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
+ /* 157 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
+ /* 158 */ "upsert ::=",
+ /* 159 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
+ /* 160 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
+ /* 161 */ "upsert ::= ON CONFLICT DO NOTHING",
+ /* 162 */ "insert_cmd ::= INSERT orconf",
+ /* 163 */ "insert_cmd ::= REPLACE",
+ /* 164 */ "idlist_opt ::=",
+ /* 165 */ "idlist_opt ::= LP idlist RP",
+ /* 166 */ "idlist ::= idlist COMMA nm",
+ /* 167 */ "idlist ::= nm",
+ /* 168 */ "expr ::= LP expr RP",
+ /* 169 */ "expr ::= ID|INDEXED",
+ /* 170 */ "expr ::= JOIN_KW",
+ /* 171 */ "expr ::= nm DOT nm",
+ /* 172 */ "expr ::= nm DOT nm DOT nm",
+ /* 173 */ "term ::= NULL|FLOAT|BLOB",
+ /* 174 */ "term ::= STRING",
+ /* 175 */ "term ::= INTEGER",
+ /* 176 */ "expr ::= VARIABLE",
+ /* 177 */ "expr ::= expr COLLATE ID|STRING",
+ /* 178 */ "expr ::= CAST LP expr AS typetoken RP",
+ /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
+ /* 180 */ "expr ::= ID|INDEXED LP STAR RP",
+ /* 181 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
+ /* 182 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
+ /* 183 */ "term ::= CTIME_KW",
+ /* 184 */ "expr ::= LP nexprlist COMMA expr RP",
+ /* 185 */ "expr ::= expr AND expr",
+ /* 186 */ "expr ::= expr OR expr",
+ /* 187 */ "expr ::= expr LT|GT|GE|LE expr",
+ /* 188 */ "expr ::= expr EQ|NE expr",
+ /* 189 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
+ /* 190 */ "expr ::= expr PLUS|MINUS expr",
+ /* 191 */ "expr ::= expr STAR|SLASH|REM expr",
+ /* 192 */ "expr ::= expr CONCAT expr",
+ /* 193 */ "likeop ::= NOT LIKE_KW|MATCH",
+ /* 194 */ "expr ::= expr likeop expr",
+ /* 195 */ "expr ::= expr likeop expr ESCAPE expr",
+ /* 196 */ "expr ::= expr ISNULL|NOTNULL",
+ /* 197 */ "expr ::= expr NOT NULL",
+ /* 198 */ "expr ::= expr IS expr",
+ /* 199 */ "expr ::= expr IS NOT expr",
+ /* 200 */ "expr ::= NOT expr",
+ /* 201 */ "expr ::= BITNOT expr",
+ /* 202 */ "expr ::= PLUS|MINUS expr",
+ /* 203 */ "between_op ::= BETWEEN",
+ /* 204 */ "between_op ::= NOT BETWEEN",
+ /* 205 */ "expr ::= expr between_op expr AND expr",
+ /* 206 */ "in_op ::= IN",
+ /* 207 */ "in_op ::= NOT IN",
+ /* 208 */ "expr ::= expr in_op LP exprlist RP",
+ /* 209 */ "expr ::= LP select RP",
+ /* 210 */ "expr ::= expr in_op LP select RP",
+ /* 211 */ "expr ::= expr in_op nm dbnm paren_exprlist",
+ /* 212 */ "expr ::= EXISTS LP select RP",
+ /* 213 */ "expr ::= CASE case_operand case_exprlist case_else END",
+ /* 214 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
+ /* 215 */ "case_exprlist ::= WHEN expr THEN expr",
+ /* 216 */ "case_else ::= ELSE expr",
+ /* 217 */ "case_else ::=",
+ /* 218 */ "case_operand ::= expr",
+ /* 219 */ "case_operand ::=",
+ /* 220 */ "exprlist ::=",
+ /* 221 */ "nexprlist ::= nexprlist COMMA expr",
+ /* 222 */ "nexprlist ::= expr",
+ /* 223 */ "paren_exprlist ::=",
+ /* 224 */ "paren_exprlist ::= LP exprlist RP",
+ /* 225 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
+ /* 226 */ "uniqueflag ::= UNIQUE",
+ /* 227 */ "uniqueflag ::=",
+ /* 228 */ "eidlist_opt ::=",
+ /* 229 */ "eidlist_opt ::= LP eidlist RP",
+ /* 230 */ "eidlist ::= eidlist COMMA nm collate sortorder",
+ /* 231 */ "eidlist ::= nm collate sortorder",
+ /* 232 */ "collate ::=",
+ /* 233 */ "collate ::= COLLATE ID|STRING",
+ /* 234 */ "cmd ::= DROP INDEX ifexists fullname",
+ /* 235 */ "cmd ::= VACUUM vinto",
+ /* 236 */ "cmd ::= VACUUM nm vinto",
+ /* 237 */ "vinto ::= INTO expr",
+ /* 238 */ "vinto ::=",
+ /* 239 */ "cmd ::= PRAGMA nm dbnm",
+ /* 240 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
+ /* 241 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
+ /* 242 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
+ /* 243 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
+ /* 244 */ "plus_num ::= PLUS INTEGER|FLOAT",
+ /* 245 */ "minus_num ::= MINUS INTEGER|FLOAT",
+ /* 246 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
+ /* 247 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
+ /* 248 */ "trigger_time ::= BEFORE|AFTER",
+ /* 249 */ "trigger_time ::= INSTEAD OF",
+ /* 250 */ "trigger_time ::=",
+ /* 251 */ "trigger_event ::= DELETE|INSERT",
+ /* 252 */ "trigger_event ::= UPDATE",
+ /* 253 */ "trigger_event ::= UPDATE OF idlist",
+ /* 254 */ "when_clause ::=",
+ /* 255 */ "when_clause ::= WHEN expr",
+ /* 256 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
+ /* 257 */ "trigger_cmd_list ::= trigger_cmd SEMI",
+ /* 258 */ "trnm ::= nm DOT nm",
+ /* 259 */ "tridxby ::= INDEXED BY nm",
+ /* 260 */ "tridxby ::= NOT INDEXED",
+ /* 261 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt",
+ /* 262 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
+ /* 263 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
+ /* 264 */ "trigger_cmd ::= scanpt select scanpt",
+ /* 265 */ "expr ::= RAISE LP IGNORE RP",
+ /* 266 */ "expr ::= RAISE LP raisetype COMMA nm RP",
+ /* 267 */ "raisetype ::= ROLLBACK",
+ /* 268 */ "raisetype ::= ABORT",
+ /* 269 */ "raisetype ::= FAIL",
+ /* 270 */ "cmd ::= DROP TRIGGER ifexists fullname",
+ /* 271 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
+ /* 272 */ "cmd ::= DETACH database_kw_opt expr",
+ /* 273 */ "key_opt ::=",
+ /* 274 */ "key_opt ::= KEY expr",
+ /* 275 */ "cmd ::= REINDEX",
+ /* 276 */ "cmd ::= REINDEX nm dbnm",
+ /* 277 */ "cmd ::= ANALYZE",
+ /* 278 */ "cmd ::= ANALYZE nm dbnm",
+ /* 279 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
+ /* 280 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
+ /* 281 */ "add_column_fullname ::= fullname",
+ /* 282 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
+ /* 283 */ "cmd ::= create_vtab",
+ /* 284 */ "cmd ::= create_vtab LP vtabarglist RP",
+ /* 285 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
+ /* 286 */ "vtabarg ::=",
+ /* 287 */ "vtabargtoken ::= ANY",
+ /* 288 */ "vtabargtoken ::= lp anylist RP",
+ /* 289 */ "lp ::= LP",
+ /* 290 */ "with ::= WITH wqlist",
+ /* 291 */ "with ::= WITH RECURSIVE wqlist",
+ /* 292 */ "wqlist ::= nm eidlist_opt AS LP select RP",
+ /* 293 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
+ /* 294 */ "windowdefn_list ::= windowdefn",
+ /* 295 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
+ /* 296 */ "windowdefn ::= nm AS LP window RP",
+ /* 297 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 298 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
+ /* 299 */ "window ::= ORDER BY sortlist frame_opt",
+ /* 300 */ "window ::= nm ORDER BY sortlist frame_opt",
+ /* 301 */ "window ::= frame_opt",
+ /* 302 */ "window ::= nm frame_opt",
+ /* 303 */ "frame_opt ::=",
+ /* 304 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
+ /* 305 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
+ /* 306 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
+ /* 307 */ "frame_bound_s ::= frame_bound",
+ /* 308 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
+ /* 309 */ "frame_bound_e ::= frame_bound",
+ /* 310 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
+ /* 311 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
+ /* 312 */ "frame_bound ::= CURRENT ROW",
+ /* 313 */ "frame_exclude_opt ::=",
+ /* 314 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
+ /* 315 */ "frame_exclude ::= NO OTHERS",
+ /* 316 */ "frame_exclude ::= CURRENT ROW",
+ /* 317 */ "frame_exclude ::= GROUP|TIES",
+ /* 318 */ "window_clause ::= WINDOW windowdefn_list",
+ /* 319 */ "filter_over ::= filter_clause over_clause",
+ /* 320 */ "filter_over ::= over_clause",
+ /* 321 */ "filter_over ::= filter_clause",
+ /* 322 */ "over_clause ::= OVER LP window RP",
+ /* 323 */ "over_clause ::= OVER nm",
+ /* 324 */ "filter_clause ::= FILTER LP WHERE expr RP",
+ /* 325 */ "input ::= cmdlist",
+ /* 326 */ "cmdlist ::= cmdlist ecmd",
+ /* 327 */ "cmdlist ::= ecmd",
+ /* 328 */ "ecmd ::= SEMI",
+ /* 329 */ "ecmd ::= cmdx SEMI",
+ /* 330 */ "ecmd ::= explain cmdx SEMI",
+ /* 331 */ "trans_opt ::=",
+ /* 332 */ "trans_opt ::= TRANSACTION",
+ /* 333 */ "trans_opt ::= TRANSACTION nm",
+ /* 334 */ "savepoint_opt ::= SAVEPOINT",
+ /* 335 */ "savepoint_opt ::=",
+ /* 336 */ "cmd ::= create_table create_table_args",
+ /* 337 */ "columnlist ::= columnlist COMMA columnname carglist",
+ /* 338 */ "columnlist ::= columnname carglist",
+ /* 339 */ "nm ::= ID|INDEXED",
+ /* 340 */ "nm ::= STRING",
+ /* 341 */ "nm ::= JOIN_KW",
+ /* 342 */ "typetoken ::= typename",
+ /* 343 */ "typename ::= ID|STRING",
+ /* 344 */ "signed ::= plus_num",
+ /* 345 */ "signed ::= minus_num",
+ /* 346 */ "carglist ::= carglist ccons",
+ /* 347 */ "carglist ::=",
+ /* 348 */ "ccons ::= NULL onconf",
+ /* 349 */ "ccons ::= GENERATED ALWAYS AS generated",
+ /* 350 */ "ccons ::= AS generated",
+ /* 351 */ "conslist_opt ::= COMMA conslist",
+ /* 352 */ "conslist ::= conslist tconscomma tcons",
+ /* 353 */ "conslist ::= tcons",
+ /* 354 */ "tconscomma ::=",
+ /* 355 */ "defer_subclause_opt ::= defer_subclause",
+ /* 356 */ "resolvetype ::= raisetype",
+ /* 357 */ "selectnowith ::= oneselect",
+ /* 358 */ "oneselect ::= values",
+ /* 359 */ "sclp ::= selcollist COMMA",
+ /* 360 */ "as ::= ID|STRING",
+ /* 361 */ "expr ::= term",
+ /* 362 */ "likeop ::= LIKE_KW|MATCH",
+ /* 363 */ "exprlist ::= nexprlist",
+ /* 364 */ "nmnum ::= plus_num",
+ /* 365 */ "nmnum ::= nm",
+ /* 366 */ "nmnum ::= ON",
+ /* 367 */ "nmnum ::= DELETE",
+ /* 368 */ "nmnum ::= DEFAULT",
+ /* 369 */ "plus_num ::= INTEGER|FLOAT",
+ /* 370 */ "foreach_clause ::=",
+ /* 371 */ "foreach_clause ::= FOR EACH ROW",
+ /* 372 */ "trnm ::= nm",
+ /* 373 */ "tridxby ::=",
+ /* 374 */ "database_kw_opt ::= DATABASE",
+ /* 375 */ "database_kw_opt ::=",
+ /* 376 */ "kwcolumn_opt ::=",
+ /* 377 */ "kwcolumn_opt ::= COLUMNKW",
+ /* 378 */ "vtabarglist ::= vtabarg",
+ /* 379 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
+ /* 380 */ "vtabarg ::= vtabarg vtabargtoken",
+ /* 381 */ "anylist ::=",
+ /* 382 */ "anylist ::= anylist LP anylist RP",
+ /* 383 */ "anylist ::= anylist ANY",
+ /* 384 */ "with ::=",
 };
 #endif /* NDEBUG */
 
@@ -151871,7 +157211,7 @@ static int yyGrowStack(yyParser *p){
 #endif
     p->yystksz = newSize;
   }
-  return pNew==0; 
+  return pNew==0;
 }
 #endif
 
@@ -151913,7 +157253,7 @@ SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL)
 }
 
 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
-/* 
+/*
 ** This function allocates a new parser.
 ** The only argument is a pointer to a function which works like
 ** malloc.
@@ -151940,7 +157280,7 @@ SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sql
 /* The following function deletes the "minor type" or semantic value
 ** associated with a symbol.  The symbol can be either a terminal
 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
-** a pointer to the value to be deleted.  The code used to do the 
+** a pointer to the value to be deleted.  The code used to do the
 ** deletions is derived from the %destructor and/or %token_destructor
 ** directives of the input grammar.
 */
@@ -151955,7 +157295,7 @@ static void yy_destructor(
     /* Here is inserted the actions which take place when a
     ** terminal or non-terminal is destroyed.  This can happen
     ** when the symbol is popped from the stack during a
-    ** reduce or during error processing or when a parser is 
+    ** reduce or during error processing or when a parser is
     ** being destroyed before it is finished parsing.
     **
     ** Note: during a reduce, the only symbols destroyed are those
@@ -151963,98 +157303,98 @@ static void yy_destructor(
     ** inside the C code.
     */
 /********* Begin destructor definitions ***************************************/
-    case 198: /* select */
-    case 231: /* selectnowith */
-    case 232: /* oneselect */
-    case 244: /* values */
+    case 200: /* select */
+    case 234: /* selectnowith */
+    case 235: /* oneselect */
+    case 247: /* values */
 {
-sqlite3SelectDelete(pParse->db, (yypminor->yy25));
+sqlite3SelectDelete(pParse->db, (yypminor->yy539));
 }
       break;
-    case 209: /* term */
-    case 210: /* expr */
-    case 238: /* where_opt */
-    case 240: /* having_opt */
-    case 252: /* on_opt */
-    case 268: /* case_operand */
-    case 270: /* case_else */
-    case 273: /* vinto */
-    case 280: /* when_clause */
-    case 285: /* key_opt */
-    case 299: /* filter_clause */
+    case 211: /* term */
+    case 212: /* expr */
+    case 241: /* where_opt */
+    case 243: /* having_opt */
+    case 255: /* on_opt */
+    case 271: /* case_operand */
+    case 273: /* case_else */
+    case 276: /* vinto */
+    case 283: /* when_clause */
+    case 288: /* key_opt */
+    case 302: /* filter_clause */
 {
-sqlite3ExprDelete(pParse->db, (yypminor->yy46));
+sqlite3ExprDelete(pParse->db, (yypminor->yy202));
 }
       break;
-    case 214: /* eidlist_opt */
-    case 223: /* sortlist */
-    case 224: /* eidlist */
-    case 236: /* selcollist */
-    case 239: /* groupby_opt */
-    case 241: /* orderby_opt */
-    case 245: /* nexprlist */
-    case 246: /* sclp */
-    case 254: /* exprlist */
-    case 259: /* setlist */
-    case 267: /* paren_exprlist */
-    case 269: /* case_exprlist */
-    case 298: /* part_opt */
+    case 216: /* eidlist_opt */
+    case 226: /* sortlist */
+    case 227: /* eidlist */
+    case 239: /* selcollist */
+    case 242: /* groupby_opt */
+    case 244: /* orderby_opt */
+    case 248: /* nexprlist */
+    case 249: /* sclp */
+    case 257: /* exprlist */
+    case 262: /* setlist */
+    case 270: /* paren_exprlist */
+    case 272: /* case_exprlist */
+    case 301: /* part_opt */
 {
-sqlite3ExprListDelete(pParse->db, (yypminor->yy138));
+sqlite3ExprListDelete(pParse->db, (yypminor->yy242));
 }
       break;
-    case 230: /* fullname */
-    case 237: /* from */
-    case 248: /* seltablist */
-    case 249: /* stl_prefix */
-    case 255: /* xfullname */
+    case 233: /* fullname */
+    case 240: /* from */
+    case 251: /* seltablist */
+    case 252: /* stl_prefix */
+    case 258: /* xfullname */
 {
-sqlite3SrcListDelete(pParse->db, (yypminor->yy609));
+sqlite3SrcListDelete(pParse->db, (yypminor->yy47));
 }
       break;
-    case 233: /* wqlist */
+    case 236: /* wqlist */
 {
-sqlite3WithDelete(pParse->db, (yypminor->yy297));
+sqlite3WithDelete(pParse->db, (yypminor->yy131));
 }
       break;
-    case 243: /* window_clause */
-    case 294: /* windowdefn_list */
+    case 246: /* window_clause */
+    case 297: /* windowdefn_list */
 {
-sqlite3WindowListDelete(pParse->db, (yypminor->yy455));
+sqlite3WindowListDelete(pParse->db, (yypminor->yy303));
 }
       break;
-    case 253: /* using_opt */
-    case 256: /* idlist */
-    case 261: /* idlist_opt */
+    case 256: /* using_opt */
+    case 259: /* idlist */
+    case 264: /* idlist_opt */
 {
-sqlite3IdListDelete(pParse->db, (yypminor->yy406));
+sqlite3IdListDelete(pParse->db, (yypminor->yy600));
 }
       break;
-    case 263: /* filter_over */
-    case 295: /* windowdefn */
-    case 296: /* window */
-    case 297: /* frame_opt */
-    case 300: /* over_clause */
+    case 266: /* filter_over */
+    case 298: /* windowdefn */
+    case 299: /* window */
+    case 300: /* frame_opt */
+    case 303: /* over_clause */
 {
-sqlite3WindowDelete(pParse->db, (yypminor->yy455));
+sqlite3WindowDelete(pParse->db, (yypminor->yy303));
 }
       break;
-    case 276: /* trigger_cmd_list */
-    case 281: /* trigger_cmd */
+    case 279: /* trigger_cmd_list */
+    case 284: /* trigger_cmd */
 {
-sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy527));
+sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447));
 }
       break;
-    case 278: /* trigger_event */
+    case 281: /* trigger_event */
 {
-sqlite3IdListDelete(pParse->db, (yypminor->yy572).b);
+sqlite3IdListDelete(pParse->db, (yypminor->yy230).b);
 }
       break;
-    case 302: /* frame_bound */
-    case 303: /* frame_bound_s */
-    case 304: /* frame_bound_e */
+    case 305: /* frame_bound */
+    case 306: /* frame_bound_s */
+    case 307: /* frame_bound_e */
 {
-sqlite3ExprDelete(pParse->db, (yypminor->yy57).pExpr);
+sqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr);
 }
       break;
 /********* End destructor definitions *****************************************/
@@ -152095,7 +157435,7 @@ SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
 }
 
 #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
-/* 
+/*
 ** Deallocate and destroy a parser.  Destructors are called for
 ** all stack elements before shutting the parser down.
 **
@@ -152221,7 +157561,7 @@ static YYACTIONTYPE yy_find_shift_action(
 #endif /* YYWILDCARD */
       return yy_default[stateno];
     }else{
-      assert( i>=0 && i<sizeof(yy_action)/sizeof(yy_action[0]) );
+      assert( i>=0 && i<(int)(sizeof(yy_action)/sizeof(yy_action[0])) );
       return yy_action[i];
     }
   }while(1);
@@ -152317,7 +157657,7 @@ static void yy_shift(
     assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
   }
 #endif
-#if YYSTACKDEPTH>0 
+#if YYSTACKDEPTH>0
   if( yypParser->yytos>yypParser->yystackEnd ){
     yypParser->yytos--;
     yyStackOverflow(yypParser);
@@ -152345,387 +157685,391 @@ static void yy_shift(
 /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
 ** of that rule */
 static const YYCODETYPE yyRuleInfoLhs[] = {
-   183,  /* (0) explain ::= EXPLAIN */
-   183,  /* (1) explain ::= EXPLAIN QUERY PLAN */
-   182,  /* (2) cmdx ::= cmd */
-   184,  /* (3) cmd ::= BEGIN transtype trans_opt */
-   185,  /* (4) transtype ::= */
-   185,  /* (5) transtype ::= DEFERRED */
-   185,  /* (6) transtype ::= IMMEDIATE */
-   185,  /* (7) transtype ::= EXCLUSIVE */
-   184,  /* (8) cmd ::= COMMIT|END trans_opt */
-   184,  /* (9) cmd ::= ROLLBACK trans_opt */
-   184,  /* (10) cmd ::= SAVEPOINT nm */
-   184,  /* (11) cmd ::= RELEASE savepoint_opt nm */
-   184,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
-   189,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
-   191,  /* (14) createkw ::= CREATE */
-   193,  /* (15) ifnotexists ::= */
-   193,  /* (16) ifnotexists ::= IF NOT EXISTS */
-   192,  /* (17) temp ::= TEMP */
-   192,  /* (18) temp ::= */
-   190,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
-   190,  /* (20) create_table_args ::= AS select */
-   197,  /* (21) table_options ::= */
-   197,  /* (22) table_options ::= WITHOUT nm */
-   199,  /* (23) columnname ::= nm typetoken */
-   201,  /* (24) typetoken ::= */
-   201,  /* (25) typetoken ::= typename LP signed RP */
-   201,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
-   202,  /* (27) typename ::= typename ID|STRING */
-   206,  /* (28) scanpt ::= */
-   207,  /* (29) scantok ::= */
-   208,  /* (30) ccons ::= CONSTRAINT nm */
-   208,  /* (31) ccons ::= DEFAULT scantok term */
-   208,  /* (32) ccons ::= DEFAULT LP expr RP */
-   208,  /* (33) ccons ::= DEFAULT PLUS scantok term */
-   208,  /* (34) ccons ::= DEFAULT MINUS scantok term */
-   208,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
-   208,  /* (36) ccons ::= NOT NULL onconf */
-   208,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
-   208,  /* (38) ccons ::= UNIQUE onconf */
-   208,  /* (39) ccons ::= CHECK LP expr RP */
-   208,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
-   208,  /* (41) ccons ::= defer_subclause */
-   208,  /* (42) ccons ::= COLLATE ID|STRING */
-   213,  /* (43) autoinc ::= */
-   213,  /* (44) autoinc ::= AUTOINCR */
-   215,  /* (45) refargs ::= */
-   215,  /* (46) refargs ::= refargs refarg */
-   217,  /* (47) refarg ::= MATCH nm */
-   217,  /* (48) refarg ::= ON INSERT refact */
-   217,  /* (49) refarg ::= ON DELETE refact */
-   217,  /* (50) refarg ::= ON UPDATE refact */
-   218,  /* (51) refact ::= SET NULL */
-   218,  /* (52) refact ::= SET DEFAULT */
-   218,  /* (53) refact ::= CASCADE */
-   218,  /* (54) refact ::= RESTRICT */
-   218,  /* (55) refact ::= NO ACTION */
-   216,  /* (56) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-   216,  /* (57) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-   219,  /* (58) init_deferred_pred_opt ::= */
-   219,  /* (59) init_deferred_pred_opt ::= INITIALLY DEFERRED */
-   219,  /* (60) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-   196,  /* (61) conslist_opt ::= */
-   221,  /* (62) tconscomma ::= COMMA */
-   222,  /* (63) tcons ::= CONSTRAINT nm */
-   222,  /* (64) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-   222,  /* (65) tcons ::= UNIQUE LP sortlist RP onconf */
-   222,  /* (66) tcons ::= CHECK LP expr RP onconf */
-   222,  /* (67) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
-   225,  /* (68) defer_subclause_opt ::= */
-   211,  /* (69) onconf ::= */
-   211,  /* (70) onconf ::= ON CONFLICT resolvetype */
-   226,  /* (71) orconf ::= */
-   226,  /* (72) orconf ::= OR resolvetype */
-   227,  /* (73) resolvetype ::= IGNORE */
-   227,  /* (74) resolvetype ::= REPLACE */
-   184,  /* (75) cmd ::= DROP TABLE ifexists fullname */
-   229,  /* (76) ifexists ::= IF EXISTS */
-   229,  /* (77) ifexists ::= */
-   184,  /* (78) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
-   184,  /* (79) cmd ::= DROP VIEW ifexists fullname */
-   184,  /* (80) cmd ::= select */
-   198,  /* (81) select ::= WITH wqlist selectnowith */
-   198,  /* (82) select ::= WITH RECURSIVE wqlist selectnowith */
-   198,  /* (83) select ::= selectnowith */
-   231,  /* (84) selectnowith ::= selectnowith multiselect_op oneselect */
-   234,  /* (85) multiselect_op ::= UNION */
-   234,  /* (86) multiselect_op ::= UNION ALL */
-   234,  /* (87) multiselect_op ::= EXCEPT|INTERSECT */
-   232,  /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
-   232,  /* (89) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
-   244,  /* (90) values ::= VALUES LP nexprlist RP */
-   244,  /* (91) values ::= values COMMA LP nexprlist RP */
-   235,  /* (92) distinct ::= DISTINCT */
-   235,  /* (93) distinct ::= ALL */
-   235,  /* (94) distinct ::= */
-   246,  /* (95) sclp ::= */
-   236,  /* (96) selcollist ::= sclp scanpt expr scanpt as */
-   236,  /* (97) selcollist ::= sclp scanpt STAR */
-   236,  /* (98) selcollist ::= sclp scanpt nm DOT STAR */
-   247,  /* (99) as ::= AS nm */
-   247,  /* (100) as ::= */
-   237,  /* (101) from ::= */
-   237,  /* (102) from ::= FROM seltablist */
-   249,  /* (103) stl_prefix ::= seltablist joinop */
-   249,  /* (104) stl_prefix ::= */
-   248,  /* (105) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
-   248,  /* (106) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
-   248,  /* (107) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
-   248,  /* (108) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
-   194,  /* (109) dbnm ::= */
-   194,  /* (110) dbnm ::= DOT nm */
-   230,  /* (111) fullname ::= nm */
-   230,  /* (112) fullname ::= nm DOT nm */
-   255,  /* (113) xfullname ::= nm */
-   255,  /* (114) xfullname ::= nm DOT nm */
-   255,  /* (115) xfullname ::= nm DOT nm AS nm */
-   255,  /* (116) xfullname ::= nm AS nm */
-   250,  /* (117) joinop ::= COMMA|JOIN */
-   250,  /* (118) joinop ::= JOIN_KW JOIN */
-   250,  /* (119) joinop ::= JOIN_KW nm JOIN */
-   250,  /* (120) joinop ::= JOIN_KW nm nm JOIN */
-   252,  /* (121) on_opt ::= ON expr */
-   252,  /* (122) on_opt ::= */
-   251,  /* (123) indexed_opt ::= */
-   251,  /* (124) indexed_opt ::= INDEXED BY nm */
-   251,  /* (125) indexed_opt ::= NOT INDEXED */
-   253,  /* (126) using_opt ::= USING LP idlist RP */
-   253,  /* (127) using_opt ::= */
-   241,  /* (128) orderby_opt ::= */
-   241,  /* (129) orderby_opt ::= ORDER BY sortlist */
-   223,  /* (130) sortlist ::= sortlist COMMA expr sortorder nulls */
-   223,  /* (131) sortlist ::= expr sortorder nulls */
-   212,  /* (132) sortorder ::= ASC */
-   212,  /* (133) sortorder ::= DESC */
-   212,  /* (134) sortorder ::= */
-   257,  /* (135) nulls ::= NULLS FIRST */
-   257,  /* (136) nulls ::= NULLS LAST */
-   257,  /* (137) nulls ::= */
-   239,  /* (138) groupby_opt ::= */
-   239,  /* (139) groupby_opt ::= GROUP BY nexprlist */
-   240,  /* (140) having_opt ::= */
-   240,  /* (141) having_opt ::= HAVING expr */
-   242,  /* (142) limit_opt ::= */
-   242,  /* (143) limit_opt ::= LIMIT expr */
-   242,  /* (144) limit_opt ::= LIMIT expr OFFSET expr */
-   242,  /* (145) limit_opt ::= LIMIT expr COMMA expr */
-   184,  /* (146) cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
-   238,  /* (147) where_opt ::= */
-   238,  /* (148) where_opt ::= WHERE expr */
-   184,  /* (149) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt orderby_opt limit_opt */
-   259,  /* (150) setlist ::= setlist COMMA nm EQ expr */
-   259,  /* (151) setlist ::= setlist COMMA LP idlist RP EQ expr */
-   259,  /* (152) setlist ::= nm EQ expr */
-   259,  /* (153) setlist ::= LP idlist RP EQ expr */
-   184,  /* (154) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
-   184,  /* (155) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
-   262,  /* (156) upsert ::= */
-   262,  /* (157) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
-   262,  /* (158) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
-   262,  /* (159) upsert ::= ON CONFLICT DO NOTHING */
-   260,  /* (160) insert_cmd ::= INSERT orconf */
-   260,  /* (161) insert_cmd ::= REPLACE */
-   261,  /* (162) idlist_opt ::= */
-   261,  /* (163) idlist_opt ::= LP idlist RP */
-   256,  /* (164) idlist ::= idlist COMMA nm */
-   256,  /* (165) idlist ::= nm */
-   210,  /* (166) expr ::= LP expr RP */
-   210,  /* (167) expr ::= ID|INDEXED */
-   210,  /* (168) expr ::= JOIN_KW */
-   210,  /* (169) expr ::= nm DOT nm */
-   210,  /* (170) expr ::= nm DOT nm DOT nm */
-   209,  /* (171) term ::= NULL|FLOAT|BLOB */
-   209,  /* (172) term ::= STRING */
-   209,  /* (173) term ::= INTEGER */
-   210,  /* (174) expr ::= VARIABLE */
-   210,  /* (175) expr ::= expr COLLATE ID|STRING */
-   210,  /* (176) expr ::= CAST LP expr AS typetoken RP */
-   210,  /* (177) expr ::= ID|INDEXED LP distinct exprlist RP */
-   210,  /* (178) expr ::= ID|INDEXED LP STAR RP */
-   210,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
-   210,  /* (180) expr ::= ID|INDEXED LP STAR RP filter_over */
-   209,  /* (181) term ::= CTIME_KW */
-   210,  /* (182) expr ::= LP nexprlist COMMA expr RP */
-   210,  /* (183) expr ::= expr AND expr */
-   210,  /* (184) expr ::= expr OR expr */
-   210,  /* (185) expr ::= expr LT|GT|GE|LE expr */
-   210,  /* (186) expr ::= expr EQ|NE expr */
-   210,  /* (187) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-   210,  /* (188) expr ::= expr PLUS|MINUS expr */
-   210,  /* (189) expr ::= expr STAR|SLASH|REM expr */
-   210,  /* (190) expr ::= expr CONCAT expr */
-   264,  /* (191) likeop ::= NOT LIKE_KW|MATCH */
-   210,  /* (192) expr ::= expr likeop expr */
-   210,  /* (193) expr ::= expr likeop expr ESCAPE expr */
-   210,  /* (194) expr ::= expr ISNULL|NOTNULL */
-   210,  /* (195) expr ::= expr NOT NULL */
-   210,  /* (196) expr ::= expr IS expr */
-   210,  /* (197) expr ::= expr IS NOT expr */
-   210,  /* (198) expr ::= NOT expr */
-   210,  /* (199) expr ::= BITNOT expr */
-   210,  /* (200) expr ::= PLUS|MINUS expr */
-   265,  /* (201) between_op ::= BETWEEN */
-   265,  /* (202) between_op ::= NOT BETWEEN */
-   210,  /* (203) expr ::= expr between_op expr AND expr */
-   266,  /* (204) in_op ::= IN */
-   266,  /* (205) in_op ::= NOT IN */
-   210,  /* (206) expr ::= expr in_op LP exprlist RP */
-   210,  /* (207) expr ::= LP select RP */
-   210,  /* (208) expr ::= expr in_op LP select RP */
-   210,  /* (209) expr ::= expr in_op nm dbnm paren_exprlist */
-   210,  /* (210) expr ::= EXISTS LP select RP */
-   210,  /* (211) expr ::= CASE case_operand case_exprlist case_else END */
-   269,  /* (212) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-   269,  /* (213) case_exprlist ::= WHEN expr THEN expr */
-   270,  /* (214) case_else ::= ELSE expr */
-   270,  /* (215) case_else ::= */
-   268,  /* (216) case_operand ::= expr */
-   268,  /* (217) case_operand ::= */
-   254,  /* (218) exprlist ::= */
-   245,  /* (219) nexprlist ::= nexprlist COMMA expr */
-   245,  /* (220) nexprlist ::= expr */
-   267,  /* (221) paren_exprlist ::= */
-   267,  /* (222) paren_exprlist ::= LP exprlist RP */
-   184,  /* (223) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-   271,  /* (224) uniqueflag ::= UNIQUE */
-   271,  /* (225) uniqueflag ::= */
-   214,  /* (226) eidlist_opt ::= */
-   214,  /* (227) eidlist_opt ::= LP eidlist RP */
-   224,  /* (228) eidlist ::= eidlist COMMA nm collate sortorder */
-   224,  /* (229) eidlist ::= nm collate sortorder */
-   272,  /* (230) collate ::= */
-   272,  /* (231) collate ::= COLLATE ID|STRING */
-   184,  /* (232) cmd ::= DROP INDEX ifexists fullname */
-   184,  /* (233) cmd ::= VACUUM vinto */
-   184,  /* (234) cmd ::= VACUUM nm vinto */
-   273,  /* (235) vinto ::= INTO expr */
-   273,  /* (236) vinto ::= */
-   184,  /* (237) cmd ::= PRAGMA nm dbnm */
-   184,  /* (238) cmd ::= PRAGMA nm dbnm EQ nmnum */
-   184,  /* (239) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-   184,  /* (240) cmd ::= PRAGMA nm dbnm EQ minus_num */
-   184,  /* (241) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-   204,  /* (242) plus_num ::= PLUS INTEGER|FLOAT */
-   205,  /* (243) minus_num ::= MINUS INTEGER|FLOAT */
-   184,  /* (244) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-   275,  /* (245) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-   277,  /* (246) trigger_time ::= BEFORE|AFTER */
-   277,  /* (247) trigger_time ::= INSTEAD OF */
-   277,  /* (248) trigger_time ::= */
-   278,  /* (249) trigger_event ::= DELETE|INSERT */
-   278,  /* (250) trigger_event ::= UPDATE */
-   278,  /* (251) trigger_event ::= UPDATE OF idlist */
-   280,  /* (252) when_clause ::= */
-   280,  /* (253) when_clause ::= WHEN expr */
-   276,  /* (254) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-   276,  /* (255) trigger_cmd_list ::= trigger_cmd SEMI */
-   282,  /* (256) trnm ::= nm DOT nm */
-   283,  /* (257) tridxby ::= INDEXED BY nm */
-   283,  /* (258) tridxby ::= NOT INDEXED */
-   281,  /* (259) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
-   281,  /* (260) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-   281,  /* (261) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-   281,  /* (262) trigger_cmd ::= scanpt select scanpt */
-   210,  /* (263) expr ::= RAISE LP IGNORE RP */
-   210,  /* (264) expr ::= RAISE LP raisetype COMMA nm RP */
-   228,  /* (265) raisetype ::= ROLLBACK */
-   228,  /* (266) raisetype ::= ABORT */
-   228,  /* (267) raisetype ::= FAIL */
-   184,  /* (268) cmd ::= DROP TRIGGER ifexists fullname */
-   184,  /* (269) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-   184,  /* (270) cmd ::= DETACH database_kw_opt expr */
-   285,  /* (271) key_opt ::= */
-   285,  /* (272) key_opt ::= KEY expr */
-   184,  /* (273) cmd ::= REINDEX */
-   184,  /* (274) cmd ::= REINDEX nm dbnm */
-   184,  /* (275) cmd ::= ANALYZE */
-   184,  /* (276) cmd ::= ANALYZE nm dbnm */
-   184,  /* (277) cmd ::= ALTER TABLE fullname RENAME TO nm */
-   184,  /* (278) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-   286,  /* (279) add_column_fullname ::= fullname */
-   184,  /* (280) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-   184,  /* (281) cmd ::= create_vtab */
-   184,  /* (282) cmd ::= create_vtab LP vtabarglist RP */
-   288,  /* (283) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-   290,  /* (284) vtabarg ::= */
-   291,  /* (285) vtabargtoken ::= ANY */
-   291,  /* (286) vtabargtoken ::= lp anylist RP */
-   292,  /* (287) lp ::= LP */
-   258,  /* (288) with ::= WITH wqlist */
-   258,  /* (289) with ::= WITH RECURSIVE wqlist */
-   233,  /* (290) wqlist ::= nm eidlist_opt AS LP select RP */
-   233,  /* (291) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
-   294,  /* (292) windowdefn_list ::= windowdefn */
-   294,  /* (293) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-   295,  /* (294) windowdefn ::= nm AS LP window RP */
-   296,  /* (295) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-   296,  /* (296) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-   296,  /* (297) window ::= ORDER BY sortlist frame_opt */
-   296,  /* (298) window ::= nm ORDER BY sortlist frame_opt */
-   296,  /* (299) window ::= frame_opt */
-   296,  /* (300) window ::= nm frame_opt */
-   297,  /* (301) frame_opt ::= */
-   297,  /* (302) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-   297,  /* (303) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-   301,  /* (304) range_or_rows ::= RANGE|ROWS|GROUPS */
-   303,  /* (305) frame_bound_s ::= frame_bound */
-   303,  /* (306) frame_bound_s ::= UNBOUNDED PRECEDING */
-   304,  /* (307) frame_bound_e ::= frame_bound */
-   304,  /* (308) frame_bound_e ::= UNBOUNDED FOLLOWING */
-   302,  /* (309) frame_bound ::= expr PRECEDING|FOLLOWING */
-   302,  /* (310) frame_bound ::= CURRENT ROW */
-   305,  /* (311) frame_exclude_opt ::= */
-   305,  /* (312) frame_exclude_opt ::= EXCLUDE frame_exclude */
-   306,  /* (313) frame_exclude ::= NO OTHERS */
-   306,  /* (314) frame_exclude ::= CURRENT ROW */
-   306,  /* (315) frame_exclude ::= GROUP|TIES */
-   243,  /* (316) window_clause ::= WINDOW windowdefn_list */
-   263,  /* (317) filter_over ::= filter_clause over_clause */
-   263,  /* (318) filter_over ::= over_clause */
-   263,  /* (319) filter_over ::= filter_clause */
-   300,  /* (320) over_clause ::= OVER LP window RP */
-   300,  /* (321) over_clause ::= OVER nm */
-   299,  /* (322) filter_clause ::= FILTER LP WHERE expr RP */
-   179,  /* (323) input ::= cmdlist */
-   180,  /* (324) cmdlist ::= cmdlist ecmd */
-   180,  /* (325) cmdlist ::= ecmd */
-   181,  /* (326) ecmd ::= SEMI */
-   181,  /* (327) ecmd ::= cmdx SEMI */
-   181,  /* (328) ecmd ::= explain cmdx */
-   186,  /* (329) trans_opt ::= */
-   186,  /* (330) trans_opt ::= TRANSACTION */
-   186,  /* (331) trans_opt ::= TRANSACTION nm */
-   188,  /* (332) savepoint_opt ::= SAVEPOINT */
-   188,  /* (333) savepoint_opt ::= */
-   184,  /* (334) cmd ::= create_table create_table_args */
-   195,  /* (335) columnlist ::= columnlist COMMA columnname carglist */
-   195,  /* (336) columnlist ::= columnname carglist */
-   187,  /* (337) nm ::= ID|INDEXED */
-   187,  /* (338) nm ::= STRING */
-   187,  /* (339) nm ::= JOIN_KW */
-   201,  /* (340) typetoken ::= typename */
-   202,  /* (341) typename ::= ID|STRING */
-   203,  /* (342) signed ::= plus_num */
-   203,  /* (343) signed ::= minus_num */
-   200,  /* (344) carglist ::= carglist ccons */
-   200,  /* (345) carglist ::= */
-   208,  /* (346) ccons ::= NULL onconf */
-   196,  /* (347) conslist_opt ::= COMMA conslist */
-   220,  /* (348) conslist ::= conslist tconscomma tcons */
-   220,  /* (349) conslist ::= tcons */
-   221,  /* (350) tconscomma ::= */
-   225,  /* (351) defer_subclause_opt ::= defer_subclause */
-   227,  /* (352) resolvetype ::= raisetype */
-   231,  /* (353) selectnowith ::= oneselect */
-   232,  /* (354) oneselect ::= values */
-   246,  /* (355) sclp ::= selcollist COMMA */
-   247,  /* (356) as ::= ID|STRING */
-   210,  /* (357) expr ::= term */
-   264,  /* (358) likeop ::= LIKE_KW|MATCH */
-   254,  /* (359) exprlist ::= nexprlist */
-   274,  /* (360) nmnum ::= plus_num */
-   274,  /* (361) nmnum ::= nm */
-   274,  /* (362) nmnum ::= ON */
-   274,  /* (363) nmnum ::= DELETE */
-   274,  /* (364) nmnum ::= DEFAULT */
-   204,  /* (365) plus_num ::= INTEGER|FLOAT */
-   279,  /* (366) foreach_clause ::= */
-   279,  /* (367) foreach_clause ::= FOR EACH ROW */
-   282,  /* (368) trnm ::= nm */
-   283,  /* (369) tridxby ::= */
-   284,  /* (370) database_kw_opt ::= DATABASE */
-   284,  /* (371) database_kw_opt ::= */
-   287,  /* (372) kwcolumn_opt ::= */
-   287,  /* (373) kwcolumn_opt ::= COLUMNKW */
-   289,  /* (374) vtabarglist ::= vtabarg */
-   289,  /* (375) vtabarglist ::= vtabarglist COMMA vtabarg */
-   290,  /* (376) vtabarg ::= vtabarg vtabargtoken */
-   293,  /* (377) anylist ::= */
-   293,  /* (378) anylist ::= anylist LP anylist RP */
-   293,  /* (379) anylist ::= anylist ANY */
-   258,  /* (380) with ::= */
+   185,  /* (0) explain ::= EXPLAIN */
+   185,  /* (1) explain ::= EXPLAIN QUERY PLAN */
+   184,  /* (2) cmdx ::= cmd */
+   186,  /* (3) cmd ::= BEGIN transtype trans_opt */
+   187,  /* (4) transtype ::= */
+   187,  /* (5) transtype ::= DEFERRED */
+   187,  /* (6) transtype ::= IMMEDIATE */
+   187,  /* (7) transtype ::= EXCLUSIVE */
+   186,  /* (8) cmd ::= COMMIT|END trans_opt */
+   186,  /* (9) cmd ::= ROLLBACK trans_opt */
+   186,  /* (10) cmd ::= SAVEPOINT nm */
+   186,  /* (11) cmd ::= RELEASE savepoint_opt nm */
+   186,  /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
+   191,  /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
+   193,  /* (14) createkw ::= CREATE */
+   195,  /* (15) ifnotexists ::= */
+   195,  /* (16) ifnotexists ::= IF NOT EXISTS */
+   194,  /* (17) temp ::= TEMP */
+   194,  /* (18) temp ::= */
+   192,  /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
+   192,  /* (20) create_table_args ::= AS select */
+   199,  /* (21) table_options ::= */
+   199,  /* (22) table_options ::= WITHOUT nm */
+   201,  /* (23) columnname ::= nm typetoken */
+   203,  /* (24) typetoken ::= */
+   203,  /* (25) typetoken ::= typename LP signed RP */
+   203,  /* (26) typetoken ::= typename LP signed COMMA signed RP */
+   204,  /* (27) typename ::= typename ID|STRING */
+   208,  /* (28) scanpt ::= */
+   209,  /* (29) scantok ::= */
+   210,  /* (30) ccons ::= CONSTRAINT nm */
+   210,  /* (31) ccons ::= DEFAULT scantok term */
+   210,  /* (32) ccons ::= DEFAULT LP expr RP */
+   210,  /* (33) ccons ::= DEFAULT PLUS scantok term */
+   210,  /* (34) ccons ::= DEFAULT MINUS scantok term */
+   210,  /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
+   210,  /* (36) ccons ::= NOT NULL onconf */
+   210,  /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
+   210,  /* (38) ccons ::= UNIQUE onconf */
+   210,  /* (39) ccons ::= CHECK LP expr RP */
+   210,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
+   210,  /* (41) ccons ::= defer_subclause */
+   210,  /* (42) ccons ::= COLLATE ID|STRING */
+   219,  /* (43) generated ::= LP expr RP */
+   219,  /* (44) generated ::= LP expr RP ID */
+   215,  /* (45) autoinc ::= */
+   215,  /* (46) autoinc ::= AUTOINCR */
+   217,  /* (47) refargs ::= */
+   217,  /* (48) refargs ::= refargs refarg */
+   220,  /* (49) refarg ::= MATCH nm */
+   220,  /* (50) refarg ::= ON INSERT refact */
+   220,  /* (51) refarg ::= ON DELETE refact */
+   220,  /* (52) refarg ::= ON UPDATE refact */
+   221,  /* (53) refact ::= SET NULL */
+   221,  /* (54) refact ::= SET DEFAULT */
+   221,  /* (55) refact ::= CASCADE */
+   221,  /* (56) refact ::= RESTRICT */
+   221,  /* (57) refact ::= NO ACTION */
+   218,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+   218,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+   222,  /* (60) init_deferred_pred_opt ::= */
+   222,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+   222,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+   198,  /* (63) conslist_opt ::= */
+   224,  /* (64) tconscomma ::= COMMA */
+   225,  /* (65) tcons ::= CONSTRAINT nm */
+   225,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+   225,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
+   225,  /* (68) tcons ::= CHECK LP expr RP onconf */
+   225,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+   228,  /* (70) defer_subclause_opt ::= */
+   213,  /* (71) onconf ::= */
+   213,  /* (72) onconf ::= ON CONFLICT resolvetype */
+   229,  /* (73) orconf ::= */
+   229,  /* (74) orconf ::= OR resolvetype */
+   230,  /* (75) resolvetype ::= IGNORE */
+   230,  /* (76) resolvetype ::= REPLACE */
+   186,  /* (77) cmd ::= DROP TABLE ifexists fullname */
+   232,  /* (78) ifexists ::= IF EXISTS */
+   232,  /* (79) ifexists ::= */
+   186,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+   186,  /* (81) cmd ::= DROP VIEW ifexists fullname */
+   186,  /* (82) cmd ::= select */
+   200,  /* (83) select ::= WITH wqlist selectnowith */
+   200,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
+   200,  /* (85) select ::= selectnowith */
+   234,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
+   237,  /* (87) multiselect_op ::= UNION */
+   237,  /* (88) multiselect_op ::= UNION ALL */
+   237,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */
+   235,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+   235,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+   247,  /* (92) values ::= VALUES LP nexprlist RP */
+   247,  /* (93) values ::= values COMMA LP nexprlist RP */
+   238,  /* (94) distinct ::= DISTINCT */
+   238,  /* (95) distinct ::= ALL */
+   238,  /* (96) distinct ::= */
+   249,  /* (97) sclp ::= */
+   239,  /* (98) selcollist ::= sclp scanpt expr scanpt as */
+   239,  /* (99) selcollist ::= sclp scanpt STAR */
+   239,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */
+   250,  /* (101) as ::= AS nm */
+   250,  /* (102) as ::= */
+   240,  /* (103) from ::= */
+   240,  /* (104) from ::= FROM seltablist */
+   252,  /* (105) stl_prefix ::= seltablist joinop */
+   252,  /* (106) stl_prefix ::= */
+   251,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+   251,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+   251,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+   251,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+   196,  /* (111) dbnm ::= */
+   196,  /* (112) dbnm ::= DOT nm */
+   233,  /* (113) fullname ::= nm */
+   233,  /* (114) fullname ::= nm DOT nm */
+   258,  /* (115) xfullname ::= nm */
+   258,  /* (116) xfullname ::= nm DOT nm */
+   258,  /* (117) xfullname ::= nm DOT nm AS nm */
+   258,  /* (118) xfullname ::= nm AS nm */
+   253,  /* (119) joinop ::= COMMA|JOIN */
+   253,  /* (120) joinop ::= JOIN_KW JOIN */
+   253,  /* (121) joinop ::= JOIN_KW nm JOIN */
+   253,  /* (122) joinop ::= JOIN_KW nm nm JOIN */
+   255,  /* (123) on_opt ::= ON expr */
+   255,  /* (124) on_opt ::= */
+   254,  /* (125) indexed_opt ::= */
+   254,  /* (126) indexed_opt ::= INDEXED BY nm */
+   254,  /* (127) indexed_opt ::= NOT INDEXED */
+   256,  /* (128) using_opt ::= USING LP idlist RP */
+   256,  /* (129) using_opt ::= */
+   244,  /* (130) orderby_opt ::= */
+   244,  /* (131) orderby_opt ::= ORDER BY sortlist */
+   226,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
+   226,  /* (133) sortlist ::= expr sortorder nulls */
+   214,  /* (134) sortorder ::= ASC */
+   214,  /* (135) sortorder ::= DESC */
+   214,  /* (136) sortorder ::= */
+   260,  /* (137) nulls ::= NULLS FIRST */
+   260,  /* (138) nulls ::= NULLS LAST */
+   260,  /* (139) nulls ::= */
+   242,  /* (140) groupby_opt ::= */
+   242,  /* (141) groupby_opt ::= GROUP BY nexprlist */
+   243,  /* (142) having_opt ::= */
+   243,  /* (143) having_opt ::= HAVING expr */
+   245,  /* (144) limit_opt ::= */
+   245,  /* (145) limit_opt ::= LIMIT expr */
+   245,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */
+   245,  /* (147) limit_opt ::= LIMIT expr COMMA expr */
+   186,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
+   241,  /* (149) where_opt ::= */
+   241,  /* (150) where_opt ::= WHERE expr */
+   186,  /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt orderby_opt limit_opt */
+   262,  /* (152) setlist ::= setlist COMMA nm EQ expr */
+   262,  /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
+   262,  /* (154) setlist ::= nm EQ expr */
+   262,  /* (155) setlist ::= LP idlist RP EQ expr */
+   186,  /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+   186,  /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+   265,  /* (158) upsert ::= */
+   265,  /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+   265,  /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+   265,  /* (161) upsert ::= ON CONFLICT DO NOTHING */
+   263,  /* (162) insert_cmd ::= INSERT orconf */
+   263,  /* (163) insert_cmd ::= REPLACE */
+   264,  /* (164) idlist_opt ::= */
+   264,  /* (165) idlist_opt ::= LP idlist RP */
+   259,  /* (166) idlist ::= idlist COMMA nm */
+   259,  /* (167) idlist ::= nm */
+   212,  /* (168) expr ::= LP expr RP */
+   212,  /* (169) expr ::= ID|INDEXED */
+   212,  /* (170) expr ::= JOIN_KW */
+   212,  /* (171) expr ::= nm DOT nm */
+   212,  /* (172) expr ::= nm DOT nm DOT nm */
+   211,  /* (173) term ::= NULL|FLOAT|BLOB */
+   211,  /* (174) term ::= STRING */
+   211,  /* (175) term ::= INTEGER */
+   212,  /* (176) expr ::= VARIABLE */
+   212,  /* (177) expr ::= expr COLLATE ID|STRING */
+   212,  /* (178) expr ::= CAST LP expr AS typetoken RP */
+   212,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
+   212,  /* (180) expr ::= ID|INDEXED LP STAR RP */
+   212,  /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+   212,  /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
+   211,  /* (183) term ::= CTIME_KW */
+   212,  /* (184) expr ::= LP nexprlist COMMA expr RP */
+   212,  /* (185) expr ::= expr AND expr */
+   212,  /* (186) expr ::= expr OR expr */
+   212,  /* (187) expr ::= expr LT|GT|GE|LE expr */
+   212,  /* (188) expr ::= expr EQ|NE expr */
+   212,  /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+   212,  /* (190) expr ::= expr PLUS|MINUS expr */
+   212,  /* (191) expr ::= expr STAR|SLASH|REM expr */
+   212,  /* (192) expr ::= expr CONCAT expr */
+   267,  /* (193) likeop ::= NOT LIKE_KW|MATCH */
+   212,  /* (194) expr ::= expr likeop expr */
+   212,  /* (195) expr ::= expr likeop expr ESCAPE expr */
+   212,  /* (196) expr ::= expr ISNULL|NOTNULL */
+   212,  /* (197) expr ::= expr NOT NULL */
+   212,  /* (198) expr ::= expr IS expr */
+   212,  /* (199) expr ::= expr IS NOT expr */
+   212,  /* (200) expr ::= NOT expr */
+   212,  /* (201) expr ::= BITNOT expr */
+   212,  /* (202) expr ::= PLUS|MINUS expr */
+   268,  /* (203) between_op ::= BETWEEN */
+   268,  /* (204) between_op ::= NOT BETWEEN */
+   212,  /* (205) expr ::= expr between_op expr AND expr */
+   269,  /* (206) in_op ::= IN */
+   269,  /* (207) in_op ::= NOT IN */
+   212,  /* (208) expr ::= expr in_op LP exprlist RP */
+   212,  /* (209) expr ::= LP select RP */
+   212,  /* (210) expr ::= expr in_op LP select RP */
+   212,  /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
+   212,  /* (212) expr ::= EXISTS LP select RP */
+   212,  /* (213) expr ::= CASE case_operand case_exprlist case_else END */
+   272,  /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+   272,  /* (215) case_exprlist ::= WHEN expr THEN expr */
+   273,  /* (216) case_else ::= ELSE expr */
+   273,  /* (217) case_else ::= */
+   271,  /* (218) case_operand ::= expr */
+   271,  /* (219) case_operand ::= */
+   257,  /* (220) exprlist ::= */
+   248,  /* (221) nexprlist ::= nexprlist COMMA expr */
+   248,  /* (222) nexprlist ::= expr */
+   270,  /* (223) paren_exprlist ::= */
+   270,  /* (224) paren_exprlist ::= LP exprlist RP */
+   186,  /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+   274,  /* (226) uniqueflag ::= UNIQUE */
+   274,  /* (227) uniqueflag ::= */
+   216,  /* (228) eidlist_opt ::= */
+   216,  /* (229) eidlist_opt ::= LP eidlist RP */
+   227,  /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
+   227,  /* (231) eidlist ::= nm collate sortorder */
+   275,  /* (232) collate ::= */
+   275,  /* (233) collate ::= COLLATE ID|STRING */
+   186,  /* (234) cmd ::= DROP INDEX ifexists fullname */
+   186,  /* (235) cmd ::= VACUUM vinto */
+   186,  /* (236) cmd ::= VACUUM nm vinto */
+   276,  /* (237) vinto ::= INTO expr */
+   276,  /* (238) vinto ::= */
+   186,  /* (239) cmd ::= PRAGMA nm dbnm */
+   186,  /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
+   186,  /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+   186,  /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
+   186,  /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+   206,  /* (244) plus_num ::= PLUS INTEGER|FLOAT */
+   207,  /* (245) minus_num ::= MINUS INTEGER|FLOAT */
+   186,  /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+   278,  /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+   280,  /* (248) trigger_time ::= BEFORE|AFTER */
+   280,  /* (249) trigger_time ::= INSTEAD OF */
+   280,  /* (250) trigger_time ::= */
+   281,  /* (251) trigger_event ::= DELETE|INSERT */
+   281,  /* (252) trigger_event ::= UPDATE */
+   281,  /* (253) trigger_event ::= UPDATE OF idlist */
+   283,  /* (254) when_clause ::= */
+   283,  /* (255) when_clause ::= WHEN expr */
+   279,  /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+   279,  /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
+   285,  /* (258) trnm ::= nm DOT nm */
+   286,  /* (259) tridxby ::= INDEXED BY nm */
+   286,  /* (260) tridxby ::= NOT INDEXED */
+   284,  /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+   284,  /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+   284,  /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+   284,  /* (264) trigger_cmd ::= scanpt select scanpt */
+   212,  /* (265) expr ::= RAISE LP IGNORE RP */
+   212,  /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
+   231,  /* (267) raisetype ::= ROLLBACK */
+   231,  /* (268) raisetype ::= ABORT */
+   231,  /* (269) raisetype ::= FAIL */
+   186,  /* (270) cmd ::= DROP TRIGGER ifexists fullname */
+   186,  /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+   186,  /* (272) cmd ::= DETACH database_kw_opt expr */
+   288,  /* (273) key_opt ::= */
+   288,  /* (274) key_opt ::= KEY expr */
+   186,  /* (275) cmd ::= REINDEX */
+   186,  /* (276) cmd ::= REINDEX nm dbnm */
+   186,  /* (277) cmd ::= ANALYZE */
+   186,  /* (278) cmd ::= ANALYZE nm dbnm */
+   186,  /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
+   186,  /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+   289,  /* (281) add_column_fullname ::= fullname */
+   186,  /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+   186,  /* (283) cmd ::= create_vtab */
+   186,  /* (284) cmd ::= create_vtab LP vtabarglist RP */
+   291,  /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+   293,  /* (286) vtabarg ::= */
+   294,  /* (287) vtabargtoken ::= ANY */
+   294,  /* (288) vtabargtoken ::= lp anylist RP */
+   295,  /* (289) lp ::= LP */
+   261,  /* (290) with ::= WITH wqlist */
+   261,  /* (291) with ::= WITH RECURSIVE wqlist */
+   236,  /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
+   236,  /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+   297,  /* (294) windowdefn_list ::= windowdefn */
+   297,  /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+   298,  /* (296) windowdefn ::= nm AS LP window RP */
+   299,  /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+   299,  /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+   299,  /* (299) window ::= ORDER BY sortlist frame_opt */
+   299,  /* (300) window ::= nm ORDER BY sortlist frame_opt */
+   299,  /* (301) window ::= frame_opt */
+   299,  /* (302) window ::= nm frame_opt */
+   300,  /* (303) frame_opt ::= */
+   300,  /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+   300,  /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+   304,  /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
+   306,  /* (307) frame_bound_s ::= frame_bound */
+   306,  /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
+   307,  /* (309) frame_bound_e ::= frame_bound */
+   307,  /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
+   305,  /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
+   305,  /* (312) frame_bound ::= CURRENT ROW */
+   308,  /* (313) frame_exclude_opt ::= */
+   308,  /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
+   309,  /* (315) frame_exclude ::= NO OTHERS */
+   309,  /* (316) frame_exclude ::= CURRENT ROW */
+   309,  /* (317) frame_exclude ::= GROUP|TIES */
+   246,  /* (318) window_clause ::= WINDOW windowdefn_list */
+   266,  /* (319) filter_over ::= filter_clause over_clause */
+   266,  /* (320) filter_over ::= over_clause */
+   266,  /* (321) filter_over ::= filter_clause */
+   303,  /* (322) over_clause ::= OVER LP window RP */
+   303,  /* (323) over_clause ::= OVER nm */
+   302,  /* (324) filter_clause ::= FILTER LP WHERE expr RP */
+   181,  /* (325) input ::= cmdlist */
+   182,  /* (326) cmdlist ::= cmdlist ecmd */
+   182,  /* (327) cmdlist ::= ecmd */
+   183,  /* (328) ecmd ::= SEMI */
+   183,  /* (329) ecmd ::= cmdx SEMI */
+   183,  /* (330) ecmd ::= explain cmdx SEMI */
+   188,  /* (331) trans_opt ::= */
+   188,  /* (332) trans_opt ::= TRANSACTION */
+   188,  /* (333) trans_opt ::= TRANSACTION nm */
+   190,  /* (334) savepoint_opt ::= SAVEPOINT */
+   190,  /* (335) savepoint_opt ::= */
+   186,  /* (336) cmd ::= create_table create_table_args */
+   197,  /* (337) columnlist ::= columnlist COMMA columnname carglist */
+   197,  /* (338) columnlist ::= columnname carglist */
+   189,  /* (339) nm ::= ID|INDEXED */
+   189,  /* (340) nm ::= STRING */
+   189,  /* (341) nm ::= JOIN_KW */
+   203,  /* (342) typetoken ::= typename */
+   204,  /* (343) typename ::= ID|STRING */
+   205,  /* (344) signed ::= plus_num */
+   205,  /* (345) signed ::= minus_num */
+   202,  /* (346) carglist ::= carglist ccons */
+   202,  /* (347) carglist ::= */
+   210,  /* (348) ccons ::= NULL onconf */
+   210,  /* (349) ccons ::= GENERATED ALWAYS AS generated */
+   210,  /* (350) ccons ::= AS generated */
+   198,  /* (351) conslist_opt ::= COMMA conslist */
+   223,  /* (352) conslist ::= conslist tconscomma tcons */
+   223,  /* (353) conslist ::= tcons */
+   224,  /* (354) tconscomma ::= */
+   228,  /* (355) defer_subclause_opt ::= defer_subclause */
+   230,  /* (356) resolvetype ::= raisetype */
+   234,  /* (357) selectnowith ::= oneselect */
+   235,  /* (358) oneselect ::= values */
+   249,  /* (359) sclp ::= selcollist COMMA */
+   250,  /* (360) as ::= ID|STRING */
+   212,  /* (361) expr ::= term */
+   267,  /* (362) likeop ::= LIKE_KW|MATCH */
+   257,  /* (363) exprlist ::= nexprlist */
+   277,  /* (364) nmnum ::= plus_num */
+   277,  /* (365) nmnum ::= nm */
+   277,  /* (366) nmnum ::= ON */
+   277,  /* (367) nmnum ::= DELETE */
+   277,  /* (368) nmnum ::= DEFAULT */
+   206,  /* (369) plus_num ::= INTEGER|FLOAT */
+   282,  /* (370) foreach_clause ::= */
+   282,  /* (371) foreach_clause ::= FOR EACH ROW */
+   285,  /* (372) trnm ::= nm */
+   286,  /* (373) tridxby ::= */
+   287,  /* (374) database_kw_opt ::= DATABASE */
+   287,  /* (375) database_kw_opt ::= */
+   290,  /* (376) kwcolumn_opt ::= */
+   290,  /* (377) kwcolumn_opt ::= COLUMNKW */
+   292,  /* (378) vtabarglist ::= vtabarg */
+   292,  /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
+   293,  /* (380) vtabarg ::= vtabarg vtabargtoken */
+   296,  /* (381) anylist ::= */
+   296,  /* (382) anylist ::= anylist LP anylist RP */
+   296,  /* (383) anylist ::= anylist ANY */
+   261,  /* (384) with ::= */
 };
 
 /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
@@ -152774,344 +158118,348 @@ static const signed char yyRuleInfoNRhs[] = {
    -4,  /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
    -1,  /* (41) ccons ::= defer_subclause */
    -2,  /* (42) ccons ::= COLLATE ID|STRING */
-    0,  /* (43) autoinc ::= */
-   -1,  /* (44) autoinc ::= AUTOINCR */
-    0,  /* (45) refargs ::= */
-   -2,  /* (46) refargs ::= refargs refarg */
-   -2,  /* (47) refarg ::= MATCH nm */
-   -3,  /* (48) refarg ::= ON INSERT refact */
-   -3,  /* (49) refarg ::= ON DELETE refact */
-   -3,  /* (50) refarg ::= ON UPDATE refact */
-   -2,  /* (51) refact ::= SET NULL */
-   -2,  /* (52) refact ::= SET DEFAULT */
-   -1,  /* (53) refact ::= CASCADE */
-   -1,  /* (54) refact ::= RESTRICT */
-   -2,  /* (55) refact ::= NO ACTION */
-   -3,  /* (56) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-   -2,  /* (57) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-    0,  /* (58) init_deferred_pred_opt ::= */
-   -2,  /* (59) init_deferred_pred_opt ::= INITIALLY DEFERRED */
-   -2,  /* (60) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-    0,  /* (61) conslist_opt ::= */
-   -1,  /* (62) tconscomma ::= COMMA */
-   -2,  /* (63) tcons ::= CONSTRAINT nm */
-   -7,  /* (64) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-   -5,  /* (65) tcons ::= UNIQUE LP sortlist RP onconf */
-   -5,  /* (66) tcons ::= CHECK LP expr RP onconf */
-  -10,  /* (67) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
-    0,  /* (68) defer_subclause_opt ::= */
-    0,  /* (69) onconf ::= */
-   -3,  /* (70) onconf ::= ON CONFLICT resolvetype */
-    0,  /* (71) orconf ::= */
-   -2,  /* (72) orconf ::= OR resolvetype */
-   -1,  /* (73) resolvetype ::= IGNORE */
-   -1,  /* (74) resolvetype ::= REPLACE */
-   -4,  /* (75) cmd ::= DROP TABLE ifexists fullname */
-   -2,  /* (76) ifexists ::= IF EXISTS */
-    0,  /* (77) ifexists ::= */
-   -9,  /* (78) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
-   -4,  /* (79) cmd ::= DROP VIEW ifexists fullname */
-   -1,  /* (80) cmd ::= select */
-   -3,  /* (81) select ::= WITH wqlist selectnowith */
-   -4,  /* (82) select ::= WITH RECURSIVE wqlist selectnowith */
-   -1,  /* (83) select ::= selectnowith */
-   -3,  /* (84) selectnowith ::= selectnowith multiselect_op oneselect */
-   -1,  /* (85) multiselect_op ::= UNION */
-   -2,  /* (86) multiselect_op ::= UNION ALL */
-   -1,  /* (87) multiselect_op ::= EXCEPT|INTERSECT */
-   -9,  /* (88) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
-  -10,  /* (89) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
-   -4,  /* (90) values ::= VALUES LP nexprlist RP */
-   -5,  /* (91) values ::= values COMMA LP nexprlist RP */
-   -1,  /* (92) distinct ::= DISTINCT */
-   -1,  /* (93) distinct ::= ALL */
-    0,  /* (94) distinct ::= */
-    0,  /* (95) sclp ::= */
-   -5,  /* (96) selcollist ::= sclp scanpt expr scanpt as */
-   -3,  /* (97) selcollist ::= sclp scanpt STAR */
-   -5,  /* (98) selcollist ::= sclp scanpt nm DOT STAR */
-   -2,  /* (99) as ::= AS nm */
-    0,  /* (100) as ::= */
-    0,  /* (101) from ::= */
-   -2,  /* (102) from ::= FROM seltablist */
-   -2,  /* (103) stl_prefix ::= seltablist joinop */
-    0,  /* (104) stl_prefix ::= */
-   -7,  /* (105) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
-   -9,  /* (106) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
-   -7,  /* (107) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
-   -7,  /* (108) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
-    0,  /* (109) dbnm ::= */
-   -2,  /* (110) dbnm ::= DOT nm */
-   -1,  /* (111) fullname ::= nm */
-   -3,  /* (112) fullname ::= nm DOT nm */
-   -1,  /* (113) xfullname ::= nm */
-   -3,  /* (114) xfullname ::= nm DOT nm */
-   -5,  /* (115) xfullname ::= nm DOT nm AS nm */
-   -3,  /* (116) xfullname ::= nm AS nm */
-   -1,  /* (117) joinop ::= COMMA|JOIN */
-   -2,  /* (118) joinop ::= JOIN_KW JOIN */
-   -3,  /* (119) joinop ::= JOIN_KW nm JOIN */
-   -4,  /* (120) joinop ::= JOIN_KW nm nm JOIN */
-   -2,  /* (121) on_opt ::= ON expr */
-    0,  /* (122) on_opt ::= */
-    0,  /* (123) indexed_opt ::= */
-   -3,  /* (124) indexed_opt ::= INDEXED BY nm */
-   -2,  /* (125) indexed_opt ::= NOT INDEXED */
-   -4,  /* (126) using_opt ::= USING LP idlist RP */
-    0,  /* (127) using_opt ::= */
-    0,  /* (128) orderby_opt ::= */
-   -3,  /* (129) orderby_opt ::= ORDER BY sortlist */
-   -5,  /* (130) sortlist ::= sortlist COMMA expr sortorder nulls */
-   -3,  /* (131) sortlist ::= expr sortorder nulls */
-   -1,  /* (132) sortorder ::= ASC */
-   -1,  /* (133) sortorder ::= DESC */
-    0,  /* (134) sortorder ::= */
-   -2,  /* (135) nulls ::= NULLS FIRST */
-   -2,  /* (136) nulls ::= NULLS LAST */
-    0,  /* (137) nulls ::= */
-    0,  /* (138) groupby_opt ::= */
-   -3,  /* (139) groupby_opt ::= GROUP BY nexprlist */
-    0,  /* (140) having_opt ::= */
-   -2,  /* (141) having_opt ::= HAVING expr */
-    0,  /* (142) limit_opt ::= */
-   -2,  /* (143) limit_opt ::= LIMIT expr */
-   -4,  /* (144) limit_opt ::= LIMIT expr OFFSET expr */
-   -4,  /* (145) limit_opt ::= LIMIT expr COMMA expr */
-   -8,  /* (146) cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
-    0,  /* (147) where_opt ::= */
-   -2,  /* (148) where_opt ::= WHERE expr */
-  -10,  /* (149) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt orderby_opt limit_opt */
-   -5,  /* (150) setlist ::= setlist COMMA nm EQ expr */
-   -7,  /* (151) setlist ::= setlist COMMA LP idlist RP EQ expr */
-   -3,  /* (152) setlist ::= nm EQ expr */
-   -5,  /* (153) setlist ::= LP idlist RP EQ expr */
-   -7,  /* (154) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
-   -7,  /* (155) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
-    0,  /* (156) upsert ::= */
-  -11,  /* (157) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
-   -8,  /* (158) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
-   -4,  /* (159) upsert ::= ON CONFLICT DO NOTHING */
-   -2,  /* (160) insert_cmd ::= INSERT orconf */
-   -1,  /* (161) insert_cmd ::= REPLACE */
-    0,  /* (162) idlist_opt ::= */
-   -3,  /* (163) idlist_opt ::= LP idlist RP */
-   -3,  /* (164) idlist ::= idlist COMMA nm */
-   -1,  /* (165) idlist ::= nm */
-   -3,  /* (166) expr ::= LP expr RP */
-   -1,  /* (167) expr ::= ID|INDEXED */
-   -1,  /* (168) expr ::= JOIN_KW */
-   -3,  /* (169) expr ::= nm DOT nm */
-   -5,  /* (170) expr ::= nm DOT nm DOT nm */
-   -1,  /* (171) term ::= NULL|FLOAT|BLOB */
-   -1,  /* (172) term ::= STRING */
-   -1,  /* (173) term ::= INTEGER */
-   -1,  /* (174) expr ::= VARIABLE */
-   -3,  /* (175) expr ::= expr COLLATE ID|STRING */
-   -6,  /* (176) expr ::= CAST LP expr AS typetoken RP */
-   -5,  /* (177) expr ::= ID|INDEXED LP distinct exprlist RP */
-   -4,  /* (178) expr ::= ID|INDEXED LP STAR RP */
-   -6,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
-   -5,  /* (180) expr ::= ID|INDEXED LP STAR RP filter_over */
-   -1,  /* (181) term ::= CTIME_KW */
-   -5,  /* (182) expr ::= LP nexprlist COMMA expr RP */
-   -3,  /* (183) expr ::= expr AND expr */
-   -3,  /* (184) expr ::= expr OR expr */
-   -3,  /* (185) expr ::= expr LT|GT|GE|LE expr */
-   -3,  /* (186) expr ::= expr EQ|NE expr */
-   -3,  /* (187) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
-   -3,  /* (188) expr ::= expr PLUS|MINUS expr */
-   -3,  /* (189) expr ::= expr STAR|SLASH|REM expr */
-   -3,  /* (190) expr ::= expr CONCAT expr */
-   -2,  /* (191) likeop ::= NOT LIKE_KW|MATCH */
-   -3,  /* (192) expr ::= expr likeop expr */
-   -5,  /* (193) expr ::= expr likeop expr ESCAPE expr */
-   -2,  /* (194) expr ::= expr ISNULL|NOTNULL */
-   -3,  /* (195) expr ::= expr NOT NULL */
-   -3,  /* (196) expr ::= expr IS expr */
-   -4,  /* (197) expr ::= expr IS NOT expr */
-   -2,  /* (198) expr ::= NOT expr */
-   -2,  /* (199) expr ::= BITNOT expr */
-   -2,  /* (200) expr ::= PLUS|MINUS expr */
-   -1,  /* (201) between_op ::= BETWEEN */
-   -2,  /* (202) between_op ::= NOT BETWEEN */
-   -5,  /* (203) expr ::= expr between_op expr AND expr */
-   -1,  /* (204) in_op ::= IN */
-   -2,  /* (205) in_op ::= NOT IN */
-   -5,  /* (206) expr ::= expr in_op LP exprlist RP */
-   -3,  /* (207) expr ::= LP select RP */
-   -5,  /* (208) expr ::= expr in_op LP select RP */
-   -5,  /* (209) expr ::= expr in_op nm dbnm paren_exprlist */
-   -4,  /* (210) expr ::= EXISTS LP select RP */
-   -5,  /* (211) expr ::= CASE case_operand case_exprlist case_else END */
-   -5,  /* (212) case_exprlist ::= case_exprlist WHEN expr THEN expr */
-   -4,  /* (213) case_exprlist ::= WHEN expr THEN expr */
-   -2,  /* (214) case_else ::= ELSE expr */
-    0,  /* (215) case_else ::= */
-   -1,  /* (216) case_operand ::= expr */
-    0,  /* (217) case_operand ::= */
-    0,  /* (218) exprlist ::= */
-   -3,  /* (219) nexprlist ::= nexprlist COMMA expr */
-   -1,  /* (220) nexprlist ::= expr */
-    0,  /* (221) paren_exprlist ::= */
-   -3,  /* (222) paren_exprlist ::= LP exprlist RP */
-  -12,  /* (223) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
-   -1,  /* (224) uniqueflag ::= UNIQUE */
-    0,  /* (225) uniqueflag ::= */
-    0,  /* (226) eidlist_opt ::= */
-   -3,  /* (227) eidlist_opt ::= LP eidlist RP */
-   -5,  /* (228) eidlist ::= eidlist COMMA nm collate sortorder */
-   -3,  /* (229) eidlist ::= nm collate sortorder */
-    0,  /* (230) collate ::= */
-   -2,  /* (231) collate ::= COLLATE ID|STRING */
-   -4,  /* (232) cmd ::= DROP INDEX ifexists fullname */
-   -2,  /* (233) cmd ::= VACUUM vinto */
-   -3,  /* (234) cmd ::= VACUUM nm vinto */
-   -2,  /* (235) vinto ::= INTO expr */
-    0,  /* (236) vinto ::= */
-   -3,  /* (237) cmd ::= PRAGMA nm dbnm */
-   -5,  /* (238) cmd ::= PRAGMA nm dbnm EQ nmnum */
-   -6,  /* (239) cmd ::= PRAGMA nm dbnm LP nmnum RP */
-   -5,  /* (240) cmd ::= PRAGMA nm dbnm EQ minus_num */
-   -6,  /* (241) cmd ::= PRAGMA nm dbnm LP minus_num RP */
-   -2,  /* (242) plus_num ::= PLUS INTEGER|FLOAT */
-   -2,  /* (243) minus_num ::= MINUS INTEGER|FLOAT */
-   -5,  /* (244) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
-  -11,  /* (245) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
-   -1,  /* (246) trigger_time ::= BEFORE|AFTER */
-   -2,  /* (247) trigger_time ::= INSTEAD OF */
-    0,  /* (248) trigger_time ::= */
-   -1,  /* (249) trigger_event ::= DELETE|INSERT */
-   -1,  /* (250) trigger_event ::= UPDATE */
-   -3,  /* (251) trigger_event ::= UPDATE OF idlist */
-    0,  /* (252) when_clause ::= */
-   -2,  /* (253) when_clause ::= WHEN expr */
-   -3,  /* (254) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
-   -2,  /* (255) trigger_cmd_list ::= trigger_cmd SEMI */
-   -3,  /* (256) trnm ::= nm DOT nm */
-   -3,  /* (257) tridxby ::= INDEXED BY nm */
-   -2,  /* (258) tridxby ::= NOT INDEXED */
-   -8,  /* (259) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
-   -8,  /* (260) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
-   -6,  /* (261) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-   -3,  /* (262) trigger_cmd ::= scanpt select scanpt */
-   -4,  /* (263) expr ::= RAISE LP IGNORE RP */
-   -6,  /* (264) expr ::= RAISE LP raisetype COMMA nm RP */
-   -1,  /* (265) raisetype ::= ROLLBACK */
-   -1,  /* (266) raisetype ::= ABORT */
-   -1,  /* (267) raisetype ::= FAIL */
-   -4,  /* (268) cmd ::= DROP TRIGGER ifexists fullname */
-   -6,  /* (269) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
-   -3,  /* (270) cmd ::= DETACH database_kw_opt expr */
-    0,  /* (271) key_opt ::= */
-   -2,  /* (272) key_opt ::= KEY expr */
-   -1,  /* (273) cmd ::= REINDEX */
-   -3,  /* (274) cmd ::= REINDEX nm dbnm */
-   -1,  /* (275) cmd ::= ANALYZE */
-   -3,  /* (276) cmd ::= ANALYZE nm dbnm */
-   -6,  /* (277) cmd ::= ALTER TABLE fullname RENAME TO nm */
-   -7,  /* (278) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
-   -1,  /* (279) add_column_fullname ::= fullname */
-   -8,  /* (280) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
-   -1,  /* (281) cmd ::= create_vtab */
-   -4,  /* (282) cmd ::= create_vtab LP vtabarglist RP */
-   -8,  /* (283) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
-    0,  /* (284) vtabarg ::= */
-   -1,  /* (285) vtabargtoken ::= ANY */
-   -3,  /* (286) vtabargtoken ::= lp anylist RP */
-   -1,  /* (287) lp ::= LP */
-   -2,  /* (288) with ::= WITH wqlist */
-   -3,  /* (289) with ::= WITH RECURSIVE wqlist */
-   -6,  /* (290) wqlist ::= nm eidlist_opt AS LP select RP */
-   -8,  /* (291) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
-   -1,  /* (292) windowdefn_list ::= windowdefn */
-   -3,  /* (293) windowdefn_list ::= windowdefn_list COMMA windowdefn */
-   -5,  /* (294) windowdefn ::= nm AS LP window RP */
-   -5,  /* (295) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
-   -6,  /* (296) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
-   -4,  /* (297) window ::= ORDER BY sortlist frame_opt */
-   -5,  /* (298) window ::= nm ORDER BY sortlist frame_opt */
-   -1,  /* (299) window ::= frame_opt */
-   -2,  /* (300) window ::= nm frame_opt */
-    0,  /* (301) frame_opt ::= */
-   -3,  /* (302) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-   -6,  /* (303) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-   -1,  /* (304) range_or_rows ::= RANGE|ROWS|GROUPS */
-   -1,  /* (305) frame_bound_s ::= frame_bound */
-   -2,  /* (306) frame_bound_s ::= UNBOUNDED PRECEDING */
-   -1,  /* (307) frame_bound_e ::= frame_bound */
-   -2,  /* (308) frame_bound_e ::= UNBOUNDED FOLLOWING */
-   -2,  /* (309) frame_bound ::= expr PRECEDING|FOLLOWING */
-   -2,  /* (310) frame_bound ::= CURRENT ROW */
-    0,  /* (311) frame_exclude_opt ::= */
-   -2,  /* (312) frame_exclude_opt ::= EXCLUDE frame_exclude */
-   -2,  /* (313) frame_exclude ::= NO OTHERS */
-   -2,  /* (314) frame_exclude ::= CURRENT ROW */
-   -1,  /* (315) frame_exclude ::= GROUP|TIES */
-   -2,  /* (316) window_clause ::= WINDOW windowdefn_list */
-   -2,  /* (317) filter_over ::= filter_clause over_clause */
-   -1,  /* (318) filter_over ::= over_clause */
-   -1,  /* (319) filter_over ::= filter_clause */
-   -4,  /* (320) over_clause ::= OVER LP window RP */
-   -2,  /* (321) over_clause ::= OVER nm */
-   -5,  /* (322) filter_clause ::= FILTER LP WHERE expr RP */
-   -1,  /* (323) input ::= cmdlist */
-   -2,  /* (324) cmdlist ::= cmdlist ecmd */
-   -1,  /* (325) cmdlist ::= ecmd */
-   -1,  /* (326) ecmd ::= SEMI */
-   -2,  /* (327) ecmd ::= cmdx SEMI */
-   -2,  /* (328) ecmd ::= explain cmdx */
-    0,  /* (329) trans_opt ::= */
-   -1,  /* (330) trans_opt ::= TRANSACTION */
-   -2,  /* (331) trans_opt ::= TRANSACTION nm */
-   -1,  /* (332) savepoint_opt ::= SAVEPOINT */
-    0,  /* (333) savepoint_opt ::= */
-   -2,  /* (334) cmd ::= create_table create_table_args */
-   -4,  /* (335) columnlist ::= columnlist COMMA columnname carglist */
-   -2,  /* (336) columnlist ::= columnname carglist */
-   -1,  /* (337) nm ::= ID|INDEXED */
-   -1,  /* (338) nm ::= STRING */
-   -1,  /* (339) nm ::= JOIN_KW */
-   -1,  /* (340) typetoken ::= typename */
-   -1,  /* (341) typename ::= ID|STRING */
-   -1,  /* (342) signed ::= plus_num */
-   -1,  /* (343) signed ::= minus_num */
-   -2,  /* (344) carglist ::= carglist ccons */
-    0,  /* (345) carglist ::= */
-   -2,  /* (346) ccons ::= NULL onconf */
-   -2,  /* (347) conslist_opt ::= COMMA conslist */
-   -3,  /* (348) conslist ::= conslist tconscomma tcons */
-   -1,  /* (349) conslist ::= tcons */
-    0,  /* (350) tconscomma ::= */
-   -1,  /* (351) defer_subclause_opt ::= defer_subclause */
-   -1,  /* (352) resolvetype ::= raisetype */
-   -1,  /* (353) selectnowith ::= oneselect */
-   -1,  /* (354) oneselect ::= values */
-   -2,  /* (355) sclp ::= selcollist COMMA */
-   -1,  /* (356) as ::= ID|STRING */
-   -1,  /* (357) expr ::= term */
-   -1,  /* (358) likeop ::= LIKE_KW|MATCH */
-   -1,  /* (359) exprlist ::= nexprlist */
-   -1,  /* (360) nmnum ::= plus_num */
-   -1,  /* (361) nmnum ::= nm */
-   -1,  /* (362) nmnum ::= ON */
-   -1,  /* (363) nmnum ::= DELETE */
-   -1,  /* (364) nmnum ::= DEFAULT */
-   -1,  /* (365) plus_num ::= INTEGER|FLOAT */
-    0,  /* (366) foreach_clause ::= */
-   -3,  /* (367) foreach_clause ::= FOR EACH ROW */
-   -1,  /* (368) trnm ::= nm */
-    0,  /* (369) tridxby ::= */
-   -1,  /* (370) database_kw_opt ::= DATABASE */
-    0,  /* (371) database_kw_opt ::= */
-    0,  /* (372) kwcolumn_opt ::= */
-   -1,  /* (373) kwcolumn_opt ::= COLUMNKW */
-   -1,  /* (374) vtabarglist ::= vtabarg */
-   -3,  /* (375) vtabarglist ::= vtabarglist COMMA vtabarg */
-   -2,  /* (376) vtabarg ::= vtabarg vtabargtoken */
-    0,  /* (377) anylist ::= */
-   -4,  /* (378) anylist ::= anylist LP anylist RP */
-   -2,  /* (379) anylist ::= anylist ANY */
-    0,  /* (380) with ::= */
+   -3,  /* (43) generated ::= LP expr RP */
+   -4,  /* (44) generated ::= LP expr RP ID */
+    0,  /* (45) autoinc ::= */
+   -1,  /* (46) autoinc ::= AUTOINCR */
+    0,  /* (47) refargs ::= */
+   -2,  /* (48) refargs ::= refargs refarg */
+   -2,  /* (49) refarg ::= MATCH nm */
+   -3,  /* (50) refarg ::= ON INSERT refact */
+   -3,  /* (51) refarg ::= ON DELETE refact */
+   -3,  /* (52) refarg ::= ON UPDATE refact */
+   -2,  /* (53) refact ::= SET NULL */
+   -2,  /* (54) refact ::= SET DEFAULT */
+   -1,  /* (55) refact ::= CASCADE */
+   -1,  /* (56) refact ::= RESTRICT */
+   -2,  /* (57) refact ::= NO ACTION */
+   -3,  /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+   -2,  /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+    0,  /* (60) init_deferred_pred_opt ::= */
+   -2,  /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
+   -2,  /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+    0,  /* (63) conslist_opt ::= */
+   -1,  /* (64) tconscomma ::= COMMA */
+   -2,  /* (65) tcons ::= CONSTRAINT nm */
+   -7,  /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+   -5,  /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
+   -5,  /* (68) tcons ::= CHECK LP expr RP onconf */
+  -10,  /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+    0,  /* (70) defer_subclause_opt ::= */
+    0,  /* (71) onconf ::= */
+   -3,  /* (72) onconf ::= ON CONFLICT resolvetype */
+    0,  /* (73) orconf ::= */
+   -2,  /* (74) orconf ::= OR resolvetype */
+   -1,  /* (75) resolvetype ::= IGNORE */
+   -1,  /* (76) resolvetype ::= REPLACE */
+   -4,  /* (77) cmd ::= DROP TABLE ifexists fullname */
+   -2,  /* (78) ifexists ::= IF EXISTS */
+    0,  /* (79) ifexists ::= */
+   -9,  /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+   -4,  /* (81) cmd ::= DROP VIEW ifexists fullname */
+   -1,  /* (82) cmd ::= select */
+   -3,  /* (83) select ::= WITH wqlist selectnowith */
+   -4,  /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
+   -1,  /* (85) select ::= selectnowith */
+   -3,  /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
+   -1,  /* (87) multiselect_op ::= UNION */
+   -2,  /* (88) multiselect_op ::= UNION ALL */
+   -1,  /* (89) multiselect_op ::= EXCEPT|INTERSECT */
+   -9,  /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+  -10,  /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+   -4,  /* (92) values ::= VALUES LP nexprlist RP */
+   -5,  /* (93) values ::= values COMMA LP nexprlist RP */
+   -1,  /* (94) distinct ::= DISTINCT */
+   -1,  /* (95) distinct ::= ALL */
+    0,  /* (96) distinct ::= */
+    0,  /* (97) sclp ::= */
+   -5,  /* (98) selcollist ::= sclp scanpt expr scanpt as */
+   -3,  /* (99) selcollist ::= sclp scanpt STAR */
+   -5,  /* (100) selcollist ::= sclp scanpt nm DOT STAR */
+   -2,  /* (101) as ::= AS nm */
+    0,  /* (102) as ::= */
+    0,  /* (103) from ::= */
+   -2,  /* (104) from ::= FROM seltablist */
+   -2,  /* (105) stl_prefix ::= seltablist joinop */
+    0,  /* (106) stl_prefix ::= */
+   -7,  /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+   -9,  /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+   -7,  /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+   -7,  /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+    0,  /* (111) dbnm ::= */
+   -2,  /* (112) dbnm ::= DOT nm */
+   -1,  /* (113) fullname ::= nm */
+   -3,  /* (114) fullname ::= nm DOT nm */
+   -1,  /* (115) xfullname ::= nm */
+   -3,  /* (116) xfullname ::= nm DOT nm */
+   -5,  /* (117) xfullname ::= nm DOT nm AS nm */
+   -3,  /* (118) xfullname ::= nm AS nm */
+   -1,  /* (119) joinop ::= COMMA|JOIN */
+   -2,  /* (120) joinop ::= JOIN_KW JOIN */
+   -3,  /* (121) joinop ::= JOIN_KW nm JOIN */
+   -4,  /* (122) joinop ::= JOIN_KW nm nm JOIN */
+   -2,  /* (123) on_opt ::= ON expr */
+    0,  /* (124) on_opt ::= */
+    0,  /* (125) indexed_opt ::= */
+   -3,  /* (126) indexed_opt ::= INDEXED BY nm */
+   -2,  /* (127) indexed_opt ::= NOT INDEXED */
+   -4,  /* (128) using_opt ::= USING LP idlist RP */
+    0,  /* (129) using_opt ::= */
+    0,  /* (130) orderby_opt ::= */
+   -3,  /* (131) orderby_opt ::= ORDER BY sortlist */
+   -5,  /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
+   -3,  /* (133) sortlist ::= expr sortorder nulls */
+   -1,  /* (134) sortorder ::= ASC */
+   -1,  /* (135) sortorder ::= DESC */
+    0,  /* (136) sortorder ::= */
+   -2,  /* (137) nulls ::= NULLS FIRST */
+   -2,  /* (138) nulls ::= NULLS LAST */
+    0,  /* (139) nulls ::= */
+    0,  /* (140) groupby_opt ::= */
+   -3,  /* (141) groupby_opt ::= GROUP BY nexprlist */
+    0,  /* (142) having_opt ::= */
+   -2,  /* (143) having_opt ::= HAVING expr */
+    0,  /* (144) limit_opt ::= */
+   -2,  /* (145) limit_opt ::= LIMIT expr */
+   -4,  /* (146) limit_opt ::= LIMIT expr OFFSET expr */
+   -4,  /* (147) limit_opt ::= LIMIT expr COMMA expr */
+   -8,  /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
+    0,  /* (149) where_opt ::= */
+   -2,  /* (150) where_opt ::= WHERE expr */
+  -11,  /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt orderby_opt limit_opt */
+   -5,  /* (152) setlist ::= setlist COMMA nm EQ expr */
+   -7,  /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
+   -3,  /* (154) setlist ::= nm EQ expr */
+   -5,  /* (155) setlist ::= LP idlist RP EQ expr */
+   -7,  /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+   -7,  /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+    0,  /* (158) upsert ::= */
+  -11,  /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+   -8,  /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+   -4,  /* (161) upsert ::= ON CONFLICT DO NOTHING */
+   -2,  /* (162) insert_cmd ::= INSERT orconf */
+   -1,  /* (163) insert_cmd ::= REPLACE */
+    0,  /* (164) idlist_opt ::= */
+   -3,  /* (165) idlist_opt ::= LP idlist RP */
+   -3,  /* (166) idlist ::= idlist COMMA nm */
+   -1,  /* (167) idlist ::= nm */
+   -3,  /* (168) expr ::= LP expr RP */
+   -1,  /* (169) expr ::= ID|INDEXED */
+   -1,  /* (170) expr ::= JOIN_KW */
+   -3,  /* (171) expr ::= nm DOT nm */
+   -5,  /* (172) expr ::= nm DOT nm DOT nm */
+   -1,  /* (173) term ::= NULL|FLOAT|BLOB */
+   -1,  /* (174) term ::= STRING */
+   -1,  /* (175) term ::= INTEGER */
+   -1,  /* (176) expr ::= VARIABLE */
+   -3,  /* (177) expr ::= expr COLLATE ID|STRING */
+   -6,  /* (178) expr ::= CAST LP expr AS typetoken RP */
+   -5,  /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
+   -4,  /* (180) expr ::= ID|INDEXED LP STAR RP */
+   -6,  /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+   -5,  /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
+   -1,  /* (183) term ::= CTIME_KW */
+   -5,  /* (184) expr ::= LP nexprlist COMMA expr RP */
+   -3,  /* (185) expr ::= expr AND expr */
+   -3,  /* (186) expr ::= expr OR expr */
+   -3,  /* (187) expr ::= expr LT|GT|GE|LE expr */
+   -3,  /* (188) expr ::= expr EQ|NE expr */
+   -3,  /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
+   -3,  /* (190) expr ::= expr PLUS|MINUS expr */
+   -3,  /* (191) expr ::= expr STAR|SLASH|REM expr */
+   -3,  /* (192) expr ::= expr CONCAT expr */
+   -2,  /* (193) likeop ::= NOT LIKE_KW|MATCH */
+   -3,  /* (194) expr ::= expr likeop expr */
+   -5,  /* (195) expr ::= expr likeop expr ESCAPE expr */
+   -2,  /* (196) expr ::= expr ISNULL|NOTNULL */
+   -3,  /* (197) expr ::= expr NOT NULL */
+   -3,  /* (198) expr ::= expr IS expr */
+   -4,  /* (199) expr ::= expr IS NOT expr */
+   -2,  /* (200) expr ::= NOT expr */
+   -2,  /* (201) expr ::= BITNOT expr */
+   -2,  /* (202) expr ::= PLUS|MINUS expr */
+   -1,  /* (203) between_op ::= BETWEEN */
+   -2,  /* (204) between_op ::= NOT BETWEEN */
+   -5,  /* (205) expr ::= expr between_op expr AND expr */
+   -1,  /* (206) in_op ::= IN */
+   -2,  /* (207) in_op ::= NOT IN */
+   -5,  /* (208) expr ::= expr in_op LP exprlist RP */
+   -3,  /* (209) expr ::= LP select RP */
+   -5,  /* (210) expr ::= expr in_op LP select RP */
+   -5,  /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
+   -4,  /* (212) expr ::= EXISTS LP select RP */
+   -5,  /* (213) expr ::= CASE case_operand case_exprlist case_else END */
+   -5,  /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
+   -4,  /* (215) case_exprlist ::= WHEN expr THEN expr */
+   -2,  /* (216) case_else ::= ELSE expr */
+    0,  /* (217) case_else ::= */
+   -1,  /* (218) case_operand ::= expr */
+    0,  /* (219) case_operand ::= */
+    0,  /* (220) exprlist ::= */
+   -3,  /* (221) nexprlist ::= nexprlist COMMA expr */
+   -1,  /* (222) nexprlist ::= expr */
+    0,  /* (223) paren_exprlist ::= */
+   -3,  /* (224) paren_exprlist ::= LP exprlist RP */
+  -12,  /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+   -1,  /* (226) uniqueflag ::= UNIQUE */
+    0,  /* (227) uniqueflag ::= */
+    0,  /* (228) eidlist_opt ::= */
+   -3,  /* (229) eidlist_opt ::= LP eidlist RP */
+   -5,  /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
+   -3,  /* (231) eidlist ::= nm collate sortorder */
+    0,  /* (232) collate ::= */
+   -2,  /* (233) collate ::= COLLATE ID|STRING */
+   -4,  /* (234) cmd ::= DROP INDEX ifexists fullname */
+   -2,  /* (235) cmd ::= VACUUM vinto */
+   -3,  /* (236) cmd ::= VACUUM nm vinto */
+   -2,  /* (237) vinto ::= INTO expr */
+    0,  /* (238) vinto ::= */
+   -3,  /* (239) cmd ::= PRAGMA nm dbnm */
+   -5,  /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
+   -6,  /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
+   -5,  /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
+   -6,  /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
+   -2,  /* (244) plus_num ::= PLUS INTEGER|FLOAT */
+   -2,  /* (245) minus_num ::= MINUS INTEGER|FLOAT */
+   -5,  /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+  -11,  /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+   -1,  /* (248) trigger_time ::= BEFORE|AFTER */
+   -2,  /* (249) trigger_time ::= INSTEAD OF */
+    0,  /* (250) trigger_time ::= */
+   -1,  /* (251) trigger_event ::= DELETE|INSERT */
+   -1,  /* (252) trigger_event ::= UPDATE */
+   -3,  /* (253) trigger_event ::= UPDATE OF idlist */
+    0,  /* (254) when_clause ::= */
+   -2,  /* (255) when_clause ::= WHEN expr */
+   -3,  /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+   -2,  /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
+   -3,  /* (258) trnm ::= nm DOT nm */
+   -3,  /* (259) tridxby ::= INDEXED BY nm */
+   -2,  /* (260) tridxby ::= NOT INDEXED */
+   -9,  /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+   -8,  /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+   -6,  /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+   -3,  /* (264) trigger_cmd ::= scanpt select scanpt */
+   -4,  /* (265) expr ::= RAISE LP IGNORE RP */
+   -6,  /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
+   -1,  /* (267) raisetype ::= ROLLBACK */
+   -1,  /* (268) raisetype ::= ABORT */
+   -1,  /* (269) raisetype ::= FAIL */
+   -4,  /* (270) cmd ::= DROP TRIGGER ifexists fullname */
+   -6,  /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+   -3,  /* (272) cmd ::= DETACH database_kw_opt expr */
+    0,  /* (273) key_opt ::= */
+   -2,  /* (274) key_opt ::= KEY expr */
+   -1,  /* (275) cmd ::= REINDEX */
+   -3,  /* (276) cmd ::= REINDEX nm dbnm */
+   -1,  /* (277) cmd ::= ANALYZE */
+   -3,  /* (278) cmd ::= ANALYZE nm dbnm */
+   -6,  /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
+   -7,  /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+   -1,  /* (281) add_column_fullname ::= fullname */
+   -8,  /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+   -1,  /* (283) cmd ::= create_vtab */
+   -4,  /* (284) cmd ::= create_vtab LP vtabarglist RP */
+   -8,  /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+    0,  /* (286) vtabarg ::= */
+   -1,  /* (287) vtabargtoken ::= ANY */
+   -3,  /* (288) vtabargtoken ::= lp anylist RP */
+   -1,  /* (289) lp ::= LP */
+   -2,  /* (290) with ::= WITH wqlist */
+   -3,  /* (291) with ::= WITH RECURSIVE wqlist */
+   -6,  /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
+   -8,  /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+   -1,  /* (294) windowdefn_list ::= windowdefn */
+   -3,  /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
+   -5,  /* (296) windowdefn ::= nm AS LP window RP */
+   -5,  /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+   -6,  /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+   -4,  /* (299) window ::= ORDER BY sortlist frame_opt */
+   -5,  /* (300) window ::= nm ORDER BY sortlist frame_opt */
+   -1,  /* (301) window ::= frame_opt */
+   -2,  /* (302) window ::= nm frame_opt */
+    0,  /* (303) frame_opt ::= */
+   -3,  /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+   -6,  /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+   -1,  /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
+   -1,  /* (307) frame_bound_s ::= frame_bound */
+   -2,  /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
+   -1,  /* (309) frame_bound_e ::= frame_bound */
+   -2,  /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
+   -2,  /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
+   -2,  /* (312) frame_bound ::= CURRENT ROW */
+    0,  /* (313) frame_exclude_opt ::= */
+   -2,  /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
+   -2,  /* (315) frame_exclude ::= NO OTHERS */
+   -2,  /* (316) frame_exclude ::= CURRENT ROW */
+   -1,  /* (317) frame_exclude ::= GROUP|TIES */
+   -2,  /* (318) window_clause ::= WINDOW windowdefn_list */
+   -2,  /* (319) filter_over ::= filter_clause over_clause */
+   -1,  /* (320) filter_over ::= over_clause */
+   -1,  /* (321) filter_over ::= filter_clause */
+   -4,  /* (322) over_clause ::= OVER LP window RP */
+   -2,  /* (323) over_clause ::= OVER nm */
+   -5,  /* (324) filter_clause ::= FILTER LP WHERE expr RP */
+   -1,  /* (325) input ::= cmdlist */
+   -2,  /* (326) cmdlist ::= cmdlist ecmd */
+   -1,  /* (327) cmdlist ::= ecmd */
+   -1,  /* (328) ecmd ::= SEMI */
+   -2,  /* (329) ecmd ::= cmdx SEMI */
+   -3,  /* (330) ecmd ::= explain cmdx SEMI */
+    0,  /* (331) trans_opt ::= */
+   -1,  /* (332) trans_opt ::= TRANSACTION */
+   -2,  /* (333) trans_opt ::= TRANSACTION nm */
+   -1,  /* (334) savepoint_opt ::= SAVEPOINT */
+    0,  /* (335) savepoint_opt ::= */
+   -2,  /* (336) cmd ::= create_table create_table_args */
+   -4,  /* (337) columnlist ::= columnlist COMMA columnname carglist */
+   -2,  /* (338) columnlist ::= columnname carglist */
+   -1,  /* (339) nm ::= ID|INDEXED */
+   -1,  /* (340) nm ::= STRING */
+   -1,  /* (341) nm ::= JOIN_KW */
+   -1,  /* (342) typetoken ::= typename */
+   -1,  /* (343) typename ::= ID|STRING */
+   -1,  /* (344) signed ::= plus_num */
+   -1,  /* (345) signed ::= minus_num */
+   -2,  /* (346) carglist ::= carglist ccons */
+    0,  /* (347) carglist ::= */
+   -2,  /* (348) ccons ::= NULL onconf */
+   -4,  /* (349) ccons ::= GENERATED ALWAYS AS generated */
+   -2,  /* (350) ccons ::= AS generated */
+   -2,  /* (351) conslist_opt ::= COMMA conslist */
+   -3,  /* (352) conslist ::= conslist tconscomma tcons */
+   -1,  /* (353) conslist ::= tcons */
+    0,  /* (354) tconscomma ::= */
+   -1,  /* (355) defer_subclause_opt ::= defer_subclause */
+   -1,  /* (356) resolvetype ::= raisetype */
+   -1,  /* (357) selectnowith ::= oneselect */
+   -1,  /* (358) oneselect ::= values */
+   -2,  /* (359) sclp ::= selcollist COMMA */
+   -1,  /* (360) as ::= ID|STRING */
+   -1,  /* (361) expr ::= term */
+   -1,  /* (362) likeop ::= LIKE_KW|MATCH */
+   -1,  /* (363) exprlist ::= nexprlist */
+   -1,  /* (364) nmnum ::= plus_num */
+   -1,  /* (365) nmnum ::= nm */
+   -1,  /* (366) nmnum ::= ON */
+   -1,  /* (367) nmnum ::= DELETE */
+   -1,  /* (368) nmnum ::= DEFAULT */
+   -1,  /* (369) plus_num ::= INTEGER|FLOAT */
+    0,  /* (370) foreach_clause ::= */
+   -3,  /* (371) foreach_clause ::= FOR EACH ROW */
+   -1,  /* (372) trnm ::= nm */
+    0,  /* (373) tridxby ::= */
+   -1,  /* (374) database_kw_opt ::= DATABASE */
+    0,  /* (375) database_kw_opt ::= */
+    0,  /* (376) kwcolumn_opt ::= */
+   -1,  /* (377) kwcolumn_opt ::= COLUMNKW */
+   -1,  /* (378) vtabarglist ::= vtabarg */
+   -3,  /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
+   -2,  /* (380) vtabarg ::= vtabarg vtabargtoken */
+    0,  /* (381) anylist ::= */
+   -4,  /* (382) anylist ::= anylist LP anylist RP */
+   -2,  /* (383) anylist ::= anylist ANY */
+    0,  /* (384) with ::= */
 };
 
 static void yy_accept(yyParser*);  /* Forward Declaration */
@@ -153141,16 +158489,20 @@ static YYACTIONTYPE yy_reduce(
   (void)yyLookahead;
   (void)yyLookaheadToken;
   yymsp = yypParser->yytos;
+  assert( yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) );
 #ifndef NDEBUG
-  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
+  if( yyTraceFILE ){
     yysize = yyRuleInfoNRhs[yyruleno];
     if( yysize ){
-      fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
+      fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
         yyTracePrompt,
-        yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
+        yyruleno, yyRuleName[yyruleno],
+        yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action",
+        yymsp[yysize].stateno);
     }else{
-      fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
-        yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
+      fprintf(yyTraceFILE, "%sReduce %d [%s]%s.\n",
+        yyTracePrompt, yyruleno, yyRuleName[yyruleno],
+        yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action");
     }
   }
 #endif /* NDEBUG */
@@ -153165,7 +158517,7 @@ static YYACTIONTYPE yy_reduce(
       assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
     }
 #endif
-#if YYSTACKDEPTH>0 
+#if YYSTACKDEPTH>0
     if( yypParser->yytos>=yypParser->yystackEnd ){
       yyStackOverflow(yypParser);
       /* The call to yyStackOverflow() above pops the stack until it is
@@ -153208,16 +158560,16 @@ static YYACTIONTYPE yy_reduce(
 { sqlite3FinishCoding(pParse); }
         break;
       case 3: /* cmd ::= BEGIN transtype trans_opt */
-{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy32);}
+{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);}
         break;
       case 4: /* transtype ::= */
-{yymsp[1].minor.yy32 = TK_DEFERRED;}
+{yymsp[1].minor.yy192 = TK_DEFERRED;}
         break;
       case 5: /* transtype ::= DEFERRED */
       case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
       case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
-      case 304: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==304);
-{yymsp[0].minor.yy32 = yymsp[0].major; /*A-overwrites-X*/}
+      case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306);
+{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/}
         break;
       case 8: /* cmd ::= COMMIT|END trans_opt */
       case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
@@ -153240,7 +158592,7 @@ static YYACTIONTYPE yy_reduce(
         break;
       case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
 {
-   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy32,0,0,yymsp[-2].minor.yy32);
+   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192);
 }
         break;
       case 14: /* createkw ::= CREATE */
@@ -153249,38 +158601,38 @@ static YYACTIONTYPE yy_reduce(
       case 15: /* ifnotexists ::= */
       case 18: /* temp ::= */ yytestcase(yyruleno==18);
       case 21: /* table_options ::= */ yytestcase(yyruleno==21);
-      case 43: /* autoinc ::= */ yytestcase(yyruleno==43);
-      case 58: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==58);
-      case 68: /* defer_subclause_opt ::= */ yytestcase(yyruleno==68);
-      case 77: /* ifexists ::= */ yytestcase(yyruleno==77);
-      case 94: /* distinct ::= */ yytestcase(yyruleno==94);
-      case 230: /* collate ::= */ yytestcase(yyruleno==230);
-{yymsp[1].minor.yy32 = 0;}
+      case 45: /* autoinc ::= */ yytestcase(yyruleno==45);
+      case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60);
+      case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70);
+      case 79: /* ifexists ::= */ yytestcase(yyruleno==79);
+      case 96: /* distinct ::= */ yytestcase(yyruleno==96);
+      case 232: /* collate ::= */ yytestcase(yyruleno==232);
+{yymsp[1].minor.yy192 = 0;}
         break;
       case 16: /* ifnotexists ::= IF NOT EXISTS */
-{yymsp[-2].minor.yy32 = 1;}
+{yymsp[-2].minor.yy192 = 1;}
         break;
       case 17: /* temp ::= TEMP */
-      case 44: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==44);
-{yymsp[0].minor.yy32 = 1;}
+      case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46);
+{yymsp[0].minor.yy192 = 1;}
         break;
       case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
 {
-  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy32,0);
+  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0);
 }
         break;
       case 20: /* create_table_args ::= AS select */
 {
-  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy25);
-  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy25);
+  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539);
+  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
 }
         break;
       case 22: /* table_options ::= WITHOUT nm */
 {
   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
-    yymsp[-1].minor.yy32 = TF_WithoutRowid | TF_NoVisibleRowid;
+    yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid;
   }else{
-    yymsp[-1].minor.yy32 = 0;
+    yymsp[-1].minor.yy192 = 0;
     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
   }
 }
@@ -153289,8 +158641,8 @@ static YYACTIONTYPE yy_reduce(
 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
         break;
       case 24: /* typetoken ::= */
-      case 61: /* conslist_opt ::= */ yytestcase(yyruleno==61);
-      case 100: /* as ::= */ yytestcase(yyruleno==100);
+      case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63);
+      case 102: /* as ::= */ yytestcase(yyruleno==102);
 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
         break;
       case 25: /* typetoken ::= typename LP signed RP */
@@ -153309,7 +158661,7 @@ static YYACTIONTYPE yy_reduce(
       case 28: /* scanpt ::= */
 {
   assert( yyLookahead!=YYNOCODE );
-  yymsp[1].minor.yy8 = yyLookaheadToken.z;
+  yymsp[1].minor.yy436 = yyLookaheadToken.z;
 }
         break;
       case 29: /* scantok ::= */
@@ -153319,21 +158671,21 @@ static YYACTIONTYPE yy_reduce(
 }
         break;
       case 30: /* ccons ::= CONSTRAINT nm */
-      case 63: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==63);
+      case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65);
 {pParse->constraintName = yymsp[0].minor.yy0;}
         break;
       case 31: /* ccons ::= DEFAULT scantok term */
-{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy46,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
         break;
       case 32: /* ccons ::= DEFAULT LP expr RP */
-{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy46,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
+{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
         break;
       case 33: /* ccons ::= DEFAULT PLUS scantok term */
-{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy46,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
+{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
         break;
       case 34: /* ccons ::= DEFAULT MINUS scantok term */
 {
-  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy46, 0);
+  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0);
   sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
 }
         break;
@@ -153348,170 +158700,176 @@ static YYACTIONTYPE yy_reduce(
 }
         break;
       case 36: /* ccons ::= NOT NULL onconf */
-{sqlite3AddNotNull(pParse, yymsp[0].minor.yy32);}
+{sqlite3AddNotNull(pParse, yymsp[0].minor.yy192);}
         break;
       case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
-{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy32,yymsp[0].minor.yy32,yymsp[-2].minor.yy32);}
+{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);}
         break;
       case 38: /* ccons ::= UNIQUE onconf */
-{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy32,0,0,0,0,
+{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0,
                                    SQLITE_IDXTYPE_UNIQUE);}
         break;
       case 39: /* ccons ::= CHECK LP expr RP */
-{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy46);}
+{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z);}
         break;
       case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */
-{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy138,yymsp[0].minor.yy32);}
+{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);}
         break;
       case 41: /* ccons ::= defer_subclause */
-{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy32);}
+{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);}
         break;
       case 42: /* ccons ::= COLLATE ID|STRING */
 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
         break;
-      case 45: /* refargs ::= */
-{ yymsp[1].minor.yy32 = OE_None*0x0101; /* EV: R-19803-45884 */}
+      case 43: /* generated ::= LP expr RP */
+{sqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);}
+        break;
+      case 44: /* generated ::= LP expr RP ID */
+{sqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);}
         break;
-      case 46: /* refargs ::= refargs refarg */
-{ yymsp[-1].minor.yy32 = (yymsp[-1].minor.yy32 & ~yymsp[0].minor.yy495.mask) | yymsp[0].minor.yy495.value; }
+      case 47: /* refargs ::= */
+{ yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */}
         break;
-      case 47: /* refarg ::= MATCH nm */
-{ yymsp[-1].minor.yy495.value = 0;     yymsp[-1].minor.yy495.mask = 0x000000; }
+      case 48: /* refargs ::= refargs refarg */
+{ yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
         break;
-      case 48: /* refarg ::= ON INSERT refact */
-{ yymsp[-2].minor.yy495.value = 0;     yymsp[-2].minor.yy495.mask = 0x000000; }
+      case 49: /* refarg ::= MATCH nm */
+{ yymsp[-1].minor.yy207.value = 0;     yymsp[-1].minor.yy207.mask = 0x000000; }
         break;
-      case 49: /* refarg ::= ON DELETE refact */
-{ yymsp[-2].minor.yy495.value = yymsp[0].minor.yy32;     yymsp[-2].minor.yy495.mask = 0x0000ff; }
+      case 50: /* refarg ::= ON INSERT refact */
+{ yymsp[-2].minor.yy207.value = 0;     yymsp[-2].minor.yy207.mask = 0x000000; }
         break;
-      case 50: /* refarg ::= ON UPDATE refact */
-{ yymsp[-2].minor.yy495.value = yymsp[0].minor.yy32<<8;  yymsp[-2].minor.yy495.mask = 0x00ff00; }
+      case 51: /* refarg ::= ON DELETE refact */
+{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192;     yymsp[-2].minor.yy207.mask = 0x0000ff; }
         break;
-      case 51: /* refact ::= SET NULL */
-{ yymsp[-1].minor.yy32 = OE_SetNull;  /* EV: R-33326-45252 */}
+      case 52: /* refarg ::= ON UPDATE refact */
+{ yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8;  yymsp[-2].minor.yy207.mask = 0x00ff00; }
         break;
-      case 52: /* refact ::= SET DEFAULT */
-{ yymsp[-1].minor.yy32 = OE_SetDflt;  /* EV: R-33326-45252 */}
+      case 53: /* refact ::= SET NULL */
+{ yymsp[-1].minor.yy192 = OE_SetNull;  /* EV: R-33326-45252 */}
         break;
-      case 53: /* refact ::= CASCADE */
-{ yymsp[0].minor.yy32 = OE_Cascade;  /* EV: R-33326-45252 */}
+      case 54: /* refact ::= SET DEFAULT */
+{ yymsp[-1].minor.yy192 = OE_SetDflt;  /* EV: R-33326-45252 */}
         break;
-      case 54: /* refact ::= RESTRICT */
-{ yymsp[0].minor.yy32 = OE_Restrict; /* EV: R-33326-45252 */}
+      case 55: /* refact ::= CASCADE */
+{ yymsp[0].minor.yy192 = OE_Cascade;  /* EV: R-33326-45252 */}
         break;
-      case 55: /* refact ::= NO ACTION */
-{ yymsp[-1].minor.yy32 = OE_None;     /* EV: R-33326-45252 */}
+      case 56: /* refact ::= RESTRICT */
+{ yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */}
         break;
-      case 56: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
-{yymsp[-2].minor.yy32 = 0;}
+      case 57: /* refact ::= NO ACTION */
+{ yymsp[-1].minor.yy192 = OE_None;     /* EV: R-33326-45252 */}
         break;
-      case 57: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
-      case 72: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==72);
-      case 160: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==160);
-{yymsp[-1].minor.yy32 = yymsp[0].minor.yy32;}
+      case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
+{yymsp[-2].minor.yy192 = 0;}
         break;
-      case 59: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
-      case 76: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==76);
-      case 202: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==202);
-      case 205: /* in_op ::= NOT IN */ yytestcase(yyruleno==205);
-      case 231: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==231);
-{yymsp[-1].minor.yy32 = 1;}
+      case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
+      case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74);
+      case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162);
+{yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;}
         break;
-      case 60: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
-{yymsp[-1].minor.yy32 = 0;}
+      case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
+      case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78);
+      case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204);
+      case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207);
+      case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233);
+{yymsp[-1].minor.yy192 = 1;}
         break;
-      case 62: /* tconscomma ::= COMMA */
+      case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
+{yymsp[-1].minor.yy192 = 0;}
+        break;
+      case 64: /* tconscomma ::= COMMA */
 {pParse->constraintName.n = 0;}
         break;
-      case 64: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
-{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy138,yymsp[0].minor.yy32,yymsp[-2].minor.yy32,0);}
+      case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
+{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);}
         break;
-      case 65: /* tcons ::= UNIQUE LP sortlist RP onconf */
-{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy138,yymsp[0].minor.yy32,0,0,0,0,
+      case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */
+{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0,
                                        SQLITE_IDXTYPE_UNIQUE);}
         break;
-      case 66: /* tcons ::= CHECK LP expr RP onconf */
-{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy46);}
+      case 68: /* tcons ::= CHECK LP expr RP onconf */
+{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z);}
         break;
-      case 67: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
+      case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
 {
-    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy138, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy138, yymsp[-1].minor.yy32);
-    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy32);
+    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192);
+    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192);
 }
         break;
-      case 69: /* onconf ::= */
-      case 71: /* orconf ::= */ yytestcase(yyruleno==71);
-{yymsp[1].minor.yy32 = OE_Default;}
+      case 71: /* onconf ::= */
+      case 73: /* orconf ::= */ yytestcase(yyruleno==73);
+{yymsp[1].minor.yy192 = OE_Default;}
         break;
-      case 70: /* onconf ::= ON CONFLICT resolvetype */
-{yymsp[-2].minor.yy32 = yymsp[0].minor.yy32;}
+      case 72: /* onconf ::= ON CONFLICT resolvetype */
+{yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;}
         break;
-      case 73: /* resolvetype ::= IGNORE */
-{yymsp[0].minor.yy32 = OE_Ignore;}
+      case 75: /* resolvetype ::= IGNORE */
+{yymsp[0].minor.yy192 = OE_Ignore;}
         break;
-      case 74: /* resolvetype ::= REPLACE */
-      case 161: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==161);
-{yymsp[0].minor.yy32 = OE_Replace;}
+      case 76: /* resolvetype ::= REPLACE */
+      case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163);
+{yymsp[0].minor.yy192 = OE_Replace;}
         break;
-      case 75: /* cmd ::= DROP TABLE ifexists fullname */
+      case 77: /* cmd ::= DROP TABLE ifexists fullname */
 {
-  sqlite3DropTable(pParse, yymsp[0].minor.yy609, 0, yymsp[-1].minor.yy32);
+  sqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192);
 }
         break;
-      case 78: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
+      case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
 {
-  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy138, yymsp[0].minor.yy25, yymsp[-7].minor.yy32, yymsp[-5].minor.yy32);
+  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192);
 }
         break;
-      case 79: /* cmd ::= DROP VIEW ifexists fullname */
+      case 81: /* cmd ::= DROP VIEW ifexists fullname */
 {
-  sqlite3DropTable(pParse, yymsp[0].minor.yy609, 1, yymsp[-1].minor.yy32);
+  sqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192);
 }
         break;
-      case 80: /* cmd ::= select */
+      case 82: /* cmd ::= select */
 {
-  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
-  sqlite3Select(pParse, yymsp[0].minor.yy25, &dest);
-  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy25);
+  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0, 0};
+  sqlite3Select(pParse, yymsp[0].minor.yy539, &dest);
+  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
 }
         break;
-      case 81: /* select ::= WITH wqlist selectnowith */
+      case 83: /* select ::= WITH wqlist selectnowith */
 {
-  Select *p = yymsp[0].minor.yy25;
+  Select *p = yymsp[0].minor.yy539;
   if( p ){
-    p->pWith = yymsp[-1].minor.yy297;
+    p->pWith = yymsp[-1].minor.yy131;
     parserDoubleLinkSelect(pParse, p);
   }else{
-    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy297);
+    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
   }
-  yymsp[-2].minor.yy25 = p;
+  yymsp[-2].minor.yy539 = p;
 }
         break;
-      case 82: /* select ::= WITH RECURSIVE wqlist selectnowith */
+      case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */
 {
-  Select *p = yymsp[0].minor.yy25;
+  Select *p = yymsp[0].minor.yy539;
   if( p ){
-    p->pWith = yymsp[-1].minor.yy297;
+    p->pWith = yymsp[-1].minor.yy131;
     parserDoubleLinkSelect(pParse, p);
   }else{
-    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy297);
+    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
   }
-  yymsp[-3].minor.yy25 = p;
+  yymsp[-3].minor.yy539 = p;
 }
         break;
-      case 83: /* select ::= selectnowith */
+      case 85: /* select ::= selectnowith */
 {
-  Select *p = yymsp[0].minor.yy25;
+  Select *p = yymsp[0].minor.yy539;
   if( p ){
     parserDoubleLinkSelect(pParse, p);
   }
-  yymsp[0].minor.yy25 = p; /*A-overwrites-X*/
+  yymsp[0].minor.yy539 = p; /*A-overwrites-X*/
 }
         break;
-      case 84: /* selectnowith ::= selectnowith multiselect_op oneselect */
+      case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */
 {
-  Select *pRhs = yymsp[0].minor.yy25;
-  Select *pLhs = yymsp[-2].minor.yy25;
+  Select *pRhs = yymsp[0].minor.yy539;
+  Select *pLhs = yymsp[-2].minor.yy539;
   if( pRhs && pRhs->pPrior ){
     SrcList *pFrom;
     Token x;
@@ -153521,142 +158879,140 @@ static YYACTIONTYPE yy_reduce(
     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
   }
   if( pRhs ){
-    pRhs->op = (u8)yymsp[-1].minor.yy32;
+    pRhs->op = (u8)yymsp[-1].minor.yy192;
     pRhs->pPrior = pLhs;
     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
     pRhs->selFlags &= ~SF_MultiValue;
-    if( yymsp[-1].minor.yy32!=TK_ALL ) pParse->hasCompound = 1;
+    if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1;
   }else{
     sqlite3SelectDelete(pParse->db, pLhs);
   }
-  yymsp[-2].minor.yy25 = pRhs;
+  yymsp[-2].minor.yy539 = pRhs;
 }
         break;
-      case 85: /* multiselect_op ::= UNION */
-      case 87: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==87);
-{yymsp[0].minor.yy32 = yymsp[0].major; /*A-overwrites-OP*/}
+      case 87: /* multiselect_op ::= UNION */
+      case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89);
+{yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/}
         break;
-      case 86: /* multiselect_op ::= UNION ALL */
-{yymsp[-1].minor.yy32 = TK_ALL;}
+      case 88: /* multiselect_op ::= UNION ALL */
+{yymsp[-1].minor.yy192 = TK_ALL;}
         break;
-      case 88: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
+      case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
 {
-  yymsp[-8].minor.yy25 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy138,yymsp[-5].minor.yy609,yymsp[-4].minor.yy46,yymsp[-3].minor.yy138,yymsp[-2].minor.yy46,yymsp[-1].minor.yy138,yymsp[-7].minor.yy32,yymsp[0].minor.yy46);
+  yymsp[-8].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202);
 }
         break;
-      case 89: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
+      case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
 {
-  yymsp[-9].minor.yy25 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy138,yymsp[-6].minor.yy609,yymsp[-5].minor.yy46,yymsp[-4].minor.yy138,yymsp[-3].minor.yy46,yymsp[-1].minor.yy138,yymsp[-8].minor.yy32,yymsp[0].minor.yy46);
-  if( yymsp[-9].minor.yy25 ){
-    yymsp[-9].minor.yy25->pWinDefn = yymsp[-2].minor.yy455;
+  yymsp[-9].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202);
+  if( yymsp[-9].minor.yy539 ){
+    yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303;
   }else{
-    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy455);
+    sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303);
   }
 }
         break;
-      case 90: /* values ::= VALUES LP nexprlist RP */
+      case 92: /* values ::= VALUES LP nexprlist RP */
 {
-  yymsp[-3].minor.yy25 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy138,0,0,0,0,0,SF_Values,0);
+  yymsp[-3].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0);
 }
         break;
-      case 91: /* values ::= values COMMA LP nexprlist RP */
+      case 93: /* values ::= values COMMA LP nexprlist RP */
 {
-  Select *pRight, *pLeft = yymsp[-4].minor.yy25;
-  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy138,0,0,0,0,0,SF_Values|SF_MultiValue,0);
+  Select *pRight, *pLeft = yymsp[-4].minor.yy539;
+  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0);
   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
   if( pRight ){
     pRight->op = TK_ALL;
     pRight->pPrior = pLeft;
-    yymsp[-4].minor.yy25 = pRight;
+    yymsp[-4].minor.yy539 = pRight;
   }else{
-    yymsp[-4].minor.yy25 = pLeft;
+    yymsp[-4].minor.yy539 = pLeft;
   }
 }
         break;
-      case 92: /* distinct ::= DISTINCT */
-{yymsp[0].minor.yy32 = SF_Distinct;}
+      case 94: /* distinct ::= DISTINCT */
+{yymsp[0].minor.yy192 = SF_Distinct;}
         break;
-      case 93: /* distinct ::= ALL */
-{yymsp[0].minor.yy32 = SF_All;}
+      case 95: /* distinct ::= ALL */
+{yymsp[0].minor.yy192 = SF_All;}
         break;
-      case 95: /* sclp ::= */
-      case 128: /* orderby_opt ::= */ yytestcase(yyruleno==128);
-      case 138: /* groupby_opt ::= */ yytestcase(yyruleno==138);
-      case 218: /* exprlist ::= */ yytestcase(yyruleno==218);
-      case 221: /* paren_exprlist ::= */ yytestcase(yyruleno==221);
-      case 226: /* eidlist_opt ::= */ yytestcase(yyruleno==226);
-{yymsp[1].minor.yy138 = 0;}
+      case 97: /* sclp ::= */
+      case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130);
+      case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140);
+      case 220: /* exprlist ::= */ yytestcase(yyruleno==220);
+      case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223);
+      case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228);
+{yymsp[1].minor.yy242 = 0;}
         break;
-      case 96: /* selcollist ::= sclp scanpt expr scanpt as */
+      case 98: /* selcollist ::= sclp scanpt expr scanpt as */
 {
-   yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy138, yymsp[-2].minor.yy46);
-   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy138, &yymsp[0].minor.yy0, 1);
-   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy138,yymsp[-3].minor.yy8,yymsp[-1].minor.yy8);
+   yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
+   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1);
+   sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436);
 }
         break;
-      case 97: /* selcollist ::= sclp scanpt STAR */
+      case 99: /* selcollist ::= sclp scanpt STAR */
 {
   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
-  yymsp[-2].minor.yy138 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy138, p);
+  yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p);
 }
         break;
-      case 98: /* selcollist ::= sclp scanpt nm DOT STAR */
+      case 100: /* selcollist ::= sclp scanpt nm DOT STAR */
 {
   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
   Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy138, pDot);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot);
 }
         break;
-      case 99: /* as ::= AS nm */
-      case 110: /* dbnm ::= DOT nm */ yytestcase(yyruleno==110);
-      case 242: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==242);
-      case 243: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==243);
+      case 101: /* as ::= AS nm */
+      case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112);
+      case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244);
+      case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245);
 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
         break;
-      case 101: /* from ::= */
-{yymsp[1].minor.yy609 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy609));}
+      case 103: /* from ::= */
+      case 106: /* stl_prefix ::= */ yytestcase(yyruleno==106);
+{yymsp[1].minor.yy47 = 0;}
         break;
-      case 102: /* from ::= FROM seltablist */
+      case 104: /* from ::= FROM seltablist */
 {
-  yymsp[-1].minor.yy609 = yymsp[0].minor.yy609;
-  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy609);
+  yymsp[-1].minor.yy47 = yymsp[0].minor.yy47;
+  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47);
 }
         break;
-      case 103: /* stl_prefix ::= seltablist joinop */
+      case 105: /* stl_prefix ::= seltablist joinop */
 {
-   if( ALWAYS(yymsp[-1].minor.yy609 && yymsp[-1].minor.yy609->nSrc>0) ) yymsp[-1].minor.yy609->a[yymsp[-1].minor.yy609->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy32;
+   if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192;
 }
         break;
-      case 104: /* stl_prefix ::= */
-{yymsp[1].minor.yy609 = 0;}
-        break;
-      case 105: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
+      case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
 {
-  yymsp[-6].minor.yy609 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy609,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy406);
-  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy609, &yymsp[-2].minor.yy0);
+  yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0);
 }
         break;
-      case 106: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
+      case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
 {
-  yymsp[-8].minor.yy609 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy609,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy406);
-  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy609, yymsp[-4].minor.yy138);
+  yymsp[-8].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242);
 }
         break;
-      case 107: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
+      case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
 {
-    yymsp[-6].minor.yy609 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy609,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy25,yymsp[-1].minor.yy46,yymsp[0].minor.yy406);
+    yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
   }
         break;
-      case 108: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
+      case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
 {
-    if( yymsp[-6].minor.yy609==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy46==0 && yymsp[0].minor.yy406==0 ){
-      yymsp[-6].minor.yy609 = yymsp[-4].minor.yy609;
-    }else if( yymsp[-4].minor.yy609->nSrc==1 ){
-      yymsp[-6].minor.yy609 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy609,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy406);
-      if( yymsp[-6].minor.yy609 ){
-        struct SrcList_item *pNew = &yymsp[-6].minor.yy609->a[yymsp[-6].minor.yy609->nSrc-1];
-        struct SrcList_item *pOld = yymsp[-4].minor.yy609->a;
+    if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){
+      yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47;
+    }else if( yymsp[-4].minor.yy47->nSrc==1 ){
+      yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
+      if( yymsp[-6].minor.yy47 ){
+        struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1];
+        struct SrcList_item *pOld = yymsp[-4].minor.yy47->a;
         pNew->zName = pOld->zName;
         pNew->zDatabase = pOld->zDatabase;
         pNew->pSelect = pOld->pSelect;
@@ -153669,212 +159025,213 @@ static YYACTIONTYPE yy_reduce(
         pOld->zName = pOld->zDatabase = 0;
         pOld->pSelect = 0;
       }
-      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy609);
+      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47);
     }else{
       Select *pSubquery;
-      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy609);
-      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy609,0,0,0,0,SF_NestedFrom,0);
-      yymsp[-6].minor.yy609 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy609,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy46,yymsp[0].minor.yy406);
+      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47);
+      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0);
+      yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
     }
   }
         break;
-      case 109: /* dbnm ::= */
-      case 123: /* indexed_opt ::= */ yytestcase(yyruleno==123);
+      case 111: /* dbnm ::= */
+      case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125);
 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
         break;
-      case 111: /* fullname ::= nm */
+      case 113: /* fullname ::= nm */
 {
-  yylhsminor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
-  if( IN_RENAME_OBJECT && yylhsminor.yy609 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy609->a[0].zName, &yymsp[0].minor.yy0);
+  yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
+  if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
 }
-  yymsp[0].minor.yy609 = yylhsminor.yy609;
+  yymsp[0].minor.yy47 = yylhsminor.yy47;
         break;
-      case 112: /* fullname ::= nm DOT nm */
+      case 114: /* fullname ::= nm DOT nm */
 {
-  yylhsminor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
-  if( IN_RENAME_OBJECT && yylhsminor.yy609 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy609->a[0].zName, &yymsp[0].minor.yy0);
+  yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
+  if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
 }
-  yymsp[-2].minor.yy609 = yylhsminor.yy609;
+  yymsp[-2].minor.yy47 = yylhsminor.yy47;
         break;
-      case 113: /* xfullname ::= nm */
-{yymsp[0].minor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
+      case 115: /* xfullname ::= nm */
+{yymsp[0].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
         break;
-      case 114: /* xfullname ::= nm DOT nm */
-{yymsp[-2].minor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 116: /* xfullname ::= nm DOT nm */
+{yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 115: /* xfullname ::= nm DOT nm AS nm */
+      case 117: /* xfullname ::= nm DOT nm AS nm */
 {
-   yymsp[-4].minor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
-   if( yymsp[-4].minor.yy609 ) yymsp[-4].minor.yy609->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+   yymsp[-4].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
+   if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
 }
         break;
-      case 116: /* xfullname ::= nm AS nm */
-{  
-   yymsp[-2].minor.yy609 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
-   if( yymsp[-2].minor.yy609 ) yymsp[-2].minor.yy609->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
+      case 118: /* xfullname ::= nm AS nm */
+{
+   yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
+   if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
 }
         break;
-      case 117: /* joinop ::= COMMA|JOIN */
-{ yymsp[0].minor.yy32 = JT_INNER; }
+      case 119: /* joinop ::= COMMA|JOIN */
+{ yymsp[0].minor.yy192 = JT_INNER; }
         break;
-      case 118: /* joinop ::= JOIN_KW JOIN */
-{yymsp[-1].minor.yy32 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
+      case 120: /* joinop ::= JOIN_KW JOIN */
+{yymsp[-1].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
         break;
-      case 119: /* joinop ::= JOIN_KW nm JOIN */
-{yymsp[-2].minor.yy32 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
+      case 121: /* joinop ::= JOIN_KW nm JOIN */
+{yymsp[-2].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
         break;
-      case 120: /* joinop ::= JOIN_KW nm nm JOIN */
-{yymsp[-3].minor.yy32 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
+      case 122: /* joinop ::= JOIN_KW nm nm JOIN */
+{yymsp[-3].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
         break;
-      case 121: /* on_opt ::= ON expr */
-      case 141: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==141);
-      case 148: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==148);
-      case 214: /* case_else ::= ELSE expr */ yytestcase(yyruleno==214);
-      case 235: /* vinto ::= INTO expr */ yytestcase(yyruleno==235);
-{yymsp[-1].minor.yy46 = yymsp[0].minor.yy46;}
+      case 123: /* on_opt ::= ON expr */
+      case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143);
+      case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150);
+      case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216);
+      case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237);
+{yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;}
         break;
-      case 122: /* on_opt ::= */
-      case 140: /* having_opt ::= */ yytestcase(yyruleno==140);
-      case 142: /* limit_opt ::= */ yytestcase(yyruleno==142);
-      case 147: /* where_opt ::= */ yytestcase(yyruleno==147);
-      case 215: /* case_else ::= */ yytestcase(yyruleno==215);
-      case 217: /* case_operand ::= */ yytestcase(yyruleno==217);
-      case 236: /* vinto ::= */ yytestcase(yyruleno==236);
-{yymsp[1].minor.yy46 = 0;}
+      case 124: /* on_opt ::= */
+      case 142: /* having_opt ::= */ yytestcase(yyruleno==142);
+      case 144: /* limit_opt ::= */ yytestcase(yyruleno==144);
+      case 149: /* where_opt ::= */ yytestcase(yyruleno==149);
+      case 217: /* case_else ::= */ yytestcase(yyruleno==217);
+      case 219: /* case_operand ::= */ yytestcase(yyruleno==219);
+      case 238: /* vinto ::= */ yytestcase(yyruleno==238);
+{yymsp[1].minor.yy202 = 0;}
         break;
-      case 124: /* indexed_opt ::= INDEXED BY nm */
+      case 126: /* indexed_opt ::= INDEXED BY nm */
 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
         break;
-      case 125: /* indexed_opt ::= NOT INDEXED */
+      case 127: /* indexed_opt ::= NOT INDEXED */
 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
         break;
-      case 126: /* using_opt ::= USING LP idlist RP */
-{yymsp[-3].minor.yy406 = yymsp[-1].minor.yy406;}
+      case 128: /* using_opt ::= USING LP idlist RP */
+{yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;}
         break;
-      case 127: /* using_opt ::= */
-      case 162: /* idlist_opt ::= */ yytestcase(yyruleno==162);
-{yymsp[1].minor.yy406 = 0;}
+      case 129: /* using_opt ::= */
+      case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164);
+{yymsp[1].minor.yy600 = 0;}
         break;
-      case 129: /* orderby_opt ::= ORDER BY sortlist */
-      case 139: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==139);
-{yymsp[-2].minor.yy138 = yymsp[0].minor.yy138;}
+      case 131: /* orderby_opt ::= ORDER BY sortlist */
+      case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141);
+{yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;}
         break;
-      case 130: /* sortlist ::= sortlist COMMA expr sortorder nulls */
+      case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */
 {
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy138,yymsp[-2].minor.yy46);
-  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy138,yymsp[-1].minor.yy32,yymsp[0].minor.yy32);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202);
+  sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
 }
         break;
-      case 131: /* sortlist ::= expr sortorder nulls */
+      case 133: /* sortlist ::= expr sortorder nulls */
 {
-  yymsp[-2].minor.yy138 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy46); /*A-overwrites-Y*/
-  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy138,yymsp[-1].minor.yy32,yymsp[0].minor.yy32);
+  yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/
+  sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
 }
         break;
-      case 132: /* sortorder ::= ASC */
-{yymsp[0].minor.yy32 = SQLITE_SO_ASC;}
+      case 134: /* sortorder ::= ASC */
+{yymsp[0].minor.yy192 = SQLITE_SO_ASC;}
         break;
-      case 133: /* sortorder ::= DESC */
-{yymsp[0].minor.yy32 = SQLITE_SO_DESC;}
+      case 135: /* sortorder ::= DESC */
+{yymsp[0].minor.yy192 = SQLITE_SO_DESC;}
         break;
-      case 134: /* sortorder ::= */
-      case 137: /* nulls ::= */ yytestcase(yyruleno==137);
-{yymsp[1].minor.yy32 = SQLITE_SO_UNDEFINED;}
+      case 136: /* sortorder ::= */
+      case 139: /* nulls ::= */ yytestcase(yyruleno==139);
+{yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;}
         break;
-      case 135: /* nulls ::= NULLS FIRST */
-{yymsp[-1].minor.yy32 = SQLITE_SO_ASC;}
+      case 137: /* nulls ::= NULLS FIRST */
+{yymsp[-1].minor.yy192 = SQLITE_SO_ASC;}
         break;
-      case 136: /* nulls ::= NULLS LAST */
-{yymsp[-1].minor.yy32 = SQLITE_SO_DESC;}
+      case 138: /* nulls ::= NULLS LAST */
+{yymsp[-1].minor.yy192 = SQLITE_SO_DESC;}
         break;
-      case 143: /* limit_opt ::= LIMIT expr */
-{yymsp[-1].minor.yy46 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy46,0);}
+      case 145: /* limit_opt ::= LIMIT expr */
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);}
         break;
-      case 144: /* limit_opt ::= LIMIT expr OFFSET expr */
-{yymsp[-3].minor.yy46 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy46,yymsp[0].minor.yy46);}
+      case 146: /* limit_opt ::= LIMIT expr OFFSET expr */
+{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
         break;
-      case 145: /* limit_opt ::= LIMIT expr COMMA expr */
-{yymsp[-3].minor.yy46 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);}
+      case 147: /* limit_opt ::= LIMIT expr COMMA expr */
+{yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);}
         break;
-      case 146: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
+      case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt orderby_opt limit_opt */
 {
-  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy609, &yymsp[-3].minor.yy0);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy47, &yymsp[-3].minor.yy0);
 #ifndef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
-  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy138); yymsp[-1].minor.yy138 = 0;
-  sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy46); yymsp[0].minor.yy46 = 0;
+  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242); yymsp[-1].minor.yy242 = 0;
+  sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202); yymsp[0].minor.yy202 = 0;
 #endif
-  sqlite3DeleteFrom(pParse,yymsp[-4].minor.yy609,yymsp[-2].minor.yy46,yymsp[-1].minor.yy138,yymsp[0].minor.yy46);
+  sqlite3DeleteFrom(pParse,yymsp[-4].minor.yy47,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);
 }
         break;
-      case 149: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt orderby_opt limit_opt */
+      case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt orderby_opt limit_opt */
 {
-  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy609, &yymsp[-5].minor.yy0);
-  sqlite3ExprListCheckLength(pParse,yymsp[-3].minor.yy138,"set list"); 
-  sqlite3Update(pParse,yymsp[-6].minor.yy609,yymsp[-3].minor.yy138,yymsp[-2].minor.yy46,yymsp[-7].minor.yy32,yymsp[-1].minor.yy138,yymsp[0].minor.yy46,0);
+  sqlite3SrcListIndexedBy(pParse, yymsp[-7].minor.yy47, &yymsp[-6].minor.yy0);
+  yymsp[-7].minor.yy47 = sqlite3SrcListAppendList(pParse, yymsp[-7].minor.yy47, yymsp[-3].minor.yy47);
+  sqlite3ExprListCheckLength(pParse,yymsp[-4].minor.yy242,"set list");
+  sqlite3Update(pParse,yymsp[-7].minor.yy47,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,yymsp[-8].minor.yy192,yymsp[-1].minor.yy242,yymsp[0].minor.yy202,0);
 }
         break;
-      case 150: /* setlist ::= setlist COMMA nm EQ expr */
+      case 152: /* setlist ::= setlist COMMA nm EQ expr */
 {
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy138, yymsp[0].minor.yy46);
-  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy138, &yymsp[-2].minor.yy0, 1);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
+  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1);
 }
         break;
-      case 151: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
+      case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
 {
-  yymsp[-6].minor.yy138 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy138, yymsp[-3].minor.yy406, yymsp[0].minor.yy46);
+  yymsp[-6].minor.yy242 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
 }
         break;
-      case 152: /* setlist ::= nm EQ expr */
+      case 154: /* setlist ::= nm EQ expr */
 {
-  yylhsminor.yy138 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy46);
-  sqlite3ExprListSetName(pParse, yylhsminor.yy138, &yymsp[-2].minor.yy0, 1);
+  yylhsminor.yy242 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202);
+  sqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1);
 }
-  yymsp[-2].minor.yy138 = yylhsminor.yy138;
+  yymsp[-2].minor.yy242 = yylhsminor.yy242;
         break;
-      case 153: /* setlist ::= LP idlist RP EQ expr */
+      case 155: /* setlist ::= LP idlist RP EQ expr */
 {
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy406, yymsp[0].minor.yy46);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
 }
         break;
-      case 154: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
+      case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
 {
-  sqlite3Insert(pParse, yymsp[-3].minor.yy609, yymsp[-1].minor.yy25, yymsp[-2].minor.yy406, yymsp[-5].minor.yy32, yymsp[0].minor.yy288);
+  sqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318);
 }
         break;
-      case 155: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
+      case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
 {
-  sqlite3Insert(pParse, yymsp[-3].minor.yy609, 0, yymsp[-2].minor.yy406, yymsp[-5].minor.yy32, 0);
+  sqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0);
 }
         break;
-      case 156: /* upsert ::= */
-{ yymsp[1].minor.yy288 = 0; }
+      case 158: /* upsert ::= */
+{ yymsp[1].minor.yy318 = 0; }
         break;
-      case 157: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
-{ yymsp[-10].minor.yy288 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy138,yymsp[-5].minor.yy46,yymsp[-1].minor.yy138,yymsp[0].minor.yy46);}
+      case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
+{ yymsp[-10].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);}
         break;
-      case 158: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
-{ yymsp[-7].minor.yy288 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy138,yymsp[-2].minor.yy46,0,0); }
+      case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
+{ yymsp[-7].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); }
         break;
-      case 159: /* upsert ::= ON CONFLICT DO NOTHING */
-{ yymsp[-3].minor.yy288 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
+      case 161: /* upsert ::= ON CONFLICT DO NOTHING */
+{ yymsp[-3].minor.yy318 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
         break;
-      case 163: /* idlist_opt ::= LP idlist RP */
-{yymsp[-2].minor.yy406 = yymsp[-1].minor.yy406;}
+      case 165: /* idlist_opt ::= LP idlist RP */
+{yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;}
         break;
-      case 164: /* idlist ::= idlist COMMA nm */
-{yymsp[-2].minor.yy406 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy406,&yymsp[0].minor.yy0);}
+      case 166: /* idlist ::= idlist COMMA nm */
+{yymsp[-2].minor.yy600 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);}
         break;
-      case 165: /* idlist ::= nm */
-{yymsp[0].minor.yy406 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
+      case 167: /* idlist ::= nm */
+{yymsp[0].minor.yy600 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
         break;
-      case 166: /* expr ::= LP expr RP */
-{yymsp[-2].minor.yy46 = yymsp[-1].minor.yy46;}
+      case 168: /* expr ::= LP expr RP */
+{yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;}
         break;
-      case 167: /* expr ::= ID|INDEXED */
-      case 168: /* expr ::= JOIN_KW */ yytestcase(yyruleno==168);
-{yymsp[0].minor.yy46=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 169: /* expr ::= ID|INDEXED */
+      case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170);
+{yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 169: /* expr ::= nm DOT nm */
+      case 171: /* expr ::= nm DOT nm */
 {
   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
@@ -153882,11 +159239,11 @@ static YYACTIONTYPE yy_reduce(
     sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
     sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
   }
-  yylhsminor.yy46 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
+  yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
 }
-  yymsp[-2].minor.yy46 = yylhsminor.yy46;
+  yymsp[-2].minor.yy202 = yylhsminor.yy202;
         break;
-      case 170: /* expr ::= nm DOT nm DOT nm */
+      case 172: /* expr ::= nm DOT nm DOT nm */
 {
   Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
   Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
@@ -153896,26 +159253,26 @@ static YYACTIONTYPE yy_reduce(
     sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
     sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
   }
-  yylhsminor.yy46 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
+  yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
 }
-  yymsp[-4].minor.yy46 = yylhsminor.yy46;
+  yymsp[-4].minor.yy202 = yylhsminor.yy202;
         break;
-      case 171: /* term ::= NULL|FLOAT|BLOB */
-      case 172: /* term ::= STRING */ yytestcase(yyruleno==172);
-{yymsp[0].minor.yy46=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
+      case 173: /* term ::= NULL|FLOAT|BLOB */
+      case 174: /* term ::= STRING */ yytestcase(yyruleno==174);
+{yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
         break;
-      case 173: /* term ::= INTEGER */
+      case 175: /* term ::= INTEGER */
 {
-  yylhsminor.yy46 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
+  yylhsminor.yy202 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
 }
-  yymsp[0].minor.yy46 = yylhsminor.yy46;
+  yymsp[0].minor.yy202 = yylhsminor.yy202;
         break;
-      case 174: /* expr ::= VARIABLE */
+      case 176: /* expr ::= VARIABLE */
 {
   if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
     u32 n = yymsp[0].minor.yy0.n;
-    yymsp[0].minor.yy46 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
-    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy46, n);
+    yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
+    sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n);
   }else{
     /* When doing a nested parse, one can include terms in an expression
     ** that look like this:   #1 #2 ...  These terms refer to registers
@@ -153924,156 +159281,159 @@ static YYACTIONTYPE yy_reduce(
     assert( t.n>=2 );
     if( pParse->nested==0 ){
       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
-      yymsp[0].minor.yy46 = 0;
+      yymsp[0].minor.yy202 = 0;
     }else{
-      yymsp[0].minor.yy46 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
-      if( yymsp[0].minor.yy46 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy46->iTable);
+      yymsp[0].minor.yy202 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
+      if( yymsp[0].minor.yy202 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable);
     }
   }
 }
         break;
-      case 175: /* expr ::= expr COLLATE ID|STRING */
+      case 177: /* expr ::= expr COLLATE ID|STRING */
 {
-  yymsp[-2].minor.yy46 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy46, &yymsp[0].minor.yy0, 1);
+  yymsp[-2].minor.yy202 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1);
 }
         break;
-      case 176: /* expr ::= CAST LP expr AS typetoken RP */
+      case 178: /* expr ::= CAST LP expr AS typetoken RP */
 {
-  yymsp[-5].minor.yy46 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
-  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy46, yymsp[-3].minor.yy46, 0);
+  yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
+  sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0);
 }
         break;
-      case 177: /* expr ::= ID|INDEXED LP distinct exprlist RP */
+      case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */
 {
-  yylhsminor.yy46 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy138, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy32);
+  yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192);
 }
-  yymsp[-4].minor.yy46 = yylhsminor.yy46;
+  yymsp[-4].minor.yy202 = yylhsminor.yy202;
         break;
-      case 178: /* expr ::= ID|INDEXED LP STAR RP */
+      case 180: /* expr ::= ID|INDEXED LP STAR RP */
 {
-  yylhsminor.yy46 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
+  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
 }
-  yymsp[-3].minor.yy46 = yylhsminor.yy46;
+  yymsp[-3].minor.yy202 = yylhsminor.yy202;
         break;
-      case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
+      case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
 {
-  yylhsminor.yy46 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy138, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy32);
-  sqlite3WindowAttach(pParse, yylhsminor.yy46, yymsp[0].minor.yy455);
+  yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192);
+  sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
 }
-  yymsp[-5].minor.yy46 = yylhsminor.yy46;
+  yymsp[-5].minor.yy202 = yylhsminor.yy202;
         break;
-      case 180: /* expr ::= ID|INDEXED LP STAR RP filter_over */
+      case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */
 {
-  yylhsminor.yy46 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
-  sqlite3WindowAttach(pParse, yylhsminor.yy46, yymsp[0].minor.yy455);
+  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
+  sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
 }
-  yymsp[-4].minor.yy46 = yylhsminor.yy46;
+  yymsp[-4].minor.yy202 = yylhsminor.yy202;
         break;
-      case 181: /* term ::= CTIME_KW */
+      case 183: /* term ::= CTIME_KW */
 {
-  yylhsminor.yy46 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
+  yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
 }
-  yymsp[0].minor.yy46 = yylhsminor.yy46;
+  yymsp[0].minor.yy202 = yylhsminor.yy202;
         break;
-      case 182: /* expr ::= LP nexprlist COMMA expr RP */
+      case 184: /* expr ::= LP nexprlist COMMA expr RP */
 {
-  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy138, yymsp[-1].minor.yy46);
-  yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
-  if( yymsp[-4].minor.yy46 ){
-    yymsp[-4].minor.yy46->x.pList = pList;
+  ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202);
+  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
+  if( yymsp[-4].minor.yy202 ){
+    yymsp[-4].minor.yy202->x.pList = pList;
+    if( ALWAYS(pList->nExpr) ){
+      yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate;
+    }
   }else{
     sqlite3ExprListDelete(pParse->db, pList);
   }
 }
         break;
-      case 183: /* expr ::= expr AND expr */
-{yymsp[-2].minor.yy46=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy46,yymsp[0].minor.yy46);}
+      case 185: /* expr ::= expr AND expr */
+{yymsp[-2].minor.yy202=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
         break;
-      case 184: /* expr ::= expr OR expr */
-      case 185: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==185);
-      case 186: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==186);
-      case 187: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==187);
-      case 188: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==188);
-      case 189: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==189);
-      case 190: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==190);
-{yymsp[-2].minor.yy46=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy46,yymsp[0].minor.yy46);}
+      case 186: /* expr ::= expr OR expr */
+      case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187);
+      case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188);
+      case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189);
+      case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190);
+      case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191);
+      case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192);
+{yymsp[-2].minor.yy202=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
         break;
-      case 191: /* likeop ::= NOT LIKE_KW|MATCH */
+      case 193: /* likeop ::= NOT LIKE_KW|MATCH */
 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
         break;
-      case 192: /* expr ::= expr likeop expr */
+      case 194: /* expr ::= expr likeop expr */
 {
   ExprList *pList;
   int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
   yymsp[-1].minor.yy0.n &= 0x7fffffff;
-  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy46);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy46);
-  yymsp[-2].minor.yy46 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
-  if( bNot ) yymsp[-2].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy46, 0);
-  if( yymsp[-2].minor.yy46 ) yymsp[-2].minor.yy46->flags |= EP_InfixFunc;
+  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202);
+  yymsp[-2].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
+  if( bNot ) yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0);
+  if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc;
 }
         break;
-      case 193: /* expr ::= expr likeop expr ESCAPE expr */
+      case 195: /* expr ::= expr likeop expr ESCAPE expr */
 {
   ExprList *pList;
   int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
   yymsp[-3].minor.yy0.n &= 0x7fffffff;
-  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy46);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy46);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy46);
-  yymsp[-4].minor.yy46 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
-  if( bNot ) yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy46, 0);
-  if( yymsp[-4].minor.yy46 ) yymsp[-4].minor.yy46->flags |= EP_InfixFunc;
+  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
+  yymsp[-4].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
+  if( bNot ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+  if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc;
 }
         break;
-      case 194: /* expr ::= expr ISNULL|NOTNULL */
-{yymsp[-1].minor.yy46 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy46,0);}
+      case 196: /* expr ::= expr ISNULL|NOTNULL */
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);}
         break;
-      case 195: /* expr ::= expr NOT NULL */
-{yymsp[-2].minor.yy46 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy46,0);}
+      case 197: /* expr ::= expr NOT NULL */
+{yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);}
         break;
-      case 196: /* expr ::= expr IS expr */
+      case 198: /* expr ::= expr IS expr */
 {
-  yymsp[-2].minor.yy46 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy46,yymsp[0].minor.yy46);
-  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy46, yymsp[-2].minor.yy46, TK_ISNULL);
+  yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);
+  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL);
 }
         break;
-      case 197: /* expr ::= expr IS NOT expr */
+      case 199: /* expr ::= expr IS NOT expr */
 {
-  yymsp[-3].minor.yy46 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy46,yymsp[0].minor.yy46);
-  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy46, yymsp[-3].minor.yy46, TK_NOTNULL);
+  yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202);
+  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL);
 }
         break;
-      case 198: /* expr ::= NOT expr */
-      case 199: /* expr ::= BITNOT expr */ yytestcase(yyruleno==199);
-{yymsp[-1].minor.yy46 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy46, 0);/*A-overwrites-B*/}
+      case 200: /* expr ::= NOT expr */
+      case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201);
+{yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/}
         break;
-      case 200: /* expr ::= PLUS|MINUS expr */
+      case 202: /* expr ::= PLUS|MINUS expr */
 {
-  yymsp[-1].minor.yy46 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy46, 0);
+  yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0);
   /*A-overwrites-B*/
 }
         break;
-      case 201: /* between_op ::= BETWEEN */
-      case 204: /* in_op ::= IN */ yytestcase(yyruleno==204);
-{yymsp[0].minor.yy32 = 0;}
+      case 203: /* between_op ::= BETWEEN */
+      case 206: /* in_op ::= IN */ yytestcase(yyruleno==206);
+{yymsp[0].minor.yy192 = 0;}
         break;
-      case 203: /* expr ::= expr between_op expr AND expr */
+      case 205: /* expr ::= expr between_op expr AND expr */
 {
-  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy46);
-  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy46);
-  yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy46, 0);
-  if( yymsp[-4].minor.yy46 ){
-    yymsp[-4].minor.yy46->x.pList = pList;
+  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
+  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0);
+  if( yymsp[-4].minor.yy202 ){
+    yymsp[-4].minor.yy202->x.pList = pList;
   }else{
     sqlite3ExprListDelete(pParse->db, pList);
-  } 
-  if( yymsp[-3].minor.yy32 ) yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy46, 0);
+  }
+  if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
 }
         break;
-      case 206: /* expr ::= expr in_op LP exprlist RP */
+      case 208: /* expr ::= expr in_op LP exprlist RP */
 {
-    if( yymsp[-1].minor.yy138==0 ){
+    if( yymsp[-1].minor.yy242==0 ){
       /* Expressions of the form
       **
       **      expr1 IN ()
@@ -154082,533 +159442,542 @@ static YYACTIONTYPE yy_reduce(
       ** simplify to constants 0 (false) and 1 (true), respectively,
       ** regardless of the value of expr1.
       */
-      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy46);
-      yymsp[-4].minor.yy46 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy32 ? "1" : "0");
-    }else{
-      yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy46, 0);
-      if( yymsp[-4].minor.yy46 ){
-        yymsp[-4].minor.yy46->x.pList = yymsp[-1].minor.yy138;
-        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy46);
+      sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202);
+      yymsp[-4].minor.yy202 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? "1" : "0");
+    }else if( yymsp[-1].minor.yy242->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy242->a[0].pExpr) ){
+      Expr *pRHS = yymsp[-1].minor.yy242->a[0].pExpr;
+      yymsp[-1].minor.yy242->a[0].pExpr = 0;
+      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
+      pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
+      yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy202, pRHS);
+      if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
+    }else{
+      yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+      if( yymsp[-4].minor.yy202 ){
+        yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242;
+        sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
       }else{
-        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy138);
+        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
       }
-      if( yymsp[-3].minor.yy32 ) yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy46, 0);
+      if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
     }
   }
         break;
-      case 207: /* expr ::= LP select RP */
+      case 209: /* expr ::= LP select RP */
 {
-    yymsp[-2].minor.yy46 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy46, yymsp[-1].minor.yy25);
+    yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539);
   }
         break;
-      case 208: /* expr ::= expr in_op LP select RP */
+      case 210: /* expr ::= expr in_op LP select RP */
 {
-    yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy46, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy46, yymsp[-1].minor.yy25);
-    if( yymsp[-3].minor.yy32 ) yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy46, 0);
+    yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539);
+    if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
   }
         break;
-      case 209: /* expr ::= expr in_op nm dbnm paren_exprlist */
+      case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */
 {
     SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
-    if( yymsp[0].minor.yy138 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy138);
-    yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy46, 0);
-    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy46, pSelect);
-    if( yymsp[-3].minor.yy32 ) yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy46, 0);
+    if( yymsp[0].minor.yy242 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242);
+    yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
+    sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect);
+    if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
   }
         break;
-      case 210: /* expr ::= EXISTS LP select RP */
+      case 212: /* expr ::= EXISTS LP select RP */
 {
     Expr *p;
-    p = yymsp[-3].minor.yy46 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
-    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy25);
+    p = yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
+    sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539);
   }
         break;
-      case 211: /* expr ::= CASE case_operand case_exprlist case_else END */
+      case 213: /* expr ::= CASE case_operand case_exprlist case_else END */
 {
-  yymsp[-4].minor.yy46 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy46, 0);
-  if( yymsp[-4].minor.yy46 ){
-    yymsp[-4].minor.yy46->x.pList = yymsp[-1].minor.yy46 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy138,yymsp[-1].minor.yy46) : yymsp[-2].minor.yy138;
-    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy46);
+  yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0);
+  if( yymsp[-4].minor.yy202 ){
+    yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242;
+    sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
   }else{
-    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy138);
-    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy46);
+    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);
+    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202);
   }
 }
         break;
-      case 212: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
+      case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
 {
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy138, yymsp[-2].minor.yy46);
-  yymsp[-4].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy138, yymsp[0].minor.yy46);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
+  yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
 }
         break;
-      case 213: /* case_exprlist ::= WHEN expr THEN expr */
+      case 215: /* case_exprlist ::= WHEN expr THEN expr */
 {
-  yymsp[-3].minor.yy138 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy46);
-  yymsp[-3].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy138, yymsp[0].minor.yy46);
+  yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
+  yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202);
 }
         break;
-      case 216: /* case_operand ::= expr */
-{yymsp[0].minor.yy46 = yymsp[0].minor.yy46; /*A-overwrites-X*/}
+      case 218: /* case_operand ::= expr */
+{yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/}
         break;
-      case 219: /* nexprlist ::= nexprlist COMMA expr */
-{yymsp[-2].minor.yy138 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy138,yymsp[0].minor.yy46);}
+      case 221: /* nexprlist ::= nexprlist COMMA expr */
+{yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);}
         break;
-      case 220: /* nexprlist ::= expr */
-{yymsp[0].minor.yy138 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy46); /*A-overwrites-Y*/}
+      case 222: /* nexprlist ::= expr */
+{yymsp[0].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/}
         break;
-      case 222: /* paren_exprlist ::= LP exprlist RP */
-      case 227: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==227);
-{yymsp[-2].minor.yy138 = yymsp[-1].minor.yy138;}
+      case 224: /* paren_exprlist ::= LP exprlist RP */
+      case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229);
+{yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;}
         break;
-      case 223: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
+      case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
 {
-  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
-                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy138, yymsp[-10].minor.yy32,
-                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy46, SQLITE_SO_ASC, yymsp[-8].minor.yy32, SQLITE_IDXTYPE_APPDEF);
+  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
+                     sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192,
+                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF);
   if( IN_RENAME_OBJECT && pParse->pNewIndex ){
     sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
   }
 }
         break;
-      case 224: /* uniqueflag ::= UNIQUE */
-      case 266: /* raisetype ::= ABORT */ yytestcase(yyruleno==266);
-{yymsp[0].minor.yy32 = OE_Abort;}
+      case 226: /* uniqueflag ::= UNIQUE */
+      case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268);
+{yymsp[0].minor.yy192 = OE_Abort;}
         break;
-      case 225: /* uniqueflag ::= */
-{yymsp[1].minor.yy32 = OE_None;}
+      case 227: /* uniqueflag ::= */
+{yymsp[1].minor.yy192 = OE_None;}
         break;
-      case 228: /* eidlist ::= eidlist COMMA nm collate sortorder */
+      case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */
 {
-  yymsp[-4].minor.yy138 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy138, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy32, yymsp[0].minor.yy32);
+  yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192);
 }
         break;
-      case 229: /* eidlist ::= nm collate sortorder */
+      case 231: /* eidlist ::= nm collate sortorder */
 {
-  yymsp[-2].minor.yy138 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy32, yymsp[0].minor.yy32); /*A-overwrites-Y*/
+  yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/
 }
         break;
-      case 232: /* cmd ::= DROP INDEX ifexists fullname */
-{sqlite3DropIndex(pParse, yymsp[0].minor.yy609, yymsp[-1].minor.yy32);}
+      case 234: /* cmd ::= DROP INDEX ifexists fullname */
+{sqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);}
         break;
-      case 233: /* cmd ::= VACUUM vinto */
-{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy46);}
+      case 235: /* cmd ::= VACUUM vinto */
+{sqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);}
         break;
-      case 234: /* cmd ::= VACUUM nm vinto */
-{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy46);}
+      case 236: /* cmd ::= VACUUM nm vinto */
+{sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);}
         break;
-      case 237: /* cmd ::= PRAGMA nm dbnm */
+      case 239: /* cmd ::= PRAGMA nm dbnm */
 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
         break;
-      case 238: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
+      case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
         break;
-      case 239: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
+      case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
         break;
-      case 240: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
+      case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
         break;
-      case 241: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
+      case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
         break;
-      case 244: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
+      case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
 {
   Token all;
   all.z = yymsp[-3].minor.yy0.z;
   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
-  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy527, &all);
+  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all);
 }
         break;
-      case 245: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
+      case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
 {
-  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy32, yymsp[-4].minor.yy572.a, yymsp[-4].minor.yy572.b, yymsp[-2].minor.yy609, yymsp[0].minor.yy46, yymsp[-10].minor.yy32, yymsp[-8].minor.yy32);
+  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192);
   yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
 }
         break;
-      case 246: /* trigger_time ::= BEFORE|AFTER */
-{ yymsp[0].minor.yy32 = yymsp[0].major; /*A-overwrites-X*/ }
+      case 248: /* trigger_time ::= BEFORE|AFTER */
+{ yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ }
         break;
-      case 247: /* trigger_time ::= INSTEAD OF */
-{ yymsp[-1].minor.yy32 = TK_INSTEAD;}
+      case 249: /* trigger_time ::= INSTEAD OF */
+{ yymsp[-1].minor.yy192 = TK_INSTEAD;}
         break;
-      case 248: /* trigger_time ::= */
-{ yymsp[1].minor.yy32 = TK_BEFORE; }
+      case 250: /* trigger_time ::= */
+{ yymsp[1].minor.yy192 = TK_BEFORE; }
         break;
-      case 249: /* trigger_event ::= DELETE|INSERT */
-      case 250: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==250);
-{yymsp[0].minor.yy572.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy572.b = 0;}
+      case 251: /* trigger_event ::= DELETE|INSERT */
+      case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252);
+{yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;}
         break;
-      case 251: /* trigger_event ::= UPDATE OF idlist */
-{yymsp[-2].minor.yy572.a = TK_UPDATE; yymsp[-2].minor.yy572.b = yymsp[0].minor.yy406;}
+      case 253: /* trigger_event ::= UPDATE OF idlist */
+{yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;}
         break;
-      case 252: /* when_clause ::= */
-      case 271: /* key_opt ::= */ yytestcase(yyruleno==271);
-{ yymsp[1].minor.yy46 = 0; }
+      case 254: /* when_clause ::= */
+      case 273: /* key_opt ::= */ yytestcase(yyruleno==273);
+{ yymsp[1].minor.yy202 = 0; }
         break;
-      case 253: /* when_clause ::= WHEN expr */
-      case 272: /* key_opt ::= KEY expr */ yytestcase(yyruleno==272);
-{ yymsp[-1].minor.yy46 = yymsp[0].minor.yy46; }
+      case 255: /* when_clause ::= WHEN expr */
+      case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274);
+{ yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; }
         break;
-      case 254: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
+      case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
 {
-  assert( yymsp[-2].minor.yy527!=0 );
-  yymsp[-2].minor.yy527->pLast->pNext = yymsp[-1].minor.yy527;
-  yymsp[-2].minor.yy527->pLast = yymsp[-1].minor.yy527;
+  assert( yymsp[-2].minor.yy447!=0 );
+  yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447;
+  yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447;
 }
         break;
-      case 255: /* trigger_cmd_list ::= trigger_cmd SEMI */
-{ 
-  assert( yymsp[-1].minor.yy527!=0 );
-  yymsp[-1].minor.yy527->pLast = yymsp[-1].minor.yy527;
+      case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */
+{
+  assert( yymsp[-1].minor.yy447!=0 );
+  yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447;
 }
         break;
-      case 256: /* trnm ::= nm DOT nm */
+      case 258: /* trnm ::= nm DOT nm */
 {
   yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
-  sqlite3ErrorMsg(pParse, 
+  sqlite3ErrorMsg(pParse,
         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
         "statements within triggers");
 }
         break;
-      case 257: /* tridxby ::= INDEXED BY nm */
+      case 259: /* tridxby ::= INDEXED BY nm */
 {
   sqlite3ErrorMsg(pParse,
         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
         "within triggers");
 }
         break;
-      case 258: /* tridxby ::= NOT INDEXED */
+      case 260: /* tridxby ::= NOT INDEXED */
 {
   sqlite3ErrorMsg(pParse,
         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
         "within triggers");
 }
         break;
-      case 259: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
-{yylhsminor.yy527 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy138, yymsp[-1].minor.yy46, yymsp[-6].minor.yy32, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy8);}
-  yymsp[-7].minor.yy527 = yylhsminor.yy527;
+      case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
+{yylhsminor.yy447 = sqlite3TriggerUpdateStep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy47, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202, yymsp[-7].minor.yy192, yymsp[-8].minor.yy0.z, yymsp[0].minor.yy436);}
+  yymsp[-8].minor.yy447 = yylhsminor.yy447;
         break;
-      case 260: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
+      case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
 {
-   yylhsminor.yy527 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy406,yymsp[-2].minor.yy25,yymsp[-6].minor.yy32,yymsp[-1].minor.yy288,yymsp[-7].minor.yy8,yymsp[0].minor.yy8);/*yylhsminor.yy527-overwrites-yymsp[-6].minor.yy32*/
+   yylhsminor.yy447 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/
 }
-  yymsp[-7].minor.yy527 = yylhsminor.yy527;
+  yymsp[-7].minor.yy447 = yylhsminor.yy447;
         break;
-      case 261: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
-{yylhsminor.yy527 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy46, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy8);}
-  yymsp[-5].minor.yy527 = yylhsminor.yy527;
+      case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
+{yylhsminor.yy447 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);}
+  yymsp[-5].minor.yy447 = yylhsminor.yy447;
         break;
-      case 262: /* trigger_cmd ::= scanpt select scanpt */
-{yylhsminor.yy527 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy25, yymsp[-2].minor.yy8, yymsp[0].minor.yy8); /*yylhsminor.yy527-overwrites-yymsp[-1].minor.yy25*/}
-  yymsp[-2].minor.yy527 = yylhsminor.yy527;
+      case 264: /* trigger_cmd ::= scanpt select scanpt */
+{yylhsminor.yy447 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/}
+  yymsp[-2].minor.yy447 = yylhsminor.yy447;
         break;
-      case 263: /* expr ::= RAISE LP IGNORE RP */
+      case 265: /* expr ::= RAISE LP IGNORE RP */
 {
-  yymsp[-3].minor.yy46 = sqlite3PExpr(pParse, TK_RAISE, 0, 0); 
-  if( yymsp[-3].minor.yy46 ){
-    yymsp[-3].minor.yy46->affExpr = OE_Ignore;
+  yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
+  if( yymsp[-3].minor.yy202 ){
+    yymsp[-3].minor.yy202->affExpr = OE_Ignore;
   }
 }
         break;
-      case 264: /* expr ::= RAISE LP raisetype COMMA nm RP */
+      case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */
 {
-  yymsp[-5].minor.yy46 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1); 
-  if( yymsp[-5].minor.yy46 ) {
-    yymsp[-5].minor.yy46->affExpr = (char)yymsp[-3].minor.yy32;
+  yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
+  if( yymsp[-5].minor.yy202 ) {
+    yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192;
   }
 }
         break;
-      case 265: /* raisetype ::= ROLLBACK */
-{yymsp[0].minor.yy32 = OE_Rollback;}
+      case 267: /* raisetype ::= ROLLBACK */
+{yymsp[0].minor.yy192 = OE_Rollback;}
         break;
-      case 267: /* raisetype ::= FAIL */
-{yymsp[0].minor.yy32 = OE_Fail;}
+      case 269: /* raisetype ::= FAIL */
+{yymsp[0].minor.yy192 = OE_Fail;}
         break;
-      case 268: /* cmd ::= DROP TRIGGER ifexists fullname */
+      case 270: /* cmd ::= DROP TRIGGER ifexists fullname */
 {
-  sqlite3DropTrigger(pParse,yymsp[0].minor.yy609,yymsp[-1].minor.yy32);
+  sqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192);
 }
         break;
-      case 269: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
+      case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
 {
-  sqlite3Attach(pParse, yymsp[-3].minor.yy46, yymsp[-1].minor.yy46, yymsp[0].minor.yy46);
+  sqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202);
 }
         break;
-      case 270: /* cmd ::= DETACH database_kw_opt expr */
+      case 272: /* cmd ::= DETACH database_kw_opt expr */
 {
-  sqlite3Detach(pParse, yymsp[0].minor.yy46);
+  sqlite3Detach(pParse, yymsp[0].minor.yy202);
 }
         break;
-      case 273: /* cmd ::= REINDEX */
+      case 275: /* cmd ::= REINDEX */
 {sqlite3Reindex(pParse, 0, 0);}
         break;
-      case 274: /* cmd ::= REINDEX nm dbnm */
+      case 276: /* cmd ::= REINDEX nm dbnm */
 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
         break;
-      case 275: /* cmd ::= ANALYZE */
+      case 277: /* cmd ::= ANALYZE */
 {sqlite3Analyze(pParse, 0, 0);}
         break;
-      case 276: /* cmd ::= ANALYZE nm dbnm */
+      case 278: /* cmd ::= ANALYZE nm dbnm */
 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
         break;
-      case 277: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
+      case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
 {
-  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy609,&yymsp[0].minor.yy0);
+  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0);
 }
         break;
-      case 278: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
+      case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
 {
   yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
   sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
 }
         break;
-      case 279: /* add_column_fullname ::= fullname */
+      case 281: /* add_column_fullname ::= fullname */
 {
   disableLookaside(pParse);
-  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy609);
+  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47);
 }
         break;
-      case 280: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
+      case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
 {
-  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy609, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
+  sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
 }
         break;
-      case 281: /* cmd ::= create_vtab */
+      case 283: /* cmd ::= create_vtab */
 {sqlite3VtabFinishParse(pParse,0);}
         break;
-      case 282: /* cmd ::= create_vtab LP vtabarglist RP */
+      case 284: /* cmd ::= create_vtab LP vtabarglist RP */
 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
         break;
-      case 283: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
+      case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
 {
-    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy32);
+    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192);
 }
         break;
-      case 284: /* vtabarg ::= */
+      case 286: /* vtabarg ::= */
 {sqlite3VtabArgInit(pParse);}
         break;
-      case 285: /* vtabargtoken ::= ANY */
-      case 286: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==286);
-      case 287: /* lp ::= LP */ yytestcase(yyruleno==287);
+      case 287: /* vtabargtoken ::= ANY */
+      case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288);
+      case 289: /* lp ::= LP */ yytestcase(yyruleno==289);
 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
         break;
-      case 288: /* with ::= WITH wqlist */
-      case 289: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==289);
-{ sqlite3WithPush(pParse, yymsp[0].minor.yy297, 1); }
+      case 290: /* with ::= WITH wqlist */
+      case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291);
+{ sqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); }
         break;
-      case 290: /* wqlist ::= nm eidlist_opt AS LP select RP */
+      case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */
 {
-  yymsp[-5].minor.yy297 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy138, yymsp[-1].minor.yy25); /*A-overwrites-X*/
+  yymsp[-5].minor.yy131 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/
 }
         break;
-      case 291: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
+      case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
 {
-  yymsp[-7].minor.yy297 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy297, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy138, yymsp[-1].minor.yy25);
+  yymsp[-7].minor.yy131 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539);
 }
         break;
-      case 292: /* windowdefn_list ::= windowdefn */
-{ yylhsminor.yy455 = yymsp[0].minor.yy455; }
-  yymsp[0].minor.yy455 = yylhsminor.yy455;
+      case 294: /* windowdefn_list ::= windowdefn */
+{ yylhsminor.yy303 = yymsp[0].minor.yy303; }
+  yymsp[0].minor.yy303 = yylhsminor.yy303;
         break;
-      case 293: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
+      case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
 {
-  assert( yymsp[0].minor.yy455!=0 );
-  sqlite3WindowChain(pParse, yymsp[0].minor.yy455, yymsp[-2].minor.yy455);
-  yymsp[0].minor.yy455->pNextWin = yymsp[-2].minor.yy455;
-  yylhsminor.yy455 = yymsp[0].minor.yy455;
+  assert( yymsp[0].minor.yy303!=0 );
+  sqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303);
+  yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303;
+  yylhsminor.yy303 = yymsp[0].minor.yy303;
 }
-  yymsp[-2].minor.yy455 = yylhsminor.yy455;
+  yymsp[-2].minor.yy303 = yylhsminor.yy303;
         break;
-      case 294: /* windowdefn ::= nm AS LP window RP */
+      case 296: /* windowdefn ::= nm AS LP window RP */
 {
-  if( ALWAYS(yymsp[-1].minor.yy455) ){
-    yymsp[-1].minor.yy455->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
+  if( ALWAYS(yymsp[-1].minor.yy303) ){
+    yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
   }
-  yylhsminor.yy455 = yymsp[-1].minor.yy455;
+  yylhsminor.yy303 = yymsp[-1].minor.yy303;
 }
-  yymsp[-4].minor.yy455 = yylhsminor.yy455;
+  yymsp[-4].minor.yy303 = yylhsminor.yy303;
         break;
-      case 295: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
+      case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
 {
-  yymsp[-4].minor.yy455 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy455, yymsp[-2].minor.yy138, yymsp[-1].minor.yy138, 0);
+  yymsp[-4].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0);
 }
         break;
-      case 296: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
+      case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
 {
-  yylhsminor.yy455 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy455, yymsp[-2].minor.yy138, yymsp[-1].minor.yy138, &yymsp[-5].minor.yy0);
+  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0);
 }
-  yymsp[-5].minor.yy455 = yylhsminor.yy455;
+  yymsp[-5].minor.yy303 = yylhsminor.yy303;
         break;
-      case 297: /* window ::= ORDER BY sortlist frame_opt */
+      case 299: /* window ::= ORDER BY sortlist frame_opt */
 {
-  yymsp[-3].minor.yy455 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy455, 0, yymsp[-1].minor.yy138, 0);
+  yymsp[-3].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0);
 }
         break;
-      case 298: /* window ::= nm ORDER BY sortlist frame_opt */
+      case 300: /* window ::= nm ORDER BY sortlist frame_opt */
 {
-  yylhsminor.yy455 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy455, 0, yymsp[-1].minor.yy138, &yymsp[-4].minor.yy0);
+  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);
 }
-  yymsp[-4].minor.yy455 = yylhsminor.yy455;
+  yymsp[-4].minor.yy303 = yylhsminor.yy303;
         break;
-      case 299: /* window ::= frame_opt */
-      case 318: /* filter_over ::= over_clause */ yytestcase(yyruleno==318);
+      case 301: /* window ::= frame_opt */
+      case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320);
 {
-  yylhsminor.yy455 = yymsp[0].minor.yy455;
+  yylhsminor.yy303 = yymsp[0].minor.yy303;
 }
-  yymsp[0].minor.yy455 = yylhsminor.yy455;
+  yymsp[0].minor.yy303 = yylhsminor.yy303;
         break;
-      case 300: /* window ::= nm frame_opt */
+      case 302: /* window ::= nm frame_opt */
 {
-  yylhsminor.yy455 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy455, 0, 0, &yymsp[-1].minor.yy0);
+  yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0);
 }
-  yymsp[-1].minor.yy455 = yylhsminor.yy455;
+  yymsp[-1].minor.yy303 = yylhsminor.yy303;
         break;
-      case 301: /* frame_opt ::= */
-{ 
-  yymsp[1].minor.yy455 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
+      case 303: /* frame_opt ::= */
+{
+  yymsp[1].minor.yy303 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
 }
         break;
-      case 302: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
-{ 
-  yylhsminor.yy455 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy32, yymsp[-1].minor.yy57.eType, yymsp[-1].minor.yy57.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy118);
+      case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
+{
+  yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58);
 }
-  yymsp[-2].minor.yy455 = yylhsminor.yy455;
+  yymsp[-2].minor.yy303 = yylhsminor.yy303;
         break;
-      case 303: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
-{ 
-  yylhsminor.yy455 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy32, yymsp[-3].minor.yy57.eType, yymsp[-3].minor.yy57.pExpr, yymsp[-1].minor.yy57.eType, yymsp[-1].minor.yy57.pExpr, yymsp[0].minor.yy118);
+      case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
+{
+  yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58);
 }
-  yymsp[-5].minor.yy455 = yylhsminor.yy455;
+  yymsp[-5].minor.yy303 = yylhsminor.yy303;
         break;
-      case 305: /* frame_bound_s ::= frame_bound */
-      case 307: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==307);
-{yylhsminor.yy57 = yymsp[0].minor.yy57;}
-  yymsp[0].minor.yy57 = yylhsminor.yy57;
+      case 307: /* frame_bound_s ::= frame_bound */
+      case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309);
+{yylhsminor.yy77 = yymsp[0].minor.yy77;}
+  yymsp[0].minor.yy77 = yylhsminor.yy77;
         break;
-      case 306: /* frame_bound_s ::= UNBOUNDED PRECEDING */
-      case 308: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==308);
-      case 310: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==310);
-{yylhsminor.yy57.eType = yymsp[-1].major; yylhsminor.yy57.pExpr = 0;}
-  yymsp[-1].minor.yy57 = yylhsminor.yy57;
+      case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */
+      case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310);
+      case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312);
+{yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;}
+  yymsp[-1].minor.yy77 = yylhsminor.yy77;
         break;
-      case 309: /* frame_bound ::= expr PRECEDING|FOLLOWING */
-{yylhsminor.yy57.eType = yymsp[0].major; yylhsminor.yy57.pExpr = yymsp[-1].minor.yy46;}
-  yymsp[-1].minor.yy57 = yylhsminor.yy57;
+      case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */
+{yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;}
+  yymsp[-1].minor.yy77 = yylhsminor.yy77;
         break;
-      case 311: /* frame_exclude_opt ::= */
-{yymsp[1].minor.yy118 = 0;}
+      case 313: /* frame_exclude_opt ::= */
+{yymsp[1].minor.yy58 = 0;}
         break;
-      case 312: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
-{yymsp[-1].minor.yy118 = yymsp[0].minor.yy118;}
+      case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
+{yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;}
         break;
-      case 313: /* frame_exclude ::= NO OTHERS */
-      case 314: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==314);
-{yymsp[-1].minor.yy118 = yymsp[-1].major; /*A-overwrites-X*/}
+      case 315: /* frame_exclude ::= NO OTHERS */
+      case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316);
+{yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/}
         break;
-      case 315: /* frame_exclude ::= GROUP|TIES */
-{yymsp[0].minor.yy118 = yymsp[0].major; /*A-overwrites-X*/}
+      case 317: /* frame_exclude ::= GROUP|TIES */
+{yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/}
         break;
-      case 316: /* window_clause ::= WINDOW windowdefn_list */
-{ yymsp[-1].minor.yy455 = yymsp[0].minor.yy455; }
+      case 318: /* window_clause ::= WINDOW windowdefn_list */
+{ yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; }
         break;
-      case 317: /* filter_over ::= filter_clause over_clause */
+      case 319: /* filter_over ::= filter_clause over_clause */
 {
-  yymsp[0].minor.yy455->pFilter = yymsp[-1].minor.yy46;
-  yylhsminor.yy455 = yymsp[0].minor.yy455;
+  yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202;
+  yylhsminor.yy303 = yymsp[0].minor.yy303;
 }
-  yymsp[-1].minor.yy455 = yylhsminor.yy455;
+  yymsp[-1].minor.yy303 = yylhsminor.yy303;
         break;
-      case 319: /* filter_over ::= filter_clause */
+      case 321: /* filter_over ::= filter_clause */
 {
-  yylhsminor.yy455 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
-  if( yylhsminor.yy455 ){
-    yylhsminor.yy455->eFrmType = TK_FILTER;
-    yylhsminor.yy455->pFilter = yymsp[0].minor.yy46;
+  yylhsminor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+  if( yylhsminor.yy303 ){
+    yylhsminor.yy303->eFrmType = TK_FILTER;
+    yylhsminor.yy303->pFilter = yymsp[0].minor.yy202;
   }else{
-    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy46);
+    sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202);
   }
 }
-  yymsp[0].minor.yy455 = yylhsminor.yy455;
+  yymsp[0].minor.yy303 = yylhsminor.yy303;
         break;
-      case 320: /* over_clause ::= OVER LP window RP */
+      case 322: /* over_clause ::= OVER LP window RP */
 {
-  yymsp[-3].minor.yy455 = yymsp[-1].minor.yy455;
-  assert( yymsp[-3].minor.yy455!=0 );
+  yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303;
+  assert( yymsp[-3].minor.yy303!=0 );
 }
         break;
-      case 321: /* over_clause ::= OVER nm */
+      case 323: /* over_clause ::= OVER nm */
 {
-  yymsp[-1].minor.yy455 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
-  if( yymsp[-1].minor.yy455 ){
-    yymsp[-1].minor.yy455->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
+  yymsp[-1].minor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
+  if( yymsp[-1].minor.yy303 ){
+    yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
   }
 }
         break;
-      case 322: /* filter_clause ::= FILTER LP WHERE expr RP */
-{ yymsp[-4].minor.yy46 = yymsp[-1].minor.yy46; }
+      case 324: /* filter_clause ::= FILTER LP WHERE expr RP */
+{ yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; }
         break;
       default:
-      /* (323) input ::= cmdlist */ yytestcase(yyruleno==323);
-      /* (324) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==324);
-      /* (325) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=325);
-      /* (326) ecmd ::= SEMI */ yytestcase(yyruleno==326);
-      /* (327) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==327);
-      /* (328) ecmd ::= explain cmdx */ yytestcase(yyruleno==328);
-      /* (329) trans_opt ::= */ yytestcase(yyruleno==329);
-      /* (330) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==330);
-      /* (331) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==331);
-      /* (332) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==332);
-      /* (333) savepoint_opt ::= */ yytestcase(yyruleno==333);
-      /* (334) cmd ::= create_table create_table_args */ yytestcase(yyruleno==334);
-      /* (335) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==335);
-      /* (336) columnlist ::= columnname carglist */ yytestcase(yyruleno==336);
-      /* (337) nm ::= ID|INDEXED */ yytestcase(yyruleno==337);
-      /* (338) nm ::= STRING */ yytestcase(yyruleno==338);
-      /* (339) nm ::= JOIN_KW */ yytestcase(yyruleno==339);
-      /* (340) typetoken ::= typename */ yytestcase(yyruleno==340);
-      /* (341) typename ::= ID|STRING */ yytestcase(yyruleno==341);
-      /* (342) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=342);
-      /* (343) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=343);
-      /* (344) carglist ::= carglist ccons */ yytestcase(yyruleno==344);
-      /* (345) carglist ::= */ yytestcase(yyruleno==345);
-      /* (346) ccons ::= NULL onconf */ yytestcase(yyruleno==346);
-      /* (347) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==347);
-      /* (348) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==348);
-      /* (349) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=349);
-      /* (350) tconscomma ::= */ yytestcase(yyruleno==350);
-      /* (351) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=351);
-      /* (352) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=352);
-      /* (353) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=353);
-      /* (354) oneselect ::= values */ yytestcase(yyruleno==354);
-      /* (355) sclp ::= selcollist COMMA */ yytestcase(yyruleno==355);
-      /* (356) as ::= ID|STRING */ yytestcase(yyruleno==356);
-      /* (357) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=357);
-      /* (358) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==358);
-      /* (359) exprlist ::= nexprlist */ yytestcase(yyruleno==359);
-      /* (360) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=360);
-      /* (361) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=361);
-      /* (362) nmnum ::= ON */ yytestcase(yyruleno==362);
-      /* (363) nmnum ::= DELETE */ yytestcase(yyruleno==363);
-      /* (364) nmnum ::= DEFAULT */ yytestcase(yyruleno==364);
-      /* (365) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==365);
-      /* (366) foreach_clause ::= */ yytestcase(yyruleno==366);
-      /* (367) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==367);
-      /* (368) trnm ::= nm */ yytestcase(yyruleno==368);
-      /* (369) tridxby ::= */ yytestcase(yyruleno==369);
-      /* (370) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==370);
-      /* (371) database_kw_opt ::= */ yytestcase(yyruleno==371);
-      /* (372) kwcolumn_opt ::= */ yytestcase(yyruleno==372);
-      /* (373) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==373);
-      /* (374) vtabarglist ::= vtabarg */ yytestcase(yyruleno==374);
-      /* (375) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==375);
-      /* (376) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==376);
-      /* (377) anylist ::= */ yytestcase(yyruleno==377);
-      /* (378) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==378);
-      /* (379) anylist ::= anylist ANY */ yytestcase(yyruleno==379);
-      /* (380) with ::= */ yytestcase(yyruleno==380);
+      /* (325) input ::= cmdlist */ yytestcase(yyruleno==325);
+      /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326);
+      /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327);
+      /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328);
+      /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329);
+      /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330);
+      /* (331) trans_opt ::= */ yytestcase(yyruleno==331);
+      /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332);
+      /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333);
+      /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334);
+      /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335);
+      /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336);
+      /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337);
+      /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338);
+      /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339);
+      /* (340) nm ::= STRING */ yytestcase(yyruleno==340);
+      /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341);
+      /* (342) typetoken ::= typename */ yytestcase(yyruleno==342);
+      /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343);
+      /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344);
+      /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345);
+      /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346);
+      /* (347) carglist ::= */ yytestcase(yyruleno==347);
+      /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348);
+      /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349);
+      /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350);
+      /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351);
+      /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352);
+      /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353);
+      /* (354) tconscomma ::= */ yytestcase(yyruleno==354);
+      /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355);
+      /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356);
+      /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357);
+      /* (358) oneselect ::= values */ yytestcase(yyruleno==358);
+      /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359);
+      /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360);
+      /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361);
+      /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362);
+      /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363);
+      /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364);
+      /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365);
+      /* (366) nmnum ::= ON */ yytestcase(yyruleno==366);
+      /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367);
+      /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368);
+      /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369);
+      /* (370) foreach_clause ::= */ yytestcase(yyruleno==370);
+      /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371);
+      /* (372) trnm ::= nm */ yytestcase(yyruleno==372);
+      /* (373) tridxby ::= */ yytestcase(yyruleno==373);
+      /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374);
+      /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375);
+      /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376);
+      /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377);
+      /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378);
+      /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379);
+      /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380);
+      /* (381) anylist ::= */ yytestcase(yyruleno==381);
+      /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382);
+      /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383);
+      /* (384) with ::= */ yytestcase(yyruleno==384);
         break;
 /********** End reduce actions ************************************************/
   };
@@ -154790,7 +160159,7 @@ SQLITE_PRIVATE void sqlite3Parser(
 #ifdef YYERRORSYMBOL
       /* A syntax error has occurred.
       ** The response to an error depends upon whether or not the
-      ** grammar defines an error token "ERROR".  
+      ** grammar defines an error token "ERROR".
       **
       ** This is what we do if the grammar does define ERROR:
       **
@@ -154904,8 +160273,8 @@ SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
   return yyFallback[iToken];
 #else
   (void)iToken;
-#endif
   return 0;
+#endif
 }
 
 /************** End of parse.c ***********************************************/
@@ -155014,7 +160383,7 @@ static const unsigned char aiClass[] = {
 ** lower-case ASCII equivalent.  On ASCII machines, this is just
 ** an upper-to-lower case map.  On EBCDIC machines we also need
 ** to adjust the encoding.  The mapping is only valid for alphabetics
-** which are the only characters for which this feature is used. 
+** which are the only characters for which this feature is used.
 **
 ** Used by keywordhash.h
 */
@@ -155046,7 +160415,7 @@ const unsigned char ebcdicToAscii[] = {
 
 /*
 ** The sqlite3KeywordCode function looks up an identifier to determine if
-** it is a keyword.  If it is a keyword, the token code of that keyword is 
+** it is a keyword.  If it is a keyword, the token code of that keyword is
 ** returned.  If the input is not a keyword, TK_ID is returned.
 **
 ** The implementation of this routine was generated by a program,
@@ -155070,20 +160439,20 @@ const unsigned char ebcdicToAscii[] = {
 ** is substantially reduced.  This is important for embedded applications
 ** on platforms with limited memory.
 */
-/* Hash score: 221 */
-/* zKWText[] encodes 967 bytes of keyword text in 638 bytes */
+/* Hash score: 227 */
+/* zKWText[] encodes 984 bytes of keyword text in 648 bytes */
 /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
 /*   ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT       */
 /*   IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS             */
-/*   CONSTRAINTOFFSETRIGGEREFERENCESUNIQUERYWITHOUTERELEASEATTACH       */
-/*   AVINGLOBEGINNERANGEBETWEENOTHINGROUPSCASCADETACHCASECOLLATE        */
-/*   CREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORT        */
-/*   UPDATEVALUESVIRTUALASTWHENWHERECURSIVEAFTERENAMEANDEFAULT          */
-/*   AUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSSCURRENT_TIMESTAMP        */
-/*   ARTITIONDEFERREDISTINCTDROPRECEDINGFAILIMITFILTEREPLACEFIRST       */
-/*   FOLLOWINGFROMFULLIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS          */
+/*   CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES     */
+/*   UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT        */
+/*   CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE       */
+/*   PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND     */
+/*   EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS           */
+/*   CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST      */
+/*   FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS      */
 /*   UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY               */
-static const char zKWText[637] = {
+static const char zKWText[647] = {
   'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
   'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
   'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
@@ -155094,123 +160463,255 @@ static const char zKWText[637] = {
   'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C',
   'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X',
   'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R',
-  'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','E','F',
-  'E','R','E','N','C','E','S','U','N','I','Q','U','E','R','Y','W','I','T',
-  'H','O','U','T','E','R','E','L','E','A','S','E','A','T','T','A','C','H',
-  'A','V','I','N','G','L','O','B','E','G','I','N','N','E','R','A','N','G',
-  'E','B','E','T','W','E','E','N','O','T','H','I','N','G','R','O','U','P',
-  'S','C','A','S','C','A','D','E','T','A','C','H','C','A','S','E','C','O',
-  'L','L','A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T',
-  '_','D','A','T','E','I','M','M','E','D','I','A','T','E','J','O','I','N',
-  'S','E','R','T','M','A','T','C','H','P','L','A','N','A','L','Y','Z','E',
-  'P','R','A','G','M','A','B','O','R','T','U','P','D','A','T','E','V','A',
-  'L','U','E','S','V','I','R','T','U','A','L','A','S','T','W','H','E','N',
-  'W','H','E','R','E','C','U','R','S','I','V','E','A','F','T','E','R','E',
-  'N','A','M','E','A','N','D','E','F','A','U','L','T','A','U','T','O','I',
-  'N','C','R','E','M','E','N','T','C','A','S','T','C','O','L','U','M','N',
-  'C','O','M','M','I','T','C','O','N','F','L','I','C','T','C','R','O','S',
-  'S','C','U','R','R','E','N','T','_','T','I','M','E','S','T','A','M','P',
-  'A','R','T','I','T','I','O','N','D','E','F','E','R','R','E','D','I','S',
-  'T','I','N','C','T','D','R','O','P','R','E','C','E','D','I','N','G','F',
-  'A','I','L','I','M','I','T','F','I','L','T','E','R','E','P','L','A','C',
-  'E','F','I','R','S','T','F','O','L','L','O','W','I','N','G','F','R','O',
-  'M','F','U','L','L','I','F','O','R','D','E','R','E','S','T','R','I','C',
-  'T','O','T','H','E','R','S','O','V','E','R','I','G','H','T','R','O','L',
-  'L','B','A','C','K','R','O','W','S','U','N','B','O','U','N','D','E','D',
-  'U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M','V','I',
-  'E','W','I','N','D','O','W','B','Y','I','N','I','T','I','A','L','L','Y',
-  'P','R','I','M','A','R','Y',
+  'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N',
+  'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N',
+  'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C',
+  'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E',
+  'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E',
+  'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A',
+  'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E',
+  'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E',
+  'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M',
+  'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M',
+  'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V',
+  'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R',
+  'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E',
+  'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A',
+  'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O',
+  'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T',
+  'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S',
+  'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E',
+  'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E',
+  'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W',
+  'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O',
+  'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O',
+  'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W',
+  'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I',
+  'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B',
+  'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
 };
 /* aKWHash[i] is the hash value for the i-th keyword */
 static const unsigned char aKWHash[127] = {
-    82, 113, 130,  80, 110,  29,   0,   0,  89,   0,  83,  70,   0,
-    53,  35,  84,  15,   0, 129,  92,  64, 124, 131,  19,   0,   0,
-   136,   0, 134, 126,   0,  22, 100,   0,   9,   0,   0, 121,  78,
-     0,  76,   6,   0,  58,  97, 143,   0, 132, 108,   0,   0,  48,
-     0, 111,  24,   0,  17,   0, 137,  63,  23,  26,   5,  65, 138,
-   103, 120,   0, 142, 114,  69, 141,  66, 118,  72,   0,  98,   0,
-   107,  41,   0, 106,   0,   0,   0, 102,  99, 104, 109, 123,  14,
-    50, 122,   0,  87,   0, 139, 119, 140,  68, 127, 135,  86,  81,
-    37,  91, 117,   0,   0, 101,  51, 128, 125,   0, 133,   0,   0,
-    44,   0,  93,  67,  39,   0,  20,  45, 115,  88,
+    84, 102, 132,  82, 114,  29,   0,   0,  91,   0,  85,  72,   0,
+    53,  35,  86,  15,   0,  42,  94,  54, 126, 133,  19,   0,   0,
+   138,   0,  40, 128,   0,  22, 104,   0,   9,   0,   0, 122,  80,
+     0,  78,   6,   0,  65,  99, 145,   0, 134, 112,   0,   0,  48,
+     0, 100,  24,   0,  17,   0,  27,  70,  23,  26,   5,  60, 140,
+   107, 121,   0,  73, 101,  71, 143,  61, 119,  74,   0,  49,   0,
+    11,  41,   0, 110,   0,   0,   0, 106,  10, 108, 113, 124,  14,
+    50, 123,   0,  89,   0,  18, 120, 142,  56, 129, 137,  88,  83,
+    37,  30, 125,   0,   0, 105,  51, 130, 127,   0,  34,   0,   0,
+    44,   0,  95,  38,  39,   0,  20,  45, 116,  90,
 };
 /* aKWNext[] forms the hash collision chain.  If aKWHash[i]==0
 ** then the i-th keyword has no more hash collisions.  Otherwise,
 ** the next keyword with the same hash is aKWHash[i]-1. */
-static const unsigned char aKWNext[143] = {
-     0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
-     0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
-     0,   0,   0,  21,   0,   0,   0,   0,  12,   0,   0,   0,   0,
-     0,   0,   0,   7,   0,  36,   0,   0,  28,   0,   0,   0,  31,
-     0,   0,   0,  40,   0,   0,   0,   0,   0,  60,   0,  54,   0,
-     0,  38,  47,   0,   0,   0,   3,   0,   0,  74,   1,  73,   0,
-     0,   0,  52,   0,   0,   0,   0,   0,   0,  57,  59,  56,  30,
-     0,   0,   0,  46,   0,  16,  49,  10,   0,   0,   0,   0,   0,
-     0,   0,  11,  79,  95,   0,   0,   8,   0, 112,   0, 105,   0,
-    43,  62,   0,  77,   0, 116,   0,  61,   0,   0,  94,  42,  55,
-     0,  75,  34,  90,  32,  33,  27,  25,  18,  96,   0,  71,  85,
+static const unsigned char aKWNext[145] = {
+     0,   0,   0,   0,   4,   0,  43,   0,   0, 103, 111,   0,   0,
+     0,   2,   0,   0, 141,   0,   0,   0,  13,   0,   0,   0,   0,
+   139,   0,   0, 118,  52,   0,   0, 135,  12,   0,   0,  62,   0,
+   136,   0, 131,   0,   0,  36,   0,   0,  28,  77,   0,   0,   0,
+     0,  59,   0,  47,   0,   0,   0,   0,   0,   0,   0,   0,   0,
+     0,  69,   0,   0,   0,   0,   0, 144,   3,   0,  58,   0,   1,
+    75,   0,   0,   0,  31,   0,   0,   0,   0,   0,   0,  64,  66,
+    63,   0,   0,   0,   0,  46,   0,  16,   0, 115,   0,   0,   0,
+     0,   0,   0,   0,   0,   0,   0,  81,  97,   0,   8,   0, 109,
+    21,   7,  67,   0,  79,  93, 117,   0,   0,  68,   0,   0,  96,
+     0,  55,   0,  76,   0,  92,  32,  33,  57,  25,   0,  98,   0,
+     0,  87,
 };
 /* aKWLen[i] is the length (in bytes) of the i-th keyword */
-static const unsigned char aKWLen[143] = {
+static const unsigned char aKWLen[145] = {
      7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
      7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   7,
      6,   9,   4,   2,   6,   5,   9,   9,   4,   7,   3,   2,   4,
      4,   6,  11,   6,   2,   7,   5,   5,   9,   6,  10,   4,   6,
-     2,   3,   7,  10,   6,   5,   7,   4,   5,   7,   6,   6,   4,
-     5,   5,   5,   7,   7,   6,   5,   7,   3,   6,   4,   7,   6,
-    12,   9,   4,   6,   5,   4,   7,   6,   5,   6,   6,   7,   4,
-     4,   5,   9,   5,   6,   3,   7,  13,   2,   2,   4,   6,   6,
-     8,   5,  17,  12,   7,   9,   8,   8,   2,   4,   9,   4,   5,
-     6,   7,   5,   9,   4,   4,   2,   5,   8,   6,   4,   5,   8,
-     4,   3,   9,   5,   5,   6,   4,   6,   2,   2,   9,   3,   7,
+     2,   3,   7,   5,   9,   6,   6,   4,   5,   5,  10,   6,   5,
+     7,   4,   5,   7,   6,   7,   7,   6,   5,   7,   3,   7,   4,
+     7,   6,  12,   9,   4,   6,   5,   4,   7,   6,   5,   6,   6,
+     7,   6,   4,   5,   9,   5,   6,   3,   8,   8,   2,  13,   2,
+     2,   4,   6,   6,   8,   5,  17,  12,   7,   9,   4,   9,   4,
+     4,   6,   7,   5,   9,   4,   4,   5,   2,   5,   8,   6,   4,
+     5,   8,   4,   3,   9,   5,   5,   6,   4,   6,   2,   2,   9,
+     3,   7,
 };
 /* aKWOffset[i] is the index into zKWText[] of the start of
 ** the text for the i-th keyword. */
-static const unsigned short int aKWOffset[143] = {
+static const unsigned short int aKWOffset[145] = {
      0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
     36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
     86,  90,  90,  94,  99, 101, 105, 111, 119, 123, 123, 123, 126,
    129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
-   184, 187, 189, 195, 205, 208, 213, 213, 217, 221, 228, 233, 238,
-   241, 244, 248, 253, 259, 265, 265, 271, 272, 276, 282, 286, 293,
-   299, 311, 320, 322, 328, 333, 335, 342, 347, 352, 358, 364, 370,
-   374, 378, 381, 390, 394, 400, 402, 409, 411, 413, 422, 426, 432,
-   438, 446, 451, 451, 451, 467, 476, 483, 484, 491, 494, 503, 506,
-   511, 516, 523, 528, 537, 541, 545, 547, 551, 559, 565, 568, 573,
-   581, 581, 585, 594, 599, 604, 610, 613, 616, 619, 621, 626, 630,
+   184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
+   244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
+   299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371,
+   377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433,
+   435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510,
+   513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575,
+   578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631,
+   636, 640,
 };
 /* aKWCode[i] is the parser symbol code for the i-th keyword */
-static const unsigned char aKWCode[143] = {
-  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
-  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
-  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
-  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
-  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
-  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,         
-  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,       
-  TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    
-  TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
-  TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT, 
-  TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        TK_TRIGGER,    
-  TK_REFERENCES, TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
-  TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_LIKE_KW,    
-  TK_BEGIN,      TK_JOIN_KW,    TK_RANGE,      TK_BETWEEN,    TK_NOTHING,    
-  TK_GROUPS,     TK_GROUP,      TK_CASCADE,    TK_ASC,        TK_DETACH,     
-  TK_CASE,       TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_IMMEDIATE,  
-  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
-  TK_PRAGMA,     TK_ABORT,      TK_UPDATE,     TK_VALUES,     TK_VIRTUAL,    
-  TK_LAST,       TK_WHEN,       TK_WHERE,      TK_RECURSIVE,  TK_AFTER,      
-  TK_RENAME,     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         
-  TK_IN,         TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   
-  TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_CURRENT,    TK_PARTITION,  
-  TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       TK_PRECEDING,  
-  TK_FAIL,       TK_LIMIT,      TK_FILTER,     TK_REPLACE,    TK_FIRST,      
-  TK_FOLLOWING,  TK_FROM,       TK_JOIN_KW,    TK_IF,         TK_ORDER,      
-  TK_RESTRICT,   TK_OTHERS,     TK_OVER,       TK_JOIN_KW,    TK_ROLLBACK,   
-  TK_ROWS,       TK_ROW,        TK_UNBOUNDED,  TK_UNION,      TK_USING,      
-  TK_VACUUM,     TK_VIEW,       TK_WINDOW,     TK_DO,         TK_BY,         
-  TK_INITIALLY,  TK_ALL,        TK_PRIMARY,    
+static const unsigned char aKWCode[145] = {
+  TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
+  TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
+  TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
+  TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
+  TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
+  TK_EXCLUDE,    TK_DELETE,     TK_TEMP,       TK_TEMP,       TK_OR,
+  TK_ISNULL,     TK_NULLS,      TK_SAVEPOINT,  TK_INTERSECT,  TK_TIES,
+  TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
+  TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
+  TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_CONSTRAINT,
+  TK_INTO,       TK_OFFSET,     TK_OF,         TK_SET,        TK_TRIGGER,
+  TK_RANGE,      TK_GENERATED,  TK_DETACH,     TK_HAVING,     TK_LIKE_KW,
+  TK_BEGIN,      TK_JOIN_KW,    TK_REFERENCES, TK_UNIQUE,     TK_QUERY,
+  TK_WITHOUT,    TK_WITH,       TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,
+  TK_BETWEEN,    TK_NOTHING,    TK_GROUPS,     TK_GROUP,      TK_CASCADE,
+  TK_ASC,        TK_DEFAULT,    TK_CASE,       TK_COLLATE,    TK_CREATE,
+  TK_CTIME_KW,   TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,
+  TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     TK_ABORT,      TK_UPDATE,
+  TK_VALUES,     TK_VIRTUAL,    TK_ALWAYS,     TK_WHEN,       TK_WHERE,
+  TK_RECURSIVE,  TK_AFTER,      TK_RENAME,     TK_AND,        TK_DEFERRED,
+  TK_DISTINCT,   TK_IS,         TK_AUTOINCR,   TK_TO,         TK_IN,
+  TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
+  TK_CTIME_KW,   TK_CTIME_KW,   TK_CURRENT,    TK_PARTITION,  TK_DROP,
+  TK_PRECEDING,  TK_FAIL,       TK_LAST,       TK_FILTER,     TK_REPLACE,
+  TK_FIRST,      TK_FOLLOWING,  TK_FROM,       TK_JOIN_KW,    TK_LIMIT,
+  TK_IF,         TK_ORDER,      TK_RESTRICT,   TK_OTHERS,     TK_OVER,
+  TK_JOIN_KW,    TK_ROLLBACK,   TK_ROWS,       TK_ROW,        TK_UNBOUNDED,
+  TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_WINDOW,
+  TK_DO,         TK_BY,         TK_INITIALLY,  TK_ALL,        TK_PRIMARY,
 };
+/* Hash table decoded:
+**   0: INSERT
+**   1: IS
+**   2: ROLLBACK TRIGGER
+**   3: IMMEDIATE
+**   4: PARTITION
+**   5: TEMP
+**   6:
+**   7:
+**   8: VALUES WITHOUT
+**   9:
+**  10: MATCH
+**  11: NOTHING
+**  12:
+**  13: OF
+**  14: TIES IGNORE
+**  15: PLAN
+**  16: INSTEAD INDEXED
+**  17:
+**  18: TRANSACTION RIGHT
+**  19: WHEN
+**  20: SET HAVING
+**  21: IF
+**  22: ROWS
+**  23: SELECT
+**  24:
+**  25:
+**  26: VACUUM SAVEPOINT
+**  27:
+**  28: LIKE UNION VIRTUAL REFERENCES
+**  29: RESTRICT
+**  30:
+**  31: THEN REGEXP
+**  32: TO
+**  33:
+**  34: BEFORE
+**  35:
+**  36:
+**  37: FOLLOWING COLLATE CASCADE
+**  38: CREATE
+**  39:
+**  40: CASE REINDEX
+**  41: EACH
+**  42:
+**  43: QUERY
+**  44: AND ADD
+**  45: PRIMARY ANALYZE
+**  46:
+**  47: ROW ASC DETACH
+**  48: CURRENT_TIME CURRENT_DATE
+**  49:
+**  50:
+**  51: EXCLUSIVE TEMPORARY
+**  52:
+**  53: DEFERRED
+**  54: DEFERRABLE
+**  55:
+**  56: DATABASE
+**  57:
+**  58: DELETE VIEW GENERATED
+**  59: ATTACH
+**  60: END
+**  61: EXCLUDE
+**  62: ESCAPE DESC
+**  63: GLOB
+**  64: WINDOW ELSE
+**  65: COLUMN
+**  66: FIRST
+**  67:
+**  68: GROUPS ALL
+**  69: DISTINCT DROP KEY
+**  70: BETWEEN
+**  71: INITIALLY
+**  72: BEGIN
+**  73: FILTER CHECK ACTION
+**  74: GROUP INDEX
+**  75:
+**  76: EXISTS DEFAULT
+**  77:
+**  78: FOR CURRENT_TIMESTAMP
+**  79: EXCEPT
+**  80:
+**  81: CROSS
+**  82:
+**  83:
+**  84:
+**  85: CAST
+**  86: FOREIGN AUTOINCREMENT
+**  87: COMMIT
+**  88: CURRENT AFTER ALTER
+**  89: FULL FAIL CONFLICT
+**  90: EXPLAIN
+**  91: CONSTRAINT
+**  92: FROM ALWAYS
+**  93:
+**  94: ABORT
+**  95:
+**  96: AS DO
+**  97: REPLACE WITH RELEASE
+**  98: BY RENAME
+**  99: RANGE RAISE
+** 100: OTHERS
+** 101: USING NULLS
+** 102: PRAGMA
+** 103: JOIN ISNULL OFFSET
+** 104: NOT
+** 105: OR LAST LEFT
+** 106: LIMIT
+** 107:
+** 108:
+** 109: IN
+** 110: INTO
+** 111: OVER RECURSIVE
+** 112: ORDER OUTER
+** 113:
+** 114: INTERSECT UNBOUNDED
+** 115:
+** 116:
+** 117: ON
+** 118:
+** 119: WHERE
+** 120: NO INNER
+** 121: NULL
+** 122:
+** 123: TABLE
+** 124: NATURAL NOTNULL
+** 125: PRECEDING
+** 126: UPDATE UNIQUE
+*/
 /* Check to see if z[0..n-1] is a keyword. If it is, write the
 ** parser symbol code for that keyword into *pType.  Always
 ** return the integer n (the length of the token). */
@@ -155221,12 +160722,17 @@ static int keywordCode(const char *z, int n, int *pType){
     i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
     for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
       if( aKWLen[i]!=n ) continue;
-      j = 0;
       zKW = &zKWText[aKWOffset[i]];
 #ifdef SQLITE_ASCII
+      if( (z[0]&~0x20)!=zKW[0] ) continue;
+      if( (z[1]&~0x20)!=zKW[1] ) continue;
+      j = 2;
       while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
 #endif
 #ifdef SQLITE_EBCDIC
+      if( toupper(z[0])!=zKW[0] ) continue;
+      if( toupper(z[1])!=zKW[1] ) continue;
+      j = 2;
       while( j<n && toupper(z[j])==zKW[j] ){ j++; }
 #endif
       if( j<n ) continue;
@@ -155285,94 +160791,96 @@ static int keywordCode(const char *z, int n, int *pType){
       testcase( i==52 ); /* OF */
       testcase( i==53 ); /* SET */
       testcase( i==54 ); /* TRIGGER */
-      testcase( i==55 ); /* REFERENCES */
-      testcase( i==56 ); /* UNIQUE */
-      testcase( i==57 ); /* QUERY */
-      testcase( i==58 ); /* WITHOUT */
-      testcase( i==59 ); /* WITH */
-      testcase( i==60 ); /* OUTER */
-      testcase( i==61 ); /* RELEASE */
-      testcase( i==62 ); /* ATTACH */
-      testcase( i==63 ); /* HAVING */
-      testcase( i==64 ); /* GLOB */
-      testcase( i==65 ); /* BEGIN */
-      testcase( i==66 ); /* INNER */
-      testcase( i==67 ); /* RANGE */
-      testcase( i==68 ); /* BETWEEN */
-      testcase( i==69 ); /* NOTHING */
-      testcase( i==70 ); /* GROUPS */
-      testcase( i==71 ); /* GROUP */
-      testcase( i==72 ); /* CASCADE */
-      testcase( i==73 ); /* ASC */
-      testcase( i==74 ); /* DETACH */
-      testcase( i==75 ); /* CASE */
-      testcase( i==76 ); /* COLLATE */
-      testcase( i==77 ); /* CREATE */
-      testcase( i==78 ); /* CURRENT_DATE */
-      testcase( i==79 ); /* IMMEDIATE */
-      testcase( i==80 ); /* JOIN */
-      testcase( i==81 ); /* INSERT */
-      testcase( i==82 ); /* MATCH */
-      testcase( i==83 ); /* PLAN */
-      testcase( i==84 ); /* ANALYZE */
-      testcase( i==85 ); /* PRAGMA */
-      testcase( i==86 ); /* ABORT */
-      testcase( i==87 ); /* UPDATE */
-      testcase( i==88 ); /* VALUES */
-      testcase( i==89 ); /* VIRTUAL */
-      testcase( i==90 ); /* LAST */
-      testcase( i==91 ); /* WHEN */
-      testcase( i==92 ); /* WHERE */
-      testcase( i==93 ); /* RECURSIVE */
-      testcase( i==94 ); /* AFTER */
-      testcase( i==95 ); /* RENAME */
-      testcase( i==96 ); /* AND */
-      testcase( i==97 ); /* DEFAULT */
-      testcase( i==98 ); /* AUTOINCREMENT */
-      testcase( i==99 ); /* TO */
-      testcase( i==100 ); /* IN */
-      testcase( i==101 ); /* CAST */
-      testcase( i==102 ); /* COLUMN */
-      testcase( i==103 ); /* COMMIT */
-      testcase( i==104 ); /* CONFLICT */
-      testcase( i==105 ); /* CROSS */
-      testcase( i==106 ); /* CURRENT_TIMESTAMP */
-      testcase( i==107 ); /* CURRENT_TIME */
-      testcase( i==108 ); /* CURRENT */
-      testcase( i==109 ); /* PARTITION */
-      testcase( i==110 ); /* DEFERRED */
-      testcase( i==111 ); /* DISTINCT */
-      testcase( i==112 ); /* IS */
-      testcase( i==113 ); /* DROP */
-      testcase( i==114 ); /* PRECEDING */
-      testcase( i==115 ); /* FAIL */
-      testcase( i==116 ); /* LIMIT */
-      testcase( i==117 ); /* FILTER */
-      testcase( i==118 ); /* REPLACE */
-      testcase( i==119 ); /* FIRST */
-      testcase( i==120 ); /* FOLLOWING */
-      testcase( i==121 ); /* FROM */
-      testcase( i==122 ); /* FULL */
-      testcase( i==123 ); /* IF */
-      testcase( i==124 ); /* ORDER */
-      testcase( i==125 ); /* RESTRICT */
-      testcase( i==126 ); /* OTHERS */
-      testcase( i==127 ); /* OVER */
-      testcase( i==128 ); /* RIGHT */
-      testcase( i==129 ); /* ROLLBACK */
-      testcase( i==130 ); /* ROWS */
-      testcase( i==131 ); /* ROW */
-      testcase( i==132 ); /* UNBOUNDED */
-      testcase( i==133 ); /* UNION */
-      testcase( i==134 ); /* USING */
-      testcase( i==135 ); /* VACUUM */
-      testcase( i==136 ); /* VIEW */
-      testcase( i==137 ); /* WINDOW */
-      testcase( i==138 ); /* DO */
-      testcase( i==139 ); /* BY */
-      testcase( i==140 ); /* INITIALLY */
-      testcase( i==141 ); /* ALL */
-      testcase( i==142 ); /* PRIMARY */
+      testcase( i==55 ); /* RANGE */
+      testcase( i==56 ); /* GENERATED */
+      testcase( i==57 ); /* DETACH */
+      testcase( i==58 ); /* HAVING */
+      testcase( i==59 ); /* GLOB */
+      testcase( i==60 ); /* BEGIN */
+      testcase( i==61 ); /* INNER */
+      testcase( i==62 ); /* REFERENCES */
+      testcase( i==63 ); /* UNIQUE */
+      testcase( i==64 ); /* QUERY */
+      testcase( i==65 ); /* WITHOUT */
+      testcase( i==66 ); /* WITH */
+      testcase( i==67 ); /* OUTER */
+      testcase( i==68 ); /* RELEASE */
+      testcase( i==69 ); /* ATTACH */
+      testcase( i==70 ); /* BETWEEN */
+      testcase( i==71 ); /* NOTHING */
+      testcase( i==72 ); /* GROUPS */
+      testcase( i==73 ); /* GROUP */
+      testcase( i==74 ); /* CASCADE */
+      testcase( i==75 ); /* ASC */
+      testcase( i==76 ); /* DEFAULT */
+      testcase( i==77 ); /* CASE */
+      testcase( i==78 ); /* COLLATE */
+      testcase( i==79 ); /* CREATE */
+      testcase( i==80 ); /* CURRENT_DATE */
+      testcase( i==81 ); /* IMMEDIATE */
+      testcase( i==82 ); /* JOIN */
+      testcase( i==83 ); /* INSERT */
+      testcase( i==84 ); /* MATCH */
+      testcase( i==85 ); /* PLAN */
+      testcase( i==86 ); /* ANALYZE */
+      testcase( i==87 ); /* PRAGMA */
+      testcase( i==88 ); /* ABORT */
+      testcase( i==89 ); /* UPDATE */
+      testcase( i==90 ); /* VALUES */
+      testcase( i==91 ); /* VIRTUAL */
+      testcase( i==92 ); /* ALWAYS */
+      testcase( i==93 ); /* WHEN */
+      testcase( i==94 ); /* WHERE */
+      testcase( i==95 ); /* RECURSIVE */
+      testcase( i==96 ); /* AFTER */
+      testcase( i==97 ); /* RENAME */
+      testcase( i==98 ); /* AND */
+      testcase( i==99 ); /* DEFERRED */
+      testcase( i==100 ); /* DISTINCT */
+      testcase( i==101 ); /* IS */
+      testcase( i==102 ); /* AUTOINCREMENT */
+      testcase( i==103 ); /* TO */
+      testcase( i==104 ); /* IN */
+      testcase( i==105 ); /* CAST */
+      testcase( i==106 ); /* COLUMN */
+      testcase( i==107 ); /* COMMIT */
+      testcase( i==108 ); /* CONFLICT */
+      testcase( i==109 ); /* CROSS */
+      testcase( i==110 ); /* CURRENT_TIMESTAMP */
+      testcase( i==111 ); /* CURRENT_TIME */
+      testcase( i==112 ); /* CURRENT */
+      testcase( i==113 ); /* PARTITION */
+      testcase( i==114 ); /* DROP */
+      testcase( i==115 ); /* PRECEDING */
+      testcase( i==116 ); /* FAIL */
+      testcase( i==117 ); /* LAST */
+      testcase( i==118 ); /* FILTER */
+      testcase( i==119 ); /* REPLACE */
+      testcase( i==120 ); /* FIRST */
+      testcase( i==121 ); /* FOLLOWING */
+      testcase( i==122 ); /* FROM */
+      testcase( i==123 ); /* FULL */
+      testcase( i==124 ); /* LIMIT */
+      testcase( i==125 ); /* IF */
+      testcase( i==126 ); /* ORDER */
+      testcase( i==127 ); /* RESTRICT */
+      testcase( i==128 ); /* OTHERS */
+      testcase( i==129 ); /* OVER */
+      testcase( i==130 ); /* RIGHT */
+      testcase( i==131 ); /* ROLLBACK */
+      testcase( i==132 ); /* ROWS */
+      testcase( i==133 ); /* ROW */
+      testcase( i==134 ); /* UNBOUNDED */
+      testcase( i==135 ); /* UNION */
+      testcase( i==136 ); /* USING */
+      testcase( i==137 ); /* VACUUM */
+      testcase( i==138 ); /* VIEW */
+      testcase( i==139 ); /* WINDOW */
+      testcase( i==140 ); /* DO */
+      testcase( i==141 ); /* BY */
+      testcase( i==142 ); /* INITIALLY */
+      testcase( i==143 ); /* ALL */
+      testcase( i==144 ); /* PRIMARY */
       *pType = aKWCode[i];
       break;
     }
@@ -155384,7 +160892,7 @@ SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
   keywordCode((char*)z, n, &id);
   return id;
 }
-#define SQLITE_N_KEYWORD 143
+#define SQLITE_N_KEYWORD 145
 SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
   if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
   *pzName = zKWText + aKWOffset[i];
@@ -155405,14 +160913,14 @@ SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
 ** IdChar(X) will be true.  Otherwise it is false.
 **
 ** For ASCII, any character with the high-order bit set is
-** allowed in an identifier.  For 7-bit characters, 
+** allowed in an identifier.  For 7-bit characters,
 ** sqlite3IsIdChar[X] must be 1.
 **
 ** For EBCDIC, the rules are more complex but have the same
 ** end result.
 **
 ** Ticket #1066.  the SQL standard does not allow '$' in the
-** middle of identifiers.  But many SQL implementations do. 
+** middle of identifiers.  But many SQL implementations do.
 ** SQLite will allow '$' in identifiers for compatibility.
 ** But the feature is undocumented.
 */
@@ -155452,12 +160960,12 @@ static int getToken(const unsigned char **pz){
   do {
     z += sqlite3GetToken(z, &t);
   }while( t==TK_SPACE );
-  if( t==TK_ID 
-   || t==TK_STRING 
-   || t==TK_JOIN_KW 
-   || t==TK_WINDOW 
-   || t==TK_OVER 
-   || sqlite3ParserFallback(t)==TK_ID 
+  if( t==TK_ID
+   || t==TK_STRING
+   || t==TK_JOIN_KW
+   || t==TK_WINDOW
+   || t==TK_OVER
+   || sqlite3ParserFallback(t)==TK_ID
   ){
     t = TK_ID;
   }
@@ -155474,8 +160982,8 @@ static int getToken(const unsigned char **pz){
 **
 **   SELECT sum(x) OVER ...
 **
-** In the above, "OVER" might be a keyword, or it might be an alias for the 
-** sum(x) expression. If a "%fallback ID OVER" directive were added to 
+** In the above, "OVER" might be a keyword, or it might be an alias for the
+** sum(x) expression. If a "%fallback ID OVER" directive were added to
 ** grammar, then SQLite would always treat "OVER" as an alias, making it
 ** impossible to call a window-function without a FILTER clause.
 **
@@ -155519,7 +161027,7 @@ static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
 #endif /* SQLITE_OMIT_WINDOWFUNC */
 
 /*
-** Return the length (in bytes) of the token that begins at z[0]. 
+** Return the length (in bytes) of the token that begins at z[0].
 ** Store the token type in *tokenType before returning.
 */
 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
@@ -155676,6 +161184,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
       }
       /* If the next character is a digit, this is a floating point
       ** number that begins with ".".  Fall thru into the next case */
+      /* no break */ deliberate_fall_through
     }
     case CC_DIGIT: {
       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
@@ -155697,7 +161206,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
         *tokenType = TK_FLOAT;
       }
       if( (z[i]=='e' || z[i]=='E') &&
-           ( sqlite3Isdigit(z[i+1]) 
+           ( sqlite3Isdigit(z[i+1])
             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
            )
       ){
@@ -155780,6 +161289,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
 #endif
       /* If it is not a BLOB literal, then it must be an ID, since no
       ** SQL keywords start with the letter 'x'.  Fall through */
+      /* no break */ deliberate_fall_through
     }
     case CC_ID: {
       i = 1;
@@ -155802,7 +161312,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
 /*
 ** Run the parser on the given SQL string.  The parser structure is
 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
-** then an and attempt is made to write an error message into 
+** then an and attempt is made to write an error message into
 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
 ** error message.
 */
@@ -155822,7 +161332,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   assert( zSql!=0 );
   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   if( db->nVdbeActive==0 ){
-    db->u1.isInterrupted = 0;
+    AtomicStore(&db->u1.isInterrupted, 0);
   }
   pParse->rc = SQLITE_OK;
   pParse->zTail = zSql;
@@ -155861,13 +161371,13 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
 #ifndef SQLITE_OMIT_WINDOWFUNC
     if( tokenType>=TK_WINDOW ){
       assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
-           || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW 
+           || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
       );
 #else
     if( tokenType>=TK_SPACE ){
       assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
 #endif /* SQLITE_OMIT_WINDOWFUNC */
-      if( db->u1.isInterrupted ){
+      if( AtomicLoad(&db->u1.isInterrupted) ){
         pParse->rc = SQLITE_INTERRUPT;
         break;
       }
@@ -155932,7 +161442,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
   assert( pzErrMsg!=0 );
   if( pParse->zErrMsg ){
     *pzErrMsg = pParse->zErrMsg;
-    sqlite3_log(pParse->rc, "%s in \"%s\"", 
+    sqlite3_log(pParse->rc, "%s in \"%s\"",
                 *pzErrMsg, pParse->zTail);
     pParse->zErrMsg = 0;
     nErr++;
@@ -155954,7 +161464,7 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr
 #endif
 
   if( !IN_SPECIAL_PARSE ){
-    /* If the pParse->declareVtab flag is set, do not delete any table 
+    /* If the pParse->declareVtab flag is set, do not delete any table
     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
     ** will take responsibility for freeing the Table structure.
     */
@@ -156011,7 +161521,7 @@ SQLITE_PRIVATE char *sqlite3Normalize(
   int nParen;        /* Number of nested levels of parentheses */
   int iStartIN;      /* Start of RHS of IN operator in z[] */
   int nParenAtIN;    /* Value of nParent at start of RHS of IN operator */
-  int j;             /* Bytes of normalized SQL generated so far */
+  u32 j;             /* Bytes of normalized SQL generated so far */
   sqlite3_str *pStr; /* The normalized SQL string under construction */
 
   db = sqlite3VdbeDb(pVdbe);
@@ -156055,7 +161565,7 @@ SQLITE_PRIVATE char *sqlite3Normalize(
       }
       case TK_RP: {
         if( iStartIN>0 && nParen==nParenAtIN ){
-          assert( pStr->nChar>=iStartIN );
+          assert( pStr->nChar>=(u32)iStartIN );
           pStr->nChar = iStartIN+1;
           sqlite3_str_append(pStr, "?,?,?", 5);
           iStartIN = 0;
@@ -156187,7 +161697,7 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
 **   (2) NORMAL    We are in the middle of statement which ends with a single
 **                 semicolon.
 **
-**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
+**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
 **                 a statement.
 **
 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
@@ -156530,29 +162040,91 @@ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
 }  /* extern "C" */
 #endif  /* __cplusplus */
 
-
 /************** End of sqliteicu.h *******************************************/
 /************** Continuing where we left off in main.c ***********************/
 #endif
+
+/*
+** This is an extension initializer that is a no-op and always
+** succeeds, except that it fails if the fault-simulation is set
+** to 500.
+*/
+static int sqlite3TestExtInit(sqlite3 *db){
+  (void)db;
+  return sqlite3FaultSim(500);
+}
+
+
+/*
+** Forward declarations of external module initializer functions
+** for modules that need them.
+*/
+#ifdef SQLITE_ENABLE_FTS1
+SQLITE_PRIVATE int sqlite3Fts1Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_FTS2
+SQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*);
+#endif
+#ifdef SQLITE_ENABLE_FTS5
+SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
+#endif
 #ifdef SQLITE_ENABLE_JSON1
 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
 #endif
 #ifdef SQLITE_ENABLE_STMTVTAB
 SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
 #endif
+
+/*
+** An array of pointers to extension initializer functions for
+** built-in extensions.
+*/
+static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
+#ifdef SQLITE_ENABLE_FTS1
+  sqlite3Fts1Init,
+#endif
+#ifdef SQLITE_ENABLE_FTS2
+  sqlite3Fts2Init,
+#endif
+#ifdef SQLITE_ENABLE_FTS3
+  sqlite3Fts3Init,
+#endif
 #ifdef SQLITE_ENABLE_FTS5
-SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
+  sqlite3Fts5Init,
 #endif
+#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
+  sqlite3IcuInit,
+#endif
+#ifdef SQLITE_ENABLE_RTREE
+  sqlite3RtreeInit,
+#endif
+#ifdef SQLITE_ENABLE_DBPAGE_VTAB
+  sqlite3DbpageRegister,
+#endif
+#ifdef SQLITE_ENABLE_DBSTAT_VTAB
+  sqlite3DbstatRegister,
+#endif
+  sqlite3TestExtInit,
+#ifdef SQLITE_ENABLE_JSON1
+  sqlite3Json1Init,
+#endif
+#ifdef SQLITE_ENABLE_STMTVTAB
+  sqlite3StmtVtabInit,
+#endif
+#ifdef SQLITE_ENABLE_BYTECODE_VTAB
+  sqlite3VdbeBytecodeVtabInit,
+#endif
+};
 
 #ifndef SQLITE_AMALGAMATION
 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
-** contains the text of SQLITE_VERSION macro. 
+** contains the text of SQLITE_VERSION macro.
 */
 const char sqlite3_version[] = SQLITE_VERSION;
 #endif
 
 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
-** a pointer to the to the sqlite3_version[] string constant. 
+** a pointer to the to the sqlite3_version[] string constant.
 */
 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
 
@@ -156616,13 +162188,13 @@ char *sqlite3_temp_directory = 0;
 char *sqlite3_data_directory = 0;
 
 /*
-** Initialize SQLite.  
+** Initialize SQLite.
 **
 ** This routine must be called to initialize the memory allocation,
 ** VFS, and mutex subsystems prior to doing any serious work with
 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
 ** this routine will be called automatically by key routines such as
-** sqlite3_open().  
+** sqlite3_open().
 **
 ** This routine is a no-op except on its very first call for the process,
 ** or for the first call after a call to sqlite3_shutdown.
@@ -156647,7 +162219,7 @@ char *sqlite3_data_directory = 0;
 **       without blocking.
 */
 SQLITE_API int sqlite3_initialize(void){
-  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
+  MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )      /* The main static mutex */
   int rc;                                      /* Result code */
 #ifdef SQLITE_EXTRA_INIT
   int bRunExtraInit = 0;                       /* Extra initialization needed */
@@ -156670,9 +162242,12 @@ SQLITE_API int sqlite3_initialize(void){
   ** must be complete.  So isInit must not be set until the very end
   ** of this routine.
   */
-  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
+  if( sqlite3GlobalConfig.isInit ){
+    sqlite3MemoryBarrier();
+    return SQLITE_OK;
+  }
 
-  /* Make sure the mutex subsystem is initialized.  If unable to 
+  /* Make sure the mutex subsystem is initialized.  If unable to
   ** initialize the mutex subsystem, return early with the error.
   ** If the system is so sick that we are unable to allocate a mutex,
   ** there is not much SQLite is going to be able to do.
@@ -156684,13 +162259,13 @@ SQLITE_API int sqlite3_initialize(void){
   if( rc ) return rc;
 
   /* Initialize the malloc() system and the recursive pInitMutex mutex.
-  ** This operation is protected by the STATIC_MASTER mutex.  Note that
+  ** This operation is protected by the STATIC_MAIN mutex.  Note that
   ** MutexAlloc() is called for a static mutex prior to initializing the
   ** malloc subsystem - this implies that the allocation of a static
   ** mutex must not require support from the malloc subsystem.
   */
-  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
-  sqlite3_mutex_enter(pMaster);
+  MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
+  sqlite3_mutex_enter(pMainMtx);
   sqlite3GlobalConfig.isMutexInit = 1;
   if( !sqlite3GlobalConfig.isMallocInit ){
     rc = sqlite3MallocInit();
@@ -156708,7 +162283,7 @@ SQLITE_API int sqlite3_initialize(void){
   if( rc==SQLITE_OK ){
     sqlite3GlobalConfig.nRefInitMutex++;
   }
-  sqlite3_mutex_leave(pMaster);
+  sqlite3_mutex_leave(pMainMtx);
 
   /* If rc is not SQLITE_OK at this point, then either the malloc
   ** subsystem could not be initialized or the system failed to allocate
@@ -156754,8 +162329,9 @@ SQLITE_API int sqlite3_initialize(void){
     }
 #endif
     if( rc==SQLITE_OK ){
-      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
+      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
+      sqlite3MemoryBarrier();
       sqlite3GlobalConfig.isInit = 1;
 #ifdef SQLITE_EXTRA_INIT
       bRunExtraInit = 1;
@@ -156768,14 +162344,14 @@ SQLITE_API int sqlite3_initialize(void){
   /* Go back under the static mutex and clean up the recursive
   ** mutex to prevent a resource leak.
   */
-  sqlite3_mutex_enter(pMaster);
+  sqlite3_mutex_enter(pMainMtx);
   sqlite3GlobalConfig.nRefInitMutex--;
   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
     sqlite3GlobalConfig.pInitMutex = 0;
   }
-  sqlite3_mutex_leave(pMaster);
+  sqlite3_mutex_leave(pMainMtx);
 
   /* The following is just a sanity check to make sure SQLite has
   ** been compiled correctly.  It is important to run this code, but
@@ -156988,7 +162564,7 @@ SQLITE_API int sqlite3_config(int op, ...){
       ** a single parameter which is a pointer to an integer and writes into
       ** that integer the number of extra bytes per page required for each page
       ** in SQLITE_CONFIG_PAGECACHE. */
-      *va_arg(ap, int*) = 
+      *va_arg(ap, int*) =
           sqlite3HeaderSizeBtree() +
           sqlite3HeaderSizePcache() +
           sqlite3HeaderSizePcache1();
@@ -157075,7 +162651,7 @@ SQLITE_API int sqlite3_config(int op, ...){
       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
       break;
     }
-    
+
     /* Record a pointer to the logger function and its first argument.
     ** The default is NULL.  Logging is disabled if the function pointer is
     ** NULL.
@@ -157197,7 +162773,7 @@ SQLITE_API int sqlite3_config(int op, ...){
 
 /*
 ** Set up the lookaside buffers for a database connection.
-** Return SQLITE_OK on success.  
+** Return SQLITE_OK on success.
 ** If lookaside is already active, return SQLITE_BUSY.
 **
 ** The sz parameter is the number of bytes in each lookaside slot.
@@ -157209,12 +162785,15 @@ SQLITE_API int sqlite3_config(int op, ...){
 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
 #ifndef SQLITE_OMIT_LOOKASIDE
   void *pStart;
-  
+  sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
+  int nBig;   /* Number of full-size slots */
+  int nSm;    /* Number smaller LOOKASIDE_SMALL-byte slots */
+
   if( sqlite3LookasideUsed(db,0)>0 ){
     return SQLITE_BUSY;
   }
   /* Free any existing lookaside buffer for this handle before
-  ** allocating a new one so we don't have to have space for 
+  ** allocating a new one so we don't have to have space for
   ** both at the same time.
   */
   if( db->lookaside.bMalloced ){
@@ -157231,37 +162810,71 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
     pStart = 0;
   }else if( pBuf==0 ){
     sqlite3BeginBenignMalloc();
-    pStart = sqlite3Malloc( sz*(sqlite3_int64)cnt );  /* IMP: R-61949-35727 */
+    pStart = sqlite3Malloc( szAlloc );  /* IMP: R-61949-35727 */
     sqlite3EndBenignMalloc();
-    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
+    if( pStart ) szAlloc = sqlite3MallocSize(pStart);
   }else{
     pStart = pBuf;
   }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+  if( sz>=LOOKASIDE_SMALL*3 ){
+    nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
+    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
+  }else if( sz>=LOOKASIDE_SMALL*2 ){
+    nBig = szAlloc/(LOOKASIDE_SMALL+sz);
+    nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
+  }else
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+  if( sz>0 ){
+    nBig = szAlloc/sz;
+    nSm = 0;
+  }else{
+    nBig = nSm = 0;
+  }
   db->lookaside.pStart = pStart;
   db->lookaside.pInit = 0;
   db->lookaside.pFree = 0;
   db->lookaside.sz = (u16)sz;
+  db->lookaside.szTrue = (u16)sz;
   if( pStart ){
     int i;
     LookasideSlot *p;
     assert( sz > (int)sizeof(LookasideSlot*) );
-    db->lookaside.nSlot = cnt;
     p = (LookasideSlot*)pStart;
-    for(i=cnt-1; i>=0; i--){
+    for(i=0; i<nBig; i++){
       p->pNext = db->lookaside.pInit;
       db->lookaside.pInit = p;
       p = (LookasideSlot*)&((u8*)p)[sz];
     }
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+    db->lookaside.pSmallInit = 0;
+    db->lookaside.pSmallFree = 0;
+    db->lookaside.pMiddle = p;
+    for(i=0; i<nSm; i++){
+      p->pNext = db->lookaside.pSmallInit;
+      db->lookaside.pSmallInit = p;
+      p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
+    }
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
+    assert( ((uptr)p)<=szAlloc + (uptr)pStart );
     db->lookaside.pEnd = p;
     db->lookaside.bDisable = 0;
     db->lookaside.bMalloced = pBuf==0 ?1:0;
+    db->lookaside.nSlot = nBig+nSm;
   }else{
     db->lookaside.pStart = db;
+#ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
+    db->lookaside.pSmallInit = 0;
+    db->lookaside.pSmallFree = 0;
+    db->lookaside.pMiddle = db;
+#endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
     db->lookaside.pEnd = db;
     db->lookaside.bDisable = 1;
+    db->lookaside.sz = 0;
     db->lookaside.bMalloced = 0;
     db->lookaside.nSlot = 0;
   }
+  assert( sqlite3LookasideUsed(db,0)==0 );
 #endif /* SQLITE_OMIT_LOOKASIDE */
   return SQLITE_OK;
 }
@@ -157319,7 +162932,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
   sqlite3BtreeEnterAll(db);
   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
     Btree *pBt = db->aDb[i].pBt;
-    if( pBt && sqlite3BtreeIsInTrans(pBt) ){
+    if( pBt && sqlite3BtreeTxnState(pBt)==SQLITE_TXN_WRITE ){
       Pager *pPager = sqlite3BtreePager(pBt);
       rc = sqlite3PagerFlush(pPager);
       if( rc==SQLITE_BUSY ){
@@ -157375,6 +162988,8 @@ SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
         { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,    SQLITE_LegacyAlter    },
         { SQLITE_DBCONFIG_DQS_DDL,               SQLITE_DqsDDL         },
         { SQLITE_DBCONFIG_DQS_DML,               SQLITE_DqsDML         },
+        { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,    SQLITE_LegacyFileFmt  },
+        { SQLITE_DBCONFIG_TRUSTED_SCHEMA,        SQLITE_TrustedSchema  },
       };
       unsigned int i;
       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
@@ -157453,7 +163068,7 @@ SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
 }
 
 /*
-** Another built-in collating sequence: NOCASE. 
+** Another built-in collating sequence: NOCASE.
 **
 ** This collating sequence is intended to be used for "case independent
 ** comparison". SQLite's knowledge of upper and lower case equivalents
@@ -157597,7 +163212,7 @@ static void disconnectAllVtab(sqlite3 *db){
 
 /*
 ** Return TRUE if database connection db has unfinalized prepared
-** statements or unfinished sqlite3_backup objects.  
+** statements or unfinished sqlite3_backup objects.
 */
 static int connectionIsBusy(sqlite3 *db){
   int j;
@@ -157624,7 +163239,7 @@ static int sqlite3Close(sqlite3 *db, int forceZombie){
   }
   sqlite3_mutex_enter(db->mutex);
   if( db->mTrace & SQLITE_TRACE_CLOSE ){
-    db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
+    db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
   }
 
   /* Force xDisconnect calls on all virtual tables */
@@ -157664,6 +163279,36 @@ static int sqlite3Close(sqlite3 *db, int forceZombie){
 }
 
 /*
+** Return the transaction state for a single databse, or the maximum
+** transaction state over all attached databases if zSchema is null.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3 *db, const char *zSchema){
+  int iDb, nDb;
+  int iTxn = -1;
+#ifdef SQLITE_ENABLE_API_ARMOR
+  if( !sqlite3SafetyCheckOk(db) ){
+    (void)SQLITE_MISUSE_BKPT;
+    return -1;
+  }
+#endif
+  sqlite3_mutex_enter(db->mutex);
+  if( zSchema ){
+    nDb = iDb = sqlite3FindDbName(db, zSchema);
+    if( iDb<0 ) nDb--;
+  }else{
+    iDb = 0;
+    nDb = db->nDb-1;
+  }
+  for(; iDb<=nDb; iDb++){
+    Btree *pBt = db->aDb[iDb].pBt;
+    int x = pBt!=0 ? sqlite3BtreeTxnState(pBt) : SQLITE_TXN_NONE;
+    if( x>iTxn ) iTxn = x;
+  }
+  sqlite3_mutex_leave(db->mutex);
+  return iTxn;
+}
+
+/*
 ** Two variations on the public interface for closing a database
 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
 ** leaves the connection option if there are unfinalized prepared
@@ -157783,7 +163428,7 @@ SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
   /* The temp-database schema is allocated differently from the other schema
   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
   ** So it needs to be freed here. Todo: Why not roll the temp schema into
-  ** the same sqliteMalloc() as the one that allocates the database 
+  ** the same sqliteMalloc() as the one that allocates the database
   ** structure?
   */
   sqlite3DbFree(db, db->aDb[1].pSchema);
@@ -157811,7 +163456,7 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   assert( sqlite3_mutex_held(db->mutex) );
   sqlite3BeginBenignMalloc();
 
-  /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
+  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
   ** This is important in case the transaction being rolled back has
   ** modified the database schema. If the b-tree mutexes are not taken
   ** here, then another shared-cache connection might sneak in between
@@ -157823,7 +163468,7 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
   for(i=0; i<db->nDb; i++){
     Btree *p = db->aDb[i].pBt;
     if( p ){
-      if( sqlite3BtreeIsInTrans(p) ){
+      if( sqlite3BtreeTxnState(p)==SQLITE_TXN_WRITE ){
         inTrans = 1;
       }
       sqlite3BtreeRollback(p, tripCode, !schemaChange);
@@ -157915,6 +163560,7 @@ SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
+      case SQLITE_CANTOPEN_SYMLINK:   zName = "SQLITE_CANTOPEN_SYMLINK";  break;
       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
@@ -158036,8 +163682,7 @@ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
 */
 static int sqliteDefaultBusyCallback(
   void *ptr,               /* Database connection */
-  int count,               /* Number of times table has been busy */
-  sqlite3_file *pFile      /* The file on which the lock occurred */
+  int count                /* Number of times table has been busy */
 ){
 #if SQLITE_OS_WIN || HAVE_USLEEP
   /* This case is for systems that have support for sleeping for fractions of
@@ -158051,19 +163696,6 @@ static int sqliteDefaultBusyCallback(
   int tmout = db->busyTimeout;
   int delay, prior;
 
-#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
-  if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
-    if( count ){
-      tmout = 0;
-      sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
-      return 0;
-    }else{
-      return 1;
-    }
-  }
-#else
-  UNUSED_PARAMETER(pFile);
-#endif
   assert( count>=0 );
   if( count < NDELAY ){
     delay = delays[count];
@@ -158083,7 +163715,6 @@ static int sqliteDefaultBusyCallback(
   ** must be done in increments of whole seconds */
   sqlite3 *db = (sqlite3 *)ptr;
   int tmout = ((sqlite3 *)ptr)->busyTimeout;
-  UNUSED_PARAMETER(pFile);
   if( (count+1)*1000 > tmout ){
     return 0;
   }
@@ -158101,25 +163732,16 @@ static int sqliteDefaultBusyCallback(
 ** If this routine returns non-zero, the lock is retried.  If it
 ** returns 0, the operation aborts with an SQLITE_BUSY error.
 */
-SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
+SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
   int rc;
   if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
-  if( p->bExtraFileArg ){
-    /* Add an extra parameter with the pFile pointer to the end of the
-    ** callback argument list */
-    int (*xTra)(void*,int,sqlite3_file*);
-    xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
-    rc = xTra(p->pBusyArg, p->nBusy, pFile);
-  }else{
-    /* Legacy style busy handler callback */
-    rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
-  }
+  rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
   if( rc==0 ){
     p->nBusy = -1;
   }else{
     p->nBusy++;
   }
-  return rc; 
+  return rc;
 }
 
 /*
@@ -158138,7 +163760,6 @@ SQLITE_API int sqlite3_busy_handler(
   db->busyHandler.xBusyHandler = xBusy;
   db->busyHandler.pBusyArg = pArg;
   db->busyHandler.nBusy = 0;
-  db->busyHandler.bExtraFileArg = 0;
   db->busyTimeout = 0;
   sqlite3_mutex_leave(db->mutex);
   return SQLITE_OK;
@@ -158151,9 +163772,9 @@ SQLITE_API int sqlite3_busy_handler(
 ** be invoked every nOps opcodes.
 */
 SQLITE_API void sqlite3_progress_handler(
-  sqlite3 *db, 
+  sqlite3 *db,
   int nOps,
-  int (*xProgress)(void*), 
+  int (*xProgress)(void*),
   void *pArg
 ){
 #ifdef SQLITE_ENABLE_API_ARMOR
@@ -158189,7 +163810,6 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
     sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
                              (void*)db);
     db->busyTimeout = ms;
-    db->busyHandler.bExtraFileArg = 1;
   }else{
     sqlite3_busy_handler(db, 0, 0);
   }
@@ -158206,7 +163826,7 @@ SQLITE_API void sqlite3_interrupt(sqlite3 *db){
     return;
   }
 #endif
-  db->u1.isInterrupted = 1;
+  AtomicStore(&db->u1.isInterrupted, 1);
 }
 
 
@@ -158214,7 +163834,7 @@ SQLITE_API void sqlite3_interrupt(sqlite3 *db){
 ** This function is exactly the same as sqlite3_create_function(), except
 ** that it is designed to be called by internal code. The difference is
 ** that if a malloc() fails in sqlite3_create_function(), an error code
-** is returned and the mallocFailed flag cleared. 
+** is returned and the mallocFailed flag cleared.
 */
 SQLITE_PRIVATE int sqlite3CreateFunc(
   sqlite3 *db,
@@ -158247,9 +163867,16 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
 
   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
   assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
-  extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|SQLITE_SUBTYPE);
+  extraFlags = enc &  (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
+                       SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
-  
+
+  /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE.  But
+  ** the meaning is inverted.  So flip the bit. */
+  assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
+  extraFlags ^= SQLITE_FUNC_UNSAFE;
+
+
 #ifndef SQLITE_OMIT_UTF16
   /* If SQLITE_UTF16 is specified as the encoding type, transform this
   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
@@ -158262,11 +163889,13 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
     enc = SQLITE_UTF16NATIVE;
   }else if( enc==SQLITE_ANY ){
     int rc;
-    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
+    rc = sqlite3CreateFunc(db, zFunctionName, nArg,
+         (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
          pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
     if( rc==SQLITE_OK ){
-      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
-          pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
+      rc = sqlite3CreateFunc(db, zFunctionName, nArg,
+           (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
+           pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
     }
     if( rc!=SQLITE_OK ){
       return rc;
@@ -158276,7 +163905,7 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
 #else
   enc = SQLITE_UTF8;
 #endif
-  
+
   /* Check if an existing function is being overridden or deleted. If so,
   ** and there are active VMs, then return SQLITE_BUSY. If a function
   ** is being overridden/deleted but there are no active VMs, allow the
@@ -158285,7 +163914,7 @@ SQLITE_PRIVATE int sqlite3CreateFunc(
   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
     if( db->nVdbeActive ){
-      sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
+      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
         "unable to delete/modify user-function due to active statements");
       assert( !db->mallocFailed );
       return SQLITE_BUSY;
@@ -158360,7 +163989,7 @@ static int createFunctionApi(
     pArg->xDestroy = xDestroy;
     pArg->pUserData = p;
   }
-  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, 
+  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
       xSFunc, xStep, xFinal, xValue, xInverse, pArg
   );
   if( pArg && pArg->nRef==0 ){
@@ -158478,7 +164107,7 @@ static void sqlite3InvalidFunction(
 **
 ** If the function already exists as a regular global function, then
 ** this routine is a no-op.  If the function does not exist, then create
-** a new one that always throws a run-time error.  
+** a new one that always throws a run-time error.
 **
 ** When virtual tables intend to provide an overloaded function, they
 ** should call this routine to make sure the global function exists.
@@ -158511,7 +164140,7 @@ SQLITE_API int sqlite3_overload_function(
 #ifndef SQLITE_OMIT_TRACE
 /*
 ** Register a trace function.  The pArg from the previously registered trace
-** is returned.  
+** is returned.
 **
 ** A NULL trace function means that no tracing is executes.  A non-NULL
 ** trace is a pointer to a function that is invoked at the start of each
@@ -158530,7 +164159,7 @@ SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), vo
   sqlite3_mutex_enter(db->mutex);
   pOld = db->pTraceArg;
   db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
-  db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
+  db->trace.xLegacy = xTrace;
   db->pTraceArg = pArg;
   sqlite3_mutex_leave(db->mutex);
   return pOld;
@@ -158554,7 +164183,7 @@ SQLITE_API int sqlite3_trace_v2(
   if( mTrace==0 ) xTrace = 0;
   if( xTrace==0 ) mTrace = 0;
   db->mTrace = mTrace;
-  db->xTrace = xTrace;
+  db->trace.xV2 = xTrace;
   db->pTraceArg = pArg;
   sqlite3_mutex_leave(db->mutex);
   return SQLITE_OK;
@@ -158562,8 +164191,8 @@ SQLITE_API int sqlite3_trace_v2(
 
 #ifndef SQLITE_OMIT_DEPRECATED
 /*
-** Register a profile function.  The pArg from the previously registered 
-** profile function is returned.  
+** Register a profile function.  The pArg from the previously registered
+** profile function is returned.
 **
 ** A NULL profile function means that no profiling is executes.  A non-NULL
 ** profile is a pointer to a function that is invoked at the conclusion of
@@ -158697,7 +164326,7 @@ SQLITE_API void *sqlite3_preupdate_hook(
 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
 ** wal_autocheckpoint()).
-*/ 
+*/
 SQLITE_PRIVATE int sqlite3WalDefaultHook(
   void *pClientData,     /* Argument */
   sqlite3 *db,           /* Connection */
@@ -158820,7 +164449,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(
   /* If there are no active statements, clear the interrupt flag at this
   ** point.  */
   if( db->nVdbeActive==0 ){
-    db->u1.isInterrupted = 0;
+    AtomicStore(&db->u1.isInterrupted, 0);
   }
 
   sqlite3_mutex_leave(db->mutex);
@@ -158831,7 +164460,7 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(
 
 /*
 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
-** to contains a zero-length string, all attached databases are 
+** to contains a zero-length string, all attached databases are
 ** checkpointed.
 */
 #undef sqlite3_wal_checkpoint
@@ -158846,9 +164475,9 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
 ** not currently open in WAL mode.
 **
-** If a transaction is open on the database being checkpointed, this 
-** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
-** an error occurs while running the checkpoint, an SQLite error code is 
+** If a transaction is open on the database being checkpointed, this
+** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
+** an error occurs while running the checkpoint, an SQLite error code is
 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
 **
 ** The mutex on database handle db should be held by the caller. The mutex
@@ -159017,7 +164646,7 @@ SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
 }
 SQLITE_API int sqlite3_system_errno(sqlite3 *db){
   return db ? db->iSysErrno : 0;
-}  
+}
 
 /*
 ** Return a string that describes the kind of error specified in the
@@ -159034,7 +164663,7 @@ SQLITE_API const char *sqlite3_errstr(int rc){
 */
 static int createCollation(
   sqlite3* db,
-  const char *zName, 
+  const char *zName,
   u8 enc,
   void* pCtx,
   int(*xCompare)(void*,int,const void*,int,const void*),
@@ -159042,7 +164671,7 @@ static int createCollation(
 ){
   CollSeq *pColl;
   int enc2;
-  
+
   assert( sqlite3_mutex_held(db->mutex) );
 
   /* If SQLITE_UTF16 is specified as the encoding type, transform this
@@ -159059,14 +164688,14 @@ static int createCollation(
     return SQLITE_MISUSE_BKPT;
   }
 
-  /* Check if this call is removing or replacing an existing collation 
+  /* Check if this call is removing or replacing an existing collation
   ** sequence. If so, and there are active VMs, return busy. If there
   ** are no active VMs, invalidate any pre-compiled statements.
   */
   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
   if( pColl && pColl->xCmp ){
     if( db->nVdbeActive ){
-      sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
+      sqlite3ErrorWithMsg(db, SQLITE_BUSY,
         "unable to delete/modify collation sequence due to active statements");
       return SQLITE_BUSY;
     }
@@ -159077,7 +164706,7 @@ static int createCollation(
     ** then any copies made by synthCollSeq() need to be invalidated.
     ** Also, collation destructor - CollSeq.xDel() - function may need
     ** to be called.
-    */ 
+    */
     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
       int j;
@@ -159226,17 +164855,19 @@ SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
 ** query parameter. The second argument contains the URI (or non-URI filename)
 ** itself. When this function is called the *pFlags variable should contain
 ** the default flags to open the database handle with. The value stored in
-** *pFlags may be updated before returning if the URI filename contains 
+** *pFlags may be updated before returning if the URI filename contains
 ** "cache=xxx" or "mode=xxx" query parameters.
 **
 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
 ** the VFS that should be used to open the database file. *pzFile is set to
-** point to a buffer containing the name of the file to open. It is the 
-** responsibility of the caller to eventually call sqlite3_free() to release
-** this buffer.
+** point to a buffer containing the name of the file to open.  The value
+** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
+** and is in the same format as names created using sqlite3_create_filename().
+** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
+** the value returned in *pzFile to avoid a memory leak.
 **
 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
-** may be set to point to a buffer containing an English language error 
+** may be set to point to a buffer containing an English language error
 ** message. It is the responsibility of the caller to eventually release
 ** this buffer by calling sqlite3_free().
 */
@@ -159244,7 +164875,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
   const char *zUri,               /* Nul-terminated URI to parse */
   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
-  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
+  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
   char **pzFile,                  /* OUT: Filename component of URI */
   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
 ){
@@ -159265,9 +164896,9 @@ SQLITE_PRIVATE int sqlite3ParseUri(
     int eState;                   /* Parser state when parsing URI */
     int iIn;                      /* Input character index */
     int iOut = 0;                 /* Output character index */
-    size_t nByte = nUri+2;        /* Bytes of space to allocate */
+    size_t nByte = nUri+8;        /* Bytes of space to allocate */
 
-    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
+    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
     ** method that there may be extra parameters following the file-name.  */
     flags |= SQLITE_OPEN_URI;
 
@@ -159275,6 +164906,9 @@ SQLITE_PRIVATE int sqlite3ParseUri(
     zFile = sqlite3Malloc(nByte);
     if( !zFile ) return SQLITE_NOMEM_BKPT;
 
+    memset(zFile, 0, 4);  /* 4-byte of 0x00 is the start of DB name marker */
+    zFile += 4;
+
     iIn = 5;
 #ifdef SQLITE_ALLOW_URI_AUTHORITY
     if( strncmp(zUri+5, "///", 3)==0 ){
@@ -159282,7 +164916,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
       /* The following condition causes URIs with five leading / characters
       ** like file://///host/path to be converted into UNCs like //host/path.
       ** The correct URI for that UNC has only two or four leading / characters
-      ** file://host/path or file:////host/path.  But 5 leading slashes is a 
+      ** file://host/path or file:////host/path.  But 5 leading slashes is a
       ** common error, we are told, so we handle it as a special case. */
       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
@@ -159294,7 +164928,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
       iIn = 7;
       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
-        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
+        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
             iIn-7, &zUri[7]);
         rc = SQLITE_ERROR;
         goto parse_uri_out;
@@ -159302,8 +164936,8 @@ SQLITE_PRIVATE int sqlite3ParseUri(
     }
 #endif
 
-    /* Copy the filename and any query parameters into the zFile buffer. 
-    ** Decode %HH escape codes along the way. 
+    /* Copy the filename and any query parameters into the zFile buffer.
+    ** Decode %HH escape codes along the way.
     **
     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
     ** on the parsing context. As follows:
@@ -159315,9 +164949,9 @@ SQLITE_PRIVATE int sqlite3ParseUri(
     eState = 0;
     while( (c = zUri[iIn])!=0 && c!='#' ){
       iIn++;
-      if( c=='%' 
-       && sqlite3Isxdigit(zUri[iIn]) 
-       && sqlite3Isxdigit(zUri[iIn+1]) 
+      if( c=='%'
+       && sqlite3Isxdigit(zUri[iIn])
+       && sqlite3Isxdigit(zUri[iIn+1])
       ){
         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
         octet += sqlite3HexToInt(zUri[iIn++]);
@@ -159329,7 +164963,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
           ** case we ignore all text in the remainder of the path, name or
           ** value currently being parsed. So ignore the current character
           ** and skip to the next "?", "=" or "&", as appropriate. */
-          while( (c = zUri[iIn])!=0 && c!='#' 
+          while( (c = zUri[iIn])!=0 && c!='#'
               && (eState!=0 || c!='?')
               && (eState!=1 || (c!='=' && c!='&'))
               && (eState!=2 || c!='&')
@@ -159364,10 +164998,9 @@ SQLITE_PRIVATE int sqlite3ParseUri(
       zFile[iOut++] = c;
     }
     if( eState==1 ) zFile[iOut++] = '\0';
-    zFile[iOut++] = '\0';
-    zFile[iOut++] = '\0';
+    memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
 
-    /* Check if there were any options specified that should be interpreted 
+    /* Check if there were any options specified that should be interpreted
     ** here. Options that are interpreted here include "vfs" and those that
     ** correspond to flags that may be passed to the sqlite3_open_v2()
     ** method. */
@@ -159403,7 +165036,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
           static const struct OpenMode aOpenMode[] = {
             { "ro",  SQLITE_OPEN_READONLY },
-            { "rw",  SQLITE_OPEN_READWRITE }, 
+            { "rw",  SQLITE_OPEN_READWRITE },
             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
             { "memory", SQLITE_OPEN_MEMORY },
             { 0, 0 }
@@ -159445,13 +165078,14 @@ SQLITE_PRIVATE int sqlite3ParseUri(
     }
 
   }else{
-    zFile = sqlite3Malloc(nUri+2);
+    zFile = sqlite3Malloc(nUri+8);
     if( !zFile ) return SQLITE_NOMEM_BKPT;
+    memset(zFile, 0, 4);
+    zFile += 4;
     if( nUri ){
       memcpy(zFile, zUri, nUri);
     }
-    zFile[nUri] = '\0';
-    zFile[nUri+1] = '\0';
+    memset(zFile+nUri, 0, 4);
     flags &= ~SQLITE_OPEN_URI;
   }
 
@@ -159462,7 +165096,7 @@ SQLITE_PRIVATE int sqlite3ParseUri(
   }
  parse_uri_out:
   if( rc!=SQLITE_OK ){
-    sqlite3_free(zFile);
+    sqlite3_free_filename(zFile);
     zFile = 0;
   }
   *pFlags = flags;
@@ -159470,44 +165104,26 @@ SQLITE_PRIVATE int sqlite3ParseUri(
   return rc;
 }
 
-#if defined(SQLITE_HAS_CODEC)
 /*
-** Process URI filename query parameters relevant to the SQLite Encryption
-** Extension.  Return true if any of the relevant query parameters are
-** seen and return false if not.
+** This routine does the core work of extracting URI parameters from a
+** database filename for the sqlite3_uri_parameter() interface.
 */
-SQLITE_PRIVATE int sqlite3CodecQueryParameters(
-  sqlite3 *db,           /* Database connection */
-  const char *zDb,       /* Which schema is being created/attached */
-  const char *zUri       /* URI filename */
-){
-  const char *zKey;
-  if( (zKey = sqlite3_uri_parameter(zUri, "hexkey"))!=0 && zKey[0] ){
-    u8 iByte;
-    int i;
-    char zDecoded[40];
-    for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
-      iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
-      if( (i&1)!=0 ) zDecoded[i/2] = iByte;
-    }
-    sqlite3_key_v2(db, zDb, zDecoded, i/2);
-    return 1;
-  }else if( (zKey = sqlite3_uri_parameter(zUri, "key"))!=0 ){
-    sqlite3_key_v2(db, zDb, zKey, sqlite3Strlen30(zKey));
-    return 1;
-  }else if( (zKey = sqlite3_uri_parameter(zUri, "textkey"))!=0 ){
-    sqlite3_key_v2(db, zDb, zKey, -1);
-    return 1;
-  }else{
-    return 0;
+static const char *uriParameter(const char *zFilename, const char *zParam){
+  zFilename += sqlite3Strlen30(zFilename) + 1;
+  while( zFilename[0] ){
+    int x = strcmp(zFilename, zParam);
+    zFilename += sqlite3Strlen30(zFilename) + 1;
+    if( x==0 ) return zFilename;
+    zFilename += sqlite3Strlen30(zFilename) + 1;
   }
+  return 0;
 }
-#endif
+
 
 
 /*
 ** This routine does the work of opening a database on behalf of
-** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
+** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
 ** is UTF-8 encoded.
 */
 static int openDatabase(
@@ -159521,6 +165137,7 @@ static int openDatabase(
   int isThreadsafe;               /* True for threadsafe connections */
   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
+  int i;                          /* Loop counter */
 
 #ifdef SQLITE_ENABLE_API_ARMOR
   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
@@ -159559,12 +165176,12 @@ static int openDatabase(
   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
                SQLITE_OPEN_EXCLUSIVE |
                SQLITE_OPEN_MAIN_DB |
-               SQLITE_OPEN_TEMP_DB | 
-               SQLITE_OPEN_TRANSIENT_DB | 
-               SQLITE_OPEN_MAIN_JOURNAL | 
-               SQLITE_OPEN_TEMP_JOURNAL | 
-               SQLITE_OPEN_SUBJOURNAL | 
-               SQLITE_OPEN_MASTER_JOURNAL |
+               SQLITE_OPEN_TEMP_DB |
+               SQLITE_OPEN_TRANSIENT_DB |
+               SQLITE_OPEN_MAIN_JOURNAL |
+               SQLITE_OPEN_TEMP_JOURNAL |
+               SQLITE_OPEN_SUBJOURNAL |
+               SQLITE_OPEN_SUPER_JOURNAL |
                SQLITE_OPEN_NOMUTEX |
                SQLITE_OPEN_FULLMUTEX |
                SQLITE_OPEN_WAL
@@ -159573,7 +165190,7 @@ static int openDatabase(
   /* Allocate the sqlite data structure */
   db = sqlite3MallocZero( sizeof(sqlite3) );
   if( db==0 ) goto opendb_out;
-  if( isThreadsafe 
+  if( isThreadsafe
 #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
    || sqlite3GlobalConfig.bCoreMutex
 #endif
@@ -159594,6 +165211,7 @@ static int openDatabase(
   db->magic = SQLITE_MAGIC_BUSY;
   db->aDb = db->aDbStatic;
   db->lookaside.bDisable = 1;
+  db->lookaside.sz = 0;
 
   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
@@ -159607,13 +165225,15 @@ static int openDatabase(
                  | SQLITE_EnableTrigger
                  | SQLITE_EnableView
                  | SQLITE_CacheSpill
-
+#if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
+                 | SQLITE_TrustedSchema
+#endif
 /* The SQLITE_DQS compile-time option determines the default settings
 ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
 **
 **    SQLITE_DQS     SQLITE_DBCONFIG_DQS_DDL    SQLITE_DBCONFIG_DQS_DML
 **    ----------     -----------------------    -----------------------
-**     undefined               on                          on   
+**     undefined               on                          on
 **         3                   on                          on
 **         2                   on                         off
 **         1                  off                          on
@@ -159663,6 +165283,9 @@ static int openDatabase(
 #if defined(SQLITE_DEFAULT_DEFENSIVE)
                  | SQLITE_Defensive
 #endif
+#if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
+                 | SQLITE_LegacyAlter
+#endif
       ;
   sqlite3HashInit(&db->aCollSeq);
 #ifndef SQLITE_OMIT_VIRTUALTABLE
@@ -159684,15 +165307,10 @@ static int openDatabase(
   if( db->mallocFailed ){
     goto opendb_out;
   }
-  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
-  ** strings is BINARY. 
-  */
-  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
-  assert( db->pDfltColl!=0 );
 
   /* Parse the filename/URI argument
   **
-  ** Only allow sensible combinations of bits in the flags argument.  
+  ** Only allow sensible combinations of bits in the flags argument.
   ** Throw an error if any non-sense combination is used.  If we
   ** do not block illegal combinations here, it could trigger
   ** assert() statements in deeper layers.  Sensible combinations
@@ -159710,7 +165328,7 @@ static int openDatabase(
   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
   if( ((1<<(flags&7)) & 0x46)==0 ){
-    rc = SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
+    rc = SQLITE_MISUSE_BKPT;  /* IMP: R-18321-05872 */
   }else{
     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
   }
@@ -159733,12 +165351,14 @@ static int openDatabase(
   }
   sqlite3BtreeEnter(db->aDb[0].pBt);
   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
-  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
+  if( !db->mallocFailed ){
+    sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
+  }
   sqlite3BtreeLeave(db->aDb[0].pBt);
   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
 
   /* The default safety_level for the main database is FULL; for the temp
-  ** database it is OFF. This matches the pager layer defaults.  
+  ** database it is OFF. This matches the pager layer defaults.
   */
   db->aDb[0].zDbSName = "main";
   db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
@@ -159758,14 +165378,11 @@ static int openDatabase(
   sqlite3RegisterPerConnectionBuiltinFunctions(db);
   rc = sqlite3_errcode(db);
 
-#ifdef SQLITE_ENABLE_FTS5
-  /* Register any built-in FTS5 module before loading the automatic
-  ** extensions. This allows automatic extensions to register FTS5 
-  ** tokenizers and auxiliary functions.  */
-  if( !db->mallocFailed && rc==SQLITE_OK ){
-    rc = sqlite3Fts5Init(db);
+
+  /* Load compiled-in extensions */
+  for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
+    rc = sqlite3BuiltinExtensions[i](db);
   }
-#endif
 
   /* Load automatic extensions - extensions that have been registered
   ** using the sqlite3_automatic_extension() API.
@@ -159778,60 +165395,11 @@ static int openDatabase(
     }
   }
 
-#ifdef SQLITE_ENABLE_FTS1
-  if( !db->mallocFailed ){
-    extern int sqlite3Fts1Init(sqlite3*);
-    rc = sqlite3Fts1Init(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_FTS2
-  if( !db->mallocFailed && rc==SQLITE_OK ){
-    extern int sqlite3Fts2Init(sqlite3*);
-    rc = sqlite3Fts2Init(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
-  if( !db->mallocFailed && rc==SQLITE_OK ){
-    rc = sqlite3Fts3Init(db);
-  }
-#endif
-
-#if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
-  if( !db->mallocFailed && rc==SQLITE_OK ){
-    rc = sqlite3IcuInit(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_RTREE
-  if( !db->mallocFailed && rc==SQLITE_OK){
-    rc = sqlite3RtreeInit(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_DBPAGE_VTAB
-  if( !db->mallocFailed && rc==SQLITE_OK){
-    rc = sqlite3DbpageRegister(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_DBSTAT_VTAB
-  if( !db->mallocFailed && rc==SQLITE_OK){
-    rc = sqlite3DbstatRegister(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_JSON1
-  if( !db->mallocFailed && rc==SQLITE_OK){
-    rc = sqlite3Json1Init(db);
-  }
-#endif
-
-#ifdef SQLITE_ENABLE_STMTVTAB
-  if( !db->mallocFailed && rc==SQLITE_OK){
-    rc = sqlite3StmtVtabInit(db);
-  }
+#ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
+  /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
+  ** option gives access to internal functions by default.
+  ** Testing use only!!! */
+  db->mDbFlags |= DBFLAG_InternalFunc;
 #endif
 
   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
@@ -159874,10 +165442,7 @@ opendb_out:
     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
   }
 #endif
-#if defined(SQLITE_HAS_CODEC)
-  if( rc==SQLITE_OK ) sqlite3CodecQueryParameters(db, 0, zOpen);
-#endif
-  sqlite3_free(zOpen);
+  sqlite3_free_filename(zOpen);
   return rc & 0xff;
 }
 
@@ -159886,8 +165451,8 @@ opendb_out:
 ** Open a new database handle.
 */
 SQLITE_API int sqlite3_open(
-  const char *zFilename, 
-  sqlite3 **ppDb 
+  const char *zFilename,
+  sqlite3 **ppDb
 ){
   return openDatabase(zFilename, ppDb,
                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
@@ -159906,7 +165471,7 @@ SQLITE_API int sqlite3_open_v2(
 ** Open a new database handle.
 */
 SQLITE_API int sqlite3_open16(
-  const void *zFilename, 
+  const void *zFilename,
   sqlite3 **ppDb
 ){
   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
@@ -159946,9 +165511,9 @@ SQLITE_API int sqlite3_open16(
 */
 #undef sqlite3_create_collation
 SQLITE_API int sqlite3_create_collation(
-  sqlite3* db, 
-  const char *zName, 
-  int enc, 
+  sqlite3* db,
+  const char *zName,
+  int enc,
   void* pCtx,
   int(*xCompare)(void*,int,const void*,int,const void*)
 ){
@@ -159959,9 +165524,9 @@ SQLITE_API int sqlite3_create_collation(
 ** Register a new collation sequence with the database handle db.
 */
 SQLITE_API int sqlite3_create_collation_v2(
-  sqlite3* db, 
-  const char *zName, 
-  int enc, 
+  sqlite3* db,
+  const char *zName,
+  int enc,
   void* pCtx,
   int(*xCompare)(void*,int,const void*,int,const void*),
   void(*xDel)(void*)
@@ -159984,9 +165549,9 @@ SQLITE_API int sqlite3_create_collation_v2(
 ** Register a new collation sequence with the database handle db.
 */
 SQLITE_API int sqlite3_create_collation16(
-  sqlite3* db, 
+  sqlite3* db,
   const void *zName,
-  int enc, 
+  int enc,
   void* pCtx,
   int(*xCompare)(void*,int,const void*,int,const void*)
 ){
@@ -160014,8 +165579,8 @@ SQLITE_API int sqlite3_create_collation16(
 ** db. Replace any previously installed collation sequence factory.
 */
 SQLITE_API int sqlite3_collation_needed(
-  sqlite3 *db, 
-  void *pCollNeededArg, 
+  sqlite3 *db,
+  void *pCollNeededArg,
   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
 ){
 #ifdef SQLITE_ENABLE_API_ARMOR
@@ -160035,8 +165600,8 @@ SQLITE_API int sqlite3_collation_needed(
 ** db. Replace any previously installed collation sequence factory.
 */
 SQLITE_API int sqlite3_collation_needed16(
-  sqlite3 *db, 
-  void *pCollNeededArg, 
+  sqlite3 *db,
+  void *pCollNeededArg,
   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
 ){
 #ifdef SQLITE_ENABLE_API_ARMOR
@@ -160105,13 +165670,15 @@ SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
   testcase( sqlite3GlobalConfig.xLog!=0 );
   return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
 }
-#ifdef SQLITE_DEBUG
+#if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
 SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
   char zMsg[100];
   sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
   testcase( sqlite3GlobalConfig.xLog!=0 );
   return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
 }
+#endif
+#ifdef SQLITE_DEBUG
 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
   testcase( sqlite3GlobalConfig.xLog!=0 );
   return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
@@ -160206,13 +165773,13 @@ SQLITE_API int sqlite3_table_column_metadata(
   /* The following block stores the meta information that will be returned
   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
   ** and autoinc. At this point there are two possibilities:
-  ** 
-  **     1. The specified column name was rowid", "oid" or "_rowid_" 
-  **        and there is no explicitly declared IPK column. 
   **
-  **     2. The table is not a view and the column name identified an 
+  **     1. The specified column name was rowid", "oid" or "_rowid_"
+  **        and there is no explicitly declared IPK column.
+  **
+  **     2. The table is not a view and the column name identified an
   **        explicitly declared column. Copy meta information from *pCol.
-  */ 
+  */
   if( pCol ){
     zDataType = sqlite3ColumnType(pCol,0);
     zCollSeq = pCol->zColl;
@@ -160262,7 +165829,7 @@ SQLITE_API int sqlite3_sleep(int ms){
   pVfs = sqlite3_vfs_find(0);
   if( pVfs==0 ) return 0;
 
-  /* This function works in milliseconds, but the underlying OsSleep() 
+  /* This function works in milliseconds, but the underlying OsSleep()
   ** API uses microseconds. Hence the 1000's.
   */
   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
@@ -160314,8 +165881,17 @@ SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, vo
     }else if( op==SQLITE_FCNTL_DATA_VERSION ){
       *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
       rc = SQLITE_OK;
+    }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
+      int iNew = *(int*)pArg;
+      *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
+      if( iNew>=0 && iNew<=255 ){
+        sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
+      }
+      rc = SQLITE_OK;
     }else{
+      int nSave = db->busyHandler.nBusy;
       rc = sqlite3OsFileControl(fd, op, pArg);
+      db->busyHandler.nBusy = nSave;
     }
     sqlite3BtreeLeave(pBtree);
   }
@@ -160373,6 +165949,7 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     ** This test-control also resets the PRNG so that the new seed will
     ** be used for the next call to sqlite3_randomness().
     */
+#ifndef SQLITE_OMIT_WSD
     case SQLITE_TESTCTRL_PRNG_SEED: {
       int x = va_arg(ap, int);
       int y;
@@ -160383,6 +165960,7 @@ SQLITE_API int sqlite3_test_control(int op, ...){
       sqlite3_randomness(0,0);
       break;
     }
+#endif
 
     /*
     **  sqlite3_test_control(BITVEC_TEST, size, program)
@@ -160424,7 +166002,7 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     /*
     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
     **
-    ** Register hooks to call to indicate which malloc() failures 
+    ** Register hooks to call to indicate which malloc() failures
     ** are benign.
     */
     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
@@ -160522,29 +166100,15 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     **      10     little-endian, determined at run-time
     **  432101     big-endian,    determined at compile-time
     **  123410     little-endian, determined at compile-time
-    */ 
+    */
     case SQLITE_TESTCTRL_BYTEORDER: {
       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
       break;
     }
 
-    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
-    **
-    ** Set the nReserve size to N for the main database on the database
-    ** connection db.
-    */
-    case SQLITE_TESTCTRL_RESERVE: {
-      sqlite3 *db = va_arg(ap, sqlite3*);
-      int x = va_arg(ap,int);
-      sqlite3_mutex_enter(db->mutex);
-      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
-      sqlite3_mutex_leave(db->mutex);
-      break;
-    }
-
     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
     **
-    ** Enable or disable various optimizations for testing purposes.  The 
+    ** Enable or disable various optimizations for testing purposes.  The
     ** argument N is a bitmask of optimizations to be disabled.  For normal
     ** operation N should be 0.  The idea is that a test program (like the
     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
@@ -160569,15 +166133,14 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     }
 #endif
 
-    /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCS, int onoff);
+    /*   sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
     **
-    ** If parameter onoff is non-zero, internal-use-only SQL functions
-    ** are visible to ordinary SQL.  This is useful for testing but is
-    ** unsafe because invalid parameters to those internal-use-only functions
-    ** can result in crashes or segfaults.
+    ** Toggle the ability to use internal functions on or off for
+    ** the database connection given in the argument.
     */
     case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
-      sqlite3GlobalConfig.bInternalFunctions = va_arg(ap, int);
+      sqlite3 *db = va_arg(ap, sqlite3*);
+      db->mDbFlags ^= DBFLAG_InternalFunc;
       break;
     }
 
@@ -160597,8 +166160,14 @@ SQLITE_API int sqlite3_test_control(int op, ...){
     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
     **
     ** Set or clear a flag that causes SQLite to verify that type, name,
-    ** and tbl_name fields of the sqlite_master table.  This is normally
+    ** and tbl_name fields of the sqlite_schema table.  This is normally
     ** on, but it is sometimes useful to turn it off for testing.
+    **
+    ** 2020-07-22:  Disabling EXTRA_SCHEMA_CHECKS also disables the
+    ** verification of rootpage numbers when parsing the schema.  This
+    ** is useful to make it easier to reach strange internal error states
+    ** during testing.  The EXTRA_SCHEMA_CHECKS setting is always enabled
+    ** in production.
     */
     case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
       sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
@@ -160617,7 +166186,7 @@ SQLITE_API int sqlite3_test_control(int op, ...){
 
     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
     **
-    ** Set the VDBE coverage callback function to xCallback with context 
+    ** Set the VDBE coverage callback function to xCallback with context
     ** pointer ptr.
     */
     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
@@ -160707,6 +166276,44 @@ SQLITE_API int sqlite3_test_control(int op, ...){
       sqlite3ResultIntReal(pCtx);
       break;
     }
+
+    /*  sqlite3_test_control(SQLITE_TESTCTRL_SEEK_COUNT,
+    **    sqlite3 *db,    // Database connection
+    **    u64 *pnSeek     // Write seek count here
+    **  );
+    **
+    ** This test-control queries the seek-counter on the "main" database
+    ** file.  The seek-counter is written into *pnSeek and is then reset.
+    ** The seek-count is only available if compiled with SQLITE_DEBUG.
+    */
+    case SQLITE_TESTCTRL_SEEK_COUNT: {
+      sqlite3 *db = va_arg(ap, sqlite3*);
+      u64 *pn = va_arg(ap, sqlite3_uint64*);
+      *pn = sqlite3BtreeSeekCount(db->aDb->pBt);
+      (void)db;  /* Silence harmless unused variable warning */
+      break;
+    }
+
+    /*  sqlite3_test_control(SQLITE_TESTCTRL_TRACEFLAGS, op, ptr)
+    **
+    **  "ptr" is a pointer to a u32.
+    **
+    **   op==0       Store the current sqlite3SelectTrace in *ptr
+    **   op==1       Set sqlite3SelectTrace to the value *ptr
+    **   op==3       Store the current sqlite3WhereTrace in *ptr
+    **   op==3       Set sqlite3WhereTrace to the value *ptr
+    */
+    case SQLITE_TESTCTRL_TRACEFLAGS: {
+       int opTrace = va_arg(ap, int);
+       u32 *ptr = va_arg(ap, u32*);
+       switch( opTrace ){
+         case 0:   *ptr = sqlite3SelectTrace;      break;
+         case 1:   sqlite3SelectTrace = *ptr;      break;
+         case 2:   *ptr = sqlite3WhereTrace;       break;
+         case 3:   sqlite3WhereTrace = *ptr;       break;
+       }
+       break;
+    }
   }
   va_end(ap);
 #endif /* SQLITE_UNTESTABLE */
@@ -160714,8 +166321,85 @@ SQLITE_API int sqlite3_test_control(int op, ...){
 }
 
 /*
+** The Pager stores the Database filename, Journal filename, and WAL filename
+** consecutively in memory, in that order.  The database filename is prefixed
+** by four zero bytes.  Locate the start of the database filename by searching
+** backwards for the first byte following four consecutive zero bytes.
+**
+** This only works if the filename passed in was obtained from the Pager.
+*/
+static const char *databaseName(const char *zName){
+  while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
+    zName--;
+  }
+  return zName;
+}
+
+/*
+** Append text z[] to the end of p[].  Return a pointer to the first
+** character after then zero terminator on the new text in p[].
+*/
+static char *appendText(char *p, const char *z){
+  size_t n = strlen(z);
+  memcpy(p, z, n+1);
+  return p+n+1;
+}
+
+/*
+** Allocate memory to hold names for a database, journal file, WAL file,
+** and query parameters.  The pointer returned is valid for use by
+** sqlite3_filename_database() and sqlite3_uri_parameter() and related
+** functions.
+**
+** Memory layout must be compatible with that generated by the pager
+** and expected by sqlite3_uri_parameter() and databaseName().
+*/
+SQLITE_API char *sqlite3_create_filename(
+  const char *zDatabase,
+  const char *zJournal,
+  const char *zWal,
+  int nParam,
+  const char **azParam
+){
+  sqlite3_int64 nByte;
+  int i;
+  char *pResult, *p;
+  nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
+  for(i=0; i<nParam*2; i++){
+    nByte += strlen(azParam[i])+1;
+  }
+  pResult = p = sqlite3_malloc64( nByte );
+  if( p==0 ) return 0;
+  memset(p, 0, 4);
+  p += 4;
+  p = appendText(p, zDatabase);
+  for(i=0; i<nParam*2; i++){
+    p = appendText(p, azParam[i]);
+  }
+  *(p++) = 0;
+  p = appendText(p, zJournal);
+  p = appendText(p, zWal);
+  *(p++) = 0;
+  *(p++) = 0;
+  assert( (sqlite3_int64)(p - pResult)==nByte );
+  return pResult + 4;
+}
+
+/*
+** Free memory obtained from sqlite3_create_filename().  It is a severe
+** error to call this routine with any parameter other than a pointer
+** previously obtained from sqlite3_create_filename() or a NULL pointer.
+*/
+SQLITE_API void sqlite3_free_filename(char *p){
+  if( p==0 ) return;
+  p = (char*)databaseName(p);
+  sqlite3_free(p - 4);
+}
+
+
+/*
 ** This is a utility routine, useful to VFS implementations, that checks
-** to see if a database file was a URI that contained a specific query 
+** to see if a database file was a URI that contained a specific query
 ** parameter, and if so obtains the value of the query parameter.
 **
 ** The zFilename argument is the filename pointer passed into the xOpen()
@@ -160726,14 +166410,22 @@ SQLITE_API int sqlite3_test_control(int op, ...){
 */
 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
   if( zFilename==0 || zParam==0 ) return 0;
+  zFilename = databaseName(zFilename);
+  return uriParameter(zFilename, zParam);
+}
+
+/*
+** Return a pointer to the name of Nth query parameter of the filename.
+*/
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){
+  if( zFilename==0 || N<0 ) return 0;
+  zFilename = databaseName(zFilename);
   zFilename += sqlite3Strlen30(zFilename) + 1;
-  while( zFilename[0] ){
-    int x = strcmp(zFilename, zParam);
+  while( zFilename[0] && (N--)>0 ){
     zFilename += sqlite3Strlen30(zFilename) + 1;
-    if( x==0 ) return zFilename;
     zFilename += sqlite3Strlen30(zFilename) + 1;
   }
-  return 0;
+  return zFilename[0] ? zFilename : 0;
 }
 
 /*
@@ -160762,6 +166454,38 @@ SQLITE_API sqlite3_int64 sqlite3_uri_int64(
 }
 
 /*
+** Translate a filename that was handed to a VFS routine into the corresponding
+** database, journal, or WAL file.
+**
+** It is an error to pass this routine a filename string that was not
+** passed into the VFS from the SQLite core.  Doing so is similar to
+** passing free() a pointer that was not obtained from malloc() - it is
+** an error that we cannot easily detect but that will likely cause memory
+** corruption.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char *zFilename){
+  return databaseName(zFilename);
+}
+SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){
+  zFilename = databaseName(zFilename);
+  zFilename += sqlite3Strlen30(zFilename) + 1;
+  while( zFilename[0] ){
+    zFilename += sqlite3Strlen30(zFilename) + 1;
+    zFilename += sqlite3Strlen30(zFilename) + 1;
+  }
+  return zFilename + 1;
+}
+SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){
+#ifdef SQLITE_OMIT_WAL
+  return 0;
+#else
+  zFilename = sqlite3_filename_journal(zFilename);
+  zFilename += sqlite3Strlen30(zFilename) + 1;
+  return zFilename;
+#endif
+}
+
+/*
 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
 */
 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
@@ -160803,11 +166527,11 @@ SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
 
 #ifdef SQLITE_ENABLE_SNAPSHOT
 /*
-** Obtain a snapshot handle for the snapshot of database zDb currently 
+** Obtain a snapshot handle for the snapshot of database zDb currently
 ** being read by handle db.
 */
 SQLITE_API int sqlite3_snapshot_get(
-  sqlite3 *db, 
+  sqlite3 *db,
   const char *zDb,
   sqlite3_snapshot **ppSnapshot
 ){
@@ -160825,7 +166549,7 @@ SQLITE_API int sqlite3_snapshot_get(
     int iDb = sqlite3FindDbName(db, zDb);
     if( iDb==0 || iDb>1 ){
       Btree *pBt = db->aDb[iDb].pBt;
-      if( 0==sqlite3BtreeIsInTrans(pBt) ){
+      if( SQLITE_TXN_WRITE!=sqlite3BtreeTxnState(pBt) ){
         rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
         if( rc==SQLITE_OK ){
           rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
@@ -160843,8 +166567,8 @@ SQLITE_API int sqlite3_snapshot_get(
 ** Open a read-transaction on the snapshot idendified by pSnapshot.
 */
 SQLITE_API int sqlite3_snapshot_open(
-  sqlite3 *db, 
-  const char *zDb, 
+  sqlite3 *db,
+  const char *zDb,
   sqlite3_snapshot *pSnapshot
 ){
   int rc = SQLITE_ERROR;
@@ -160861,10 +166585,10 @@ SQLITE_API int sqlite3_snapshot_open(
     iDb = sqlite3FindDbName(db, zDb);
     if( iDb==0 || iDb>1 ){
       Btree *pBt = db->aDb[iDb].pBt;
-      if( sqlite3BtreeIsInTrans(pBt)==0 ){
+      if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_WRITE ){
         Pager *pPager = sqlite3BtreePager(pBt);
         int bUnlock = 0;
-        if( sqlite3BtreeIsInReadTrans(pBt) ){
+        if( sqlite3BtreeTxnState(pBt)!=SQLITE_TXN_NONE ){
           if( db->nVdbeActive==0 ){
             rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
             if( rc==SQLITE_OK ){
@@ -160913,7 +166637,7 @@ SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
   iDb = sqlite3FindDbName(db, zDb);
   if( iDb==0 || iDb>1 ){
     Btree *pBt = db->aDb[iDb].pBt;
-    if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
+    if( SQLITE_TXN_NONE==sqlite3BtreeTxnState(pBt) ){
       rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
       if( rc==SQLITE_OK ){
         rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
@@ -160946,7 +166670,7 @@ SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   int i, n;
   int nOpt;
   const char **azCompileOpt;
+
 #if SQLITE_ENABLE_API_ARMOR
   if( zOptName==0 ){
     (void)SQLITE_MISUSE_BKPT;
@@ -160959,7 +166683,7 @@ SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   n = sqlite3Strlen30(zOptName);
 
-  /* Since nOpt is normally in single digits, a linear search is 
+  /* Since nOpt is normally in single digits, a linear search is
   ** adequate. No need for a binary search. */
   for(i=0; i<nOpt; i++){
     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
@@ -161019,25 +166743,25 @@ SQLITE_API const char *sqlite3_compileoption_get(int N){
 */
 
 #define assertMutexHeld() \
-  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
+  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN)) )
 
 /*
 ** Head of a linked list of all sqlite3 objects created by this process
 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
-** is not NULL. This variable may only accessed while the STATIC_MASTER
+** is not NULL. This variable may only accessed while the STATIC_MAIN
 ** mutex is held.
 */
 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
 
 #ifndef NDEBUG
 /*
-** This function is a complex assert() that verifies the following 
+** This function is a complex assert() that verifies the following
 ** properties of the blocked connections list:
 **
-**   1) Each entry in the list has a non-NULL value for either 
+**   1) Each entry in the list has a non-NULL value for either
 **      pUnlockConnection or pBlockingConnection, or both.
 **
-**   2) All entries in the list that share a common value for 
+**   2) All entries in the list that share a common value for
 **      xUnlockNotify are grouped together.
 **
 **   3) If the argument db is not NULL, then none of the entries in the
@@ -161089,8 +166813,8 @@ static void addToBlockedList(sqlite3 *db){
   sqlite3 **pp;
   assertMutexHeld();
   for(
-    pp=&sqlite3BlockedList; 
-    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
+    pp=&sqlite3BlockedList;
+    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
     pp=&(*pp)->pNextBlocked
   );
   db->pNextBlocked = *pp;
@@ -161098,20 +166822,20 @@ static void addToBlockedList(sqlite3 *db){
 }
 
 /*
-** Obtain the STATIC_MASTER mutex.
+** Obtain the STATIC_MAIN mutex.
 */
 static void enterMutex(void){
-  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
+  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
   checkListProperties(0);
 }
 
 /*
-** Release the STATIC_MASTER mutex.
+** Release the STATIC_MAIN mutex.
 */
 static void leaveMutex(void){
   assertMutexHeld();
   checkListProperties(0);
-  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
+  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN));
 }
 
 /*
@@ -161152,9 +166876,9 @@ SQLITE_API int sqlite3_unlock_notify(
     db->xUnlockNotify = 0;
     db->pUnlockArg = 0;
   }else if( 0==db->pBlockingConnection ){
-    /* The blocking transaction has been concluded. Or there never was a 
+    /* The blocking transaction has been concluded. Or there never was a
     ** blocking transaction. In either case, invoke the notify callback
-    ** immediately. 
+    ** immediately.
     */
     xNotify(&pArg, 1);
   }else{
@@ -161180,7 +166904,7 @@ SQLITE_API int sqlite3_unlock_notify(
 }
 
 /*
-** This function is called while stepping or preparing a statement 
+** This function is called while stepping or preparing a statement
 ** associated with connection db. The operation will return SQLITE_LOCKED
 ** to the user because it requires a lock that will not be available
 ** until connection pBlocker concludes its current transaction.
@@ -161196,7 +166920,7 @@ SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
 
 /*
 ** This function is called when
-** the transaction opened by database db has just finished. Locks held 
+** the transaction opened by database db has just finished. Locks held
 ** by database connection db have been released.
 **
 ** This function loops through each entry in the blocked connections
@@ -161222,7 +166946,7 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
 
   aArg = aStatic;
-  enterMutex();         /* Enter STATIC_MASTER mutex */
+  enterMutex();         /* Enter STATIC_MAIN mutex */
 
   /* This loop runs once for each entry in the blocked-connections list. */
   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
@@ -161256,7 +166980,7 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
         }else{
           /* This occurs when the array of context pointers that need to
           ** be passed to the unlock-notify callback is larger than the
-          ** aStatic[] array allocated on the stack and the attempt to 
+          ** aStatic[] array allocated on the stack and the attempt to
           ** allocate a larger array from the heap has failed.
           **
           ** This is a difficult situation to handle. Returning an error
@@ -161264,17 +166988,17 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
           ** is returned the transaction on connection db will still be
           ** closed and the unlock-notify callbacks on blocked connections
           ** will go unissued. This might cause the application to wait
-          ** indefinitely for an unlock-notify callback that will never 
+          ** indefinitely for an unlock-notify callback that will never
           ** arrive.
           **
           ** Instead, invoke the unlock-notify callback with the context
           ** array already accumulated. We can then clear the array and
-          ** begin accumulating any further context pointers without 
+          ** begin accumulating any further context pointers without
           ** requiring any dynamic allocation. This is sub-optimal because
           ** it means that instead of one callback with a large array of
           ** context pointers the application will receive two or more
           ** callbacks with smaller arrays of context pointers, which will
-          ** reduce the applications ability to prioritize multiple 
+          ** reduce the applications ability to prioritize multiple
           ** connections. But it is the best that can be done under the
           ** circumstances.
           */
@@ -161305,11 +167029,11 @@ SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
     xUnlockNotify(aArg, nArg);
   }
   sqlite3_free(aDyn);
-  leaveMutex();         /* Leave STATIC_MASTER mutex */
+  leaveMutex();         /* Leave STATIC_MAIN mutex */
 }
 
 /*
-** This is called when the database connection passed as an argument is 
+** This is called when the database connection passed as an argument is
 ** being closed. The connection is removed from the blocked list.
 */
 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
@@ -161386,7 +167110,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
 ** A doclist (document list) holds a docid-sorted list of hits for a
 ** given term.  Doclists hold docids and associated token positions.
 ** A docid is the unique integer identifier for a single document.
-** A position is the index of a word within the document.  The first 
+** A position is the index of a word within the document.  The first
 ** word of the document has a position of 0.
 **
 ** FTS3 used to optionally store character offsets using a compile-time
@@ -161411,7 +167135,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
 **
 ** Here, array { X } means zero or more occurrences of X, adjacent in
 ** memory.  A "position" is an index of a token in the token stream
-** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
+** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
 ** in the same logical place as the position element, and act as sentinals
 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
 ** The positions numbers are not stored literally but rather as two more
@@ -161435,7 +167159,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
 ** a document record consists of a docid followed by a position-list and
 ** a doclist consists of one or more document records.
 **
-** A bare doclist omits the position information, becoming an 
+** A bare doclist omits the position information, becoming an
 ** array of varint-encoded docids.
 **
 **** Segment leaf nodes ****
@@ -161631,7 +167355,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
 #ifndef _FTSINT_H
 #define _FTSINT_H
 
-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 # define NDEBUG 1
 #endif
 
@@ -161654,7 +167378,7 @@ SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
 
 /* If not building as part of the core, include sqlite3ext.h. */
 #ifndef SQLITE_CORE
-/* # include "sqlite3ext.h"  */
+/* # include "sqlite3ext.h" */
 SQLITE_EXTENSION_INIT3
 #endif
 
@@ -161698,7 +167422,7 @@ SQLITE_EXTENSION_INIT3
 ** When an fts3 table is created, it passes any arguments passed to
 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
-** implementation. The xCreate() function in turn returns an 
+** implementation. The xCreate() function in turn returns an
 ** sqlite3_tokenizer structure representing the specific tokenizer to
 ** be used for the fts3 table (customized by the tokenizer clause arguments).
 **
@@ -161730,7 +167454,7 @@ struct sqlite3_tokenizer_module {
   ** then argc is set to 2, and the argv[] array contains pointers
   ** to the strings "arg1" and "arg2".
   **
-  ** This method should return either SQLITE_OK (0), or an SQLite error 
+  ** This method should return either SQLITE_OK (0), or an SQLite error
   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
   ** to point at the newly created tokenizer structure. The generic
   ** sqlite3_tokenizer.pModule variable should not be initialized by
@@ -161751,7 +167475,7 @@ struct sqlite3_tokenizer_module {
   /*
   ** Create a tokenizer cursor to tokenize an input buffer. The caller
   ** is responsible for ensuring that the input buffer remains valid
-  ** until the cursor is closed (using the xClose() method). 
+  ** until the cursor is closed (using the xClose() method).
   */
   int (*xOpen)(
     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
@@ -161760,7 +167484,7 @@ struct sqlite3_tokenizer_module {
   );
 
   /*
-  ** Destroy an existing tokenizer cursor. The fts3 module calls this 
+  ** Destroy an existing tokenizer cursor. The fts3 module calls this
   ** method exactly once for each successful call to xOpen().
   */
   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
@@ -161771,7 +167495,7 @@ struct sqlite3_tokenizer_module {
   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
   ** the end of the buffer has been reached, or an SQLite error code.
   **
-  ** *ppToken should be set to point at a buffer containing the 
+  ** *ppToken should be set to point at a buffer containing the
   ** normalized version of the token (i.e. after any case-folding and/or
   ** stemming has been performed). *pnBytes should be set to the length
   ** of this buffer in bytes. The input text that generated the token is
@@ -161783,7 +167507,7 @@ struct sqlite3_tokenizer_module {
   **
   ** The buffer *ppToken is set to point at is managed by the tokenizer
   ** implementation. It is only required to be valid until the next call
-  ** to xNext() or xClose(). 
+  ** to xNext() or xClose().
   */
   /* TODO(shess) current implementation requires pInput to be
   ** nul-terminated.  This should either be fixed, or pInput/nBytes
@@ -161801,7 +167525,7 @@ struct sqlite3_tokenizer_module {
   ** Methods below this point are only available if iVersion>=1.
   */
 
-  /* 
+  /*
   ** Configure the language id of a tokenizer cursor.
   */
   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
@@ -161870,7 +167594,7 @@ struct Fts3Hash {
   } *ht;
 };
 
-/* Each element in the hash table is an instance of the following 
+/* Each element in the hash table is an instance of the following
 ** structure.  All elements are stored on a single doubly-linked list.
 **
 ** Again, this structure is intended to be opaque, but it can't really
@@ -161889,10 +167613,10 @@ struct Fts3HashElem {
 **                           (including the null-terminator, if any).  Case
 **                           is respected in comparisons.
 **
-**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
+**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
 **                           memcmp() is used to compare keys.
 **
-** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
+** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
 */
 #define FTS3_HASH_STRING    1
 #define FTS3_HASH_BINARY    2
@@ -161945,7 +167669,7 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 
 /*
 ** This constant determines the maximum depth of an FTS expression tree
-** that the library will create and use. FTS uses recursion to perform 
+** that the library will create and use. FTS uses recursion to perform
 ** various operations on the query tree, so the disadvantage of a large
 ** limit is that it may allow very large queries to use large amounts
 ** of stack space (perhaps causing a stack overflow).
@@ -161963,11 +167687,11 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 #define FTS3_MERGE_COUNT 16
 
 /*
-** This is the maximum amount of data (in bytes) to store in the 
+** This is the maximum amount of data (in bytes) to store in the
 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
 ** populated as documents are inserted/updated/deleted in a transaction
 ** and used to create a new segment when the transaction is committed.
-** However if this limit is reached midway through a transaction, a new 
+** However if this limit is reached midway through a transaction, a new
 ** segment is created and the hash table cleared immediately.
 */
 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
@@ -161998,7 +167722,7 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 /*
 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
 ** in the document set and zero or more prefix indexes. All indexes are stored
-** as one or more b+-trees in the %_segments and %_segdir tables. 
+** as one or more b+-trees in the %_segments and %_segdir tables.
 **
 ** It is possible to determine which index a b+-tree belongs to based on the
 ** value stored in the "%_segdir.level" column. Given this value L, the index
@@ -162006,8 +167730,8 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
 ** between 1024 and 2047 to index 1, and so on.
 **
-** It is considered impossible for an index to use more than 1024 levels. In 
-** theory though this may happen, but only after at least 
+** It is considered impossible for an index to use more than 1024 levels. In
+** theory though this may happen, but only after at least
 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
 */
 #define FTS3_SEGDIR_MAXLEVEL      1024
@@ -162025,11 +167749,11 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const voi
 ** Terminator values for position-lists and column-lists.
 */
 #define POS_COLUMN  (1)     /* Column-list terminator */
-#define POS_END     (0)     /* Position-list terminator */ 
+#define POS_END     (0)     /* Position-list terminator */
 
 /*
 ** The assert_fts3_nc() macro is similar to the assert() macro, except that it
-** is used for assert() conditions that are true only if it can be 
+** is used for assert() conditions that are true only if it can be
 ** guranteed that the database is not corrupt.
 */
 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
@@ -162041,7 +167765,7 @@ SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
 
 /*
 ** This section provides definitions to allow the
-** FTS3 extension to be compiled outside of the 
+** FTS3 extension to be compiled outside of the
 ** amalgamation.
 */
 #ifndef SQLITE_AMALGAMATION
@@ -162079,7 +167803,7 @@ typedef sqlite3_int64 i64;        /* 8-byte signed integer */
 /*
 ** Activate assert() only if SQLITE_TEST is enabled.
 */
-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 # define NDEBUG 1
 #endif
 
@@ -162094,6 +167818,11 @@ typedef sqlite3_int64 i64;        /* 8-byte signed integer */
 # define TESTONLY(X)
 #endif
 
+#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
+#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
+
+#define deliberate_fall_through
+
 #endif /* SQLITE_AMALGAMATION */
 
 #ifdef SQLITE_DEBUG
@@ -162137,9 +167866,10 @@ struct Fts3Table {
   char *zLanguageid;              /* languageid=xxx option, or NULL */
   int nAutoincrmerge;             /* Value configured by 'automerge' */
   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
+  int bLock;                      /* Used to prevent recursive content= tbls */
 
-  /* Precompiled statements used by the implementation. Each of these 
-  ** statements is run and reset within a single virtual table API call. 
+  /* Precompiled statements used by the implementation. Each of these
+  ** statements is run and reset within a single virtual table API call.
   */
   sqlite3_stmt *aStmt[40];
   sqlite3_stmt *pSeekStmt;        /* Cache for fts3CursorSeekStmt() */
@@ -162157,8 +167887,8 @@ struct Fts3Table {
   char *zSegmentsTbl;             /* Name of %_segments table */
   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
 
-  /* 
-  ** The following array of hash tables is used to buffer pending index 
+  /*
+  ** The following array of hash tables is used to buffer pending index
   ** updates during transactions. All pending updates buffered at any one
   ** time must share a common language-id (see the FTS4 langid= feature).
   ** The current language id is stored in variable iPrevLangid.
@@ -162168,10 +167898,10 @@ struct Fts3Table {
   ** terms that appear in the document set. Each subsequent index in aIndex[]
   ** is an index of prefixes of a specific length.
   **
-  ** Variable nPendingData contains an estimate the memory consumed by the 
+  ** Variable nPendingData contains an estimate the memory consumed by the
   ** pending data structures, including hash table overhead, but not including
   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
-  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
+  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
   ** recently inserted record.
   */
   int nIndex;                     /* Size of aIndex[] */
@@ -162195,13 +167925,23 @@ struct Fts3Table {
   int mxSavepoint;       /* Largest valid xSavepoint integer */
 #endif
 
-#ifdef SQLITE_TEST
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   /* True to disable the incremental doclist optimization. This is controled
   ** by special insert command 'test-no-incr-doclist'.  */
   int bNoIncrDoclist;
+
+  /* Number of segments in a level */
+  int nMergeCount;
 #endif
 };
 
+/* Macro to find the number of segments to merge */
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
+# define MergeCount(P) ((P)->nMergeCount)
+#else
+# define MergeCount(P) FTS3_MERGE_COUNT
+#endif
+
 /*
 ** When the core wants to read from the virtual table, it creates a
 ** virtual table cursor (an instance of the following structure) using
@@ -162244,10 +167984,10 @@ struct Fts3Cursor {
 **
 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
-** 
+**
 ** Because the LHS of the MATCH operator is 2nd column "b",
 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
-** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
+** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
 ** indicating that all columns should be searched,
 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
 */
@@ -162306,8 +168046,8 @@ struct Fts3Phrase {
   char *pOrPoslist;
   i64 iOrDocid;
 
-  /* Variables below this point are populated by fts3_expr.c when parsing 
-  ** a MATCH expression. Everything above is part of the evaluation phase. 
+  /* Variables below this point are populated by fts3_expr.c when parsing
+  ** a MATCH expression. Everything above is part of the evaluation phase.
   */
   int nToken;                /* Number of tokens in the phrase */
   int iColumn;               /* Index of column this phrase must match */
@@ -162317,10 +168057,10 @@ struct Fts3Phrase {
 /*
 ** A tree of these objects forms the RHS of a MATCH operator.
 **
-** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
-** points to a malloced buffer, size nDoclist bytes, containing the results 
-** of this phrase query in FTS3 doclist format. As usual, the initial 
-** "Length" field found in doclists stored on disk is omitted from this 
+** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
+** points to a malloced buffer, size nDoclist bytes, containing the results
+** of this phrase query in FTS3 doclist format. As usual, the initial
+** "Length" field found in doclists stored on disk is omitted from this
 ** buffer.
 **
 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
@@ -162332,7 +168072,7 @@ struct Fts3Phrase {
 **   aMI[iCol*3 + 1] = Number of occurrences
 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
 **
-** The aMI array is allocated using sqlite3_malloc(). It should be freed 
+** The aMI array is allocated using sqlite3_malloc(). It should be freed
 ** when the expression node is.
 */
 struct Fts3Expr {
@@ -162356,7 +168096,7 @@ struct Fts3Expr {
 
 /*
 ** Candidate values for Fts3Query.eType. Note that the order of the first
-** four values is in order of precedence when parsing expressions. For 
+** four values is in order of precedence when parsing expressions. For
 ** example, the following:
 **
 **   "a OR b AND c NOT d NEAR e"
@@ -162413,7 +168153,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Ft
 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
 
-SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
+SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
 
 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
@@ -162465,6 +168205,8 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
+SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *);
+SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*);
 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
@@ -162473,11 +168215,12 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
+SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
 
 /* fts3_tokenizer.c */
 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
-SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
+SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
     sqlite3_tokenizer **, char **
 );
 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
@@ -162513,7 +168256,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
-SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
+SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
 
@@ -162548,23 +168291,11 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
 /* #include <stdarg.h> */
 
 /* #include "fts3.h" */
-#ifndef SQLITE_CORE 
+#ifndef SQLITE_CORE
 /* # include "sqlite3ext.h" */
   SQLITE_EXTENSION_INIT1
 #endif
 
-/*
-** The following are copied from sqliteInt.h.
-**
-** Constants for the largest and smallest possible 64-bit signed integers.
-** These macros are designed to work correctly on both 32-bit and 64-bit
-** compilers.
-*/
-#ifndef SQLITE_AMALGAMATION
-# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
-# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
-#endif
-
 static int fts3EvalNext(Fts3Cursor *pCsr);
 static int fts3EvalStart(Fts3Cursor *pCsr);
 static int fts3TermSegReaderCursor(
@@ -162587,7 +168318,7 @@ SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
 SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
 #endif
 
-/* 
+/*
 ** Write a 64-bit variable-length integer to memory starting at p[0].
 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
 ** The number of bytes written is returned.
@@ -162611,12 +168342,7 @@ SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
   v = (*ptr++);                                               \
   if( (v & mask2)==0 ){ var = v; return ret; }
 
-/* 
-** Read a 64-bit variable-length integer from memory starting at p[0].
-** Return the number of bytes read, or 0 on error.
-** The value is stored in *v.
-*/
-SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
+SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){
   const unsigned char *p = (const unsigned char*)pBuf;
   const unsigned char *pStart = p;
   u32 a;
@@ -162639,7 +168365,42 @@ SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
 }
 
 /*
-** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to 
+** Read a 64-bit variable-length integer from memory starting at p[0].
+** Return the number of bytes read, or 0 on error.
+** The value is stored in *v.
+*/
+SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
+  return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
+}
+
+/*
+** Read a 64-bit variable-length integer from memory starting at p[0] and
+** not extending past pEnd[-1].
+** Return the number of bytes read, or 0 on error.
+** The value is stored in *v.
+*/
+SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(
+  const char *pBuf,
+  const char *pEnd,
+  sqlite_int64 *v
+){
+  const unsigned char *p = (const unsigned char*)pBuf;
+  const unsigned char *pStart = p;
+  const unsigned char *pX = (const unsigned char*)pEnd;
+  u64 b = 0;
+  int shift;
+  for(shift=0; shift<=63; shift+=7){
+    u64 c = p<pX ? *p : 0;
+    p++;
+    b += (c&0x7F) << shift;
+    if( (c & 0x80)==0 ) break;
+  }
+  *v = b;
+  return (int)(p - pStart);
+}
+
+/*
+** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
 ** a non-negative 32-bit integer before it is returned.
 */
 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
@@ -162698,7 +168459,7 @@ SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
     int iOut = 0;                 /* Index of next byte to write to output */
 
     /* If the first byte was a '[', then the close-quote character is a ']' */
-    if( quote=='[' ) quote = ']';  
+    if( quote=='[' ) quote = ']';
 
     while( z[iIn] ){
       if( z[iIn]==quote ){
@@ -162734,14 +168495,14 @@ static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
 ** varint is part of.
 */
 static void fts3GetReverseVarint(
-  char **pp, 
-  char *pStart, 
+  char **pp,
+  char *pStart,
   sqlite3_int64 *pVal
 ){
   sqlite3_int64 iVal;
   char *p;
 
-  /* Pointer p now points at the first byte past the varint we are 
+  /* Pointer p now points at the first byte past the varint we are
   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
   ** clear on character p[-1]. */
   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
@@ -162828,7 +168589,7 @@ static int fts3DestroyMethod(sqlite3_vtab *pVtab){
   sqlite3 *db = p->db;             /* Database handle */
 
   /* Drop the shadow tables */
-  fts3DbExec(&rc, db, 
+  fts3DbExec(&rc, db,
     "DROP TABLE IF EXISTS %Q.'%q_segments';"
     "DROP TABLE IF EXISTS %Q.'%q_segdir';"
     "DROP TABLE IF EXISTS %Q.'%q_docsize';"
@@ -162854,7 +168615,7 @@ static int fts3DestroyMethod(sqlite3_vtab *pVtab){
 ** passed as the first argument. This is done as part of the xConnect()
 ** and xCreate() methods.
 **
-** If *pRc is non-zero when this function is called, it is a no-op. 
+** If *pRc is non-zero when this function is called, it is a no-op.
 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
 ** before returning.
 */
@@ -162877,7 +168638,7 @@ static void fts3DeclareVtab(int *pRc, Fts3Table *p){
 
     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
     zSql = sqlite3_mprintf(
-        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
+        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
         zCols, p->zName, zLanguageid
     );
     if( !zCols || !zSql ){
@@ -162896,7 +168657,7 @@ static void fts3DeclareVtab(int *pRc, Fts3Table *p){
 ** Create the %_stat table if it does not already exist.
 */
 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
-  fts3DbExec(pRc, p->db, 
+  fts3DbExec(pRc, p->db,
       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
           "(id INTEGER PRIMARY KEY, value BLOB);",
       p->zDb, p->zName
@@ -162932,9 +168693,9 @@ static int fts3CreateTables(Fts3Table *p){
       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
     }
     if( zContentCols==0 ) rc = SQLITE_NOMEM;
-  
+
     /* Create the content table */
-    fts3DbExec(&rc, db, 
+    fts3DbExec(&rc, db,
        "CREATE TABLE %Q.'%q_content'(%s)",
        p->zDb, p->zName, zContentCols
     );
@@ -162942,11 +168703,11 @@ static int fts3CreateTables(Fts3Table *p){
   }
 
   /* Create other tables */
-  fts3DbExec(&rc, db, 
+  fts3DbExec(&rc, db,
       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
       p->zDb, p->zName
   );
-  fts3DbExec(&rc, db, 
+  fts3DbExec(&rc, db,
       "CREATE TABLE %Q.'%q_segdir'("
         "level INTEGER,"
         "idx INTEGER,"
@@ -162959,7 +168720,7 @@ static int fts3CreateTables(Fts3Table *p){
       p->zDb, p->zName
   );
   if( p->bHasDocsize ){
-    fts3DbExec(&rc, db, 
+    fts3DbExec(&rc, db,
         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
         p->zDb, p->zName
     );
@@ -162974,7 +168735,7 @@ static int fts3CreateTables(Fts3Table *p){
 /*
 ** Store the current database page-size in bytes in p->nPgsz.
 **
-** If *pRc is non-zero when this function is called, it is a no-op. 
+** If *pRc is non-zero when this function is called, it is a no-op.
 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
 ** before returning.
 */
@@ -162983,7 +168744,7 @@ static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
     int rc;                       /* Return code */
     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
-  
+
     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
     if( !zSql ){
       rc = SQLITE_NOMEM;
@@ -163009,11 +168770,11 @@ static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
 **
 **   <key> = <value>
 **
-** There may not be whitespace surrounding the "=" character. The <value> 
+** There may not be whitespace surrounding the "=" character. The <value>
 ** term may be quoted, but the <key> may not.
 */
 static int fts3IsSpecialColumn(
-  const char *z, 
+  const char *z,
   int *pnKey,
   char **pzValue
 ){
@@ -163090,7 +168851,7 @@ static char *fts3QuoteId(char const *zInput){
 }
 
 /*
-** Return a list of comma separated SQL expressions and a FROM clause that 
+** Return a list of comma separated SQL expressions and a FROM clause that
 ** could be used in a SELECT statement such as the following:
 **
 **     SELECT <list of expressions> FROM %_content AS x ...
@@ -163141,7 +168902,7 @@ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
     }
   }
-  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
+  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
       p->zDb,
       (p->zContentTbl ? p->zContentTbl : p->zName),
       (p->zContentTbl ? "" : "_content")
@@ -163156,7 +168917,7 @@ static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
 **
 ** If argument zFunc is not NULL, then all but the first question mark
 ** is preceded by zFunc and an open bracket, and followed by a closed
-** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
+** bracket. For example, if zFunc is "zip" and the FTS3 table has three
 ** user-defined text columns, the following string is returned:
 **
 **     "?, zip(?), zip(?), zip(?)"
@@ -163192,12 +168953,28 @@ static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
 }
 
 /*
+** Buffer z contains a positive integer value encoded as utf-8 text.
+** Decode this value and store it in *pnOut, returning the number of bytes
+** consumed. If an overflow error occurs return a negative value.
+*/
+SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){
+  u64 iVal = 0;
+  int i;
+  for(i=0; z[i]>='0' && z[i]<='9'; i++){
+    iVal = iVal*10 + (z[i] - '0');
+    if( iVal>0x7FFFFFFF ) return -1;
+  }
+  *pnOut = (int)iVal;
+  return i;
+}
+
+/*
 ** This function interprets the string at (*pp) as a non-negative integer
-** value. It reads the integer and sets *pnOut to the value read, then 
+** value. It reads the integer and sets *pnOut to the value read, then
 ** sets *pp to point to the byte immediately following the last byte of
 ** the integer value.
 **
-** Only decimal digits ('0'..'9') may be part of an integer value. 
+** Only decimal digits ('0'..'9') may be part of an integer value.
 **
 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
 ** the output value undefined. Otherwise SQLITE_OK is returned.
@@ -163206,19 +168983,17 @@ static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
 */
 static int fts3GobbleInt(const char **pp, int *pnOut){
   const int MAX_NPREFIX = 10000000;
-  const char *p;                  /* Iterator pointer */
   int nInt = 0;                   /* Output value */
-
-  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
-    nInt = nInt * 10 + (p[0] - '0');
-    if( nInt>MAX_NPREFIX ){
-      nInt = 0;
-      break;
-    }
+  int nByte;
+  nByte = sqlite3Fts3ReadInt(*pp, &nInt);
+  if( nInt>MAX_NPREFIX ){
+    nInt = 0;
+  }
+  if( nByte==0 ){
+    return SQLITE_ERROR;
   }
-  if( p==*pp ) return SQLITE_ERROR;
   *pnOut = nInt;
-  *pp = p;
+  *pp += nByte;
   return SQLITE_OK;
 }
 
@@ -163318,7 +169093,7 @@ static int fts3ContentColumns(
   char **pzErr                    /* OUT: error message */
 ){
   int rc = SQLITE_OK;             /* Return code */
-  char *zSql;                     /* "SELECT *" statement on zTbl */  
+  char *zSql;                     /* "SELECT *" statement on zTbl */
   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
 
   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
@@ -163460,9 +169235,9 @@ static int fts3InitVtab(
     char *zVal;
 
     /* Check if this is a tokenizer specification */
-    if( !pTokenizer 
+    if( !pTokenizer
      && strlen(z)>8
-     && 0==sqlite3_strnicmp(z, "tokenize", 8) 
+     && 0==sqlite3_strnicmp(z, "tokenize", 8)
      && 0==sqlite3Fts3IsIdChar(z[8])
     ){
       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
@@ -163522,8 +169297,8 @@ static int fts3InitVtab(
             break;
 
           case 4:               /* ORDER */
-            if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
-             && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
+            if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
+             && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
             ){
               sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
               rc = SQLITE_ERROR;
@@ -163574,17 +169349,17 @@ static int fts3InitVtab(
   **      TABLE statement, use all columns from the content table.
   */
   if( rc==SQLITE_OK && zContent ){
-    sqlite3_free(zCompress); 
-    sqlite3_free(zUncompress); 
+    sqlite3_free(zCompress);
+    sqlite3_free(zUncompress);
     zCompress = 0;
     zUncompress = 0;
     if( nCol==0 ){
-      sqlite3_free((void*)aCol); 
+      sqlite3_free((void*)aCol);
       aCol = 0;
       rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
 
       /* If a languageid= option was specified, remove the language id
-      ** column from the aCol[] array. */ 
+      ** column from the aCol[] array. */
       if( rc==SQLITE_OK && zLanguageid ){
         int j;
         for(j=0; j<nCol; j++){
@@ -163671,7 +169446,7 @@ static int fts3InitVtab(
 
   /* Fill in the azColumn array */
   for(iCol=0; iCol<nCol; iCol++){
-    char *z; 
+    char *z;
     int n = 0;
     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
     if( n>0 ){
@@ -163690,7 +169465,7 @@ static int fts3InitVtab(
     for(i=0; i<nNotindexed; i++){
       char *zNot = azNotindexed[i];
       if( zNot && n==(int)strlen(zNot)
-       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) 
+       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
       ){
         p->abNotindexed[iCol] = 1;
         sqlite3_free(zNot);
@@ -163714,7 +169489,7 @@ static int fts3InitVtab(
   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
   if( rc!=SQLITE_OK ) goto fts3_init_out;
 
-  /* If this is an xCreate call, create the underlying tables in the 
+  /* If this is an xCreate call, create the underlying tables in the
   ** database. TODO: For xConnect(), it could verify that said tables exist.
   */
   if( isCreate ){
@@ -163733,6 +169508,10 @@ static int fts3InitVtab(
   fts3DatabasePageSize(&rc, p);
   p->nNodeSize = p->nPgsz-35;
 
+#if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
+  p->nMergeCount = FTS3_MERGE_COUNT;
+#endif
+
   /* Declare the table schema to SQLite. */
   fts3DeclareVtab(&rc, p);
 
@@ -163810,11 +169589,11 @@ static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
 #endif
 }
 
-/* 
+/*
 ** Implementation of the xBestIndex method for FTS3 tables. There
 ** are three possible strategies, in order of preference:
 **
-**   1. Direct lookup by rowid or docid. 
+**   1. Direct lookup by rowid or docid.
 **   2. Full-text search using a MATCH operator on a non-docid column.
 **   3. Linear scan of %_content table.
 */
@@ -163828,8 +169607,12 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
   int iIdx;
 
+  if( p->bLock ){
+    return SQLITE_ERROR;
+  }
+
   /* By default use a full table scan. This is an expensive option,
-  ** so search through the constraints to see if a more efficient 
+  ** so search through the constraints to see if a more efficient
   ** strategy is possible.
   */
   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
@@ -163865,12 +169648,12 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
     **
     ** If there is more than one MATCH constraint available, use the first
     ** one encountered. If there is both a MATCH constraint and a direct
-    ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
+    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
     ** though the rowid/docid lookup is faster than a MATCH query, selecting
-    ** it would lead to an "unable to use function MATCH in the requested 
+    ** it would lead to an "unable to use function MATCH in the requested
     ** context" error.
     */
-    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
+    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
     ){
       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
@@ -163879,7 +169662,7 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
     }
 
     /* Equality constraint on the langid column */
-    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
+    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
      && pCons->iColumn==p->nColumn + 2
     ){
       iLangidCons = i;
@@ -163907,22 +169690,22 @@ static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
   if( iCons>=0 ){
     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
     pInfo->aConstraintUsage[iCons].omit = 1;
-  } 
+  }
   if( iLangidCons>=0 ){
     pInfo->idxNum |= FTS3_HAVE_LANGID;
     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
-  } 
+  }
   if( iDocidGe>=0 ){
     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
-  } 
+  }
   if( iDocidLe>=0 ){
     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
-  } 
+  }
 
   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
-  ** docid) order. Both ascending and descending are possible. 
+  ** docid) order. Both ascending and descending are possible.
   */
   if( pInfo->nOrderBy==1 ){
     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
@@ -163949,7 +169732,7 @@ static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
   UNUSED_PARAMETER(pVTab);
 
   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
-  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
+  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
   ** if the allocation fails, return SQLITE_NOMEM.
   */
   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
@@ -164026,7 +169809,11 @@ static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
     }else{
       zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
       if( !zSql ) return SQLITE_NOMEM;
-      rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
+      p->bLock++;
+      rc = sqlite3_prepare_v3(
+          p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
+      );
+      p->bLock--;
       sqlite3_free(zSql);
     }
     if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
@@ -164037,18 +169824,22 @@ static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
 /*
 ** Position the pCsr->pStmt statement so that it is on the row
 ** of the %_content table that contains the last match.  Return
-** SQLITE_OK on success.  
+** SQLITE_OK on success.
 */
 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
   int rc = SQLITE_OK;
   if( pCsr->isRequireSeek ){
     rc = fts3CursorSeekStmt(pCsr);
     if( rc==SQLITE_OK ){
+      Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
+      pTab->bLock++;
       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
       pCsr->isRequireSeek = 0;
       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
+        pTab->bLock--;
         return SQLITE_OK;
       }else{
+        pTab->bLock--;
         rc = sqlite3_reset(pCsr->pStmt);
         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
           /* If no row was found and no error has occurred, then the %_content
@@ -164069,7 +169860,7 @@ static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
 
 /*
 ** This function is used to process a single interior node when searching
-** a b-tree for a term or term prefix. The node data is passed to this 
+** a b-tree for a term or term prefix. The node data is passed to this
 ** function via the zNode/nNode parameters. The term to search for is
 ** passed in zTerm/nTerm.
 **
@@ -164097,10 +169888,11 @@ static int fts3ScanInteriorNode(
   i64 nAlloc = 0;                 /* Size of allocated buffer */
   int isFirstTerm = 1;            /* True when processing first term on page */
   sqlite3_int64 iChild;           /* Block id of child node to descend to */
+  int nBuffer = 0;                /* Total term size */
 
-  /* Skip over the 'height' varint that occurs at the start of every 
+  /* Skip over the 'height' varint that occurs at the start of every
   ** interior node. Then load the blockid of the left-child of the b-tree
-  ** node into variable iChild.  
+  ** node into variable iChild.
   **
   ** Even if the data structure on disk is corrupted, this (reading two
   ** varints from the buffer) does not risk an overread. If zNode is a
@@ -164116,21 +169908,24 @@ static int fts3ScanInteriorNode(
   if( zCsr>zEnd ){
     return FTS_CORRUPT_VTAB;
   }
-  
+
   while( zCsr<zEnd && (piFirst || piLast) ){
     int cmp;                      /* memcmp() result */
     int nSuffix;                  /* Size of term suffix */
     int nPrefix = 0;              /* Size of term prefix */
-    int nBuffer;                  /* Total term size */
-  
+
     /* Load the next term on the node into zBuffer. Use realloc() to expand
     ** the size of zBuffer if required.  */
     if( !isFirstTerm ){
       zCsr += fts3GetVarint32(zCsr, &nPrefix);
+      if( nPrefix>nBuffer ){
+        rc = FTS_CORRUPT_VTAB;
+        goto finish_scan;
+      }
     }
     isFirstTerm = 0;
     zCsr += fts3GetVarint32(zCsr, &nSuffix);
-    
+
     assert( nPrefix>=0 && nSuffix>=0 );
     if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
       rc = FTS_CORRUPT_VTAB;
@@ -164153,8 +169948,8 @@ static int fts3ScanInteriorNode(
 
     /* Compare the term we are searching for with the term just loaded from
     ** the interior node. If the specified term is greater than or equal
-    ** to the term from the interior node, then all terms on the sub-tree 
-    ** headed by node iChild are smaller than zTerm. No need to search 
+    ** to the term from the interior node, then all terms on the sub-tree
+    ** headed by node iChild are smaller than zTerm. No need to search
     ** iChild.
     **
     ** If the interior node term is larger than the specified term, then
@@ -164190,20 +169985,20 @@ static int fts3ScanInteriorNode(
 ** node for the range of leaf nodes that may contain the specified term
 ** or terms for which the specified term is a prefix.
 **
-** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
+** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
 ** left-most leaf node in the tree that may contain the specified term.
 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
 ** right-most leaf node that may contain a term for which the specified
 ** term is a prefix.
 **
-** It is possible that the range of returned leaf nodes does not contain 
-** the specified term or any terms for which it is a prefix. However, if the 
+** It is possible that the range of returned leaf nodes does not contain
+** the specified term or any terms for which it is a prefix. However, if the
 ** segment does contain any such terms, they are stored within the identified
 ** range. Because this function only inspects interior segment nodes (and
 ** never loads leaf nodes into memory), it is not possible to be sure.
 **
 ** If an error occurs, an error code other than SQLITE_OK is returned.
-*/ 
+*/
 static int fts3SelectLeaf(
   Fts3Table *p,                   /* Virtual table handle */
   const char *zTerm,              /* Term to select leaves for */
@@ -164220,7 +170015,7 @@ static int fts3SelectLeaf(
 
   fts3GetVarint32(zNode, &iHeight);
   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
-  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
+  assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
 
   if( rc==SQLITE_OK && iHeight>1 ){
     char *zBlob = 0;              /* Blob read from %_segments table */
@@ -164240,7 +170035,13 @@ static int fts3SelectLeaf(
       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
     }
     if( rc==SQLITE_OK ){
-      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
+      int iNewHeight = 0;
+      fts3GetVarint32(zBlob, &iNewHeight);
+      if( iNewHeight>=iHeight ){
+        rc = FTS_CORRUPT_VTAB;
+      }else{
+        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
+      }
     }
     sqlite3_free(zBlob);
   }
@@ -164249,7 +170050,7 @@ static int fts3SelectLeaf(
 }
 
 /*
-** This function is used to create delta-encoded serialized lists of FTS3 
+** This function is used to create delta-encoded serialized lists of FTS3
 ** varints. Each call to this function appends a single varint to a list.
 */
 static void fts3PutDeltaVarint(
@@ -164257,17 +170058,17 @@ static void fts3PutDeltaVarint(
   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
   sqlite3_int64 iVal              /* Write this value to the list */
 ){
-  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
+  assert_fts3_nc( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
   *piPrev = iVal;
 }
 
 /*
-** When this function is called, *ppPoslist is assumed to point to the 
+** When this function is called, *ppPoslist is assumed to point to the
 ** start of a position-list. After it returns, *ppPoslist points to the
 ** first byte after the position-list.
 **
-** A position list is list of positions (delta encoded) and columns for 
+** A position list is list of positions (delta encoded) and columns for
 ** a single document record of a doclist.  So, in other words, this
 ** routine advances *ppPoslist so that it points to the next docid in
 ** the doclist, or to the first byte past the end of the doclist.
@@ -164280,12 +170081,12 @@ static void fts3PoslistCopy(char **pp, char **ppPoslist){
   char *pEnd = *ppPoslist;
   char c = 0;
 
-  /* The end of a position list is marked by a zero encoded as an FTS3 
+  /* The end of a position list is marked by a zero encoded as an FTS3
   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
   ** of some other, multi-byte, value.
   **
-  ** The following while-loop moves pEnd to point to the first byte that is not 
+  ** The following while-loop moves pEnd to point to the first byte that is not
   ** immediately preceded by a byte with the 0x80 bit set. Then increments
   ** pEnd once more so that it points to the byte immediately following the
   ** last byte in the position-list.
@@ -164307,7 +170108,7 @@ static void fts3PoslistCopy(char **pp, char **ppPoslist){
 }
 
 /*
-** When this function is called, *ppPoslist is assumed to point to the 
+** When this function is called, *ppPoslist is assumed to point to the
 ** start of a column-list. After it returns, *ppPoslist points to the
 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
 **
@@ -164358,7 +170159,7 @@ static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
 ** (in which case **pp will be a terminator bytes POS_END (0) or
 ** (1)).
 **
-** If *pp points past the end of the current position-list, set *pi to 
+** If *pp points past the end of the current position-list, set *pi to
 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
 ** increment the current value of *pi by the value read, and set *pp to
 ** point to the next value before returning.
@@ -164374,7 +170175,9 @@ static void fts3ReadNextPos(
   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
 ){
   if( (**pp)&0xFE ){
-    fts3GetDeltaVarint(pp, pi);
+    int iVal;
+    *pp += fts3GetVarint32((*pp), &iVal);
+    *pi += iVal;
     *pi -= 2;
   }else{
     *pi = POSITION_LIST_END;
@@ -164386,7 +170189,7 @@ static void fts3ReadNextPos(
 ** the value of iCol encoded as a varint to *pp.   This will start a new
 ** column list.
 **
-** Set *pp to point to the byte just after the last byte written before 
+** Set *pp to point to the byte just after the last byte written before
 ** returning (do not modify it if iCol==0). Return the total number of bytes
 ** written (0 if iCol==0).
 */
@@ -164421,7 +170224,7 @@ static int fts3PoslistMerge(
     int iCol1;         /* The current column index in pp1 */
     int iCol2;         /* The current column index in pp2 */
 
-    if( *p1==POS_COLUMN ){ 
+    if( *p1==POS_COLUMN ){
       fts3GetVarint32(&p1[1], &iCol1);
       if( iCol1==0 ) return FTS_CORRUPT_VTAB;
     }
@@ -164445,7 +170248,7 @@ static int fts3PoslistMerge(
 
       /* At this point, both p1 and p2 point to the start of column-lists
       ** for the same column (the column with index iCol1 and iCol2).
-      ** A column-list is a list of non-negative delta-encoded varints, each 
+      ** A column-list is a list of non-negative delta-encoded varints, each
       ** incremented by 2 before being stored. Each list is terminated by a
       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
       ** and writes the results to buffer p. p is left pointing to the byte
@@ -164454,8 +170257,11 @@ static int fts3PoslistMerge(
       */
       fts3GetDeltaVarint(&p1, &i1);
       fts3GetDeltaVarint(&p2, &i2);
+      if( i1<2 || i2<2 ){
+        break;
+      }
       do {
-        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
+        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
         iPrev -= 2;
         if( i1==i2 ){
           fts3ReadNextPos(&p1, &i1);
@@ -164497,7 +170303,7 @@ static int fts3PoslistMerge(
 ** When this function returns, both *pp1 and *pp2 are left pointing to the
 ** byte following the 0x00 terminator of their respective position lists.
 **
-** If isSaveLeft is 0, an entry is added to the output position list for 
+** If isSaveLeft is 0, an entry is added to the output position list for
 ** each position in *pp2 for which there exists one or more positions in
 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
@@ -164522,12 +170328,12 @@ static int fts3PoslistPhraseMerge(
   /* Never set both isSaveLeft and isExact for the same invocation. */
   assert( isSaveLeft==0 || isExact==0 );
 
-  assert( p!=0 && *p1!=0 && *p2!=0 );
-  if( *p1==POS_COLUMN ){ 
+  assert_fts3_nc( p!=0 && *p1!=0 && *p2!=0 );
+  if( *p1==POS_COLUMN ){
     p1++;
     p1 += fts3GetVarint32(p1, &iCol1);
   }
-  if( *p2==POS_COLUMN ){ 
+  if( *p2==POS_COLUMN ){
     p2++;
     p2 += fts3GetVarint32(p2, &iCol2);
   }
@@ -164549,8 +170355,8 @@ static int fts3PoslistPhraseMerge(
       if( iPos1<0 || iPos2<0 ) break;
 
       while( 1 ){
-        if( iPos2==iPos1+nToken 
-         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
+        if( iPos2==iPos1+nToken
+         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
         ){
           sqlite3_int64 iSave;
           iSave = isSaveLeft ? iPos1 : iPos2;
@@ -164585,8 +170391,8 @@ static int fts3PoslistPhraseMerge(
 
     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
-    ** end of the position list, or the 0x01 that precedes the next 
-    ** column-number in the position list. 
+    ** end of the position list, or the 0x01 that precedes the next
+    ** column-number in the position list.
     */
     else if( iCol1<iCol2 ){
       fts3ColumnlistCopy(0, &p1);
@@ -164615,14 +170421,14 @@ static int fts3PoslistPhraseMerge(
 
 /*
 ** Merge two position-lists as required by the NEAR operator. The argument
-** position lists correspond to the left and right phrases of an expression 
+** position lists correspond to the left and right phrases of an expression
 ** like:
 **
 **     "phrase 1" NEAR "phrase number 2"
 **
-** Position list *pp1 corresponds to the left-hand side of the NEAR 
-** expression and *pp2 to the right. As usual, the indexes in the position 
-** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
+** Position list *pp1 corresponds to the left-hand side of the NEAR
+** expression and *pp2 to the right. As usual, the indexes in the position
+** lists are the offsets of the last token in each phrase (tokens "1" and "2"
 ** in the example above).
 **
 ** The output position list - written to *pp - is a copy of *pp2 with those
@@ -164662,7 +170468,7 @@ static int fts3PoslistNearMerge(
   return res;
 }
 
-/* 
+/*
 ** An instance of this function is used to merge together the (potentially
 ** large number of) doclists for each term that matches a prefix query.
 ** See function fts3TermSelectMerge() for details.
@@ -164683,7 +170489,7 @@ struct TermSelect {
 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
 **
 ** If bDescIdx is false, the value read is added to *pVal before returning.
-** If it is true, the value read is subtracted from *pVal before this 
+** If it is true, the value read is subtracted from *pVal before this
 ** function returns.
 */
 static void fts3GetDeltaVarint3(
@@ -164695,12 +170501,12 @@ static void fts3GetDeltaVarint3(
   if( *pp>=pEnd ){
     *pp = 0;
   }else{
-    sqlite3_int64 iVal;
-    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
+    u64 iVal;
+    *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
     if( bDescIdx ){
-      *pVal -= iVal;
+      *pVal = (i64)((u64)*pVal - iVal);
     }else{
-      *pVal += iVal;
+      *pVal = (i64)((u64)*pVal + iVal);
     }
   }
 }
@@ -164711,9 +170517,9 @@ static void fts3GetDeltaVarint3(
 ** end of the value written.
 **
 ** If *pbFirst is zero when this function is called, the value written to
-** the buffer is that of parameter iVal. 
+** the buffer is that of parameter iVal.
 **
-** If *pbFirst is non-zero when this function is called, then the value 
+** If *pbFirst is non-zero when this function is called, then the value
 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
 ** (if bDescIdx is non-zero).
 **
@@ -164727,15 +170533,16 @@ static void fts3PutDeltaVarint3(
   int *pbFirst,                   /* IN/OUT: True after first int written */
   sqlite3_int64 iVal              /* Write this value to the list */
 ){
-  sqlite3_int64 iWrite;
+  sqlite3_uint64 iWrite;
   if( bDescIdx==0 || *pbFirst==0 ){
-    iWrite = iVal - *piPrev;
+    assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
+    iWrite = (u64)iVal - (u64)*piPrev;
   }else{
-    iWrite = *piPrev - iVal;
+    assert_fts3_nc( *piPrev>=iVal );
+    iWrite = (u64)*piPrev - (u64)iVal;
   }
   assert( *pbFirst || *piPrev==0 );
   assert_fts3_nc( *pbFirst==0 || iWrite>0 );
-  assert( *pbFirst==0 || iWrite>=0 );
   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
   *piPrev = iVal;
   *pbFirst = 1;
@@ -164745,17 +170552,18 @@ static void fts3PutDeltaVarint3(
 /*
 ** This macro is used by various functions that merge doclists. The two
 ** arguments are 64-bit docid values. If the value of the stack variable
-** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
+** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
 ** Otherwise, (i2-i1).
 **
 ** Using this makes it easier to write code that can merge doclists that are
 ** sorted in either ascending or descending order.
 */
-#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
+/* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
+#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
 
 /*
 ** This function does an "OR" merge of two doclists (output contains all
-** positions contained in either argument doclist). If the docids in the 
+** positions contained in either argument doclist). If the docids in the
 ** input doclists are sorted in ascending order, parameter bDescDoclist
 ** should be false. If they are sorted in ascending order, it should be
 ** passed a non-zero value.
@@ -164795,12 +170603,12 @@ static int fts3DoclistOrMerge(
   ** current and previous docid (a positive number - since the list is in
   ** ascending order).
   **
-  ** The first docid written to the output is therefore encoded using the 
+  ** The first docid written to the output is therefore encoded using the
   ** same number of bytes as it is in whichever of the input lists it is
-  ** read from. And each subsequent docid read from the same input list 
+  ** read from. And each subsequent docid read from the same input list
   ** consumes either the same or less bytes as it did in the input (since
   ** the difference between it and the previous value in the output must
-  ** be a positive value less than or equal to the delta value read from 
+  ** be a positive value less than or equal to the delta value read from
   ** the input list). The same argument applies to all but the first docid
   ** read from the 'other' list. And to the contents of all position lists
   ** that will be copied and merged from the input to the output.
@@ -164812,9 +170620,9 @@ static int fts3DoclistOrMerge(
   **
   ** The space required to store the output is therefore the sum of the
   ** sizes of the two inputs, plus enough space for exactly one of the input
-  ** docids to grow. 
+  ** docids to grow.
   **
-  ** A symetric argument may be made if the doclists are in descending 
+  ** A symetric argument may be made if the doclists are in descending
   ** order.
   */
   aOut = sqlite3_malloc((size_t)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
@@ -164841,7 +170649,7 @@ static int fts3DoclistOrMerge(
       fts3PoslistCopy(&p, &p2);
       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
     }
-    
+
     assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
   }
 
@@ -164864,7 +170672,7 @@ static int fts3DoclistOrMerge(
 ** exactly nDist tokens before it.
 **
 ** If the docids in the input doclists are sorted in ascending order,
-** parameter bDescDoclist should be false. If they are sorted in ascending 
+** parameter bDescDoclist should be false. If they are sorted in ascending
 ** order, it should be passed a non-zero value.
 **
 ** The right-hand input doclist is overwritten by this function.
@@ -165010,7 +170818,7 @@ static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
         int nNew;
         char *aNew;
 
-        int rc = fts3DoclistOrMerge(p->bDescIdx, 
+        int rc = fts3DoclistOrMerge(p->bDescIdx,
             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
         );
         if( rc!=SQLITE_OK ){
@@ -165054,15 +170862,15 @@ static int fts3TermSelectMerge(
 ){
   if( pTS->aaOutput[0]==0 ){
     /* If this is the first term selected, copy the doclist to the output
-    ** buffer using memcpy(). 
+    ** buffer using memcpy().
     **
-    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 
+    ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
     ** allocation. This is so as to ensure that the buffer is big enough
     ** to hold the current doclist AND'd with any other doclist. If the
     ** doclists are stored in order=ASC order, this padding would not be
     ** required (since the size of [doclistA AND doclistB] is always less
     ** than or equal to the size of [doclistA] in that case). But this is
-    ** not true for order=DESC. For example, a doclist containing (1, -1) 
+    ** not true for order=DESC. For example, a doclist containing (1, -1)
     ** may be smaller than (-1), as in the first example the -1 may be stored
     ** as a single-byte delta, whereas in the second it must be stored as a
     ** FTS3_VARINT_MAX byte varint.
@@ -165092,7 +170900,7 @@ static int fts3TermSelectMerge(
         char *aNew;
         int nNew;
 
-        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
+        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
         );
         if( rc!=SQLITE_OK ){
@@ -165103,7 +170911,7 @@ static int fts3TermSelectMerge(
         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
         sqlite3_free(pTS->aaOutput[iOut]);
         pTS->aaOutput[iOut] = 0;
-  
+
         aMerge = aNew;
         nMerge = nNew;
         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
@@ -165120,7 +170928,7 @@ static int fts3TermSelectMerge(
 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
 */
 static int fts3SegReaderCursorAppend(
-  Fts3MultiSegReader *pCsr, 
+  Fts3MultiSegReader *pCsr,
   Fts3SegReader *pNew
 ){
   if( (pCsr->nSegment%16)==0 ){
@@ -165159,13 +170967,13 @@ static int fts3SegReaderCursor(
   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
   int rc2;                        /* Result of sqlite3_reset() */
 
-  /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
+  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
   ** for the pending-terms. If this is a scan, then this call must be being
   ** made by an fts4aux module, not an FTS table. In this case calling
-  ** Fts3SegReaderPending might segfault, as the data structures used by 
+  ** Fts3SegReaderPending might segfault, as the data structures used by
   ** fts4aux are not completely populated. So it's easiest to filter these
   ** calls out here.  */
-  if( iLevel<0 && p->aIndex ){
+  if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
     Fts3SegReader *pSeg = 0;
     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
     if( rc==SQLITE_OK && pSeg ){
@@ -165196,10 +171004,10 @@ static int fts3SegReaderCursor(
         if( rc!=SQLITE_OK ) goto finished;
         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
       }
-      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
+
+      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
           (isPrefix==0 && isScan==0),
-          iStartBlock, iLeavesEndBlock, 
+          iStartBlock, iLeavesEndBlock,
           iEndBlock, zRoot, nRoot, &pSeg
       );
       if( rc!=SQLITE_OK ) goto finished;
@@ -165215,7 +171023,7 @@ static int fts3SegReaderCursor(
 }
 
 /*
-** Set up a cursor object for iterating through a full-text index or a 
+** Set up a cursor object for iterating through a full-text index or a
 ** single level therein.
 */
 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
@@ -165231,7 +171039,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
 ){
   assert( iIndex>=0 && iIndex<p->nIndex );
   assert( iLevel==FTS3_SEGCURSOR_ALL
-      ||  iLevel==FTS3_SEGCURSOR_PENDING 
+      ||  iLevel==FTS3_SEGCURSOR_PENDING
       ||  iLevel>=0
   );
   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
@@ -165257,20 +171065,20 @@ static int fts3SegReaderCursorAddZero(
   int nTerm,                      /* Number of bytes in zTerm */
   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
 ){
-  return fts3SegReaderCursor(p, 
+  return fts3SegReaderCursor(p,
       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
   );
 }
 
 /*
 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
-** if isPrefix is true, to scan the doclist for all terms for which 
+** if isPrefix is true, to scan the doclist for all terms for which
 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
 ** an SQLite error code.
 **
 ** It is the responsibility of the caller to free this object by eventually
-** passing it to fts3SegReaderCursorFree() 
+** passing it to fts3SegReaderCursorFree()
 **
 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
@@ -165295,7 +171103,7 @@ static int fts3TermSegReaderCursor(
       for(i=1; bFound==0 && i<p->nIndex; i++){
         if( p->aIndex[i].nPrefix==nTerm ){
           bFound = 1;
-          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
+          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
           );
           pSegcsr->bLookup = 1;
@@ -165305,7 +171113,7 @@ static int fts3TermSegReaderCursor(
       for(i=1; bFound==0 && i<p->nIndex; i++){
         if( p->aIndex[i].nPrefix==nTerm+1 ){
           bFound = 1;
-          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
+          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
           );
           if( rc==SQLITE_OK ){
@@ -165318,7 +171126,7 @@ static int fts3TermSegReaderCursor(
     }
 
     if( bFound==0 ){
-      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
+      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
       );
       pSegcsr->bLookup = !isPrefix;
@@ -165366,7 +171174,7 @@ static int fts3TermSelect(
 
   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
   while( SQLITE_OK==rc
-      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
+      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
   ){
     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
   }
@@ -165395,7 +171203,7 @@ static int fts3TermSelect(
 **
 ** If the isPoslist argument is true, then it is assumed that the doclist
 ** contains a position-list following each docid. Otherwise, it is assumed
-** that the doclist is simply a list of docids stored as delta encoded 
+** that the doclist is simply a list of docids stored as delta encoded
 ** varints.
 */
 static int fts3DoclistCountDocids(char *aList, int nList){
@@ -165428,6 +171236,8 @@ static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
   int rc;
   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
+    Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
+    pTab->bLock++;
     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
       pCsr->isEof = 1;
       rc = sqlite3_reset(pCsr->pStmt);
@@ -165435,6 +171245,7 @@ static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
       rc = SQLITE_OK;
     }
+    pTab->bLock--;
   }else{
     rc = fts3EvalNext((Fts3Cursor *)pCursor);
   }
@@ -165495,6 +171306,10 @@ static int fts3FilterMethod(
   UNUSED_PARAMETER(idxStr);
   UNUSED_PARAMETER(nVal);
 
+  if( p->bLock ){
+    return SQLITE_ERROR;
+  }
+
   eSearch = (idxNum & 0x0000FFFF);
   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
   assert( p->pSegments==0 );
@@ -165534,7 +171349,7 @@ static int fts3FilterMethod(
 
     assert( p->base.zErrMsg==0 );
     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
-        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
+        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
         &p->base.zErrMsg
     );
     if( rc!=SQLITE_OK ){
@@ -165561,12 +171376,16 @@ static int fts3FilterMethod(
           (pCsr->bDesc ? "DESC" : "ASC")
       );
     }else{
-      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 
+      zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
       );
     }
     if( zSql ){
-      rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
+      p->bLock++;
+      rc = sqlite3_prepare_v3(
+          p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
+      );
+      p->bLock--;
       sqlite3_free(zSql);
     }else{
       rc = SQLITE_NOMEM;
@@ -165582,8 +171401,8 @@ static int fts3FilterMethod(
   return fts3NextMethod(pCursor);
 }
 
-/* 
-** This is the xEof method of the virtual table. SQLite calls this 
+/*
+** This is the xEof method of the virtual table. SQLite calls this
 ** routine to find out if it has reached the end of a result set.
 */
 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
@@ -165595,7 +171414,7 @@ static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
   return pCsr->isEof;
 }
 
-/* 
+/*
 ** This is the xRowid method. The SQLite core calls this routine to
 ** retrieve the rowid for the current row of the result set. fts3
 ** exposes %_content.docid as the rowid for the virtual table. The
@@ -165607,7 +171426,7 @@ static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** This is the xColumn method, called by SQLite to request a value from
 ** the row that the supplied cursor currently points to.
 **
@@ -165650,7 +171469,7 @@ static int fts3ColumnMethod(
         break;
       }else{
         iCol = p->nColumn;
-        /* fall-through */
+        /* no break */ deliberate_fall_through
       }
 
     default:
@@ -165667,8 +171486,8 @@ static int fts3ColumnMethod(
   return rc;
 }
 
-/* 
-** This function is the implementation of the xUpdate callback used by 
+/*
+** This function is the implementation of the xUpdate callback used by
 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
 ** inserted, updated or deleted.
 */
@@ -165703,7 +171522,7 @@ static int fts3SyncMethod(sqlite3_vtab *pVtab){
   **
   ** Of course, updating the input segments also involves deleting a bunch
   ** of blocks from the segments table. But this is not considered overhead
-  ** as it would also be required by a crisis-merge that used the same input 
+  ** as it would also be required by a crisis-merge that used the same input
   ** segments.
   */
   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
@@ -165713,8 +171532,8 @@ static int fts3SyncMethod(sqlite3_vtab *pVtab){
   i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
 
   rc = sqlite3Fts3PendingTermsFlush(p);
-  if( rc==SQLITE_OK 
-   && p->nLeafAdd>(nMinMerge/16) 
+  if( rc==SQLITE_OK
+   && p->nLeafAdd>(nMinMerge/16)
    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
   ){
     int mxLevel = 0;              /* Maximum relative level value in db */
@@ -165753,7 +171572,7 @@ static int fts3SetHasStat(Fts3Table *p){
 }
 
 /*
-** Implementation of xBegin() method. 
+** Implementation of xBegin() method.
 */
 static int fts3BeginMethod(sqlite3_vtab *pVtab){
   Fts3Table *p = (Fts3Table*)pVtab;
@@ -165809,17 +171628,17 @@ static void fts3ReversePoslist(char *pStart, char **ppPoslist){
   /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
   while( p>pStart && (c=*p--)==0 );
 
-  /* Search backwards for a varint with value zero (the end of the previous 
+  /* Search backwards for a varint with value zero (the end of the previous
   ** poslist). This is an 0x00 byte preceded by some byte that does not
   ** have the 0x80 bit set.  */
-  while( p>pStart && (*p & 0x80) | c ){ 
-    c = *p--; 
+  while( p>pStart && (*p & 0x80) | c ){
+    c = *p--;
   }
   assert( p==pStart || c==0 );
 
   /* At this point p points to that preceding byte without the 0x80 bit
   ** set. So to find the start of the poslist, skip forward 2 bytes then
-  ** over a varint. 
+  ** over a varint.
   **
   ** Normally. The other case is that p==pStart and the poslist to return
   ** is the first in the doclist. In this case do not skip forward 2 bytes.
@@ -165840,7 +171659,7 @@ static void fts3ReversePoslist(char *pStart, char **ppPoslist){
 ** offsets() and optimize() SQL functions.
 **
 ** If the value passed as the third argument is a blob of size
-** sizeof(Fts3Cursor*), then the blob contents are copied to the 
+** sizeof(Fts3Cursor*), then the blob contents are copied to the
 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
 ** message is written to context pContext and SQLITE_ERROR returned. The
 ** string passed via zFunc is used as part of the error message.
@@ -165885,7 +171704,7 @@ static void fts3SnippetFunc(
   assert( nVal>=1 );
 
   if( nVal>6 ){
-    sqlite3_result_error(pContext, 
+    sqlite3_result_error(pContext,
         "wrong number of arguments to function snippet()", -1);
     return;
   }
@@ -165893,9 +171712,13 @@ static void fts3SnippetFunc(
 
   switch( nVal ){
     case 6: nToken = sqlite3_value_int(apVal[5]);
+            /* no break */ deliberate_fall_through
     case 5: iCol = sqlite3_value_int(apVal[4]);
+            /* no break */ deliberate_fall_through
     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
+            /* no break */ deliberate_fall_through
     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
+            /* no break */ deliberate_fall_through
     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
   }
   if( !zEllipsis || !zEnd || !zStart ){
@@ -165927,8 +171750,8 @@ static void fts3OffsetsFunc(
   }
 }
 
-/* 
-** Implementation of the special optimize() function for FTS3. This 
+/*
+** Implementation of the special optimize() function for FTS3. This
 ** function merges all segments in the database to a single segment.
 ** Example usage is:
 **
@@ -166037,10 +171860,10 @@ static int fts3RenameMethod(
   /* At this point it must be known if the %_stat table exists or not.
   ** So bHasStat may not be 2.  */
   rc = fts3SetHasStat(p);
-  
+
   /* As it happens, the pending terms table is always empty here. This is
-  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
-  ** always opens a savepoint transaction. And the xSavepoint() method 
+  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
+  ** always opens a savepoint transaction. And the xSavepoint() method
   ** flushes the pending terms table. But leave the (no-op) call to
   ** PendingTermsFlush() in in case that changes.
   */
@@ -166131,7 +171954,7 @@ static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
 */
 static int fts3ShadowName(const char *zName){
   static const char *azName[] = {
-    "content", "docsize", "segdir", "segments", "stat", 
+    "content", "docsize", "segdir", "segments", "stat",
   };
   unsigned int i;
   for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
@@ -166179,7 +172002,7 @@ static void hashDestroy(void *p){
 }
 
 /*
-** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
+** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
 ** respectively. The following three forward declarations are for functions
 ** declared in these files used to retrieve the respective implementations.
@@ -166243,11 +172066,11 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   /* Load the built-in tokenizers into the hash table */
   if( rc==SQLITE_OK ){
     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
-     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
+     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
 
 #ifndef SQLITE_DISABLE_FTS3_UNICODE
-     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
-     || sqlite3Fts3HashInsert(pHash, "unicode", 8, (void *)pUnicode) 
+     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
+     || sqlite3Fts3HashInsert(pHash, "unicode", 8, (void *)pUnicode)
 #endif
 #ifdef SQLITE_ENABLE_ICU
      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
@@ -166263,11 +172086,11 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
   }
 #endif
 
-  /* Create the virtual table wrapper around the hash-table and overload 
+  /* Create the virtual table wrapper around the hash-table and overload
   ** the four scalar functions. If this is successful, register the
   ** module with sqlite.
   */
-  if( SQLITE_OK==rc 
+  if( SQLITE_OK==rc
    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
@@ -166301,7 +172124,7 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
 
 /*
 ** Allocate an Fts3MultiSegReader for each token in the expression headed
-** by pExpr. 
+** by pExpr.
 **
 ** An Fts3SegReader object is a cursor that can seek or scan a range of
 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
@@ -166311,7 +172134,7 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
 ** segment b-tree (if the term is not a prefix or it is a prefix for which
 ** there exists prefix b-tree of the right length) then it may be traversed
-** and merged incrementally. Otherwise, it has to be merged into an in-memory 
+** and merged incrementally. Otherwise, it has to be merged into an in-memory
 ** doclist and then traversed.
 */
 static void fts3EvalAllocateReaders(
@@ -166328,7 +172151,7 @@ static void fts3EvalAllocateReaders(
       *pnToken += nToken;
       for(i=0; i<nToken; i++){
         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
-        int rc = fts3TermSegReaderCursor(pCsr, 
+        int rc = fts3TermSegReaderCursor(pCsr,
             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
         );
         if( rc!=SQLITE_OK ){
@@ -166534,7 +172357,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
         sqlite3_free(aPoslist);
         return SQLITE_NOMEM;
       }
-      
+
       pPhrase->doclist.pList = aOut;
       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
         pPhrase->doclist.bFreeList = 1;
@@ -166559,7 +172382,7 @@ static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
 #define MAX_INCR_PHRASE_TOKENS 4
 
 /*
-** This function is called for each Fts3Phrase in a full-text query 
+** This function is called for each Fts3Phrase in a full-text query
 ** expression to initialize the mechanism for returning rows. Once this
 ** function has been called successfully on an Fts3Phrase, it may be
 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
@@ -166577,14 +172400,14 @@ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
 
   /* Determine if doclists may be loaded from disk incrementally. This is
   ** possible if the bOptOk argument is true, the FTS doclists will be
-  ** scanned in forward order, and the phrase consists of 
+  ** scanned in forward order, and the phrase consists of
   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
   ** tokens or prefix tokens that cannot use a prefix-index.  */
   int bHaveIncr = 0;
-  int bIncrOk = (bOptOk 
-   && pCsr->bDesc==pTab->bDescIdx 
+  int bIncrOk = (bOptOk
+   && pCsr->bDesc==pTab->bDescIdx
    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
-#ifdef SQLITE_TEST
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
    && pTab->bNoIncrDoclist==0
 #endif
   );
@@ -166618,12 +172441,12 @@ static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
 }
 
 /*
-** This function is used to iterate backwards (from the end to start) 
+** This function is used to iterate backwards (from the end to start)
 ** through doclists. It is used by this module to iterate through phrase
 ** doclists in reverse and by the fts3_write.c module to iterate through
 ** pending-terms lists when writing to databases with "order=desc".
 **
-** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
+** The doclist may be sorted in ascending (parameter bDescIdx==0) or
 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
 ** function iterates from the end of the doclist to the beginning.
 */
@@ -166695,7 +172518,7 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
 
   assert( nDoclist>0 );
   assert( *pbEof==0 );
-  assert( p || *piDocid==0 );
+  assert_fts3_nc( p || *piDocid==0 );
   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
 
   if( p==0 ){
@@ -166703,7 +172526,7 @@ SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
     p += sqlite3Fts3GetVarint(p, piDocid);
   }else{
     fts3PoslistCopy(0, &p);
-    while( p<&aDoclist[nDoclist] && *p==0 ) p++; 
+    while( p<&aDoclist[nDoclist] && *p==0 ) p++;
     if( p>=&aDoclist[nDoclist] ){
       *pbEof = 1;
     }else{
@@ -166726,15 +172549,16 @@ static void fts3EvalDlPhraseNext(
   u8 *pbEof
 ){
   char *pIter;                            /* Used to iterate through aAll */
-  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
+  char *pEnd;                             /* 1 byte past end of aAll */
+
   if( pDL->pNextDocid ){
     pIter = pDL->pNextDocid;
+    assert( pDL->aAll!=0 || pIter==0 );
   }else{
     pIter = pDL->aAll;
   }
 
-  if( pIter>=pEnd ){
+  if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
     /* We have already reached the end of this doclist. EOF. */
     *pbEof = 1;
   }else{
@@ -166775,12 +172599,12 @@ struct TokenDoclist {
 };
 
 /*
-** Token pToken is an incrementally loaded token that is part of a 
+** Token pToken is an incrementally loaded token that is part of a
 ** multi-token phrase. Advance it to the next matching document in the
 ** database and populate output variable *p with the details of the new
 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
 **
-** If an error occurs, return an SQLite error code. Otherwise, return 
+** If an error occurs, return an SQLite error code. Otherwise, return
 ** SQLITE_OK.
 */
 static int incrPhraseTokenNext(
@@ -166821,18 +172645,18 @@ static int incrPhraseTokenNext(
 /*
 ** The phrase iterator passed as the second argument:
 **
-**   * features at least one token that uses an incremental doclist, and 
+**   * features at least one token that uses an incremental doclist, and
 **
 **   * does not contain any deferred tokens.
 **
 ** Advance it to the next matching documnent in the database and populate
-** the Fts3Doclist.pList and nList fields. 
+** the Fts3Doclist.pList and nList fields.
 **
 ** If there is no "next" entry and no error occurs, then *pbEof is set to
 ** 1 before returning. Otherwise, if no error occurs and the iterator is
 ** successfully advanced, *pbEof is set to 0.
 **
-** If an error occurs, return an SQLite error code. Otherwise, return 
+** If an error occurs, return an SQLite error code. Otherwise, return
 ** SQLITE_OK.
 */
 static int fts3EvalIncrPhraseNext(
@@ -166850,7 +172674,7 @@ static int fts3EvalIncrPhraseNext(
   assert( p->bIncr==1 );
 
   if( p->nToken==1 ){
-    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
+    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
         &pDL->iDocid, &pDL->pList, &pDL->nList
     );
     if( pDL->pList==0 ) bEof = 1;
@@ -166880,8 +172704,8 @@ static int fts3EvalIncrPhraseNext(
 
       /* Keep advancing iterators until they all point to the same document */
       for(i=0; i<p->nToken; i++){
-        while( rc==SQLITE_OK && bEof==0 
-            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
+        while( rc==SQLITE_OK && bEof==0
+            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
         ){
           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
@@ -166928,8 +172752,8 @@ static int fts3EvalIncrPhraseNext(
 }
 
 /*
-** Attempt to move the phrase iterator to point to the next matching docid. 
-** If an error occurs, return an SQLite error code. Otherwise, return 
+** Attempt to move the phrase iterator to point to the next matching docid.
+** If an error occurs, return an SQLite error code. Otherwise, return
 ** SQLITE_OK.
 **
 ** If there is no "next" entry and no error occurs, then *pbEof is set to
@@ -166948,7 +172772,7 @@ static int fts3EvalPhraseNext(
   if( p->bIncr ){
     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
-    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
+    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
     );
     pDL->pList = pDL->pNextDocid;
@@ -167008,7 +172832,7 @@ static void fts3EvalStartReaders(
 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
 ** to phrases that are connected only by AND and NEAR operators (not OR or
 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
-** separately. The root of a tokens AND/NEAR cluster is stored in 
+** separately. The root of a tokens AND/NEAR cluster is stored in
 ** Fts3TokenAndCost.pRoot.
 */
 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
@@ -167076,7 +172900,7 @@ static void fts3EvalTokenCosts(
 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
 ** an SQLite error code.
 **
-** The average document size in pages is calculated by first calculating 
+** The average document size in pages is calculated by first calculating
 ** determining the average size in bytes, B. If B is less than the amount
 ** of data that will fit on a single leaf page of an intkey table in
 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
@@ -167086,10 +172910,10 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
   int rc = SQLITE_OK;
   if( pCsr->nRowAvg==0 ){
     /* The average document size, which is required to calculate the cost
-    ** of each doclist, has not yet been determined. Read the required 
+    ** of each doclist, has not yet been determined. Read the required
     ** data from the %_stat table to calculate it.
     **
-    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
+    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
     ** varints, where nCol is the number of columns in the FTS3 table.
     ** The first varint is the number of documents currently stored in
     ** the table. The following nCol varints contain the total amount of
@@ -167106,12 +172930,13 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
     if( rc!=SQLITE_OK ) return rc;
     a = sqlite3_column_blob(pStmt, 0);
-    assert( a );
-
-    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
-    a += sqlite3Fts3GetVarint(a, &nDoc);
-    while( a<pEnd ){
-      a += sqlite3Fts3GetVarint(a, &nByte);
+    testcase( a==0 );  /* If %_stat.value set to X'' */
+    if( a ){
+      pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
+      a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
+      while( a<pEnd ){
+        a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
+      }
     }
     if( nDoc==0 || nByte==0 ){
       sqlite3_reset(pStmt);
@@ -167120,7 +172945,7 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
 
     pCsr->nDoc = nDoc;
     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
-    assert( pCsr->nRowAvg>0 ); 
+    assert( pCsr->nRowAvg>0 );
     rc = sqlite3_reset(pStmt);
   }
 
@@ -167129,11 +172954,11 @@ static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
 }
 
 /*
-** This function is called to select the tokens (if any) that will be 
+** This function is called to select the tokens (if any) that will be
 ** deferred. The array aTC[] has already been populated when this is
 ** called.
 **
-** This function is called once for each AND/NEAR cluster in the 
+** This function is called once for each AND/NEAR cluster in the
 ** expression. Each invocation determines which tokens to defer within
 ** the cluster with root node pRoot. See comments above the definition
 ** of struct Fts3TokenAndCost for more details.
@@ -167183,8 +173008,8 @@ static int fts3EvalSelectDeferred(
   assert( rc!=SQLITE_OK || nDocSize>0 );
 
 
-  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
-  ** of the number of overflow pages that will be loaded by the pager layer 
+  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
+  ** of the number of overflow pages that will be loaded by the pager layer
   ** to retrieve the entire doclist for the token from the full-text index.
   ** Load the doclists for tokens that are either:
   **
@@ -167195,7 +173020,7 @@ static int fts3EvalSelectDeferred(
   **
   ** After each token doclist is loaded, merge it with the others from the
   ** same phrase and count the number of documents that the merged doclist
-  ** contains. Set variable "nMinEst" to the smallest number of documents in 
+  ** contains. Set variable "nMinEst" to the smallest number of documents in
   ** any phrase doclist for which 1 or more token doclists have been loaded.
   ** Let nOther be the number of other phrases for which it is certain that
   ** one or more tokens will not be deferred.
@@ -167211,8 +173036,8 @@ static int fts3EvalSelectDeferred(
 
     /* Set pTC to point to the cheapest remaining token. */
     for(iTC=0; iTC<nTC; iTC++){
-      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
-       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
+      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
+       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
       ){
         pTC = &aTC[iTC];
       }
@@ -167221,7 +173046,7 @@ static int fts3EvalSelectDeferred(
 
     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
       /* The number of overflow pages to load for this (and therefore all
-      ** subsequent) tokens is greater than the estimated number of pages 
+      ** subsequent) tokens is greater than the estimated number of pages
       ** that will be loaded if all subsequent tokens are deferred.
       */
       Fts3PhraseToken *pToken = pTC->pToken;
@@ -167230,7 +173055,7 @@ static int fts3EvalSelectDeferred(
       pToken->pSegcsr = 0;
     }else{
       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
-      ** for-loop. Except, limit the value to 2^24 to prevent it from 
+      ** for-loop. Except, limit the value to 2^24 to prevent it from
       ** overflowing the 32-bit integer it is stored in. */
       if( ii<12 ) nLoad4 = nLoad4*4;
 
@@ -167343,7 +173168,7 @@ static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
 **
 ** Parameter nNear is passed the NEAR distance of the expression (5 in
 ** the example above). When this function is called, *paPoslist points to
-** the position list, and *pnToken is the number of phrase tokens in, the
+** the position list, and *pnToken is the number of phrase tokens in the
 ** phrase on the other side of the NEAR operator to pPhrase. For example,
 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
 ** the position list associated with phrase "abc".
@@ -167352,7 +173177,7 @@ static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
 ** close to a position in the *paPoslist position list are removed. If this
 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
 **
-** Before returning, *paPoslist is set to point to the position lsit 
+** Before returning, *paPoslist is set to point to the position lsit
 ** associated with pPhrase. And *pnToken is set to the number of tokens in
 ** pPhrase.
 */
@@ -167366,8 +173191,8 @@ static int fts3EvalNearTrim(
   int nParam1 = nNear + pPhrase->nToken;
   int nParam2 = nNear + *pnToken;
   int nNew;
-  char *p2; 
-  char *pOut; 
+  char *p2;
+  char *pOut;
   int res;
 
   assert( pPhrase->doclist.pList );
@@ -167378,10 +173203,12 @@ static int fts3EvalNearTrim(
   );
   if( res ){
     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
-    assert( pPhrase->doclist.pList[nNew]=='\0' );
-    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
-    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
-    pPhrase->doclist.nList = nNew;
+    if( nNew>=0 ){
+      assert( pPhrase->doclist.pList[nNew]=='\0' );
+      assert( nNew<=pPhrase->doclist.nList && nNew>0 );
+      memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
+      pPhrase->doclist.nList = nNew;
+    }
     *paPoslist = pPhrase->doclist.pList;
     *pnToken = pPhrase->nToken;
   }
@@ -167414,19 +173241,19 @@ static int fts3EvalNearTrim(
 **
 **   1. Deferred tokens are not taken into account. If a phrase consists
 **      entirely of deferred tokens, it is assumed to match every row in
-**      the db. In this case the position-list is not populated at all. 
+**      the db. In this case the position-list is not populated at all.
 **
 **      Or, if a phrase contains one or more deferred tokens and one or
-**      more non-deferred tokens, then the expression is advanced to the 
+**      more non-deferred tokens, then the expression is advanced to the
 **      next possible match, considering only non-deferred tokens. In other
 **      words, if the phrase is "A B C", and "B" is deferred, the expression
-**      is advanced to the next row that contains an instance of "A * C", 
+**      is advanced to the next row that contains an instance of "A * C",
 **      where "*" may match any single token. The position list in this case
 **      is populated as for "A * C" before returning.
 **
-**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
+**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
 **      advanced to point to the next row that matches "x AND y".
-** 
+**
 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
 ** really a match, taking into account deferred tokens and NEAR operators.
 */
@@ -167490,11 +173317,12 @@ static void fts3EvalNextRow(
                 fts3EvalNextRow(pCsr, pLeft, pRc);
               }
             }
+            pRight->bEof = pLeft->bEof = 1;
           }
         }
         break;
       }
-  
+
       case FTSQUERY_OR: {
         Fts3Expr *pLeft = pExpr->pLeft;
         Fts3Expr *pRight = pExpr->pRight;
@@ -167534,9 +173362,9 @@ static void fts3EvalNextRow(
 
         fts3EvalNextRow(pCsr, pLeft, pRc);
         if( pLeft->bEof==0 ){
-          while( !*pRc 
-              && !pRight->bEof 
-              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
+          while( !*pRc
+              && !pRight->bEof
+              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
           ){
             fts3EvalNextRow(pCsr, pRight, pRc);
           }
@@ -167561,14 +173389,14 @@ static void fts3EvalNextRow(
 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
 ** cluster, then this function returns 1 immediately.
 **
-** Otherwise, it checks if the current row really does match the NEAR 
-** expression, using the data currently stored in the position lists 
-** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
+** Otherwise, it checks if the current row really does match the NEAR
+** expression, using the data currently stored in the position lists
+** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
 **
 ** If the current row is a match, the position list associated with each
 ** phrase in the NEAR expression is edited in place to contain only those
 ** phrase instances sufficiently close to their peers to satisfy all NEAR
-** constraints. In this case it returns 1. If the NEAR expression does not 
+** constraints. In this case it returns 1. If the NEAR expression does not
 ** match the current row, 0 is returned. The position lists may or may not
 ** be edited if 0 is returned.
 */
@@ -167591,15 +173419,15 @@ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
   **                |        |
   **               "w"      "x"
   **
-  ** The right-hand child of a NEAR node is always a phrase. The 
+  ** The right-hand child of a NEAR node is always a phrase. The
   ** left-hand child may be either a phrase or a NEAR node. There are
   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
   */
-  if( *pRc==SQLITE_OK 
-   && pExpr->eType==FTSQUERY_NEAR 
+  if( *pRc==SQLITE_OK
+   && pExpr->eType==FTSQUERY_NEAR
    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
   ){
-    Fts3Expr *p; 
+    Fts3Expr *p;
     size_t nTmp = 0;              /* Bytes of temp space */
     char *aTmp;                   /* Temp space for PoslistNearMerge() */
 
@@ -167646,12 +173474,12 @@ static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
 /*
 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
 ** Assuming no error occurs or has occurred, It returns non-zero if the
-** expression passed as the second argument matches the row that pCsr 
+** expression passed as the second argument matches the row that pCsr
 ** currently points to, or zero if it does not.
 **
 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
-** If an error occurs during execution of this function, *pRc is set to 
-** the appropriate SQLite error code. In this case the returned value is 
+** If an error occurs during execution of this function, *pRc is set to
+** the appropriate SQLite error code. In this case the returned value is
 ** undefined.
 */
 static int fts3EvalTestExpr(
@@ -167670,10 +173498,10 @@ static int fts3EvalTestExpr(
          && fts3EvalNearTest(pExpr, pRc)
         );
 
-        /* If the NEAR expression does not match any rows, zero the doclist for 
+        /* If the NEAR expression does not match any rows, zero the doclist for
         ** all phrases involved in the NEAR. This is because the snippet(),
-        ** offsets() and matchinfo() functions are not supposed to recognize 
-        ** any instances of phrases that are part of unmatched NEAR queries. 
+        ** offsets() and matchinfo() functions are not supposed to recognize
+        ** any instances of phrases that are part of unmatched NEAR queries.
         ** For example if this expression:
         **
         **    ... MATCH 'a OR (b NEAR c)'
@@ -167685,8 +173513,8 @@ static int fts3EvalTestExpr(
         ** then any snippet() should ony highlight the "a" term, not the "b"
         ** (as "b" is part of a non-matching NEAR clause).
         */
-        if( bHit==0 
-         && pExpr->eType==FTSQUERY_NEAR 
+        if( bHit==0
+         && pExpr->eType==FTSQUERY_NEAR
          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
         ){
           Fts3Expr *p;
@@ -167718,7 +173546,7 @@ static int fts3EvalTestExpr(
 
       default: {
 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
-        if( pCsr->pDeferred 
+        if( pCsr->pDeferred
          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
         ){
           Fts3Phrase *pPhrase = pExpr->pPhrase;
@@ -167732,7 +173560,10 @@ static int fts3EvalTestExpr(
         }else
 #endif
         {
-          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
+          bHit = (
+              pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId
+           && pExpr->pPhrase->doclist.nList>0
+          );
         }
         break;
       }
@@ -167774,7 +173605,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
     ** memory and scan it to determine the position list for each deferred
     ** token. Then, see if this row is really a match, considering deferred
     ** tokens and NEAR operators (neither of which were taken into account
-    ** earlier, by fts3EvalNextRow()). 
+    ** earlier, by fts3EvalNextRow()).
     */
     if( pCsr->pDeferred ){
       rc = fts3CursorSeek(0, pCsr);
@@ -167829,7 +173660,7 @@ static int fts3EvalNext(Fts3Cursor *pCsr){
 
 /*
 ** Restart interation for expression pExpr so that the next call to
-** fts3EvalNext() visits the first row. Do not allow incremental 
+** fts3EvalNext() visits the first row. Do not allow incremental
 ** loading or merging of phrase doclists for this iteration.
 **
 ** If *pRc is other than SQLITE_OK when this function is called, it is
@@ -167872,11 +173703,11 @@ static void fts3EvalRestart(
 }
 
 /*
-** After allocating the Fts3Expr.aMI[] array for each phrase in the 
+** After allocating the Fts3Expr.aMI[] array for each phrase in the
 ** expression rooted at pExpr, the cursor iterates through all rows matched
 ** by pExpr, calling this function for each row. This function increments
 ** the values in Fts3Expr.aMI[] according to the position-list currently
-** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
+** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
 ** expression nodes.
 */
 static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
@@ -167970,9 +173801,9 @@ static int fts3EvalGatherStats(
         pCsr->isRequireSeek = 1;
         pCsr->isMatchinfoNeeded = 1;
         pCsr->iPrevId = pRoot->iDocid;
-      }while( pCsr->isEof==0 
-           && pRoot->eType==FTSQUERY_NEAR 
-           && sqlite3Fts3EvalTestDeferred(pCsr, &rc) 
+      }while( pCsr->isEof==0
+           && pRoot->eType==FTSQUERY_NEAR
+           && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
       );
 
       if( rc==SQLITE_OK && pCsr->isEof==0 ){
@@ -167987,7 +173818,7 @@ static int fts3EvalGatherStats(
       pRoot->bEof = bEof;
     }else{
       /* Caution: pRoot may iterate through docids in ascending or descending
-      ** order. For this reason, even though it seems more defensive, the 
+      ** order. For this reason, even though it seems more defensive, the
       ** do loop can not be written:
       **
       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
@@ -167995,7 +173826,8 @@ static int fts3EvalGatherStats(
       fts3EvalRestart(pCsr, pRoot, &rc);
       do {
         fts3EvalNextRow(pCsr, pRoot, &rc);
-        assert( pRoot->bEof==0 );
+        assert_fts3_nc( pRoot->bEof==0 );
+        if( pRoot->bEof ) rc = FTS_CORRUPT_VTAB;
       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
     }
   }
@@ -168003,10 +173835,10 @@ static int fts3EvalGatherStats(
 }
 
 /*
-** This function is used by the matchinfo() module to query a phrase 
+** This function is used by the matchinfo() module to query a phrase
 ** expression node for the following information:
 **
-**   1. The total number of occurrences of the phrase in each column of 
+**   1. The total number of occurrences of the phrase in each column of
 **      the FTS table (considering all rows), and
 **
 **   2. For each column, the number of rows in the table for which the
@@ -168020,12 +173852,12 @@ static int fts3EvalGatherStats(
 **
 ** Caveats:
 **
-**   * If a phrase consists entirely of deferred tokens, then all output 
+**   * If a phrase consists entirely of deferred tokens, then all output
 **     values are set to the number of documents in the table. In other
-**     words we assume that very common tokens occur exactly once in each 
+**     words we assume that very common tokens occur exactly once in each
 **     column of each row of the table.
 **
-**   * If a phrase contains some deferred tokens (and some non-deferred 
+**   * If a phrase contains some deferred tokens (and some non-deferred
 **     tokens), count the potential occurrence identified by considering
 **     the non-deferred tokens instead of actual phrase occurrences.
 **
@@ -168063,14 +173895,14 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
 
 /*
 ** The expression pExpr passed as the second argument to this function
-** must be of type FTSQUERY_PHRASE. 
+** must be of type FTSQUERY_PHRASE.
 **
 ** The returned value is either NULL or a pointer to a buffer containing
 ** a position-list indicating the occurrences of the phrase in column iCol
-** of the current row. 
+** of the current row.
 **
-** More specifically, the returned buffer contains 1 varint for each 
-** occurrence of the phrase in the column, stored using the normal (delta+2) 
+** More specifically, the returned buffer contains 1 varint for each
+** occurrence of the phrase in the column, stored using the normal (delta+2)
 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
 ** if the requested column contains "a b X c d X X" and the position-list
 ** for 'X' is requested, the buffer returned may contain:
@@ -168092,7 +173924,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
   int iThis;
   sqlite3_int64 iDocid;
 
-  /* If this phrase is applies specifically to some column other than 
+  /* If this phrase is applies specifically to some column other than
   ** column iCol, return a NULL pointer.  */
   *ppOut = 0;
   assert( iCol>=0 && iCol<pTab->nColumn );
@@ -168111,8 +173943,8 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
     int bMatch;
 
-    /* Check if this phrase descends from an OR expression node. If not, 
-    ** return NULL. Otherwise, the entry that corresponds to docid 
+    /* Check if this phrase descends from an OR expression node. If not,
+    ** return NULL. Otherwise, the entry that corresponds to docid
     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
     ** tree that the node is part of has been marked as EOF, but the node
     ** itself is not EOF, then it may point to an earlier entry. */
@@ -168160,7 +173992,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
           (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
           sqlite3Fts3DoclistNext(
-              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
+              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
               &pIter, &iDocid, &bEof
           );
         }
@@ -168169,7 +174001,7 @@ SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
           int dummy;
           sqlite3Fts3DoclistPrev(
-              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
+              bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
               &pIter, &iDocid, &dummy, &bEof
               );
         }
@@ -168245,7 +174077,7 @@ SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
 __declspec(dllexport)
 #endif
 SQLITE_API int sqlite3_fts3_init(
-  sqlite3 *db, 
+  sqlite3 *db,
   char **pzErrMsg,
   const sqlite3_api_routines *pApi
 ){
@@ -168339,11 +174171,11 @@ static int fts3auxConnectMethod(
   */
   if( argc!=4 && argc!=5 ) goto bad_args;
 
-  zDb = argv[1]; 
+  zDb = argv[1];
   nDb = (int)strlen(zDb);
   if( argc==5 ){
     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
-      zDb = argv[3]; 
+      zDb = argv[3];
       nDb = (int)strlen(zDb);
       zFts3 = argv[4];
     }else{
@@ -168407,7 +174239,7 @@ static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
 */
 static int fts3auxBestIndexMethod(
-  sqlite3_vtab *pVTab, 
+  sqlite3_vtab *pVTab,
   sqlite3_index_info *pInfo
 ){
   int i;
@@ -168420,14 +174252,14 @@ static int fts3auxBestIndexMethod(
   UNUSED_PARAMETER(pVTab);
 
   /* This vtab delivers always results in "ORDER BY term ASC" order. */
-  if( pInfo->nOrderBy==1 
-   && pInfo->aOrderBy[0].iColumn==0 
+  if( pInfo->nOrderBy==1
+   && pInfo->aOrderBy[0].iColumn==0
    && pInfo->aOrderBy[0].desc==0
   ){
     pInfo->orderByConsumed = 1;
   }
 
-  /* Search for equality and range constraints on the "term" column. 
+  /* Search for equality and range constraints on the "term" column.
   ** And equality constraints on the hidden "languageid" column. */
   for(i=0; i<pInfo->nConstraint; i++){
     if( pInfo->aConstraint[i].usable ){
@@ -168508,11 +174340,11 @@ static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
   if( nSize>pCsr->nStat ){
     struct Fts3auxColstats *aNew;
-    aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat, 
+    aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
         sizeof(struct Fts3auxColstats) * nSize
     );
     if( aNew==0 ) return SQLITE_NOMEM;
-    memset(&aNew[pCsr->nStat], 0, 
+    memset(&aNew[pCsr->nStat], 0,
         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
     );
     pCsr->aStat = aNew;
@@ -168572,8 +174404,8 @@ static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
 
         /* State 1. In this state we are expecting either a 1, indicating
         ** that the following integer will be a column number, or the
-        ** start of a position list for column 0.  
-        ** 
+        ** start of a position list for column 0.
+        **
         ** The only difference between state 1 and state 2 is that if the
         ** integer encountered in state 1 is not 0 or 1, then we need to
         ** increment the column 0 "nDoc" count for this term.
@@ -168686,7 +174518,7 @@ static int fts3auxFilterMethod(
     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
     pCsr->nStop = (int)strlen(pCsr->zStop);
   }
-  
+
   if( iLangid>=0 ){
     iLangVal = sqlite3_value_int(apVal[iLangid]);
 
@@ -168825,15 +174657,15 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
 ******************************************************************************
 **
 ** This module contains code that implements a parser for fts3 query strings
-** (the right-hand argument to the MATCH operator). Because the supported 
+** (the right-hand argument to the MATCH operator). Because the supported
 ** syntax is relatively simple, the whole tokenizer/parser system is
-** hand-coded. 
+** hand-coded.
 */
 /* #include "fts3Int.h" */
 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
 
 /*
-** By default, this module parses the legacy syntax that has been 
+** By default, this module parses the legacy syntax that has been
 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
 ** is defined, then it uses the new syntax. The differences between
 ** the new and the old syntaxes are:
@@ -168842,7 +174674,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
 **
 **  b) The new syntax supports the AND and NOT operators. The old does not.
 **
-**  c) The old syntax supports the "-" token qualifier. This is not 
+**  c) The old syntax supports the "-" token qualifier. This is not
 **     supported by the new syntax (it is replaced by the NOT operator).
 **
 **  d) When using the old syntax, the OR operator has a greater precedence
@@ -168851,7 +174683,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
 **
 ** If compiled with SQLITE_TEST defined, then this module exports the
 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
-** to zero causes the module to use the old syntax. If it is set to 
+** to zero causes the module to use the old syntax. If it is set to
 ** non-zero the new syntax is activated. This is so both syntaxes can
 ** be tested using a single build of testfixture.
 **
@@ -168880,7 +174712,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
 #ifdef SQLITE_TEST
 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
 #else
-# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
+# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
 #  define sqlite3_fts3_enable_parentheses 1
 # else
 #  define sqlite3_fts3_enable_parentheses 0
@@ -168898,7 +174730,7 @@ SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
 /*
 ** isNot:
 **   This variable is used by function getNextNode(). When getNextNode() is
-**   called, it sets ParseContext.isNot to true if the 'next node' is a 
+**   called, it sets ParseContext.isNot to true if the 'next node' is a
 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
 **   zero.
@@ -168917,7 +174749,7 @@ struct ParseContext {
 };
 
 /*
-** This function is equivalent to the standard isspace() function. 
+** This function is equivalent to the standard isspace() function.
 **
 ** The standard isspace() can be awkward to use safely, because although it
 ** is defined to accept an argument of type int, its behavior when passed
@@ -168933,7 +174765,7 @@ static int fts3isspace(char c){
 
 /*
 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
-** zero the memory before returning a pointer to it. If unsuccessful, 
+** zero the memory before returning a pointer to it. If unsuccessful,
 ** return NULL.
 */
 static void *fts3MallocZero(size_t nByte){
@@ -168981,7 +174813,7 @@ static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
 ** single token and set *ppExpr to point to it. If the end of the buffer is
 ** reached before a token is found, set *ppExpr to zero. It is the
-** responsibility of the caller to eventually deallocate the allocated 
+** responsibility of the caller to eventually deallocate the allocated
 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
 **
 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
@@ -169035,8 +174867,8 @@ static int getNextToken(
         }
 
         while( 1 ){
-          if( !sqlite3_fts3_enable_parentheses 
-           && iStart>0 && z[iStart-1]=='-' 
+          if( !sqlite3_fts3_enable_parentheses
+           && iStart>0 && z[iStart-1]=='-'
           ){
             pParse->isNot = 1;
             iStart--;
@@ -169056,7 +174888,7 @@ static int getNextToken(
 
     pModule->xClose(pCursor);
   }
-  
+
   *ppExpr = pRet;
   return rc;
 }
@@ -169078,7 +174910,7 @@ static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
 ** Buffer zInput, length nInput, contains the contents of a quoted string
 ** that appeared as part of an fts3 query expression. Neither quote character
 ** is included in the buffer. This function attempts to tokenize the entire
-** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
+** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
 ** containing the results.
 **
 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
@@ -169103,7 +174935,7 @@ static int getNextString(
   int nToken = 0;
 
   /* The final Fts3Expr data structure, including the Fts3Phrase,
-  ** Fts3PhraseToken structures token buffers are all stored as a single 
+  ** Fts3PhraseToken structures token buffers are all stored as a single
   ** allocation so that the expression can be freed with a single call to
   ** sqlite3_free(). Setting this up requires a two pass approach.
   **
@@ -169112,7 +174944,7 @@ static int getNextString(
   ** to assemble data in two dynamic buffers:
   **
   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
-  **             structure, followed by the array of Fts3PhraseToken 
+  **             structure, followed by the array of Fts3PhraseToken
   **             structures. This pass only populates the Fts3PhraseToken array.
   **
   **   Buffer zTemp: Contains copies of all tokens.
@@ -169197,7 +175029,7 @@ no_mem:
 }
 
 /*
-** The output variable *ppExpr is populated with an allocated Fts3Expr 
+** The output variable *ppExpr is populated with an allocated Fts3Expr
 ** structure, or set to 0 if the end of the input buffer is reached.
 **
 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
@@ -169233,7 +175065,7 @@ static int getNextNode(
   pParse->isNot = 0;
 
   /* Skip over any whitespace before checking for a keyword, an open or
-  ** close bracket, or a quoted string. 
+  ** close bracket, or a quoted string.
   */
   while( nInput>0 && fts3isspace(*zInput) ){
     nInput--;
@@ -169260,19 +175092,16 @@ static int getNextNode(
       if( pKey->eType==FTSQUERY_NEAR ){
         assert( nKey==4 );
         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
-          nNear = 0;
-          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
-            nNear = nNear * 10 + (zInput[nKey] - '0');
-          }
+          nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear);
         }
       }
 
       /* At this point this is probably a keyword. But for that to be true,
       ** the next byte must contain either whitespace, an open or close
-      ** parenthesis, a quote character, or EOF. 
+      ** parenthesis, a quote character, or EOF.
       */
       cNext = zInput[nKey];
-      if( fts3isspace(cNext) 
+      if( fts3isspace(cNext)
        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
       ){
         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
@@ -169321,15 +175150,15 @@ static int getNextNode(
     }
   }
 
-  /* If control flows to this point, this must be a regular token, or 
+  /* If control flows to this point, this must be a regular token, or
   ** the end of the input. Read a regular token using the sqlite3_tokenizer
   ** interface. Before doing so, figure out if there is an explicit
-  ** column specifier for the token. 
+  ** column specifier for the token.
   **
   ** TODO: Strangely, it is not possible to associate a column specifier
   ** with a quoted phrase, only with a single token. Not sure if this was
   ** an implementation artifact or an intentional decision when fts3 was
-  ** first implemented. Whichever it was, this module duplicates the 
+  ** first implemented. Whichever it was, this module duplicates the
   ** limitation.
   */
   iCol = pParse->iDefaultCol;
@@ -169337,8 +175166,8 @@ static int getNextNode(
   for(ii=0; ii<pParse->nCol; ii++){
     const char *zStr = pParse->azCol[ii];
     int nStr = (int)strlen(zStr);
-    if( nInput>nStr && zInput[nStr]==':' 
-     && sqlite3_strnicmp(zStr, zInput, nStr)==0 
+    if( nInput>nStr && zInput[nStr]==':'
+     && sqlite3_strnicmp(zStr, zInput, nStr)==0
     ){
       iCol = ii;
       iColLen = (int)((zInput - z) + nStr + 1);
@@ -169383,7 +175212,7 @@ static int opPrecedence(Fts3Expr *p){
 }
 
 /*
-** Argument ppHead contains a pointer to the current head of a query 
+** Argument ppHead contains a pointer to the current head of a query
 ** expression tree being parsed. pPrev is the expression node most recently
 ** inserted into the tree. This function adds pNew, which is always a binary
 ** operator node, into the expression tree based on the relative precedence
@@ -169413,7 +175242,7 @@ static void insertBinaryOperator(
 
 /*
 ** Parse the fts3 query expression found in buffer z, length n. This function
-** returns either when the end of the buffer is reached or an unmatched 
+** returns either when the end of the buffer is reached or an unmatched
 ** closing bracket - ')' - is encountered.
 **
 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
@@ -169445,8 +175274,8 @@ static int fts3ExprParse(
       if( p ){
         int isPhrase;
 
-        if( !sqlite3_fts3_enable_parentheses 
-            && p->eType==FTSQUERY_PHRASE && pParse->isNot 
+        if( !sqlite3_fts3_enable_parentheses
+            && p->eType==FTSQUERY_PHRASE && pParse->isNot
         ){
           /* Create an implicit NOT operator. */
           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
@@ -169567,13 +175396,13 @@ exprparse_out:
 }
 
 /*
-** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
+** Return SQLITE_ERROR if the maximum depth of the expression tree passed
 ** as the only argument is more than nMaxDepth.
 */
 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
   int rc = SQLITE_OK;
   if( p ){
-    if( nMaxDepth<0 ){ 
+    if( nMaxDepth<0 ){
       rc = SQLITE_TOOBIG;
     }else{
       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
@@ -169588,12 +175417,12 @@ static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
 /*
 ** This function attempts to transform the expression tree at (*pp) to
 ** an equivalent but more balanced form. The tree is modified in place.
-** If successful, SQLITE_OK is returned and (*pp) set to point to the 
-** new root expression node. 
+** If successful, SQLITE_OK is returned and (*pp) set to point to the
+** new root expression node.
 **
 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
 **
-** Otherwise, if an error occurs, an SQLite error code is returned and 
+** Otherwise, if an error occurs, an SQLite error code is returned and
 ** expression (*pp) freed.
 */
 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
@@ -169708,7 +175537,7 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
           }
           pRoot = p;
         }else{
-          /* An error occurred. Delete the contents of the apLeaf[] array 
+          /* An error occurred. Delete the contents of the apLeaf[] array
           ** and pFree list. Everything else is cleaned up by the call to
           ** sqlite3Fts3ExprFree(pRoot) below.  */
           Fts3Expr *pDel;
@@ -169750,7 +175579,7 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
       }
     }
   }
-  
+
   if( rc!=SQLITE_OK ){
     sqlite3Fts3ExprFree(pRoot);
     pRoot = 0;
@@ -169764,9 +175593,9 @@ static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
 ** differences:
 **
 **   1. It does not do expression rebalancing.
-**   2. It does not check that the expression does not exceed the 
+**   2. It does not check that the expression does not exceed the
 **      maximum allowable depth.
-**   3. Even if it fails, *ppExpr may still be set to point to an 
+**   3. Even if it fails, *ppExpr may still be set to point to an
 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
 **      in this case.
 */
@@ -169805,7 +175634,7 @@ static int fts3ExprParseUnbalanced(
   if( rc==SQLITE_OK && sParse.nNest ){
     rc = SQLITE_ERROR;
   }
-  
+
   return rc;
 }
 
@@ -169824,7 +175653,7 @@ static int fts3ExprParseUnbalanced(
 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
 ** use to normalize query tokens while parsing the expression. The azCol[]
 ** array, which is assumed to contain nCol entries, should contain the names
-** of each column in the target fts3 table, in order from left to right. 
+** of each column in the target fts3 table, in order from left to right.
 ** Column names must be nul-terminated strings.
 **
 ** The iDefaultCol parameter should be passed the index of the table column
@@ -169847,7 +175676,7 @@ SQLITE_PRIVATE int sqlite3Fts3ExprParse(
   int rc = fts3ExprParseUnbalanced(
       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
   );
-  
+
   /* Rebalance the expression. And check that its depth does not exceed
   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
   if( rc==SQLITE_OK && *ppExpr ){
@@ -169862,7 +175691,7 @@ SQLITE_PRIVATE int sqlite3Fts3ExprParse(
     *ppExpr = 0;
     if( rc==SQLITE_TOOBIG ){
       sqlite3Fts3ErrMsg(pzErr,
-          "FTS expression tree is too large (maximum depth %d)", 
+          "FTS expression tree is too large (maximum depth %d)",
           SQLITE_FTS3_MAX_EXPR_DEPTH
       );
       rc = SQLITE_ERROR;
@@ -169924,11 +175753,11 @@ SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
 /*
 ** Return a pointer to a buffer containing a text representation of the
 ** expression passed as the first argument. The buffer is obtained from
-** sqlite3_malloc(). It is the responsibility of the caller to use 
+** sqlite3_malloc(). It is the responsibility of the caller to use
 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
 ** NULL is returned.
 **
-** If the second argument is not NULL, then its contents are prepended to 
+** If the second argument is not NULL, then its contents are prepended to
 ** the returned expression text and then freed using sqlite3_free().
 */
 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
@@ -169942,7 +175771,7 @@ static char *exprToString(Fts3Expr *pExpr, char *zBuf){
       zBuf = sqlite3_mprintf(
           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
       for(i=0; zBuf && i<pPhrase->nToken; i++){
-        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
+        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
             (pPhrase->aToken[i].isPrefix?"+":"")
         );
@@ -169975,7 +175804,7 @@ static char *exprToString(Fts3Expr *pExpr, char *zBuf){
 }
 
 /*
-** This is the implementation of a scalar SQL function used to test the 
+** This is the implementation of a scalar SQL function used to test the
 ** expression parser. It should be called as follows:
 **
 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
@@ -170008,7 +175837,7 @@ static void fts3ExprTestCommon(
   char *zErr = 0;
 
   if( argc<3 ){
-    sqlite3_result_error(context, 
+    sqlite3_result_error(context,
         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
     );
     return;
@@ -170086,15 +175915,15 @@ static void fts3ExprTestRebalance(
 }
 
 /*
-** Register the query expression parser test function fts3_exprtest() 
-** with database connection db. 
+** Register the query expression parser test function fts3_exprtest()
+** with database connection db.
 */
 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
   int rc = sqlite3_create_function(
       db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
   );
   if( rc==SQLITE_OK ){
-    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
+    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
         -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
     );
   }
@@ -170158,8 +175987,8 @@ static void fts3HashFree(void *p){
 ** fields of the Hash structure.
 **
 ** "pNew" is a pointer to the hash table that is to be initialized.
-** keyClass is one of the constants 
-** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
+** keyClass is one of the constants
+** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
 ** determines what kind of key the hash table will use.  "copyKey" is
 ** true if the hash table should make its own private copy of keys and
 ** false if it should just use the supplied pointer.
@@ -170236,7 +176065,7 @@ static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
 /*
 ** Return a pointer to the appropriate hash function given the key class.
 **
-** The C syntax in this function definition may be unfamilar to some 
+** The C syntax in this function definition may be unfamilar to some
 ** programmers, so we provide the following additional explanation:
 **
 ** The name of the function is "ftsHashFunction".  The function takes a
@@ -170296,7 +176125,7 @@ static void fts3HashInsertElement(
 
 
 /* Resize the hash table so that it cantains "new_size" buckets.
-** "new_size" must be a power of 2.  The hash table might fail 
+** "new_size" must be a power of 2.  The hash table might fail
 ** to resize if sqliteMalloc() fails.
 **
 ** Return non-zero if a memory allocation error occurs.
@@ -170341,7 +176170,7 @@ static Fts3HashElem *fts3FindElementByHash(
     count = pEntry->count;
     xCompare = ftsCompareFunction(pH->keyClass);
     while( count-- && elem ){
-      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
+      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
         return elem;
       }
       elem = elem->next;
@@ -170360,7 +176189,7 @@ static void fts3RemoveElementByHash(
 ){
   struct _fts3ht *pEntry;
   if( elem->prev ){
-    elem->prev->next = elem->next; 
+    elem->prev->next = elem->next;
   }else{
     pH->first = elem->next;
   }
@@ -170388,8 +176217,8 @@ static void fts3RemoveElementByHash(
 }
 
 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
-  const Fts3Hash *pH, 
-  const void *pKey, 
+  const Fts3Hash *pH,
+  const void *pKey,
   int nKey
 ){
   int h;                          /* A hash on key */
@@ -170403,7 +176232,7 @@ SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
 }
 
-/* 
+/*
 ** Attempt to locate an element of the hash table pH with a key
 ** that matches pKey,nKey.  Return the data for this element if it is
 ** found, or NULL if there is no match.
@@ -170577,7 +176406,7 @@ static int porterDestroy(sqlite3_tokenizer *pTokenizer){
 /*
 ** Prepare to begin tokenizing a particular string.  The input
 ** string to be tokenized is zInput[0..nInput-1].  A cursor
-** used to incrementally tokenize this string is returned in 
+** used to incrementally tokenize this string is returned in
 ** *ppCursor.
 */
 static int porterOpen(
@@ -170630,7 +176459,7 @@ static const char cType[] = {
 /*
 ** isConsonant() and isVowel() determine if their first character in
 ** the string they point to is a consonant or a vowel, according
-** to Porter ruls.  
+** to Porter ruls.
 **
 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
 ** 'Y' is a consonant unless it follows another consonant,
@@ -170750,11 +176579,11 @@ static int star_oh(const char *z){
 
 /*
 ** If the word ends with zFrom and xCond() is true for the stem
-** of the word that preceeds the zFrom ending, then change the 
+** of the word that preceeds the zFrom ending, then change the
 ** ending to zTo.
 **
 ** The input word *pz and zFrom are both in reverse order.  zTo
-** is in normal order. 
+** is in normal order.
 **
 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
 ** match.  Not that TRUE is returned even if xCond() fails and
@@ -170823,9 +176652,9 @@ static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
 ** word contains digits, 3 bytes are taken from the beginning and
 ** 3 bytes from the end.  For long words without digits, 10 bytes
 ** are taken from each end.  US-ASCII case folding still applies.
-** 
-** If the input word contains not digits but does characters not 
-** in [a-zA-Z] then no stemming is attempted and this routine just 
+**
+** If the input word contains not digits but does characters not
+** in [a-zA-Z] then no stemming is attempted and this routine just
 ** copies the input into the input into the output with US-ASCII
 ** case folding.
 **
@@ -170870,11 +176699,11 @@ static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
     }
   }
 
-  /* Step 1b */  
+  /* Step 1b */
   z2 = z;
   if( stem(&z, "dee", "ee", m_gt_0) ){
     /* Do nothing.  The work was all in the test */
-  }else if( 
+  }else if(
      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
       && z!=z2
   ){
@@ -170913,7 +176742,7 @@ static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
      stem(&z, "igol", "log", m_gt_0);
      break;
    case 'l':
-     if( !stem(&z, "ilb", "ble", m_gt_0) 
+     if( !stem(&z, "ilb", "ble", m_gt_0)
       && !stem(&z, "illa", "al", m_gt_0)
       && !stem(&z, "iltne", "ent", m_gt_0)
       && !stem(&z, "ile", "e", m_gt_0)
@@ -171201,7 +177030,7 @@ static int fts3TokenizerEnabled(sqlite3_context *context){
 }
 
 /*
-** Implementation of the SQL scalar function for accessing the underlying 
+** Implementation of the SQL scalar function for accessing the underlying
 ** hash table. This function may be called as follows:
 **
 **   SELECT <function-name>(<key-name>);
@@ -171373,7 +177202,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
     if( rc!=SQLITE_OK ){
       sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
     }else{
-      (*ppTok)->pModule = m; 
+      (*ppTok)->pModule = m;
     }
     sqlite3_free((void *)aArg);
   }
@@ -171393,7 +177222,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
 /* #include <string.h> */
 
 /*
-** Implementation of a special SQL scalar function for testing tokenizers 
+** Implementation of a special SQL scalar function for testing tokenizers
 ** designed to be used in concert with the Tcl testing framework. This
 ** function must be called with two or more arguments:
 **
@@ -171405,9 +177234,9 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
 **
 ** The return value is a string that may be interpreted as a Tcl
 ** list. For each token in the <input-string>, three elements are
-** added to the returned list. The first is the token position, the 
+** added to the returned list. The first is the token position, the
 ** second is the token text (folded, stemmed, etc.) and the third is the
-** substring of <input-string> associated with the token. For example, 
+** substring of <input-string> associated with the token. For example,
 ** using the built-in "simple" tokenizer:
 **
 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
@@ -171415,7 +177244,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
 ** will return the string:
 **
 **   "{0 i I 1 dont don't 2 see see 3 how how}"
-**   
+**
 */
 static void testFunc(
   sqlite3_context *context,
@@ -171510,8 +177339,8 @@ finish:
 
 static
 int registerTokenizer(
-  sqlite3 *db, 
-  char *zName, 
+  sqlite3 *db,
+  char *zName,
   const sqlite3_tokenizer_module *p
 ){
   int rc;
@@ -171533,8 +177362,8 @@ int registerTokenizer(
 
 static
 int queryTokenizer(
-  sqlite3 *db, 
-  char *zName,  
+  sqlite3 *db,
+  char *zName,
   const sqlite3_tokenizer_module **pp
 ){
   int rc;
@@ -171549,7 +177378,9 @@ int queryTokenizer(
 
   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
   if( SQLITE_ROW==sqlite3_step(pStmt) ){
-    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
+    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB
+     && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp)
+    ){
       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
     }
   }
@@ -171617,28 +177448,28 @@ static void intTestFunc(
 /*
 ** Set up SQL objects in database db used to access the contents of
 ** the hash table pointed to by argument pHash. The hash table must
-** been initialized to use string keys, and to take a private copy 
+** been initialized to use string keys, and to take a private copy
 ** of the key when a value is inserted. i.e. by a call similar to:
 **
 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
 **
 ** This function adds a scalar function (see header comment above
 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
-** defined at compilation time, a temporary virtual table (see header 
-** comment above struct HashTableVtab) to the database schema. Both 
+** defined at compilation time, a temporary virtual table (see header
+** comment above struct HashTableVtab) to the database schema. Both
 ** provide read/write access to the contents of *pHash.
 **
 ** The third argument to this function, zName, is used as the name
 ** of both the scalar and, if created, the virtual table.
 */
 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
-  sqlite3 *db, 
-  Fts3Hash *pHash, 
+  sqlite3 *db,
+  Fts3Hash *pHash,
   const char *zName
 ){
   int rc = SQLITE_OK;
   void *p = (void *)pHash;
-  const int any = SQLITE_ANY;
+  const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
 
 #ifdef SQLITE_TEST
   char *zTest = 0;
@@ -171787,7 +177618,7 @@ static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
 /*
 ** Prepare to begin tokenizing a particular string.  The input
 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
-** used to incrementally tokenize this string is returned in 
+** used to incrementally tokenize this string is returned in
 ** *ppCursor.
 */
 static int simpleOpen(
@@ -171942,8 +177773,8 @@ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
 **
 **   input = <string>
 **
-** The virtual table module tokenizes this <string>, using the FTS3 
-** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
+** The virtual table module tokenizes this <string>, using the FTS3
+** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
 ** statement and returns one row for each token in the result. With
 ** fields set as follows:
 **
@@ -172012,7 +177843,7 @@ static int fts3tokQueryTokenizer(
 
 /*
 ** The second argument, argv[], is an array of pointers to nul-terminated
-** strings. This function makes a copy of the array and strings into a 
+** strings. This function makes a copy of the array and strings into a
 ** single block of memory. It then dequotes any of the strings that appear
 ** to be quoted.
 **
@@ -172068,7 +177899,7 @@ static int fts3tokDequoteArray(
 ** and xCreate are identical operations.
 **
 **   argv[0]: module name
-**   argv[1]: database name 
+**   argv[1]: database name
 **   argv[2]: table name
 **   argv[3]: first argument (tokenizer name)
 */
@@ -172105,7 +177936,8 @@ static int fts3tokConnectMethod(
 
   assert( (rc==SQLITE_OK)==(pMod!=0) );
   if( rc==SQLITE_OK ){
-    const char * const *azArg = (const char * const *)&azDequote[1];
+    const char * const *azArg = 0;
+    if( nDequote>1 ) azArg = (const char * const *)&azDequote[1];
     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
   }
 
@@ -172148,16 +177980,16 @@ static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
 */
 static int fts3tokBestIndexMethod(
-  sqlite3_vtab *pVTab, 
+  sqlite3_vtab *pVTab,
   sqlite3_index_info *pInfo
 ){
   int i;
   UNUSED_PARAMETER(pVTab);
 
   for(i=0; i<pInfo->nConstraint; i++){
-    if( pInfo->aConstraint[i].usable 
-     && pInfo->aConstraint[i].iColumn==0 
-     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
+    if( pInfo->aConstraint[i].usable
+     && pInfo->aConstraint[i].iColumn==0
+     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
     ){
       pInfo->idxNum = 1;
       pInfo->aConstraintUsage[i].argvIndex = 1;
@@ -172267,7 +178099,7 @@ static int fts3tokFilterMethod(
     if( pCsr->zInput==0 ){
       rc = SQLITE_NOMEM;
     }else{
-      memcpy(pCsr->zInput, zByte, nByte);
+      if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte);
       pCsr->zInput[nByte] = 0;
       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
       if( rc==SQLITE_OK ){
@@ -172388,7 +178220,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
 ** This file is part of the SQLite FTS3 extension module. Specifically,
 ** this file contains code to insert, update and delete rows from FTS3
 ** tables. It also contains code to merge FTS3 b-tree segments. Some
-** of the sub-routines used to merge segments are also used by the query 
+** of the sub-routines used to merge segments are also used by the query
 ** code in fts3.c.
 */
 
@@ -172398,13 +178230,13 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
 /* #include <string.h> */
 /* #include <assert.h> */
 /* #include <stdlib.h> */
-
+/* #include <stdio.h> */
 
 #define FTS_MAX_APPENDABLE_HEIGHT 16
 
 /*
 ** When full-text index nodes are loaded from disk, the buffer that they
-** are loaded into has the following number of bytes of padding at the end 
+** are loaded into has the following number of bytes of padding at the end
 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
 ** of 920 bytes is allocated for it.
 **
@@ -172421,10 +178253,10 @@ SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
 ** method before retrieving all query results (as may happen, for example,
 ** if a query has a LIMIT clause).
 **
-** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
+** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
-** The code is written so that the hard lower-limit for each of these values 
-** is 1. Clearly such small values would be inefficient, but can be useful 
+** The code is written so that the hard lower-limit for each of these values
+** is 1. Clearly such small values would be inefficient, but can be useful
 ** for testing purposes.
 **
 ** If this module is built with SQLITE_TEST defined, these constants may
@@ -172437,12 +178269,12 @@ int test_fts3_node_chunk_threshold = (4*1024)*4;
 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
 #else
-# define FTS3_NODE_CHUNKSIZE (4*1024) 
+# define FTS3_NODE_CHUNKSIZE (4*1024)
 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
 #endif
 
 /*
-** The two values that may be meaningfully bound to the :1 parameter in
+** The values that may be meaningfully bound to the :1 parameter in
 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
 */
 #define FTS_STAT_DOCTOTAL      0
@@ -172451,7 +178283,7 @@ int test_fts3_node_chunk_threshold = (4*1024)*4;
 
 /*
 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
-** and incremental merge operation that takes place. This is used for 
+** and incremental merge operation that takes place. This is used for
 ** debugging FTS only, it should not usually be turned on in production
 ** systems.
 */
@@ -172537,7 +178369,7 @@ struct Fts3SegReader {
   char *aDoclist;                 /* Pointer to doclist of current entry */
   int nDoclist;                   /* Size of doclist in current entry */
 
-  /* The following variables are used by fts3SegReaderNextDocid() to iterate 
+  /* The following variables are used by fts3SegReaderNextDocid() to iterate
   ** through the current doclist (aDoclist/nDoclist).
   */
   char *pOffsetList;
@@ -172582,11 +178414,11 @@ struct SegmentWriter {
 **   fts3NodeFree()
 **
 ** When a b+tree is written to the database (either as a result of a merge
-** or the pending-terms table being flushed), leaves are written into the 
+** or the pending-terms table being flushed), leaves are written into the
 ** database file as soon as they are completely populated. The interior of
 ** the tree is assembled in memory and written out only once all leaves have
 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
-** very large, meaning that the interior of the tree consumes relatively 
+** very large, meaning that the interior of the tree consumes relatively
 ** little memory.
 */
 struct SegmentNode {
@@ -172607,7 +178439,7 @@ struct SegmentNode {
 */
 #define SQL_DELETE_CONTENT             0
 #define SQL_IS_EMPTY                   1
-#define SQL_DELETE_ALL_CONTENT         2 
+#define SQL_DELETE_ALL_CONTENT         2
 #define SQL_DELETE_ALL_SEGMENTS        3
 #define SQL_DELETE_ALL_SEGDIR          4
 #define SQL_DELETE_ALL_DOCSIZE         5
@@ -172655,7 +178487,7 @@ struct SegmentNode {
 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
 **
 ** If argument apVal is not NULL, then it must point to an array with
-** at least as many entries as the requested statement has bound 
+** at least as many entries as the requested statement has bound
 ** parameters. The values are bound to the statements parameters before
 ** returning.
 */
@@ -172679,7 +178511,7 @@ static int fts3SqlStmt(
 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
 
-          /* Return segments in order from oldest to newest.*/ 
+          /* Return segments in order from oldest to newest.*/
 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
@@ -172710,13 +178542,15 @@ static int fts3SqlStmt(
 ** returns zero rows.  */
 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
          "  GROUP BY level HAVING cnt>=?"
-         "  ORDER BY (level %% 1024) ASC LIMIT 1",
+         "  ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1",
 
 /* Estimate the upper limit on the number of leaf nodes in a new segment
-** created by merging the oldest :2 segments from absolute level :1. See 
+** created by merging the oldest :2 segments from absolute level :1. See
 ** function sqlite3Fts3Incrmerge() for details.  */
 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
-         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
+         "  FROM (SELECT * FROM %Q.'%q_segdir' "
+         "        WHERE level = ? ORDER BY idx ASC LIMIT ?"
+         "  )",
 
 /* SQL_DELETE_SEGDIR_ENTRY
 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
@@ -172728,7 +178562,7 @@ static int fts3SqlStmt(
 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
 
 /* SQL_SELECT_SEGDIR
-**   Read a single entry from the %_segdir table. The entry from absolute 
+**   Read a single entry from the %_segdir table. The entry from absolute
 **   level :1 with index value :2.  */
 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
@@ -172752,7 +178586,7 @@ static int fts3SqlStmt(
 **   Return the largest relative level in the FTS index or indexes.  */
 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
 
-          /* Return segments in order from oldest to newest.*/ 
+          /* Return segments in order from oldest to newest.*/
 /* 37 */  "SELECT level, idx, end_block "
             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
             "ORDER BY level DESC, idx ASC",
@@ -172768,7 +178602,7 @@ static int fts3SqlStmt(
 
   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
-  
+
   pStmt = p->aStmt[eStmt];
   if( !pStmt ){
     int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
@@ -172873,7 +178707,7 @@ static void fts3SqlExec(
   sqlite3_stmt *pStmt;
   int rc;
   if( *pRC ) return;
-  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
+  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
   if( rc==SQLITE_OK ){
     sqlite3_step(pStmt);
     rc = sqlite3_reset(pStmt);
@@ -172883,22 +178717,22 @@ static void fts3SqlExec(
 
 
 /*
-** This function ensures that the caller has obtained an exclusive 
-** shared-cache table-lock on the %_segdir table. This is required before 
+** This function ensures that the caller has obtained an exclusive
+** shared-cache table-lock on the %_segdir table. This is required before
 ** writing data to the fts3 table. If this lock is not acquired first, then
 ** the caller may end up attempting to take this lock as part of committing
-** a transaction, causing SQLite to return SQLITE_LOCKED or 
+** a transaction, causing SQLite to return SQLITE_LOCKED or
 ** LOCKED_SHAREDCACHEto a COMMIT command.
 **
-** It is best to avoid this because if FTS3 returns any error when 
-** committing a transaction, the whole transaction will be rolled back. 
-** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
-** It can still happen if the user locks the underlying tables directly 
+** It is best to avoid this because if FTS3 returns any error when
+** committing a transaction, the whole transaction will be rolled back.
+** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
+** It can still happen if the user locks the underlying tables directly
 ** instead of accessing them via FTS.
 */
 static int fts3Writelock(Fts3Table *p){
   int rc = SQLITE_OK;
-  
+
   if( p->nPendingData==0 ){
     sqlite3_stmt *pStmt;
     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
@@ -172915,7 +178749,7 @@ static int fts3Writelock(Fts3Table *p){
 /*
 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
 ** Within each language id, a separate index is maintained to store the
-** document terms, and each configured prefix size (configured the FTS 
+** document terms, and each configured prefix size (configured the FTS
 ** "prefix=" option). And each index consists of multiple levels ("relative
 ** levels").
 **
@@ -172925,14 +178759,14 @@ static int fts3Writelock(Fts3Table *p){
 ** separate component values into the single 64-bit integer value that
 ** can be used to query the %_segdir table.
 **
-** Specifically, each language-id/index combination is allocated 1024 
+** Specifically, each language-id/index combination is allocated 1024
 ** 64-bit integer level values ("absolute levels"). The main terms index
 ** for language-id 0 is allocate values 0-1023. The first prefix index
 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
 ** Language 1 indexes are allocated immediately following language 0.
 **
 ** So, for a system with nPrefix prefix indexes configured, the block of
-** absolute levels that corresponds to language-id iLangid and index 
+** absolute levels that corresponds to language-id iLangid and index
 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
 */
 static sqlite3_int64 getAbsoluteLevel(
@@ -172953,7 +178787,7 @@ static sqlite3_int64 getAbsoluteLevel(
 /*
 ** Set *ppStmt to a statement handle that may be used to iterate through
 ** all rows in the %_segdir table, from oldest to newest. If successful,
-** return SQLITE_OK. If an error occurs while preparing the statement, 
+** return SQLITE_OK. If an error occurs while preparing the statement,
 ** return an SQLite error code.
 **
 ** There is only ever one instance of this SQL statement compiled for
@@ -172984,16 +178818,16 @@ SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
   if( iLevel<0 ){
     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
-    if( rc==SQLITE_OK ){ 
+    if( rc==SQLITE_OK ){
       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
-      sqlite3_bind_int64(pStmt, 2, 
+      sqlite3_bind_int64(pStmt, 2,
           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
       );
     }
   }else{
     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
-    if( rc==SQLITE_OK ){ 
+    if( rc==SQLITE_OK ){
       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
     }
   }
@@ -173071,7 +178905,7 @@ static int fts3PendingListAppend(
   assert( !p || p->iLastDocid<=iDocid );
 
   if( !p || p->iLastDocid!=iDocid ){
-    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
+    u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);
     if( p ){
       assert( p->nData<p->nSpace );
       assert( p->aData[p->nData]==0 );
@@ -173137,7 +178971,7 @@ static int fts3PendingTermsAddOne(
   }
   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
-      /* Malloc failed while inserting the new entry. This can only 
+      /* Malloc failed while inserting the new entry. This can only
       ** happen if there was no previous entry for this token.
       */
       assert( 0==fts3HashFind(pHash, zToken, nToken) );
@@ -173183,7 +179017,7 @@ static int fts3PendingTermsAdd(
   assert( pTokenizer && pModule );
 
   /* If the user has inserted a NULL value, this function may be called with
-  ** zText==0. In this case, add zero token entries to the hash table and 
+  ** zText==0. In this case, add zero token entries to the hash table and
   ** return early. */
   if( zText==0 ){
     *pnWord = 0;
@@ -173214,8 +179048,8 @@ static int fts3PendingTermsAdd(
     rc = fts3PendingTermsAddOne(
         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
     );
-    
-    /* Add the term to each of the prefix indexes that it is not too 
+
+    /* Add the term to each of the prefix indexes that it is not too
     ** short for. */
     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
       struct Fts3Index *pIndex = &p->aIndex[i];
@@ -173231,8 +179065,8 @@ static int fts3PendingTermsAdd(
   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
 }
 
-/* 
-** Calling this function indicates that subsequent calls to 
+/*
+** Calling this function indicates that subsequent calls to
 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
 ** contents of the document with docid iDocid.
 */
@@ -173251,10 +179085,10 @@ static int fts3PendingTermsDocid(
   ** buffer was half empty, that would let the less frequent terms
   ** generate longer doclists.
   */
-  if( iDocid<p->iPrevDocid 
+  if( iDocid<p->iPrevDocid
    || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
    || p->iPrevLangid!=iLangid
-   || p->nPendingData>p->nMaxPendingData 
+   || p->nPendingData>p->nMaxPendingData
   ){
     int rc = sqlite3Fts3PendingTermsFlush(p);
     if( rc!=SQLITE_OK ) return rc;
@@ -173266,7 +179100,7 @@ static int fts3PendingTermsDocid(
 }
 
 /*
-** Discard the contents of the pending-terms hash tables. 
+** Discard the contents of the pending-terms hash tables.
 */
 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
   int i;
@@ -173291,9 +179125,9 @@ SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
 */
 static int fts3InsertTerms(
-  Fts3Table *p, 
-  int iLangid, 
-  sqlite3_value **apVal, 
+  Fts3Table *p,
+  int iLangid,
+  sqlite3_value **apVal,
   u32 *aSz
 ){
   int i;                          /* Iterator variable */
@@ -173356,7 +179190,7 @@ static int fts3InsertData(
   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
   if( rc==SQLITE_OK && p->zLanguageid ){
     rc = sqlite3_bind_int(
-        pContentInsert, p->nColumn+2, 
+        pContentInsert, p->nColumn+2,
         sqlite3_value_int(apVal[p->nColumn+4])
     );
   }
@@ -173383,8 +179217,8 @@ static int fts3InsertData(
     if( rc!=SQLITE_OK ) return rc;
   }
 
-  /* Execute the statement to insert the record. Set *piDocid to the 
-  ** new docid value. 
+  /* Execute the statement to insert the record. Set *piDocid to the
+  ** new docid value.
   */
   sqlite3_step(pContentInsert);
   rc = sqlite3_reset(pContentInsert);
@@ -173434,7 +179268,7 @@ static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
 ** (an integer) of a row about to be deleted. Remove all terms from the
 ** full-text index.
 */
-static void fts3DeleteTerms( 
+static void fts3DeleteTerms(
   int *pRC,               /* Result code */
   Fts3Table *p,           /* The FTS table to delete from */
   sqlite3_value *pRowid,  /* The docid to be deleted */
@@ -173481,7 +179315,7 @@ static void fts3DeleteTerms(
 */
 static int fts3SegmentMerge(Fts3Table *, int, int, int);
 
-/* 
+/*
 ** This function allocates a new level iLevel index in the segdir table.
 ** Usually, indexes are allocated within a level sequentially starting
 ** with 0, so the allocated index is one greater than the value returned
@@ -173490,17 +179324,17 @@ static int fts3SegmentMerge(Fts3Table *, int, int, int);
 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
 **
 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
-** level, they are merged into a single level (iLevel+1) segment and the 
+** level, they are merged into a single level (iLevel+1) segment and the
 ** allocated index is 0.
 **
 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
 ** returned. Otherwise, an SQLite error code is returned.
 */
 static int fts3AllocateSegdirIdx(
-  Fts3Table *p, 
+  Fts3Table *p,
   int iLangid,                    /* Language id */
   int iIndex,                     /* Index for p->aIndex */
-  int iLevel, 
+  int iLevel,
   int *piIdx
 ){
   int rc;                         /* Return Code */
@@ -173528,7 +179362,7 @@ static int fts3AllocateSegdirIdx(
     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
     */
-    if( iNext>=FTS3_MERGE_COUNT ){
+    if( iNext>=MergeCount(p) ){
       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
       *piIdx = 0;
@@ -173548,7 +179382,7 @@ static int fts3AllocateSegdirIdx(
 ** This function reads data from a single row of the %_segments table. The
 ** specific row is identified by the iBlockid parameter. If paBlob is not
 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
-** with the contents of the blob stored in the "block" column of the 
+** with the contents of the blob stored in the "block" column of the
 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
 ** to the size of the blob in bytes before returning.
 **
@@ -173612,6 +179446,8 @@ SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
       }
       *paBlob = aByte;
     }
+  }else if( rc==SQLITE_ERROR ){
+    rc = FTS_CORRUPT_VTAB;
   }
 
   return rc;
@@ -173625,14 +179461,14 @@ SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
   sqlite3_blob_close(p->pSegments);
   p->pSegments = 0;
 }
-    
+
 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
   int nRead;                      /* Number of bytes to read */
   int rc;                         /* Return code */
 
   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
   rc = sqlite3_blob_read(
-      pReader->pBlob, 
+      pReader->pBlob,
       &pReader->aNode[pReader->nPopulate],
       nRead,
       pReader->nPopulate
@@ -173652,10 +179488,10 @@ static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
 
 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
   int rc = SQLITE_OK;
-  assert( !pReader->pBlob 
+  assert( !pReader->pBlob
        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
   );
-  while( pReader->pBlob && rc==SQLITE_OK 
+  while( pReader->pBlob && rc==SQLITE_OK
      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
   ){
     rc = fts3SegReaderIncrRead(pReader);
@@ -173681,7 +179517,7 @@ static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
 ** SQLITE_DONE. Otherwise, an SQLite error code.
 */
 static int fts3SegReaderNext(
-  Fts3Table *p, 
+  Fts3Table *p,
   Fts3SegReader *pReader,
   int bIncr
 ){
@@ -173721,7 +179557,7 @@ static int fts3SegReaderNext(
 
     fts3SegReaderSetEof(pReader);
 
-    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
+    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
     ** blocks have already been traversed.  */
 #ifdef CORRUPT_DB
     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
@@ -173731,7 +179567,7 @@ static int fts3SegReaderNext(
     }
 
     rc = sqlite3Fts3ReadBlock(
-        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
+        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
         (bIncr ? &pReader->nPopulate : 0)
     );
     if( rc!=SQLITE_OK ) return rc;
@@ -173747,14 +179583,14 @@ static int fts3SegReaderNext(
 
   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
   if( rc!=SQLITE_OK ) return rc;
-  
-  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
+
+  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
   ** safe (no risk of overread) even if the node data is corrupted. */
   pNext += fts3GetVarint32(pNext, &nPrefix);
   pNext += fts3GetVarint32(pNext, &nSuffix);
-  if( nSuffix<=0 
+  if( nSuffix<=0
    || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
-   || nPrefix>pReader->nTermAlloc
+   || nPrefix>pReader->nTerm
   ){
     return FTS_CORRUPT_VTAB;
   }
@@ -173783,11 +179619,12 @@ static int fts3SegReaderNext(
   pReader->pOffsetList = 0;
 
   /* Check that the doclist does not appear to extend past the end of the
-  ** b-tree node. And that the final byte of the doclist is 0x00. If either 
+  ** b-tree node. And that the final byte of the doclist is 0x00. If either
   ** of these statements is untrue, then the data structure is corrupt.
   */
   if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
+   || pReader->nDoclist==0
   ){
     return FTS_CORRUPT_VTAB;
   }
@@ -173807,7 +179644,7 @@ static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
     pReader->iDocid = 0;
     pReader->nOffsetList = 0;
     sqlite3Fts3DoclistPrev(0,
-        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
+        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
         &pReader->iDocid, &pReader->nOffsetList, &bEof
     );
   }else{
@@ -173823,8 +179660,8 @@ static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
 /*
 ** Advance the SegReader to point to the next docid in the doclist
 ** associated with the current term.
-** 
-** If arguments ppOffsetList and pnOffsetList are not NULL, then 
+**
+** If arguments ppOffsetList and pnOffsetList are not NULL, then
 ** *ppOffsetList is set to point to the first column-offset list
 ** in the doclist entry (i.e. immediately past the docid varint).
 ** *pnOffsetList is set to the length of the set of column-offset
@@ -173867,22 +179704,22 @@ static int fts3SegReaderNextDocid(
     ** following block advances it to point one byte past the end of
     ** the same offset list. */
     while( 1 ){
-  
+
       /* The following line of code (and the "p++" below the while() loop) is
-      ** normally all that is required to move pointer p to the desired 
+      ** normally all that is required to move pointer p to the desired
       ** position. The exception is if this node is being loaded from disk
       ** incrementally and pointer "p" now points to the first byte past
       ** the populated part of pReader->aNode[].
       */
       while( *p | c ) c = *p++ & 0x80;
       assert( *p==0 );
-  
+
       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
       rc = fts3SegReaderIncrRead(pReader);
       if( rc!=SQLITE_OK ) return rc;
     }
     p++;
-  
+
     /* If required, populate the output variables with a pointer to and the
     ** size of the previous offset-list.
     */
@@ -173893,7 +179730,7 @@ static int fts3SegReaderNextDocid(
 
     /* List may have been edited in place by fts3EvalNearTrim() */
     while( p<pEnd && *p==0 ) p++;
-  
+
     /* If there are no more entries in the doclist, set pOffsetList to
     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
     ** Fts3SegReader.pOffsetList to point to the next offset list before
@@ -173904,23 +179741,23 @@ static int fts3SegReaderNextDocid(
     }else{
       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
       if( rc==SQLITE_OK ){
-        sqlite3_int64 iDelta;
-        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
+        u64 iDelta;
+        pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
         if( pTab->bDescIdx ){
-          pReader->iDocid -= iDelta;
+          pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
         }else{
-          pReader->iDocid += iDelta;
+          pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
         }
       }
     }
   }
 
-  return SQLITE_OK;
+  return rc;
 }
 
 
 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
-  Fts3Cursor *pCsr, 
+  Fts3Cursor *pCsr,
   Fts3MultiSegReader *pMsr,
   int *pnOvfl
 ){
@@ -173935,8 +179772,8 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
 
   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
     Fts3SegReader *pReader = pMsr->apSegment[ii];
-    if( !fts3SegReaderIsPending(pReader) 
-     && !fts3SegReaderIsRootOnly(pReader) 
+    if( !fts3SegReaderIsPending(pReader)
+     && !fts3SegReaderIsRootOnly(pReader)
     ){
       sqlite3_int64 jj;
       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
@@ -173954,7 +179791,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
 }
 
 /*
-** Free all allocations associated with the iterator passed as the 
+** Free all allocations associated with the iterator passed as the
 ** second argument.
 */
 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
@@ -174113,7 +179950,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
 
   }else{
     /* The query is a simple term lookup that matches at most one term in
-    ** the index. All that is required is a straight hash-lookup. 
+    ** the index. All that is required is a straight hash-lookup.
     **
     ** Because the stack address of pE may be accessed via the aElem pointer
     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
@@ -174148,7 +179985,7 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
 }
 
 /*
-** Compare the entries pointed to by two Fts3SegReader structures. 
+** Compare the entries pointed to by two Fts3SegReader structures.
 ** Comparison is as follows:
 **
 **   1) EOF is greater than not EOF.
@@ -174219,7 +180056,7 @@ static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
 
 /*
 ** Compare the term that the Fts3SegReader object passed as the first argument
-** points to with the term specified by arguments zTerm and nTerm. 
+** points to with the term specified by arguments zTerm and nTerm.
 **
 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
@@ -174280,7 +180117,7 @@ static void fts3SegReaderSort(
 #endif
 }
 
-/* 
+/*
 ** Insert a record into the %_segments table.
 */
 static int fts3WriteSegment(
@@ -174322,7 +180159,7 @@ SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
   return rc;
 }
 
-/* 
+/*
 ** Insert a record into the %_segdir table.
 */
 static int fts3WriteSegdir(
@@ -174360,7 +180197,7 @@ static int fts3WriteSegdir(
 
 /*
 ** Return the size of the common prefix (if any) shared by zPrev and
-** zNext, in bytes. For example, 
+** zNext, in bytes. For example,
 **
 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
@@ -174384,7 +180221,7 @@ static int fts3PrefixCompress(
 */
 static int fts3NodeAddTerm(
   Fts3Table *p,                   /* Virtual table handle */
-  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
+  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
   const char *zTerm,              /* Pointer to buffer containing term */
   int nTerm                       /* Size of term in bytes */
@@ -174393,7 +180230,7 @@ static int fts3NodeAddTerm(
   int rc;
   SegmentNode *pNew;
 
-  /* First try to append the term to the current node. Return early if 
+  /* First try to append the term to the current node. Return early if
   ** this is possible.
   */
   if( pTree ){
@@ -174405,6 +180242,11 @@ static int fts3NodeAddTerm(
     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
     nSuffix = nTerm-nPrefix;
 
+    /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
+    ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
+    ** compared with BINARY collation. This indicates corruption.  */
+    if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
+
     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
     if( nReq<=p->nNodeSize || !pTree->zTerm ){
 
@@ -174413,8 +180255,8 @@ static int fts3NodeAddTerm(
         ** and the static node buffer (p->nNodeSize bytes) is not large
         ** enough. Use a separately malloced buffer instead This wastes
         ** p->nNodeSize bytes, but since this scenario only comes about when
-        ** the database contain two terms that share a prefix of almost 2KB, 
-        ** this is not expected to be a serious problem. 
+        ** the database contain two terms that share a prefix of almost 2KB,
+        ** this is not expected to be a serious problem.
         */
         assert( pTree->aData==(char *)&pTree[1] );
         pTree->aData = (char *)sqlite3_malloc(nReq);
@@ -174458,7 +180300,7 @@ static int fts3NodeAddTerm(
   ** If this is the first node in the tree, the term is added to it.
   **
   ** Otherwise, the term is not added to the new node, it is left empty for
-  ** now. Instead, the term is inserted into the parent of pTree. If pTree 
+  ** now. Instead, the term is inserted into the parent of pTree. If pTree
   ** has no parent, one is created here.
   */
   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
@@ -174483,7 +180325,7 @@ static int fts3NodeAddTerm(
     pTree->zMalloc = 0;
   }else{
     pNew->pLeftmost = pNew;
-    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
+    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
   }
 
   *ppTree = pNew;
@@ -174494,8 +180336,8 @@ static int fts3NodeAddTerm(
 ** Helper function for fts3NodeWrite().
 */
 static int fts3TreeFinishNode(
-  SegmentNode *pTree, 
-  int iHeight, 
+  SegmentNode *pTree,
+  int iHeight,
   sqlite3_int64 iLeftChild
 ){
   int nStart;
@@ -174508,15 +180350,15 @@ static int fts3TreeFinishNode(
 
 /*
 ** Write the buffer for the segment node pTree and all of its peers to the
-** database. Then call this function recursively to write the parent of 
-** pTree and its peers to the database. 
+** database. Then call this function recursively to write the parent of
+** pTree and its peers to the database.
 **
 ** Except, if pTree is a root node, do not write it to the database. Instead,
 ** set output variables *paRoot and *pnRoot to contain the root node.
 **
 ** If successful, SQLITE_OK is returned and output variable *piLast is
 ** set to the largest blockid written to the database (or zero if no
-** blocks were written to the db). Otherwise, an SQLite error code is 
+** blocks were written to the db). Otherwise, an SQLite error code is
 ** returned.
 */
 static int fts3NodeWrite(
@@ -174544,7 +180386,7 @@ static int fts3NodeWrite(
     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
       int nWrite = pIter->nData - nStart;
-  
+
       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
       iNextFree++;
       iNextLeaf += (pIter->nEntry+1);
@@ -174590,7 +180432,7 @@ static void fts3NodeFree(SegmentNode *pTree){
 */
 static int fts3SegWriterAdd(
   Fts3Table *p,                   /* Virtual table handle */
-  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
+  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
   int isCopyTerm,                 /* True if buffer zTerm must be copied */
   const char *zTerm,              /* Pointer to buffer containing term */
   int nTerm,                      /* Size of term in bytes */
@@ -174633,7 +180475,7 @@ static int fts3SegWriterAdd(
   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
   nSuffix = nTerm-nPrefix;
 
-  /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of 
+  /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
   ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
   ** compared with BINARY collation. This indicates corruption.  */
   if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
@@ -174649,6 +180491,7 @@ static int fts3SegWriterAdd(
     int rc;
 
     /* The current leaf node is full. Write it out to the database. */
+    if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
     if( rc!=SQLITE_OK ) return rc;
     p->nLeafAdd++;
@@ -174698,9 +180541,11 @@ static int fts3SegWriterAdd(
   /* Append the prefix-compressed term and doclist to the buffer. */
   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
+  assert( nSuffix>0 );
   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
   nData += nSuffix;
   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
+  assert( nDoclist>0 );
   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
   pWriter->nData = nData + nDoclist;
 
@@ -174720,6 +180565,7 @@ static int fts3SegWriterAdd(
       pWriter->zTerm = zNew;
     }
     assert( pWriter->zTerm==pWriter->zMalloc );
+    assert( nTerm>0 );
     memcpy(pWriter->zTerm, zTerm, nTerm);
   }else{
     pWriter->zTerm = (char *)zTerm;
@@ -174755,12 +180601,12 @@ static int fts3SegWriterFlush(
           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
     }
     if( rc==SQLITE_OK ){
-      rc = fts3WriteSegdir(p, iLevel, iIdx, 
+      rc = fts3WriteSegdir(p, iLevel, iIdx,
           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
     }
   }else{
     /* The entire tree fits on the root node. Write it to the segdir table. */
-    rc = fts3WriteSegdir(p, iLevel, iIdx, 
+    rc = fts3WriteSegdir(p, iLevel, iIdx,
         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
   }
   p->nLeafAdd++;
@@ -174768,7 +180614,7 @@ static int fts3SegWriterFlush(
 }
 
 /*
-** Release all memory held by the SegmentWriter object passed as the 
+** Release all memory held by the SegmentWriter object passed as the
 ** first argument.
 */
 static void fts3SegWriterFree(SegmentWriter *pWriter){
@@ -174818,9 +180664,9 @@ static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
 ** Return SQLITE_OK if successful, or an SQLite error code if not.
 */
 static int fts3SegmentMaxLevel(
-  Fts3Table *p, 
+  Fts3Table *p,
   int iLangid,
-  int iIndex, 
+  int iIndex,
   sqlite3_int64 *pnMax
 ){
   sqlite3_stmt *pStmt;
@@ -174836,7 +180682,7 @@ static int fts3SegmentMaxLevel(
   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   if( rc!=SQLITE_OK ) return rc;
   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
-  sqlite3_bind_int64(pStmt, 2, 
+  sqlite3_bind_int64(pStmt, 2,
       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
   );
   if( SQLITE_ROW==sqlite3_step(pStmt) ){
@@ -174865,8 +180711,8 @@ static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
   if( rc!=SQLITE_OK ) return rc;
   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
-  sqlite3_bind_int64(pStmt, 2, 
-      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
+  sqlite3_bind_int64(pStmt, 2,
+      (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
   );
 
   *pbMax = 0;
@@ -174903,9 +180749,9 @@ static int fts3DeleteSegment(
 ** This function is used after merging multiple segments into a single large
 ** segment to delete the old, now redundant, segment b-trees. Specifically,
 ** it:
-** 
-**   1) Deletes all %_segments entries for the segments associated with 
-**      each of the SegReader objects in the array passed as the third 
+**
+**   1) Deletes all %_segments entries for the segments associated with
+**      each of the SegReader objects in the array passed as the third
 **      argument, and
 **
 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
@@ -174937,7 +180783,7 @@ static int fts3DeleteSegdir(
     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
     if( rc==SQLITE_OK ){
       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
-      sqlite3_bind_int64(pDelete, 2, 
+      sqlite3_bind_int64(pDelete, 2,
           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
       );
     }
@@ -174959,7 +180805,7 @@ static int fts3DeleteSegdir(
 }
 
 /*
-** When this function is called, buffer *ppList (size *pnList bytes) contains 
+** When this function is called, buffer *ppList (size *pnList bytes) contains
 ** a position list that may (or may not) feature multiple columns. This
 ** function adjusts the pointer *ppList and the length *pnList so that they
 ** identify the subset of the position list that corresponds to column iCol.
@@ -174986,7 +180832,7 @@ static void fts3ColumnFilter(
   while( 1 ){
     char c = 0;
     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
-  
+
     if( iCol==iCurrent ){
       nList = (int)(p - pList);
       break;
@@ -175028,6 +180874,7 @@ static int fts3MsrBufferData(
     pMsr->aBuffer = pNew;
   }
 
+  assert( nList>0 );
   memcpy(pMsr->aBuffer, pList, nList);
   return SQLITE_OK;
 }
@@ -175066,7 +180913,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
 
       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
       j = 1;
-      while( rc==SQLITE_OK 
+      while( rc==SQLITE_OK
         && j<nMerge
         && apSegment[j]->pOffsetList
         && apSegment[j]->iDocid==iDocid
@@ -175109,7 +180956,7 @@ static int fts3SegReaderStart(
   int i;
   int nSeg = pCsr->nSegment;
 
-  /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
+  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
   ** for, then advance each segment iterator until it points to a term of
   ** equal or greater value than the specified term. This prevents many
   ** unnecessary merge/sort operations for the case where single segment
@@ -175193,7 +181040,7 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
 **   sqlite3Fts3SegReaderStart()
 **   sqlite3Fts3SegReaderStep()
 **
-** then the entire doclist for the term is available in 
+** then the entire doclist for the term is available in
 ** MultiSegReader.aDoclist/nDoclist.
 */
 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
@@ -175215,6 +181062,19 @@ SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
   return SQLITE_OK;
 }
 
+static int fts3GrowSegReaderBuffer(Fts3MultiSegReader *pCsr, int nReq){
+  if( nReq>pCsr->nBuffer ){
+    char *aNew;
+    pCsr->nBuffer = nReq*2;
+    aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
+    if( !aNew ){
+      return SQLITE_NOMEM;
+    }
+    pCsr->aBuffer = aNew;
+  }
+  return SQLITE_OK;
+}
+
 
 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   Fts3Table *p,                   /* Virtual table handle */
@@ -175241,9 +181101,9 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
   do {
     int nMerge;
     int i;
-  
+
     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
-    ** forward. Then sort the list in order of current term again.  
+    ** forward. Then sort the list in order of current term again.
     */
     for(i=0; i<pCsr->nAdvance; i++){
       Fts3SegReader *pSeg = apSegment[i];
@@ -175265,34 +181125,34 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
     pCsr->zTerm = apSegment[0]->zTerm;
 
     /* If this is a prefix-search, and if the term that apSegment[0] points
-    ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
+    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
     ** required callbacks have been made. In this case exit early.
     **
     ** Similarly, if this is a search for an exact match, and the first term
     ** of segment apSegment[0] is not a match, exit early.
     */
     if( pFilter->zTerm && !isScan ){
-      if( pCsr->nTerm<pFilter->nTerm 
+      if( pCsr->nTerm<pFilter->nTerm
        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
-       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
+       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
       ){
         break;
       }
     }
 
     nMerge = 1;
-    while( nMerge<nSegment 
+    while( nMerge<nSegment
         && apSegment[nMerge]->aNode
-        && apSegment[nMerge]->nTerm==pCsr->nTerm 
+        && apSegment[nMerge]->nTerm==pCsr->nTerm
         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
     ){
       nMerge++;
     }
 
     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
-    if( nMerge==1 
-     && !isIgnoreEmpty 
-     && !isFirst 
+    if( nMerge==1
+     && !isIgnoreEmpty
+     && !isFirst
      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
     ){
       pCsr->nDoclist = apSegment[0]->nDoclist;
@@ -175337,34 +181197,26 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
 
         if( !isIgnoreEmpty || nList>0 ){
 
-          /* Calculate the 'docid' delta value to write into the merged 
+          /* Calculate the 'docid' delta value to write into the merged
           ** doclist. */
           sqlite3_int64 iDelta;
           if( p->bDescIdx && nDoclist>0 ){
-            iDelta = iPrev - iDocid;
+            if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
+            iDelta = (i64)((u64)iPrev - (u64)iDocid);
           }else{
-            iDelta = iDocid - iPrev;
-          }
-          if( iDelta<=0 && (nDoclist>0 || iDelta!=iDocid) ){
-            return FTS_CORRUPT_VTAB;
+            if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
+            iDelta = (i64)((u64)iDocid - (u64)iPrev);
           }
-          assert( nDoclist>0 || iDelta==iDocid );
 
           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
-          if( nDoclist+nByte>pCsr->nBuffer ){
-            char *aNew;
-            pCsr->nBuffer = (nDoclist+nByte)*2;
-            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
-            if( !aNew ){
-              return SQLITE_NOMEM;
-            }
-            pCsr->aBuffer = aNew;
-          }
+
+          rc = fts3GrowSegReaderBuffer(pCsr, nByte+nDoclist);
+          if( rc ) return rc;
 
           if( isFirst ){
             char *a = &pCsr->aBuffer[nDoclist];
             int nWrite;
-           
+
             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
             if( nWrite ){
               iPrev = iDocid;
@@ -175384,6 +181236,9 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
       }
       if( nDoclist>0 ){
+        rc = fts3GrowSegReaderBuffer(pCsr, nDoclist+FTS3_NODE_PADDING);
+        if( rc ) return rc;
+        memset(&pCsr->aBuffer[nDoclist], 0, FTS3_NODE_PADDING);
         pCsr->aDoclist = pCsr->aBuffer;
         pCsr->nDoclist = nDoclist;
         rc = SQLITE_ROW;
@@ -175414,18 +181269,18 @@ SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
 }
 
 /*
-** Decode the "end_block" field, selected by column iCol of the SELECT 
-** statement passed as the first argument. 
+** Decode the "end_block" field, selected by column iCol of the SELECT
+** statement passed as the first argument.
 **
 ** The "end_block" field may contain either an integer, or a text field
-** containing the text representation of two non-negative integers separated 
-** by one or more space (0x20) characters. In the first case, set *piEndBlock 
-** to the integer value and *pnByte to zero before returning. In the second, 
+** containing the text representation of two non-negative integers separated
+** by one or more space (0x20) characters. In the first case, set *piEndBlock
+** to the integer value and *pnByte to zero before returning. In the second,
 ** set *piEndBlock to the first value and *pnByte to the second.
 */
 static void fts3ReadEndBlockField(
-  sqlite3_stmt *pStmt, 
-  int iCol, 
+  sqlite3_stmt *pStmt,
+  int iCol,
   i64 *piEndBlock,
   i64 *pnByte
 ){
@@ -175433,11 +181288,11 @@ static void fts3ReadEndBlockField(
   if( zText ){
     int i;
     int iMul = 1;
-    i64 iVal = 0;
+    u64 iVal = 0;
     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
       iVal = iVal*10 + (zText[i] - '0');
     }
-    *piEndBlock = iVal;
+    *piEndBlock = (i64)iVal;
     while( zText[i]==' ' ) i++;
     iVal = 0;
     if( zText[i]=='-' ){
@@ -175447,7 +181302,7 @@ static void fts3ReadEndBlockField(
     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
       iVal = iVal*10 + (zText[i] - '0');
     }
-    *pnByte = (iVal * (i64)iMul);
+    *pnByte = ((i64)iVal * (i64)iMul);
   }
 }
 
@@ -175471,10 +181326,10 @@ static int fts3PromoteSegments(
     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
     i64 nLimit = (nByte*3)/2;
 
-    /* Loop through all entries in the %_segdir table corresponding to 
+    /* Loop through all entries in the %_segdir table corresponding to
     ** segments in this index on levels greater than iAbsLevel. If there is
-    ** at least one such segment, and it is possible to determine that all 
-    ** such segments are smaller than nLimit bytes in size, they will be 
+    ** at least one such segment, and it is possible to determine that all
+    ** such segments are smaller than nLimit bytes in size, they will be
     ** promoted to level iAbsLevel.  */
     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
     sqlite3_bind_int64(pRange, 2, iLast);
@@ -175482,7 +181337,7 @@ static int fts3PromoteSegments(
       i64 nSize = 0, dummy;
       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
       if( nSize<=0 || nSize>nLimit ){
-        /* If nSize==0, then the %_segdir.end_block field does not not 
+        /* If nSize==0, then the %_segdir.end_block field does not not
         ** contain a size value. This happens if it was written by an
         ** old version of FTS. In this case it is not possible to determine
         ** the size of the segment, and so segment promotion does not
@@ -175548,18 +181403,18 @@ static int fts3PromoteSegments(
 }
 
 /*
-** Merge all level iLevel segments in the database into a single 
+** Merge all level iLevel segments in the database into a single
 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
-** single segment with a level equal to the numerically largest level 
+** single segment with a level equal to the numerically largest level
 ** currently present in the database.
 **
 ** If this function is called with iLevel<0, but there is only one
-** segment in the database, SQLITE_DONE is returned immediately. 
-** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
+** segment in the database, SQLITE_DONE is returned immediately.
+** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
 ** an SQLite error code is returned.
 */
 static int fts3SegmentMerge(
-  Fts3Table *p, 
+  Fts3Table *p,
   int iLangid,                    /* Language id to merge */
   int iIndex,                     /* Index in p->aIndex[] to merge */
   int iLevel                      /* Level to merge */
@@ -175603,7 +181458,7 @@ static int fts3SegmentMerge(
   }else{
     /* This call is to merge all segments at level iLevel. find the next
     ** available segment index at level iLevel+1. The call to
-    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
+    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
     ** a single iLevel+2 segment if necessary.  */
     assert( FTS3_SEGCURSOR_PENDING==-1 );
     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
@@ -175614,8 +181469,8 @@ static int fts3SegmentMerge(
 
   assert( csr.nSegment>0 );
   assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
-  assert_fts3_nc( 
-    iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) 
+  assert_fts3_nc(
+    iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
   );
 
   memset(&filter, 0, sizeof(Fts3SegFilter));
@@ -175626,11 +181481,11 @@ static int fts3SegmentMerge(
   while( SQLITE_OK==rc ){
     rc = sqlite3Fts3SegReaderStep(p, &csr);
     if( rc!=SQLITE_ROW ) break;
-    rc = fts3SegWriterAdd(p, &pWriter, 1, 
+    rc = fts3SegWriterAdd(p, &pWriter, 1,
         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
   }
   if( rc!=SQLITE_OK ) goto finished;
-  assert( pWriter || bIgnoreEmpty );
+  assert_fts3_nc( pWriter || bIgnoreEmpty );
 
   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
     rc = fts3DeleteSegdir(
@@ -175654,13 +181509,13 @@ static int fts3SegmentMerge(
 }
 
 
-/* 
-** Flush the contents of pendingTerms to level 0 segments. 
+/*
+** Flush the contents of pendingTerms to level 0 segments.
 */
 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
   int rc = SQLITE_OK;
   int i;
-        
+
   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
@@ -175764,7 +181619,7 @@ static void fts3InsertDocsize(
 /*
 ** Record 0 of the %_stat table contains a blob consisting of N varints,
 ** where N is the number of user defined columns in the fts3 table plus
-** two. If nCol is the number of user defined columns, then values of the 
+** two. If nCol is the number of user defined columns, then values of the
 ** varints are set as follows:
 **
 **   Varint 0:       Total number of rows in the table.
@@ -175849,7 +181704,7 @@ static void fts3UpdateDocTotals(
 }
 
 /*
-** Merge the entire database so that there is one segment for each 
+** Merge the entire database so that there is one segment for each
 ** iIndex/iLangid combination.
 */
 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
@@ -175857,7 +181712,10 @@ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   int rc;
   sqlite3_stmt *pAllLangid = 0;
 
-  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
+  rc = sqlite3Fts3PendingTermsFlush(p);
+  if( rc==SQLITE_OK ){
+    rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
+  }
   if( rc==SQLITE_OK ){
     int rc2;
     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
@@ -175878,7 +181736,6 @@ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
   }
 
   sqlite3Fts3SegmentsClose(p);
-  sqlite3Fts3PendingTermsClear(p);
 
   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
 }
@@ -175888,7 +181745,7 @@ static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
 **
 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
 **
-** The entire FTS index is discarded and rebuilt. If the table is one 
+** The entire FTS index is discarded and rebuilt. If the table is one
 ** created using the content=xxx option, then the new index is based on
 ** the current contents of the xxx table. Otherwise, it is rebuilt based
 ** on the contents of the %_content table.
@@ -175968,9 +181825,9 @@ static int fts3DoRebuild(Fts3Table *p){
 
 
 /*
-** This function opens a cursor used to read the input data for an 
+** This function opens a cursor used to read the input data for an
 ** incremental merge operation. Specifically, it opens a cursor to scan
-** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
+** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
 ** level iAbsLevel.
 */
 static int fts3IncrmergeCsr(
@@ -175980,7 +181837,7 @@ static int fts3IncrmergeCsr(
   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
 ){
   int rc;                         /* Return Code */
-  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
+  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
   sqlite3_int64 nByte;            /* Bytes allocated at pCsr->apSegment[] */
 
   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
@@ -176035,7 +181892,7 @@ struct Blob {
 };
 
 /*
-** This structure is used to build up buffers containing segment b-tree 
+** This structure is used to build up buffers containing segment b-tree
 ** nodes (blocks).
 */
 struct NodeWriter {
@@ -176104,12 +181961,12 @@ static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
 
 /*
 ** Attempt to advance the node-reader object passed as the first argument to
-** the next entry on the node. 
+** the next entry on the node.
 **
-** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
+** Return an error code if an error occurs (SQLITE_NOMEM is possible).
 ** Otherwise return SQLITE_OK. If there is no next entry on the node
 ** (e.g. because the current entry is the last) set NodeReader->aNode to
-** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
+** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
 ** variables for the new entry.
 */
 static int nodeReaderNext(NodeReader *p){
@@ -176162,7 +182019,7 @@ static void nodeReaderRelease(NodeReader *p){
 /*
 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
 **
-** If successful, SQLITE_OK is returned and the NodeReader object set to 
+** If successful, SQLITE_OK is returned and the NodeReader object set to
 ** point to the first entry on the node (if any). Otherwise, an SQLite
 ** error code is returned.
 */
@@ -176211,17 +182068,18 @@ static int fts3IncrmergePush(
     int nSpace;
 
     /* Figure out how much space the key will consume if it is written to
-    ** the current node of layer iLayer. Due to the prefix compression, 
+    ** the current node of layer iLayer. Due to the prefix compression,
     ** the space required changes depending on which node the key is to
     ** be added to.  */
     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
     nSuffix = nTerm - nPrefix;
+    if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
     nSpace  = sqlite3Fts3VarintLen(nPrefix);
     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
 
-    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
+    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
       /* If the current node of layer iLayer contains zero keys, or if adding
-      ** the key to it will not cause it to grow to larger than nNodeSize 
+      ** the key to it will not cause it to grow to larger than nNodeSize
       ** bytes in size, write the key here.  */
 
       Blob *pBlk = &pNode->block;
@@ -176277,12 +182135,12 @@ static int fts3IncrmergePush(
 ** A node header is a single 0x00 byte for a leaf node, or a height varint
 ** followed by the left-hand-child varint for an internal node.
 **
-** The term to be appended is passed via arguments zTerm/nTerm. For a 
+** The term to be appended is passed via arguments zTerm/nTerm. For a
 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
 ** node, both aDoclist and nDoclist must be passed 0.
 **
 ** If the size of the value in blob pPrev is zero, then this is the first
-** term written to the node. Otherwise, pPrev contains a copy of the 
+** term written to the node. Otherwise, pPrev contains a copy of the
 ** previous term. Before this function returns, it is updated to contain a
 ** copy of zTerm/nTerm.
 **
@@ -176299,7 +182157,7 @@ static int fts3AppendToNode(
   const char *zTerm,              /* New term to write */
   int nTerm,                      /* Size of zTerm in bytes */
   const char *aDoclist,           /* Doclist (or NULL) to write */
-  int nDoclist                    /* Size of aDoclist in bytes */ 
+  int nDoclist                    /* Size of aDoclist in bytes */
 ){
   int rc = SQLITE_OK;             /* Return code */
   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
@@ -176374,7 +182232,7 @@ static int fts3IncrmergeAppend(
     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
     pWriter->nWork++;
 
-    /* Add the current term to the parent node. The term added to the 
+    /* Add the current term to the parent node. The term added to the
     ** parent must:
     **
     **   a) be greater than the largest term on the leaf node just written
@@ -176439,7 +182297,7 @@ static void fts3IncrmergeRelease(
   NodeWriter *pRoot;              /* NodeWriter for root node */
   int rc = *pRc;                  /* Error code */
 
-  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
+  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
   ** root node. If the segment fits entirely on a single leaf node, iRoot
   ** will be set to 0. If the root node is the parent of the leaves, iRoot
   ** will be 1. And so on.  */
@@ -176457,17 +182315,17 @@ static void fts3IncrmergeRelease(
 
   /* The entire output segment fits on a single node. Normally, this means
   ** the node would be stored as a blob in the "root" column of the %_segdir
-  ** table. However, this is not permitted in this case. The problem is that 
-  ** space has already been reserved in the %_segments table, and so the 
-  ** start_block and end_block fields of the %_segdir table must be populated. 
-  ** And, by design or by accident, released versions of FTS cannot handle 
+  ** table. However, this is not permitted in this case. The problem is that
+  ** space has already been reserved in the %_segments table, and so the
+  ** start_block and end_block fields of the %_segdir table must be populated.
+  ** And, by design or by accident, released versions of FTS cannot handle
   ** segments that fit entirely on the root node with start_block!=0.
   **
-  ** Instead, create a synthetic root node that contains nothing but a 
+  ** Instead, create a synthetic root node that contains nothing but a
   ** pointer to the single content node. So that the segment consists of a
   ** single leaf and a single interior (root) node.
   **
-  ** Todo: Better might be to defer allocating space in the %_segments 
+  ** Todo: Better might be to defer allocating space in the %_segments
   ** table until we are sure it is needed.
   */
   if( iRoot==0 ){
@@ -176495,7 +182353,7 @@ static void fts3IncrmergeRelease(
 
   /* Write the %_segdir record. */
   if( rc==SQLITE_OK ){
-    rc = fts3WriteSegdir(p, 
+    rc = fts3WriteSegdir(p,
         pWriter->iAbsLevel+1,               /* level */
         pWriter->iIdx,                      /* idx */
         pWriter->iStart,                    /* start_block */
@@ -176534,11 +182392,11 @@ static int fts3TermCmp(
 
 
 /*
-** Query to see if the entry in the %_segments table with blockid iEnd is 
+** Query to see if the entry in the %_segments table with blockid iEnd is
 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
-** returning. Otherwise, set *pbRes to 0. 
+** returning. Otherwise, set *pbRes to 0.
 **
-** Or, if an error occurs while querying the database, return an SQLite 
+** Or, if an error occurs while querying the database, return an SQLite
 ** error code. The final value of *pbRes is undefined in this case.
 **
 ** This is used to test if a segment is an "appendable" segment. If it
@@ -176556,14 +182414,14 @@ static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
     rc = sqlite3_reset(pCheck);
   }
-  
+
   *pbRes = bRes;
   return rc;
 }
 
 /*
 ** This function is called when initializing an incremental-merge operation.
-** It checks if the existing segment with index value iIdx at absolute level 
+** It checks if the existing segment with index value iIdx at absolute level
 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
 ** merge-writer object *pWriter is initialized to write to it.
 **
@@ -176572,7 +182430,7 @@ static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
 **   * It was initially created as an appendable segment (with all required
 **     space pre-allocated), and
 **
-**   * The first key read from the input (arguments zKey and nKey) is 
+**   * The first key read from the input (arguments zKey and nKey) is
 **     greater than the largest key currently stored in the potential
 **     output segment.
 */
@@ -176610,6 +182468,10 @@ static int fts3IncrmergeLoad(
       pWriter->bNoLeafData = (pWriter->nLeafData==0);
       nRoot = sqlite3_column_bytes(pSelect, 4);
       aRoot = sqlite3_column_blob(pSelect, 4);
+      if( aRoot==0 ){
+        sqlite3_reset(pSelect);
+        return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
+      }
     }else{
       return sqlite3_reset(pSelect);
     }
@@ -176645,6 +182507,10 @@ static int fts3IncrmergeLoad(
       int i;
       int nHeight = (int)aRoot[0];
       NodeWriter *pNode;
+      if( nHeight<1 || nHeight>=FTS_MAX_APPENDABLE_HEIGHT ){
+        sqlite3_reset(pSelect);
+        return FTS_CORRUPT_VTAB;
+      }
 
       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
       pWriter->iStart = iStart;
@@ -176658,7 +182524,7 @@ static int fts3IncrmergeLoad(
 
       pNode = &pWriter->aNodeWriter[nHeight];
       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
-      blobGrowBuffer(&pNode->block, 
+      blobGrowBuffer(&pNode->block,
           MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
       );
       if( rc==SQLITE_OK ){
@@ -176684,7 +182550,7 @@ static int fts3IncrmergeLoad(
               pNode = &pWriter->aNodeWriter[i-1];
               pNode->iBlock = reader.iChild;
               rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
-              blobGrowBuffer(&pNode->block, 
+              blobGrowBuffer(&pNode->block,
                   MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
               );
               if( rc==SQLITE_OK ){
@@ -176710,13 +182576,13 @@ static int fts3IncrmergeLoad(
 /*
 ** Determine the largest segment index value that exists within absolute
 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
-** one before returning SQLITE_OK. Or, if there are no segments at all 
+** one before returning SQLITE_OK. Or, if there are no segments at all
 ** within level iAbsLevel, set *piIdx to zero.
 **
 ** If an error occurs, return an SQLite error code. The final value of
 ** *piIdx is undefined in this case.
 */
-static int fts3IncrmergeOutputIdx( 
+static int fts3IncrmergeOutputIdx(
   Fts3Table *p,                   /* FTS Table handle */
   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
@@ -176735,7 +182601,7 @@ static int fts3IncrmergeOutputIdx(
   return rc;
 }
 
-/* 
+/*
 ** Allocate an appendable output segment on absolute level iAbsLevel+1
 ** with idx value iIdx.
 **
@@ -176749,7 +182615,7 @@ static int fts3IncrmergeOutputIdx(
 ** When an appendable segment is allocated, it is estimated that the
 ** maximum number of leaf blocks that may be required is the sum of the
 ** number of leaf blocks consumed by the input segments, plus the number
-** of input segments, multiplied by two. This value is stored in stack 
+** of input segments, multiplied by two. This value is stored in stack
 ** variable nLeafEst.
 **
 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
@@ -176758,10 +182624,10 @@ static int fts3IncrmergeOutputIdx(
 ** of interior nodes that are parents of the leaf nodes start at block
 ** (start_block + (1 + end_block - start_block) / 16). And so on.
 **
-** In the actual code below, the value "16" is replaced with the 
+** In the actual code below, the value "16" is replaced with the
 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
 */
-static int fts3IncrmergeWriter( 
+static int fts3IncrmergeWriter(
   Fts3Table *p,                   /* Fts3 table handle */
   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
   int iIdx,                       /* Index of new output segment */
@@ -176799,7 +182665,7 @@ static int fts3IncrmergeWriter(
   if( rc!=SQLITE_OK ) return rc;
 
   /* Insert the marker in the %_segments table to make sure nobody tries
-  ** to steal the space just allocated. This is also used to identify 
+  ** to steal the space just allocated. This is also used to identify
   ** appendable segments.  */
   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
   if( rc!=SQLITE_OK ) return rc;
@@ -176816,13 +182682,13 @@ static int fts3IncrmergeWriter(
 }
 
 /*
-** Remove an entry from the %_segdir table. This involves running the 
+** Remove an entry from the %_segdir table. This involves running the
 ** following two statements:
 **
 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
 **
-** The DELETE statement removes the specific %_segdir level. The UPDATE 
+** The DELETE statement removes the specific %_segdir level. The UPDATE
 ** statement ensures that the remaining segments have contiguously allocated
 ** idx values.
 */
@@ -176947,8 +182813,8 @@ static int fts3TruncateNode(
   pNew->n = 0;
 
   /* Populate new node buffer */
-  for(rc = nodeReaderInit(&reader, aNode, nNode); 
-      rc==SQLITE_OK && reader.aNode; 
+  for(rc = nodeReaderInit(&reader, aNode, nNode);
+      rc==SQLITE_OK && reader.aNode;
       rc = nodeReaderNext(&reader)
   ){
     if( pNew->n==0 ){
@@ -176975,7 +182841,7 @@ static int fts3TruncateNode(
 }
 
 /*
-** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
+** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
 ** level iAbsLevel. This may involve deleting entries from the %_segments
 ** table, and modifying existing entries in both the %_segments and %_segdir
 ** tables.
@@ -177099,9 +182965,9 @@ static int fts3IncrmergeChomp(
       }
       *pnRem = 0;
     }else{
-      /* The incremental merge did not copy all the data from this 
+      /* The incremental merge did not copy all the data from this
       ** segment to the upper level. The segment is modified in place
-      ** so that it contains no keys smaller than zTerm/nTerm. */ 
+      ** so that it contains no keys smaller than zTerm/nTerm. */
       const char *zTerm = pSeg->zTerm;
       int nTerm = pSeg->nTerm;
       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
@@ -177137,7 +183003,7 @@ static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
 }
 
 /*
-** Load an incr-merge hint from the database. The incr-merge hint, if one 
+** Load an incr-merge hint from the database. The incr-merge hint, if one
 ** exists, is stored in the rowid==1 row of the %_stat table.
 **
 ** If successful, populate blob *pHint with the value read from the %_stat
@@ -177174,7 +183040,7 @@ static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
 /*
 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
-** consists of two varints, the absolute level number of the input segments 
+** consists of two varints, the absolute level number of the input segments
 ** and the number of input segments.
 **
 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
@@ -177195,7 +183061,7 @@ static void fts3IncrmergeHintPush(
 
 /*
 ** Read the last entry (most recently pushed) from the hint blob *pHint
-** and then remove the entry. Write the two values read to *piAbsLevel and 
+** and then remove the entry. Write the two values read to *piAbsLevel and
 ** *pnInput before returning.
 **
 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
@@ -177205,13 +183071,17 @@ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
   const int nHint = pHint->n;
   int i;
 
-  i = pHint->n-2;
+  i = pHint->n-1;
+  if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
+  if( i==0 ) return FTS_CORRUPT_VTAB;
+  i--;
   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
 
   pHint->n = i;
   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
   i += fts3GetVarint32(&pHint->a[i], pnInput);
+  assert( i<=nHint );
   if( i!=nHint ) return FTS_CORRUPT_VTAB;
 
   return SQLITE_OK;
@@ -177221,10 +183091,10 @@ static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
 /*
 ** Attempt an incremental merge that writes nMerge leaf blocks.
 **
-** Incremental merges happen nMin segments at a time. The segments 
-** to be merged are the nMin oldest segments (the ones with the smallest 
-** values for the _segdir.idx field) in the highest level that contains 
-** at least nMin segments. Multiple merges might occur in an attempt to 
+** Incremental merges happen nMin segments at a time. The segments
+** to be merged are the nMin oldest segments (the ones with the smallest
+** values for the _segdir.idx field) in the highest level that contains
+** at least nMin segments. Multiple merges might occur in an attempt to
 ** write the quota of nMerge leaf blocks.
 */
 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
@@ -177255,7 +183125,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
     /* Search the %_segdir table for the absolute level with the smallest
     ** relative level number that contains at least nMin segments, if any.
     ** If one is found, set iAbsLevel to the absolute level number and
-    ** nSeg to nMin. If no level with at least nMin segments can be found, 
+    ** nSeg to nMin. If no level with at least nMin segments can be found,
     ** set nSeg to -1.
     */
     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
@@ -177271,7 +183141,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
 
     /* If the hint read from the %_stat table is not empty, check if the
     ** last entry in it specifies a relative level smaller than or equal
-    ** to the level identified by the block above (if any). If so, this 
+    ** to the level identified by the block above (if any). If so, this
     ** iteration of the loop will work on merging at the hinted level.
     */
     if( rc==SQLITE_OK && hint.n ){
@@ -177281,8 +183151,14 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
 
       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
+        /* Based on the scan in the block above, it is known that there
+        ** are no levels with a relative level smaller than that of
+        ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
+        ** no levels with more than nMin segments. Use this to limit the
+        ** value of nHintSeg to avoid a large memory allocation in case the
+        ** merge-hint is corrupt*/
         iAbsLevel = iHintAbsLevel;
-        nSeg = nHintSeg;
+        nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
         bUseHint = 1;
         bDirtyHint = 1;
       }else{
@@ -177295,13 +183171,19 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
     /* If nSeg is less that zero, then there is no level with at least
     ** nMin segments and no hint in the %_stat table. No work to do.
     ** Exit early in this case.  */
-    if( nSeg<0 ) break;
+    if( nSeg<=0 ) break;
+
+    assert( nMod<=0x7FFFFFFF );
+    if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){
+      rc = FTS_CORRUPT_VTAB;
+      break;
+    }
 
-    /* Open a cursor to iterate through the contents of the oldest nSeg 
-    ** indexes of absolute level iAbsLevel. If this cursor is opened using 
+    /* Open a cursor to iterate through the contents of the oldest nSeg
+    ** indexes of absolute level iAbsLevel. If this cursor is opened using
     ** the 'hint' parameters, it is possible that there are less than nSeg
     ** segments available in level iAbsLevel. In this case, no work is
-    ** done on iAbsLevel - fall through to the next iteration of the loop 
+    ** done on iAbsLevel - fall through to the next iteration of the loop
     ** to start work on some other level.  */
     memset(pWriter, 0, nAlloc);
     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
@@ -177323,8 +183205,15 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
     }
     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
-     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
     ){
+      int bEmpty = 0;
+      rc = sqlite3Fts3SegReaderStep(p, pCsr);
+      if( rc==SQLITE_OK ){
+        bEmpty = 1;
+      }else if( rc!=SQLITE_ROW ){
+        sqlite3Fts3SegReaderFinish(pCsr);
+        break;
+      }
       if( bUseHint && iIdx>0 ){
         const char *zKey = pCsr->zTerm;
         int nKey = pCsr->nTerm;
@@ -177335,11 +183224,13 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
 
       if( rc==SQLITE_OK && pWriter->nLeafEst ){
         fts3LogMerge(nSeg, iAbsLevel);
-        do {
-          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
-          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
-          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
-        }while( rc==SQLITE_ROW );
+        if( bEmpty==0 ){
+          do {
+            rc = fts3IncrmergeAppend(p, pWriter, pCsr);
+            if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
+            if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
+          }while( rc==SQLITE_ROW );
+        }
 
         /* Update or delete the input segments */
         if( rc==SQLITE_OK ){
@@ -177380,7 +183271,7 @@ SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
 ** the integer.
 **
 ** This function used for parameters to merge= and incrmerge=
-** commands. 
+** commands.
 */
 static int fts3Getint(const char **pz){
   const char *z = *pz;
@@ -177404,7 +183295,7 @@ static int fts3DoIncrmerge(
   const char *zParam              /* Nul-terminated string containing "A,B" */
 ){
   int rc;
-  int nMin = (FTS3_MERGE_COUNT / 2);
+  int nMin = (MergeCount(p) / 2);
   int nMerge = 0;
   const char *z = zParam;
 
@@ -177449,7 +183340,7 @@ static int fts3DoAutoincrmerge(
   int rc = SQLITE_OK;
   sqlite3_stmt *pStmt = 0;
   p->nAutoincrmerge = fts3Getint(&zParam);
-  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
+  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
     p->nAutoincrmerge = 8;
   }
   if( !p->bHasStat ){
@@ -177532,12 +183423,12 @@ static u64 fts3ChecksumIndex(
 
       i64 iDocid = 0;
       i64 iCol = 0;
-      i64 iPos = 0;
+      u64 iPos = 0;
 
       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
       while( pCsr<pEnd ){
-        i64 iVal = 0;
-        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
+        u64 iVal = 0;
+        pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
         if( pCsr<pEnd ){
           if( iVal==0 || iVal==1 ){
             iCol = 0;
@@ -177545,8 +183436,12 @@ static u64 fts3ChecksumIndex(
             if( iVal ){
               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
             }else{
-              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
-              iDocid += iVal;
+              pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
+              if( p->bDescIdx ){
+                iDocid = (i64)((u64)iDocid - iVal);
+              }else{
+                iDocid = (i64)((u64)iDocid + iVal);
+              }
             }
           }else{
             iPos += (iVal - 2);
@@ -177571,7 +183466,7 @@ static u64 fts3ChecksumIndex(
 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
 ** to false before returning.
 **
-** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
+** If an error occurs (e.g. an OOM or IO error), return an SQLite error
 ** code. The final value of *pbOk is undefined in this case.
 */
 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
@@ -177602,7 +183497,7 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
     sqlite3_stmt *pStmt = 0;
     char *zSql;
-   
+
     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
     if( !zSql ){
       rc = SQLITE_NOMEM;
@@ -177619,10 +183514,9 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
         if( p->abNotindexed[iCol]==0 ){
           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
-          int nText = sqlite3_column_bytes(pStmt, iCol+1);
           sqlite3_tokenizer_cursor *pT = 0;
 
-          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
+          rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
           while( rc==SQLITE_OK ){
             char const *zToken;       /* Buffer containing token */
             int nToken = 0;           /* Number of bytes in token */
@@ -177662,7 +183556,7 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
 **
-** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
+** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
 ** error code.
 **
 ** The integrity-check works as follows. For each token and indexed token
@@ -177671,7 +183565,7 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
 **
 **     + The index number (0 for the main index, 1 for the first prefix
 **       index etc.),
-**     + The token (or token prefix) text itself, 
+**     + The token (or token prefix) text itself,
 **     + The language-id of the row it appears in,
 **     + The docid of the row it appears in,
 **     + The column it appears in, and
@@ -177682,7 +183576,7 @@ static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
 **
 ** The integrity-check code calculates the same checksum in two ways:
 **
-**     1. By scanning the contents of the FTS index, and 
+**     1. By scanning the contents of the FTS index, and
 **     2. By scanning and tokenizing the content table.
 **
 ** If the two checksums are identical, the integrity-check is deemed to have
@@ -177703,11 +183597,11 @@ static int fts3DoIntegrityCheck(
 **
 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
 **
-** Argument pVal contains the result of <expr>. Currently the only 
+** Argument pVal contains the result of <expr>. Currently the only
 ** meaningful value to insert is the text 'optimize'.
 */
 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
-  int rc;                         /* Return Code */
+  int rc = SQLITE_ERROR;           /* Return Code */
   const char *zVal = (const char *)sqlite3_value_text(pVal);
   int nVal = sqlite3_value_bytes(pVal);
 
@@ -177723,21 +183617,27 @@ static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
     rc = fts3DoIncrmerge(p, &zVal[6]);
   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
     rc = fts3DoAutoincrmerge(p, &zVal[10]);
-#ifdef SQLITE_TEST
-  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
-    p->nNodeSize = atoi(&zVal[9]);
-    rc = SQLITE_OK;
-  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
-    p->nMaxPendingData = atoi(&zVal[11]);
-    rc = SQLITE_OK;
-  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
-    p->bNoIncrDoclist = atoi(&zVal[21]);
-    rc = SQLITE_OK;
-#endif
+#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
   }else{
-    rc = SQLITE_ERROR;
+    int v;
+    if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
+      v = atoi(&zVal[9]);
+      if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
+      rc = SQLITE_OK;
+    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
+      v = atoi(&zVal[11]);
+      if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
+      rc = SQLITE_OK;
+    }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
+      p->bNoIncrDoclist = atoi(&zVal[21]);
+      rc = SQLITE_OK;
+    }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
+      v = atoi(&zVal[11]);
+      if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
+      rc = SQLITE_OK;
+    }
+#endif
   }
-
   return rc;
 }
 
@@ -177755,7 +183655,7 @@ SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
 }
 
 /*
-** Free all entries in the pCsr->pDeffered list. Entries are added to 
+** Free all entries in the pCsr->pDeffered list. Entries are added to
 ** this list using sqlite3Fts3DeferToken().
 */
 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
@@ -177783,14 +183683,14 @@ SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
     int i;                        /* Used to iterate through table columns */
     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
-  
+
     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
     sqlite3_tokenizer *pT = p->pTokenizer;
     sqlite3_tokenizer_module const *pModule = pT->pModule;
-   
+
     assert( pCsr->isRequireSeek==0 );
     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
-  
+
     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
       if( p->abNotindexed[i]==0 ){
         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
@@ -177831,8 +183731,8 @@ SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
 }
 
 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
-  Fts3DeferredToken *p, 
-  char **ppData, 
+  Fts3DeferredToken *p,
+  char **ppData,
   int *pnData
 ){
   char *pRet;
@@ -177852,7 +183752,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
   *pnData = p->pList->nData - nSkip;
   *ppData = pRet;
-  
+
   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
   return SQLITE_OK;
 }
@@ -177872,7 +183772,7 @@ SQLITE_PRIVATE int sqlite3Fts3DeferToken(
   }
   memset(pDeferred, 0, sizeof(*pDeferred));
   pDeferred->pToken = pToken;
-  pDeferred->pNext = pCsr->pDeferred; 
+  pDeferred->pNext = pCsr->pDeferred;
   pDeferred->iCol = iCol;
   pCsr->pDeferred = pDeferred;
 
@@ -177889,8 +183789,8 @@ SQLITE_PRIVATE int sqlite3Fts3DeferToken(
 ** of subsiduary data structures accordingly.
 */
 static int fts3DeleteByRowid(
-  Fts3Table *p, 
-  sqlite3_value *pRowid, 
+  Fts3Table *p,
+  sqlite3_value *pRowid,
   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
   u32 *aSzDel
 ){
@@ -177928,14 +183828,14 @@ static int fts3DeleteByRowid(
 ** This function does the work for the xUpdate method of FTS3 virtual
 ** tables. The schema of the virtual table being:
 **
-**     CREATE TABLE <table name>( 
+**     CREATE TABLE <table name>(
 **       <user columns>,
-**       <table name> HIDDEN, 
-**       docid HIDDEN, 
+**       <table name> HIDDEN,
+**       docid HIDDEN,
 **       <langid> HIDDEN
 **     );
 **
-** 
+**
 */
 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
@@ -177955,7 +183855,7 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   assert( p->bHasStat==0 || p->bHasStat==1 );
 
   assert( p->pSegments==0 );
-  assert( 
+  assert(
       nArg==1                     /* DELETE operations */
    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
   );
@@ -177964,9 +183864,9 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   **
   **   INSERT INTO xyz(xyz) VALUES('command');
   */
-  if( nArg>1 
-   && sqlite3_value_type(apVal[0])==SQLITE_NULL 
-   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
+  if( nArg>1
+   && sqlite3_value_type(apVal[0])==SQLITE_NULL
+   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
   ){
     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
     goto update_out;
@@ -178005,24 +183905,24 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
       pNewRowid = apVal[1];
     }
 
-    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
+    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
         sqlite3_value_type(apVal[0])==SQLITE_NULL
      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
     )){
       /* The new rowid is not NULL (in this case the rowid will be
-      ** automatically assigned and there is no chance of a conflict), and 
+      ** automatically assigned and there is no chance of a conflict), and
       ** the statement is either an INSERT or an UPDATE that modifies the
       ** rowid column. So if the conflict mode is REPLACE, then delete any
-      ** existing row with rowid=pNewRowid. 
+      ** existing row with rowid=pNewRowid.
       **
-      ** Or, if the conflict mode is not REPLACE, insert the new record into 
+      ** Or, if the conflict mode is not REPLACE, insert the new record into
       ** the %_content table. If we hit the duplicate rowid constraint (or any
       ** other error) while doing so, return immediately.
       **
       ** This branch may also run if pNewRowid contains a value that cannot
-      ** be losslessly converted to an integer. In this case, the eventual 
+      ** be losslessly converted to an integer. In this case, the eventual
       ** call to fts3InsertData() (either just below or further on in this
-      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
+      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
       ** invoked, it will delete zero rows (since no row will have
       ** docid=$pNewRowid if $pNewRowid is not an integer value).
       */
@@ -178043,7 +183943,7 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
   }
-  
+
   /* If this is an INSERT or UPDATE operation, insert the new record. */
   if( nArg>1 && rc==SQLITE_OK ){
     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
@@ -178076,10 +183976,10 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
   return rc;
 }
 
-/* 
+/*
 ** Flush any data in the pending-terms hash table to disk. If successful,
-** merge all segments in the database (including the new segment, if 
-** there was any data to flush) into a single segment. 
+** merge all segments in the database (including the new segment, if
+** there was any data to flush) into a single segment.
 */
 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
   int rc;
@@ -178135,7 +184035,7 @@ SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
 #define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
 
 /*
-** The default value for the second argument to matchinfo(). 
+** The default value for the second argument to matchinfo().
 */
 #define FTS3_MATCHINFO_DEFAULT   "pcx"
 
@@ -178152,7 +184052,7 @@ struct LoadDoclistCtx {
 };
 
 /*
-** The following types are used as part of the implementation of the 
+** The following types are used as part of the implementation of the
 ** fts3BestSnippet() routine.
 */
 typedef struct SnippetIter SnippetIter;
@@ -178185,7 +184085,7 @@ struct SnippetFragment {
 };
 
 /*
-** This type is used as an fts3ExprIterate() context object while 
+** This type is used as an fts3ExprIterate() context object while
 ** accumulating the data returned by the matchinfo() function.
 */
 typedef struct MatchInfo MatchInfo;
@@ -178256,8 +184156,8 @@ static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
 static void fts3MIBufferFree(void *p){
   MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
 
-  assert( (u32*)p==&pBuf->aMatchinfo[1] 
-       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] 
+  assert( (u32*)p==&pBuf->aMatchinfo[1]
+       || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
   );
   if( (u32*)p==&pBuf->aMatchinfo[1] ){
     pBuf->aRef[1] = 0;
@@ -178313,7 +184213,7 @@ SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
   }
 }
 
-/* 
+/*
 ** End of MatchinfoBuffer code.
 *************************************************************************/
 
@@ -178374,7 +184274,7 @@ static int fts3ExprIterate2(
 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
 ** For each phrase node found, the supplied callback function is invoked.
 **
-** If the callback function returns anything other than SQLITE_OK, 
+** If the callback function returns anything other than SQLITE_OK,
 ** the iteration is abandoned and the error code returned immediately.
 ** Otherwise, SQLITE_OK is returned after a callback has been made for
 ** all eligible phrase nodes.
@@ -178409,11 +184309,11 @@ static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
 
 /*
 ** Load the doclists for each phrase in the query associated with FTS3 cursor
-** pCsr. 
+** pCsr.
 **
-** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
-** phrases in the expression (all phrases except those directly or 
-** indirectly descended from the right-hand-side of a NOT operator). If 
+** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
+** phrases in the expression (all phrases except those directly or
+** indirectly descended from the right-hand-side of a NOT operator). If
 ** pnToken is not NULL, then it is set to the number of tokens in all
 ** matchable phrases of the expression.
 */
@@ -178443,7 +184343,7 @@ static int fts3ExprPhraseCount(Fts3Expr *pExpr){
 }
 
 /*
-** Advance the position list iterator specified by the first two 
+** Advance the position list iterator specified by the first two
 ** arguments so that it points to the first element with a value greater
 ** than or equal to parameter iNext.
 */
@@ -178512,7 +184412,7 @@ static int fts3SnippetNextCandidate(SnippetIter *pIter){
 }
 
 /*
-** Retrieve information about the current candidate snippet of snippet 
+** Retrieve information about the current candidate snippet of snippet
 ** iterator pIter.
 */
 static void fts3SnippetDetails(
@@ -178592,7 +184492,7 @@ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
     }
   }else{
     assert( rc!=SQLITE_OK || (
-       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
+       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
     ));
   }
 
@@ -178600,14 +184500,14 @@ static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
 }
 
 /*
-** Select the fragment of text consisting of nFragment contiguous tokens 
+** Select the fragment of text consisting of nFragment contiguous tokens
 ** from column iCol that represent the "best" snippet. The best snippet
 ** is the snippet with the highest score, where scores are calculated
 ** by adding:
 **
 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
 **
-**   (b) +1000 points for the first occurrence of each matchable phrase in 
+**   (b) +1000 points for the first occurrence of each matchable phrase in
 **       the snippet for which the corresponding mCovered bit is not set.
 **
 ** The selected snippet parameters are stored in structure *pFragment before
@@ -178664,11 +184564,11 @@ static int fts3BestSnippet(
     /* Set the *pmSeen output variable. */
     for(i=0; i<nList; i++){
       if( sIter.aPhrase[i].pHead ){
-        *pmSeen |= (u64)1 << i;
+        *pmSeen |= (u64)1 << (i%64);
       }
     }
 
-    /* Loop through all candidate snippets. Store the best snippet in 
+    /* Loop through all candidate snippets. Store the best snippet in
      ** *pFragment. Store its associated 'score' in iBestScore.
      */
     pFragment->iCol = iCol;
@@ -178740,8 +184640,8 @@ static int fts3StringAppend(
 **
 **     ........X.....X
 **
-** This function "shifts" the beginning of the snippet forward in the 
-** document so that there are approximately the same number of 
+** This function "shifts" the beginning of the snippet forward in the
+** document so that there are approximately the same number of
 ** non-highlighted terms to the right of the final highlighted term as there
 ** are to the left of the first highlighted term. For example, to this:
 **
@@ -178749,8 +184649,8 @@ static int fts3StringAppend(
 **
 ** This is done as part of extracting the snippet text, not when selecting
 ** the snippet. Snippet selection is done based on doclists only, so there
-** is no way for fts3BestSnippet() to know whether or not the document 
-** actually contains terms that follow the final highlighted term. 
+** is no way for fts3BestSnippet() to know whether or not the document
+** actually contains terms that follow the final highlighted term.
 */
 static int fts3SnippetShift(
   Fts3Table *pTab,                /* FTS3 table snippet comes from */
@@ -178840,7 +184740,7 @@ static int fts3SnippetText(
   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
-  
+
   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
   if( zDoc==0 ){
     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
@@ -178880,7 +184780,7 @@ static int fts3SnippetText(
       if( rc==SQLITE_DONE ){
         /* Special case - the last token of the snippet is also the last token
         ** of the column. Append any punctuation that occurred between the end
-        ** of the previous token and the end of the document to the output. 
+        ** of the previous token and the end of the document to the output.
         ** Then break out of the loop. */
         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
       }
@@ -178897,7 +184797,7 @@ static int fts3SnippetText(
 
       /* Now that the shift has been done, check if the initial "..." are
       ** required. They are required if (a) this is not the first fragment,
-      ** or (b) this fragment does not begin at position 0 of its column. 
+      ** or (b) this fragment does not begin at position 0 of its column.
       */
       if( rc==SQLITE_OK ){
         if( iPos>0 || iFragment>0 ){
@@ -178933,8 +184833,8 @@ static int fts3SnippetText(
 
 
 /*
-** This function is used to count the entries in a column-list (a 
-** delta-encoded list of term offsets within a single column of a single 
+** This function is used to count the entries in a column-list (a
+** delta-encoded list of term offsets within a single column of a single
 ** row). When this function is called, *ppCollist should point to the
 ** beginning of the first varint in the column-list (the varint that
 ** contains the position of the first matching term in the column data).
@@ -178980,7 +184880,7 @@ static int fts3ExprLHits(
     iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
   }
 
-  while( 1 ){
+  if( pIter ) while( 1 ){
     int nHit = fts3ColumnlistCount(&pIter);
     if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
       if( p->flag==FTS3_MATCHINFO_LHITS ){
@@ -179020,11 +184920,11 @@ static int fts3ExprLHitGather(
 
 /*
 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
-** for a single query. 
+** for a single query.
 **
 ** fts3ExprIterate() callback to load the 'global' elements of a
-** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
-** of the matchinfo array that are constant for all rows returned by the 
+** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
+** of the matchinfo array that are constant for all rows returned by the
 ** current query.
 **
 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
@@ -179040,7 +184940,7 @@ static int fts3ExprLHitGather(
 ** at least one instance of phrase iPhrase.
 **
 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
-** Y values are set to nDoc, where nDoc is the number of documents in the 
+** Y values are set to nDoc, where nDoc is the number of documents in the
 ** file system. This is done because the full-text index doclist is required
 ** to calculate these values properly, and the full-text index doclist is
 ** not available for deferred tokens.
@@ -179058,7 +184958,7 @@ static int fts3ExprGlobalHitsCb(
 
 /*
 ** fts3ExprIterate() callback used to collect the "local" part of the
-** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
+** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
 ** array that are different for each row returned by the query.
 */
 static int fts3ExprLocalHitsCb(
@@ -179085,7 +184985,7 @@ static int fts3ExprLocalHitsCb(
 }
 
 static int fts3MatchinfoCheck(
-  Fts3Table *pTab, 
+  Fts3Table *pTab,
   char cArg,
   char **pzErr
 ){
@@ -179110,8 +185010,8 @@ static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
 
   switch( cArg ){
     case FTS3_MATCHINFO_NDOC:
-    case FTS3_MATCHINFO_NPHRASE: 
-    case FTS3_MATCHINFO_NCOL: 
+    case FTS3_MATCHINFO_NPHRASE:
+    case FTS3_MATCHINFO_NCOL:
       nVal = 1;
       break;
 
@@ -179142,11 +185042,15 @@ static int fts3MatchinfoSelectDoctotal(
   Fts3Table *pTab,
   sqlite3_stmt **ppStmt,
   sqlite3_int64 *pnDoc,
-  const char **paLen
+  const char **paLen,
+  const char **ppEnd
 ){
   sqlite3_stmt *pStmt;
   const char *a;
+  const char *pEnd;
   sqlite3_int64 nDoc;
+  int n;
+
 
   if( !*ppStmt ){
     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
@@ -179155,17 +185059,25 @@ static int fts3MatchinfoSelectDoctotal(
   pStmt = *ppStmt;
   assert( sqlite3_data_count(pStmt)==1 );
 
+  n = sqlite3_column_bytes(pStmt, 0);
   a = sqlite3_column_blob(pStmt, 0);
-  a += sqlite3Fts3GetVarint(a, &nDoc);
-  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
-  *pnDoc = (u32)nDoc;
+  if( a==0 ){
+    return FTS_CORRUPT_VTAB;
+  }
+  pEnd = a + n;
+  a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
+  if( nDoc<=0 || a>pEnd ){
+    return FTS_CORRUPT_VTAB;
+  }
+  *pnDoc = nDoc;
 
   if( paLen ) *paLen = a;
+  if( ppEnd ) *ppEnd = pEnd;
   return SQLITE_OK;
 }
 
 /*
-** An instance of the following structure is used to store state while 
+** An instance of the following structure is used to store state while
 ** iterating through a multi-column position-list corresponding to the
 ** hits for a single phrase on a single row in order to calculate the
 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
@@ -179178,7 +185090,7 @@ struct LcsIterator {
   int iPos;                       /* Current position */
 };
 
-/* 
+/*
 ** If LcsIterator.iCol is set to the following value, the iterator has
 ** finished iterating through all offsets for all columns.
 */
@@ -179215,16 +185127,16 @@ static int fts3LcsIteratorAdvance(LcsIterator *pIter){
   pIter->pRead = pRead;
   return rc;
 }
-  
+
 /*
-** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
+** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
 **
 ** If the call is successful, the longest-common-substring lengths for each
-** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
+** column are written into the first nCol elements of the pInfo->aMatchinfo[]
 ** array before returning. SQLITE_OK is returned in this case.
 **
 ** Otherwise, if an error occurs, an SQLite error code is returned and the
-** data written to the first nCol elements of pInfo->aMatchinfo[] is 
+** data written to the first nCol elements of pInfo->aMatchinfo[] is
 ** undefined.
 */
 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
@@ -179301,7 +185213,7 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
 
 /*
 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
-** be returned by the matchinfo() function. Argument zArg contains the 
+** be returned by the matchinfo() function. Argument zArg contains the
 ** format string passed as the second argument to matchinfo (or the
 ** default value "pcx" if no second argument was specified). The format
 ** string has already been validated and the pInfo->aMatchinfo[] array
@@ -179312,7 +185224,7 @@ static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
 ** have already been populated.
 **
-** Return SQLITE_OK if successful, or an SQLite error code if an error 
+** Return SQLITE_OK if successful, or an SQLite error code if an error
 ** occurs. If a value other than SQLITE_OK is returned, the state the
 ** pInfo->aMatchinfo[] buffer is left in is undefined.
 */
@@ -179337,27 +185249,32 @@ static int fts3MatchinfoValues(
       case FTS3_MATCHINFO_NCOL:
         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
         break;
-        
+
       case FTS3_MATCHINFO_NDOC:
         if( bGlobal ){
           sqlite3_int64 nDoc = 0;
-          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
+          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0);
           pInfo->aMatchinfo[0] = (u32)nDoc;
         }
         break;
 
-      case FTS3_MATCHINFO_AVGLENGTH: 
+      case FTS3_MATCHINFO_AVGLENGTH:
         if( bGlobal ){
           sqlite3_int64 nDoc;     /* Number of rows in table */
           const char *a;          /* Aggregate column length array */
+          const char *pEnd;       /* First byte past end of length array */
 
-          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
+          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd);
           if( rc==SQLITE_OK ){
             int iCol;
             for(iCol=0; iCol<pInfo->nCol; iCol++){
               u32 iVal;
               sqlite3_int64 nToken;
               a += sqlite3Fts3GetVarint(a, &nToken);
+              if( a>pEnd ){
+                rc = SQLITE_CORRUPT_VTAB;
+                break;
+              }
               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
               pInfo->aMatchinfo[iCol] = iVal;
             }
@@ -179371,9 +185288,14 @@ static int fts3MatchinfoValues(
         if( rc==SQLITE_OK ){
           int iCol;
           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
+          const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0);
           for(iCol=0; iCol<pInfo->nCol; iCol++){
             sqlite3_int64 nToken;
-            a += sqlite3Fts3GetVarint(a, &nToken);
+            a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken);
+            if( a>pEnd ){
+              rc = SQLITE_CORRUPT_VTAB;
+              break;
+            }
             pInfo->aMatchinfo[iCol] = (u32)nToken;
           }
         }
@@ -179404,7 +185326,7 @@ static int fts3MatchinfoValues(
         if( rc!=SQLITE_OK ) break;
         if( bGlobal ){
           if( pCsr->pDeferred ){
-            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
+            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0);
             if( rc!=SQLITE_OK ) break;
           }
           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
@@ -179425,7 +185347,7 @@ static int fts3MatchinfoValues(
 
 
 /*
-** Populate pCsr->aMatchinfo[] with data for the current row. The 
+** Populate pCsr->aMatchinfo[] with data for the current row. The
 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
 */
 static void fts3GetMatchinfo(
@@ -179445,8 +185367,8 @@ static void fts3GetMatchinfo(
   sInfo.pCursor = pCsr;
   sInfo.nCol = pTab->nColumn;
 
-  /* If there is cached matchinfo() data, but the format string for the 
-  ** cache does not match the format string for this request, discard 
+  /* If there is cached matchinfo() data, but the format string for the
+  ** cache does not match the format string for this request, discard
   ** the cached data. */
   if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
     sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
@@ -179454,7 +185376,7 @@ static void fts3GetMatchinfo(
   }
 
   /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
-  ** matchinfo function has been called for this query. In this case 
+  ** matchinfo function has been called for this query. In this case
   ** allocate the array used to accumulate the matchinfo data and
   ** initialize those elements that are constant for every row.
   */
@@ -179529,7 +185451,7 @@ SQLITE_PRIVATE void sqlite3Fts3Snippet(
 
   /* The returned text includes up to four fragments of text extracted from
   ** the data in the current row. The first iteration of the for(...) loop
-  ** below attempts to locate a single fragment of text nToken tokens in 
+  ** below attempts to locate a single fragment of text nToken tokens in
   ** size that contains at least one instance of all phrases in the query
   ** expression that appear in the current row. If such a fragment of text
   ** cannot be found, the second iteration of the loop attempts to locate
@@ -179600,7 +185522,7 @@ SQLITE_PRIVATE void sqlite3Fts3Snippet(
   assert( nFToken>0 );
 
   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
-    rc = fts3SnippetText(pCsr, &aSnippet[i], 
+    rc = fts3SnippetText(pCsr, &aSnippet[i],
         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
     );
   }
@@ -179698,7 +185620,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
   sCtx.iDocid = pCsr->iPrevId;
   sCtx.pCsr = pCsr;
 
-  /* Loop through the table columns, appending offset information to 
+  /* Loop through the table columns, appending offset information to
   ** string-buffer res for each column.
   */
   for(iCol=0; iCol<pTab->nColumn; iCol++){
@@ -179711,7 +185633,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
     const char *zDoc;
     int nDoc;
 
-    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
+    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
     ** no way that this operation can fail, so the return code from
     ** fts3ExprIterate() can be discarded.
     */
@@ -179719,11 +185641,11 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
     sCtx.iTerm = 0;
     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
 
-    /* Retreive the text stored in column iCol. If an SQL NULL is stored 
+    /* Retreive the text stored in column iCol. If an SQL NULL is stored
     ** in column iCol, jump immediately to the next iteration of the loop.
     ** If an OOM occurs while retrieving the data (this can happen if SQLite
-    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
-    ** to the caller. 
+    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
+    ** to the caller.
     */
     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
@@ -179770,7 +185692,7 @@ SQLITE_PRIVATE void sqlite3Fts3Offsets(
         }
         if( rc==SQLITE_OK ){
           char aBuffer[64];
-          sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
+          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
           );
           rc = fts3StringAppend(&res, aBuffer, -1);
@@ -179951,7 +185873,7 @@ static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
 **
 ** For each codepoint in the zIn/nIn string, this function checks if the
 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
-** If so, no action is taken. Otherwise, the codepoint is added to the 
+** If so, no action is taken. Otherwise, the codepoint is added to the
 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
 ** codepoints in the aiException[] array.
@@ -179977,8 +185899,8 @@ static int unicodeAddExceptions(
   while( z<zTerm ){
     READ_UTF8(z, zTerm, iCode);
     assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
-    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
-     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 
+    if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
+     && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
     ){
       nEntry++;
     }
@@ -179995,7 +185917,7 @@ static int unicodeAddExceptions(
     z = (const unsigned char *)zIn;
     while( z<zTerm ){
       READ_UTF8(z, zTerm, iCode);
-      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum 
+      if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
        && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
       ){
         int i, j;
@@ -180098,7 +186020,7 @@ static int unicodeCreate(
 /*
 ** Prepare to begin tokenizing a particular string.  The input
 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
-** used to incrementally tokenize this string is returned in 
+** used to incrementally tokenize this string is returned in
 ** *ppCursor.
 */
 static int unicodeOpen(
@@ -180162,7 +186084,7 @@ static int unicodeNext(
   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
 
   /* Scan past any delimiter characters before the start of the next token.
-  ** Return SQLITE_DONE early if this takes us all the way to the end of 
+  ** Return SQLITE_DONE early if this takes us all the way to the end of
   ** the input.  */
   while( z<zTerm ){
     READ_UTF8(z, zTerm, iCode);
@@ -180194,7 +186116,7 @@ static int unicodeNext(
     /* If the cursor is not at EOF, read the next character */
     if( z>=zTerm ) break;
     READ_UTF8(z, zTerm, iCode);
-  }while( unicodeIsAlnum(p, (int)iCode) 
+  }while( unicodeIsAlnum(p, (int)iCode)
        || sqlite3FtsUnicodeIsdiacritic((int)iCode)
   );
 
@@ -180209,7 +186131,7 @@ static int unicodeNext(
 }
 
 /*
-** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
+** Set *ppModule to a pointer to the sqlite3_tokenizer_module
 ** structure for the unicode tokenizer.
 */
 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
@@ -180264,11 +186186,11 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
   ** range of unicode codepoints that are not either letters or numbers (i.e.
   ** codepoints for which this function should return 0).
   **
-  ** The most significant 22 bits in each 32-bit value contain the first 
+  ** The most significant 22 bits in each 32-bit value contain the first
   ** codepoint in the range. The least significant 10 bits are used to store
-  ** the size of the range (always at least 1). In other words, the value 
-  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
-  ** C. It is not possible to represent a range larger than 1023 codepoints 
+  ** the size of the range (always at least 1). In other words, the value
+  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
+  ** C. It is not possible to represent a range larger than 1023 codepoints
   ** using this format.
   */
   static const unsigned int aEntry[] = {
@@ -180289,14 +186211,14 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D402,
     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
     0x002B8802, 0x002BC002, 0x002BE806, 0x002C0403, 0x002CF001,
-    0x002CF807, 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802,
+    0x002CF807, 0x002D1C02, 0x002D2C03, 0x002D5403, 0x002D8802,
     0x002DC001, 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804,
     0x002F5C01, 0x002FCC08, 0x00300005, 0x0030F807, 0x00311803,
     0x00312804, 0x00315402, 0x00318802, 0x0031DC01, 0x0031FC01,
     0x00320404, 0x0032F001, 0x0032F807, 0x00331803, 0x00332804,
     0x00335402, 0x00338802, 0x00340004, 0x0034EC02, 0x0034F807,
     0x00351803, 0x00352804, 0x00353C01, 0x00355C01, 0x00358802,
-    0x0035E401, 0x00360802, 0x00372801, 0x00373C06, 0x00375801,
+    0x0035E401, 0x00360403, 0x00372801, 0x00373C06, 0x00375801,
     0x00376008, 0x0037C803, 0x0038C401, 0x0038D007, 0x0038FC01,
     0x00391C09, 0x00396802, 0x003AC401, 0x003AD009, 0x003B2006,
     0x003C041F, 0x003CD00C, 0x003DC417, 0x003E340B, 0x003E6424,
@@ -180308,7 +186230,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
     0x005F6004, 0x005F7401, 0x0060000F, 0x00621402, 0x0062A401,
     0x0064800C, 0x0064C00C, 0x00650001, 0x00651002, 0x00677822,
     0x00685C05, 0x00687802, 0x0069540A, 0x0069801D, 0x0069FC01,
-    0x006A8007, 0x006AA006, 0x006AC00F, 0x006C0005, 0x006CD011,
+    0x006A8007, 0x006AA006, 0x006AC011, 0x006C0005, 0x006CD011,
     0x006D6823, 0x006E0003, 0x006E840D, 0x006F980E, 0x006FF004,
     0x00709014, 0x0070EC05, 0x0071F802, 0x00730008, 0x00734019,
     0x0073B401, 0x0073D001, 0x0073DC03, 0x0077003A, 0x0077EC05,
@@ -180318,63 +186240,65 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
     0x00845001, 0x00845803, 0x00847806, 0x00849401, 0x00849C01,
     0x0084A401, 0x0084B801, 0x0084E802, 0x00850005, 0x00852804,
     0x00853C01, 0x00862802, 0x00864297, 0x0091000B, 0x0092704E,
-    0x00940276, 0x009E53E0, 0x00ADD820, 0x00AE6068, 0x00B39406,
+    0x00940276, 0x009E53E0, 0x00ADD820, 0x00AE5C69, 0x00B39406,
     0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001, 0x00B5FC01,
-    0x00B7804F, 0x00B8C020, 0x00BA001A, 0x00BA6C59, 0x00BC00D6,
+    0x00B7804F, 0x00B8C023, 0x00BA001A, 0x00BA6C59, 0x00BC00D6,
     0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807, 0x00C0D802,
     0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01, 0x00C64002,
     0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E, 0x00C94001,
     0x00C98020, 0x00CA2827, 0x00CB0140, 0x01370040, 0x02924037,
     0x0293F802, 0x02983403, 0x0299BC10, 0x029A7802, 0x029BC008,
     0x029C0017, 0x029C8002, 0x029E2402, 0x02A00801, 0x02A01801,
-    0x02A02C01, 0x02A08C09, 0x02A0D804, 0x02A1D004, 0x02A20002,
+    0x02A02C01, 0x02A08C0A, 0x02A0D804, 0x02A1D004, 0x02A20002,
     0x02A2D012, 0x02A33802, 0x02A38012, 0x02A3E003, 0x02A3F001,
     0x02A3FC01, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
     0x02A6CC1B, 0x02A77802, 0x02A79401, 0x02A8A40E, 0x02A90C01,
     0x02A93002, 0x02A97004, 0x02A9DC03, 0x02A9EC03, 0x02AAC001,
     0x02AAC803, 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802,
-    0x02ABAC07, 0x02ABD402, 0x02AD6C01, 0x02AF8C0B, 0x03600001,
-    0x036DFC02, 0x036FFC02, 0x037FFC01, 0x03EC7801, 0x03ECA401,
-    0x03EEC810, 0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88033,
-    0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
-    0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
-    0x04040003, 0x0404DC09, 0x0405E411, 0x04063003, 0x0406400C,
-    0x04068001, 0x0407402E, 0x040B8001, 0x040DD805, 0x040E7C01,
-    0x040F4001, 0x0415BC01, 0x04215C01, 0x0421DC02, 0x04247C01,
-    0x0424FC01, 0x04280403, 0x04281402, 0x04283004, 0x0428E003,
-    0x0428FC01, 0x04294009, 0x0429FC01, 0x042B2001, 0x042B9402,
-    0x042BC007, 0x042CE407, 0x042E6404, 0x04349004, 0x043D180B,
-    0x043D5405, 0x04400003, 0x0440E016, 0x0441FC04, 0x0442C012,
-    0x04433401, 0x04440003, 0x04449C0E, 0x04450004, 0x04451402,
-    0x0445CC03, 0x04460003, 0x0446CC0E, 0x04471409, 0x04476C01,
-    0x04477403, 0x0448B013, 0x044AA401, 0x044B7C0C, 0x044C0004,
-    0x044CEC02, 0x044CF807, 0x044D1C02, 0x044D2C03, 0x044D5C01,
-    0x044D8802, 0x044D9807, 0x044DC005, 0x0450D412, 0x04512C05,
-    0x04516C01, 0x04517402, 0x0452C014, 0x04531801, 0x0456BC07,
-    0x0456E020, 0x04577002, 0x0458C014, 0x0459800D, 0x045AAC0D,
-    0x045C740F, 0x045CF004, 0x0460B010, 0x04674407, 0x04676807,
-    0x04678801, 0x04679001, 0x0468040A, 0x0468CC07, 0x0468EC0D,
-    0x0469440B, 0x046A2813, 0x046A7805, 0x0470BC08, 0x0470E008,
-    0x04710405, 0x0471C002, 0x04724816, 0x0472A40E, 0x0474C406,
-    0x0474E801, 0x0474F002, 0x0474FC07, 0x04751C01, 0x04762805,
-    0x04764002, 0x04764C05, 0x047BCC06, 0x047F541D, 0x047FFC01,
-    0x0491C005, 0x04D0C009, 0x05A9B802, 0x05ABC006, 0x05ACC010,
-    0x05AD1002, 0x05BA5C04, 0x05BD3C01, 0x05BD4437, 0x05BE3C04,
-    0x05BF8801, 0x06F27008, 0x074000F6, 0x07440027, 0x0744A4C0,
-    0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
-    0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
-    0x075EA401, 0x075F0C01, 0x0760028C, 0x076A6C05, 0x076A840F,
-    0x07800007, 0x07802011, 0x07806C07, 0x07808C02, 0x07809805,
-    0x0784C007, 0x07853C01, 0x078BB004, 0x078BFC01, 0x07A34007,
-    0x07A51007, 0x07A57802, 0x07B2B001, 0x07B2C001, 0x07B4B801,
-    0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F, 0x07C2C40F,
-    0x07C3040F, 0x07C34425, 0x07C4405D, 0x07C5C03D, 0x07C7981D,
-    0x07C8402C, 0x07C90009, 0x07C94002, 0x07C98006, 0x07CC03D6,
-    0x07DB800D, 0x07DBC00B, 0x07DC0074, 0x07DE0059, 0x07DF800C,
-    0x07E0000C, 0x07E04038, 0x07E1400A, 0x07E18028, 0x07E2401E,
-    0x07E4000C, 0x07E43465, 0x07E5CC04, 0x07E5E829, 0x07E69406,
-    0x07E6B81D, 0x07E73487, 0x07E9800E, 0x07E9C004, 0x07E9E003,
-    0x07EA0003, 0x07EA4006, 0x38000401, 0x38008060, 0x380400F0,
+    0x02ABAC07, 0x02ABD402, 0x02AD6C01, 0x02ADA802, 0x02AF8C0B,
+    0x03600001, 0x036DFC02, 0x036FFC02, 0x037FFC01, 0x03EC7801,
+    0x03ECA401, 0x03EEC810, 0x03F4F802, 0x03F7F002, 0x03F8001A,
+    0x03F88033, 0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F,
+    0x03FC6807, 0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007,
+    0x03FFE405, 0x04040003, 0x0404DC09, 0x0405E411, 0x04063003,
+    0x0406400D, 0x04068001, 0x0407402E, 0x040B8001, 0x040DD805,
+    0x040E7C01, 0x040F4001, 0x0415BC01, 0x04215C01, 0x0421DC02,
+    0x04247C01, 0x0424FC01, 0x04280403, 0x04281402, 0x04283004,
+    0x0428E003, 0x0428FC01, 0x04294009, 0x0429FC01, 0x042B2001,
+    0x042B9402, 0x042BC007, 0x042CE407, 0x042E6404, 0x04349004,
+    0x043AAC03, 0x043D180B, 0x043D5405, 0x04400003, 0x0440E016,
+    0x0441FC04, 0x0442C012, 0x04433401, 0x04440003, 0x04449C0E,
+    0x04450004, 0x04451402, 0x0445CC03, 0x04460003, 0x0446CC0E,
+    0x0447140B, 0x04476C01, 0x04477403, 0x0448B013, 0x044AA401,
+    0x044B7C0C, 0x044C0004, 0x044CEC02, 0x044CF807, 0x044D1C02,
+    0x044D2C03, 0x044D5C01, 0x044D8802, 0x044D9807, 0x044DC005,
+    0x0450D412, 0x04512C05, 0x04516802, 0x04517402, 0x0452C014,
+    0x04531801, 0x0456BC07, 0x0456E020, 0x04577002, 0x0458C014,
+    0x0459800D, 0x045AAC0D, 0x045C740F, 0x045CF004, 0x0460B010,
+    0x0464C006, 0x0464DC02, 0x0464EC04, 0x04650001, 0x04650805,
+    0x04674407, 0x04676807, 0x04678801, 0x04679001, 0x0468040A,
+    0x0468CC07, 0x0468EC0D, 0x0469440B, 0x046A2813, 0x046A7805,
+    0x0470BC08, 0x0470E008, 0x04710405, 0x0471C002, 0x04724816,
+    0x0472A40E, 0x0474C406, 0x0474E801, 0x0474F002, 0x0474FC07,
+    0x04751C01, 0x04762805, 0x04764002, 0x04764C05, 0x047BCC06,
+    0x047F541D, 0x047FFC01, 0x0491C005, 0x04D0C009, 0x05A9B802,
+    0x05ABC006, 0x05ACC010, 0x05AD1002, 0x05BA5C04, 0x05BD3C01,
+    0x05BD4437, 0x05BE3C04, 0x05BF8801, 0x05BF9001, 0x05BFC002,
+    0x06F27008, 0x074000F6, 0x07440027, 0x0744A4C0, 0x07480046,
+    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
+    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
+    0x075F0C01, 0x0760028C, 0x076A6C05, 0x076A840F, 0x07800007,
+    0x07802011, 0x07806C07, 0x07808C02, 0x07809805, 0x0784C007,
+    0x07853C01, 0x078BB004, 0x078BFC01, 0x07A34007, 0x07A51007,
+    0x07A57802, 0x07B2B001, 0x07B2C001, 0x07B4B801, 0x07BBC002,
+    0x07C0002C, 0x07C0C064, 0x07C2800F, 0x07C2C40F, 0x07C3040F,
+    0x07C34425, 0x07C434A1, 0x07C7981D, 0x07C8402C, 0x07C90009,
+    0x07C94002, 0x07C98006, 0x07CC03D8, 0x07DB800D, 0x07DBC00D,
+    0x07DC0074, 0x07DE0059, 0x07DF800C, 0x07E0000C, 0x07E04038,
+    0x07E1400A, 0x07E18028, 0x07E2401E, 0x07E2C002, 0x07E40079,
+    0x07E5E852, 0x07E73487, 0x07E9800E, 0x07E9C005, 0x07E9E003,
+    0x07EA0007, 0x07EA4019, 0x07EAC007, 0x07EB0003, 0x07EB4007,
+    0x07EC0093, 0x07EE5037, 0x38000401, 0x38008060, 0x380400F0,
   };
   static const unsigned int aAscii[4] = {
     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
@@ -180414,46 +186338,46 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
 */
 static int remove_diacritic(int c, int bComplex){
   static const unsigned short aDia[] = {
-        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
-     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
-     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
-     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
-     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, 
-     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, 
-     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, 
-     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, 
-     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, 
-    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, 
-    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, 
-    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, 
-    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, 
-    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, 
-    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, 
-    63182, 63242, 63274, 63310, 63368, 63390, 
+        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
+     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
+     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
+     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
+     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896,
+     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106,
+     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344,
+     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198,
+     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468,
+    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
+    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
+    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
+    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
+    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
+    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
+    63182, 63242, 63274, 63310, 63368, 63390,
   };
 #define HIBIT ((unsigned char)0x80)
   static const unsigned char aChar[] = {
-    '\0',      'a',       'c',       'e',       'i',       'n',       
-    'o',       'u',       'y',       'y',       'a',       'c',       
-    'd',       'e',       'e',       'g',       'h',       'i',       
-    'j',       'k',       'l',       'n',       'o',       'r',       
-    's',       't',       'u',       'u',       'w',       'y',       
-    'z',       'o',       'u',       'a',       'i',       'o',       
-    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       
-    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       
-    'e',       'i',       'o',       'r',       'u',       's',       
-    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       
-    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',      
-    '\0',      '\0',      '\0',      '\0',      'a',       'b',       
-    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, 
-    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, 
-    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       
-    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       
-    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       
-    'w',       'x',       'y',       'z',       'h',       't',       
-    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, 
-    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, 
-    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       
+    '\0',      'a',       'c',       'e',       'i',       'n',
+    'o',       'u',       'y',       'y',       'a',       'c',
+    'd',       'e',       'e',       'g',       'h',       'i',
+    'j',       'k',       'l',       'n',       'o',       'r',
+    's',       't',       'u',       'u',       'w',       'y',
+    'z',       'o',       'u',       'a',       'i',       'o',
+    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',
+    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',
+    'e',       'i',       'o',       'r',       'u',       's',
+    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',
+    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',
+    '\0',      '\0',      '\0',      '\0',      'a',       'b',
+    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT,
+    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT,
+    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',
+    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',
+    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',
+    'w',       'x',       'y',       'z',       'h',       't',
+    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
+    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT,
+    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',
   };
 
   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
@@ -180583,22 +186507,23 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
     {42926, 80, 1},        {42928, 92, 1},        {42929, 86, 1},
     {42930, 90, 1},        {42931, 68, 1},        {42932, 1, 12},
     {42946, 0, 1},         {42948, 178, 1},       {42949, 82, 1},
-    {42950, 96, 1},        {43888, 94, 80},       {65313, 14, 26},
+    {42950, 96, 1},        {42951, 1, 4},         {42997, 0, 1},
+    {43888, 94, 80},       {65313, 14, 26},
   };
   static const unsigned short aiOff[] = {
-   1,     2,     8,     15,    16,    26,    28,    32,    
-   34,    37,    38,    40,    48,    63,    64,    69,    
-   71,    79,    80,    116,   202,   203,   205,   206,   
-   207,   209,   210,   211,   213,   214,   217,   218,   
-   219,   775,   928,   7264,  10792, 10795, 23217, 23221, 
-   23228, 23229, 23231, 23254, 23256, 23275, 23278, 26672, 
-   30152, 30204, 35267, 54721, 54753, 54754, 54756, 54787, 
-   54793, 54809, 57153, 57274, 57921, 58019, 58363, 59314, 
-   59315, 59324, 59325, 59326, 59332, 59356, 61722, 62528, 
-   65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424, 
-   65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480, 
-   65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528, 
-   65529, 
+   1,     2,     8,     15,    16,    26,    28,    32,
+   34,    37,    38,    40,    48,    63,    64,    69,
+   71,    79,    80,    116,   202,   203,   205,   206,
+   207,   209,   210,   211,   213,   214,   217,   218,
+   219,   775,   928,   7264,  10792, 10795, 23217, 23221,
+   23228, 23229, 23231, 23254, 23256, 23275, 23278, 26672,
+   30152, 30204, 35267, 54721, 54753, 54754, 54756, 54787,
+   54793, 54809, 57153, 57274, 57921, 58019, 58363, 59314,
+   59315, 59324, 59325, 59326, 59332, 59356, 61722, 62528,
+   65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424,
+   65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480,
+   65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528,
+   65529,
   };
 
   int ret = c;
@@ -180636,7 +186561,7 @@ SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
       ret = remove_diacritic(ret, eRemoveDiacritic==2);
     }
   }
-  
+
   else if( c>=66560 && c<66600 ){
     ret = c + 40;
   }
@@ -180708,6 +186633,10 @@ SQLITE_EXTENSION_INIT1
 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
 #endif
 
+#ifndef deliberate_fall_through
+# define deliberate_fall_through
+#endif
+
 /*
 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
 ** to pass signed char values.
@@ -180880,7 +186809,7 @@ static void jsonReset(JsonString *p){
 }
 
 
-/* Report an out-of-memory (OOM) condition 
+/* Report an out-of-memory (OOM) condition
 */
 static void jsonOom(JsonString *p){
   p->bErr = 1;
@@ -180919,6 +186848,7 @@ static int jsonGrow(JsonString *p, u32 N){
 /* Append N bytes from zIn onto the end of the JsonString string.
 */
 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
+  if( N==0 ) return;
   if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
   memcpy(p->zBuf+p->nUsed, zIn, N);
   p->nUsed += N;
@@ -180997,7 +186927,7 @@ static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
 }
 
 /*
-** Append a function parameter value to the JSON string under 
+** Append a function parameter value to the JSON string under
 ** construction.
 */
 static void jsonAppendValue(
@@ -181042,7 +186972,7 @@ static void jsonAppendValue(
 */
 static void jsonResult(JsonString *p){
   if( p->bErr==0 ){
-    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, 
+    sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
                           p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
                           SQLITE_UTF8);
     jsonZero(p);
@@ -181124,7 +187054,7 @@ static void jsonRenderNode(
         jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
         break;
       }
-      /* Fall through into the next case */
+      /* no break */ deliberate_fall_through
     }
     case JSON_REAL:
     case JSON_INT: {
@@ -181188,6 +187118,37 @@ static void jsonReturnJson(
 }
 
 /*
+** Translate a single byte of Hex into an integer.
+** This routine only works if h really is a valid hexadecimal
+** character:  0..9a..fA..F
+*/
+static u8 jsonHexToInt(int h){
+  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
+#ifdef SQLITE_EBCDIC
+  h += 9*(1&~(h>>4));
+#else
+  h += 9*(1&(h>>6));
+#endif
+  return (u8)(h & 0xf);
+}
+
+/*
+** Convert a 4-byte hex string into an integer
+*/
+static u32 jsonHexToInt4(const char *z){
+  u32 v;
+  assert( safe_isxdigit(z[0]) );
+  assert( safe_isxdigit(z[1]) );
+  assert( safe_isxdigit(z[2]) );
+  assert( safe_isxdigit(z[3]) );
+  v = (jsonHexToInt(z[0])<<12)
+    + (jsonHexToInt(z[1])<<8)
+    + (jsonHexToInt(z[2])<<4)
+    + jsonHexToInt(z[3]);
+  return v;
+}
+
+/*
 ** Make the JsonNode the return value of the function.
 */
 static void jsonReturn(
@@ -181234,7 +187195,7 @@ static void jsonReturn(
       sqlite3_result_int64(pCtx, i);
       int_done:
       break;
-      int_as_real: /* fall through to real */;
+      int_as_real: i=0; /* no break */ deliberate_fall_through
     }
     case JSON_REAL: {
       double r;
@@ -181254,7 +187215,7 @@ static void jsonReturn(
       if( pNode->jnFlags & JNODE_RAW ){
         sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
                             SQLITE_TRANSIENT);
-      }else 
+      }else
 #endif
       assert( (pNode->jnFlags & JNODE_RAW)==0 );
       if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
@@ -181280,15 +187241,8 @@ static void jsonReturn(
           }else{
             c = z[++i];
             if( c=='u' ){
-              u32 v = 0, k;
-              for(k=0; k<4; i++, k++){
-                assert( i<n-2 );
-                c = z[i+1];
-                assert( safe_isxdigit(c) );
-                if( c<='9' ) v = v*16 + c - '0';
-                else if( c<='F' ) v = v*16 + c - 'A' + 10;
-                else v = v*16 + c - 'a' + 10;
-              }
+              u32 v = jsonHexToInt4(z+i+1);
+              i += 4;
               if( v==0 ) break;
               if( v<=0x7f ){
                 zOut[j++] = (char)v;
@@ -181296,9 +187250,25 @@ static void jsonReturn(
                 zOut[j++] = (char)(0xc0 | (v>>6));
                 zOut[j++] = 0x80 | (v&0x3f);
               }else{
-                zOut[j++] = (char)(0xe0 | (v>>12));
-                zOut[j++] = 0x80 | ((v>>6)&0x3f);
-                zOut[j++] = 0x80 | (v&0x3f);
+                u32 vlo;
+                if( (v&0xfc00)==0xd800
+                  && i<n-6
+                  && z[i+1]=='\\'
+                  && z[i+2]=='u'
+                  && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
+                ){
+                  /* We have a surrogate pair */
+                  v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
+                  i += 6;
+                  zOut[j++] = 0xf0 | (v>>18);
+                  zOut[j++] = 0x80 | ((v>>12)&0x3f);
+                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
+                  zOut[j++] = 0x80 | (v&0x3f);
+                }else{
+                  zOut[j++] = 0xe0 | (v>>12);
+                  zOut[j++] = 0x80 | ((v>>6)&0x3f);
+                  zOut[j++] = 0x80 | (v&0x3f);
+                }
               }
             }else{
               if( c=='b' ){
@@ -181801,18 +187771,49 @@ static JsonNode *jsonLookupStep(
       }
       return pNode;
     }
-  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
-    if( pRoot->eType!=JSON_ARRAY ) return 0;
+  }else if( zPath[0]=='[' ){
     i = 0;
     j = 1;
     while( safe_isdigit(zPath[j]) ){
       i = i*10 + zPath[j] - '0';
       j++;
     }
-    if( zPath[j]!=']' ){
-      *pzErr = zPath;
-      return 0;
+    if( j<2 || zPath[j]!=']' ){
+      if( zPath[1]=='#' ){
+        JsonNode *pBase = pRoot;
+        int iBase = iRoot;
+        if( pRoot->eType!=JSON_ARRAY ) return 0;
+        for(;;){
+          while( j<=pBase->n ){
+            if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
+            j += jsonNodeSize(&pBase[j]);
+          }
+          if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
+          iBase += pBase->u.iAppend;
+          pBase = &pParse->aNode[iBase];
+          j = 1;
+        }
+        j = 2;
+        if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
+          unsigned int x = 0;
+          j = 3;
+          do{
+            x = x*10 + zPath[j] - '0';
+            j++;
+          }while( safe_isdigit(zPath[j]) );
+          if( x>i ) return 0;
+          i -= x;
+        }
+        if( zPath[j]!=']' ){
+          *pzErr = zPath;
+          return 0;
+        }
+      }else{
+        *pzErr = zPath;
+        return 0;
+      }
     }
+    if( pRoot->eType!=JSON_ARRAY ) return 0;
     zPath += j + 1;
     j = 1;
     for(;;){
@@ -181935,7 +187936,7 @@ static void jsonWrongNumArgs(
   char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
                                zFuncName);
   sqlite3_result_error(pCtx, zMsg, -1);
-  sqlite3_free(zMsg);     
+  sqlite3_free(zMsg);
 }
 
 /*
@@ -182022,7 +188023,7 @@ static void jsonTest1Func(
 
 /*
 ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
-** corresponding to the SQL value input.  Mostly this means putting 
+** corresponding to the SQL value input.  Mostly this means putting
 ** double-quotes around strings and returning the unquoted string "null"
 ** when given a NULL input.
 */
@@ -182069,7 +188070,7 @@ static void jsonArrayFunc(
 ** json_array_length(JSON)
 ** json_array_length(JSON, PATH)
 **
-** Return the number of elements in the top-level JSON array.  
+** Return the number of elements in the top-level JSON array.
 ** Return 0 if the input is not a well-formed JSON array.
 */
 static void jsonArrayLengthFunc(
@@ -182562,7 +188563,7 @@ static void jsonGroupInverse(
       if( c=='}' || c==']' ) nNest--;
     }
   }
-  pStr->nUsed -= i;      
+  pStr->nUsed -= i;
   memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
 }
 #else
@@ -182678,13 +188679,14 @@ static int jsonEachConnect(
   UNUSED_PARAM(argv);
   UNUSED_PARAM(argc);
   UNUSED_PARAM(pAux);
-  rc = sqlite3_declare_vtab(db, 
+  rc = sqlite3_declare_vtab(db,
      "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
                     "json HIDDEN,root HIDDEN)");
   if( rc==SQLITE_OK ){
     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
     if( pNew==0 ) return SQLITE_NOMEM;
     memset(pNew, 0, sizeof(*pNew));
+    sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
   }
   return rc;
 }
@@ -182856,7 +188858,7 @@ static int jsonEachColumn(
       break;
     }
     case JEACH_ID: {
-      sqlite3_result_int64(ctx, 
+      sqlite3_result_int64(ctx,
          (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
       break;
     }
@@ -182896,6 +188898,7 @@ static int jsonEachColumn(
       }
       /* For json_each() path and root are the same so fall through
       ** into the root case */
+      /* no break */ deliberate_fall_through
     }
     default: {
       const char *zRoot = p->zRoot;
@@ -183175,16 +189178,19 @@ SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
     { "json_tree",            &jsonTreeModule               },
   };
 #endif
+  static const int enc =
+       SQLITE_UTF8 |
+       SQLITE_DETERMINISTIC |
+       SQLITE_INNOCUOUS;
   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
-    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
-                                 SQLITE_UTF8 | SQLITE_DETERMINISTIC,
+    rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
                                  (void*)&aFunc[i].flag,
                                  aFunc[i].xFunc, 0, 0);
   }
 #ifndef SQLITE_OMIT_WINDOWFUNC
   for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
     rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
-                SQLITE_SUBTYPE | SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
+                                 SQLITE_SUBTYPE | enc, 0,
                                  aAgg[i].xStep, aAgg[i].xFinal,
                                  aAgg[i].xValue, jsonGroupInverse, 0);
   }
@@ -183203,8 +189209,8 @@ SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
 __declspec(dllexport)
 #endif
 SQLITE_API int sqlite3_json_init(
-  sqlite3 *db, 
-  char **pzErrMsg, 
+  sqlite3 *db,
+  char **pzErrMsg,
   const sqlite3_api_routines *pApi
 ){
   SQLITE_EXTENSION_INIT2(pApi);
@@ -183235,7 +189241,7 @@ SQLITE_API int sqlite3_json_init(
 ** Database Format of R-Tree Tables
 ** --------------------------------
 **
-** The data structure for a single virtual r-tree table is stored in three 
+** The data structure for a single virtual r-tree table is stored in three
 ** native SQLite tables declared as follows. In each case, the '%' character
 ** in the table name is replaced with the user-supplied name of the r-tree
 ** table.
@@ -183261,7 +189267,7 @@ SQLITE_API int sqlite3_json_init(
 **      of the node contain the tree depth as a big-endian integer.
 **      For non-root nodes, the first 2 bytes are left unused.
 **
-**   2. The next 2 bytes contain the number of entries currently 
+**   2. The next 2 bytes contain the number of entries currently
 **      stored in the node.
 **
 **   3. The remainder of the node contains the node entries. Each entry
@@ -183280,6 +189286,7 @@ SQLITE_API int sqlite3_json_init(
 #else
 /*   #include "sqlite3.h" */
 #endif
+SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
 
 #ifndef SQLITE_AMALGAMATION
 #include "sqlite3rtree.h"
@@ -183299,6 +189306,7 @@ typedef unsigned int u32;
 /* #include <string.h> */
 /* #include <stdio.h> */
 /* #include <assert.h> */
+/* #include <stdlib.h> */
 
 /*  The following macro is used to suppress compiler warnings.
 */
@@ -183323,7 +189331,7 @@ typedef struct RtreeSearchPoint RtreeSearchPoint;
 #define RTREE_MAX_AUX_COLUMN 100
 
 /* Size of hash table Rtree.aHash. This hash table is not expected to
-** ever contain very many entries, so a fixed number of buckets is 
+** ever contain very many entries, so a fixed number of buckets is
 ** used.
 */
 #define HASHSIZE 97
@@ -183332,13 +189340,13 @@ typedef struct RtreeSearchPoint RtreeSearchPoint;
 ** the number of rows in the virtual table to calculate the costs of
 ** various strategies. If possible, this estimate is loaded from the
 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
-** Otherwise, if no sqlite_stat1 entry is available, use 
+** Otherwise, if no sqlite_stat1 entry is available, use
 ** RTREE_DEFAULT_ROWEST.
 */
 #define RTREE_DEFAULT_ROWEST 1048576
 #define RTREE_MIN_ROWEST         100
 
-/* 
+/*
 ** An rtree virtual-table object.
 */
 struct Rtree {
@@ -183357,7 +189365,7 @@ struct Rtree {
 #endif
   int iDepth;                 /* Current depth of the r-tree structure */
   char *zDb;                  /* Name of database containing r-tree table */
-  char *zName;                /* Name of r-tree table */ 
+  char *zName;                /* Name of r-tree table */
   u32 nBusy;                  /* Current number of users of this structure */
   i64 nRowEst;                /* Estimated number of rows in this table */
   u32 nCursor;                /* Number of open cursors */
@@ -183366,7 +189374,7 @@ struct Rtree {
 
   /* List of nodes removed during a CondenseTree operation. List is
   ** linked together via the pointer normally used for hash chains -
-  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
+  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
   */
   RtreeNode *pDeleted;
@@ -183392,7 +189400,7 @@ struct Rtree {
   /* Statement for writing to the "aux:" fields, if there are any */
   sqlite3_stmt *pWriteAux;
 
-  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
+  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
 };
 
 /* Possible values for Rtree.eCoordType: */
@@ -183441,7 +189449,7 @@ struct RtreeSearchPoint {
 };
 
 /*
-** The minimum number of cells allowed for a node is a third of the 
+** The minimum number of cells allowed for a node is a third of the
 ** maximum. In Gutman's notation:
 **
 **     m = M/3
@@ -183456,7 +189464,7 @@ struct RtreeSearchPoint {
 /*
 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
-** Therefore all non-root nodes must contain at least 3 entries. Since 
+** Therefore all non-root nodes must contain at least 3 entries. Since
 ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
 ** 40 or less.
 */
@@ -183470,7 +189478,7 @@ struct RtreeSearchPoint {
 */
 #define RTREE_CACHE_SZ  5
 
-/* 
+/*
 ** An rtree cursor object.
 */
 struct RtreeCursor {
@@ -183543,8 +189551,14 @@ struct RtreeConstraint {
 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
 
+/* Special operators available only on cursors.  Needs to be consecutive
+** with the normal values above, but must be less than RTREE_MATCH.  These
+** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
+** x<'xyz' (RTREE_TRUE) */
+#define RTREE_TRUE  0x3f  /* ? */
+#define RTREE_FALSE 0x40  /* @ */
 
-/* 
+/*
 ** An rtree structure node.
 */
 struct RtreeNode {
@@ -183559,7 +189573,7 @@ struct RtreeNode {
 /* Return the number of cells in a node  */
 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
 
-/* 
+/*
 ** A single cell from a node, deserialized
 */
 struct RtreeCell {
@@ -183574,11 +189588,11 @@ struct RtreeCell {
 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
 ** operators in order to constrain a search.
 **
-** xGeom and xQueryFunc are the callback functions.  Exactly one of 
+** xGeom and xQueryFunc are the callback functions.  Exactly one of
 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
 ** SQL function was created using sqlite3_rtree_geometry_callback() or
 ** sqlite3_rtree_query_callback().
-** 
+**
 ** This object is deleted automatically by the destructor mechanism in
 ** sqlite3_create_function_v2().
 */
@@ -183631,6 +189645,23 @@ struct RtreeMatchArg {
 #endif
 
 /*
+** Make sure that the compiler intrinsics we desire are enabled when
+** compiling with an appropriate version of MSVC unless prevented by
+** the SQLITE_DISABLE_INTRINSIC define.
+*/
+#if !defined(SQLITE_DISABLE_INTRINSIC)
+#  if defined(_MSC_VER) && _MSC_VER>=1400
+#    if !defined(_WIN32_WCE)
+/* #      include <intrin.h> */
+#      pragma intrinsic(_byteswap_ulong)
+#      pragma intrinsic(_byteswap_uint64)
+#    else
+/* #      include <cmnintrin.h> */
+#    endif
+#  endif
+#endif
+
+/*
 ** Macros to determine whether the machine is big or little endian,
 ** and whether or not that determination is run-time or compile-time.
 **
@@ -183679,9 +189710,9 @@ static void readCoord(u8 *p, RtreeCoord *pCoord){
   pCoord->u = *(u32*)p;
 #else
   pCoord->u = (
-    (((u32)p[0]) << 24) + 
-    (((u32)p[1]) << 16) + 
-    (((u32)p[2]) <<  8) + 
+    (((u32)p[0]) << 24) +
+    (((u32)p[1]) << 16) +
+    (((u32)p[2]) <<  8) +
     (((u32)p[3]) <<  0)
   );
 #endif
@@ -183701,13 +189732,13 @@ static i64 readInt64(u8 *p){
   return x;
 #else
   return (i64)(
-    (((u64)p[0]) << 56) + 
-    (((u64)p[1]) << 48) + 
-    (((u64)p[2]) << 40) + 
-    (((u64)p[3]) << 32) + 
-    (((u64)p[4]) << 24) + 
-    (((u64)p[5]) << 16) + 
-    (((u64)p[6]) <<  8) + 
+    (((u64)p[0]) << 56) +
+    (((u64)p[1]) << 48) +
+    (((u64)p[2]) << 40) +
+    (((u64)p[3]) << 32) +
+    (((u64)p[4]) << 24) +
+    (((u64)p[5]) << 16) +
+    (((u64)p[6]) <<  8) +
     (((u64)p[7]) <<  0)
   );
 #endif
@@ -183952,7 +189983,7 @@ static int nodeAcquire(
   ** are the leaves, and so on. If the depth as specified on the root node
   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
   */
-  if( pNode && iNode==1 ){
+  if( pNode && rc==SQLITE_OK && iNode==1 ){
     pRtree->iDepth = readInt16(pNode->zData);
     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
       rc = SQLITE_CORRUPT_VTAB;
@@ -183961,7 +189992,7 @@ static int nodeAcquire(
   }
 
   /* If no error has occurred so far, check if the "number of entries"
-  ** field on the node is too large. If so, set the return code to 
+  ** field on the node is too large. If so, set the return code to
   ** SQLITE_CORRUPT_VTAB.
   */
   if( pNode && rc==SQLITE_OK ){
@@ -184160,7 +190191,7 @@ static int rtreeInit(
   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
 );
 
-/* 
+/*
 ** Rtree virtual table module xCreate method.
 */
 static int rtreeCreate(
@@ -184173,7 +190204,7 @@ static int rtreeCreate(
   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
 }
 
-/* 
+/*
 ** Rtree virtual table module xConnect method.
 */
 static int rtreeConnect(
@@ -184218,7 +190249,7 @@ static void rtreeRelease(Rtree *pRtree){
   }
 }
 
-/* 
+/*
 ** Rtree virtual table module xDisconnect method.
 */
 static int rtreeDisconnect(sqlite3_vtab *pVtab){
@@ -184226,7 +190257,7 @@ static int rtreeDisconnect(sqlite3_vtab *pVtab){
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** Rtree virtual table module xDestroy method.
 */
 static int rtreeDestroy(sqlite3_vtab *pVtab){
@@ -184236,7 +190267,7 @@ static int rtreeDestroy(sqlite3_vtab *pVtab){
     "DROP TABLE '%q'.'%q_node';"
     "DROP TABLE '%q'.'%q_rowid';"
     "DROP TABLE '%q'.'%q_parent';",
-    pRtree->zDb, pRtree->zName, 
+    pRtree->zDb, pRtree->zName,
     pRtree->zDb, pRtree->zName,
     pRtree->zDb, pRtree->zName
   );
@@ -184254,7 +190285,7 @@ static int rtreeDestroy(sqlite3_vtab *pVtab){
   return rc;
 }
 
-/* 
+/*
 ** Rtree virtual table module xOpen method.
 */
 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
@@ -184276,9 +190307,12 @@ static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
 
 
 /*
-** Free the RtreeCursor.aConstraint[] array and its contents.
+** Reset a cursor back to its initial state.
 */
-static void freeCursorConstraints(RtreeCursor *pCsr){
+static void resetCursor(RtreeCursor *pCsr){
+  Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
+  int ii;
+  sqlite3_stmt *pStmt;
   if( pCsr->aConstraint ){
     int i;                        /* Used to iterate through constraint array */
     for(i=0; i<pCsr->nConstraint; i++){
@@ -184291,20 +190325,24 @@ static void freeCursorConstraints(RtreeCursor *pCsr){
     sqlite3_free(pCsr->aConstraint);
     pCsr->aConstraint = 0;
   }
+  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
+  sqlite3_free(pCsr->aPoint);
+  pStmt = pCsr->pReadAux;
+  memset(pCsr, 0, sizeof(RtreeCursor));
+  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
+  pCsr->pReadAux = pStmt;
+
 }
 
-/* 
+/*
 ** Rtree virtual table module xClose method.
 */
 static int rtreeClose(sqlite3_vtab_cursor *cur){
   Rtree *pRtree = (Rtree *)(cur->pVtab);
-  int ii;
   RtreeCursor *pCsr = (RtreeCursor *)cur;
   assert( pRtree->nCursor>0 );
-  freeCursorConstraints(pCsr);
+  resetCursor(pCsr);
   sqlite3_finalize(pCsr->pReadAux);
-  sqlite3_free(pCsr->aPoint);
-  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
   sqlite3_free(pCsr);
   pRtree->nCursor--;
   nodeBlobReset(pRtree);
@@ -184314,7 +190352,7 @@ static int rtreeClose(sqlite3_vtab_cursor *cur){
 /*
 ** Rtree virtual table module xEof method.
 **
-** Return non-zero if the cursor does not currently point to a valid 
+** Return non-zero if the cursor does not currently point to a valid
 ** record (i.e if the scan has finished), or zero otherwise.
 */
 static int rtreeEof(sqlite3_vtab_cursor *cur){
@@ -184370,7 +190408,7 @@ static int rtreeEof(sqlite3_vtab_cursor *cur){
 
 /*
 ** Check the RTree node or entry given by pCellData and p against the MATCH
-** constraint pConstraint.  
+** constraint pConstraint.
 */
 static int rtreeCallbackConstraint(
   RtreeConstraint *pConstraint,  /* The constraint to test */
@@ -184443,7 +190481,7 @@ static int rtreeCallbackConstraint(
   return rc;
 }
 
-/* 
+/*
 ** Check the internal RTree node given by pCellData against constraint p.
 ** If this constraint cannot be satisfied by any child within the node,
 ** set *peWithin to NOT_WITHIN.
@@ -184461,10 +190499,13 @@ static void rtreeNonleafConstraint(
   */
   pCellData += 8 + 4*(p->iCoord&0xfe);
 
-  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
-      || p->op==RTREE_GT || p->op==RTREE_EQ );
+  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
+      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
+      || p->op==RTREE_FALSE );
   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
   switch( p->op ){
+    case RTREE_TRUE:  return;   /* Always satisfied */
+    case RTREE_FALSE: break;    /* Never satisfied */
     case RTREE_LE:
     case RTREE_LT:
     case RTREE_EQ:
@@ -184501,28 +190542,31 @@ static void rtreeLeafConstraint(
 ){
   RtreeDValue xN;      /* Coordinate value converted to a double */
 
-  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
-      || p->op==RTREE_GT || p->op==RTREE_EQ );
+  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
+      || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
+      || p->op==RTREE_FALSE );
   pCellData += 8 + p->iCoord*4;
   assert( ((((char*)pCellData) - (char*)0)&3)==0 );  /* 4-byte aligned */
   RTREE_DECODE_COORD(eInt, pCellData, xN);
   switch( p->op ){
-    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
-    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
-    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
-    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
-    default:       if( xN == p->u.rValue ) return;  break;
+    case RTREE_TRUE:  return;   /* Always satisfied */
+    case RTREE_FALSE: break;    /* Never satisfied */
+    case RTREE_LE:    if( xN <= p->u.rValue ) return;  break;
+    case RTREE_LT:    if( xN <  p->u.rValue ) return;  break;
+    case RTREE_GE:    if( xN >= p->u.rValue ) return;  break;
+    case RTREE_GT:    if( xN >  p->u.rValue ) return;  break;
+    default:          if( xN == p->u.rValue ) return;  break;
   }
   *peWithin = NOT_WITHIN;
 }
 
 /*
-** One of the cells in node pNode is guaranteed to have a 64-bit 
+** One of the cells in node pNode is guaranteed to have a 64-bit
 ** integer value equal to iRowid. Return the index of this cell.
 */
 static int nodeRowidIndex(
-  Rtree *pRtree, 
-  RtreeNode *pNode, 
+  Rtree *pRtree,
+  RtreeNode *pNode,
   i64 iRowid,
   int *piIndex
 ){
@@ -184664,7 +190708,7 @@ static RtreeSearchPoint *rtreeSearchPointNew(
   pFirst = rtreeSearchPointFirst(pCur);
   pCur->anQueue[iLevel]++;
   if( pFirst==0
-   || pFirst->rScore>rScore 
+   || pFirst->rScore>rScore
    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
   ){
     if( pCur->bPoint ){
@@ -184848,7 +190892,7 @@ static int rtreeStepToLeaf(RtreeCursor *pCur){
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** Rtree virtual table module xNext method.
 */
 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
@@ -184866,7 +190910,7 @@ static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
   return rc;
 }
 
-/* 
+/*
 ** Rtree virtual table module xRowid method.
 */
 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
@@ -184880,7 +190924,7 @@ static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
   return rc;
 }
 
-/* 
+/*
 ** Rtree virtual table module xColumn method.
 */
 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
@@ -184913,7 +190957,7 @@ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
                                 &pCsr->pReadAux, 0);
         if( rc ) return rc;
       }
-      sqlite3_bind_int64(pCsr->pReadAux, 1, 
+      sqlite3_bind_int64(pCsr->pReadAux, 1,
           nodeGetRowid(pRtree, pNode, p->iCell));
       rc = sqlite3_step(pCsr->pReadAux);
       if( rc==SQLITE_ROW ){
@@ -184926,12 +190970,12 @@ static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
     }
     sqlite3_result_value(ctx,
          sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
-  }  
+  }
   return SQLITE_OK;
 }
 
-/* 
-** Use nodeAcquire() to obtain the leaf node containing the record with 
+/*
+** Use nodeAcquire() to obtain the leaf node containing the record with
 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
 ** return SQLITE_OK. If there is no such record in the table, set
 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
@@ -184990,11 +191034,11 @@ static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** Rtree virtual table module xFilter method.
 */
 static int rtreeFilter(
-  sqlite3_vtab_cursor *pVtabCursor, 
+  sqlite3_vtab_cursor *pVtabCursor,
   int idxNum, const char *idxStr,
   int argc, sqlite3_value **argv
 ){
@@ -185004,17 +191048,11 @@ static int rtreeFilter(
   int ii;
   int rc = SQLITE_OK;
   int iCell = 0;
-  sqlite3_stmt *pStmt;
 
   rtreeReference(pRtree);
 
   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
-  freeCursorConstraints(pCsr);
-  sqlite3_free(pCsr->aPoint);
-  pStmt = pCsr->pReadAux;
-  memset(pCsr, 0, sizeof(RtreeCursor));
-  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
-  pCsr->pReadAux = pStmt;
+  resetCursor(pCsr);
 
   pCsr->iStrategy = idxNum;
   if( idxNum==1 ){
@@ -185023,7 +191061,15 @@ static int rtreeFilter(
     RtreeSearchPoint *p;     /* Search point for the leaf */
     i64 iRowid = sqlite3_value_int64(argv[0]);
     i64 iNode = 0;
-    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
+    int eType = sqlite3_value_numeric_type(argv[0]);
+    if( eType==SQLITE_INTEGER
+     || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)
+    ){
+      rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
+    }else{
+      rc = SQLITE_OK;
+      pLeaf = 0;
+    }
     if( rc==SQLITE_OK && pLeaf!=0 ){
       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
       assert( p!=0 );  /* Always returns pCsr->sPoint */
@@ -185037,8 +191083,8 @@ static int rtreeFilter(
       pCsr->atEOF = 1;
     }
   }else{
-    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
-    ** with the configured constraints. 
+    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
+    ** with the configured constraints.
     */
     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
     if( rc==SQLITE_OK && argc>0 ){
@@ -185053,6 +191099,7 @@ static int rtreeFilter(
                 || (idxStr && (int)strlen(idxStr)==argc*2) );
         for(ii=0; ii<argc; ii++){
           RtreeConstraint *p = &pCsr->aConstraint[ii];
+          int eType = sqlite3_value_numeric_type(argv[ii]);
           p->op = idxStr[ii*2];
           p->iCoord = idxStr[ii*2+1]-'0';
           if( p->op>=RTREE_MATCH ){
@@ -185067,12 +191114,21 @@ static int rtreeFilter(
             p->pInfo->nCoord = pRtree->nDim2;
             p->pInfo->anQueue = pCsr->anQueue;
             p->pInfo->mxLevel = pRtree->iDepth + 1;
-          }else{
+          }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
 #ifdef SQLITE_RTREE_INT_ONLY
             p->u.rValue = sqlite3_value_int64(argv[ii]);
 #else
             p->u.rValue = sqlite3_value_double(argv[ii]);
 #endif
+          }else{
+            p->u.rValue = RTREE_ZERO;
+            if( eType==SQLITE_NULL ){
+              p->op = RTREE_FALSE;
+            }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
+              p->op = RTREE_TRUE;
+            }else{
+              p->op = RTREE_FALSE;
+            }
           }
         }
       }
@@ -185099,7 +191155,7 @@ static int rtreeFilter(
 
 /*
 ** Rtree virtual table module xBestIndex method. There are three
-** table scan strategies to choose from (in order from most to 
+** table scan strategies to choose from (in order from most to
 ** least desirable):
 **
 **   idxNum     idxStr        Strategy
@@ -185109,8 +191165,8 @@ static int rtreeFilter(
 **   ------------------------------------------------
 **
 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
-** 2 is used, idxStr is formatted to contain 2 bytes for each 
-** constraint used. The first two bytes of idxStr correspond to 
+** 2 is used, idxStr is formatted to contain 2 bytes for each
+** constraint used. The first two bytes of idxStr correspond to
 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
 ** (argvIndex==1) etc.
 **
@@ -185156,8 +191212,8 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
 
-    if( bMatch==0 && p->usable 
-     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ 
+    if( bMatch==0 && p->usable
+     && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
     ){
       /* We have an equality constraint on the rowid. Use strategy 1. */
       int jj;
@@ -185170,11 +191226,11 @@ static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
       pIdxInfo->aConstraintUsage[jj].omit = 1;
 
       /* This strategy involves a two rowid lookups on an B-Tree structures
-      ** and then a linear search of an R-Tree node. This should be 
-      ** considered almost as quick as a direct rowid lookup (for which 
+      ** and then a linear search of an R-Tree node. This should be
+      ** considered almost as quick as a direct rowid lookup (for which
       ** sqlite uses an internal cost of 0.0). It is expected to return
       ** a single row.
-      */ 
+      */
       pIdxInfo->estimatedCost = 30.0;
       pIdxInfo->estimatedRows = 1;
       pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
@@ -185290,8 +191346,8 @@ static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
   for(ii=0; ii<pRtree->nDim2; ii+=2){
     RtreeCoord *a1 = &p1->aCoord[ii];
     RtreeCoord *a2 = &p2->aCoord[ii];
-    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
-     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
+    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
+     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
     ){
       return 0;
     }
@@ -185312,9 +191368,9 @@ static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
 }
 
 static RtreeDValue cellOverlap(
-  Rtree *pRtree, 
-  RtreeCell *p, 
-  RtreeCell *aCell, 
+  Rtree *pRtree,
+  RtreeCell *p,
+  RtreeCell *aCell,
   int nCell
 ){
   int ii;
@@ -185425,7 +191481,7 @@ static int AdjustTree(
       cellUnion(pRtree, &cell, pCell);
       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
     }
+
     p = pParent;
   }
   return SQLITE_OK;
@@ -185456,7 +191512,7 @@ static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
 
 /*
 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
-** nIdx. The aIdx array contains the set of integers from 0 to 
+** nIdx. The aIdx array contains the set of integers from 0 to
 ** (nIdx-1) in no particular order. This function sorts the values
 ** in aIdx according to the indexed values in aDistance. For
 ** example, assuming the inputs:
@@ -185472,9 +191528,9 @@ static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
 ** sorting algorithm.
 */
 static void SortByDistance(
-  int *aIdx, 
-  int nIdx, 
-  RtreeDValue *aDistance, 
+  int *aIdx,
+  int nIdx,
+  RtreeDValue *aDistance,
   int *aSpare
 ){
   if( nIdx>1 ){
@@ -185528,7 +191584,7 @@ static void SortByDistance(
 
 /*
 ** Arguments aIdx, aCell and aSpare all point to arrays of size
-** nIdx. The aIdx array contains the set of integers from 0 to 
+** nIdx. The aIdx array contains the set of integers from 0 to
 ** (nIdx-1) in no particular order. This function sorts the values
 ** in aIdx according to dimension iDim of the cells in aCell. The
 ** minimum value of dimension iDim is considered first, the
@@ -185539,10 +191595,10 @@ static void SortByDistance(
 */
 static void SortByDimension(
   Rtree *pRtree,
-  int *aIdx, 
-  int nIdx, 
-  int iDim, 
-  RtreeCell *aCell, 
+  int *aIdx,
+  int nIdx,
+  int iDim,
+  RtreeCell *aCell,
   int *aSpare
 ){
   if( nIdx>1 ){
@@ -185639,8 +191695,8 @@ static int splitNodeStartree(
     int nLeft;
 
     for(
-      nLeft=RTREE_MINCELLS(pRtree); 
-      nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
+      nLeft=RTREE_MINCELLS(pRtree);
+      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
       nLeft++
     ){
       RtreeCell left;
@@ -185695,9 +191751,9 @@ static int splitNodeStartree(
 
 
 static int updateMapping(
-  Rtree *pRtree, 
-  i64 iRowid, 
-  RtreeNode *pNode, 
+  Rtree *pRtree,
+  i64 iRowid,
+  RtreeNode *pNode,
   int iHeight
 ){
   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
@@ -185733,7 +191789,7 @@ static int SplitNode(
   RtreeCell leftbbox;
   RtreeCell rightbbox;
 
-  /* Allocate an array and populate it with a copy of pCell and 
+  /* Allocate an array and populate it with a copy of pCell and
   ** all cells from node pLeft. Then zero the original node.
   */
   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
@@ -185850,14 +191906,14 @@ splitnode_out:
 }
 
 /*
-** If node pLeaf is not the root of the r-tree and its pParent pointer is 
+** If node pLeaf is not the root of the r-tree and its pParent pointer is
 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
 ** the pLeaf->pParent chain all the way up to the root node.
 **
 ** This operation is required when a row is deleted (or updated - an update
 ** is implemented as a delete followed by an insert). SQLite provides the
 ** rowid of the row to delete, which can be used to find the leaf on which
-** the entry resides (argument pLeaf). Once the leaf is located, this 
+** the entry resides (argument pLeaf). Once the leaf is located, this
 ** function is called to determine its ancestry.
 */
 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
@@ -185931,7 +191987,7 @@ static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
     return rc;
   }
-  
+
   /* Remove the node from the in-memory hash table and link it into
   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
   */
@@ -185946,9 +192002,9 @@ static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
 
 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
   RtreeNode *pParent = pNode->pParent;
-  int rc = SQLITE_OK; 
+  int rc = SQLITE_OK;
   if( pParent ){
-    int ii; 
+    int ii;
     int nCell = NCELL(pNode);
     RtreeCell box;                            /* Bounding box for pNode */
     nodeGetCell(pRtree, pNode, 0, &box);
@@ -186003,9 +192059,9 @@ static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
 }
 
 static int Reinsert(
-  Rtree *pRtree, 
-  RtreeNode *pNode, 
-  RtreeCell *pCell, 
+  Rtree *pRtree,
+  RtreeNode *pNode,
+  RtreeCell *pCell,
   int iHeight
 ){
   int *aOrder;
@@ -186059,7 +192115,7 @@ static int Reinsert(
   for(ii=0; ii<nCell; ii++){
     aDistance[ii] = RTREE_ZERO;
     for(iDim=0; iDim<pRtree->nDim; iDim++){
-      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
+      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
                                DCOORD(aCell[ii].aCoord[iDim*2]));
       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
     }
@@ -186104,7 +192160,7 @@ static int Reinsert(
 }
 
 /*
-** Insert cell pCell into node pNode. Node pNode is the head of a 
+** Insert cell pCell into node pNode. Node pNode is the head of a
 ** subtree iHeight high (leaf nodes have iHeight==0).
 */
 static int rtreeInsertCell(
@@ -186194,8 +192250,8 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   /* Obtain a reference to the root node to initialize Rtree.iDepth */
   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
 
-  /* Obtain a reference to the leaf node that contains the entry 
-  ** about to be deleted. 
+  /* Obtain a reference to the leaf node that contains the entry
+  ** about to be deleted.
   */
   if( rc==SQLITE_OK ){
     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
@@ -186226,11 +192282,11 @@ static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
   }
 
   /* Check if the root node now has exactly one child. If so, remove
-  ** it, schedule the contents of the child for reinsertion and 
+  ** it, schedule the contents of the child for reinsertion and
   ** reduce the tree height by one.
   **
   ** This is equivalent to copying the contents of the child into
-  ** the root node (the operation that Gutman's paper says to perform 
+  ** the root node (the operation that Gutman's paper says to perform
   ** in this scenario).
   */
   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
@@ -186300,8 +192356,8 @@ static RtreeValue rtreeValueUp(sqlite3_value *v){
 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
 
 /*
-** A constraint has failed while inserting a row into an rtree table. 
-** Assuming no OOM error occurs, this function sets the error message 
+** A constraint has failed while inserting a row into an rtree table.
+** Assuming no OOM error occurs, this function sets the error message
 ** (at pRtree->base.zErrMsg) to an appropriate value and returns
 ** SQLITE_CONSTRAINT.
 **
@@ -186314,7 +192370,7 @@ static RtreeValue rtreeValueUp(sqlite3_value *v){
 */
 static int rtreeConstraintError(Rtree *pRtree, int iCol){
   sqlite3_stmt *pStmt = 0;
-  char *zSql; 
+  char *zSql;
   int rc;
 
   assert( iCol==0 || iCol%2 );
@@ -186351,9 +192407,9 @@ static int rtreeConstraintError(Rtree *pRtree, int iCol){
 ** The xUpdate method for rtree module virtual tables.
 */
 static int rtreeUpdate(
-  sqlite3_vtab *pVtab, 
-  int nData, 
-  sqlite3_value **aData, 
+  sqlite3_vtab *pVtab,
+  int nData,
+  sqlite3_value **aData,
   sqlite_int64 *pRowid
 ){
   Rtree *pRtree = (Rtree *)pVtab;
@@ -186420,7 +192476,7 @@ static int rtreeUpdate(
       }
     }
 
-    /* If a rowid value was supplied, check if it is already present in 
+    /* If a rowid value was supplied, check if it is already present in
     ** the table. If so, the constraint has failed. */
     if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
       cell.iRowid = sqlite3_value_int64(aData[2]);
@@ -186526,8 +192582,8 @@ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
-    , pRtree->zDb, pRtree->zName, zNewName 
-    , pRtree->zDb, pRtree->zName, zNewName 
+    , pRtree->zDb, pRtree->zName, zNewName
+    , pRtree->zDb, pRtree->zName, zNewName
     , pRtree->zDb, pRtree->zName, zNewName
   );
   if( zSql ){
@@ -186542,8 +192598,8 @@ static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
 ** The xSavepoint method.
 **
 ** This module does not need to do anything to support savepoints. However,
-** it uses this hook to close any open blob handle. This is done because a 
-** DROP TABLE command - which fortunately always opens a savepoint - cannot 
+** it uses this hook to close any open blob handle. This is done because a
+** DROP TABLE command - which fortunately always opens a savepoint - cannot
 ** succeed if there are any open blob handles. i.e. if the blob handle were
 ** not closed here, the following would fail:
 **
@@ -186650,10 +192706,10 @@ static const sqlite3_module rtreeModule = {
 };
 
 static int rtreeSqlInit(
-  Rtree *pRtree, 
-  sqlite3 *db, 
-  const char *zDb, 
-  const char *zPrefix, 
+  Rtree *pRtree,
+  sqlite3 *db,
+  const char *zDb,
+  const char *zPrefix,
   int isCreate
 ){
   int rc = SQLITE_OK;
@@ -186733,7 +192789,7 @@ static int rtreeSqlInit(
     }
     zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
     if( zSql ){
-      rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0); 
+      rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
     }else{
       rc = SQLITE_NOMEM;
     }
@@ -186763,7 +192819,7 @@ static int rtreeSqlInit(
       if( zSql==0 ){
         rc = SQLITE_NOMEM;
       }else{
-        rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0); 
+        rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
         sqlite3_free(zSql);
       }
     }
@@ -186804,9 +192860,9 @@ static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
 ** table already exists. In this case the node-size is determined by inspecting
 ** the root node of the tree.
 **
-** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
-** This ensures that each node is stored on a single database page. If the 
-** database page-size is so large that more than RTREE_MAXCELLS entries 
+** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
+** This ensures that each node is stored on a single database page. If the
+** database page-size is so large that more than RTREE_MAXCELLS entries
 ** would fit in a single node, use a smaller node-size.
 */
 static int getNodeSize(
@@ -186849,7 +192905,15 @@ static int getNodeSize(
   return rc;
 }
 
-/* 
+/*
+** Return the length of a token
+*/
+static int rtreeTokenLength(const char *z){
+  int dummy = 0;
+  return sqlite3GetToken((const unsigned char*)z,&dummy);
+}
+
+/*
 ** This function is the implementation of both the xConnect and xCreate
 ** methods of the r-tree virtual table.
 **
@@ -186885,8 +192949,8 @@ static int rtreeInit(
   };
 
   assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
-  if( argc>RTREE_MAX_AUX_COLUMN+3 ){
-    *pzErr = sqlite3_mprintf("%s", aErrMsg[3]);
+  if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
+    *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
     return SQLITE_ERROR;
   }
 
@@ -186914,16 +192978,20 @@ static int rtreeInit(
   ** the r-tree table schema.
   */
   pSql = sqlite3_str_new(db);
-  sqlite3_str_appendf(pSql, "CREATE TABLE x(%s", argv[3]);
+  sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
+                      rtreeTokenLength(argv[3]), argv[3]);
   for(ii=4; ii<argc; ii++){
-    if( argv[ii][0]=='+' ){
+    const char *zArg = argv[ii];
+    if( zArg[0]=='+' ){
       pRtree->nAux++;
-      sqlite3_str_appendf(pSql, ",%s", argv[ii]+1);
+      sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
     }else if( pRtree->nAux>0 ){
       break;
     }else{
+      static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
       pRtree->nDim2++;
-      sqlite3_str_appendf(pSql, ",%s", argv[ii]);
+      sqlite3_str_appendf(pSql, azFormat[eCoordType],
+                          rtreeTokenLength(zArg), zArg);
     }
   }
   sqlite3_str_appendf(pSql, ");");
@@ -186988,7 +193056,7 @@ rtreeInit_fail:
 **
 ** The human readable string takes the form of a Tcl list with one
 ** entry for each cell in the r-tree node. Each entry is itself a
-** list, containing the 8-byte rowid/pageno followed by the 
+** list, containing the 8-byte rowid/pageno followed by the
 ** <num-dimension>*2 coordinates.
 */
 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
@@ -187044,10 +193112,10 @@ static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
 */
 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
   UNUSED_PARAMETER(nArg);
-  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
+  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
    || sqlite3_value_bytes(apArg[0])<2
   ){
-    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
+    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
   }else{
     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
     sqlite3_result_int(ctx, readInt16(zBlob));
@@ -187130,7 +193198,7 @@ static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
     if( z==0 ){
       pCheck->rc = SQLITE_NOMEM;
     }else{
-      pCheck->zReport = sqlite3_mprintf("%z%s%z", 
+      pCheck->zReport = sqlite3_mprintf("%z%s%z",
           pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
       );
       if( pCheck->zReport==0 ){
@@ -187161,7 +193229,7 @@ static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
 
   if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
     pCheck->pGetNode = rtreeCheckPrepare(pCheck,
-        "SELECT data FROM %Q.'%q_node' WHERE nodeno=?", 
+        "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
         pCheck->zDb, pCheck->zTab
     );
   }
@@ -187231,7 +193299,7 @@ static void rtreeCheckMapping(
   }else if( rc==SQLITE_ROW ){
     i64 ii = sqlite3_column_int64(pStmt, 0);
     if( ii!=iVal ){
-      rtreeCheckAppendMsg(pCheck, 
+      rtreeCheckAppendMsg(pCheck,
           "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
           iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
       );
@@ -187247,13 +193315,13 @@ static void rtreeCheckMapping(
 ** if they are not.
 **
 ** Additionally, if pParent is not NULL, then it is assumed to point to
-** the array of coordinates on the parent page that bound the page 
+** the array of coordinates on the parent page that bound the page
 ** containing pCell. In this case it is also verified that the two
 ** sets of coordinates are mutually consistent and an error message added
 ** to the RtreeCheck object if they are not.
 */
 static void rtreeCheckCellCoord(
-  RtreeCheck *pCheck, 
+  RtreeCheck *pCheck,
   i64 iNode,                      /* Node id to use in error messages */
   int iCell,                      /* Cell number to use in error messages */
   u8 *pCell,                      /* Pointer to cell coordinates */
@@ -187269,7 +193337,7 @@ static void rtreeCheckCellCoord(
 
     /* printf("%e, %e\n", c1.u.f, c2.u.f); */
     if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
-      rtreeCheckAppendMsg(pCheck, 
+      rtreeCheckAppendMsg(pCheck,
           "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
       );
     }
@@ -187278,10 +193346,10 @@ static void rtreeCheckCellCoord(
       readCoord(&pParent[4*2*i], &p1);
       readCoord(&pParent[4*(2*i + 1)], &p2);
 
-      if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f) 
+      if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
        || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
       ){
-        rtreeCheckAppendMsg(pCheck, 
+        rtreeCheckAppendMsg(pCheck,
             "Dimension %d of cell %d on node %lld is corrupt relative to parent"
             , i, iCell, iNode
         );
@@ -187313,7 +193381,7 @@ static void rtreeCheckNode(
   aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
   if( aNode ){
     if( nNode<4 ){
-      rtreeCheckAppendMsg(pCheck, 
+      rtreeCheckAppendMsg(pCheck,
           "Node %lld is too small (%d bytes)", iNode, nNode
       );
     }else{
@@ -187329,8 +193397,8 @@ static void rtreeCheckNode(
       }
       nCell = readInt16(&aNode[2]);
       if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
-        rtreeCheckAppendMsg(pCheck, 
-            "Node %lld is too small for cell count of %d (%d bytes)", 
+        rtreeCheckAppendMsg(pCheck,
+            "Node %lld is too small for cell count of %d (%d bytes)",
             iNode, nCell, nNode
         );
       }else{
@@ -187473,11 +193541,11 @@ static int rtreeCheckTable(
 **       b) unless the cell is on the root node, that the cell is bounded
 **          by the parent cell on the parent node.
 **
-**       c) for leaf nodes, that there is an entry in the %_rowid 
-**          table corresponding to the cell's rowid value that 
+**       c) for leaf nodes, that there is an entry in the %_rowid
+**          table corresponding to the cell's rowid value that
 **          points to the correct node.
 **
-**       d) for cells on non-leaf nodes, that there is an entry in the 
+**       d) for cells on non-leaf nodes, that there is an entry in the
 **          %_parent table mapping from the cell's child node to the
 **          node that it resides on.
 **
@@ -187486,17 +193554,17 @@ static int rtreeCheckTable(
 **      is a leaf cell that corresponds to each entry in the %_rowid table.
 **
 **   3. That there are the same number of entries in the %_parent table
-**      as there are non-leaf cells in the r-tree structure, and that 
-**      there is a non-leaf cell that corresponds to each entry in the 
+**      as there are non-leaf cells in the r-tree structure, and that
+**      there is a non-leaf cell that corresponds to each entry in the
 **      %_parent table.
 */
 static void rtreecheck(
-  sqlite3_context *ctx, 
-  int nArg, 
+  sqlite3_context *ctx,
+  int nArg,
   sqlite3_value **apArg
 ){
   if( nArg!=1 && nArg!=2 ){
-    sqlite3_result_error(ctx, 
+    sqlite3_result_error(ctx,
         "wrong number of arguments to function rtreecheck()", -1
     );
   }else{
@@ -187887,7 +193955,7 @@ static void geopolyBlobFunc(
 ){
   GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
   if( p ){
-    sqlite3_result_blob(context, p->hdr, 
+    sqlite3_result_blob(context, p->hdr,
        4+8*p->nVertex, SQLITE_TRANSIENT);
     sqlite3_free(p);
   }
@@ -187995,7 +194063,7 @@ static void geopolyXformFunc(
       GeoX(p,ii) = x1;
       GeoY(p,ii) = y1;
     }
-    sqlite3_result_blob(context, p->hdr, 
+    sqlite3_result_blob(context, p->hdr,
        4+8*p->nVertex, SQLITE_TRANSIENT);
     sqlite3_free(p);
   }
@@ -188039,7 +194107,7 @@ static void geopolyAreaFunc(
   if( p ){
     sqlite3_result_double(context, geopolyArea(p));
     sqlite3_free(p);
-  }            
+  }
 }
 
 /*
@@ -188047,7 +194115,7 @@ static void geopolyAreaFunc(
 **
 ** If the rotation of polygon X is clockwise (incorrect) instead of
 ** counter-clockwise (the correct winding order according to RFC7946)
-** then reverse the order of the vertexes in polygon X.  
+** then reverse the order of the vertexes in polygon X.
 **
 ** In other words, this routine returns a CCW polygon regardless of the
 ** winding order of its input.
@@ -188073,10 +194141,10 @@ static void geopolyCcwFunc(
         GeoY(p,jj) = t;
       }
     }
-    sqlite3_result_blob(context, p->hdr, 
+    sqlite3_result_blob(context, p->hdr,
        4+8*p->nVertex, SQLITE_TRANSIENT);
     sqlite3_free(p);
-  }            
+  }
 }
 
 #define GEOPOLY_PI 3.1415926535897932385
@@ -188209,6 +194277,8 @@ static GeoPoly *geopolyBBox(
       aCoord[2].f = mnY;
       aCoord[3].f = mxY;
     }
+  }else{
+    memset(aCoord, 0, sizeof(RtreeCoord)*4);
   }
   return pOut;
 }
@@ -188223,7 +194293,7 @@ static void geopolyBBoxFunc(
 ){
   GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
   if( p ){
-    sqlite3_result_blob(context, p->hdr, 
+    sqlite3_result_blob(context, p->hdr,
        4+8*p->nVertex, SQLITE_TRANSIENT);
     sqlite3_free(p);
   }
@@ -188274,7 +194344,7 @@ static void geopolyBBoxFinal(
   if( pBBox==0 ) return;
   p = geopolyBBox(context, 0, pBBox->a, 0);
   if( p ){
-    sqlite3_result_blob(context, p->hdr, 
+    sqlite3_result_blob(context, p->hdr,
        4+8*p->nVertex, SQLITE_TRANSIENT);
     sqlite3_free(p);
   }
@@ -188454,7 +194524,7 @@ static void geopolyAddOneSegment(
   pEvent->eType = 1;
   pEvent->pSeg = pSeg;
 }
-  
+
 
 
 /*
@@ -188494,7 +194564,7 @@ static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
     }
   }
   pLast->pNext = pRight ? pRight : pLeft;
-  return head.pNext;  
+  return head.pNext;
 }
 
 /*
@@ -188543,7 +194613,7 @@ static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
     }
   }
   pLast->pNext = pRight ? pRight : pLeft;
-  return head.pNext;  
+  return head.pNext;
 }
 
 /*
@@ -188588,8 +194658,8 @@ static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
   GeoSegment *pSeg;
   unsigned char aOverlap[4];
 
-  nByte = sizeof(GeoEvent)*nVertex*2 
-           + sizeof(GeoSegment)*nVertex 
+  nByte = sizeof(GeoEvent)*nVertex*2
+           + sizeof(GeoSegment)*nVertex
            + sizeof(GeoOverlap);
   p = sqlite3_malloc64( nByte );
   if( p==0 ) return -1;
@@ -188599,7 +194669,7 @@ static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
   geopolyAddSegments(p, p1, 1);
   geopolyAddSegments(p, p2, 2);
   pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
-  rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
+  rX = pThisEvent && pThisEvent->x==0.0 ? -1.0 : 0.0;
   memset(aOverlap, 0, sizeof(aOverlap));
   while( pThisEvent ){
     if( pThisEvent->x!=rX ){
@@ -188731,7 +194801,7 @@ static void geopolyDebugFunc(
 #endif
 }
 
-/* 
+/*
 ** This function is the implementation of both the xConnect and xCreate
 ** methods of the geopoly virtual table.
 **
@@ -188821,7 +194891,7 @@ geopolyInit_fail:
 }
 
 
-/* 
+/*
 ** GEOPOLY virtual table module xCreate method.
 */
 static int geopolyCreate(
@@ -188834,7 +194904,7 @@ static int geopolyCreate(
   return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
 }
 
-/* 
+/*
 ** GEOPOLY virtual table module xConnect method.
 */
 static int geopolyConnect(
@@ -188848,7 +194918,7 @@ static int geopolyConnect(
 }
 
 
-/* 
+/*
 ** GEOPOLY virtual table module xFilter method.
 **
 ** Query plans:
@@ -188871,17 +194941,11 @@ static int geopolyFilter(
   RtreeNode *pRoot = 0;
   int rc = SQLITE_OK;
   int iCell = 0;
-  sqlite3_stmt *pStmt;
 
   rtreeReference(pRtree);
 
   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
-  freeCursorConstraints(pCsr);
-  sqlite3_free(pCsr->aPoint);
-  pStmt = pCsr->pReadAux;
-  memset(pCsr, 0, sizeof(RtreeCursor));
-  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
-  pCsr->pReadAux = pStmt;
+  resetCursor(pCsr);
 
   pCsr->iStrategy = idxNum;
   if( idxNum==1 ){
@@ -188904,8 +194968,8 @@ static int geopolyFilter(
       pCsr->atEOF = 1;
     }
   }else{
-    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
-    ** with the configured constraints. 
+    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
+    ** with the configured constraints.
     */
     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
     if( rc==SQLITE_OK && idxNum<=3 ){
@@ -188986,7 +195050,7 @@ geopoly_filter_end:
 
 /*
 ** Rtree virtual table module xBestIndex method. There are three
-** table scan strategies to choose from (in order from most to 
+** table scan strategies to choose from (in order from most to
 ** least desirable):
 **
 **   idxNum     idxStr        Strategy
@@ -189046,7 +195110,7 @@ static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
 }
 
 
-/* 
+/*
 ** GEOPOLY virtual table module xColumn method.
 */
 static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
@@ -189066,7 +195130,7 @@ static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
                                 &pCsr->pReadAux, 0);
         if( rc ) return rc;
       }
-      sqlite3_bind_int64(pCsr->pReadAux, 1, 
+      sqlite3_bind_int64(pCsr->pReadAux, 1,
           nodeGetRowid(pRtree, pNode, p->iCell));
       rc = sqlite3_step(pCsr->pReadAux);
       if( rc==SQLITE_ROW ){
@@ -189105,9 +195169,9 @@ static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
 **     argv[3] = new value for first application-defined column....
 */
 static int geopolyUpdate(
-  sqlite3_vtab *pVtab, 
-  int nData, 
-  sqlite3_value **aData, 
+  sqlite3_vtab *pVtab,
+  int nData,
+  sqlite3_value **aData,
   sqlite_int64 *pRowid
 ){
   Rtree *pRtree = (Rtree *)pVtab;
@@ -189149,7 +195213,7 @@ static int geopolyUpdate(
     }
     coordChange = 1;
 
-    /* If a rowid value was supplied, check if it is already present in 
+    /* If a rowid value was supplied, check if it is already present in
     ** the table. If so, the constraint has failed. */
     if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
       int steprc;
@@ -189318,14 +195382,20 @@ static int sqlite3_geopoly_init(sqlite3 *db){
   };
   int i;
   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
-    int enc = aFunc[i].bPure ? SQLITE_UTF8|SQLITE_DETERMINISTIC : SQLITE_UTF8;
+    int enc;
+    if( aFunc[i].bPure ){
+      enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS;
+    }else{
+      enc = SQLITE_UTF8|SQLITE_DIRECTONLY;
+    }
     rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
                                  enc, 0,
                                  aFunc[i].xFunc, 0, 0);
   }
   for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
-    rc = sqlite3_create_function(db, aAgg[i].zName, 1, SQLITE_UTF8, 0,
-                                 0, aAgg[i].xStep, aAgg[i].xFinal);
+    rc = sqlite3_create_function(db, aAgg[i].zName, 1,
+              SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0,
+              0, aAgg[i].xStep, aAgg[i].xFinal);
   }
   if( rc==SQLITE_OK ){
     rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
@@ -189339,7 +195409,7 @@ static int sqlite3_geopoly_init(sqlite3 *db){
 
 /*
 ** Register the r-tree module with database handle db. This creates the
-** virtual table module "rtree" and the debugging/analysis scalar 
+** virtual table module "rtree" and the debugging/analysis scalar
 ** function "rtreenode".
 */
 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
@@ -189466,7 +195536,7 @@ SQLITE_API int sqlite3_rtree_geometry_callback(
   pGeomCtx->xQueryFunc = 0;
   pGeomCtx->xDestructor = 0;
   pGeomCtx->pContext = pContext;
-  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
+  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   );
 }
@@ -189491,7 +195561,7 @@ SQLITE_API int sqlite3_rtree_query_callback(
   pGeomCtx->xQueryFunc = xQueryFunc;
   pGeomCtx->xDestructor = xDestructor;
   pGeomCtx->pContext = pContext;
-  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 
+  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
   );
 }
@@ -189527,9 +195597,9 @@ SQLITE_API int sqlite3_rtree_init(
 *************************************************************************
 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
 **
-** This file implements an integration between the ICU library 
-** ("International Components for Unicode", an open-source library 
-** for handling unicode data) and SQLite. The integration uses 
+** This file implements an integration between the ICU library
+** ("International Components for Unicode", an open-source library
+** for handling unicode data) and SQLite. The integration uses
 ** ICU to provide the following to SQLite:
 **
 **   * An implementation of the SQL regexp() function (and hence REGEXP
@@ -189540,7 +195610,7 @@ SQLITE_API int sqlite3_rtree_init(
 **
 **   * Integration of ICU and SQLite collation sequences.
 **
-**   * An implementation of the LIKE operator that uses ICU to 
+**   * An implementation of the LIKE operator that uses ICU to
 **     provide case-independent matching.
 */
 
@@ -189567,7 +195637,7 @@ SQLITE_API int sqlite3_rtree_init(
 ** This function is called when an ICU function called from within
 ** the implementation of an SQL scalar function returns an error.
 **
-** The scalar function context passed as the first argument is 
+** The scalar function context passed as the first argument is
 ** loaded with an error message based on the following two args.
 */
 static void icuFunctionError(
@@ -189632,7 +195702,7 @@ static const unsigned char icuUtf8Trans1[] = {
 
 /*
 ** Compare two UTF-8 strings for equality where the first string is
-** a "LIKE" expression. Return true (1) if they are the same and 
+** a "LIKE" expression. Return true (1) if they are the same and
 ** false (0) if they are different.
 */
 static int icuLikeCompare(
@@ -189659,12 +195729,12 @@ static int icuLikeCompare(
     **     3. uPattern is an unescaped escape character, or
     **     4. uPattern is to be handled as an ordinary character
     */
-    if( !prevEscape && uPattern==MATCH_ALL ){
+    if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){
       /* Case 1. */
       uint8_t c;
 
       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
-      ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
+      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
       ** test string.
       */
       while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
@@ -189685,12 +195755,12 @@ static int icuLikeCompare(
       }
       return 0;
 
-    }else if( !prevEscape && uPattern==MATCH_ONE ){
+    }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){
       /* Case 2. */
       if( *zString==0 ) return 0;
       SQLITE_ICU_SKIP_UTF8(zString);
 
-    }else if( !prevEscape && uPattern==(uint32_t)uEsc){
+    }else if( uPattern==(uint32_t)uEsc && !prevEscape ){
       /* Case 3. */
       prevEscape = 1;
 
@@ -189717,15 +195787,15 @@ static int icuLikeCompare(
 **
 **       A LIKE B
 **
-** is implemented as like(B, A). If there is an escape character E, 
+** is implemented as like(B, A). If there is an escape character E,
 **
 **       A LIKE B ESCAPE E
 **
 ** is mapped to like(B, A, E).
 */
 static void icuLikeFunc(
-  sqlite3_context *context, 
-  int argc, 
+  sqlite3_context *context,
+  int argc,
   sqlite3_value **argv
 ){
   const unsigned char *zA = sqlite3_value_text(argv[0]);
@@ -189751,7 +195821,7 @@ static void icuLikeFunc(
     if( zE==0 ) return;
     U8_NEXT(zE, i, nE, uEsc);
     if( i!=nE){
-      sqlite3_result_error(context, 
+      sqlite3_result_error(context,
           "ESCAPE expression must be a single character", -1);
       return;
     }
@@ -189774,7 +195844,7 @@ static void icuRegexpDelete(void *p){
 /*
 ** Implementation of SQLite REGEXP operator. This scalar function takes
 ** two arguments. The first is a regular expression pattern to compile
-** the second is a string to match against that pattern. If either 
+** the second is a string to match against that pattern. If either
 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
 ** is 1 if the string matches the pattern, or 0 otherwise.
 **
@@ -189798,8 +195868,8 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
 
   (void)nArg;  /* Unused parameter */
 
-  /* If the left hand side of the regexp operator is NULL, 
-  ** then the result is also NULL. 
+  /* If the left hand side of the regexp operator is NULL,
+  ** then the result is also NULL.
   */
   if( !zString ){
     return;
@@ -189837,7 +195907,7 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
   }
 
   /* Set the text that the regular expression operates on to a NULL
-  ** pointer. This is not really necessary, but it is tidier than 
+  ** pointer. This is not really necessary, but it is tidier than
   ** leaving the regular expression object configured with an invalid
   ** pointer after this function returns.
   */
@@ -189848,7 +195918,7 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
 }
 
 /*
-** Implementations of scalar functions for case mapping - upper() and 
+** Implementations of scalar functions for case mapping - upper() and
 ** lower(). Function upper() converts its input to upper-case (ABC).
 ** Function lower() converts to lower-case (abc).
 **
@@ -189856,7 +195926,7 @@ static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
 ** "language specific". Refer to ICU documentation for the differences
 ** between the two.
 **
-** To utilise "general" case mapping, the upper() or lower() scalar 
+** To utilise "general" case mapping, the upper() or lower() scalar
 ** functions are invoked with one argument:
 **
 **     upper('ABC') -> 'abc'
@@ -189964,7 +196034,7 @@ static int icuCollationColl(
 /*
 ** Implementation of the scalar function icu_load_collation().
 **
-** This scalar function is used to add ICU collation based collation 
+** This scalar function is used to add ICU collation based collation
 ** types to an SQLite database connection. It is intended to be called
 ** as follows:
 **
@@ -189975,8 +196045,8 @@ static int icuCollationColl(
 ** collation sequence to create.
 */
 static void icuLoadCollation(
-  sqlite3_context *p, 
-  int nArg, 
+  sqlite3_context *p,
+  int nArg,
   sqlite3_value **apArg
 ){
   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
@@ -190002,7 +196072,7 @@ static void icuLoadCollation(
   }
   assert(p);
 
-  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
+  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
       icuCollationColl, icuCollationDel
   );
   if( rc!=SQLITE_OK ){
@@ -190015,35 +196085,36 @@ static void icuLoadCollation(
 ** Register the ICU extension functions with database db.
 */
 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
+# define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
   static const struct IcuScalar {
     const char *zName;                        /* Function name */
     unsigned char nArg;                       /* Number of arguments */
-    unsigned short enc;                       /* Optimal text encoding */
+    unsigned int enc;                         /* Optimal text encoding */
     unsigned char iContext;                   /* sqlite3_user_data() context */
     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
   } scalars[] = {
-    {"icu_load_collation",  2, SQLITE_UTF8,                1, icuLoadCollation},
+    {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
-    {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC,         0, icuRegexpFunc},
-    {"lower",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
-    {"lower",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       0, icuCaseFunc16},
-    {"upper",  1, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
-    {"upper",  2, SQLITE_UTF16|SQLITE_DETERMINISTIC,       1, icuCaseFunc16},
-    {"lower",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
-    {"lower",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuCaseFunc16},
-    {"upper",  1, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
-    {"upper",  2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        1, icuCaseFunc16},
-    {"like",   2, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
-    {"like",   3, SQLITE_UTF8|SQLITE_DETERMINISTIC,        0, icuLikeFunc},
+    {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS,         0, icuRegexpFunc},
+    {"lower",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},
+    {"lower",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       0, icuCaseFunc16},
+    {"upper",  1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},
+    {"upper",  2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS,       1, icuCaseFunc16},
+    {"lower",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},
+    {"lower",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuCaseFunc16},
+    {"upper",  1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},
+    {"upper",  2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        1, icuCaseFunc16},
+    {"like",   2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},
+    {"like",   3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS,        0, icuLikeFunc},
 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
   };
   int rc = SQLITE_OK;
   int i;
-  
+
   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
     const struct IcuScalar *p = &scalars[i];
     rc = sqlite3_create_function(
-        db, p->zName, p->nArg, p->enc, 
+        db, p->zName, p->nArg, p->enc,
         p->iContext ? (void*)db : (void*)0,
         p->xFunc, 0, 0
     );
@@ -190057,7 +196128,7 @@ SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
 __declspec(dllexport)
 #endif
 SQLITE_API int sqlite3_icu_init(
-  sqlite3 *db, 
+  sqlite3 *db,
   char **pzErrMsg,
   const sqlite3_api_routines *pApi
 ){
@@ -190160,7 +196231,7 @@ static int icuDestroy(sqlite3_tokenizer *pTokenizer){
 /*
 ** Prepare to begin tokenizing a particular string.  The input
 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
-** used to incrementally tokenize this string is returned in 
+** used to incrementally tokenize this string is returned in
 ** *ppCursor.
 */
 static int icuOpen(
@@ -190202,7 +196273,7 @@ static int icuOpen(
   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
 
   pCsr->aOffset[iOut] = iInput;
-  U8_NEXT(zInput, iInput, nInput, c); 
+  U8_NEXT(zInput, iInput, nInput, c);
   while( c>0 ){
     int isError = 0;
     c = u_foldCase(c, opt);
@@ -190348,7 +196419,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 *************************************************************************
 **
 **
-** OVERVIEW 
+** OVERVIEW
 **
 **  The RBU extension requires that the RBU update be packaged as an
 **  SQLite database. The tables it expects to find are described in
@@ -190356,34 +196427,34 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **  that the user wishes to write to, a corresponding data_xyz table is
 **  created in the RBU database and populated with one row for each row to
 **  update, insert or delete from the target table.
-** 
+**
 **  The update proceeds in three stages:
-** 
+**
 **  1) The database is updated. The modified database pages are written
 **     to a *-oal file. A *-oal file is just like a *-wal file, except
 **     that it is named "<database>-oal" instead of "<database>-wal".
 **     Because regular SQLite clients do not look for file named
 **     "<database>-oal", they go on using the original database in
 **     rollback mode while the *-oal file is being generated.
-** 
+**
 **     During this stage RBU does not update the database by writing
 **     directly to the target tables. Instead it creates "imposter"
 **     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
 **     to update each b-tree individually. All updates required by each
 **     b-tree are completed before moving on to the next, and all
 **     updates are done in sorted key order.
-** 
+**
 **  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
 **     location using a call to rename(2). Before doing this the RBU
 **     module takes an EXCLUSIVE lock on the database file, ensuring
 **     that there are no other active readers.
-** 
+**
 **     Once the EXCLUSIVE lock is released, any other database readers
 **     detect the new *-wal file and read the database in wal mode. At
 **     this point they see the new version of the database - including
 **     the updates made as part of the RBU update.
-** 
-**  3) The new *-wal file is checkpointed. This proceeds in the same way 
+**
+**  3) The new *-wal file is checkpointed. This proceeds in the same way
 **     as a regular database checkpoint, except that a single frame is
 **     checkpointed each time sqlite3rbu_step() is called. If the RBU
 **     handle is closed before the entire *-wal file is checkpointed,
@@ -190392,7 +196463,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **     the future.
 **
 ** POTENTIAL PROBLEMS
-** 
+**
 **  The rename() call might not be portable. And RBU is not currently
 **  syncing the directory after renaming the file.
 **
@@ -190414,7 +196485,7 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **  fields are collected.  This means we're probably writing a lot more
 **  data to disk when saving the state of an ongoing update to the RBU
 **  update database than is strictly necessary.
-** 
+**
 */
 
 /* #include <assert.h> */
@@ -190438,42 +196509,42 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **
 *************************************************************************
 **
-** This file contains the public interface for the RBU extension. 
+** This file contains the public interface for the RBU extension.
 */
 
 /*
 ** SUMMARY
 **
-** Writing a transaction containing a large number of operations on 
+** Writing a transaction containing a large number of operations on
 ** b-tree indexes that are collectively larger than the available cache
-** memory can be very inefficient. 
+** memory can be very inefficient.
 **
 ** The problem is that in order to update a b-tree, the leaf page (at least)
 ** containing the entry being inserted or deleted must be modified. If the
-** working set of leaves is larger than the available cache memory, then a 
-** single leaf that is modified more than once as part of the transaction 
+** working set of leaves is larger than the available cache memory, then a
+** single leaf that is modified more than once as part of the transaction
 ** may be loaded from or written to the persistent media multiple times.
 ** Additionally, because the index updates are likely to be applied in
-** random order, access to pages within the database is also likely to be in 
+** random order, access to pages within the database is also likely to be in
 ** random order, which is itself quite inefficient.
 **
 ** One way to improve the situation is to sort the operations on each index
 ** by index key before applying them to the b-tree. This leads to an IO
 ** pattern that resembles a single linear scan through the index b-tree,
-** and all but guarantees each modified leaf page is loaded and stored 
+** and all but guarantees each modified leaf page is loaded and stored
 ** exactly once. SQLite uses this trick to improve the performance of
 ** CREATE INDEX commands. This extension allows it to be used to improve
 ** the performance of large transactions on existing databases.
 **
-** Additionally, this extension allows the work involved in writing the 
-** large transaction to be broken down into sub-transactions performed 
-** sequentially by separate processes. This is useful if the system cannot 
-** guarantee that a single update process will run for long enough to apply 
-** the entire update, for example because the update is being applied on a 
-** mobile device that is frequently rebooted. Even after the writer process 
+** Additionally, this extension allows the work involved in writing the
+** large transaction to be broken down into sub-transactions performed
+** sequentially by separate processes. This is useful if the system cannot
+** guarantee that a single update process will run for long enough to apply
+** the entire update, for example because the update is being applied on a
+** mobile device that is frequently rebooted. Even after the writer process
 ** has committed one or more sub-transactions, other database clients continue
-** to read from the original database snapshot. In other words, partially 
-** applied transactions are not visible to other clients. 
+** to read from the original database snapshot. In other words, partially
+** applied transactions are not visible to other clients.
 **
 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
 ** transmitted via a wireless network to a mobile device. A transaction
@@ -190489,9 +196560,9 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **
 **   * INSERT statements may not use any default values.
 **
-**   * UPDATE and DELETE statements must identify their target rows by 
+**   * UPDATE and DELETE statements must identify their target rows by
 **     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
-**     KEY fields may not be updated or deleted. If the table being written 
+**     KEY fields may not be updated or deleted. If the table being written
 **     has no PRIMARY KEY, affected rows must be identified by rowid.
 **
 **   * UPDATE statements may not modify PRIMARY KEY columns.
@@ -190508,10 +196579,10 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 ** PREPARATION
 **
 ** An "RBU update" is stored as a separate SQLite database. A database
-** containing an RBU update is an "RBU database". For each table in the 
+** containing an RBU update is an "RBU database". For each table in the
 ** target database to be updated, the RBU database should contain a table
 ** named "data_<target name>" containing the same set of columns as the
-** target table, and one more - "rbu_control". The data_% table should 
+** target table, and one more - "rbu_control". The data_% table should
 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
 ** the same type as the corresponding column in the target database.
 ** The "rbu_control" column should have no type at all. For example, if
@@ -190526,22 +196597,22 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 ** The order of the columns in the data_% table does not matter.
 **
 ** Instead of a regular table, the RBU database may also contain virtual
-** tables or view named using the data_<target> naming scheme. 
+** tables or view named using the data_<target> naming scheme.
 **
-** Instead of the plain data_<target> naming scheme, RBU database tables 
+** Instead of the plain data_<target> naming scheme, RBU database tables
 ** may also be named data<integer>_<target>, where <integer> is any sequence
 ** of zero or more numeric characters (0-9). This can be significant because
-** tables within the RBU database are always processed in order sorted by 
+** tables within the RBU database are always processed in order sorted by
 ** name. By judicious selection of the <integer> portion of the names
 ** of the RBU tables the user can therefore control the order in which they
 ** are processed. This can be useful, for example, to ensure that "external
 ** content" FTS4 tables are updated before their underlying content tables.
 **
 ** If the target database table is a virtual table or a table that has no
-** PRIMARY KEY declaration, the data_% table must also contain a column 
-** named "rbu_rowid". This column is mapped to the tables implicit primary 
-** key column - "rowid". Virtual tables for which the "rowid" column does 
-** not function like a primary key value cannot be updated using RBU. For 
+** PRIMARY KEY declaration, the data_% table must also contain a column
+** named "rbu_rowid". This column is mapped to the tables implicit primary
+** key column - "rowid". Virtual tables for which the "rowid" column does
+** not function like a primary key value cannot be updated using RBU. For
 ** example, if the target db contains either of the following:
 **
 **   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
@@ -190564,35 +196635,35 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
 **   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
 **
-** For each row to INSERT into the target database as part of the RBU 
+** For each row to INSERT into the target database as part of the RBU
 ** update, the corresponding data_% table should contain a single record
 ** with the "rbu_control" column set to contain integer value 0. The
-** other columns should be set to the values that make up the new record 
-** to insert. 
+** other columns should be set to the values that make up the new record
+** to insert.
 **
-** If the target database table has an INTEGER PRIMARY KEY, it is not 
-** possible to insert a NULL value into the IPK column. Attempting to 
+** If the target database table has an INTEGER PRIMARY KEY, it is not
+** possible to insert a NULL value into the IPK column. Attempting to
 ** do so results in an SQLITE_MISMATCH error.
 **
-** For each row to DELETE from the target database as part of the RBU 
+** For each row to DELETE from the target database as part of the RBU
 ** update, the corresponding data_% table should contain a single record
 ** with the "rbu_control" column set to contain integer value 1. The
 ** real primary key values of the row to delete should be stored in the
 ** corresponding columns of the data_% table. The values stored in the
 ** other columns are not used.
 **
-** For each row to UPDATE from the target database as part of the RBU 
+** For each row to UPDATE from the target database as part of the RBU
 ** update, the corresponding data_% table should contain a single record
 ** with the "rbu_control" column set to contain a value of type text.
-** The real primary key values identifying the row to update should be 
+** The real primary key values identifying the row to update should be
 ** stored in the corresponding columns of the data_% table row, as should
-** the new values of all columns being update. The text value in the 
+** the new values of all columns being update. The text value in the
 ** "rbu_control" column must contain the same number of characters as
 ** there are columns in the target database table, and must consist entirely
-** of 'x' and '.' characters (or in some special cases 'd' - see below). For 
+** of 'x' and '.' characters (or in some special cases 'd' - see below). For
 ** each column that is being updated, the corresponding character is set to
 ** 'x'. For those that remain as they are, the corresponding character of the
-** rbu_control value should be set to '.'. For example, given the tables 
+** rbu_control value should be set to '.'. For example, given the tables
 ** above, the update statement:
 **
 **   UPDATE t1 SET c = 'usa' WHERE a = 4;
@@ -190606,30 +196677,30 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 ** target table with the value stored in the corresponding data_% column, the
 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
 ** the target table column. rbu_delta() is invoked with two arguments - the
-** original value currently stored in the target table column and the 
+** original value currently stored in the target table column and the
 ** value specified in the data_xxx table.
 **
 ** For example, this row:
 **
 **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
 **
-** is similar to an UPDATE statement such as: 
+** is similar to an UPDATE statement such as:
 **
 **   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
 **
-** Finally, if an 'f' character appears in place of a 'd' or 's' in an 
+** Finally, if an 'f' character appears in place of a 'd' or 's' in an
 ** ota_control string, the contents of the data_xxx table column is assumed
 ** to be a "fossil delta" - a patch to be applied to a blob value in the
 ** format used by the fossil source-code management system. In this case
-** the existing value within the target database table must be of type BLOB. 
+** the existing value within the target database table must be of type BLOB.
 ** It is replaced by the result of applying the specified fossil delta to
 ** itself.
 **
 ** If the target database table is a virtual table or a table with no PRIMARY
-** KEY, the rbu_control value should not include a character corresponding 
+** KEY, the rbu_control value should not include a character corresponding
 ** to the rbu_rowid value. For example, this:
 **
-**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) 
+**   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
 **       VALUES(NULL, 'usa', 12, '.x');
 **
 ** causes a result similar to:
@@ -190639,14 +196710,14 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
 ** However, RBU is more efficient if reading the rows in from each data_xxx
 ** table in "rowid" order is roughly the same as reading them sorted by
-** the PRIMARY KEY of the corresponding target database table. In other 
-** words, rows should be sorted using the destination table PRIMARY KEY 
+** the PRIMARY KEY of the corresponding target database table. In other
+** words, rows should be sorted using the destination table PRIMARY KEY
 ** fields before they are inserted into the data_xxx tables.
 **
 ** USAGE
 **
-** The API declared below allows an application to apply an RBU update 
-** stored on disk to an existing target database. Essentially, the 
+** The API declared below allows an application to apply an RBU update
+** stored on disk to an existing target database. Essentially, the
 ** application:
 **
 **     1) Opens an RBU handle using the sqlite3rbu_open() function.
@@ -190657,24 +196728,24 @@ SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
 **
 **     3) Calls the sqlite3rbu_step() function one or more times on
 **        the new handle. Each call to sqlite3rbu_step() performs a single
-**        b-tree operation, so thousands of calls may be required to apply 
+**        b-tree operation, so thousands of calls may be required to apply
 **        a complete update.
 **
 **     4) Calls sqlite3rbu_close() to close the RBU update handle. If
 **        sqlite3rbu_step() has been called enough times to completely
 **        apply the update to the target database, then the RBU database
-**        is marked as fully applied. Otherwise, the state of the RBU 
-**        update application is saved in the RBU database for later 
+**        is marked as fully applied. Otherwise, the state of the RBU
+**        update application is saved in the RBU database for later
 **        resumption.
 **
 ** See comments below for more detail on APIs.
 **
 ** If an update is only partially applied to the target database by the
-** time sqlite3rbu_close() is called, various state information is saved 
+** time sqlite3rbu_close() is called, various state information is saved
 ** within the RBU database. This allows subsequent processes to automatically
 ** resume the RBU update from where it left off.
 **
-** To remove all RBU extension state information, returning an RBU database 
+** To remove all RBU extension state information, returning an RBU database
 ** to its original contents, it is sufficient to drop all tables that begin
 ** with the prefix "rbu_"
 **
@@ -190710,21 +196781,21 @@ typedef struct sqlite3rbu sqlite3rbu;
 ** the path to the RBU database. Each call to this function must be matched
 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
-** or zRbu begin with "file:", it will be interpreted as an SQLite 
+** or zRbu begin with "file:", it will be interpreted as an SQLite
 ** database URI, not a regular file name.
 **
-** If the zState argument is passed a NULL value, the RBU extension stores 
-** the current state of the update (how many rows have been updated, which 
+** If the zState argument is passed a NULL value, the RBU extension stores
+** the current state of the update (how many rows have been updated, which
 ** indexes are yet to be updated etc.) within the RBU database itself. This
 ** can be convenient, as it means that the RBU application does not need to
-** organize removing a separate state file after the update is concluded. 
-** Or, if zState is non-NULL, it must be a path to a database file in which 
+** organize removing a separate state file after the update is concluded.
+** Or, if zState is non-NULL, it must be a path to a database file in which
 ** the RBU extension can store the state of the update.
 **
 ** When resuming an RBU update, the zState argument must be passed the same
 ** value as when the RBU update was started.
 **
-** Once the RBU update is finished, the RBU extension does not 
+** Once the RBU update is finished, the RBU extension does not
 ** automatically remove any zState database file, even if it created it.
 **
 ** By default, RBU uses the default VFS to access the files on disk. To
@@ -190737,7 +196808,7 @@ typedef struct sqlite3rbu sqlite3rbu;
 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
 */
 SQLITE_API sqlite3rbu *sqlite3rbu_open(
-  const char *zTarget, 
+  const char *zTarget,
   const char *zRbu,
   const char *zState
 );
@@ -190747,13 +196818,13 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open(
 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
 ** that it can be suspended and resumed like an RBU update.
 **
-** The second argument to this function identifies a database in which 
-** to store the state of the RBU vacuum operation if it is suspended. The 
+** The second argument to this function identifies a database in which
+** to store the state of the RBU vacuum operation if it is suspended. The
 ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
 ** operation, the state database should either not exist or be empty
-** (contain no tables). If an RBU vacuum is suspended by calling 
+** (contain no tables). If an RBU vacuum is suspended by calling
 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
-** returned SQLITE_DONE, the vacuum state is stored in the state database. 
+** returned SQLITE_DONE, the vacuum state is stored in the state database.
 ** The vacuum can be resumed by calling this function to open a new RBU
 ** handle specifying the same target and state databases.
 **
@@ -190761,26 +196832,26 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open(
 ** name of the state database is "<database>-vacuum", where <database>
 ** is the name of the target database file. In this case, on UNIX, if the
 ** state database is not already present in the file-system, it is created
-** with the same permissions as the target db is made. 
+** with the same permissions as the target db is made.
 **
-** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the 
-** state database ends with "-vactmp". This name is reserved for internal 
+** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
+** state database ends with "-vactmp". This name is reserved for internal
 ** use.
 **
 ** This function does not delete the state database after an RBU vacuum
 ** is completed, even if it created it. However, if the call to
 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
 ** of the state tables within the state database are zeroed. This way,
-** the next call to sqlite3rbu_vacuum() opens a handle that starts a 
+** the next call to sqlite3rbu_vacuum() opens a handle that starts a
 ** new RBU vacuum operation.
 **
 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
-** describing the sqlite3rbu_create_vfs() API function below for 
-** a description of the complications associated with using RBU with 
+** describing the sqlite3rbu_create_vfs() API function below for
+** a description of the complications associated with using RBU with
 ** zipvfs databases.
 */
 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
-  const char *zTarget, 
+  const char *zTarget,
   const char *zState
 );
 
@@ -190792,7 +196863,7 @@ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
 ** is removed entirely. If the second parameter is negative, the limit is
 ** not modified (this is useful for querying the current limit).
 **
-** In all cases the returned value is the current limit in bytes (zero 
+** In all cases the returned value is the current limit in bytes (zero
 ** indicates unlimited).
 **
 ** If the temp space limit is exceeded during operation, an SQLITE_FULL
@@ -190801,13 +196872,13 @@ SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
 
 /*
-** Return the current amount of temp file space, in bytes, currently used by 
+** Return the current amount of temp file space, in bytes, currently used by
 ** the RBU handle passed as the only argument.
 */
 SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
 
 /*
-** Internally, each RBU connection uses a separate SQLite database 
+** Internally, each RBU connection uses a separate SQLite database
 ** connection to access the target and rbu update databases. This
 ** API allows the application direct access to these database handles.
 **
@@ -190818,10 +196889,10 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
 ** following scenarios:
 **
 **   * If any target tables are virtual tables, it may be necessary to
-**     call sqlite3_create_module() on the target database handle to 
+**     call sqlite3_create_module() on the target database handle to
 **     register the required virtual table implementations.
 **
-**   * If the data_xxx tables in the RBU source database are virtual 
+**   * If the data_xxx tables in the RBU source database are virtual
 **     tables, the application may need to call sqlite3_create_module() on
 **     the rbu update db handle to any required virtual table
 **     implementations.
@@ -190840,12 +196911,12 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
 SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
 
 /*
-** Do some work towards applying the RBU update to the target db. 
+** Do some work towards applying the RBU update to the target db.
 **
-** Return SQLITE_DONE if the update has been completely applied, or 
+** Return SQLITE_DONE if the update has been completely applied, or
 ** SQLITE_OK if no error occurs but there remains work to do to apply
-** the RBU update. If an error does occur, some other error code is 
-** returned. 
+** the RBU update. If an error does occur, some other error code is
+** returned.
 **
 ** Once a call to sqlite3rbu_step() has returned a value other than
 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
@@ -190858,7 +196929,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
 **
 ** If a power failure or application crash occurs during an update, following
 ** system recovery RBU may resume the update from the point at which the state
-** was last saved. In other words, from the most recent successful call to 
+** was last saved. In other words, from the most recent successful call to
 ** sqlite3rbu_close() or this function.
 **
 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
@@ -190866,7 +196937,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
 SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
 
 /*
-** Close an RBU handle. 
+** Close an RBU handle.
 **
 ** If the RBU update has been completely applied, mark the RBU database
 ** as fully applied. Otherwise, assuming no error has occurred, save the
@@ -190880,20 +196951,20 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
 ** eventually free any such buffer using sqlite3_free().
 **
 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
-** update has been partially applied, or SQLITE_DONE if it has been 
+** update has been partially applied, or SQLITE_DONE if it has been
 ** completely applied.
 */
 SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
 
 /*
-** Return the total number of key-value operations (inserts, deletes or 
+** Return the total number of key-value operations (inserts, deletes or
 ** updates) that have been performed on the target database since the
 ** current RBU update was started.
 */
 SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
 
 /*
-** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) 
+** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
 ** progress indications for the two stages of an RBU update. This API may
 ** be useful for driving GUI progress indicators and similar.
 **
@@ -190906,16 +196977,16 @@ SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
 ** The update is visible to non-RBU clients during stage 2. During stage 1
 ** non-RBU reader clients may see the original database.
 **
-** If this API is called during stage 2 of the update, output variable 
+** If this API is called during stage 2 of the update, output variable
 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
 ** to a value between 0 and 10000 to indicate the permyriadage progress of
-** stage 2. A value of 5000 indicates that stage 2 is half finished, 
+** stage 2. A value of 5000 indicates that stage 2 is half finished,
 ** 9000 indicates that it is 90% finished, and so on.
 **
-** If this API is called during stage 1 of the update, output variable 
+** If this API is called during stage 1 of the update, output variable
 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
-** value to which (*pnOne) is set depends on whether or not the RBU 
-** database contains an "rbu_count" table. The rbu_count table, if it 
+** value to which (*pnOne) is set depends on whether or not the RBU
+** database contains an "rbu_count" table. The rbu_count table, if it
 ** exists, must contain the same columns as the following:
 **
 **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
@@ -190974,20 +197045,20 @@ SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
 
 /*
 ** Create an RBU VFS named zName that accesses the underlying file-system
-** via existing VFS zParent. Or, if the zParent parameter is passed NULL, 
+** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
 ** then the new RBU VFS uses the default system VFS to access the file-system.
-** The new object is registered as a non-default VFS with SQLite before 
+** The new object is registered as a non-default VFS with SQLite before
 ** returning.
 **
 ** Part of the RBU implementation uses a custom VFS object. Usually, this
-** object is created and deleted automatically by RBU. 
+** object is created and deleted automatically by RBU.
 **
 ** The exception is for applications that also use zipvfs. In this case,
 ** the custom VFS must be explicitly created by the user before the RBU
 ** handle is opened. The RBU VFS should be installed so that the zipvfs
-** VFS uses the RBU VFS, which in turn uses any other VFS layers in use 
+** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
 ** (for example multiplexor) to access the file-system. For example,
-** to assemble an RBU enabled VFS stack that uses both zipvfs and 
+** to assemble an RBU enabled VFS stack that uses both zipvfs and
 ** multiplexor (error checking omitted):
 **
 **     // Create a VFS named "multiplex" (not the default).
@@ -191009,9 +197080,9 @@ SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
 ** that does not include the RBU layer results in an error.
 **
-** The overhead of adding the "rbu" VFS to the system is negligible for 
-** non-RBU users. There is no harm in an application accessing the 
-** file-system via "rbu" all the time, even if it only uses RBU functionality 
+** The overhead of adding the "rbu" VFS to the system is negligible for
+** non-RBU users. There is no harm in an application accessing the
+** file-system via "rbu" all the time, even if it only uses RBU functionality
 ** occasionally.
 */
 SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
@@ -191064,17 +197135,17 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
 ** RBU_STATE_STAGE:
 **   May be set to integer values 1, 2, 4 or 5. As follows:
 **       1: the *-rbu file is currently under construction.
-**       2: the *-rbu file has been constructed, but not yet moved 
+**       2: the *-rbu file has been constructed, but not yet moved
 **          to the *-wal path.
 **       4: the checkpoint is underway.
 **       5: the rbu update has been checkpointed.
 **
 ** RBU_STATE_TBL:
-**   Only valid if STAGE==1. The target database name of the table 
+**   Only valid if STAGE==1. The target database name of the table
 **   currently being written.
 **
 ** RBU_STATE_IDX:
-**   Only valid if STAGE==1. The target database name of the index 
+**   Only valid if STAGE==1. The target database name of the index
 **   currently being written, or NULL if the main table is currently being
 **   updated.
 **
@@ -191094,14 +197165,14 @@ SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
 **   be continued if this happens).
 **
 ** RBU_STATE_COOKIE:
-**   Valid if STAGE==1. The current change-counter cookie value in the 
+**   Valid if STAGE==1. The current change-counter cookie value in the
 **   target db file.
 **
 ** RBU_STATE_OALSZ:
 **   Valid if STAGE==1. The size in bytes of the *-oal file.
 **
 ** RBU_STATE_DATATBL:
-**   Only valid if STAGE==1. The RBU database name of the table 
+**   Only valid if STAGE==1. The RBU database name of the table
 **   currently being read.
 */
 #define RBU_STATE_STAGE        1
@@ -191183,7 +197254,7 @@ struct RbuSpan {
 ** the target database that require updating. For each such table, the
 ** iterator visits, in order:
 **
-**     * the table itself, 
+**     * the table itself,
 **     * each index of the table (zero or more points to visit), and
 **     * a special "cleanup table" state.
 **
@@ -191197,7 +197268,7 @@ struct RbuSpan {
 **   this array set set to 1. This is because in that case, the module has
 **   no way to tell which fields will be required to add and remove entries
 **   from the partial indexes.
-**   
+**
 */
 struct RbuObjIter {
   sqlite3_stmt *pTblIter;         /* Iterate through tables */
@@ -191279,7 +197350,7 @@ struct RbuFrame {
 **
 ** nPhaseOneStep:
 **   If the RBU database contains an rbu_count table, this value is set to
-**   a running estimate of the number of b-tree operations required to 
+**   a running estimate of the number of b-tree operations required to
 **   finish populating the *-oal file. This allows the sqlite3_bp_progress()
 **   API to calculate the permyriadage progress of populating the *-oal file
 **   using the formula:
@@ -191299,7 +197370,7 @@ struct RbuFrame {
 **
 **     * the RBU update contains any UPDATE operations. If the PK specified
 **       for an UPDATE operation does not exist in the target table, then
-**       no b-tree operations are required on index b-trees. Or if the 
+**       no b-tree operations are required on index b-trees. Or if the
 **       specified PK does exist, then (nIndex*2) such operations are
 **       required (one delete and one insert on each index b-tree).
 **
@@ -191656,7 +197727,7 @@ static void rbuFossilDeltaFunc(
 /*
 ** Prepare the SQL statement in buffer zSql against database handle db.
 ** If successful, set *ppStmt to point to the new statement and return
-** SQLITE_OK. 
+** SQLITE_OK.
 **
 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
@@ -191664,7 +197735,7 @@ static void rbuFossilDeltaFunc(
 ** of the caller to (eventually) free this buffer using sqlite3_free().
 */
 static int prepareAndCollectError(
-  sqlite3 *db, 
+  sqlite3 *db,
   sqlite3_stmt **ppStmt,
   char **pzErrmsg,
   const char *zSql
@@ -191696,9 +197767,9 @@ static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
 /*
 ** Unless it is NULL, argument zSql points to a buffer allocated using
 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
-** statement against database db and frees the buffer. If statement 
-** compilation is successful, *ppStmt is set to point to the new statement 
-** handle and SQLITE_OK is returned. 
+** statement against database db and frees the buffer. If statement
+** compilation is successful, *ppStmt is set to point to the new statement
+** handle and SQLITE_OK is returned.
 **
 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
 ** returned. In this case, *pzErrmsg may also be set to point to an error
@@ -191709,7 +197780,7 @@ static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
 */
 static int prepareFreeAndCollectError(
-  sqlite3 *db, 
+  sqlite3 *db,
   sqlite3_stmt **ppStmt,
   char **pzErrmsg,
   char *zSql
@@ -191766,7 +197837,7 @@ static void rbuObjIterClearStatements(RbuObjIter *pIter){
   }
   sqlite3_free(pIter->aIdxCol);
   sqlite3_free(pIter->zIdxSql);
-  
+
   pIter->pSelect = 0;
   pIter->pInsert = 0;
   pIter->pDelete = 0;
@@ -191793,16 +197864,16 @@ static void rbuObjIterFinalize(RbuObjIter *pIter){
 /*
 ** Advance the iterator to the next position.
 **
-** If no error occurs, SQLITE_OK is returned and the iterator is left 
-** pointing to the next entry. Otherwise, an error code and message is 
-** left in the RBU handle passed as the first argument. A copy of the 
+** If no error occurs, SQLITE_OK is returned and the iterator is left
+** pointing to the next entry. Otherwise, an error code and message is
+** left in the RBU handle passed as the first argument. A copy of the
 ** error code is returned.
 */
 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
   int rc = p->rc;
   if( rc==SQLITE_OK ){
 
-    /* Free any SQLite statements used while processing the previous object */ 
+    /* Free any SQLite statements used while processing the previous object */
     rbuObjIterClearStatements(pIter);
     if( pIter->zIdx==0 ){
       rc = sqlite3_exec(p->dbMain,
@@ -191861,7 +197932,7 @@ static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
 ** The implementation of the rbu_target_name() SQL function. This function
 ** accepts one or two arguments. The first argument is the name of a table -
 ** the name of a table in the RBU database.  The second, if it is present, is 1
-** for a view or 0 for a table. 
+** for a view or 0 for a table.
 **
 ** For a non-vacuum RBU handle, if the table name matches the pattern:
 **
@@ -191909,19 +197980,19 @@ static void rbuTargetNameFunc(
 /*
 ** Initialize the iterator structure passed as the second argument.
 **
-** If no error occurs, SQLITE_OK is returned and the iterator is left 
-** pointing to the first entry. Otherwise, an error code and message is 
-** left in the RBU handle passed as the first argument. A copy of the 
+** If no error occurs, SQLITE_OK is returned and the iterator is left
+** pointing to the first entry. Otherwise, an error code and message is
+** left in the RBU handle passed as the first argument. A copy of the
 ** error code is returned.
 */
 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
   int rc;
   memset(pIter, 0, sizeof(RbuObjIter));
 
-  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, 
+  rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
     sqlite3_mprintf(
       "SELECT rbu_target_name(name, type='view') AS target, name "
-      "FROM sqlite_master "
+      "FROM sqlite_schema "
       "WHERE type IN ('table', 'view') AND target IS NOT NULL "
       " %s "
       "ORDER BY name"
@@ -191930,7 +198001,7 @@ static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
   if( rc==SQLITE_OK ){
     rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
         "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
-        "  FROM main.sqlite_master "
+        "  FROM main.sqlite_schema "
         "  WHERE type='index' AND tbl_name = ?"
     );
   }
@@ -191946,7 +198017,7 @@ static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
 **
 ** If an error has already occurred (p->rc is already set to something other
 ** than SQLITE_OK), then this function returns NULL without modifying the
-** stored error code. In this case it still calls sqlite3_free() on any 
+** stored error code. In this case it still calls sqlite3_free() on any
 ** printf() parameters associated with %z conversions.
 */
 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
@@ -191992,12 +198063,12 @@ static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
 }
 
 /*
-** Attempt to allocate and return a pointer to a zeroed block of nByte 
-** bytes. 
+** Attempt to allocate and return a pointer to a zeroed block of nByte
+** bytes.
 **
-** If an error (i.e. an OOM condition) occurs, return NULL and leave an 
-** error code in the rbu handle passed as the first argument. Or, if an 
-** error has already occurred when this function is called, return NULL 
+** If an error (i.e. an OOM condition) occurs, return NULL and leave an
+** error code in the rbu handle passed as the first argument. Or, if an
+** error has already occurred when this function is called, return NULL
 ** immediately without attempting the allocation or modifying the stored
 ** error code.
 */
@@ -192094,7 +198165,7 @@ static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
 **     RBU_PK_VTAB:          Table is a virtual table.
 **
 **   Argument *piPk is also of type (int*), and also points to an output
-**   parameter. Unless the table has an external primary key index 
+**   parameter. Unless the table has an external primary key index
 **   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
 **   if the table does have an external primary key index, then *piPk
 **   is set to the root page number of the primary key index before
@@ -192102,12 +198173,12 @@ static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
 **
 ** ALGORITHM:
 **
-**   if( no entry exists in sqlite_master ){
+**   if( no entry exists in sqlite_schema ){
 **     return RBU_PK_NOTABLE
 **   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
 **     return RBU_PK_VTAB
 **   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
-**     if( the index that is the pk exists in sqlite_master ){
+**     if( the index that is the pk exists in sqlite_schema ){
 **       *piPK = rootpage of that index.
 **       return RBU_PK_EXTERNAL
 **     }else{
@@ -192127,9 +198198,9 @@ static void rbuTableType(
   int *piPk
 ){
   /*
-  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
+  ** 0) SELECT count(*) FROM sqlite_schema where name=%Q AND IsVirtual(%Q)
   ** 1) PRAGMA index_list = ?
-  ** 2) SELECT count(*) FROM sqlite_master where name=%Q 
+  ** 2) SELECT count(*) FROM sqlite_schema where name=%Q
   ** 3) PRAGMA table_info = ?
   */
   sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
@@ -192138,10 +198209,10 @@ static void rbuTableType(
   *piPk = 0;
 
   assert( p->rc==SQLITE_OK );
-  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, 
+  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
     sqlite3_mprintf(
           "SELECT (sql LIKE 'create virtual%%'), rootpage"
-          "  FROM sqlite_master"
+          "  FROM sqlite_schema"
           " WHERE name=%Q", zTab
   ));
   if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
@@ -192154,7 +198225,7 @@ static void rbuTableType(
   }
   *piTnum = sqlite3_column_int(aStmt[0], 1);
 
-  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, 
+  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
     sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
   );
   if( p->rc ) goto rbuTableType_end;
@@ -192162,9 +198233,9 @@ static void rbuTableType(
     const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
     const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
     if( zOrig && zIdx && zOrig[0]=='p' ){
-      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, 
+      p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
           sqlite3_mprintf(
-            "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
+            "SELECT rootpage FROM sqlite_schema WHERE name = %Q", zIdx
       ));
       if( p->rc==SQLITE_OK ){
         if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
@@ -192178,7 +198249,7 @@ static void rbuTableType(
     }
   }
 
-  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, 
+  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
     sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
   );
   if( p->rc==SQLITE_OK ){
@@ -192254,7 +198325,7 @@ static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
 ** the table (not index) that the iterator currently points to.
 **
 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
-** an error does occur, an error code and error message are also left in 
+** an error does occur, an error code and error message are also left in
 ** the RBU handle.
 */
 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
@@ -192276,7 +198347,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
     if( p->rc ) return p->rc;
     if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
 
-    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK 
+    assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
          || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
          || pIter->eType==RBU_PK_VTAB
     );
@@ -192284,7 +198355,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
     /* Populate the azTblCol[] and nTblCol variables based on the columns
     ** of the input table. Ignore any input table columns that begin with
     ** "rbu_".  */
-    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
+    p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
         sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
     );
     if( p->rc==SQLITE_OK ){
@@ -192320,7 +198391,7 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
     ** present in the input table. Populate the abTblPk[], azTblType[] and
     ** aiTblOrder[] arrays at the same time.  */
     if( p->rc==SQLITE_OK ){
-      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 
+      p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
           sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
       );
     }
@@ -192363,8 +198434,8 @@ static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
 }
 
 /*
-** This function constructs and returns a pointer to a nul-terminated 
-** string containing some SQL clause or list based on one or more of the 
+** This function constructs and returns a pointer to a nul-terminated
+** string containing some SQL clause or list based on one or more of the
 ** column names currently stored in the pIter->azTblCol[] array.
 */
 static char *rbuObjIterGetCollist(
@@ -192415,10 +198486,10 @@ static char *rbuObjIterGetPkList(
 }
 
 /*
-** This function is called as part of restarting an RBU vacuum within 
+** This function is called as part of restarting an RBU vacuum within
 ** stage 1 of the process (while the *-oal file is being built) while
 ** updating a table (not an index). The table may be a rowid table or
-** a WITHOUT ROWID table. It queries the target database to find the 
+** a WITHOUT ROWID table. It queries the target database to find the
 ** largest key that has already been written to the target table and
 ** constructs a WHERE clause that can be used to extract the remaining
 ** rows from the source table. For a rowid table, the WHERE clause
@@ -192442,7 +198513,7 @@ static char *rbuVacuumTableStart(
   sqlite3_stmt *pMax = 0;
   char *zRet = 0;
   if( bRowid ){
-    p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, 
+    p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
         sqlite3_mprintf(
           "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
         )
@@ -192458,9 +198529,9 @@ static char *rbuVacuumTableStart(
     char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
 
     if( p->rc==SQLITE_OK ){
-      p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg, 
+      p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
           sqlite3_mprintf(
-            "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1", 
+            "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
                 zSelect, zWrite, pIter->zTbl, zOrder
           )
       );
@@ -192482,12 +198553,12 @@ static char *rbuVacuumTableStart(
 ** This function is called as part of restating an RBU vacuum when the
 ** current operation is writing content to an index. If possible, it
 ** queries the target index b-tree for the largest key already written to
-** it, then composes and returns an expression that can be used in a WHERE 
-** clause to select the remaining required rows from the source table. 
+** it, then composes and returns an expression that can be used in a WHERE
+** clause to select the remaining required rows from the source table.
 ** It is only possible to return such an expression if:
 **
 **   * The index contains no DESC columns, and
-**   * The last key written to the index before the operation was 
+**   * The last key written to the index before the operation was
 **     suspended does not contain any NULL values.
 **
 ** The expression is of the form:
@@ -192497,7 +198568,7 @@ static char *rbuVacuumTableStart(
 ** except that the "?" placeholders are replaced with literal values.
 **
 ** If the expression cannot be created, NULL is returned. In this case,
-** the caller has to use an OFFSET clause to extract only the required 
+** the caller has to use an OFFSET clause to extract only the required
 ** rows from the sourct table, just as it does for an RBU update operation.
 */
 char *rbuVacuumIndexStart(
@@ -192590,23 +198661,23 @@ char *rbuVacuumIndexStart(
 }
 
 /*
-** This function is used to create a SELECT list (the list of SQL 
-** expressions that follows a SELECT keyword) for a SELECT statement 
-** used to read from an data_xxx or rbu_tmp_xxx table while updating the 
-** index object currently indicated by the iterator object passed as the 
-** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used 
+** This function is used to create a SELECT list (the list of SQL
+** expressions that follows a SELECT keyword) for a SELECT statement
+** used to read from an data_xxx or rbu_tmp_xxx table while updating the
+** index object currently indicated by the iterator object passed as the
+** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
 ** to obtain the required information.
 **
 ** If the index is of the following form:
 **
 **   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
 **
-** and "t1" is a table with an explicit INTEGER PRIMARY KEY column 
+** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
 ** "ipk", the returned string is:
 **
 **   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
 **
-** As well as the returned string, three other malloc'd strings are 
+** As well as the returned string, three other malloc'd strings are
 ** returned via output parameters. As follows:
 **
 **   pzImposterCols: ...
@@ -192676,11 +198747,11 @@ static char *rbuObjIterGetIndexCols(
 
     if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
       const char *zOrder = (bDesc ? " DESC" : "");
-      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", 
+      zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
           zImpPK, zCom, nBind, zCol, zOrder
       );
     }
-    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", 
+    zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
         zImpCols, zCom, nBind, zCol, zType, zCollate
     );
     zWhere = sqlite3_mprintf(
@@ -192726,7 +198797,7 @@ static char *rbuObjIterGetIndexCols(
 ** the text ", old._rowid_" to the returned value.
 */
 static char *rbuObjIterGetOldlist(
-  sqlite3rbu *p, 
+  sqlite3rbu *p,
   RbuObjIter *pIter,
   const char *zObj
 ){
@@ -192767,7 +198838,7 @@ static char *rbuObjIterGetOldlist(
 **   "b = ?1 AND c = ?2"
 */
 static char *rbuObjIterGetWhere(
-  sqlite3rbu *p, 
+  sqlite3rbu *p,
   RbuObjIter *pIter
 ){
   char *zList = 0;
@@ -192782,7 +198853,7 @@ static char *rbuObjIterGetWhere(
         zSep = " AND ";
       }
     }
-    zList = rbuMPrintf(p, 
+    zList = rbuMPrintf(p,
         "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
     );
 
@@ -192822,7 +198893,7 @@ static void rbuBadControlError(sqlite3rbu *p){
 **
 ** The memory for the returned string is obtained from sqlite3_malloc().
 ** It is the responsibility of the caller to eventually free it using
-** sqlite3_free(). 
+** sqlite3_free().
 **
 ** If an OOM error is encountered when allocating space for the new
 ** string, an error code is left in the rbu handle passed as the first
@@ -192846,19 +198917,19 @@ static char *rbuObjIterGetSetlist(
       for(i=0; i<pIter->nTblCol; i++){
         char c = zMask[pIter->aiSrcOrder[i]];
         if( c=='x' ){
-          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", 
+          zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
               zList, zSep, pIter->azTblCol[i], i+1
           );
           zSep = ", ";
         }
         else if( c=='d' ){
-          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", 
+          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
           );
           zSep = ", ";
         }
         else if( c=='f' ){
-          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", 
+          zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
           );
           zSep = ", ";
@@ -192876,7 +198947,7 @@ static char *rbuObjIterGetSetlist(
 **
 ** The memory for the returned string is obtained from sqlite3_malloc().
 ** It is the responsibility of the caller to eventually free it using
-** sqlite3_free(). 
+** sqlite3_free().
 **
 ** If an OOM error is encountered when allocating space for the new
 ** string, an error code is left in the rbu handle passed as the first
@@ -192900,8 +198971,8 @@ static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
 }
 
 /*
-** The iterator currently points to a table (not index) of type 
-** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY 
+** The iterator currently points to a table (not index) of type
+** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
 ** declaration for the corresponding imposter table. For example,
 ** if the iterator points to a table created as:
 **
@@ -192918,7 +198989,7 @@ static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
     const char *zSep = "PRIMARY KEY(";
     sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
     sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
-   
+
     p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
         sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
     );
@@ -192956,7 +199027,7 @@ static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
 ** a table b-tree where the table has an external primary key. If the
 ** iterator passed as the second argument does not currently point to
 ** a table (not index) with an external primary key, this function is a
-** no-op. 
+** no-op.
 **
 ** Assuming the iterator does point to a table with an external PK, this
 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
@@ -192983,8 +199054,8 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
     /* Figure out the name of the primary key index for the current table.
     ** This is needed for the argument to "PRAGMA index_xinfo". Set
     ** zIdx to point to a nul-terminated string containing this name. */
-    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, 
-        "SELECT name FROM sqlite_master WHERE rootpage = ?"
+    p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
+        "SELECT name FROM sqlite_schema WHERE rootpage = ?"
     );
     if( p->rc==SQLITE_OK ){
       sqlite3_bind_int(pQuery, 1, tnum);
@@ -193005,7 +199076,7 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
         int iCid = sqlite3_column_int(pXInfo, 1);
         int bDesc = sqlite3_column_int(pXInfo, 3);
         const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
-        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma, 
+        zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
             iCid, pIter->azTblType[iCid], zCollate
         );
         zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
@@ -193017,7 +199088,7 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
 
     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
     rbuMPrintfExec(p, p->dbMain,
-        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", 
+        "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
         zCols, zPk
     );
     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
@@ -193025,7 +199096,7 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
 }
 
 /*
-** If an error has already occurred when this function is called, it 
+** If an error has already occurred when this function is called, it
 ** immediately returns zero (without doing any work). Or, if an error
 ** occurs during the execution of this function, it sets the error code
 ** in the sqlite3rbu object indicated by the first argument and returns
@@ -193038,9 +199109,9 @@ static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
 ** an imposter table are created, or zero otherwise.
 **
 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
-** virtual tables are written to directly. The imposter table has the 
-** same schema as the actual target table (less any UNIQUE constraints). 
-** More precisely, the "same schema" means the same columns, types, 
+** virtual tables are written to directly. The imposter table has the
+** same schema as the actual target table (less any UNIQUE constraints).
+** More precisely, the "same schema" means the same columns, types,
 ** collation sequences. For tables that do not have an external PRIMARY
 ** KEY, it also means the same PRIMARY KEY declaration.
 */
@@ -193066,7 +199137,7 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
         ** "PRIMARY KEY" to the imposter table column declaration. */
         zPk = "PRIMARY KEY ";
       }
-      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s", 
+      zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
           zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
           (pIter->abNotNull[iCol] ? " NOT NULL" : "")
       );
@@ -193081,8 +199152,8 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
     }
 
     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
-    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", 
-        pIter->zTbl, zSql, 
+    rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
+        pIter->zTbl, zSql,
         (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
     );
     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
@@ -193096,12 +199167,12 @@ static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
 **     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
 **
 ** The number of bound variables is equal to the number of columns in
-** the target table, plus one (for the rbu_control column), plus one more 
-** (for the rbu_rowid column) if the target table is an implicit IPK or 
+** the target table, plus one (for the rbu_control column), plus one more
+** (for the rbu_rowid column) if the target table is an implicit IPK or
 ** virtual table.
 */
 static void rbuObjIterPrepareTmpInsert(
-  sqlite3rbu *p, 
+  sqlite3rbu *p,
   RbuObjIter *pIter,
   const char *zCollist,
   const char *zRbuRowid
@@ -193112,14 +199183,14 @@ static void rbuObjIterPrepareTmpInsert(
     assert( pIter->pTmpInsert==0 );
     p->rc = prepareFreeAndCollectError(
         p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
-          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", 
+          "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
           p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
     ));
   }
 }
 
 static void rbuTmpInsertFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nVal,
   sqlite3_value **apVal
 ){
@@ -193128,8 +199199,8 @@ static void rbuTmpInsertFunc(
   int i;
 
   assert( sqlite3_value_int(apVal[0])!=0
-      || p->objiter.eType==RBU_PK_EXTERNAL 
-      || p->objiter.eType==RBU_PK_NONE 
+      || p->objiter.eType==RBU_PK_EXTERNAL
+      || p->objiter.eType==RBU_PK_NONE
   );
   if( sqlite3_value_int(apVal[0])!=0 ){
     p->nPhaseOneStep += p->objiter.nIndex;
@@ -193157,7 +199228,7 @@ static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
 
   if( rc==SQLITE_OK ){
     rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
-        "SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?"
+        "SELECT trim(sql) FROM sqlite_schema WHERE type='index' AND name=?"
     );
   }
   if( rc==SQLITE_OK ){
@@ -193244,12 +199315,12 @@ static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
 }
 
 /*
-** Ensure that the SQLite statement handles required to update the 
-** target database object currently indicated by the iterator passed 
+** Ensure that the SQLite statement handles required to update the
+** target database object currently indicated by the iterator passed
 ** as the second argument are available.
 */
 static int rbuObjIterPrepareAll(
-  sqlite3rbu *p, 
+  sqlite3rbu *p,
   RbuObjIter *pIter,
   int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
 ){
@@ -193323,9 +199394,9 @@ static int rbuObjIterPrepareAll(
 
           zSql = sqlite3_mprintf(
               "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
-              zCollist, 
+              zCollist,
               pIter->zDataTbl,
-              zPart, 
+              zPart,
               (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
               zCollist, zLimit
           );
@@ -193346,7 +199417,7 @@ static int rbuObjIterPrepareAll(
               "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
               "ORDER BY %s%s",
               zCollist, p->zStateDb, pIter->zDataTbl, zPart,
-              zCollist, pIter->zDataTbl, 
+              zCollist, pIter->zDataTbl,
               zPart,
               (zPart ? "AND" : "WHERE"),
               zCollist, zLimit
@@ -193388,7 +199459,7 @@ static int rbuObjIterPrepareAll(
       if( p->rc==SQLITE_OK ){
         p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
             sqlite3_mprintf(
-              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", 
+              "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
               zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
             )
         );
@@ -193481,10 +199552,10 @@ static int rbuObjIterPrepareAll(
           p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
               sqlite3_mprintf(
                 "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
-                zCollist, 
+                zCollist,
                 (rbuIsVacuum(p) ? "0 AS " : ""),
                 zRbuRowid,
-                pIter->zDataTbl, (zStart ? zStart : ""), 
+                pIter->zDataTbl, (zStart ? zStart : ""),
                 (zOrder ? "ORDER BY" : ""), zOrder,
                 zLimit
               )
@@ -193502,16 +199573,16 @@ static int rbuObjIterPrepareAll(
     sqlite3_free(zCollist);
     sqlite3_free(zLimit);
   }
-  
+
   return p->rc;
 }
 
 /*
 ** Set output variable *ppStmt to point to an UPDATE statement that may
 ** be used to update the imposter table for the main table b-tree of the
-** table object that pIter currently points to, assuming that the 
+** table object that pIter currently points to, assuming that the
 ** rbu_control column of the data_xyz table contains zMask.
-** 
+**
 ** If the zMask string does not specify any columns to update, then this
 ** is not an error. Output variable *ppStmt is set to NULL in this case.
 */
@@ -193538,7 +199609,7 @@ static int rbuGetUpdateStmt(
       *pp = pUp->pNext;
       pUp->pNext = pIter->pRbuUpdate;
       pIter->pRbuUpdate = pUp;
-      *ppStmt = pUp->pUpdate; 
+      *ppStmt = pUp->pUpdate;
       return SQLITE_OK;
     }
     nUp++;
@@ -193568,7 +199639,7 @@ static int rbuGetUpdateStmt(
       const char *zPrefix = "";
 
       if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
-      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", 
+      zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
           zPrefix, pIter->zTbl, zSet, zWhere
       );
       p->rc = prepareFreeAndCollectError(
@@ -193584,8 +199655,8 @@ static int rbuGetUpdateStmt(
 }
 
 static sqlite3 *rbuOpenDbhandle(
-  sqlite3rbu *p, 
-  const char *zName, 
+  sqlite3rbu *p,
+  const char *zName,
   int bUseVfs
 ){
   sqlite3 *db = 0;
@@ -193614,8 +199685,8 @@ static void rbuFreeState(RbuState *p){
 }
 
 /*
-** Allocate an RbuState object and load the contents of the rbu_state 
-** table into it. Return a pointer to the new object. It is the 
+** Allocate an RbuState object and load the contents of the rbu_state
+** table into it. Return a pointer to the new object. It is the
 ** responsibility of the caller to eventually free the object using
 ** sqlite3_free().
 **
@@ -193631,7 +199702,7 @@ static RbuState *rbuLoadState(sqlite3rbu *p){
   pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
   if( pRet==0 ) return 0;
 
-  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
+  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
       sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
   );
   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
@@ -193739,9 +199810,9 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
       int bOk = 0;
       sqlite3_stmt *pCnt = 0;
       p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
-          "SELECT count(*) FROM stat.sqlite_master"
+          "SELECT count(*) FROM stat.sqlite_schema"
       );
-      if( p->rc==SQLITE_OK 
+      if( p->rc==SQLITE_OK
        && sqlite3_step(pCnt)==SQLITE_ROW
        && 1==sqlite3_column_int(pCnt, 0)
       ){
@@ -193754,7 +199825,7 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
         p->rc = SQLITE_ERROR;
         p->zErrmsg = sqlite3_mprintf("invalid state database");
       }
-    
+
       if( p->rc==SQLITE_OK ){
         p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
       }
@@ -193808,7 +199879,7 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
         if( *zExtra=='\0' ) zExtra = 0;
       }
 
-      zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s", 
+      zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
           sqlite3_db_filename(p->dbRbu, "main"),
           (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
       );
@@ -193823,19 +199894,19 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
   }
 
   if( p->rc==SQLITE_OK ){
-    p->rc = sqlite3_create_function(p->dbMain, 
+    p->rc = sqlite3_create_function(p->dbMain,
         "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
     );
   }
 
   if( p->rc==SQLITE_OK ){
-    p->rc = sqlite3_create_function(p->dbMain, 
+    p->rc = sqlite3_create_function(p->dbMain,
         "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
     );
   }
 
   if( p->rc==SQLITE_OK ){
-    p->rc = sqlite3_create_function(p->dbRbu, 
+    p->rc = sqlite3_create_function(p->dbRbu,
         "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
     );
   }
@@ -193843,9 +199914,9 @@ static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
   if( p->rc==SQLITE_OK ){
     p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
   }
-  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
+  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_schema");
 
-  /* Mark the database file just opened as an RBU target database. If 
+  /* Mark the database file just opened as an RBU target database. If
   ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
   ** This is an error.  */
   if( p->rc==SQLITE_OK ){
@@ -193893,10 +199964,10 @@ static void rbuFileSuffix3(const char *zBase, char *z){
 }
 
 /*
-** Return the current wal-index header checksum for the target database 
+** Return the current wal-index header checksum for the target database
 ** as a 64-bit integer.
 **
-** The checksum is store in the first page of xShmMap memory as an 8-byte 
+** The checksum is store in the first page of xShmMap memory as an 8-byte
 ** blob starting at byte offset 40.
 */
 static i64 rbuShmChecksum(sqlite3rbu *p){
@@ -193914,11 +199985,11 @@ static i64 rbuShmChecksum(sqlite3rbu *p){
 
 /*
 ** This function is called as part of initializing or reinitializing an
-** incremental checkpoint. 
+** incremental checkpoint.
 **
-** It populates the sqlite3rbu.aFrame[] array with the set of 
-** (wal frame -> db page) copy operations required to checkpoint the 
-** current wal file, and obtains the set of shm locks required to safely 
+** It populates the sqlite3rbu.aFrame[] array with the set of
+** (wal frame -> db page) copy operations required to checkpoint the
+** current wal file, and obtains the set of shm locks required to safely
 ** perform the copy operations directly on the file-system.
 **
 ** If argument pState is not NULL, then the incremental checkpoint is
@@ -193936,7 +200007,7 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
   if( pState==0 ){
     p->eStage = 0;
     if( p->rc==SQLITE_OK ){
-      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
+      p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_schema", 0, 0, 0);
     }
   }
 
@@ -193953,19 +200024,19 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
   **     would be read/written are recorded in the sqlite3rbu.aFrame[]
   **     array.
   **
-  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, 
+  **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
   **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
   **     no-ops. These locks will not be released until the connection
   **     is closed.
   **
-  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL 
+  **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL
   **     error.
   **
   ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
   ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
-  ** array populated with a set of (frame -> page) mappings. Because the 
-  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy 
-  ** data from the wal file into the database file according to the 
+  ** array populated with a set of (frame -> page) mappings. Because the
+  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
+  ** data from the wal file into the database file according to the
   ** contents of aFrame[].
   */
   if( p->rc==SQLITE_OK ){
@@ -193998,9 +200069,9 @@ static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
         p->nPagePerSector = 1;
       }
 
-      /* Call xSync() on the wal file. This causes SQLite to sync the 
-      ** directory in which the target database and the wal file reside, in 
-      ** case it has not been synced since the rename() call in 
+      /* Call xSync() on the wal file. This causes SQLite to sync the
+      ** directory in which the target database and the wal file reside, in
+      ** case it has not been synced since the rename() call in
       ** rbuMoveOalFile(). */
       p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
     }
@@ -194041,7 +200112,7 @@ static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
 
 /*
 ** Called when a page of data is written to offset iOff of the database
-** file while the rbu handle is in capture mode. Record the page number 
+** file while the rbu handle is in capture mode. Record the page number
 ** of the page being written in the aFrame[] array.
 */
 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
@@ -194109,7 +200180,7 @@ static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
 ** on the database file. This proc moves the *-oal file to the *-wal path,
 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
-** If an error occurs, leave an error code and error message in the rbu 
+** If an error occurs, leave an error code and error message in the rbu
 ** handle.
 */
 static void rbuMoveOalFile(sqlite3rbu *p){
@@ -194131,7 +200202,7 @@ static void rbuMoveOalFile(sqlite3rbu *p){
   }else{
     /* Move the *-oal file to *-wal. At this point connection p->db is
     ** holding a SHARED lock on the target database file (because it is
-    ** in WAL mode). So no other connection may be writing the db. 
+    ** in WAL mode). So no other connection may be writing the db.
     **
     ** In order to ensure that there are no database readers, an EXCLUSIVE
     ** lock is obtained here before the *-oal is moved to *-wal.
@@ -194289,8 +200360,8 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){
     /* If this is an INSERT into a table b-tree and the table has an
     ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
     ** to write a NULL into the IPK column. That is not permitted.  */
-    if( eType==RBU_INSERT 
-     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] 
+    if( eType==RBU_INSERT
+     && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
      && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
     ){
       p->rc = SQLITE_MISMATCH;
@@ -194307,18 +200378,18 @@ static void rbuStepOneOp(sqlite3rbu *p, int eType){
     if( p->rc ) return;
   }
   if( pIter->zIdx==0 ){
-    if( pIter->eType==RBU_PK_VTAB 
-     || pIter->eType==RBU_PK_NONE 
-     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) 
+    if( pIter->eType==RBU_PK_VTAB
+     || pIter->eType==RBU_PK_NONE
+     || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
     ){
-      /* For a virtual table, or a table with no primary key, the 
+      /* For a virtual table, or a table with no primary key, the
       ** SELECT statement is:
       **
       **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
       **
       ** Hence column_value(pIter->nCol+1).
       */
-      assertColumnName(pIter->pSelect, pIter->nCol+1, 
+      assertColumnName(pIter->pSelect, pIter->nCol+1,
           rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
       );
       pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
@@ -194382,8 +200453,8 @@ static int rbuStep(sqlite3rbu *p){
             p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
           }
         }
-        if( p->rc==SQLITE_OK 
-         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) 
+        if( p->rc==SQLITE_OK
+         && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
         ){
           /* Bind the rbu_rowid value to column _rowid_ */
           assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
@@ -194413,7 +200484,7 @@ static void rbuIncrSchemaCookie(sqlite3rbu *p){
     int iCookie = 1000000;
     sqlite3_stmt *pStmt;
 
-    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, 
+    p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
         "PRAGMA schema_version"
     );
     if( p->rc==SQLITE_OK ){
@@ -194445,7 +200516,7 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){
     int rc;
 
     assert( p->zErrmsg==0 );
-    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, 
+    rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
         sqlite3_mprintf(
           "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
           "(%d, %d), "
@@ -194460,9 +200531,9 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){
           "(%d, %Q)  ",
           p->zStateDb,
           RBU_STATE_STAGE, eStage,
-          RBU_STATE_TBL, p->objiter.zTbl, 
-          RBU_STATE_IDX, p->objiter.zIdx, 
-          RBU_STATE_ROW, p->nStep, 
+          RBU_STATE_TBL, p->objiter.zTbl,
+          RBU_STATE_IDX, p->objiter.zIdx,
+          RBU_STATE_ROW, p->nStep,
           RBU_STATE_PROGRESS, p->nProgress,
           RBU_STATE_CKPT, p->iWalCksum,
           RBU_STATE_COOKIE, (i64)pFd->iCookie,
@@ -194483,7 +200554,7 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){
 
 
 /*
-** The second argument passed to this function is the name of a PRAGMA 
+** The second argument passed to this function is the name of a PRAGMA
 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
 ** This function executes the following on sqlite3rbu.dbRbu:
 **
@@ -194502,7 +200573,7 @@ static void rbuSaveState(sqlite3rbu *p, int eStage){
 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
   if( p->rc==SQLITE_OK ){
     sqlite3_stmt *pPragma = 0;
-    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, 
+    p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
         sqlite3_mprintf("PRAGMA main.%s", zPragma)
     );
     if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
@@ -194515,7 +200586,7 @@ static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
 }
 
 /*
-** The RBU handle passed as the only argument has just been opened and 
+** The RBU handle passed as the only argument has just been opened and
 ** the state database is empty. If this RBU handle was opened for an
 ** RBU vacuum operation, create the schema in the target db.
 */
@@ -194526,8 +200597,8 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){
   assert( rbuIsVacuum(p) );
   p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
   if( p->rc==SQLITE_OK ){
-    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
-      "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
+    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
+      "SELECT sql FROM sqlite_schema WHERE sql!='' AND rootpage!=0"
       " AND name!='sqlite_sequence' "
       " ORDER BY type DESC"
     );
@@ -194541,14 +200612,14 @@ static void rbuCreateTargetSchema(sqlite3rbu *p){
   if( p->rc!=SQLITE_OK ) return;
 
   if( p->rc==SQLITE_OK ){
-    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
-        "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" 
+    p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
+        "SELECT * FROM sqlite_schema WHERE rootpage=0 OR rootpage IS NULL"
     );
   }
 
   if( p->rc==SQLITE_OK ){
-    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, 
-        "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
+    p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
+        "INSERT INTO sqlite_schema VALUES(?,?,?,?,?)"
     );
   }
 
@@ -194588,11 +200659,11 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
         while( p->rc==SQLITE_OK && pIter->zTbl ){
 
           if( pIter->bCleanup ){
-            /* Clean up the rbu_tmp_xxx table for the previous table. It 
+            /* Clean up the rbu_tmp_xxx table for the previous table. It
             ** cannot be dropped as there are currently active SQL statements.
             ** But the contents can be deleted.  */
             if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
-              rbuMPrintfExec(p, p->dbRbu, 
+              rbuMPrintfExec(p, p->dbRbu,
                   "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
               );
             }
@@ -194642,10 +200713,10 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
         if( p->rc==SQLITE_OK ){
           if( p->nStep>=p->nFrame ){
             sqlite3_file *pDb = p->pTargetFd->pReal;
-  
+
             /* Sync the db file */
             p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
-  
+
             /* Update nBackfill */
             if( p->rc==SQLITE_OK ){
               void volatile *ptr;
@@ -194654,7 +200725,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
                 ((u32 volatile*)ptr)[24] = p->iMaxFrame;
               }
             }
-  
+
             if( p->rc==SQLITE_OK ){
               p->eStage = RBU_STAGE_DONE;
               p->rc = SQLITE_DONE;
@@ -194662,7 +200733,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
           }else{
             /* At one point the following block copied a single frame from the
             ** wal file to the database file. So that one call to sqlite3rbu_step()
-            ** checkpointed a single frame. 
+            ** checkpointed a single frame.
             **
             ** However, if the sector-size is larger than the page-size, and the
             ** application calls sqlite3rbu_savestate() or close() immediately
@@ -194676,7 +200747,7 @@ SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
               iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
               rbuCheckpointFrame(p, pFrame);
               p->nStep++;
-            }while( p->nStep<p->nFrame 
+            }while( p->nStep<p->nFrame
                  && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
                  && p->rc==SQLITE_OK
             );
@@ -194722,7 +200793,7 @@ static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
     RbuObjIter *pIter = &p->objiter;
     int rc = SQLITE_OK;
 
-    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup 
+    while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
        || rbuStrCompare(pIter->zIdx, pState->zIdx)
        || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
        || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
@@ -194798,7 +200869,7 @@ static void rbuDeleteVfs(sqlite3rbu *p){
 ** the number of auxilliary indexes on the table.
 */
 static void rbuIndexCntFunc(
-  sqlite3_context *pCtx, 
+  sqlite3_context *pCtx,
   int nVal,
   sqlite3_value **apVal
 ){
@@ -194809,9 +200880,9 @@ static void rbuIndexCntFunc(
   sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
 
   assert( nVal==1 );
-  
-  rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg, 
-      sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
+
+  rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
+      sqlite3_mprintf("SELECT count(*) FROM sqlite_schema "
         "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
   );
   if( rc!=SQLITE_OK ){
@@ -194844,7 +200915,7 @@ static void rbuIndexCntFunc(
 ** and the cnt column the number of rows it contains.
 **
 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
-** for all rows in the rbu_count table, where nIndex is the number of 
+** for all rows in the rbu_count table, where nIndex is the number of
 ** indexes on the corresponding target database table.
 */
 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
@@ -194854,15 +200925,15 @@ static void rbuInitPhaseOneSteps(sqlite3rbu *p){
 
     p->nPhaseOneStep = -1;
 
-    p->rc = sqlite3_create_function(p->dbRbu, 
+    p->rc = sqlite3_create_function(p->dbRbu,
         "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
     );
-  
+
     /* Check for the rbu_count table. If it does not exist, or if an error
     ** occurs, nPhaseOneStep will be left set to -1. */
     if( p->rc==SQLITE_OK ){
       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
-          "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
+          "SELECT 1 FROM sqlite_schema WHERE tbl_name = 'rbu_count'"
       );
     }
     if( p->rc==SQLITE_OK ){
@@ -194871,7 +200942,7 @@ static void rbuInitPhaseOneSteps(sqlite3rbu *p){
       }
       p->rc = sqlite3_finalize(pStmt);
     }
-  
+
     if( p->rc==SQLITE_OK && bExists ){
       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
           "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
@@ -194889,7 +200960,7 @@ static void rbuInitPhaseOneSteps(sqlite3rbu *p){
 
 
 static sqlite3rbu *openRbuHandle(
-  const char *zTarget, 
+  const char *zTarget,
   const char *zRbu,
   const char *zState
 ){
@@ -194927,7 +200998,7 @@ static sqlite3rbu *openRbuHandle(
       ** to be a wal-mode db. But, this may have happened due to an earlier
       ** RBU vacuum operation leaving an old wal file in the directory.
       ** If this is the case, it will have been checkpointed and deleted
-      ** when the handle was closed and a second attempt to open the 
+      ** when the handle was closed and a second attempt to open the
       ** database may succeed.  */
       rbuOpenDatabase(p, &bRetry);
       if( bRetry ){
@@ -194940,7 +201011,7 @@ static sqlite3rbu *openRbuHandle(
       assert( pState || p->rc!=SQLITE_OK );
       if( p->rc==SQLITE_OK ){
 
-        if( pState->eStage==0 ){ 
+        if( pState->eStage==0 ){
           rbuDeleteOalFile(p);
           rbuInitPhaseOneSteps(p);
           p->eStage = RBU_STAGE_OAL;
@@ -194964,15 +201035,15 @@ static sqlite3rbu *openRbuHandle(
       }
     }
 
-    if( p->rc==SQLITE_OK 
+    if( p->rc==SQLITE_OK
      && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
      && pState->eStage!=0
     ){
       rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
-      if( pFd->iCookie!=pState->iCookie ){   
+      if( pFd->iCookie!=pState->iCookie ){
         /* At this point (pTargetFd->iCookie) contains the value of the
-        ** change-counter cookie (the thing that gets incremented when a 
-        ** transaction is committed in rollback mode) currently stored on 
+        ** change-counter cookie (the thing that gets incremented when a
+        ** transaction is committed in rollback mode) currently stored on
         ** page 1 of the database file. */
         p->rc = SQLITE_BUSY;
         p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
@@ -195009,7 +201080,7 @@ static sqlite3rbu *openRbuHandle(
           }
 
           /* Check if the main database is a zipvfs db. If it is, set the upper
-          ** level pager to use "journal_mode=off". This prevents it from 
+          ** level pager to use "journal_mode=off". This prevents it from
           ** generating a large journal using a temp file.  */
           if( p->rc==SQLITE_OK ){
             int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
@@ -195055,10 +201126,10 @@ static sqlite3rbu *rbuMisuseError(void){
 }
 
 /*
-** Open and return a new RBU handle. 
+** Open and return a new RBU handle.
 */
 SQLITE_API sqlite3rbu *sqlite3rbu_open(
-  const char *zTarget, 
+  const char *zTarget,
   const char *zRbu,
   const char *zState
 ){
@@ -195071,7 +201142,7 @@ SQLITE_API sqlite3rbu *sqlite3rbu_open(
 ** Open a handle to begin or resume an RBU VACUUM operation.
 */
 SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
-  const char *zTarget, 
+  const char *zTarget,
   const char *zState
 ){
   if( zTarget==0 ){ return rbuMisuseError(); }
@@ -195145,8 +201216,8 @@ SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
     rbuObjIterFinalize(&p->objiter);
 
     /* If this is an RBU vacuum handle and the vacuum has either finished
-    ** successfully or encountered an error, delete the contents of the 
-    ** state table. This causes the next call to sqlite3rbu_vacuum() 
+    ** successfully or encountered an error, delete the contents of the
+    ** state table. This causes the next call to sqlite3rbu_vacuum()
     ** specifying the current target and state databases to start a new
     ** vacuum from scratch.  */
     if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
@@ -195179,7 +201250,7 @@ SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
 }
 
 /*
-** Return the total number of key-value operations (inserts, deletes or 
+** Return the total number of key-value operations (inserts, deletes or
 ** updates) that have been performed on the target database since the
 ** current RBU update was started.
 */
@@ -195277,7 +201348,7 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
   if( p->eStage==RBU_STAGE_OAL ){
     assert( rc!=SQLITE_DONE );
     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
-    if( rc==SQLITE_OK ){ 
+    if( rc==SQLITE_OK ){
       const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
       rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
     }
@@ -195292,7 +201363,7 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
 ** of a standard VFS in the following ways:
 **
-** 1. Whenever the first page of a main database file is read or 
+** 1. Whenever the first page of a main database file is read or
 **    written, the value of the change-counter cookie is stored in
 **    rbu_file.iCookie. Similarly, the value of the "write-version"
 **    database header field is stored in rbu_file.iWriteVer. This ensures
@@ -195300,15 +201371,15 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
 **
 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
 **    member variable of the associated database file descriptor is set
-**    to point to the new file. A mutex protected linked list of all main 
-**    db fds opened using a particular RBU VFS is maintained at 
+**    to point to the new file. A mutex protected linked list of all main
+**    db fds opened using a particular RBU VFS is maintained at
 **    rbu_vfs.pMain to facilitate this.
 **
-** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file 
+** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
 **    object can be marked as the target database of an RBU update. This
 **    turns on the following extra special behaviour:
 **
-** 3a. If xAccess() is called to check if there exists a *-wal file 
+** 3a. If xAccess() is called to check if there exists a *-wal file
 **     associated with an RBU target database currently in RBU_STAGE_OAL
 **     stage (preparing the *-oal file), the following special handling
 **     applies:
@@ -195321,26 +201392,26 @@ SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
 **
 **     Then, when xOpen() is called to open the *-wal file associated with
 **     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
-**     file, the rbu vfs opens the corresponding *-oal file instead. 
+**     file, the rbu vfs opens the corresponding *-oal file instead.
 **
 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
 **     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
 **     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
 **     are no-ops on target database files in RBU_STAGE_OAL mode. This is
-**     because assert() statements in some VFS implementations fail if 
+**     because assert() statements in some VFS implementations fail if
 **     xShmLock() is called before xShmMap().
 **
 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
-**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it 
+**     mode except RBU_STAGE_DONE (all work completed and checkpointed), it
 **     fails with an SQLITE_BUSY error. This is to stop RBU connections
 **     from automatically checkpointing a *-wal (or *-oal) file from within
 **     sqlite3_close().
 **
 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
-**     all xWrite() calls on the target database file perform no IO. 
+**     all xWrite() calls on the target database file perform no IO.
 **     Instead the frame and page numbers that would be read and written
 **     are recorded. Additionally, successful attempts to obtain exclusive
-**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target 
+**     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
 **     database file are recorded. xShmLock() calls to unlock the same
 **     locks are no-ops (so that once obtained, these locks are never
 **     relinquished). Finally, calls to xSync() on the target database
@@ -195416,7 +201487,7 @@ static void rbuMainlistRemove(rbu_file *p){
 }
 
 /*
-** Given that zWal points to a buffer containing a wal file name passed to 
+** Given that zWal points to a buffer containing a wal file name passed to
 ** either the xOpen() or xAccess() VFS method, search the main-db list for
 ** a file-handle opened by the same database connection on the corresponding
 ** database file.
@@ -195469,7 +201540,7 @@ static int rbuVfsClose(sqlite3_file *pFile){
 
 
 /*
-** Read and return an unsigned 32-bit big-endian integer from the buffer 
+** Read and return an unsigned 32-bit big-endian integer from the buffer
 ** passed as the only argument.
 */
 static u32 rbuGetU32(u8 *aBuf){
@@ -195499,9 +201570,9 @@ static void rbuPutU16(u8 *aBuf, u16 iVal){
 ** Read data from an rbuVfs-file.
 */
 static int rbuVfsRead(
-  sqlite3_file *pFile, 
-  void *zBuf, 
-  int iAmt, 
+  sqlite3_file *pFile,
+  void *zBuf,
+  int iAmt,
   sqlite_int64 iOfst
 ){
   rbu_file *p = (rbu_file*)pFile;
@@ -195512,20 +201583,20 @@ static int rbuVfsRead(
     assert( p->openFlags & SQLITE_OPEN_WAL );
     rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
   }else{
-    if( pRbu && pRbu->eStage==RBU_STAGE_OAL 
-     && (p->openFlags & SQLITE_OPEN_WAL) 
-     && iOfst>=pRbu->iOalSz 
+    if( pRbu && pRbu->eStage==RBU_STAGE_OAL
+     && (p->openFlags & SQLITE_OPEN_WAL)
+     && iOfst>=pRbu->iOalSz
     ){
       rc = SQLITE_OK;
       memset(zBuf, 0, iAmt);
     }else{
       rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
 #if 1
-      /* If this is being called to read the first page of the target 
-      ** database as part of an rbu vacuum operation, synthesize the 
+      /* If this is being called to read the first page of the target
+      ** database as part of an rbu vacuum operation, synthesize the
       ** contents of the first page if it does not yet exist. Otherwise,
       ** SQLite will not check for a *-wal file.  */
-      if( pRbu && rbuIsVacuum(pRbu) 
+      if( pRbu && rbuIsVacuum(pRbu)
           && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
           && (p->openFlags & SQLITE_OPEN_MAIN_DB)
           && pRbu->rc==SQLITE_OK
@@ -195565,9 +201636,9 @@ static int rbuVfsRead(
 ** Write data to an rbuVfs-file.
 */
 static int rbuVfsWrite(
-  sqlite3_file *pFile, 
-  const void *zBuf, 
-  int iAmt, 
+  sqlite3_file *pFile,
+  const void *zBuf,
+  int iAmt,
   sqlite_int64 iOfst
 ){
   rbu_file *p = (rbu_file*)pFile;
@@ -195579,8 +201650,8 @@ static int rbuVfsWrite(
     rc = rbuCaptureDbWrite(p->pRbu, iOfst);
   }else{
     if( pRbu ){
-      if( pRbu->eStage==RBU_STAGE_OAL 
-       && (p->openFlags & SQLITE_OPEN_WAL) 
+      if( pRbu->eStage==RBU_STAGE_OAL
+       && (p->openFlags & SQLITE_OPEN_WAL)
        && iOfst>=pRbu->iOalSz
       ){
         pRbu->iOalSz = iAmt + iOfst;
@@ -195640,10 +201711,10 @@ static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
 
   /* If this is an RBU vacuum operation and this is the target database,
   ** pretend that it has at least one page. Otherwise, SQLite will not
-  ** check for the existance of a *-wal file. rbuVfsRead() contains 
+  ** check for the existance of a *-wal file. rbuVfsRead() contains
   ** similar logic.  */
-  if( rc==SQLITE_OK && *pSize==0 
-   && p->pRbu && rbuIsVacuum(p->pRbu) 
+  if( rc==SQLITE_OK && *pSize==0
+   && p->pRbu && rbuIsVacuum(p->pRbu)
    && (p->openFlags & SQLITE_OPEN_MAIN_DB)
   ){
     *pSize = 1024;
@@ -195660,10 +201731,10 @@ static int rbuVfsLock(sqlite3_file *pFile, int eLock){
   int rc = SQLITE_OK;
 
   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
-  if( eLock==SQLITE_LOCK_EXCLUSIVE 
+  if( eLock==SQLITE_LOCK_EXCLUSIVE
    && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
   ){
-    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this 
+    /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
     ** prevents it from checkpointing the database from sqlite3_close(). */
     rc = SQLITE_BUSY;
   }else{
@@ -195776,8 +201847,8 @@ static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
     /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
-    ** taking this lock also prevents any checkpoints from occurring. 
-    ** todo: really, it's not clear why this might occur, as 
+    ** taking this lock also prevents any checkpoints from occurring.
+    ** todo: really, it's not clear why this might occur, as
     ** wal_autocheckpoint ought to be turned off.  */
     if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
   }else{
@@ -195801,10 +201872,10 @@ static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
 */
 static int rbuVfsShmMap(
-  sqlite3_file *pFile, 
-  int iRegion, 
-  int szRegion, 
-  int isWrite, 
+  sqlite3_file *pFile,
+  int iRegion,
+  int szRegion,
+  int isWrite,
   void volatile **pp
 ){
   rbu_file *p = (rbu_file*)pFile;
@@ -195812,7 +201883,7 @@ static int rbuVfsShmMap(
   int eStage = (p->pRbu ? p->pRbu->eStage : 0);
 
   /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
-  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space 
+  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
   ** instead of a file on disk.  */
   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
   if( eStage==RBU_STAGE_OAL ){
@@ -195882,33 +201953,6 @@ static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
   return rc;
 }
 
-/* 
-** A main database named zName has just been opened. The following 
-** function returns a pointer to a buffer owned by SQLite that contains
-** the name of the *-wal file this db connection will use. SQLite
-** happens to pass a pointer to this buffer when using xAccess()
-** or xOpen() to operate on the *-wal file.  
-*/
-static const char *rbuMainToWal(const char *zName, int flags){
-  int n = (int)strlen(zName);
-  const char *z = &zName[n];
-  if( flags & SQLITE_OPEN_URI ){
-    int odd = 0;
-    while( 1 ){
-      if( z[0]==0 ){
-        odd = 1 - odd;
-        if( odd && z[1]==0 ) break;
-      }
-      z++;
-    }
-    z += 2;
-  }else{
-    while( *z==0 ) z++;
-  }
-  z += (n + 8 + 1);
-  return z;
-}
-
 /*
 ** Open an rbu file handle.
 */
@@ -195957,7 +202001,7 @@ static int rbuVfsOpen(
       ** the name of the *-wal file this db connection will use. SQLite
       ** happens to pass a pointer to this buffer when using xAccess()
       ** or xOpen() to operate on the *-wal file.  */
-      pFd->zWal = rbuMainToWal(zName, flags);
+      pFd->zWal = sqlite3_filename_wal(zName);
     }
     else if( flags & SQLITE_OPEN_WAL ){
       rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
@@ -195965,14 +202009,14 @@ static int rbuVfsOpen(
         if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
           /* This call is to open a *-wal file. Intead, open the *-oal. This
           ** code ensures that the string passed to xOpen() is terminated by a
-          ** pair of '\0' bytes in case the VFS attempts to extract a URI 
+          ** pair of '\0' bytes in case the VFS attempts to extract a URI
           ** parameter from it.  */
           const char *zBase = zName;
           size_t nCopy;
           char *zCopy;
           if( rbuIsVacuum(pDb->pRbu) ){
             zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
-            zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
+            zBase = sqlite3_filename_wal(zBase);
           }
           nCopy = strlen(zBase);
           zCopy = sqlite3_malloc(nCopy+2);
@@ -195994,8 +202038,8 @@ static int rbuVfsOpen(
     pFd->pRbu = pRbuVfs->pRbu;
   }
 
-  if( oflags & SQLITE_OPEN_MAIN_DB 
-   && sqlite3_uri_boolean(zName, "rbu_memory", 0) 
+  if( oflags & SQLITE_OPEN_MAIN_DB
+   && sqlite3_uri_boolean(zName, "rbu_memory", 0)
   ){
     assert( oflags & SQLITE_OPEN_MAIN_DB );
     oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
@@ -196034,9 +202078,9 @@ static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
 ** is available, or false otherwise.
 */
 static int rbuVfsAccess(
-  sqlite3_vfs *pVfs, 
-  const char *zPath, 
-  int flags, 
+  sqlite3_vfs *pVfs,
+  const char *zPath,
+  int flags,
   int *pResOut
 ){
   rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
@@ -196052,7 +202096,7 @@ static int rbuVfsAccess(
   **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
   **      ensures that the RBU extension never tries to update a database
   **      in wal mode, even if the first page of the database file has
-  **      been damaged. 
+  **      been damaged.
   **
   **   b) if the *-wal file does not exist, claim that it does anyway,
   **      causing SQLite to call xOpen() to open it. This call will also
@@ -196082,9 +202126,9 @@ static int rbuVfsAccess(
 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
 */
 static int rbuVfsFullPathname(
-  sqlite3_vfs *pVfs, 
-  const char *zPath, 
-  int nOut, 
+  sqlite3_vfs *pVfs,
+  const char *zPath,
+  int nOut,
   char *zOut
 ){
   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
@@ -196102,7 +202146,7 @@ static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
 
 /*
 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
-** utf-8 string describing the most recent error encountered associated 
+** utf-8 string describing the most recent error encountered associated
 ** with dynamic libraries.
 */
 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
@@ -196114,8 +202158,8 @@ static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
 */
 static void (*rbuVfsDlSym(
-  sqlite3_vfs *pVfs, 
-  void *pArg, 
+  sqlite3_vfs *pVfs,
+  void *pArg,
   const char *zSym
 ))(void){
   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
@@ -196132,7 +202176,7 @@ static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
 
 /*
-** Populate the buffer pointed to by zBufOut with nByte bytes of 
+** Populate the buffer pointed to by zBufOut with nByte bytes of
 ** random data.
 */
 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
@@ -196141,7 +202185,7 @@ static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
 }
 
 /*
-** Sleep for nMicro microseconds. Return the number of microseconds 
+** Sleep for nMicro microseconds. Return the number of microseconds
 ** actually slept.
 */
 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
@@ -196292,7 +202336,7 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
 **
 ** This file contains an implementation of the "dbstat" virtual table.
 **
-** The dbstat virtual table is used to extract low-level formatting
+** The dbstat virtual table is used to extract low-level storage
 ** information from an SQLite database in order to implement the
 ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
 ** for an example implementation.
@@ -196307,22 +202351,22 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
 
 /*
 ** Page paths:
-** 
-**   The value of the 'path' column describes the path taken from the 
-**   root-node of the b-tree structure to each page. The value of the 
+**
+**   The value of the 'path' column describes the path taken from the
+**   root-node of the b-tree structure to each page. The value of the
 **   root-node path is '/'.
 **
 **   The value of the path for the left-most child page of the root of
 **   a b-tree is '/000/'. (Btrees store content ordered from left to right
 **   so the pages to the left have smaller keys than the pages to the right.)
 **   The next to left-most child of the root page is
-**   '/001', and so on, each sibling page identified by a 3-digit hex 
+**   '/001', and so on, each sibling page identified by a 3-digit hex
 **   value. The children of the 451st left-most sibling have paths such
 **   as '/1c2/000/, '/1c2/001/' etc.
 **
-**   Overflow pages are specified by appending a '+' character and a 
+**   Overflow pages are specified by appending a '+' character and a
 **   six-digit hexadecimal value to the path to the cell they are linked
-**   from. For example, the three overflow pages in a chain linked from 
+**   from. For example, the three overflow pages in a chain linked from
 **   the left-most cell of the 450th child of the root page are identified
 **   by the paths:
 **
@@ -196336,27 +202380,30 @@ SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
 **
 **      '/1c2/000/'               // Left-most child of 451st child of root
 */
-#define VTAB_SCHEMA                                                         \
-  "CREATE TABLE xx( "                                                       \
-  "  name       TEXT,             /* Name of table or index */"             \
-  "  path       TEXT,             /* Path to page from root */"             \
-  "  pageno     INTEGER,          /* Page number */"                        \
-  "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
-  "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
-  "  payload    INTEGER,          /* Bytes of payload on this page */"      \
-  "  unused     INTEGER,          /* Bytes of unused space on this page */" \
-  "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
-  "  pgoffset   INTEGER,          /* Offset of page in file */"             \
-  "  pgsize     INTEGER,          /* Size of the page */"                   \
-  "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
-  ");"
-
-
+static const char zDbstatSchema[] =
+  "CREATE TABLE x("
+  " name       TEXT,"          /*  0 Name of table or index */
+  " path       TEXT,"          /*  1 Path to page from root (NULL for agg) */
+  " pageno     INTEGER,"       /*  2 Page number (page count for aggregates) */
+  " pagetype   TEXT,"          /*  3 'internal', 'leaf', 'overflow', or NULL */
+  " ncell      INTEGER,"       /*  4 Cells on page (0 for overflow) */
+  " payload    INTEGER,"       /*  5 Bytes of payload on this page */
+  " unused     INTEGER,"       /*  6 Bytes of unused space on this page */
+  " mx_payload INTEGER,"       /*  7 Largest payload size of all cells */
+  " pgoffset   INTEGER,"       /*  8 Offset of page in file (NULL for agg) */
+  " pgsize     INTEGER,"       /*  9 Size of the page (sum for aggregate) */
+  " schema     TEXT HIDDEN,"   /* 10 Database schema being analyzed */
+  " aggregate  BOOLEAN HIDDEN" /* 11 aggregate info for each table */
+  ")"
+;
+
+/* Forward reference to data structured used in this module */
 typedef struct StatTable StatTable;
 typedef struct StatCursor StatCursor;
 typedef struct StatPage StatPage;
 typedef struct StatCell StatCell;
 
+/* Size information for a single cell within a btree page */
 struct StatCell {
   int nLocal;                     /* Bytes of local payload */
   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
@@ -196366,10 +202413,11 @@ struct StatCell {
   int iOvfl;                      /* Iterates through aOvfl[] */
 };
 
+/* Size information for a single btree page */
 struct StatPage {
-  u32 iPgno;
-  DbPage *pPg;
-  int iCell;
+  u32 iPgno;                      /* Page number */
+  DbPage *pPg;                    /* Page content */
+  int iCell;                      /* Current cell */
 
   char *zPath;                    /* Path to this page */
 
@@ -196379,34 +202427,38 @@ struct StatPage {
   int nUnused;                    /* Number of unused bytes on page */
   StatCell *aCell;                /* Array of parsed cells */
   u32 iRightChildPg;              /* Right-child page number (or 0) */
-  int nMxPayload;                 /* Largest payload of any cell on this page */
+  int nMxPayload;                 /* Largest payload of any cell on the page */
 };
 
+/* The cursor for scanning the dbstat virtual table */
 struct StatCursor {
-  sqlite3_vtab_cursor base;
+  sqlite3_vtab_cursor base;       /* base class.  MUST BE FIRST! */
   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
-  int isEof;                      /* After pStmt has returned SQLITE_DONE */
+  u8 isEof;                       /* After pStmt has returned SQLITE_DONE */
+  u8 isAgg;                       /* Aggregate results for each table */
   int iDb;                        /* Schema used for this query */
 
-  StatPage aPage[32];
+  StatPage aPage[32];             /* Pages in path to current page */
   int iPage;                      /* Current entry in aPage[] */
 
   /* Values to return. */
+  u32 iPageno;                    /* Value of 'pageno' column */
   char *zName;                    /* Value of 'name' column */
   char *zPath;                    /* Value of 'path' column */
-  u32 iPageno;                    /* Value of 'pageno' column */
   const char *zPagetype;          /* Value of 'pagetype' column */
+  int nPage;                      /* Number of pages in current btree */
   int nCell;                      /* Value of 'ncell' column */
-  int nPayload;                   /* Value of 'payload' column */
-  int nUnused;                    /* Value of 'unused' column */
   int nMxPayload;                 /* Value of 'mx_payload' column */
+  i64 nUnused;                    /* Value of 'unused' column */
+  i64 nPayload;                   /* Value of 'payload' column */
   i64 iOffset;                    /* Value of 'pgOffset' column */
-  int szPage;                     /* Value of 'pgSize' column */
+  i64 szPage;                     /* Value of 'pgSize' column */
 };
 
+/* An instance of the DBSTAT virtual table */
 struct StatTable {
-  sqlite3_vtab base;
-  sqlite3 *db;
+  sqlite3_vtab base;              /* base class.  MUST BE FIRST! */
+  sqlite3 *db;                    /* Database connection that owns this vtab */
   int iDb;                        /* Index of database to analyze */
 };
 
@@ -196415,7 +202467,7 @@ struct StatTable {
 #endif
 
 /*
-** Connect to or create a statvfs virtual table.
+** Connect to or create a new DBSTAT virtual table.
 */
 static int statConnect(
   sqlite3 *db,
@@ -196439,7 +202491,8 @@ static int statConnect(
   }else{
     iDb = 0;
   }
-  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
+  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
+  rc = sqlite3_declare_vtab(db, zDbstatSchema);
   if( rc==SQLITE_OK ){
     pTab = (StatTable *)sqlite3Malloc(sizeof(StatTable));
     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
@@ -196457,7 +202510,7 @@ static int statConnect(
 }
 
 /*
-** Disconnect from or destroy a statvfs virtual table.
+** Disconnect from or destroy the DBSTAT virtual table.
 */
 static int statDisconnect(sqlite3_vtab *pVtab){
   sqlite3_free(pVtab);
@@ -196465,14 +202518,20 @@ static int statDisconnect(sqlite3_vtab *pVtab){
 }
 
 /*
-** There is no "best-index". This virtual table always does a linear
-** scan.  However, a schema=? constraint should cause this table to
-** operate on a different database schema, so check for it.
+** Compute the best query strategy and return the result in idxNum.
 **
-** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
+**   idxNum-Bit        Meaning
+**   ----------        ----------------------------------------------
+**      0x01           There is a schema=? term in the WHERE clause
+**      0x02           There is a name=? term in the WHERE clause
+**      0x04           There is an aggregate=? term in the WHERE clause
+**      0x08           Output should be ordered by name and path
 */
 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   int i;
+  int iSchema = -1;
+  int iName = -1;
+  int iAgg = -1;
 
   /* Look for a valid schema=? constraint.  If found, change the idxNum to
   ** 1 and request the value of that constraint be sent to xFilter.  And
@@ -196480,19 +202539,44 @@ static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
   ** used.
   */
   for(i=0; i<pIdxInfo->nConstraint; i++){
-    if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
-    if( pIdxInfo->aConstraint[i].usable==0 ) return SQLITE_CONSTRAINT;
     if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
-    pIdxInfo->idxNum = 1;
-    pIdxInfo->estimatedCost = 1.0;
-    pIdxInfo->aConstraintUsage[i].argvIndex = 1;
-    pIdxInfo->aConstraintUsage[i].omit = 1;
-    break;
+    if( pIdxInfo->aConstraint[i].usable==0 ){
+      /* Force DBSTAT table should always be the right-most table in a join */
+      return SQLITE_CONSTRAINT;
+    }
+    switch( pIdxInfo->aConstraint[i].iColumn ){
+      case 0: {    /* name */
+        iName = i;
+        break;
+      }
+      case 10: {   /* schema */
+        iSchema = i;
+        break;
+      }
+      case 11: {   /* aggregate */
+        iAgg = i;
+        break;
+      }
+    }
   }
+  i = 0;
+  if( iSchema>=0 ){
+    pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
+    pIdxInfo->aConstraintUsage[iSchema].omit = 1;
+    pIdxInfo->idxNum |= 0x01;
+  }
+  if( iName>=0 ){
+    pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
+    pIdxInfo->idxNum |= 0x02;
+  }
+  if( iAgg>=0 ){
+    pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
+    pIdxInfo->idxNum |= 0x04;
+  }
+  pIdxInfo->estimatedCost = 1.0;
 
-
-  /* Records are always returned in ascending order of (name, path). 
-  ** If this will satisfy the client, set the orderByConsumed flag so that 
+  /* Records are always returned in ascending order of (name, path).
+  ** If this will satisfy the client, set the orderByConsumed flag so that
   ** SQLite does not do an external sort.
   */
   if( ( pIdxInfo->nOrderBy==1
@@ -196507,13 +202591,14 @@ static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
      )
   ){
     pIdxInfo->orderByConsumed = 1;
+    pIdxInfo->idxNum |= 0x08;
   }
 
   return SQLITE_OK;
 }
 
 /*
-** Open a new statvfs cursor.
+** Open a new DBSTAT cursor.
 */
 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
   StatTable *pTab = (StatTable *)pVTab;
@@ -196563,8 +202648,18 @@ static void statResetCsr(StatCursor *pCsr){
   pCsr->isEof = 0;
 }
 
+/* Resize the space-used counters inside of the cursor */
+static void statResetCounts(StatCursor *pCsr){
+  pCsr->nCell = 0;
+  pCsr->nMxPayload = 0;
+  pCsr->nUnused = 0;
+  pCsr->nPayload = 0;
+  pCsr->szPage = 0;
+  pCsr->nPage = 0;
+}
+
 /*
-** Close a statvfs cursor.
+** Close a DBSTAT cursor.
 */
 static int statClose(sqlite3_vtab_cursor *pCursor){
   StatCursor *pCsr = (StatCursor *)pCursor;
@@ -196574,16 +202669,20 @@ static int statClose(sqlite3_vtab_cursor *pCursor){
   return SQLITE_OK;
 }
 
-static void getLocalPayload(
+/*
+** For a single cell on a btree page, compute the number of bytes of
+** content (payload) stored on that page.  That is to say, compute the
+** number of bytes of content not found on overflow pages.
+*/
+static int getLocalPayload(
   int nUsable,                    /* Usable bytes per page */
   u8 flags,                       /* Page flags */
-  int nTotal,                     /* Total record (payload) size */
-  int *pnLocal                    /* OUT: Bytes stored locally */
+  int nTotal                      /* Total record (payload) size */
 ){
   int nLocal;
   int nMinLocal;
   int nMaxLocal;
+
   if( flags==0x0D ){              /* Table leaf node */
     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
     nMaxLocal = nUsable - 35;
@@ -196594,9 +202693,12 @@ static void getLocalPayload(
 
   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
-  *pnLocal = nLocal;
+  return nLocal;
 }
 
+/* Populate the StatPage object with information about the all
+** cells found on the page currently under analysis.
+*/
 static int statDecodePage(Btree *pBt, StatPage *p){
   int nUnused;
   int iOff;
@@ -196667,7 +202769,7 @@ static int statDecodePage(Btree *pBt, StatPage *p){
           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
         }
         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
-        getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
+        nLocal = getLocalPayload(nUsable, p->flags, nPayload);
         if( nLocal<0 ) goto statPageIsCorrupt;
         pCell->nLocal = nLocal;
         assert( nPayload>=(u32)nLocal );
@@ -196675,7 +202777,9 @@ static int statDecodePage(Btree *pBt, StatPage *p){
         if( nPayload>(u32)nLocal ){
           int j;
           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
-          if( iOff+nLocal>nUsable ) goto statPageIsCorrupt;
+          if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){
+            goto statPageIsCorrupt;
+          }
           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
           pCell->nOvfl = nOvfl;
           pCell->aOvfl = sqlite3Malloc(sizeof(u32)*nOvfl);
@@ -196689,7 +202793,7 @@ static int statDecodePage(Btree *pBt, StatPage *p){
             if( rc!=SQLITE_OK ){
               assert( pPg==0 );
               return rc;
-            } 
+            }
             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
             sqlite3PagerUnref(pPg);
           }
@@ -196717,23 +202821,25 @@ static void statSizeAndOffset(StatCursor *pCsr){
   sqlite3_file *fd;
   sqlite3_int64 x[2];
 
-  /* The default page size and offset */
-  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
-  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
-
-  /* If connected to a ZIPVFS backend, override the page size and
-  ** offset with actual values obtained from ZIPVFS.
+  /* If connected to a ZIPVFS backend, find the page size and
+  ** offset from ZIPVFS.
   */
   fd = sqlite3PagerFile(pPager);
   x[0] = pCsr->iPageno;
   if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
     pCsr->iOffset = x[0];
-    pCsr->szPage = (int)x[1];
+    pCsr->szPage += x[1];
+  }else{
+    /* Not ZIPVFS: The default page size and offset */
+    pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
+    pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
   }
 }
 
 /*
-** Move a statvfs cursor to the next entry in the file.
+** Move a DBSTAT cursor to the next entry.  Normally, the next
+** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
+** the next entry is the next btree.
 */
 static int statNext(sqlite3_vtab_cursor *pCursor){
   int rc;
@@ -196749,6 +202855,8 @@ static int statNext(sqlite3_vtab_cursor *pCursor){
 
 statNextRestart:
   if( pCsr->aPage[0].pPg==0 ){
+    /* Start measuring space on the next btree */
+    statResetCounts(pCsr);
     rc = sqlite3_step(pCsr->pStmt);
     if( rc==SQLITE_ROW ){
       int nPage;
@@ -196761,44 +202869,47 @@ statNextRestart:
       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
       pCsr->aPage[0].iPgno = iRoot;
       pCsr->aPage[0].iCell = 0;
-      pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
+      if( !pCsr->isAgg ){
+        pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
+        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+      }
       pCsr->iPage = 0;
-      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+      pCsr->nPage = 1;
     }else{
       pCsr->isEof = 1;
       return sqlite3_reset(pCsr->pStmt);
     }
   }else{
-
-    /* Page p itself has already been visited. */
+    /* Continue analyzing the btree previously started */
     StatPage *p = &pCsr->aPage[pCsr->iPage];
-
+    if( !pCsr->isAgg ) statResetCounts(pCsr);
     while( p->iCell<p->nCell ){
       StatCell *pCell = &p->aCell[p->iCell];
-      if( pCell->iOvfl<pCell->nOvfl ){
-        int nUsable;
+      while( pCell->iOvfl<pCell->nOvfl ){
+        int nUsable, iOvfl;
         sqlite3BtreeEnter(pBt);
-        nUsable = sqlite3BtreeGetPageSize(pBt) - 
+        nUsable = sqlite3BtreeGetPageSize(pBt) -
                         sqlite3BtreeGetReserveNoMutex(pBt);
         sqlite3BtreeLeave(pBt);
-        pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
-        pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
-        pCsr->zPagetype = "overflow";
-        pCsr->nCell = 0;
-        pCsr->nMxPayload = 0;
-        pCsr->zPath = z = sqlite3_mprintf(
-            "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
-        );
+        pCsr->nPage++;
+        statSizeAndOffset(pCsr);
         if( pCell->iOvfl<pCell->nOvfl-1 ){
-          pCsr->nUnused = 0;
-          pCsr->nPayload = nUsable - 4;
+          pCsr->nPayload += nUsable - 4;
         }else{
-          pCsr->nPayload = pCell->nLastOvfl;
-          pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
+          pCsr->nPayload += pCell->nLastOvfl;
+          pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
         }
+        iOvfl = pCell->iOvfl;
         pCell->iOvfl++;
-        statSizeAndOffset(pCsr);
-        return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
+        if( !pCsr->isAgg ){
+          pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
+          pCsr->iPageno = pCell->aOvfl[iOvfl];
+          pCsr->zPagetype = "overflow";
+          pCsr->zPath = z = sqlite3_mprintf(
+              "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
+          );
+          return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
+        }
       }
       if( p->iRightChildPg ) break;
       p->iCell++;
@@ -196806,8 +202917,13 @@ statNextRestart:
 
     if( !p->iRightChildPg || p->iCell>p->nCell ){
       statClearPage(p);
-      if( pCsr->iPage==0 ) return statNext(pCursor);
-      pCsr->iPage--;
+      if( pCsr->iPage>0 ){
+        pCsr->iPage--;
+      }else if( pCsr->isAgg ){
+        /* label-statNext-done:  When computing aggregate space usage over
+        ** an entire btree, this is the exit point from this function */
+        return SQLITE_OK;
+      }
       goto statNextRestart; /* Tail recursion */
     }
     pCsr->iPage++;
@@ -196823,10 +202939,13 @@ statNextRestart:
       p[1].iPgno = p->aCell[p->iCell].iChildPg;
     }
     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
+    pCsr->nPage++;
     p[1].iCell = 0;
-    p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
+    if( !pCsr->isAgg ){
+      p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
+      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+    }
     p->iCell++;
-    if( z==0 ) rc = SQLITE_NOMEM_BKPT;
   }
 
 
@@ -196856,16 +202975,23 @@ statNextRestart:
           pCsr->zPagetype = "corrupted";
           break;
       }
-      pCsr->nCell = p->nCell;
-      pCsr->nUnused = p->nUnused;
-      pCsr->nMxPayload = p->nMxPayload;
-      pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
-      if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+      pCsr->nCell += p->nCell;
+      pCsr->nUnused += p->nUnused;
+      if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
+      if( !pCsr->isAgg ){
+        pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
+        if( z==0 ) rc = SQLITE_NOMEM_BKPT;
+      }
       nPayload = 0;
       for(i=0; i<p->nCell; i++){
         nPayload += p->aCell[i].nLocal;
       }
-      pCsr->nPayload = nPayload;
+      pCsr->nPayload += nPayload;
+
+      /* If computing aggregate space usage by btree, continue with the
+      ** next page.  The loop will exit via the return at label-statNext-done
+      */
+      if( pCsr->isAgg ) goto statNextRestart;
     }
   }
 
@@ -196877,36 +203003,63 @@ static int statEof(sqlite3_vtab_cursor *pCursor){
   return pCsr->isEof;
 }
 
+/* Initialize a cursor according to the query plan idxNum using the
+** arguments in argv[0].  See statBestIndex() for a description of the
+** meaning of the bits in idxNum.
+*/
 static int statFilter(
-  sqlite3_vtab_cursor *pCursor, 
+  sqlite3_vtab_cursor *pCursor,
   int idxNum, const char *idxStr,
   int argc, sqlite3_value **argv
 ){
   StatCursor *pCsr = (StatCursor *)pCursor;
   StatTable *pTab = (StatTable*)(pCursor->pVtab);
-  char *zSql;
-  int rc = SQLITE_OK;
+  sqlite3_str *pSql;      /* Query of btrees to analyze */
+  char *zSql;             /* String value of pSql */
+  int iArg = 0;           /* Count of argv[] parameters used so far */
+  int rc = SQLITE_OK;     /* Result of this operation */
+  const char *zName = 0;  /* Only provide analysis of this table */
 
-  if( idxNum==1 ){
-    const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
+  statResetCsr(pCsr);
+  sqlite3_finalize(pCsr->pStmt);
+  pCsr->pStmt = 0;
+  if( idxNum & 0x01 ){
+    /* schema=? constraint is present.  Get its value */
+    const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
     pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
     if( pCsr->iDb<0 ){
-      sqlite3_free(pCursor->pVtab->zErrMsg);
-      pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
-      return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
+      pCsr->iDb = 0;
+      pCsr->isEof = 1;
+      return SQLITE_OK;
     }
   }else{
     pCsr->iDb = pTab->iDb;
   }
-  statResetCsr(pCsr);
-  sqlite3_finalize(pCsr->pStmt);
-  pCsr->pStmt = 0;
-  zSql = sqlite3_mprintf(
-      "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
-      "  UNION ALL  "
-      "SELECT name, rootpage, type"
-      "  FROM \"%w\".sqlite_master WHERE rootpage!=0"
-      "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName);
+  if( idxNum & 0x02 ){
+    /* name=? constraint is present */
+    zName = (const char*)sqlite3_value_text(argv[iArg++]);
+  }
+  if( idxNum & 0x04 ){
+    /* aggregate=? constraint is present */
+    pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
+  }else{
+    pCsr->isAgg = 0;
+  }
+  pSql = sqlite3_str_new(pTab->db);
+  sqlite3_str_appendf(pSql,
+      "SELECT * FROM ("
+        "SELECT 'sqlite_schema' AS name,1 AS rootpage,'table' AS type"
+        " UNION ALL "
+        "SELECT name,rootpage,type"
+        " FROM \"%w\".sqlite_schema WHERE rootpage!=0)",
+      pTab->db->aDb[pCsr->iDb].zDbSName);
+  if( zName ){
+    sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
+  }
+  if( idxNum & 0x08 ){
+    sqlite3_str_appendf(pSql, " ORDER BY name");
+  }
+  zSql = sqlite3_str_finish(pSql);
   if( zSql==0 ){
     return SQLITE_NOMEM_BKPT;
   }else{
@@ -196921,8 +203074,8 @@ static int statFilter(
 }
 
 static int statColumn(
-  sqlite3_vtab_cursor *pCursor, 
-  sqlite3_context *ctx, 
+  sqlite3_vtab_cursor *pCursor,
+  sqlite3_context *ctx,
   int i
 ){
   StatCursor *pCsr = (StatCursor *)pCursor;
@@ -196931,13 +203084,21 @@ static int statColumn(
       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
       break;
     case 1:            /* path */
-      sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
+      if( !pCsr->isAgg ){
+        sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
+      }
       break;
     case 2:            /* pageno */
-      sqlite3_result_int64(ctx, pCsr->iPageno);
+      if( pCsr->isAgg ){
+        sqlite3_result_int64(ctx, pCsr->nPage);
+      }else{
+        sqlite3_result_int64(ctx, pCsr->iPageno);
+      }
       break;
     case 3:            /* pagetype */
-      sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
+      if( !pCsr->isAgg ){
+        sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
+      }
       break;
     case 4:            /* ncell */
       sqlite3_result_int(ctx, pCsr->nCell);
@@ -196952,17 +203113,23 @@ static int statColumn(
       sqlite3_result_int(ctx, pCsr->nMxPayload);
       break;
     case 8:            /* pgoffset */
-      sqlite3_result_int64(ctx, pCsr->iOffset);
+      if( !pCsr->isAgg ){
+        sqlite3_result_int64(ctx, pCsr->iOffset);
+      }
       break;
     case 9:            /* pgsize */
       sqlite3_result_int(ctx, pCsr->szPage);
       break;
-    default: {          /* schema */
+    case 10: {         /* schema */
       sqlite3 *db = sqlite3_context_db_handle(ctx);
       int iDb = pCsr->iDb;
       sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
       break;
     }
+    default: {         /* aggregate */
+      sqlite3_result_int(ctx, pCsr->isAgg);
+      break;
+    }
   }
   return SQLITE_OK;
 }
@@ -197026,7 +203193,7 @@ SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
 ** This file contains an implementation of the "sqlite_dbpage" virtual table.
 **
 ** The sqlite_dbpage virtual table is used to read or write whole raw
-** pages of the database file.  The pager interface is used so that 
+** pages of the database file.  The pager interface is used so that
 ** uncommitted changes and changes recorded in the WAL file are correctly
 ** retrieved.
 **
@@ -197086,7 +203253,8 @@ static int dbpageConnect(
   DbpageTable *pTab = 0;
   int rc = SQLITE_OK;
 
-  rc = sqlite3_declare_vtab(db, 
+  sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
+  rc = sqlite3_declare_vtab(db,
           "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
   if( rc==SQLITE_OK ){
     pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
@@ -197226,7 +203394,7 @@ static int dbpageEof(sqlite3_vtab_cursor *pCursor){
 ** idxStr is not used
 */
 static int dbpageFilter(
-  sqlite3_vtab_cursor *pCursor, 
+  sqlite3_vtab_cursor *pCursor,
   int idxNum, const char *idxStr,
   int argc, sqlite3_value **argv
 ){
@@ -197237,7 +203405,7 @@ static int dbpageFilter(
   Btree *pBt;
 
   /* Default setting is no rows of result */
-  pCsr->pgno = 1; 
+  pCsr->pgno = 1;
   pCsr->mxPgno = 0;
 
   if( idxNum & 2 ){
@@ -197272,8 +203440,8 @@ static int dbpageFilter(
 }
 
 static int dbpageColumn(
-  sqlite3_vtab_cursor *pCursor, 
-  sqlite3_context *ctx, 
+  sqlite3_vtab_cursor *pCursor,
+  sqlite3_context *ctx,
   int i
 ){
   DbpageCursor *pCsr = (DbpageCursor *)pCursor;
@@ -197350,7 +203518,7 @@ static int dbpageUpdate(
     goto update_fail;
   }
   szPage = sqlite3BtreeGetPageSize(pBt);
-  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB 
+  if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
    || sqlite3_value_bytes(argv[3])!=szPage
   ){
     zErr = "bad page value";
@@ -197495,7 +203663,7 @@ struct SessionBuffer {
 };
 
 /*
-** An object of this type is used internally as an abstraction for 
+** An object of this type is used internally as an abstraction for
 ** input data. Input data may be supplied either as a single large buffer
 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
 **  sqlite3changeset_start_strm()).
@@ -197556,11 +203724,11 @@ struct SessionTable {
   SessionChange **apChange;       /* Hash table buckets */
 };
 
-/* 
+/*
 ** RECORD FORMAT:
 **
-** The following record format is similar to (but not compatible with) that 
-** used in SQLite database files. This format is used as part of the 
+** The following record format is similar to (but not compatible with) that
+** used in SQLite database files. This format is used as part of the
 ** change-set binary format, and so must be architecture independent.
 **
 ** Unlike the SQLite database record format, each field is self-contained -
@@ -197594,7 +203762,7 @@ struct SessionTable {
 **   Real values:
 **     An 8-byte big-endian IEEE 754-2008 real value.
 **
-** Varint values are encoded in the same way as varints in the SQLite 
+** Varint values are encoded in the same way as varints in the SQLite
 ** record format.
 **
 ** CHANGESET FORMAT:
@@ -197626,7 +203794,7 @@ struct SessionTable {
 **
 ** The new.* record that is part of each INSERT change contains the values
 ** that make up the new row. Similarly, the old.* record that is part of each
-** DELETE change contains the values that made up the row that was deleted 
+** DELETE change contains the values that made up the row that was deleted
 ** from the database. In the changeset format, the records that are part
 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
 ** fields.
@@ -197635,8 +203803,8 @@ struct SessionTable {
 ** associated with table columns that are not PRIMARY KEY columns and are
 ** not modified by the UPDATE change are set to "undefined". Other fields
 ** are set to the values that made up the row before the UPDATE that the
-** change records took place. Within the new.* record, fields associated 
-** with table columns modified by the UPDATE change contain the new 
+** change records took place. Within the new.* record, fields associated
+** with table columns modified by the UPDATE change contain the new
 ** values. Fields associated with table columns that are not modified
 ** are set to "undefined".
 **
@@ -197662,7 +203830,7 @@ struct SessionTable {
 **
 ** As in the changeset format, each field of the single record that is part
 ** of a patchset change is associated with the correspondingly positioned
-** table column, counting from left to right within the CREATE TABLE 
+** table column, counting from left to right within the CREATE TABLE
 ** statement.
 **
 ** For a DELETE change, all fields within the record except those associated
@@ -197680,7 +203848,7 @@ struct SessionTable {
 **
 ** REBASE BLOB FORMAT:
 **
-** A rebase blob may be output by sqlite3changeset_apply_v2() and its 
+** A rebase blob may be output by sqlite3changeset_apply_v2() and its
 ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
 ** existing changesets. A rebase blob contains one entry for each conflict
 ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
@@ -197704,7 +203872,7 @@ struct SessionTable {
 **
 ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
 ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
-** it was a DELETE. The second field is set to 0x01 if the conflict 
+** it was a DELETE. The second field is set to 0x01 if the conflict
 ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
 **
 ** If the change that caused the conflict was a DELETE, then the single
@@ -197728,7 +203896,7 @@ struct SessionChange {
 };
 
 /*
-** Write a varint with value iVal into the buffer at aBuf. Return the 
+** Write a varint with value iVal into the buffer at aBuf. Return the
 ** number of bytes written.
 */
 static int sessionVarintPut(u8 *aBuf, int iVal){
@@ -197743,7 +203911,7 @@ static int sessionVarintLen(int iVal){
 }
 
 /*
-** Read a varint value from aBuf[] into *piVal. Return the number of 
+** Read a varint value from aBuf[] into *piVal. Return the number of
 ** bytes read.
 */
 static int sessionVarintGet(u8 *aBuf, int *piVal){
@@ -197782,13 +203950,13 @@ static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
 ** This function is used to serialize the contents of value pValue (see
 ** comment titled "RECORD FORMAT" above).
 **
-** If it is non-NULL, the serialized form of the value is written to 
+** If it is non-NULL, the serialized form of the value is written to
 ** buffer aBuf. *pnWrite is set to the number of bytes written before
 ** returning. Or, if aBuf is NULL, the only thing this function does is
 ** set *pnWrite.
 **
 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
-** within a call to sqlite3_value_text() (may fail if the db is utf-16)) 
+** within a call to sqlite3_value_text() (may fail if the db is utf-16))
 ** SQLITE_NOMEM is returned.
 */
 static int sessionSerializeValue(
@@ -197800,16 +203968,16 @@ static int sessionSerializeValue(
 
   if( pValue ){
     int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
-  
+
     eType = sqlite3_value_type(pValue);
     if( aBuf ) aBuf[0] = eType;
-  
+
     switch( eType ){
-      case SQLITE_NULL: 
+      case SQLITE_NULL:
         nByte = 1;
         break;
-  
-      case SQLITE_INTEGER: 
+
+      case SQLITE_INTEGER:
       case SQLITE_FLOAT:
         if( aBuf ){
           /* TODO: SQLite does something special to deal with mixed-endian
@@ -197826,14 +203994,14 @@ static int sessionSerializeValue(
           }
           sessionPutI64(&aBuf[1], i);
         }
-        nByte = 9; 
+        nByte = 9;
         break;
-  
+
       default: {
         u8 *z;
         int n;
         int nVarint;
-  
+
         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
         if( eType==SQLITE_TEXT ){
           z = (u8 *)sqlite3_value_text(pValue);
@@ -197843,12 +204011,12 @@ static int sessionSerializeValue(
         n = sqlite3_value_bytes(pValue);
         if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
         nVarint = sessionVarintLen(n);
-  
+
         if( aBuf ){
           sessionVarintPut(&aBuf[1], n);
           if( n ) memcpy(&aBuf[nVarint + 1], z, n);
         }
-  
+
         nByte = 1 + nVarint + n;
         break;
       }
@@ -197890,7 +204058,7 @@ static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
 }
 
 /*
-** Append the hash of the blob passed via the second and third arguments to 
+** Append the hash of the blob passed via the second and third arguments to
 ** the hash-key value passed as the first. Return the new hash-key value.
 */
 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
@@ -197909,7 +204077,7 @@ static unsigned int sessionHashAppendType(unsigned int h, int eType){
 
 /*
 ** This function may only be called from within a pre-update callback.
-** It calculates a hash based on the primary key values of the old.* or 
+** It calculates a hash based on the primary key values of the old.* or
 ** new.* row currently available and, assuming no error occurs, writes it to
 ** *piHash before returning. If the primary key contains one or more NULL
 ** values, *pbNullPK is set to true before returning.
@@ -198016,12 +204184,12 @@ static unsigned int sessionChangeHash(
     int isPK = pTab->abPK[i];
     if( bPkOnly && isPK==0 ) continue;
 
-    /* It is not possible for eType to be SQLITE_NULL here. The session 
+    /* It is not possible for eType to be SQLITE_NULL here. The session
     ** module does not record changes for rows with NULL values stored in
     ** primary key columns. */
-    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT 
-         || eType==SQLITE_TEXT || eType==SQLITE_BLOB 
-         || eType==SQLITE_NULL || eType==0 
+    assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
+         || eType==SQLITE_TEXT || eType==SQLITE_BLOB
+         || eType==SQLITE_NULL || eType==0
     );
     assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
 
@@ -198032,7 +204200,7 @@ static unsigned int sessionChangeHash(
         h = sessionHashAppendI64(h, sessionGetI64(a));
         a += 8;
       }else{
-        int n; 
+        int n;
         a += sessionVarintGet(a, &n);
         h = sessionHashAppendBlob(h, n, a);
         a += n;
@@ -198047,7 +204215,7 @@ static unsigned int sessionChangeHash(
 /*
 ** Arguments aLeft and aRight are pointers to change records for table pTab.
 ** This function returns true if the two records apply to the same row (i.e.
-** have the same values stored in the primary key columns), or false 
+** have the same values stored in the primary key columns), or false
 ** otherwise.
 */
 static int sessionChangeEqual(
@@ -198084,17 +204252,17 @@ static int sessionChangeEqual(
 ** Arguments aLeft and aRight both point to buffers containing change
 ** records with nCol columns. This function "merges" the two records into
 ** a single records which is written to the buffer at *paOut. *paOut is
-** then set to point to one byte after the last byte written before 
+** then set to point to one byte after the last byte written before
 ** returning.
 **
-** The merging of records is done as follows: For each column, if the 
+** The merging of records is done as follows: For each column, if the
 ** aRight record contains a value for the column, copy the value from
 ** their. Otherwise, if aLeft contains a value, copy it. If neither
 ** record contains a value for a given column, then neither does the
 ** output record.
 */
 static void sessionMergeRecord(
-  u8 **paOut, 
+  u8 **paOut,
   int nCol,
   u8 *aLeft,
   u8 *aRight
@@ -198124,13 +204292,13 @@ static void sessionMergeRecord(
 /*
 ** This is a helper function used by sessionMergeUpdate().
 **
-** When this function is called, both *paOne and *paTwo point to a value 
-** within a change record. Before it returns, both have been advanced so 
+** When this function is called, both *paOne and *paTwo point to a value
+** within a change record. Before it returns, both have been advanced so
 ** as to point to the next value in the record.
 **
 ** If, when this function is called, *paTwo points to a valid value (i.e.
 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
-** pointer is returned and *pnVal is set to the number of bytes in the 
+** pointer is returned and *pnVal is set to the number of bytes in the
 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
 ** set to the number of bytes in the value at *paOne. If *paOne points
 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
@@ -198229,8 +204397,8 @@ static int sessionMergeUpdate(
 
     aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
     aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
-    if( bPatchset==0 
-     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) 
+    if( bPatchset==0
+     && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
     ){
       *(aOut++) = '\0';
     }else{
@@ -198317,7 +204485,7 @@ static int sessionPreupdateEqual(
 }
 
 /*
-** If required, grow the hash table used to store changes on table pTab 
+** If required, grow the hash table used to store changes on table pTab
 ** (part of the session pSession). If a fatal OOM error occurs, set the
 ** session object to failed and return SQLITE_ERROR. Otherwise, return
 ** SQLITE_OK.
@@ -198457,7 +204625,7 @@ static int sessionTableInfo(
       *pzTab = (char *)pAlloc;
       pAlloc += nThis+1;
     }
-  
+
     i = 0;
     while( SQLITE_ROW==sqlite3_step(pStmt) ){
       int nName = sqlite3_column_bytes(pStmt, 1);
@@ -198470,7 +204638,7 @@ static int sessionTableInfo(
       i++;
     }
     rc = sqlite3_reset(pStmt);
-  
+
   }
 
   /* If successful, populate the output variables. Otherwise, zero them and
@@ -198500,14 +204668,14 @@ static int sessionTableInfo(
 ** If an error occurs, an error code is stored in sqlite3_session.rc and
 ** non-zero returned. Or, if no error occurs but the table has no primary
 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
-** indicate that updates on this table should be ignored. SessionTable.abPK 
+** indicate that updates on this table should be ignored. SessionTable.abPK
 ** is set to NULL in this case.
 */
 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
   if( pTab->nCol==0 ){
     u8 *abPK;
     assert( pTab->azCol==0 || pTab->abPK==0 );
-    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, 
+    pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
         pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
     );
     if( pSession->rc==SQLITE_OK ){
@@ -198568,7 +204736,7 @@ static int sessionStat1Depth(void *pCtx){
 
 
 /*
-** This function is only called from with a pre-update-hook reporting a 
+** This function is only called from with a pre-update-hook reporting a
 ** change on table pTab (attached to session pSession). The type of change
 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
 **
@@ -198580,8 +204748,8 @@ static void sessionPreupdateOneChange(
   sqlite3_session *pSession,      /* Session object pTab is attached to */
   SessionTable *pTab              /* Table that change applies to */
 ){
-  int iHash; 
-  int bNull = 0; 
+  int iHash;
+  int bNull = 0;
   int rc = SQLITE_OK;
   SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
 
@@ -198590,7 +204758,7 @@ static void sessionPreupdateOneChange(
   /* Load table details if required */
   if( sessionInitTable(pSession, pTab) ) return;
 
-  /* Check the number of columns in this xPreUpdate call matches the 
+  /* Check the number of columns in this xPreUpdate call matches the
   ** number of columns in the table.  */
   if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
     pSession->rc = SQLITE_SCHEMA;
@@ -198642,10 +204810,10 @@ static void sessionPreupdateOneChange(
       SessionChange *pChange; /* New change object */
       sqlite3_int64 nByte;    /* Number of bytes to allocate */
       int i;                  /* Used to iterate through columns */
-  
+
       assert( rc==SQLITE_OK );
       pTab->nEntry++;
-  
+
       /* Figure out how large an allocation is required */
       nByte = sizeof(SessionChange);
       for(i=0; i<pTab->nCol; i++){
@@ -198663,7 +204831,7 @@ static void sessionPreupdateOneChange(
         rc = sessionSerializeValue(0, p, &nByte);
         if( rc!=SQLITE_OK ) goto error_out;
       }
-  
+
       /* Allocate the change object */
       pChange = (SessionChange *)sqlite3_malloc(nByte);
       if( !pChange ){
@@ -198673,7 +204841,7 @@ static void sessionPreupdateOneChange(
         memset(pChange, 0, sizeof(SessionChange));
         pChange->aRecord = (u8 *)&pChange[1];
       }
-  
+
       /* Populate the change object. None of the preupdate_old(),
       ** preupdate_new() or SerializeValue() calls below may fail as all
       ** required values and encodings have already been cached in memory.
@@ -198701,8 +204869,8 @@ static void sessionPreupdateOneChange(
     }else if( pC->bIndirect ){
       /* If the existing change is considered "indirect", but this current
       ** change is "direct", mark the change object as direct. */
-      if( pSession->hook.xDepth(pSession->hook.pCtx)==0 
-       && pSession->bIndirect==0 
+      if( pSession->hook.xDepth(pSession->hook.pCtx)==0
+       && pSession->bIndirect==0
       ){
         pC->bIndirect = 0;
       }
@@ -198720,7 +204888,7 @@ static void sessionPreupdateOneChange(
 }
 
 static int sessionFindTable(
-  sqlite3_session *pSession, 
+  sqlite3_session *pSession,
   const char *zName,
   SessionTable **ppTab
 ){
@@ -198737,7 +204905,7 @@ static int sessionFindTable(
     /* If there is a table-filter configured, invoke it. If it returns 0,
     ** do not automatically add the new table. */
     if( pSession->xTableFilter==0
-     || pSession->xTableFilter(pSession->pFilterCtx, zName) 
+     || pSession->xTableFilter(pSession->pFilterCtx, zName)
     ){
       rc = sqlite3session_attach(pSession, zName);
       if( rc==SQLITE_OK ){
@@ -198772,8 +204940,8 @@ static void xPreUpdate(
   for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
     SessionTable *pTab;
 
-    /* If this session is attached to a different database ("main", "temp" 
-    ** etc.), or if it is not currently enabled, there is nothing to do. Skip 
+    /* If this session is attached to a different database ("main", "temp"
+    ** etc.), or if it is not currently enabled, there is nothing to do. Skip
     ** to the next session object attached to this database. */
     if( pSession->bEnable==0 ) continue;
     if( pSession->rc ) continue;
@@ -198864,7 +205032,7 @@ static void sessionDiffHooks(
 
 static char *sessionExprComparePK(
   int nCol,
-  const char *zDb1, const char *zDb2, 
+  const char *zDb1, const char *zDb2,
   const char *zTab,
   const char **azCol, u8 *abPK
 ){
@@ -198887,7 +205055,7 @@ static char *sessionExprComparePK(
 
 static char *sessionExprCompareOther(
   int nCol,
-  const char *zDb1, const char *zDb2, 
+  const char *zDb1, const char *zDb2,
   const char *zTab,
   const char **azCol, u8 *abPK
 ){
@@ -198964,9 +205132,9 @@ static int sessionDiffFindNew(
 }
 
 static int sessionDiffFindModified(
-  sqlite3_session *pSession, 
-  SessionTable *pTab, 
-  const char *zFrom, 
+  sqlite3_session *pSession,
+  SessionTable *pTab,
+  const char *zFrom,
   const char *zExpr
 ){
   int rc = SQLITE_OK;
@@ -199065,7 +205233,7 @@ SQLITE_API int sqlite3session_diff(
     }
 
     if( rc==SQLITE_OK ){
-      zExpr = sessionExprComparePK(pTo->nCol, 
+      zExpr = sessionExprComparePK(pTo->nCol,
           zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
       );
     }
@@ -199120,7 +205288,7 @@ SQLITE_API int sqlite3session_create(
   memcpy(pNew->zDb, zDb, nDb+1);
   sessionPreupdateHooks(pNew);
 
-  /* Add the new session object to the linked list of session objects 
+  /* Add the new session object to the linked list of session objects
   ** attached to database handle $db. Do this under the cover of the db
   ** handle mutex.  */
   sqlite3_mutex_enter(sqlite3_db_mutex(db));
@@ -199179,7 +205347,7 @@ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
   sqlite3_mutex_leave(sqlite3_db_mutex(db));
   sqlite3ValueFree(pSession->pZeroBlob);
 
-  /* Delete all attached table objects. And the contents of their 
+  /* Delete all attached table objects. And the contents of their
   ** associated hash-tables. */
   sessionDeleteTable(pSession->pTable);
 
@@ -199191,7 +205359,7 @@ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
 ** Set a table filter on a Session Object.
 */
 SQLITE_API void sqlite3session_table_filter(
-  sqlite3_session *pSession, 
+  sqlite3_session *pSession,
   int(*xFilter)(void*, const char*),
   void *pCtx                      /* First argument passed to xFilter */
 ){
@@ -199235,7 +205403,7 @@ SQLITE_API int sqlite3session_attach(
         rc = SQLITE_NOMEM;
       }else{
         /* Populate the new SessionTable object and link it into the list.
-        ** The new object must be linked onto the end of the list, not 
+        ** The new object must be linked onto the end of the list, not
         ** simply added to the start of it in order to ensure that tables
         ** appear in the correct order when a changeset or patchset is
         ** eventually generated. */
@@ -199303,8 +205471,8 @@ static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
-** called. Otherwise, append a single byte to the buffer. 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a single byte to the buffer.
 **
 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
 ** returning.
@@ -199316,8 +205484,8 @@ static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
-** called. Otherwise, append a single varint to the buffer. 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a single varint to the buffer.
 **
 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
 ** returning.
@@ -199329,16 +205497,16 @@ static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
-** called. Otherwise, append a blob of data to the buffer. 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
+** called. Otherwise, append a blob of data to the buffer.
 **
 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
 ** returning.
 */
 static void sessionAppendBlob(
-  SessionBuffer *p, 
-  const u8 *aBlob, 
-  int nBlob, 
+  SessionBuffer *p,
+  const u8 *aBlob,
+  int nBlob,
   int *pRc
 ){
   if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
@@ -199348,7 +205516,7 @@ static void sessionAppendBlob(
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
 ** called. Otherwise, append a string to the buffer. All bytes in the string
 ** up to (but not including) the nul-terminator are written to the buffer.
 **
@@ -199356,8 +205524,8 @@ static void sessionAppendBlob(
 ** returning.
 */
 static void sessionAppendStr(
-  SessionBuffer *p, 
-  const char *zStr, 
+  SessionBuffer *p,
+  const char *zStr,
   int *pRc
 ){
   int nStr = sqlite3Strlen30(zStr);
@@ -199368,7 +205536,7 @@ static void sessionAppendStr(
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
 ** called. Otherwise, append the string representation of integer iVal
 ** to the buffer. No nul-terminator is written.
 **
@@ -199386,9 +205554,9 @@ static void sessionAppendInteger(
 }
 
 /*
-** This function is a no-op if *pRc is other than SQLITE_OK when it is 
+** This function is a no-op if *pRc is other than SQLITE_OK when it is
 ** called. Otherwise, append the string zStr enclosed in quotes (") and
-** with any embedded quote characters escaped to the buffer. No 
+** with any embedded quote characters escaped to the buffer. No
 ** nul-terminator byte is written.
 **
 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
@@ -199461,8 +205629,8 @@ static void sessionAppendCol(
 
 /*
 **
-** This function appends an update change to the buffer (see the comments 
-** under "CHANGESET FORMAT" at the top of the file). An update change 
+** This function appends an update change to the buffer (see the comments
+** under "CHANGESET FORMAT" at the top of the file). An update change
 ** consists of:
 **
 **   1 byte:  SQLITE_UPDATE (0x17)
@@ -199477,10 +205645,10 @@ static void sessionAppendCol(
 ** If all of the old.* values are equal to their corresponding new.* value
 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
 **
-** Otherwise, the old.* record contains all primary key values and the 
-** original values of any fields that have been modified. The new.* record 
+** Otherwise, the old.* record contains all primary key values and the
+** original values of any fields that have been modified. The new.* record
 ** contains the new values of only those fields that have been modified.
-*/ 
+*/
 static int sessionAppendUpdate(
   SessionBuffer *pBuf,            /* Buffer to append to */
   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
@@ -199531,8 +205699,8 @@ static int sessionAppendUpdate(
         int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
         nAdvance = nHdr + n;
-        if( eType==sqlite3_column_type(pStmt, i) 
-         && n==sqlite3_column_bytes(pStmt, i) 
+        if( eType==sqlite3_column_type(pStmt, i)
+         && n==sqlite3_column_bytes(pStmt, i)
          && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
         ){
           break;
@@ -199759,7 +205927,7 @@ static int sessionSelectBind(
 
 /*
 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
-** is called. Otherwise, append a serialized table header (part of the binary 
+** is called. Otherwise, append a serialized table header (part of the binary
 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
 ** SQLite error code before returning.
 */
@@ -199783,7 +205951,7 @@ static void sessionAppendTableHdr(
 **
 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
-** occurs, an SQLite error code is returned and both output variables set 
+** occurs, an SQLite error code is returned and both output variables set
 ** to 0.
 */
 static int sessionGenerateChangeset(
@@ -199868,10 +206036,10 @@ static int sessionGenerateChangeset(
 
           /* If the buffer is now larger than sessions_strm_chunk_size, pass
           ** its contents to the xOutput() callback. */
-          if( xOutput 
-           && rc==SQLITE_OK 
-           && buf.nBuf>nNoop 
-           && buf.nBuf>sessions_strm_chunk_size 
+          if( xOutput
+           && rc==SQLITE_OK
+           && buf.nBuf>nNoop
+           && buf.nBuf>sessions_strm_chunk_size
           ){
             rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
             nNoop = -1;
@@ -199906,10 +206074,10 @@ static int sessionGenerateChangeset(
 }
 
 /*
-** Obtain a changeset object containing all changes recorded by the 
+** Obtain a changeset object containing all changes recorded by the
 ** session object passed as the first argument.
 **
-** It is the responsibility of the caller to eventually free the buffer 
+** It is the responsibility of the caller to eventually free the buffer
 ** using sqlite3_free().
 */
 SQLITE_API int sqlite3session_changeset(
@@ -199943,10 +206111,10 @@ SQLITE_API int sqlite3session_patchset_strm(
 }
 
 /*
-** Obtain a patchset object containing all changes recorded by the 
+** Obtain a patchset object containing all changes recorded by the
 ** session object passed as the first argument.
 **
-** It is the responsibility of the caller to eventually free the buffer 
+** It is the responsibility of the caller to eventually free the buffer
 ** using sqlite3_free().
 */
 SQLITE_API int sqlite3session_patchset(
@@ -200152,7 +206320,7 @@ static void sessionSkipRecord(
 
 /*
 ** This function sets the value of the sqlite3_value object passed as the
-** first argument to a copy of the string or blob held in the aData[] 
+** first argument to a copy of the string or blob held in the aData[]
 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
 ** error occurs.
 */
@@ -200163,7 +206331,7 @@ static int sessionValueSetStr(
   u8 enc                          /* String encoding (0 for blobs) */
 ){
   /* In theory this code could just pass SQLITE_TRANSIENT as the final
-  ** argument to sqlite3ValueSetStr() and have the copy created 
+  ** argument to sqlite3ValueSetStr() and have the copy created
   ** automatically. But doing so makes it difficult to detect any OOM
   ** error. Hence the code to create the copy externally. */
   u8 *aCopy = sqlite3_malloc(nData+1);
@@ -200264,7 +206432,7 @@ static int sessionReadRecord(
 **   + array of PK flags (1 byte per column),
 **   + table name (nul terminated).
 **
-** This function ensures that all of the above is present in the input 
+** This function ensures that all of the above is present in the input
 ** buffer (i.e. that it can be accessed without any calls to xInput()).
 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
 ** The input pointer is not moved.
@@ -200278,11 +206446,11 @@ static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
   if( rc==SQLITE_OK ){
     nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
     /* The hard upper limit for the number of columns in an SQLite
-    ** database table is, according to sqliteLimit.h, 32676. So 
-    ** consider any table-header that purports to have more than 65536 
-    ** columns to be corrupt. This is convenient because otherwise, 
-    ** if the (nCol>65536) condition below were omitted, a sufficiently 
-    ** large value for nCol may cause nRead to wrap around and become 
+    ** database table is, according to sqliteLimit.h, 32676. So
+    ** consider any table-header that purports to have more than 65536
+    ** columns to be corrupt. This is convenient because otherwise,
+    ** if the (nCol>65536) condition below were omitted, a sufficiently
+    ** large value for nCol may cause nRead to wrap around and become
     ** negative. Leading to a crash. */
     if( nCol<0 || nCol>65536 ){
       rc = SQLITE_CORRUPT_BKPT;
@@ -200347,8 +206515,8 @@ static int sessionChangesetBufferRecord(
 **   + array of PK flags (1 byte per column),
 **   + table name (nul terminated).
 **
-** This function decodes the table-header and populates the p->nCol, 
-** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is 
+** This function decodes the table-header and populates the p->nCol,
+** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
 ** also allocated or resized according to the new value of p->nCol. The
 ** input pointer is left pointing to the byte following the table header.
 **
@@ -200385,8 +206553,13 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
   }
 
   p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
-  p->abPK = (u8*)&p->apValue[p->nCol*2];
-  p->zTab = (char*)&p->abPK[p->nCol];
+  if( p->apValue==0 ){
+    p->abPK = 0;
+    p->zTab = 0;
+  }else{
+    p->abPK = (u8*)&p->apValue[p->nCol*2];
+    p->zTab = p->abPK ? (char*)&p->abPK[p->nCol] : 0;
+  }
   return (p->rc = rc);
 }
 
@@ -200401,9 +206574,9 @@ static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
 ** record is written to *paRec before returning and the number of bytes in
 ** the record to *pnRec.
 **
-** Either way, this function returns SQLITE_ROW if the iterator is 
-** successfully advanced to the next change in the changeset, an SQLite 
-** error code if an error occurs, or SQLITE_DONE if there are no further 
+** Either way, this function returns SQLITE_ROW if the iterator is
+** successfully advanced to the next change in the changeset, an SQLite
+** error code if an error occurs, or SQLITE_DONE if there are no further
 ** changes in the changeset.
 */
 static int sessionChangesetNext(
@@ -200467,7 +206640,7 @@ static int sessionChangesetNext(
     return (p->rc = SQLITE_CORRUPT_BKPT);
   }
 
-  if( paRec ){ 
+  if( paRec ){
     int nVal;                     /* Number of values to buffer */
     if( p->bPatchset==0 && op==SQLITE_UPDATE ){
       nVal = p->nCol * 2;
@@ -200634,7 +206807,7 @@ SQLITE_API int sqlite3changeset_new(
 
 /*
 ** This function may only be called with a changeset iterator that has been
-** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT 
+** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
 **
 ** If successful, *ppValue is set to point to an sqlite3_value structure
@@ -200908,6 +207081,7 @@ struct SessionApplyCtx {
   u8 *abPK;                       /* Boolean array - true if column is in PK */
   int bStat1;                     /* True if table is sqlite_stat1 */
   int bDeferConstraints;          /* True to defer constraints */
+  int bInvertConstraints;         /* Invert when iterating constraints buffer */
   SessionBuffer constraints;      /* Deferred constraints are stored here */
   SessionBuffer rebase;           /* Rebase information (if any) here */
   u8 bRebaseStarted;              /* If table header is already in rebase */
@@ -200942,7 +207116,7 @@ static int sessionDeleteRow(
   SessionBuffer buf = {0, 0, 0};
   int nPk = 0;
 
-  sessionAppendStr(&buf, "DELETE FROM ", &rc);
+  sessionAppendStr(&buf, "DELETE FROM main.", &rc);
   sessionAppendIdent(&buf, zTab, &rc);
   sessionAppendStr(&buf, " WHERE ", &rc);
 
@@ -200984,7 +207158,7 @@ static int sessionDeleteRow(
 }
 
 /*
-** Formulate and prepare a statement to UPDATE a row from database db. 
+** Formulate and prepare a statement to UPDATE a row from database db.
 ** Assuming a table structure like this:
 **
 **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
@@ -200996,7 +207170,7 @@ static int sessionDeleteRow(
 **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
 **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
 **     d = CASE WHEN ?11 THEN ?12 ELSE d END
-**     WHERE a = ?1 AND c = ?7 AND (?13 OR 
+**     WHERE a = ?1 AND c = ?7 AND (?13 OR
 **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
 **     )
 **
@@ -201025,7 +207199,7 @@ static int sessionUpdateRow(
   SessionBuffer buf = {0, 0, 0};
 
   /* Append "UPDATE tbl SET " */
-  sessionAppendStr(&buf, "UPDATE ", &rc);
+  sessionAppendStr(&buf, "UPDATE main.", &rc);
   sessionAppendIdent(&buf, zTab, &rc);
   sessionAppendStr(&buf, " SET ", &rc);
 
@@ -201148,7 +207322,7 @@ static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
 /*
 ** Prepare statements for applying changes to the sqlite_stat1 table.
 ** These are similar to those created by sessionSelectRow(),
-** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for 
+** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
 ** other tables.
 */
 static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
@@ -201182,7 +207356,7 @@ static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
 }
 
 /*
-** A wrapper around sqlite3_bind_value() that detects an extra problem. 
+** A wrapper around sqlite3_bind_value() that detects an extra problem.
 ** See comments in the body of this function for details.
 */
 static int sessionBindValue(
@@ -201205,15 +207379,15 @@ static int sessionBindValue(
 }
 
 /*
-** Iterator pIter must point to an SQLITE_INSERT entry. This function 
+** Iterator pIter must point to an SQLITE_INSERT entry. This function
 ** transfers new.* values from the current iterator entry to statement
 ** pStmt. The table being inserted into has nCol columns.
 **
-** New.* value $i from the iterator is bound to variable ($i+1) of 
+** New.* value $i from the iterator is bound to variable ($i+1) of
 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
-** to an array nCol elements in size. In this case only those values for 
-** which abPK[$i] is true are read from the iterator and bound to the 
+** to an array nCol elements in size. In this case only those values for
+** which abPK[$i] is true are read from the iterator and bound to the
 ** statement.
 **
 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
@@ -201229,8 +207403,8 @@ static int sessionBindRow(
   int rc = SQLITE_OK;
 
   /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
-  ** argument iterator points to a suitable entry. Make sure that xValue 
-  ** is one of these to guarantee that it is safe to ignore the return 
+  ** argument iterator points to a suitable entry. Make sure that xValue
+  ** is one of these to guarantee that it is safe to ignore the return
   ** in the code below. */
   assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
 
@@ -201254,18 +207428,18 @@ static int sessionBindRow(
 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
 ** This function binds the primary key values from the change that changeset
 ** iterator pIter points to to the SELECT and attempts to seek to the table
-** entry. If a row is found, the SELECT statement left pointing at the row 
+** entry. If a row is found, the SELECT statement left pointing at the row
 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
 ** has occured, the statement is reset and SQLITE_OK is returned. If an
 ** error occurs, the statement is reset and an SQLite error code is returned.
 **
-** If this function returns SQLITE_ROW, the caller must eventually reset() 
+** If this function returns SQLITE_ROW, the caller must eventually reset()
 ** statement pSelect. If any other value is returned, the statement does
 ** not require a reset().
 **
 ** If the iterator currently points to an INSERT record, bind values from the
 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
-** UPDATE, bind values from the old.* record. 
+** UPDATE, bind values from the old.* record.
 */
 static int sessionSeekToRow(
   sqlite3 *db,                    /* Database handle */
@@ -201279,7 +207453,7 @@ static int sessionSeekToRow(
   const char *zDummy;             /* Unused */
 
   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
-  rc = sessionBindRow(pIter, 
+  rc = sessionBindRow(pIter,
       op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
       nCol, abPK, pSelect
   );
@@ -201296,7 +207470,7 @@ static int sessionSeekToRow(
 ** This function is called from within sqlite3changeset_apply_v2() when
 ** a conflict is encountered and resolved using conflict resolution
 ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
-** It adds a conflict resolution record to the buffer in 
+** It adds a conflict resolution record to the buffer in
 ** SessionApplyCtx.rebase, which will eventually be returned to the caller
 ** of apply_v2() as the "rebase" buffer.
 **
@@ -201324,7 +207498,7 @@ static int sessionRebaseAdd(
     assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
     assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
 
-    sessionAppendByte(&p->rebase, 
+    sessionAppendByte(&p->rebase,
         (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
         );
     sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
@@ -201372,7 +207546,7 @@ static int sessionRebaseAdd(
 ** is set to non-zero before returning SQLITE_OK.
 **
 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
-** returned. Or, if the conflict handler returns an invalid value, 
+** returned. Or, if the conflict handler returns an invalid value,
 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
 ** this function returns SQLITE_OK.
 */
@@ -201462,16 +207636,16 @@ static int sessionConflictHandler(
 ** to true before returning. In this case the caller will invoke this function
 ** again, this time with pbRetry set to NULL.
 **
-** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is 
+** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
 ** before retrying. In this case the caller attempts to remove the conflicting
-** row before invoking this function again, this time with pbReplace set 
+** row before invoking this function again, this time with pbReplace set
 ** to NULL.
 **
 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
-** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is 
+** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
 ** returned.
 */
 static int sessionApplyOneOp(
@@ -201571,7 +207745,7 @@ static int sessionApplyOneOp(
     assert( op==SQLITE_INSERT );
     if( p->bStat1 ){
       /* Check if there is a conflicting row. For sqlite_stat1, this needs
-      ** to be done using a SELECT, as there is no PRIMARY KEY in the 
+      ** to be done using a SELECT, as there is no PRIMARY KEY in the
       ** database schema to throw an exception if a duplicate is inserted.  */
       rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
       if( rc==SQLITE_ROW ){
@@ -201604,7 +207778,7 @@ static int sessionApplyOneOp(
 ** the conflict handler callback.
 **
 ** The difference between this function and sessionApplyOne() is that this
-** function handles the case where the conflict-handler is invoked and 
+** function handles the case where the conflict-handler is invoked and
 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
 ** retried in some manner.
 */
@@ -201624,7 +207798,7 @@ static int sessionApplyOneWithRetry(
     /* If the bRetry flag is set, the change has not been applied due to an
     ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
     ** a row with the correct PK is present in the db, but one or more other
-    ** fields do not contain the expected values) and the conflict handler 
+    ** fields do not contain the expected values) and the conflict handler
     ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
     ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
     ** the SQLITE_CHANGESET_DATA problem.  */
@@ -201642,7 +207816,7 @@ static int sessionApplyOneWithRetry(
       assert( pIter->op==SQLITE_INSERT );
       rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
       if( rc==SQLITE_OK ){
-        rc = sessionBindRow(pIter, 
+        rc = sessionBindRow(pIter,
             sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
         sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
       }
@@ -201666,7 +207840,7 @@ static int sessionApplyOneWithRetry(
 ** Retry the changes accumulated in the pApply->constraints buffer.
 */
 static int sessionRetryConstraints(
-  sqlite3 *db, 
+  sqlite3 *db,
   int bPatchset,
   const char *zTab,
   SessionApplyCtx *pApply,
@@ -201680,7 +207854,9 @@ static int sessionRetryConstraints(
     SessionBuffer cons = pApply->constraints;
     memset(&pApply->constraints, 0, sizeof(SessionBuffer));
 
-    rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
+    rc = sessionChangesetStart(
+        &pIter2, 0, 0, cons.nBuf, cons.aBuf, pApply->bInvertConstraints
+    );
     if( rc==SQLITE_OK ){
       size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
       int rc2;
@@ -201714,7 +207890,7 @@ static int sessionRetryConstraints(
 
 /*
 ** Argument pIter is a changeset iterator that has been initialized, but
-** not yet passed to sqlite3changeset_next(). This function applies the 
+** not yet passed to sqlite3changeset_next(). This function applies the
 ** changeset to the main database attached to handle "db". The supplied
 ** conflict handler callback is invoked to resolve any conflicts encountered
 ** while applying the change.
@@ -201747,6 +207923,7 @@ static int sessionChangesetApply(
   pIter->in.bNoDiscard = 1;
   memset(&sApply, 0, sizeof(sApply));
   sApply.bRebase = (ppRebase && pnRebase);
+  sApply.bInvertConstraints = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
   sqlite3_mutex_enter(sqlite3_db_mutex(db));
   if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
     rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
@@ -201758,7 +207935,7 @@ static int sessionChangesetApply(
     int nCol;
     int op;
     const char *zNew;
-    
+
     sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
 
     if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
@@ -201771,7 +207948,7 @@ static int sessionChangesetApply(
 
       sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
       sqlite3_finalize(sApply.pDelete);
-      sqlite3_finalize(sApply.pUpdate); 
+      sqlite3_finalize(sApply.pUpdate);
       sqlite3_finalize(sApply.pInsert);
       sqlite3_finalize(sApply.pSelect);
       sApply.db = db;
@@ -201787,7 +207964,7 @@ static int sessionChangesetApply(
       sApply.bRebaseStarted = 0;
       memset(&sApply.constraints, 0, sizeof(SessionBuffer));
 
-      /* If an xFilter() callback was specified, invoke it now. If the 
+      /* If an xFilter() callback was specified, invoke it now. If the
       ** xFilter callback returns zero, skip this table. If it returns
       ** non-zero, proceed. */
       schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
@@ -201811,18 +207988,18 @@ static int sessionChangesetApply(
         for(i=0; i<sApply.nCol; i++){
           if( sApply.abPK[i] ) nMinCol = i+1;
         }
-  
+
         if( sApply.nCol==0 ){
           schemaMismatch = 1;
-          sqlite3_log(SQLITE_SCHEMA, 
+          sqlite3_log(SQLITE_SCHEMA,
               "sqlite3changeset_apply(): no such table: %s", zTab
           );
         }
         else if( sApply.nCol<nCol ){
           schemaMismatch = 1;
-          sqlite3_log(SQLITE_SCHEMA, 
+          sqlite3_log(SQLITE_SCHEMA,
               "sqlite3changeset_apply(): table %s has %d columns, "
-              "expected %d or more", 
+              "expected %d or more",
               zTab, sApply.nCol, nCol
           );
         }
@@ -201915,7 +208092,7 @@ static int sessionChangesetApply(
 }
 
 /*
-** Apply the changeset passed via pChangeset/nChangeset to the main 
+** Apply the changeset passed via pChangeset/nChangeset to the main
 ** database attached to handle "db".
 */
 SQLITE_API int sqlite3changeset_apply_v2(
@@ -201935,7 +208112,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
   void **ppRebase, int *pnRebase,
   int flags
 ){
-  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
+  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
   int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
   int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
   if( rc==SQLITE_OK ){
@@ -201993,7 +208170,7 @@ SQLITE_API int sqlite3changeset_apply_v2_strm(
   void **ppRebase, int *pnRebase,
   int flags
 ){
-  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
+  sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */
   int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
   int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
   if( rc==SQLITE_OK ){
@@ -202122,7 +208299,7 @@ static int sessionChangeMerge(
   }else{
     int op1 = pExist->op;
 
-    /* 
+    /*
     **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
     **   op1=INSERT, op2=UPDATE      ->      INSERT.
     **   op1=INSERT, op2=DELETE      ->      (none)
@@ -202134,7 +208311,7 @@ static int sessionChangeMerge(
     **   op1=DELETE, op2=INSERT      ->      UPDATE.
     **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
     **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
-    */   
+    */
     if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
      || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
      || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
@@ -202273,7 +208450,7 @@ static int sessionChangesetToHash(
 
         /* The new object must be linked on to the end of the list, not
         ** simply added to the start of it. This is to ensure that the
-        ** tables within the output of sqlite3changegroup_output() are in 
+        ** tables within the output of sqlite3changegroup_output() are in
         ** the right order.  */
         for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
         *ppTab = pTab;
@@ -202291,7 +208468,7 @@ static int sessionChangesetToHash(
         pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
     );
 
-    /* Search for existing entry. If found, remove it from the hash table. 
+    /* Search for existing entry. If found, remove it from the hash table.
     ** Code below may link it back in.
     */
     for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
@@ -202309,7 +208486,7 @@ static int sessionChangesetToHash(
       }
     }
 
-    rc = sessionChangeMerge(pTab, bRebase, 
+    rc = sessionChangeMerge(pTab, bRebase,
         pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
     );
     if( rc ) break;
@@ -202330,7 +208507,7 @@ static int sessionChangesetToHash(
 **
 ** If xOutput is not NULL, then the changeset/patchset is returned to the
 ** user via one or more calls to xOutput, as with the other streaming
-** interfaces. 
+** interfaces.
 **
 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
 ** buffer containing the output changeset before this function returns. In
@@ -202355,7 +208532,7 @@ static int sessionChangegroupOutput(
   assert( xOutput==0 || (ppOut==0 && pnOut==0) );
 
   /* Create the serialized output changeset based on the contents of the
-  ** hash tables attached to the SessionTable objects in list p->pList. 
+  ** hash tables attached to the SessionTable objects in list p->pList.
   */
   for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
     int i;
@@ -202458,7 +208635,7 @@ SQLITE_API int sqlite3changegroup_add_strm(
 */
 SQLITE_API int sqlite3changegroup_output_strm(
   sqlite3_changegroup *pGrp,
-  int (*xOutput)(void *pOut, const void *pData, int nData), 
+  int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 ){
   return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
@@ -202474,7 +208651,7 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
   }
 }
 
-/* 
+/*
 ** Combine two changesets together.
 */
 SQLITE_API int sqlite3changeset_concat(
@@ -202541,7 +208718,7 @@ struct sqlite3_rebaser {
 
 /*
 ** Buffers a1 and a2 must both contain a sessions module record nCol
-** fields in size. This function appends an nCol sessions module 
+** fields in size. This function appends an nCol sessions module
 ** record to buffer pBuf that is a copy of a1, except that for
 ** each field that is undefined in a1[], swap in the field from a2[].
 */
@@ -202576,20 +208753,20 @@ static void sessionAppendRecordMerge(
 }
 
 /*
-** This function is called when rebasing a local UPDATE change against one 
+** This function is called when rebasing a local UPDATE change against one
 ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
 ** old.* and new.* records for the change. The rebase buffer (a single
 ** record) is in aChange/nChange. The rebased change is appended to buffer
 ** pBuf.
 **
-** Rebasing the UPDATE involves: 
+** Rebasing the UPDATE involves:
 **
 **   * Removing any changes to fields for which the corresponding field
 **     in the rebase buffer is set to "replaced" (type 0xFF). If this
 **     means the UPDATE change updates no fields, nothing is appended
 **     to the output buffer.
 **
-**   * For each field modified by the local change for which the 
+**   * For each field modified by the local change for which the
 **     corresponding field in the rebase buffer is not "undefined" (0x00)
 **     or "replaced" (0xFF), the old.* value is replaced by the value
 **     in the rebase buffer.
@@ -202648,15 +208825,15 @@ static void sessionAppendPartialUpdate(
 }
 
 /*
-** pIter is configured to iterate through a changeset. This function rebases 
-** that changeset according to the current configuration of the rebaser 
+** pIter is configured to iterate through a changeset. This function rebases
+** that changeset according to the current configuration of the rebaser
 ** object passed as the first argument. If no error occurs and argument xOutput
 ** is not NULL, then the changeset is returned to the caller by invoking
 ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
 ** then (*ppOut) is set to point to a buffer containing the rebased changeset
 ** before this function returns. In this case (*pnOut) is set to the size of
 ** the buffer in bytes.  It is the responsibility of the caller to eventually
-** free the (*ppOut) buffer using sqlite3_free(). 
+** free the (*ppOut) buffer using sqlite3_free().
 **
 ** If an error occurs, an SQLite error code is returned. If ppOut and
 ** pnOut are not NULL, then the two output parameters are set to 0 before
@@ -202734,7 +208911,7 @@ static int sessionRebase(
               sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
               sessionAppendByte(&sOut, pIter->bIndirect, &rc);
               sessionAppendRecordMerge(&sOut, pIter->nCol,
-                  pCsr, nRec-(pCsr-aRec), 
+                  pCsr, nRec-(pCsr-aRec),
                   pChange->aRecord, pChange->nRecord, &rc
               );
             }
@@ -202791,7 +208968,7 @@ static int sessionRebase(
   return rc;
 }
 
-/* 
+/*
 ** Create a new rebaser object.
 */
 SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
@@ -202808,11 +208985,11 @@ SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
   return rc;
 }
 
-/* 
+/*
 ** Call this one or more times to configure a rebaser.
 */
 SQLITE_API int sqlite3rebaser_configure(
-  sqlite3_rebaser *p, 
+  sqlite3_rebaser *p,
   int nRebase, const void *pRebase
 ){
   sqlite3_changeset_iter *pIter = 0;   /* Iterator opened on pData/nData */
@@ -202825,15 +209002,15 @@ SQLITE_API int sqlite3rebaser_configure(
   return rc;
 }
 
-/* 
-** Rebase a changeset according to current rebaser configuration 
+/*
+** Rebase a changeset according to current rebaser configuration
 */
 SQLITE_API int sqlite3rebaser_rebase(
   sqlite3_rebaser *p,
-  int nIn, const void *pIn, 
-  int *pnOut, void **ppOut 
+  int nIn, const void *pIn,
+  int *pnOut, void **ppOut
 ){
-  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  
+  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
   int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
 
   if( rc==SQLITE_OK ){
@@ -202844,8 +209021,8 @@ SQLITE_API int sqlite3rebaser_rebase(
   return rc;
 }
 
-/* 
-** Rebase a changeset according to current rebaser configuration 
+/*
+** Rebase a changeset according to current rebaser configuration
 */
 SQLITE_API int sqlite3rebaser_rebase_strm(
   sqlite3_rebaser *p,
@@ -202854,7 +209031,7 @@ SQLITE_API int sqlite3rebaser_rebase_strm(
   int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 ){
-  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */  
+  sqlite3_changeset_iter *pIter = 0;   /* Iterator to skip through input */
   int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
 
   if( rc==SQLITE_OK ){
@@ -202865,8 +209042,8 @@ SQLITE_API int sqlite3rebaser_rebase_strm(
   return rc;
 }
 
-/* 
-** Destroy a rebaser object 
+/*
+** Destroy a rebaser object
 */
 SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
   if( p ){
@@ -202875,7 +209052,7 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
   }
 }
 
-/* 
+/*
 ** Global configuration
 */
 SQLITE_API int sqlite3session_config(int op, void *pArg){
@@ -202902,9 +209079,9 @@ SQLITE_API int sqlite3session_config(int op, void *pArg){
 /************** Begin file fts5.c ********************************************/
 
 
-#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) 
+#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
 
-#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
+#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
 # define NDEBUG 1
 #endif
 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
@@ -202923,7 +209100,7 @@ SQLITE_API int sqlite3session_config(int op, void *pArg){
 **
 ******************************************************************************
 **
-** Interfaces to extend FTS5. Using the interfaces defined in this file, 
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
 ** FTS5 may be extended with:
 **
 **     * custom tokenizers, and
@@ -202968,19 +209145,19 @@ struct Fts5PhraseIter {
 ** EXTENSION API FUNCTIONS
 **
 ** xUserData(pFts):
-**   Return a copy of the context pointer the extension function was 
+**   Return a copy of the context pointer the extension function was
 **   registered with.
 **
 ** xColumnTotalSize(pFts, iCol, pnToken):
 **   If parameter iCol is less than zero, set output variable *pnToken
 **   to the total number of tokens in the FTS5 table. Or, if iCol is
 **   non-negative but less than the number of columns in the table, return
-**   the total number of tokens in column iCol, considering all rows in 
+**   the total number of tokens in column iCol, considering all rows in
 **   the FTS5 table.
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 ** xColumnCount(pFts):
@@ -202994,7 +209171,7 @@ struct Fts5PhraseIter {
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 **   This function may be quite inefficient if used with an FTS5 table
@@ -203021,8 +209198,8 @@ struct Fts5PhraseIter {
 **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always returns 0.
 **
 ** xInst:
@@ -203037,7 +209214,7 @@ struct Fts5PhraseIter {
 **   code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. 
+**   "detail=none" or "detail=column" option.
 **
 ** xRowid:
 **   Returns the rowid of the current row.
@@ -203053,11 +209230,11 @@ struct Fts5PhraseIter {
 **
 **   with $p set to a phrase equivalent to the phrase iPhrase of the
 **   current query is executed. Any column filter that applies to
-**   phrase iPhrase of the current query is included in $p. For each 
-**   row visited, the callback function passed as the fourth argument 
-**   is invoked. The context and API objects passed to the callback 
+**   phrase iPhrase of the current query is included in $p. For each
+**   row visited, the callback function passed as the fourth argument
+**   is invoked. The context and API objects passed to the callback
 **   function may be used to access the properties of each matched row.
-**   Invoking Api.xUserData() returns a copy of the pointer passed as 
+**   Invoking Api.xUserData() returns a copy of the pointer passed as
 **   the third argument to pUserData.
 **
 **   If the callback function returns any value other than SQLITE_OK, the
@@ -203072,14 +209249,14 @@ struct Fts5PhraseIter {
 **
 ** xSetAuxdata(pFts5, pAux, xDelete)
 **
-**   Save the pointer passed as the second argument as the extension function
+**   Save the pointer passed as the second argument as the extension function's
 **   "auxiliary data". The pointer may then be retrieved by the current or any
 **   future invocation of the same fts5 extension function made as part of
 **   the same MATCH query using the xGetAuxdata() API.
 **
 **   Each extension function is allocated a single auxiliary data slot for
-**   each FTS query (MATCH expression). If the extension function is invoked 
-**   more than once for a single FTS query, then all invocations share a 
+**   each FTS query (MATCH expression). If the extension function is invoked
+**   more than once for a single FTS query, then all invocations share a
 **   single auxiliary data context.
 **
 **   If there is already an auxiliary data pointer when this function is
@@ -203098,7 +209275,7 @@ struct Fts5PhraseIter {
 **
 ** xGetAuxdata(pFts5, bClear)
 **
-**   Returns the current auxiliary data pointer for the fts5 extension 
+**   Returns the current auxiliary data pointer for the fts5 extension
 **   function. See the xSetAuxdata() method for details.
 **
 **   If the bClear argument is non-zero, then the auxiliary data is cleared
@@ -203118,7 +209295,7 @@ struct Fts5PhraseIter {
 **   method, to iterate through all instances of a single query phrase within
 **   the current row. This is the same information as is accessible via the
 **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
-**   to use, this API may be faster under some circumstances. To iterate 
+**   to use, this API may be faster under some circumstances. To iterate
 **   through instances of phrase iPhrase, use the following code:
 **
 **       Fts5PhraseIter iter;
@@ -203136,8 +209313,8 @@ struct Fts5PhraseIter {
 **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always iterates
 **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
 **
@@ -203161,16 +209338,16 @@ struct Fts5PhraseIter {
 **       }
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" option. If the FTS5 table is created with either 
-**   "detail=none" "content=" option (i.e. if it is a contentless table), 
-**   then this API always iterates through an empty set (all calls to 
+**   "detail=none" option. If the FTS5 table is created with either
+**   "detail=none" "content=" option (i.e. if it is a contentless table),
+**   then this API always iterates through an empty set (all calls to
 **   xPhraseFirstColumn() set iCol to -1).
 **
 **   The information accessed using this API and its companion
 **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
 **   (or xInst/xInstCount). The chief advantage of this API is that it is
 **   significantly more efficient than those alternatives when used with
-**   "detail=column" tables.  
+**   "detail=column" tables.
 **
 ** xPhraseNextColumn()
 **   See xPhraseFirstColumn above.
@@ -203184,7 +209361,7 @@ struct Fts5ExtensionApi {
   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
 
-  int (*xTokenize)(Fts5Context*, 
+  int (*xTokenize)(Fts5Context*,
     const char *pText, int nText, /* Text to tokenize */
     void *pCtx,                   /* Context passed to xToken() */
     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
@@ -203213,15 +209390,15 @@ struct Fts5ExtensionApi {
   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
 };
 
-/* 
+/*
 ** CUSTOM AUXILIARY FUNCTIONS
 *************************************************************************/
 
 /*************************************************************************
 ** CUSTOM TOKENIZERS
 **
-** Applications may also register custom tokenizer types. A tokenizer 
-** is registered by providing fts5 with a populated instance of the 
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
 ** following structure. All structure methods must be defined, setting
 ** any member of the fts5_tokenizer struct to NULL leads to undefined
 ** behaviour. The structure methods are expected to function as follows:
@@ -203232,16 +209409,16 @@ struct Fts5ExtensionApi {
 **
 **   The first argument passed to this function is a copy of the (void*)
 **   pointer provided by the application when the fts5_tokenizer object
-**   was registered with FTS5 (the third argument to xCreateTokenizer()). 
+**   was registered with FTS5 (the third argument to xCreateTokenizer()).
 **   The second and third arguments are an array of nul-terminated strings
 **   containing the tokenizer arguments, if any, specified following the
 **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
 **   to create the FTS5 table.
 **
-**   The final argument is an output variable. If successful, (*ppOut) 
+**   The final argument is an output variable. If successful, (*ppOut)
 **   should be set to point to the new tokenizer handle and SQLITE_OK
 **   returned. If an error occurs, some value other than SQLITE_OK should
-**   be returned. In this case, fts5 assumes that the final value of *ppOut 
+**   be returned. In this case, fts5 assumes that the final value of *ppOut
 **   is undefined.
 **
 ** xDelete:
@@ -203250,7 +209427,7 @@ struct Fts5ExtensionApi {
 **   be invoked exactly once for each successful call to xCreate().
 **
 ** xTokenize:
-**   This function is expected to tokenize the nText byte string indicated 
+**   This function is expected to tokenize the nText byte string indicated
 **   by argument pText. pText may or may not be nul-terminated. The first
 **   argument passed to this function is a pointer to an Fts5Tokenizer object
 **   returned by an earlier call to xCreate().
@@ -203264,8 +209441,8 @@ struct Fts5ExtensionApi {
 **            determine the set of tokens to add to (or delete from) the
 **            FTS index.
 **
-**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
-**            against the FTS index. The tokenizer is being called to tokenize 
+**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+**            against the FTS index. The tokenizer is being called to tokenize
 **            a bareword or quoted string specified as part of the query.
 **
 **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
@@ -203273,10 +209450,10 @@ struct Fts5ExtensionApi {
 **            followed by a "*" character, indicating that the last token
 **            returned by the tokenizer will be treated as a token prefix.
 **
-**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
+**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
 **            satisfy an fts5_api.xTokenize() request made by an auxiliary
 **            function. Or an fts5_api.xColumnSize() request made by the same
-**            on a columnsize=0 database.  
+**            on a columnsize=0 database.
 **   </ul>
 **
 **   For each token in the input string, the supplied callback xToken() must
@@ -203288,10 +209465,10 @@ struct Fts5ExtensionApi {
 **   which the token is derived within the input.
 **
 **   The second argument passed to the xToken() callback ("tflags") should
-**   normally be set to 0. The exception is if the tokenizer supports 
+**   normally be set to 0. The exception is if the tokenizer supports
 **   synonyms. In this case see the discussion below for details.
 **
-**   FTS5 assumes the xToken() callback is invoked for each token in the 
+**   FTS5 assumes the xToken() callback is invoked for each token in the
 **   order that they occur within the input text.
 **
 **   If an xToken() callback returns any value other than SQLITE_OK, then
@@ -203305,7 +209482,7 @@ struct Fts5ExtensionApi {
 ** SYNONYM SUPPORT
 **
 **   Custom tokenizers may also support synonyms. Consider a case in which a
-**   user wishes to query for a phrase such as "first place". Using the 
+**   user wishes to query for a phrase such as "first place". Using the
 **   built-in tokenizers, the FTS5 query 'first + place' will match instances
 **   of "first place" within the document set, but not alternative forms
 **   such as "1st place". In some applications, it would be better to match
@@ -203314,8 +209491,8 @@ struct Fts5ExtensionApi {
 **
 **   There are several ways to approach this in FTS5:
 **
-**   <ol><li> By mapping all synonyms to a single token. In this case, the 
-**            In the above example, this means that the tokenizer returns the
+**   <ol><li> By mapping all synonyms to a single token. In this case, using
+**            the above example, this means that the tokenizer returns the
 **            same token for inputs "first" and "1st". Say that token is in
 **            fact "first", so that when the user inserts the document "I won
 **            1st place" entries are added to the index for tokens "i", "won",
@@ -203325,34 +209502,34 @@ struct Fts5ExtensionApi {
 **
 **       <li> By querying the index for all synonyms of each query term
 **            separately. In this case, when tokenizing query text, the
-**            tokenizer may provide multiple synonyms for a single term 
-**            within the document. FTS5 then queries the index for each 
+**            tokenizer may provide multiple synonyms for a single term
+**            within the document. FTS5 then queries the index for each
 **            synonym individually. For example, faced with the query:
 **
 **   <codeblock>
 **     ... MATCH 'first place'</codeblock>
 **
 **            the tokenizer offers both "1st" and "first" as synonyms for the
-**            first token in the MATCH query and FTS5 effectively runs a query 
+**            first token in the MATCH query and FTS5 effectively runs a query
 **            similar to:
 **
 **   <codeblock>
 **     ... MATCH '(first OR 1st) place'</codeblock>
 **
 **            except that, for the purposes of auxiliary functions, the query
-**            still appears to contain just two phrases - "(first OR 1st)" 
+**            still appears to contain just two phrases - "(first OR 1st)"
 **            being treated as a single phrase.
 **
 **       <li> By adding multiple synonyms for a single term to the FTS index.
 **            Using this method, when tokenizing document text, the tokenizer
-**            provides multiple synonyms for each token. So that when a 
+**            provides multiple synonyms for each token. So that when a
 **            document such as "I won first place" is tokenized, entries are
 **            added to the FTS index for "i", "won", "first", "1st" and
 **            "place".
 **
 **            This way, even if the tokenizer does not provide synonyms
 **            when tokenizing query text (it should not - to do so would be
-**            inefficient), it doesn't matter if the user queries for 
+**            inefficient), it doesn't matter if the user queries for
 **            'first + place' or '1st + place', as there are entries in the
 **            FTS index corresponding to both forms of the first token.
 **   </ol>
@@ -203373,11 +209550,11 @@ struct Fts5ExtensionApi {
 **
 **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
 **   xToken() is called. Multiple synonyms may be specified for a single token
-**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
+**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
 **   There is no limit to the number of synonyms that may be provided for a
 **   single token.
 **
-**   In many cases, method (1) above is the best approach. It does not add 
+**   In many cases, method (1) above is the best approach. It does not add
 **   extra data to the FTS index or require FTS5 to query for multiple terms,
 **   so it is efficient in terms of disk space and query speed. However, it
 **   does not support prefix queries very well. If, as suggested above, the
@@ -203389,18 +209566,18 @@ struct Fts5ExtensionApi {
 **   will not match documents that contain the token "1st" (as the tokenizer
 **   will probably not map "1s" to any prefix of "first").
 **
-**   For full prefix support, method (3) may be preferred. In this case, 
+**   For full prefix support, method (3) may be preferred. In this case,
 **   because the index contains entries for both "first" and "1st", prefix
 **   queries such as 'fi*' or '1s*' will match correctly. However, because
 **   extra entries are added to the FTS index, this method uses more space
 **   within the database.
 **
 **   Method (2) offers a midpoint between (1) and (3). Using this method,
-**   a query such as '1s*' will match documents that contain the literal 
+**   a query such as '1s*' will match documents that contain the literal
 **   token "1st", but not "first" (assuming the tokenizer is not able to
 **   provide synonyms for prefixes). However, a non-prefix query like '1st'
 **   will match against "1st" and "first". This method does not require
-**   extra disk space, as no extra entries are added to the FTS index. 
+**   extra disk space, as no extra entries are added to the FTS index.
 **   On the other hand, it may require more CPU cycles to run MATCH queries,
 **   as separate queries of the FTS index are required for each synonym.
 **
@@ -203414,10 +209591,10 @@ typedef struct fts5_tokenizer fts5_tokenizer;
 struct fts5_tokenizer {
   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
   void (*xDelete)(Fts5Tokenizer*);
-  int (*xTokenize)(Fts5Tokenizer*, 
+  int (*xTokenize)(Fts5Tokenizer*,
       void *pCtx,
       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
-      const char *pText, int nText, 
+      const char *pText, int nText,
       int (*xToken)(
         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
         int tflags,         /* Mask of FTS5_TOKEN_* flags */
@@ -203542,7 +209719,7 @@ typedef sqlite3_uint64 u64;
 
 #endif
 
-/* Truncate very long tokens to this many bytes. Hard limit is 
+/* Truncate very long tokens to this many bytes. Hard limit is
 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
 ** field that occurs at the start of each leaf page (see fts5_index.c). */
 #define FTS5_MAX_TOKEN_SIZE 32768
@@ -203554,6 +209731,11 @@ typedef sqlite3_uint64 u64;
 */
 #define FTS5_MAX_PREFIX_INDEXES 31
 
+/*
+** Maximum segments permitted in a single index
+*/
+#define FTS5_MAX_SEGMENT 2000
+
 #define FTS5_DEFAULT_NEARDIST 10
 #define FTS5_DEFAULT_RANK     "bm25"
 
@@ -203570,7 +209752,7 @@ static int sqlite3Fts5Corrupt(void);
 
 /*
 ** The assert_nc() macro is similar to the assert() macro, except that it
-** is used for assert() conditions that are true only if it can be 
+** is used for assert() conditions that are true only if it can be
 ** guranteed that the database is not corrupt.
 */
 #ifdef SQLITE_DEBUG
@@ -203599,7 +209781,7 @@ SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
 typedef struct Fts5Global Fts5Global;
 typedef struct Fts5Colset Fts5Colset;
 
-/* If a NEAR() clump or phrase may only match a specific set of columns, 
+/* If a NEAR() clump or phrase may only match a specific set of columns,
 ** then an object of the following type is used to record the set of columns.
 ** Each entry in the aiCol[] array is a column that may be matched.
 **
@@ -203627,20 +209809,20 @@ typedef struct Fts5Config Fts5Config;
 **
 ** nAutomerge:
 **   The minimum number of segments that an auto-merge operation should
-**   attempt to merge together. A value of 1 sets the object to use the 
+**   attempt to merge together. A value of 1 sets the object to use the
 **   compile time default. Zero disables auto-merge altogether.
 **
 ** zContent:
 **
 ** zContentRowid:
-**   The value of the content_rowid= option, if one was specified. Or 
+**   The value of the content_rowid= option, if one was specified. Or
 **   the string "rowid" otherwise. This text is not quoted - if it is
 **   used as part of an SQL statement it needs to be quoted appropriately.
 **
 ** zContentExprlist:
 **
 ** pzErrmsg:
-**   This exists in order to allow the fts5_index.c module to return a 
+**   This exists in order to allow the fts5_index.c module to return a
 **   decent error message if it encounters a file-format version it does
 **   not understand.
 **
@@ -203664,14 +209846,15 @@ struct Fts5Config {
   int nPrefix;                    /* Number of prefix indexes */
   int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
   int eContent;                   /* An FTS5_CONTENT value */
-  char *zContent;                 /* content table */ 
-  char *zContentRowid;            /* "content_rowid=" option value */ 
+  char *zContent;                 /* content table */
+  char *zContentRowid;            /* "content_rowid=" option value */
   int bColumnsize;                /* "columnsize=" option value (dflt==1) */
   int eDetail;                    /* FTS5_DETAIL_XXX value */
   char *zContentExprlist;
   Fts5Tokenizer *pTok;
   fts5_tokenizer *pTokApi;
   int bLock;                      /* True when table is preparing statement */
+  int ePattern;                   /* FTS_PATTERN_XXX constant */
 
   /* Values loaded from the %_config table */
   int iCookie;                    /* Incremented when %_config is modified */
@@ -203692,17 +209875,19 @@ struct Fts5Config {
 };
 
 /* Current expected value of %_config table 'version' field */
-#define FTS5_CURRENT_VERSION 4
+#define FTS5_CURRENT_VERSION  4
 
 #define FTS5_CONTENT_NORMAL   0
 #define FTS5_CONTENT_NONE     1
 #define FTS5_CONTENT_EXTERNAL 2
 
-#define FTS5_DETAIL_FULL    0
-#define FTS5_DETAIL_NONE    1
-#define FTS5_DETAIL_COLUMNS 2
-
+#define FTS5_DETAIL_FULL      0
+#define FTS5_DETAIL_NONE      1
+#define FTS5_DETAIL_COLUMNS   2
 
+#define FTS5_PATTERN_NONE     0
+#define FTS5_PATTERN_LIKE     65  /* matches SQLITE_INDEX_CONSTRAINT_LIKE */
+#define FTS5_PATTERN_GLOB     66  /* matches SQLITE_INDEX_CONSTRAINT_GLOB */
 
 static int sqlite3Fts5ConfigParse(
     Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
@@ -203867,27 +210052,27 @@ static int sqlite3Fts5IndexClose(Fts5Index *p);
 ** Return a simple checksum value based on the arguments.
 */
 static u64 sqlite3Fts5IndexEntryCksum(
-  i64 iRowid, 
-  int iCol, 
-  int iPos, 
+  i64 iRowid,
+  int iCol,
+  int iPos,
   int iIdx,
   const char *pTerm,
   int nTerm
 );
 
 /*
-** Argument p points to a buffer containing utf-8 text that is n bytes in 
+** Argument p points to a buffer containing utf-8 text that is n bytes in
 ** size. Return the number of bytes in the nChar character prefix of the
 ** buffer, or 0 if there are less than nChar characters in total.
 */
 static int sqlite3Fts5IndexCharlenToBytelen(
-  const char *p, 
-  int nByte, 
+  const char *p,
+  int nByte,
   int nChar
 );
 
 /*
-** Open a new iterator to iterate though all rowids that match the 
+** Open a new iterator to iterate though all rowids that match the
 ** specified token or token prefix.
 */
 static int sqlite3Fts5IndexQuery(
@@ -203911,6 +210096,11 @@ static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
 static void sqlite3Fts5IterClose(Fts5IndexIter*);
 
 /*
+** Close the reader blob handle, if it is open.
+*/
+static void sqlite3Fts5IndexCloseReader(Fts5Index*);
+
+/*
 ** This interface is used by the fts5vocab module.
 */
 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
@@ -203918,7 +210108,7 @@ static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
 
 
 /*
-** Insert or remove data to or from the index. Each time a document is 
+** Insert or remove data to or from the index. Each time a document is
 ** added to or removed from the index, this function is called one or more
 ** times.
 **
@@ -203953,7 +210143,7 @@ static int sqlite3Fts5IndexSync(Fts5Index *p);
 /*
 ** Discard any data stored in the in-memory hash tables. Do not write it
 ** to the database. Additionally, assume that the contents of the %_data
-** table may have changed on disk. So any in-memory caches of %_data 
+** table may have changed on disk. So any in-memory caches of %_data
 ** records must be invalidated.
 */
 static int sqlite3Fts5IndexRollback(Fts5Index *p);
@@ -203967,18 +210157,18 @@ static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
 /*
 ** Functions called by the storage module as part of integrity-check.
 */
-static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
+static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum, int bUseCksum);
 
-/* 
-** Called during virtual module initialization to register UDF 
-** fts5_decode() with SQLite 
+/*
+** Called during virtual module initialization to register UDF
+** fts5_decode() with SQLite
 */
 static int sqlite3Fts5IndexInit(sqlite3*);
 
 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
 
 /*
-** Return the total number of entries read from the %_data table by 
+** Return the total number of entries read from the %_data table by
 ** this connection since it was created.
 */
 static int sqlite3Fts5IndexReads(Fts5Index *p);
@@ -203995,7 +210185,7 @@ static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
 **************************************************************************/
 
 /**************************************************************************
-** Interface to code in fts5_varint.c. 
+** Interface to code in fts5_varint.c.
 */
 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
 static int sqlite3Fts5GetVarintLen(u32 iVal);
@@ -204020,7 +210210,7 @@ static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
 
 
 /**************************************************************************
-** Interface to code in fts5_main.c. 
+** Interface to code in fts5_main.c.
 */
 
 /*
@@ -204034,11 +210224,10 @@ struct Fts5Table {
 };
 
 static int sqlite3Fts5GetTokenizer(
-  Fts5Global*, 
+  Fts5Global*,
   const char **azArg,
   int nArg,
-  Fts5Tokenizer**,
-  fts5_tokenizer**,
+  Fts5Config*,
   char **pzErr
 );
 
@@ -204051,7 +210240,7 @@ static int sqlite3Fts5FlushToDisk(Fts5Table*);
 **************************************************************************/
 
 /**************************************************************************
-** Interface to code in fts5_hash.c. 
+** Interface to code in fts5_hash.c.
 */
 typedef struct Fts5Hash Fts5Hash;
 
@@ -204101,7 +210290,7 @@ static void sqlite3Fts5HashScanEntry(Fts5Hash *,
 **************************************************************************/
 
 /**************************************************************************
-** Interface to code in fts5_storage.c. fts5_storage.c contains contains 
+** Interface to code in fts5_storage.c. fts5_storage.c contains contains
 ** code to access the data stored in the %_content and %_docsize tables.
 */
 
@@ -204122,7 +210311,7 @@ static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
 
-static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
+static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg);
 
 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
@@ -204150,7 +210339,7 @@ static int sqlite3Fts5StorageReset(Fts5Storage *p);
 
 
 /**************************************************************************
-** Interface to code in fts5_expr.c. 
+** Interface to code in fts5_expr.c.
 */
 typedef struct Fts5Expr Fts5Expr;
 typedef struct Fts5ExprNode Fts5ExprNode;
@@ -204166,12 +210355,20 @@ struct Fts5Token {
 
 /* Parse a MATCH expression. */
 static int sqlite3Fts5ExprNew(
-  Fts5Config *pConfig, 
+  Fts5Config *pConfig,
+  int bPhraseToAnd,
   int iCol,                       /* Column on LHS of MATCH operator */
   const char *zExpr,
-  Fts5Expr **ppNew, 
+  Fts5Expr **ppNew,
   char **pzErr
 );
+static int sqlite3Fts5ExprPattern(
+  Fts5Config *pConfig,
+  int bGlob,
+  int iCol,
+  const char *zText,
+  Fts5Expr **pp
+);
 
 /*
 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
@@ -204230,8 +210427,8 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
 );
 
 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
-  Fts5Parse *pParse, 
-  Fts5ExprPhrase *pPhrase, 
+  Fts5Parse *pParse,
+  Fts5ExprPhrase *pPhrase,
   Fts5Token *pToken,
   int bPrefix
 );
@@ -204239,14 +210436,14 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
 static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
 
 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
-  Fts5Parse*, 
+  Fts5Parse*,
   Fts5ExprNearset*,
-  Fts5ExprPhrase* 
+  Fts5ExprPhrase*
 );
 
 static Fts5Colset *sqlite3Fts5ParseColset(
-  Fts5Parse*, 
-  Fts5Colset*, 
+  Fts5Parse*,
+  Fts5Colset*,
   Fts5Token *
 );
 
@@ -204267,7 +210464,7 @@ static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
 
 
 /**************************************************************************
-** Interface to code in fts5_aux.c. 
+** Interface to code in fts5_aux.c.
 */
 
 static int sqlite3Fts5AuxInit(fts5_api*);
@@ -204276,16 +210473,20 @@ static int sqlite3Fts5AuxInit(fts5_api*);
 **************************************************************************/
 
 /**************************************************************************
-** Interface to code in fts5_tokenizer.c. 
+** Interface to code in fts5_tokenizer.c.
 */
 
 static int sqlite3Fts5TokenizerInit(fts5_api*);
+static int sqlite3Fts5TokenizerPattern(
+    int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
+    Fts5Tokenizer *pTok
+);
 /*
 ** End of interface to code in fts5_tokenizer.c.
 **************************************************************************/
 
 /**************************************************************************
-** Interface to code in fts5_vocab.c. 
+** Interface to code in fts5_vocab.c.
 */
 
 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
@@ -204296,7 +210497,7 @@ static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
 
 
 /**************************************************************************
-** Interface to automatically generated code in fts5_unicode2.c. 
+** Interface to automatically generated code in fts5_unicode2.c.
 */
 SQLITE_PRIVATE int sqlite3Fts5UnicodeIsdiacritic(int c);
 SQLITE_PRIVATE int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
@@ -204326,6 +210527,8 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*);
 #define FTS5_PLUS                            14
 #define FTS5_STAR                            15
 
+/* This file is automatically generated by Lemon from input grammar
+** source file "fts5parse.y". */
 /*
 ** 2000-05-29
 **
@@ -204350,8 +210553,6 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*);
 ** The following is the concatenation of all %include directives from the
 ** input grammar file:
 */
-/* #include <stdio.h> */
-/* #include <assert.h> */
 /************ Begin %include sections from the grammar ************************/
 
 /* #include "fts5Int.h" */
@@ -204381,11 +210582,26 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*);
 #define fts5YYMALLOCARGTYPE  size_t
 
 /**************** End of %include directives **********************************/
-/* These constants specify the various numeric values for terminal symbols
-** in a format understandable to "makeheaders".  This section is blank unless
-** "lemon" is run with the "-m" command-line option.
-***************** Begin makeheaders token definitions *************************/
-/**************** End makeheaders token definitions ***************************/
+/* These constants specify the various numeric values for terminal symbols.
+***************** Begin token definitions *************************************/
+#ifndef FTS5_OR
+#define FTS5_OR                              1
+#define FTS5_AND                             2
+#define FTS5_NOT                             3
+#define FTS5_TERM                            4
+#define FTS5_COLON                           5
+#define FTS5_MINUS                           6
+#define FTS5_LCP                             7
+#define FTS5_RCP                             8
+#define FTS5_STRING                          9
+#define FTS5_LP                             10
+#define FTS5_RP                             11
+#define FTS5_CARET                          12
+#define FTS5_COMMA                          13
+#define FTS5_PLUS                           14
+#define FTS5_STAR                           15
+#endif
+/**************** End token definitions ***************************************/
 
 /* The next sections is a series of control #defines.
 ** various aspects of the generated parser.
@@ -204410,7 +210626,7 @@ static void sqlite3Fts5UnicodeAscii(u8*, u8*);
 **                       the minor type might be the name of the identifier.
 **                       Each non-terminal can have a different minor type.
 **                       Terminal symbols all have the same minor type, though.
-**                       This macros defines the minor type for terminal 
+**                       This macros defines the minor type for terminal
 **                       symbols.
 **    fts5YYMINORTYPE        is the data type used for all minor types.
 **                       This is typically a union of many types, one of
@@ -204470,6 +210686,7 @@ typedef union {
 #define sqlite3Fts5ParserCTX_STORE
 #define fts5YYNSTATE             35
 #define fts5YYNRULE              28
+#define fts5YYNRULE_WITH_ACTION  28
 #define fts5YYNFTS5TOKEN             16
 #define fts5YY_MAX_SHIFT         34
 #define fts5YY_MIN_SHIFTREDUCE   52
@@ -204498,7 +210715,7 @@ typedef union {
 /* Next are the tables used to determine what action to take based on the
 ** current state and lookahead token.  These tables are used to implement
 ** functions that take a state number and lookahead value and return an
-** action integer.  
+** action integer.
 **
 ** Suppose the action integer is N.  Then the action is determined as
 ** follows
@@ -204598,9 +210815,9 @@ static const fts5YYACTIONTYPE fts5yy_default[] = {
 };
 /********** End of lemon-generated parsing tables *****************************/
 
-/* The next table maps tokens (terminal symbols) into fallback tokens.  
+/* The next table maps tokens (terminal symbols) into fallback tokens.
 ** If a construct like the following:
-** 
+**
 **      %fallback ID X Y Z.
 **
 ** appears in the grammar, then ID becomes a fallback token for X, Y,
@@ -204667,15 +210884,16 @@ typedef struct fts5yyParser fts5yyParser;
 
 #ifndef NDEBUG
 /* #include <stdio.h> */
+/* #include <assert.h> */
 static FILE *fts5yyTraceFILE = 0;
 static char *fts5yyTracePrompt = 0;
 #endif /* NDEBUG */
 
 #ifndef NDEBUG
-/* 
+/*
 ** Turn parser tracing on by giving a stream to which to write the trace
 ** and a prompt to preface each trace message.  Tracing is turned off
-** by making either argument NULL 
+** by making either argument NULL
 **
 ** Inputs:
 ** <ul>
@@ -204700,7 +210918,7 @@ static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
 #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
 /* For tracing shifts, the names of all terminals and nonterminals
 ** are required.  The following table supplies these names */
-static const char *const fts5yyTokenName[] = { 
+static const char *const fts5yyTokenName[] = {
   /*    0 */ "$",
   /*    1 */ "OR",
   /*    2 */ "AND",
@@ -204796,7 +211014,7 @@ static int fts5yyGrowStack(fts5yyParser *p){
 #endif
     p->fts5yystksz = newSize;
   }
-  return pNew==0; 
+  return pNew==0;
 }
 #endif
 
@@ -204838,7 +211056,7 @@ static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PD
 }
 
 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
-/* 
+/*
 ** This function allocates a new parser.
 ** The only argument is a pointer to a function which works like
 ** malloc.
@@ -204865,7 +211083,7 @@ static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sql
 /* The following function deletes the "minor type" or semantic value
 ** associated with a symbol.  The symbol can be either a terminal
 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
-** a pointer to the value to be deleted.  The code used to do the 
+** a pointer to the value to be deleted.  The code used to do the
 ** deletions is derived from the %destructor and/or %token_destructor
 ** directives of the input grammar.
 */
@@ -204880,7 +211098,7 @@ static void fts5yy_destructor(
     /* Here is inserted the actions which take place when a
     ** terminal or non-terminal is destroyed.  This can happen
     ** when the symbol is popped from the stack during a
-    ** reduce or during error processing or when a parser is 
+    ** reduce or during error processing or when a parser is
     ** being destroyed before it is finished parsing.
     **
     ** Note: during a reduce, the only symbols destroyed are those
@@ -204890,31 +211108,31 @@ static void fts5yy_destructor(
 /********* Begin destructor definitions ***************************************/
     case 16: /* input */
 {
- (void)pParse; 
+ (void)pParse;
 }
       break;
     case 17: /* expr */
     case 18: /* cnearset */
     case 19: /* exprlist */
 {
- sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24)); 
+ sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
 }
       break;
     case 20: /* colset */
     case 21: /* colsetlist */
 {
- sqlite3_free((fts5yypminor->fts5yy11)); 
+ sqlite3_free((fts5yypminor->fts5yy11));
 }
       break;
     case 22: /* nearset */
     case 23: /* nearphrases */
 {
- sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46)); 
+ sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
 }
       break;
     case 24: /* phrase */
 {
- sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53)); 
+ sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
 }
       break;
 /********* End destructor definitions *****************************************/
@@ -204955,7 +211173,7 @@ static void sqlite3Fts5ParserFinalize(void *p){
 }
 
 #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
-/* 
+/*
 ** Deallocate and destroy a parser.  Destructors are called for
 ** all stack elements before shutting the parser down.
 **
@@ -205081,7 +211299,7 @@ static fts5YYACTIONTYPE fts5yy_find_shift_action(
 #endif /* fts5YYWILDCARD */
       return fts5yy_default[stateno];
     }else{
-      assert( i>=0 && i<sizeof(fts5yy_action)/sizeof(fts5yy_action[0]) );
+      assert( i>=0 && i<(int)(sizeof(fts5yy_action)/sizeof(fts5yy_action[0])) );
       return fts5yy_action[i];
     }
   }while(1);
@@ -205177,7 +211395,7 @@ static void fts5yy_shift(
     assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
   }
 #endif
-#if fts5YYSTACKDEPTH>0 
+#if fts5YYSTACKDEPTH>0
   if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
     fts5yypParser->fts5yytos--;
     fts5yyStackOverflow(fts5yypParser);
@@ -205295,16 +211513,20 @@ static fts5YYACTIONTYPE fts5yy_reduce(
   (void)fts5yyLookahead;
   (void)fts5yyLookaheadToken;
   fts5yymsp = fts5yypParser->fts5yytos;
+  assert( fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) );
 #ifndef NDEBUG
-  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
+  if( fts5yyTraceFILE ){
     fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
     if( fts5yysize ){
-      fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
+      fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
         fts5yyTracePrompt,
-        fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
+        fts5yyruleno, fts5yyRuleName[fts5yyruleno],
+        fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action",
+        fts5yymsp[fts5yysize].stateno);
     }else{
-      fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
-        fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
+      fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s.\n",
+        fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno],
+        fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action");
     }
   }
 #endif /* NDEBUG */
@@ -205319,7 +211541,7 @@ static fts5YYACTIONTYPE fts5yy_reduce(
       assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
     }
 #endif
-#if fts5YYSTACKDEPTH>0 
+#if fts5YYSTACKDEPTH>0
     if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
       fts5yyStackOverflow(fts5yypParser);
       /* The call to fts5yyStackOverflow() above pops the stack until it is
@@ -205356,7 +211578,7 @@ static fts5YYACTIONTYPE fts5yy_reduce(
 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
         break;
       case 1: /* colset ::= MINUS LCP colsetlist RCP */
-{ 
+{
     fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
 }
         break;
@@ -205376,13 +211598,13 @@ static fts5YYACTIONTYPE fts5yy_reduce(
 }
         break;
       case 5: /* colsetlist ::= colsetlist STRING */
-{ 
+{
   fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
   fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
         break;
       case 6: /* colsetlist ::= STRING */
-{ 
-  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); 
+{
+  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
 }
   fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
         break;
@@ -205426,14 +211648,14 @@ static fts5YYACTIONTYPE fts5yy_reduce(
   fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
         break;
       case 15: /* cnearset ::= nearset */
-{ 
-  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
+{
+  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
 }
   fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
         break;
       case 16: /* cnearset ::= colset COLON nearset */
-{ 
-  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46); 
+{
+  fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
   sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
 }
   fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
@@ -205443,9 +211665,9 @@ static fts5YYACTIONTYPE fts5yy_reduce(
   fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
         break;
       case 18: /* nearset ::= CARET phrase */
-{ 
+{
   sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
-  fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); 
+  fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
 }
         break;
       case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
@@ -205457,8 +211679,8 @@ static fts5YYACTIONTYPE fts5yy_reduce(
   fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
         break;
       case 20: /* nearphrases ::= phrase */
-{ 
-  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); 
+{
+  fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
 }
   fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
         break;
@@ -205475,13 +211697,13 @@ static fts5YYACTIONTYPE fts5yy_reduce(
 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
         break;
       case 24: /* phrase ::= phrase PLUS STRING star_opt */
-{ 
+{
   fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
 }
   fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
         break;
       case 25: /* phrase ::= STRING star_opt */
-{ 
+{
   fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
 }
   fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
@@ -205672,7 +211894,7 @@ static void sqlite3Fts5Parser(
 #ifdef fts5YYERRORSYMBOL
       /* A syntax error has occurred.
       ** The response to an error depends upon whether or not the
-      ** grammar defines an error token "ERROR".  
+      ** grammar defines an error token "ERROR".
       **
       ** This is what we do if the grammar does define ERROR:
       **
@@ -205786,8 +212008,8 @@ static int sqlite3Fts5ParserFallback(int iToken){
   return fts5yyFallback[iToken];
 #else
   (void)iToken;
-#endif
   return 0;
+#endif
 }
 
 /*
@@ -205808,7 +212030,7 @@ static int sqlite3Fts5ParserFallback(int iToken){
 #include <math.h>                 /* amalgamator: keep */
 
 /*
-** Object used to iterate through all "coalesced phrase instances" in 
+** Object used to iterate through all "coalesced phrase instances" in
 ** a single column of the current row. If the phrase instances in the
 ** column being considered do not overlap, this object simply iterates
 ** through them. Or, if they do overlap (share one or more tokens in
@@ -205871,7 +212093,7 @@ static int fts5CInstIterNext(CInstIter *pIter){
 }
 
 /*
-** Initialize the iterator object indicated by the final parameter to 
+** Initialize the iterator object indicated by the final parameter to
 ** iterate through coalesced phrase instances in column iCol.
 */
 static int fts5CInstIterInit(
@@ -205916,16 +212138,16 @@ struct HighlightContext {
 
 /*
 ** Append text to the HighlightContext output string - p->zOut. Argument
-** z points to a buffer containing n bytes of text to append. If n is 
+** z points to a buffer containing n bytes of text to append. If n is
 ** negative, everything up until the first '\0' is appended to the output.
 **
-** If *pRc is set to any value other than SQLITE_OK when this function is 
-** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, 
-** *pRc is set to an error code before returning. 
+** If *pRc is set to any value other than SQLITE_OK when this function is
+** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
+** *pRc is set to an error code before returning.
 */
 static void fts5HighlightAppend(
-  int *pRc, 
-  HighlightContext *p, 
+  int *pRc,
+  HighlightContext *p,
   const char *z, int n
 ){
   if( *pRc==SQLITE_OK && z ){
@@ -206152,7 +212374,7 @@ static int fts5SnippetScore(
 }
 
 /*
-** Return the value in pVal interpreted as utf-8 text. Except, if pVal 
+** Return the value in pVal interpreted as utf-8 text. Except, if pVal
 ** contains a NULL value, return a pointer to a static string zero
 ** bytes in length instead of a NULL pointer.
 */
@@ -206221,7 +212443,7 @@ static void fts5SnippetFunction(
       sFinder.nFirst = 0;
       rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
       if( rc!=SQLITE_OK ) break;
-      rc = pApi->xTokenize(pFts, 
+      rc = pApi->xTokenize(pFts,
           sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
       );
       if( rc!=SQLITE_OK ) break;
@@ -206256,7 +212478,7 @@ static void fts5SnippetFunction(
 
           if( sFinder.aFirst[jj]<io ){
             memset(aSeen, 0, nPhrase);
-            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i, 
+            rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
               sFinder.aFirst[jj], nToken, &nScore, 0
             );
 
@@ -206335,7 +212557,7 @@ struct Fts5Bm25Data {
 ** table matched by each individual phrase within the query.
 */
 static int fts5CountCb(
-  const Fts5ExtensionApi *pApi, 
+  const Fts5ExtensionApi *pApi,
   Fts5Context *pFts,
   void *pUserData                 /* Pointer to sqlite3_int64 variable */
 ){
@@ -206346,19 +212568,19 @@ static int fts5CountCb(
 }
 
 /*
-** Set *ppData to point to the Fts5Bm25Data object for the current query. 
+** Set *ppData to point to the Fts5Bm25Data object for the current query.
 ** If the object has not already been allocated, allocate and populate it
 ** now.
 */
 static int fts5Bm25GetData(
-  const Fts5ExtensionApi *pApi, 
+  const Fts5ExtensionApi *pApi,
   Fts5Context *pFts,
   Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
 ){
   int rc = SQLITE_OK;             /* Return code */
   Fts5Bm25Data *p;                /* Object to return */
 
-  p = pApi->xGetAuxdata(pFts, 0);
+  p = (Fts5Bm25Data*)pApi->xGetAuxdata(pFts, 0);
   if( p==0 ){
     int nPhrase;                  /* Number of phrases in query */
     sqlite3_int64 nRow = 0;       /* Number of rows in table */
@@ -206399,7 +212621,7 @@ static int fts5Bm25GetData(
         ** is the number that contain at least one instance of the phrase
         ** under consideration.
         **
-        ** The problem with this is that if (N < 2*nHit), the IDF is 
+        ** The problem with this is that if (N < 2*nHit), the IDF is
         ** negative. Which is undesirable. So the mimimum allowable IDF is
         ** (1e-6) - roughly the same as a term that appears in just over
         ** half of set of 5,000,000 documents.  */
@@ -206432,7 +212654,7 @@ static void fts5Bm25Function(
 ){
   const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
   const double b = 0.75;          /* Constant "b" from BM25 formula */
-  int rc = SQLITE_OK;             /* Error code */
+  int rc;                         /* Error code */
   double score = 0.0;             /* SQL function return value */
   Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
   int i;                          /* Iterator variable */
@@ -206464,17 +212686,15 @@ static void fts5Bm25Function(
     D = (double)nTok;
   }
 
-  /* Determine the BM25 score for the current row. */
-  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
-    score += pData->aIDF[i] * (
-      ( aFreq[i] * (k1 + 1.0) ) / 
-      ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
-    );
-  }
-  
-  /* If no error has occurred, return the calculated score. Otherwise,
-  ** throw an SQL exception.  */
+  /* Determine and return the BM25 score for the current row. Or, if an
+  ** error has occurred, throw an exception. */
   if( rc==SQLITE_OK ){
+    for(i=0; i<pData->nPhrase; i++){
+      score += pData->aIDF[i] * (
+          ( aFreq[i] * (k1 + 1.0) ) /
+          ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
+      );
+    }
     sqlite3_result_double(pCtx, -1.0 * score);
   }else{
     sqlite3_result_error_code(pCtx, rc);
@@ -206565,14 +212785,14 @@ static int sqlite3Fts5Get32(const u8 *aBuf){
 }
 
 /*
-** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set 
+** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
 ** the error code in p. If an error has already occurred when this function
 ** is called, it is a no-op.
 */
 static void sqlite3Fts5BufferAppendBlob(
   int *pRc,
-  Fts5Buffer *pBuf, 
-  u32 nData, 
+  Fts5Buffer *pBuf,
+  u32 nData,
   const u8 *pData
 ){
   assert_nc( *pRc || nData>=0 );
@@ -206585,12 +212805,12 @@ static void sqlite3Fts5BufferAppendBlob(
 
 /*
 ** Append the nul-terminated string zStr to the buffer pBuf. This function
-** ensures that the byte following the buffer data is set to 0x00, even 
+** ensures that the byte following the buffer data is set to 0x00, even
 ** though this byte is not included in the pBuf->n count.
 */
 static void sqlite3Fts5BufferAppendString(
   int *pRc,
-  Fts5Buffer *pBuf, 
+  Fts5Buffer *pBuf,
   const char *zStr
 ){
   int nStr = (int)strlen(zStr);
@@ -206602,13 +212822,13 @@ static void sqlite3Fts5BufferAppendString(
 ** Argument zFmt is a printf() style format string. This function performs
 ** the printf() style processing, then appends the results to buffer pBuf.
 **
-** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte 
+** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
 ** following the buffer data is set to 0x00, even though this byte is not
 ** included in the pBuf->n count.
-*/ 
+*/
 static void sqlite3Fts5BufferAppendPrintf(
   int *pRc,
-  Fts5Buffer *pBuf, 
+  Fts5Buffer *pBuf,
   const char *zFmt, ...
 ){
   if( *pRc==SQLITE_OK ){
@@ -206635,12 +212855,12 @@ static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
     zRet = sqlite3_vmprintf(zFmt, ap);
     va_end(ap);
     if( zRet==0 ){
-      *pRc = SQLITE_NOMEM; 
+      *pRc = SQLITE_NOMEM;
     }
   }
   return zRet;
 }
+
 
 /*
 ** Free any buffer allocated by pBuf. Zero the structure before returning.
@@ -206651,7 +212871,7 @@ static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
 }
 
 /*
-** Zero the contents of the buffer object. But do not free the associated 
+** Zero the contents of the buffer object. But do not free the associated
 ** memory allocation.
 */
 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
@@ -206665,8 +212885,8 @@ static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
 */
 static void sqlite3Fts5BufferSet(
   int *pRc,
-  Fts5Buffer *pBuf, 
-  int nData, 
+  Fts5Buffer *pBuf,
+  int nData,
   const u8 *pData
 ){
   pBuf->n = 0;
@@ -206682,7 +212902,7 @@ static int sqlite3Fts5PoslistNext64(
   if( i>=n ){
     /* EOF */
     *piOff = -1;
-    return 1;  
+    return 1;
   }else{
     i64 iOff = *piOff;
     int iVal;
@@ -206737,8 +212957,8 @@ static int sqlite3Fts5PoslistReaderInit(
 ** to iPos before returning.
 */
 static void sqlite3Fts5PoslistSafeAppend(
-  Fts5Buffer *pBuf, 
-  i64 *piPrev, 
+  Fts5Buffer *pBuf,
+  i64 *piPrev,
   i64 iPos
 ){
   static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
@@ -206752,7 +212972,7 @@ static void sqlite3Fts5PoslistSafeAppend(
 }
 
 static int sqlite3Fts5PoslistWriterAppend(
-  Fts5Buffer *pBuf, 
+  Fts5Buffer *pBuf,
   Fts5PoslistWriter *pWriter,
   i64 iPos
 ){
@@ -206781,7 +213001,7 @@ static void *sqlite3Fts5MallocZero(int *pRc, size_t nByte){
 ** the length of the string is determined using strlen().
 **
 ** It is the responsibility of the caller to eventually free the returned
-** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. 
+** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
 */
 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, size_t nIn){
   char *zRet = 0;
@@ -206848,9 +213068,9 @@ static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
 }
 
 static int sqlite3Fts5TermsetAdd(
-  Fts5Termset *p, 
+  Fts5Termset *p,
   int iIdx,
-  const char *pTerm, int nTerm, 
+  const char *pTerm, int nTerm,
   int *pbPresent
 ){
   int rc = SQLITE_OK;
@@ -206871,9 +213091,9 @@ static int sqlite3Fts5TermsetAdd(
     hash = hash % ArraySize(p->apHash);
 
     for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
-      if( pEntry->iIdx==iIdx 
-          && pEntry->nTerm==nTerm 
-          && memcmp(pEntry->pTerm, pTerm, nTerm)==0 
+      if( pEntry->iIdx==iIdx
+          && pEntry->nTerm==nTerm
+          && memcmp(pEntry->pTerm, pTerm, nTerm)==0
       ){
         *pbPresent = 1;
         break;
@@ -206936,7 +213156,7 @@ static void sqlite3Fts5TermsetFree(Fts5Termset *p){
 #define FTS5_DEFAULT_HASHSIZE    (1024*1024)
 
 /* Maximum allowed page size */
-#define FTS5_MAX_PAGE_SIZE (128*1024)
+#define FTS5_MAX_PAGE_SIZE (64*1024)
 
 static int fts5_iswhitespace(char x){
   return (x==' ');
@@ -206947,8 +213167,8 @@ static int fts5_isopenquote(char x){
 }
 
 /*
-** Argument pIn points to a character that is part of a nul-terminated 
-** string. Return a pointer to the first character following *pIn in 
+** Argument pIn points to a character that is part of a nul-terminated
+** string. Return a pointer to the first character following *pIn in
 ** the string that is not a white-space character.
 */
 static const char *fts5ConfigSkipWhitespace(const char *pIn){
@@ -206960,8 +213180,8 @@ static const char *fts5ConfigSkipWhitespace(const char *pIn){
 }
 
 /*
-** Argument pIn points to a character that is part of a nul-terminated 
-** string. Return a pointer to the first character following *pIn in 
+** Argument pIn points to a character that is part of a nul-terminated
+** string. Return a pointer to the first character following *pIn in
 ** the string that is not a "bareword" character.
 */
 static const char *fts5ConfigSkipBareword(const char *pIn){
@@ -206992,9 +213212,9 @@ static const char *fts5ConfigSkipLiteral(const char *pIn){
       p++;
       if( *p=='\'' ){
         p++;
-        while( (*p>='a' && *p<='f') 
-            || (*p>='A' && *p<='F') 
-            || (*p>='0' && *p<='9') 
+        while( (*p>='a' && *p<='f')
+            || (*p>='A' && *p<='F')
+            || (*p>='0' && *p<='9')
             ){
           p++;
         }
@@ -207025,7 +213245,7 @@ static const char *fts5ConfigSkipLiteral(const char *pIn){
       if( *p=='+' || *p=='-' ) p++;
       while( fts5_isdigit(*p) ) p++;
 
-      /* At this point, if the literal was an integer, the parse is 
+      /* At this point, if the literal was an integer, the parse is
       ** finished. Or, if it is a floating point value, it may continue
       ** with either a decimal point or an 'E' character. */
       if( *p=='.' && fts5_isdigit(p[1]) ){
@@ -207049,8 +213269,8 @@ static const char *fts5ConfigSkipLiteral(const char *pIn){
 ** nul-terminator byte.
 **
 ** If the close-quote is found, the value returned is the byte offset of
-** the character immediately following it. Or, if the close-quote is not 
-** found, -1 is returned. If -1 is returned, the buffer is left in an 
+** the character immediately following it. Or, if the close-quote is not
+** found, -1 is returned. If -1 is returned, the buffer is left in an
 ** undefined state.
 */
 static int fts5Dequote(char *z){
@@ -207061,9 +213281,9 @@ static int fts5Dequote(char *z){
 
   /* Set stack variable q to the close-quote character */
   assert( q=='[' || q=='\'' || q=='"' || q=='`' );
-  if( q=='[' ) q = ']';  
+  if( q=='[' ) q = ']';
 
-  while( ALWAYS(z[iIn]) ){
+  while( z[iIn] ){
     if( z[iIn]==q ){
       if( z[iIn+1]!=q ){
         /* Character iIn was the close quote. */
@@ -207071,7 +213291,7 @@ static int fts5Dequote(char *z){
         break;
       }else{
         /* Character iIn and iIn+1 form an escaped quote character. Skip
-        ** the input cursor past both and copy a single quote character 
+        ** the input cursor past both and copy a single quote character
         ** to the output buffer. */
         iIn += 2;
         z[iOut++] = q;
@@ -207116,8 +213336,8 @@ struct Fts5Enum {
 typedef struct Fts5Enum Fts5Enum;
 
 static int fts5ConfigSetEnum(
-  const Fts5Enum *aEnum, 
-  const char *zEnum, 
+  const Fts5Enum *aEnum,
+  const char *zEnum,
   int *peVal
 ){
   int nEnum = (int)strlen(zEnum);
@@ -207237,8 +213457,8 @@ static int fts5ConfigParseSpecial(
           *pzErr = sqlite3_mprintf("parse error in tokenize directive");
           rc = SQLITE_ERROR;
         }else{
-          rc = sqlite3Fts5GetTokenizer(pGlobal, 
-              (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi,
+          rc = sqlite3Fts5GetTokenizer(pGlobal,
+              (const char**)azArg, (int)nArg, pConfig,
               pzErr
           );
         }
@@ -207304,15 +213524,13 @@ static int fts5ConfigParseSpecial(
 }
 
 /*
-** Allocate an instance of the default tokenizer ("simple") at 
+** Allocate an instance of the default tokenizer ("simple") at
 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
 ** code if an error occurs.
 */
 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
   assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
-  return sqlite3Fts5GetTokenizer(
-      pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
-  );
+  return sqlite3Fts5GetTokenizer(pGlobal, 0, 0, pConfig, 0);
 }
 
 /*
@@ -207371,14 +213589,14 @@ static const char *fts5ConfigGobbleWord(
 }
 
 static int fts5ConfigParseColumn(
-  Fts5Config *p, 
-  char *zCol, 
-  char *zArg, 
+  Fts5Config *p,
+  char *zCol,
+  char *zArg,
   char **pzErr
 ){
   int rc = SQLITE_OK;
-  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) 
-   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) 
+  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
+   || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
   ){
     *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
     rc = SQLITE_ERROR;
@@ -207421,14 +213639,14 @@ static int fts5ConfigMakeExprlist(Fts5Config *p){
 
 /*
 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
-** or xConnect method of the virtual table. This function attempts to 
+** or xConnect method of the virtual table. This function attempts to
 ** allocate an instance of Fts5Config containing the results of parsing
 ** those arguments.
 **
 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
-** new Fts5Config object. If an error occurs, an SQLite error code is 
+** new Fts5Config object. If an error occurs, an SQLite error code is
 ** returned, *ppOut is set to NULL and an error message may be left in
-** *pzErr. It is the responsibility of the caller to eventually free any 
+** *pzErr. It is the responsibility of the caller to eventually free any
 ** such error message using sqlite3_free().
 */
 static int sqlite3Fts5ConfigParse(
@@ -207515,8 +213733,8 @@ static int sqlite3Fts5ConfigParse(
   /* If no zContent option was specified, fill in the default values. */
   if( rc==SQLITE_OK && pRet->zContent==0 ){
     const char *zTail = 0;
-    assert( pRet->eContent==FTS5_CONTENT_NORMAL 
-         || pRet->eContent==FTS5_CONTENT_NONE 
+    assert( pRet->eContent==FTS5_CONTENT_NORMAL
+         || pRet->eContent==FTS5_CONTENT_NONE
     );
     if( pRet->eContent==FTS5_CONTENT_NORMAL ){
       zTail = "content";
@@ -207587,7 +213805,7 @@ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
     const char *zSep = (i==0?"":", ");
     zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
   }
-  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", 
+  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
       zSql, pConfig->zName, FTS5_RANK_NAME
   );
 
@@ -207596,7 +213814,7 @@ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
     rc = sqlite3_declare_vtab(pConfig->db, zSql);
     sqlite3_free(zSql);
   }
+
   return rc;
 }
 
@@ -207614,7 +213832,7 @@ static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
 **     int iPos            // Position of token in input (first token is 0)
 **
 ** If the callback returns a non-zero value the tokenization is abandoned
-** and no further callbacks are issued. 
+** and no further callbacks are issued.
 **
 ** This function returns SQLITE_OK if successful or an SQLite error code
 ** if an error occurs. If the tokenization was abandoned early because
@@ -207644,7 +213862,7 @@ static int sqlite3Fts5Tokenize(
 */
 static const char *fts5ConfigSkipArgs(const char *pIn){
   const char *p = pIn;
-  
+
   while( 1 ){
     p = fts5ConfigSkipWhitespace(p);
     p = fts5ConfigSkipLiteral(p);
@@ -207661,7 +213879,7 @@ static const char *fts5ConfigSkipArgs(const char *pIn){
 }
 
 /*
-** Parameter zIn contains a rank() function specification. The format of 
+** Parameter zIn contains a rank() function specification. The format of
 ** this is:
 **
 **   + Bareword (function name)
@@ -207703,7 +213921,7 @@ static int sqlite3Fts5ConfigParseRank(
       p++;
     }
     if( rc==SQLITE_OK ){
-      const char *pArgs; 
+      const char *pArgs;
       p = fts5ConfigSkipWhitespace(p);
       pArgs = p;
       if( *p!=')' ){
@@ -207729,8 +213947,8 @@ static int sqlite3Fts5ConfigParseRank(
 }
 
 static int sqlite3Fts5ConfigSetValue(
-  Fts5Config *pConfig, 
-  const char *zKey, 
+  Fts5Config *pConfig,
+  const char *zKey,
   sqlite3_value *pVal,
   int *pbBadkey
 ){
@@ -207794,6 +214012,7 @@ static int sqlite3Fts5ConfigSetValue(
       *pbBadkey = 1;
     }else{
       if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
+      if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1;
       pConfig->nCrisisMerge = nCrisisMerge;
     }
   }
@@ -207855,7 +214074,7 @@ static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
     }
     rc = sqlite3_finalize(p);
   }
-  
+
   if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
     rc = SQLITE_ERROR;
     if( pConfig->pzErrmsg ){
@@ -207944,7 +214163,7 @@ struct Fts5ExprNode {
   i64 iRowid;                     /* Current rowid */
   Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
 
-  /* Child nodes. For a NOT node, this array always contains 2 entries. For 
+  /* Child nodes. For a NOT node, this array always contains 2 entries. For
   ** AND or OR nodes, it contains 2 or more entries.  */
   int nChild;                     /* Number of child nodes */
   Fts5ExprNode *apChild[1];       /* Array of child nodes */
@@ -208003,6 +214222,7 @@ struct Fts5Parse {
   int nPhrase;                    /* Size of apPhrase array */
   Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
   Fts5ExprNode *pExpr;            /* Result of a successful parse */
+  int bPhraseToAnd;               /* Convert "a+b" to "a AND b" */
 };
 
 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
@@ -208023,7 +214243,7 @@ static int fts5ExprIsspace(char t){
 ** Read the first token from the nul-terminated string at *pz.
 */
 static int fts5ExprGetToken(
-  Fts5Parse *pParse, 
+  Fts5Parse *pParse,
   const char **pz,                /* IN/OUT: Pointer into buffer */
   Fts5Token *pToken
 ){
@@ -208091,9 +214311,10 @@ static void fts5ParseFree(void *p){ sqlite3_free(p); }
 
 static int sqlite3Fts5ExprNew(
   Fts5Config *pConfig,            /* FTS5 Configuration */
+  int bPhraseToAnd,
   int iCol,
   const char *zExpr,              /* Expression text */
-  Fts5Expr **ppNew, 
+  Fts5Expr **ppNew,
   char **pzErr
 ){
   Fts5Parse sParse;
@@ -208106,6 +214327,7 @@ static int sqlite3Fts5ExprNew(
   *ppNew = 0;
   *pzErr = 0;
   memset(&sParse, 0, sizeof(sParse));
+  sParse.bPhraseToAnd = bPhraseToAnd;
   pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
   if( pEngine==0 ){ return SQLITE_NOMEM; }
   sParse.pConfig = pConfig;
@@ -208148,6 +214370,7 @@ static int sqlite3Fts5ExprNew(
       pNew->pConfig = pConfig;
       pNew->apExprPhrase = sParse.apPhrase;
       pNew->nPhrase = sParse.nPhrase;
+      pNew->bDesc = 0;
       sParse.apPhrase = 0;
     }
   }else{
@@ -208160,6 +214383,81 @@ static int sqlite3Fts5ExprNew(
 }
 
 /*
+** This function is only called when using the special 'trigram' tokenizer.
+** Argument zText contains the text of a LIKE or GLOB pattern matched
+** against column iCol. This function creates and compiles an FTS5 MATCH
+** expression that will match a superset of the rows matched by the LIKE or
+** GLOB. If successful, SQLITE_OK is returned. Otherwise, an SQLite error
+** code.
+*/
+static int sqlite3Fts5ExprPattern(
+  Fts5Config *pConfig, int bGlob, int iCol, const char *zText, Fts5Expr **pp
+){
+  i64 nText = strlen(zText);
+  char *zExpr = (char*)sqlite3_malloc64(nText*4 + 1);
+  int rc = SQLITE_OK;
+
+  if( zExpr==0 ){
+    rc = SQLITE_NOMEM;
+  }else{
+    char aSpec[3];
+    int iOut = 0;
+    int i = 0;
+    int iFirst = 0;
+
+    if( bGlob==0 ){
+      aSpec[0] = '_';
+      aSpec[1] = '%';
+      aSpec[2] = 0;
+    }else{
+      aSpec[0] = '*';
+      aSpec[1] = '?';
+      aSpec[2] = '[';
+    }
+
+    while( i<=nText ){
+      if( i==nText
+       || zText[i]==aSpec[0] || zText[i]==aSpec[1] || zText[i]==aSpec[2]
+      ){
+        if( i-iFirst>=3 ){
+          int jj;
+          zExpr[iOut++] = '"';
+          for(jj=iFirst; jj<i; jj++){
+            zExpr[iOut++] = zText[jj];
+            if( zText[jj]=='"' ) zExpr[iOut++] = '"';
+          }
+          zExpr[iOut++] = '"';
+          zExpr[iOut++] = ' ';
+        }
+        if( zText[i]==aSpec[2] ){
+          i += 2;
+          if( zText[i-1]=='^' ) i++;
+          while( i<nText && zText[i]!=']' ) i++;
+        }
+        iFirst = i+1;
+      }
+      i++;
+    }
+    if( iOut>0 ){
+      int bAnd = 0;
+      if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
+        bAnd = 1;
+        if( pConfig->eDetail==FTS5_DETAIL_NONE ){
+          iCol = pConfig->nCol;
+        }
+      }
+      zExpr[iOut] = '\0';
+      rc = sqlite3Fts5ExprNew(pConfig, bAnd, iCol, zExpr, pp,pConfig->pzErrmsg);
+    }else{
+      *pp = 0;
+    }
+    sqlite3_free(zExpr);
+  }
+
+  return rc;
+}
+
+/*
 ** Free the expression node object passed as the only argument.
 */
 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
@@ -208249,7 +214547,7 @@ static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
 ** Argument pTerm must be a synonym iterator.
 */
 static int fts5ExprSynonymList(
-  Fts5ExprTerm *pTerm, 
+  Fts5ExprTerm *pTerm,
   i64 iRowid,
   Fts5Buffer *pBuf,               /* Use this buffer for space if required */
   u8 **pa, int *pn
@@ -208322,13 +214620,13 @@ static int fts5ExprSynonymList(
 
 /*
 ** All individual term iterators in pPhrase are guaranteed to be valid and
-** pointing to the same rowid when this function is called. This function 
+** pointing to the same rowid when this function is called. This function
 ** checks if the current rowid really is a match, and if so populates
 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
 ** is set to true if this is really a match, or false otherwise.
 **
-** SQLITE_OK is returned if an error occurs, or an SQLite error code 
-** otherwise. It is not considered an error code if the current rowid is 
+** SQLITE_OK is returned if an error occurs, or an SQLite error code
+** otherwise. It is not considered an error code if the current rowid is
 ** not a match.
 */
 static int fts5ExprPhraseIsMatch(
@@ -208342,7 +214640,7 @@ static int fts5ExprPhraseIsMatch(
   int i;
   int rc = SQLITE_OK;
   int bFirst = pPhrase->aTerm[0].bFirst;
-  
+
   fts5BufferZero(&pPhrase->poslist);
 
   /* If the aStatic[] array is not large enough, allocate a large array
@@ -208464,7 +214762,7 @@ struct Fts5NearTrimmer {
 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
 ** occurs within this function (*pRc) is set accordingly before returning.
 ** The return value is undefined in both these cases.
-** 
+**
 ** If no error occurs and non-zero (a match) is returned, the position-list
 ** of each phrase object is edited to contain only those entries that
 ** meet the constraint before returning.
@@ -208496,7 +214794,7 @@ static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
   /* Initialize a lookahead iterator for each phrase. After passing the
   ** buffer and buffer size to the lookaside-reader init function, zero
   ** the phrase poslist buffer. The new poslist for the phrase (containing
-  ** the same entries as the original with some entries removed on account 
+  ** the same entries as the original with some entries removed on account
   ** of the NEAR constraint) is written over the original even as it is
   ** being read. This is safe as the entries for the new poslist are a
   ** subset of the old, so it is not possible for data yet to be read to
@@ -208653,7 +214951,7 @@ static int fts5ExprNearTest(
     ** phrase is not a match, break out of the loop early.  */
     for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
-      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym 
+      if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
        || pNear->pColset || pPhrase->aTerm[0].bFirst
       ){
         int bMatch = 0;
@@ -208801,7 +215099,7 @@ static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
 */
 static int fts5NodeCompare(
   Fts5Expr *pExpr,
-  Fts5ExprNode *p1, 
+  Fts5ExprNode *p1,
   Fts5ExprNode *p2
 ){
   if( p2->bEof ) return -1;
@@ -208816,7 +215114,7 @@ static int fts5NodeCompare(
 ** If an EOF is reached before this happens, *pbEof is set to true before
 ** returning.
 **
-** SQLITE_OK is returned if an error occurs, or an SQLite error code 
+** SQLITE_OK is returned if an error occurs, or an SQLite error code
 ** otherwise. It is not considered an error code if an iterator reaches
 ** EOF.
 */
@@ -208833,8 +215131,8 @@ static int fts5ExprNodeTest_STRING(
   const int bDesc = pExpr->bDesc;
 
   /* Check that this node should not be FTS5_TERM */
-  assert( pNear->nPhrase>1 
-       || pNear->apPhrase[0]->nTerm>1 
+  assert( pNear->nPhrase>1
+       || pNear->apPhrase[0]->nTerm>1
        || pNear->apPhrase[0]->aTerm[0].pSynonym
        || pNear->apPhrase[0]->aTerm[0].bFirst
   );
@@ -208894,7 +215192,7 @@ static int fts5ExprNodeNext_STRING(
   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
   Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
   int bFromValid,
-  i64 iFrom 
+  i64 iFrom
 ){
   Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
   int rc = SQLITE_OK;
@@ -208912,8 +215210,8 @@ static int fts5ExprNodeNext_STRING(
     for(p=pTerm; p; p=p->pSynonym){
       if( sqlite3Fts5IterEof(p->pIter)==0 ){
         i64 ii = p->pIter->iRowid;
-        if( ii==iRowid 
-         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) 
+        if( ii==iRowid
+         || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
         ){
           if( bFromValid ){
             rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
@@ -208959,9 +215257,9 @@ static int fts5ExprNodeTest_TERM(
   Fts5Expr *pExpr,                /* Expression that pNear is a part of */
   Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
 ){
-  /* As this "NEAR" object is actually a single phrase that consists 
+  /* As this "NEAR" object is actually a single phrase that consists
   ** of a single term only, grab pointers into the poslist managed by the
-  ** fts5_index.c iterator object. This is much faster than synthesizing 
+  ** fts5_index.c iterator object. This is much faster than synthesizing
   ** a new poslist the way we have to for more complicated phrase or NEAR
   ** expressions.  */
   Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
@@ -208984,7 +215282,7 @@ static int fts5ExprNodeTest_TERM(
 ** xNext() method for a node of type FTS5_TERM.
 */
 static int fts5ExprNodeNext_TERM(
-  Fts5Expr *pExpr, 
+  Fts5Expr *pExpr,
   Fts5ExprNode *pNode,
   int bFromValid,
   i64 iFrom
@@ -209027,7 +215325,7 @@ static void fts5ExprNodeTest_OR(
 }
 
 static int fts5ExprNodeNext_OR(
-  Fts5Expr *pExpr, 
+  Fts5Expr *pExpr,
   Fts5ExprNode *pNode,
   int bFromValid,
   i64 iFrom
@@ -209039,7 +215337,7 @@ static int fts5ExprNodeNext_OR(
     Fts5ExprNode *p1 = pNode->apChild[i];
     assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
     if( p1->bEof==0 ){
-      if( (p1->iRowid==iLast) 
+      if( (p1->iRowid==iLast)
        || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
       ){
         int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
@@ -209111,7 +215409,7 @@ static int fts5ExprNodeTest_AND(
 }
 
 static int fts5ExprNodeNext_AND(
-  Fts5Expr *pExpr, 
+  Fts5Expr *pExpr,
   Fts5ExprNode *pNode,
   int bFromValid,
   i64 iFrom
@@ -209154,7 +215452,7 @@ static int fts5ExprNodeTest_NOT(
 }
 
 static int fts5ExprNodeNext_NOT(
-  Fts5Expr *pExpr, 
+  Fts5Expr *pExpr,
   Fts5ExprNode *pNode,
   int bFromValid,
   i64 iFrom
@@ -209211,7 +215509,7 @@ static int fts5ExprNodeTest(
   return rc;
 }
 
+
 /*
 ** Set node pNode, which is part of expression pExpr, to point to the first
 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
@@ -209265,8 +215563,8 @@ static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
 
 /*
 ** Begin iterating through the set of documents in index pIdx matched by
-** the MATCH expression passed as the first argument. If the "bDesc" 
-** parameter is passed a non-zero value, iteration is in descending rowid 
+** the MATCH expression passed as the first argument. If the "bDesc"
+** parameter is passed a non-zero value, iteration is in descending rowid
 ** order. Or, if it is zero, in ascending order.
 **
 ** If iterating in ascending rowid order (bDesc==0), the first document
@@ -209288,9 +215586,9 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bD
 
   /* If not at EOF but the current rowid occurs earlier than iFirst in
   ** the iteration order, move to document iFirst or later. */
-  if( rc==SQLITE_OK 
-   && 0==pRoot->bEof 
-   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 
+  if( rc==SQLITE_OK
+   && 0==pRoot->bEof
+   && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
   ){
     rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
   }
@@ -209304,7 +215602,7 @@ static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bD
 }
 
 /*
-** Move to the next document 
+** Move to the next document
 **
 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
 ** is not considered an error if the query does not match any documents.
@@ -209486,7 +215784,7 @@ static int fts5ParseTokenize(
       Fts5ExprPhrase *pNew;
       int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
 
-      pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase, 
+      pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
           sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
       );
       if( pNew==0 ){
@@ -209536,6 +215834,20 @@ static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
   pParse->pExpr = p;
 }
 
+static int parseGrowPhraseArray(Fts5Parse *pParse){
+  if( (pParse->nPhrase % 8)==0 ){
+    sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
+    Fts5ExprPhrase **apNew;
+    apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
+    if( apNew==0 ){
+      pParse->rc = SQLITE_NOMEM;
+      return SQLITE_NOMEM;
+    }
+    pParse->apPhrase = apNew;
+  }
+  return SQLITE_OK;
+}
+
 /*
 ** This function is called by the parser to process a string token. The
 ** string may or may not be quoted. In any case it is tokenized and a
@@ -209571,16 +215883,9 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
   }else{
 
     if( pAppend==0 ){
-      if( (pParse->nPhrase % 8)==0 ){
-        sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
-        Fts5ExprPhrase **apNew;
-        apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
-        if( apNew==0 ){
-          pParse->rc = SQLITE_NOMEM;
-          fts5ExprPhraseFree(sCtx.pPhrase);
-          return 0;
-        }
-        pParse->apPhrase = apNew;
+      if( parseGrowPhraseArray(pParse) ){
+        fts5ExprPhraseFree(sCtx.pPhrase);
+        return 0;
       }
       pParse->nPhrase++;
     }
@@ -209603,8 +215908,8 @@ static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
 ** expression passed as the second argument.
 */
 static int sqlite3Fts5ExprClonePhrase(
-  Fts5Expr *pExpr, 
-  int iPhrase, 
+  Fts5Expr *pExpr,
+  int iPhrase,
   Fts5Expr **ppNew
 ){
   int rc = SQLITE_OK;             /* Return code */
@@ -209615,15 +215920,15 @@ static int sqlite3Fts5ExprClonePhrase(
   pOrig = pExpr->apExprPhrase[iPhrase];
   pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
   if( rc==SQLITE_OK ){
-    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, 
+    pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
         sizeof(Fts5ExprPhrase*));
   }
   if( rc==SQLITE_OK ){
-    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, 
+    pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
         sizeof(Fts5ExprNode));
   }
   if( rc==SQLITE_OK ){
-    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, 
+    pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
         sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
   }
   if( rc==SQLITE_OK ){
@@ -209633,7 +215938,7 @@ static int sqlite3Fts5ExprClonePhrase(
       Fts5Colset *pColset;
       nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
       pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
-      if( pColset ){ 
+      if( pColset ){
         memcpy(pColset, pColsetOrig, (size_t)nByte);
       }
       pNew->pRoot->pNear->pColset = pColset;
@@ -209672,9 +215977,9 @@ static int sqlite3Fts5ExprClonePhrase(
     pNew->pRoot->pNear->nPhrase = 1;
     sCtx.pPhrase->pNode = pNew->pRoot;
 
-    if( pOrig->nTerm==1 
-     && pOrig->aTerm[0].pSynonym==0 
-     && pOrig->aTerm[0].bFirst==0 
+    if( pOrig->nTerm==1
+     && pOrig->aTerm[0].pSynonym==0
+     && pOrig->aTerm[0].bFirst==0
     ){
       pNew->pRoot->eType = FTS5_TERM;
       pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
@@ -209707,7 +216012,7 @@ static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
 }
 
 static void sqlite3Fts5ParseSetDistance(
-  Fts5Parse *pParse, 
+  Fts5Parse *pParse,
   Fts5ExprNearset *pNear,
   Fts5Token *p
 ){
@@ -209736,7 +216041,7 @@ static void sqlite3Fts5ParseSetDistance(
 ** The second argument passed to this function may be NULL, or it may be
 ** an existing Fts5Colset object. This function returns a pointer to
 ** a new colset object containing the contents of (p) with new value column
-** number iCol appended. 
+** number iCol appended.
 **
 ** If an OOM error occurs, store an error code in pParse and return NULL.
 ** The old colset object (if any) is not freed in this case.
@@ -209786,7 +216091,7 @@ static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p
   Fts5Colset *pRet;
   int nCol = pParse->pConfig->nCol;
 
-  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc, 
+  pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
       sizeof(Fts5Colset) + sizeof(int)*nCol
   );
   if( pRet ){
@@ -209839,7 +216144,7 @@ static Fts5Colset *sqlite3Fts5ParseColset(
 
 /*
 ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
-** SQLITE_OK when this function is called, NULL is returned. 
+** SQLITE_OK when this function is called, NULL is returned.
 **
 ** Otherwise, a copy of (*pOrig) is made into memory obtained from
 ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
@@ -209850,7 +216155,7 @@ static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
   if( pOrig ){
     sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
     pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
-    if( pRet ){ 
+    if( pRet ){
       memcpy(pRet, pOrig, (size_t)nByte);
     }
   }else{
@@ -209889,13 +216194,13 @@ static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
 ** zero, or it may create copies of pColset using fts5CloneColset().
 */
 static void fts5ParseSetColset(
-  Fts5Parse *pParse, 
-  Fts5ExprNode *pNode, 
+  Fts5Parse *pParse,
+  Fts5ExprNode *pNode,
   Fts5Colset *pColset,
   Fts5Colset **ppFree
 ){
   if( pParse->rc==SQLITE_OK ){
-    assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING 
+    assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
          || pNode->eType==FTS5_AND  || pNode->eType==FTS5_OR
          || pNode->eType==FTS5_NOT  || pNode->eType==FTS5_EOF
     );
@@ -209927,9 +216232,9 @@ static void fts5ParseSetColset(
 ** Apply colset pColset to expression node pExpr and all of its descendents.
 */
 static void sqlite3Fts5ParseSetColset(
-  Fts5Parse *pParse, 
-  Fts5ExprNode *pExpr, 
-  Fts5Colset *pColset 
+  Fts5Parse *pParse,
+  Fts5ExprNode *pExpr,
+  Fts5Colset *pColset
 ){
   Fts5Colset *pFree = pColset;
   if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
@@ -209947,7 +216252,7 @@ static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
   switch( pNode->eType ){
     case FTS5_STRING: {
       Fts5ExprNearset *pNear = pNode->pNear;
-      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 
+      if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
        && pNear->apPhrase[0]->aTerm[0].pSynonym==0
        && pNear->apPhrase[0]->aTerm[0].bFirst==0
       ){
@@ -209988,6 +216293,67 @@ static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
 }
 
 /*
+** This function is used when parsing LIKE or GLOB patterns against
+** trigram indexes that specify either detail=column or detail=none.
+** It converts a phrase:
+**
+**     abc + def + ghi
+**
+** into an AND tree:
+**
+**     abc AND def AND ghi
+*/
+static Fts5ExprNode *fts5ParsePhraseToAnd(
+  Fts5Parse *pParse,
+  Fts5ExprNearset *pNear
+){
+  int nTerm = pNear->apPhrase[0]->nTerm;
+  int ii;
+  int nByte;
+  Fts5ExprNode *pRet;
+
+  assert( pNear->nPhrase==1 );
+  assert( pParse->bPhraseToAnd );
+
+  nByte = sizeof(Fts5ExprNode) + nTerm*sizeof(Fts5ExprNode*);
+  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
+  if( pRet ){
+    pRet->eType = FTS5_AND;
+    pRet->nChild = nTerm;
+    fts5ExprAssignXNext(pRet);
+    pParse->nPhrase--;
+    for(ii=0; ii<nTerm; ii++){
+      Fts5ExprPhrase *pPhrase = (Fts5ExprPhrase*)sqlite3Fts5MallocZero(
+          &pParse->rc, sizeof(Fts5ExprPhrase)
+      );
+      if( pPhrase ){
+        if( parseGrowPhraseArray(pParse) ){
+          fts5ExprPhraseFree(pPhrase);
+        }else{
+          pParse->apPhrase[pParse->nPhrase++] = pPhrase;
+          pPhrase->nTerm = 1;
+          pPhrase->aTerm[0].zTerm = sqlite3Fts5Strndup(
+              &pParse->rc, pNear->apPhrase[0]->aTerm[ii].zTerm, -1
+          );
+          pRet->apChild[ii] = sqlite3Fts5ParseNode(pParse, FTS5_STRING,
+              0, 0, sqlite3Fts5ParseNearset(pParse, 0, pPhrase)
+          );
+        }
+      }
+    }
+
+    if( pParse->rc ){
+      sqlite3Fts5ParseNodeFree(pRet);
+      pRet = 0;
+    }else{
+      sqlite3Fts5ParseNearsetFree(pNear);
+    }
+  }
+
+  return pRet;
+}
+
+/*
 ** Allocate and return a new expression object. If anything goes wrong (i.e.
 ** OOM error), leave an error code in pParse and return NULL.
 */
@@ -210003,7 +216369,7 @@ static Fts5ExprNode *sqlite3Fts5ParseNode(
   if( pParse->rc==SQLITE_OK ){
     int nChild = 0;               /* Number of children of returned node */
     size_t nByte;                 /* Bytes of space to allocate for this node */
+
     assert( (eType!=FTS5_STRING && !pNear)
          || (eType==FTS5_STRING && !pLeft && !pRight)
     );
@@ -210011,51 +216377,58 @@ static Fts5ExprNode *sqlite3Fts5ParseNode(
     if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
     if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
 
-    if( eType==FTS5_NOT ){
-      nChild = 2;
-    }else if( eType==FTS5_AND || eType==FTS5_OR ){
-      nChild = 2;
-      if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
-      if( pRight->eType==eType ) nChild += pRight->nChild-1;
-    }
+    if( eType==FTS5_STRING
+     && pParse->bPhraseToAnd
+     && pNear->apPhrase[0]->nTerm>1
+    ){
+      pRet = fts5ParsePhraseToAnd(pParse, pNear);
+    }else{
+      if( eType==FTS5_NOT ){
+        nChild = 2;
+      }else if( eType==FTS5_AND || eType==FTS5_OR ){
+        nChild = 2;
+        if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
+        if( pRight->eType==eType ) nChild += pRight->nChild-1;
+      }
 
-    nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
-    pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
+      nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
+      pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
 
-    if( pRet ){
-      pRet->eType = eType;
-      pRet->pNear = pNear;
-      fts5ExprAssignXNext(pRet);
-      if( eType==FTS5_STRING ){
-        int iPhrase;
-        for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
-          pNear->apPhrase[iPhrase]->pNode = pRet;
-          if( pNear->apPhrase[iPhrase]->nTerm==0 ){
-            pRet->xNext = 0;
-            pRet->eType = FTS5_EOF;
+      if( pRet ){
+        pRet->eType = eType;
+        pRet->pNear = pNear;
+        fts5ExprAssignXNext(pRet);
+        if( eType==FTS5_STRING ){
+          int iPhrase;
+          for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
+            pNear->apPhrase[iPhrase]->pNode = pRet;
+            if( pNear->apPhrase[iPhrase]->nTerm==0 ){
+              pRet->xNext = 0;
+              pRet->eType = FTS5_EOF;
+            }
           }
-        }
 
-        if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
-          Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
-          if( pNear->nPhrase!=1 
-           || pPhrase->nTerm>1
-           || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
-          ){
-            assert( pParse->rc==SQLITE_OK );
-            pParse->rc = SQLITE_ERROR;
-            assert( pParse->zErr==0 );
-            pParse->zErr = sqlite3_mprintf(
-                "fts5: %s queries are not supported (detail!=full)", 
-                pNear->nPhrase==1 ? "phrase": "NEAR"
-                );
-            sqlite3_free(pRet);
-            pRet = 0;
+          if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
+            Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
+            if( pNear->nPhrase!=1
+                || pPhrase->nTerm>1
+                || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
+              ){
+              assert( pParse->rc==SQLITE_OK );
+              pParse->rc = SQLITE_ERROR;
+              assert( pParse->zErr==0 );
+              pParse->zErr = sqlite3_mprintf(
+                  "fts5: %s queries are not supported (detail!=full)",
+                  pNear->nPhrase==1 ? "phrase": "NEAR"
+                  );
+              sqlite3_free(pRet);
+              pRet = 0;
+            }
           }
+        }else{
+          fts5ExprAddChildren(pRet, pLeft);
+          fts5ExprAddChildren(pRet, pRight);
         }
-      }else{
-        fts5ExprAddChildren(pRet, pLeft);
-        fts5ExprAddChildren(pRet, pRight);
       }
     }
   }
@@ -210082,14 +216455,14 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
     sqlite3Fts5ParseNodeFree(pRight);
   }else{
 
-    assert( pLeft->eType==FTS5_STRING 
+    assert( pLeft->eType==FTS5_STRING
         || pLeft->eType==FTS5_TERM
         || pLeft->eType==FTS5_EOF
         || pLeft->eType==FTS5_AND
     );
-    assert( pRight->eType==FTS5_STRING 
-        || pRight->eType==FTS5_TERM 
-        || pRight->eType==FTS5_EOF 
+    assert( pRight->eType==FTS5_STRING
+        || pRight->eType==FTS5_TERM
+        || pRight->eType==FTS5_EOF
     );
 
     if( pLeft->eType==FTS5_AND ){
@@ -210097,9 +216470,9 @@ static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
     }else{
       pPrev = pLeft;
     }
-    assert( pPrev->eType==FTS5_STRING 
-        || pPrev->eType==FTS5_TERM 
-        || pPrev->eType==FTS5_EOF 
+    assert( pPrev->eType==FTS5_STRING
+        || pPrev->eType==FTS5_TERM
+        || pPrev->eType==FTS5_EOF
         );
 
     if( pRight->eType==FTS5_EOF ){
@@ -210181,20 +216554,20 @@ static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
 }
 
 /*
-** Compose a tcl-readable representation of expression pExpr. Return a 
-** pointer to a buffer containing that representation. It is the 
-** responsibility of the caller to at some point free the buffer using 
+** Compose a tcl-readable representation of expression pExpr. Return a
+** pointer to a buffer containing that representation. It is the
+** responsibility of the caller to at some point free the buffer using
 ** sqlite3_free().
 */
 static char *fts5ExprPrintTcl(
-  Fts5Config *pConfig, 
+  Fts5Config *pConfig,
   const char *zNearsetCmd,
   Fts5ExprNode *pExpr
 ){
   char *zRet = 0;
   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
     Fts5ExprNearset *pNear = pExpr->pNear;
-    int i; 
+    int i;
     int iTerm;
 
     zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
@@ -210244,9 +216617,9 @@ static char *fts5ExprPrintTcl(
     switch( pExpr->eType ){
       case FTS5_AND: zOp = "AND"; break;
       case FTS5_NOT: zOp = "NOT"; break;
-      default: 
+      default:
         assert( pExpr->eType==FTS5_OR );
-        zOp = "OR"; 
+        zOp = "OR";
         break;
     }
 
@@ -210272,12 +216645,21 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
   }else
   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
     Fts5ExprNearset *pNear = pExpr->pNear;
-    int i; 
+    int i;
     int iTerm;
 
     if( pNear->pColset ){
-      int iCol = pNear->pColset->aiCol[0];
-      zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
+      int ii;
+      Fts5Colset *pColset = pNear->pColset;
+      if( pColset->nCol>1 ) zRet = fts5PrintfAppend(zRet, "{");
+      for(ii=0; ii<pColset->nCol; ii++){
+        zRet = fts5PrintfAppend(zRet, "%s%s",
+            pConfig->azCol[pColset->aiCol[ii]], ii==pColset->nCol-1 ? "" : " "
+        );
+      }
+      if( zRet ){
+        zRet = fts5PrintfAppend(zRet, "%s : ", pColset->nCol>1 ? "}" : "");
+      }
       if( zRet==0 ) return 0;
     }
 
@@ -210317,9 +216699,9 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
     switch( pExpr->eType ){
       case FTS5_AND: zOp = " AND "; break;
       case FTS5_NOT: zOp = " NOT "; break;
-      default:  
+      default:
         assert( pExpr->eType==FTS5_OR );
-        zOp = " OR "; 
+        zOp = " OR ";
         break;
     }
 
@@ -210331,7 +216713,7 @@ static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
       }else{
         int e = pExpr->apChild[i]->eType;
         int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
-        zRet = fts5PrintfAppend(zRet, "%s%s%z%s", 
+        zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
             (i==0 ? "" : zOp),
             (b?"(":""), z, (b?")":"")
         );
@@ -210391,14 +216773,16 @@ static void fts5ExprFunction(
   azConfig[1] = "main";
   azConfig[2] = "tbl";
   for(i=3; iArg<nArg; iArg++){
-    azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
+    const char *z = (const char*)sqlite3_value_text(apVal[iArg]);
+    azConfig[i++] = (z ? z : "");
   }
 
   zExpr = (const char*)sqlite3_value_text(apVal[0]);
+  if( zExpr==0 ) zExpr = "";
 
   rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
   if( rc==SQLITE_OK ){
-    rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
+    rc = sqlite3Fts5ExprNew(pConfig, 0, pConfig->nCol, zExpr, &pExpr, &zErr);
   }
   if( rc==SQLITE_OK ){
     char *zText;
@@ -210447,7 +216831,7 @@ static void fts5ExprFunctionTcl(
 
 /*
 ** The implementation of an SQLite user-defined-function that accepts a
-** single integer as an argument. If the integer is an alpha-numeric 
+** single integer as an argument. If the integer is an alpha-numeric
 ** unicode code point, 1 is returned. Otherwise 0.
 */
 static void fts5ExprIsAlnum(
@@ -210458,7 +216842,7 @@ static void fts5ExprIsAlnum(
   int iCode;
   u8 aArr[32];
   if( nArg!=1 ){
-    sqlite3_result_error(pCtx, 
+    sqlite3_result_error(pCtx,
         "wrong number of arguments to function fts5_isalnum", -1
     );
     return;
@@ -210477,7 +216861,7 @@ static void fts5ExprFold(
   sqlite3_value **apVal           /* Function arguments */
 ){
   if( nArg!=1 && nArg!=2 ){
-    sqlite3_result_error(pCtx, 
+    sqlite3_result_error(pCtx,
         "wrong number of arguments to function fts5_fold", -1
     );
   }else{
@@ -210571,7 +216955,7 @@ static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int b
       Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
       Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
       assert( pExpr->apExprPhrase[i]->nTerm==1 );
-      if( bLive && 
+      if( bLive &&
           (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
       ){
         pRet[i].bMiss = 1;
@@ -210638,9 +217022,9 @@ static int fts5ExprPopulatePoslistsCb(
 
 static int sqlite3Fts5ExprPopulatePoslists(
   Fts5Config *pConfig,
-  Fts5Expr *pExpr, 
+  Fts5Expr *pExpr,
   Fts5PoslistPopulator *aPopulator,
-  int iCol, 
+  int iCol,
   const char *z, int n
 ){
   int i;
@@ -210652,7 +217036,7 @@ static int sqlite3Fts5ExprPopulatePoslists(
   for(i=0; i<pExpr->nPhrase; i++){
     Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
     Fts5Colset *pColset = pNode->pNear->pColset;
-    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) 
+    if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
      || aPopulator[i].bMiss
     ){
       aPopulator[i].bOk = 0;
@@ -210661,7 +217045,7 @@ static int sqlite3Fts5ExprPopulatePoslists(
     }
   }
 
-  return sqlite3Fts5Tokenize(pConfig, 
+  return sqlite3Fts5Tokenize(pConfig,
       FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
   );
 }
@@ -210726,12 +217110,12 @@ static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
 }
 
 /*
-** This function is only called for detail=columns tables. 
+** This function is only called for detail=columns tables.
 */
 static int sqlite3Fts5ExprPhraseCollist(
-  Fts5Expr *pExpr, 
-  int iPhrase, 
-  const u8 **ppCollist, 
+  Fts5Expr *pExpr,
+  int iPhrase,
+  const u8 **ppCollist,
   int *pnCollist
 ){
   Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
@@ -210741,8 +217125,8 @@ static int sqlite3Fts5ExprPhraseCollist(
   assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
   assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
 
-  if( pNode->bEof==0 
-   && pNode->iRowid==pExpr->pRoot->iRowid 
+  if( pNode->bEof==0
+   && pNode->iRowid==pExpr->pRoot->iRowid
    && pPhrase->poslist.n>0
   ){
     Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
@@ -210800,9 +217184,9 @@ struct Fts5Hash {
 };
 
 /*
-** Each entry in the hash table is represented by an object of the 
-** following type. Each object, its key (a nul-terminated string) and 
-** its current data are stored in a single memory allocation. The 
+** Each entry in the hash table is represented by an object of the
+** following type. Each object, its key (a nul-terminated string) and
+** its current data are stored in a single memory allocation. The
 ** key immediately follows the object in memory. The position list
 ** data immediately follows the key data in memory.
 **
@@ -210824,7 +217208,7 @@ struct Fts5Hash {
 struct Fts5HashEntry {
   Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
   Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
-  
+
   int nAlloc;                     /* Total size of allocation */
   int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
   int nData;                      /* Total bytes of data (incl. structure) */
@@ -210953,7 +217337,7 @@ static int fts5HashResize(Fts5Hash *pHash){
 }
 
 static int fts5HashAddPoslistSize(
-  Fts5Hash *pHash, 
+  Fts5Hash *pHash,
   Fts5HashEntry *p,
   Fts5HashEntry *p2
 ){
@@ -211016,16 +217400,16 @@ static int sqlite3Fts5HashWrite(
   u8 *pPtr;
   int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
   int bNew;                       /* If non-delete entry should be written */
-  
+
   bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
 
   /* Attempt to locate an existing hash entry */
   iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
   for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
     char *zKey = fts5EntryKey(p);
-    if( zKey[0]==bByte 
+    if( zKey[0]==bByte
      && p->nKey==nToken
-     && memcmp(&zKey[1], pToken, nToken)==0 
+     && memcmp(&zKey[1], pToken, nToken)==0
     ){
       break;
     }
@@ -211071,11 +217455,10 @@ static int sqlite3Fts5HashWrite(
       p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
     }
 
-    nIncr += p->nData;
   }else{
 
-    /* Appending to an existing hash-entry. Check that there is enough 
-    ** space to append the largest possible new entry. Worst case scenario 
+    /* Appending to an existing hash-entry. Check that there is enough
+    ** space to append the largest possible new entry. Worst case scenario
     ** is:
     **
     **     + 9 bytes for a new rowid,
@@ -211104,8 +217487,9 @@ static int sqlite3Fts5HashWrite(
   /* If this is a new rowid, append the 4-byte size field for the previous
   ** entry, and the new rowid for this entry.  */
   if( iRowid!=p->iRowid ){
+    u64 iDiff = (u64)iRowid - (u64)p->iRowid;
     fts5HashAddPoslistSize(pHash, p, 0);
-    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
+    p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iDiff);
     p->iRowid = iRowid;
     bNew = 1;
     p->iSzPoslist = p->nData;
@@ -211203,7 +217587,7 @@ static Fts5HashEntry *fts5HashEntryMerge(
 ** list.
 */
 static int fts5HashEntrySort(
-  Fts5Hash *pHash, 
+  Fts5Hash *pHash,
   const char *pTerm, int nTerm,   /* Query prefix, if any */
   Fts5HashEntry **ppSorted
 ){
@@ -211221,7 +217605,7 @@ static int fts5HashEntrySort(
   for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
     Fts5HashEntry *pIter;
     for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
-      if( pTerm==0 
+      if( pTerm==0
        || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
       ){
         Fts5HashEntry *pEntry = pIter;
@@ -211336,7 +217720,7 @@ static void sqlite3Fts5HashScanEntry(
 **
 ******************************************************************************
 **
-** Low level access to the FTS index stored in the database file. The 
+** Low level access to the FTS index stored in the database file. The
 ** routines in this file file implement all read and write access to the
 ** %_data table. Other parts of the system access this functionality via
 ** the interface defined in fts5Int.h.
@@ -211352,10 +217736,10 @@ static void sqlite3Fts5HashScanEntry(
 ** As well as the main term index, there may be up to 31 prefix indexes.
 ** The format is similar to FTS3/4, except that:
 **
-**   * all segment b-tree leaf data is stored in fixed size page records 
-**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is 
-**     taken to ensure it is possible to iterate in either direction through 
-**     the entries in a doclist, or to seek to a specific entry within a 
+**   * all segment b-tree leaf data is stored in fixed size page records
+**     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
+**     taken to ensure it is possible to iterate in either direction through
+**     the entries in a doclist, or to seek to a specific entry within a
 **     doclist, without loading it into memory.
 **
 **   * large doclists that span many pages have associated "doclist index"
@@ -211388,14 +217772,14 @@ static void sqlite3Fts5HashScanEntry(
 **     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
 **
 ** , contains the following 5 types of records. See the comments surrounding
-** the FTS5_*_ROWID macros below for a description of how %_data rowids are 
+** the FTS5_*_ROWID macros below for a description of how %_data rowids are
 ** assigned to each fo them.
 **
 ** 1. Structure Records:
 **
 **   The set of segments that make up an index - the index structure - are
 **   recorded in a single record within the %_data table. The record consists
-**   of a single 32-bit configuration cookie value followed by a list of 
+**   of a single 32-bit configuration cookie value followed by a list of
 **   SQLite varints. If the FTS table features more than one index (because
 **   there are one or more prefix indexes), it is guaranteed that all share
 **   the same cookie value.
@@ -211427,7 +217811,7 @@ static void sqlite3Fts5HashScanEntry(
 **
 **   TERM/DOCLIST FORMAT:
 **
-**     Most of each segment leaf is taken up by term/doclist data. The 
+**     Most of each segment leaf is taken up by term/doclist data. The
 **     general format of term/doclist, starting with the first term
 **     on the leaf page, is:
 **
@@ -211470,7 +217854,7 @@ static void sqlite3Fts5HashScanEntry(
 **
 **   PAGE FORMAT
 **
-**     Each leaf page begins with a 4-byte header containing 2 16-bit 
+**     Each leaf page begins with a 4-byte header containing 2 16-bit
 **     unsigned integer fields in big-endian format. They are:
 **
 **       * The byte offset of the first rowid on the page, if it exists
@@ -211505,7 +217889,7 @@ static void sqlite3Fts5HashScanEntry(
 ** 5. Segment doclist indexes:
 **
 **   Doclist indexes are themselves b-trees, however they usually consist of
-**   a single leaf record only. The format of each doclist index leaf page 
+**   a single leaf record only. The format of each doclist index leaf page
 **   is:
 **
 **     * Flags byte. Bits are:
@@ -211515,8 +217899,8 @@ static void sqlite3Fts5HashScanEntry(
 **
 **     * First rowid on page indicated by previous field. As a varint.
 **
-**     * A list of varints, one for each subsequent termless page. A 
-**       positive delta if the termless page contains at least one rowid, 
+**     * A list of varints, one for each subsequent termless page. A
+**       positive delta if the termless page contains at least one rowid,
 **       or an 0x00 byte otherwise.
 **
 **   Internal doclist index nodes are:
@@ -211529,7 +217913,7 @@ static void sqlite3Fts5HashScanEntry(
 **     * Copy of first rowid on page indicated by previous field. As a varint.
 **
 **     * A list of delta-encoded varints - the first rowid on each subsequent
-**       child page. 
+**       child page.
 **
 */
 
@@ -211546,7 +217930,7 @@ static void sqlite3Fts5HashScanEntry(
 **
 ** Each segment has a unique non-zero 16-bit id.
 **
-** The rowid for each segment leaf is found by passing the segment id and 
+** The rowid for each segment leaf is found by passing the segment id and
 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
 ** sequentially starting from 1.
 */
@@ -211565,11 +217949,6 @@ static void sqlite3Fts5HashScanEntry(
 #define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
 
-/*
-** Maximum segments permitted in a single index 
-*/
-#define FTS5_MAX_SEGMENT 2000
-
 #ifdef SQLITE_DEBUG
 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
 #endif
@@ -211648,7 +218027,7 @@ struct Fts5DoclistIter {
 
 /*
 ** The contents of the "structure" record for each index are represented
-** using an Fts5Structure record in memory. Which uses instances of the 
+** using an Fts5Structure record in memory. Which uses instances of the
 ** other Fts5StructureXXX types as components.
 */
 struct Fts5StructureSegment {
@@ -211721,10 +218100,10 @@ struct Fts5CResult {
 **   Current leaf page number within segment.
 **
 ** iLeafOffset:
-**   Byte offset within the current leaf that is the first byte of the 
+**   Byte offset within the current leaf that is the first byte of the
 **   position list data (one byte passed the position-list size field).
 **   rowid field of the current entry. Usually this is the size field of the
-**   position list data. The exception is if the rowid for the current entry 
+**   position list data. The exception is if the rowid for the current entry
 **   is the last thing on the leaf page.
 **
 ** pLeaf:
@@ -211738,7 +218117,7 @@ struct Fts5CResult {
 **   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
 **
 **   FTS5_SEGITER_ONETERM:
-**     If set, set the iterator to point to EOF after the current doclist 
+**     If set, set the iterator to point to EOF after the current doclist
 **     has been exhausted. Do not proceed to the next term in the segment.
 **
 **   FTS5_SEGITER_REVERSE:
@@ -211767,7 +218146,7 @@ struct Fts5SegIter {
   /* Next method */
   void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
 
-  /* The page and offset from which the current term was read. The offset 
+  /* The page and offset from which the current term was read. The offset
   ** is the offset of the first rowid in the current doclist.  */
   int iTermLeafPgno;
   int iTermLeafOffset;
@@ -211790,7 +218169,7 @@ struct Fts5SegIter {
 };
 
 /*
-** Argument is a pointer to an Fts5Data structure that contains a 
+** Argument is a pointer to an Fts5Data structure that contains a
 ** leaf page.
 */
 #define ASSERT_SZLEAF_OK(x) assert( \
@@ -211800,7 +218179,7 @@ struct Fts5SegIter {
 #define FTS5_SEGITER_ONETERM 0x01
 #define FTS5_SEGITER_REVERSE 0x02
 
-/* 
+/*
 ** Argument is a pointer to an Fts5Data structure that contains a leaf
 ** page. This macro evaluates to true if the leaf contains no terms, or
 ** false if it contains at least one term.
@@ -211822,13 +218201,13 @@ struct Fts5SegIter {
 ** on empty segments.
 **
 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
-** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the 
+** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
 ** comparison in this context is the index of the iterator that currently
 ** points to the smaller term/rowid combination. Iterators at EOF are
 ** considered to be greater than all other iterators.
 **
 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
-** the smallest key overall. aFirst[0] is unused. 
+** the smallest key overall. aFirst[0] is unused.
 **
 ** poslist:
 **   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
@@ -211890,7 +218269,7 @@ static void fts5PutU16(u8 *aOut, u16 iVal){
 
 static u16 fts5GetU16(const u8 *aIn){
   return ((u16)aIn[0] << 8) + aIn[1];
-} 
+}
 
 /*
 ** Allocate and return a buffer at least nByte bytes in size.
@@ -211945,7 +218324,7 @@ static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
 /*
 ** Close the read-only blob handle, if it is open.
 */
-static void fts5CloseReader(Fts5Index *p){
+static void sqlite3Fts5IndexCloseReader(Fts5Index *p){
   if( p->pReader ){
     sqlite3_blob *pReader = p->pReader;
     p->pReader = 0;
@@ -211956,7 +218335,7 @@ static void fts5CloseReader(Fts5Index *p){
 /*
 ** Retrieve a record from the %_data table.
 **
-** If an error occurs, NULL is returned and an error left in the 
+** If an error occurs, NULL is returned and an error left in the
 ** Fts5Index object.
 */
 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
@@ -211974,16 +218353,16 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
       assert( p->pReader==0 );
       p->pReader = pBlob;
       if( rc!=SQLITE_OK ){
-        fts5CloseReader(p);
+        sqlite3Fts5IndexCloseReader(p);
       }
       if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
     }
 
-    /* If the blob handle is not open at this point, open it and seek 
+    /* If the blob handle is not open at this point, open it and seek
     ** to the requested entry.  */
     if( p->pReader==0 && rc==SQLITE_OK ){
       Fts5Config *pConfig = p->pConfig;
-      rc = sqlite3_blob_open(pConfig->db, 
+      rc = sqlite3_blob_open(pConfig->db,
           pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
       );
     }
@@ -211991,7 +218370,7 @@ static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
     /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
     ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
     ** All the reasons those functions might return SQLITE_ERROR - missing
-    ** table, missing row, non-blob/text in block column - indicate 
+    ** table, missing row, non-blob/text in block column - indicate
     ** backing store corruption.  */
     if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
 
@@ -212076,7 +218455,7 @@ static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
   if( p->pWriter==0 ){
     Fts5Config *pConfig = p->pConfig;
     fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
-          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", 
+          "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
           pConfig->zDb, pConfig->zName
     ));
     if( p->rc ) return;
@@ -212100,7 +218479,7 @@ static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
   if( p->pDeleter==0 ){
     Fts5Config *pConfig = p->pConfig;
     char *zSql = sqlite3_mprintf(
-        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", 
+        "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
           pConfig->zDb, pConfig->zName
     );
     if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
@@ -212134,7 +218513,7 @@ static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
 }
 
 /*
-** Release a reference to an Fts5Structure object returned by an earlier 
+** Release a reference to an Fts5Structure object returned by an earlier
 ** call to fts5StructureRead() or fts5StructureDecode().
 */
 static void fts5StructureRelease(Fts5Structure *pStruct){
@@ -212214,7 +218593,7 @@ static int fts5StructureDecode(
         i += fts5GetVarint32(&pData[i], pLvl->nMerge);
         i += fts5GetVarint32(&pData[i], nTotal);
         if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
-        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, 
+        pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
             nTotal * sizeof(Fts5StructureSegment)
         );
         nSegment -= nTotal;
@@ -212280,10 +218659,10 @@ static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
 ** segments.
 */
 static void fts5StructureExtendLevel(
-  int *pRc, 
-  Fts5Structure *pStruct, 
-  int iLvl, 
-  int nExtra, 
+  int *pRc,
+  Fts5Structure *pStruct,
+  int iLvl,
+  int nExtra,
   int bInsert
 ){
   if( *pRc==SQLITE_OK ){
@@ -212337,7 +218716,7 @@ static i64 fts5IndexDataVersion(Fts5Index *p){
 
   if( p->rc==SQLITE_OK ){
     if( p->pDataVersion==0 ){
-      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, 
+      p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
           sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
           );
       if( p->rc ) return 0;
@@ -212356,7 +218735,7 @@ static i64 fts5IndexDataVersion(Fts5Index *p){
 ** Read, deserialize and return the structure record.
 **
 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
-** are over-allocated as described for function fts5StructureDecode() 
+** are over-allocated as described for function fts5StructureDecode()
 ** above.
 **
 ** If an error occurs, NULL is returned and an error code left in the
@@ -212505,8 +218884,8 @@ static int fts5SegmentSize(Fts5StructureSegment *pSeg){
 }
 
 /*
-** Return a copy of index structure pStruct. Except, promote as many 
-** segments as possible to level iPromote. If an OOM occurs, NULL is 
+** Return a copy of index structure pStruct. Except, promote as many
+** segments as possible to level iPromote. If an OOM occurs, NULL is
 ** returned.
 */
 static void fts5StructurePromoteTo(
@@ -212546,8 +218925,8 @@ static void fts5StructurePromoteTo(
 **
 **   b) If the segment just written is larger than the newest segment on
 **      the next populated level, then that segment, and any other adjacent
-**      segments that are also smaller than the one just written, are 
-**      promoted. 
+**      segments that are also smaller than the one just written, are
+**      promoted.
 **
 ** If one or more segments are promoted, the structure object is updated
 ** to reflect this.
@@ -212581,7 +218960,7 @@ static void fts5StructurePromote(
         if( sz>szMax ) szMax = sz;
       }
       if( szMax>=szSeg ){
-        /* Condition (a) is true. Promote the newest segment on level 
+        /* Condition (a) is true. Promote the newest segment on level
         ** iLvl to level iTst.  */
         iPromote = iTst;
         szPromote = szMax;
@@ -212600,7 +218979,7 @@ static void fts5StructurePromote(
 
 
 /*
-** Advance the iterator passed as the only argument. If the end of the 
+** Advance the iterator passed as the only argument. If the end of the
 ** doclist-index page is reached, return non-zero.
 */
 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
@@ -212615,7 +218994,7 @@ static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
   }else{
     int iOff;
     for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
-      if( pData->p[iOff] ) break; 
+      if( pData->p[iOff] ) break;
     }
 
     if( iOff<pData->nn ){
@@ -212645,7 +219024,7 @@ static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
       if( pLvl[1].bEof==0 ){
         fts5DataRelease(pLvl->pData);
         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
-        pLvl->pData = fts5DataRead(p, 
+        pLvl->pData = fts5DataRead(p,
             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
         );
         if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
@@ -212665,7 +219044,7 @@ static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
 ** points to the first rowid in the doclist-index.
 **
 **   pData:
-**     pointer to doclist-index record, 
+**     pointer to doclist-index record,
 **
 ** When this function is called pIter->iLeafPgno is the page number the
 ** doclist is associated with (the one featuring the term).
@@ -212696,7 +219075,7 @@ static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
       Fts5DlidxLvl *pChild = &pLvl[-1];
       fts5DataRelease(pChild->pData);
       memset(pChild, 0, sizeof(Fts5DlidxLvl));
-      pChild->pData = fts5DataRead(p, 
+      pChild->pData = fts5DataRead(p,
           FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
       );
     }
@@ -212719,8 +219098,8 @@ static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
     int ii;
     int nZero = 0;
 
-    /* Currently iOff points to the first byte of a varint. This block 
-    ** decrements iOff until it points to the first byte of the previous 
+    /* Currently iOff points to the first byte of a varint. This block
+    ** decrements iOff until it points to the first byte of the previous
     ** varint. Taking care not to read any memory locations that occur
     ** before the buffer in memory.  */
     iLimit = (iOff>9 ? iOff-9 : 0);
@@ -212765,7 +219144,7 @@ static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
       if( pLvl[1].bEof==0 ){
         fts5DataRelease(pLvl->pData);
         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
-        pLvl->pData = fts5DataRead(p, 
+        pLvl->pData = fts5DataRead(p,
             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
         );
         if( pLvl->pData ){
@@ -212864,7 +219243,7 @@ static void fts5SegIterNextPage(
     pIter->pLeaf = pIter->pNextLeaf;
     pIter->pNextLeaf = 0;
   }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
-    pIter->pLeaf = fts5LeafRead(p, 
+    pIter->pLeaf = fts5LeafRead(p,
         FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
     );
   }else{
@@ -212908,7 +219287,7 @@ static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
 **   Fts5SegIter.nPos
 **   Fts5SegIter.bDel
 **
-** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the 
+** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
 ** position list content (if any).
 */
 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
@@ -212959,7 +219338,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
 }
 
 /*
-** Fts5SegIter.iLeafOffset currently points to the first byte of the 
+** Fts5SegIter.iLeafOffset currently points to the first byte of the
 ** "nSuffix" field of a term. Function parameter nKeep contains the value
 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
 ** the first term in the segment).
@@ -212970,7 +219349,7 @@ static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
 **   Fts5SegIter.rowid
 **
 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
-** the first position list. The position list belonging to document 
+** the first position list. The position list belonging to document
 ** (Fts5SegIter.iRowid).
 */
 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
@@ -213018,10 +219397,10 @@ static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
 
 /*
 ** Initialize the iterator object pIter to iterate through the entries in
-** segment pSeg. The iterator is left pointing to the first entry when 
+** segment pSeg. The iterator is left pointing to the first entry when
 ** this function returns.
 **
-** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
 ** an error has already occurred when this function is called, it is a no-op.
 */
 static void fts5SegIterInit(
@@ -213066,8 +219445,8 @@ static void fts5SegIterInit(
 ** the position-list size field for the first relevant rowid on the page.
 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
 **
-** This function advances the iterator so that it points to the last 
-** relevant rowid on the page and, if necessary, initializes the 
+** This function advances the iterator so that it points to the last
+** relevant rowid on the page and, if necessary, initializes the
 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
 ** byte of the position list content associated with said rowid.
@@ -213085,7 +219464,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
 
   ASSERT_SZLEAF_OK(pIter->pLeaf);
   while( 1 ){
-    i64 iDelta = 0;
+    u64 iDelta = 0;
 
     if( eDetail==FTS5_DETAIL_NONE ){
       /* todo */
@@ -213100,7 +219479,7 @@ static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
       i += nPos;
     }
     if( i>=n ) break;
-    i += fts5GetVarint(&a[i], (u64*)&iDelta);
+    i += fts5GetVarint(&a[i], &iDelta);
     pIter->iRowid += iDelta;
 
     /* If necessary, grow the pIter->aRowidOffset[] array. */
@@ -213199,7 +219578,7 @@ static void fts5SegIterNext_Reverse(
   if( pIter->iRowidOffset>0 ){
     u8 *a = pIter->pLeaf->p;
     int iOff;
-    i64 iDelta;
+    u64 iDelta;
 
     pIter->iRowidOffset--;
     pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
@@ -213208,7 +219587,7 @@ static void fts5SegIterNext_Reverse(
     if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
       iOff += pIter->nPos;
     }
-    fts5GetVarint(&a[iOff], (u64*)&iDelta);
+    fts5GetVarint(&a[iOff], &iDelta);
     pIter->iRowid -= iDelta;
   }else{
     fts5SegIterReverseNewPage(p, pIter);
@@ -213287,10 +219666,10 @@ static void fts5SegIterNext_None(
 
 
 /*
-** Advance iterator pIter to the next entry. 
+** Advance iterator pIter to the next entry.
 **
-** If an error occurs, Fts5Index.rc is set to an appropriate error code. It 
-** is not considered an error if the iterator reaches EOF. If an error has 
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
+** is not considered an error if the iterator reaches EOF. If an error has
 ** already occurred when this function is called, it is a no-op.
 */
 static void fts5SegIterNext(
@@ -213401,7 +219780,7 @@ static void fts5SegIterNext(
     }else{
       /* The following could be done by calling fts5SegIterLoadNPos(). But
       ** this block is particularly performance critical, so equivalent
-      ** code is inlined. 
+      ** code is inlined.
       **
       ** Later: Switched back to fts5SegIterLoadNPos() because it supports
       ** detail=none mode. Not ideal.
@@ -213481,7 +219860,7 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
   }
 
   /* If pLast is NULL at this point, then the last rowid for this doclist
-  ** lies on the page currently indicated by the iterator. In this case 
+  ** lies on the page currently indicated by the iterator. In this case
   ** pIter->iLeafOffset is already set to point to the position-list size
   ** field associated with the first relevant rowid on the page.
   **
@@ -213511,8 +219890,8 @@ static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
 
 /*
 ** Iterator pIter currently points to the first rowid of a doclist.
-** There is a doclist-index associated with the final term on the current 
-** page. If the current term is the last term on the page, load the 
+** There is a doclist-index associated with the final term on the current
+** page. If the current term is the last term on the page, load the
 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
 */
 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
@@ -213526,8 +219905,8 @@ static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
   /* Check if the current doclist ends on this page. If it does, return
   ** early without loading the doclist-index (as it belongs to a different
   ** term. */
-  if( pIter->iTermLeafPgno==pIter->iLeafPgno 
-   && pIter->iEndofDoclist<pLeaf->szLeaf 
+  if( pIter->iTermLeafPgno==pIter->iLeafPgno
+   && pIter->iEndofDoclist<pLeaf->szLeaf
   ){
     return;
   }
@@ -213652,11 +220031,11 @@ static void fts5LeafSeek(
   }
 
  search_success:
-  pIter->iLeafOffset = iOff + nNew;
-  if( pIter->iLeafOffset>n || nNew<1 ){
+  if( (i64)iOff+nNew>n || nNew<1 ){
     p->rc = FTS5_CORRUPT;
     return;
   }
+  pIter->iLeafOffset = iOff + nNew;
   pIter->iTermLeafOffset = pIter->iLeafOffset;
   pIter->iTermLeafPgno = pIter->iLeafPgno;
 
@@ -213692,7 +220071,7 @@ static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
 ** Initialize the object pIter to point to term pTerm/nTerm within segment
 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
 **
-** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
 ** an error has already occurred when this function is called, it is a no-op.
 */
 static void fts5SegIterSeekInit(
@@ -213772,10 +220151,10 @@ static void fts5SegIterSeekInit(
 
 /*
 ** Initialize the object pIter to point to term pTerm/nTerm within the
-** in-memory hash table. If there is no such term in the hash-table, the 
+** in-memory hash table. If there is no such term in the hash-table, the
 ** iterator is set to EOF.
 **
-** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
+** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
 ** an error has already occurred when this function is called, it is a no-op.
 */
 static void fts5SegIterHashInit(
@@ -213805,7 +220184,7 @@ static void fts5SegIterHashInit(
       }
     }
   }else{
-    p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data), 
+    p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
         (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
     );
     if( pLeaf ){
@@ -213855,7 +220234,7 @@ static void fts5SegIterClear(Fts5SegIter *pIter){
 ** two iterators.
 */
 static void fts5AssertComparisonResult(
-  Fts5Iter *pIter, 
+  Fts5Iter *pIter,
   Fts5SegIter *p1,
   Fts5SegIter *p2,
   Fts5CResult *pRes
@@ -213892,7 +220271,7 @@ static void fts5AssertComparisonResult(
 
 /*
 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
-** is compiled. In that case, this function is essentially an assert() 
+** is compiled. In that case, this function is essentially an assert()
 ** statement used to verify that the contents of the pIter->aFirst[] array
 ** are correct.
 */
@@ -213906,9 +220285,9 @@ static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
     /* Check that pIter->iSwitchRowid is set correctly. */
     for(i=0; i<pIter->nSeg; i++){
       Fts5SegIter *p1 = &pIter->aSeg[i];
-      assert( p1==pFirst 
-           || p1->pLeaf==0 
-           || fts5BufferCompare(&pFirst->term, &p1->term) 
+      assert( p1==pFirst
+           || p1->pLeaf==0
+           || fts5BufferCompare(&pFirst->term, &p1->term)
            || p1->iRowid==pIter->iSwitchRowid
            || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
       );
@@ -213938,7 +220317,7 @@ static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
 **
 ** If the returned value is non-zero, then it is the index of an entry
 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
-** to a key that is a duplicate of another, higher priority, 
+** to a key that is a duplicate of another, higher priority,
 ** segment-iterator in the pSeg->aSeg[] array.
 */
 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
@@ -214029,7 +220408,7 @@ static void fts5SegIterGotoPage(
 }
 
 /*
-** Advance the iterator passed as the second argument until it is at or 
+** Advance the iterator passed as the second argument until it is at or
 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
 ** always advanced at least once.
 */
@@ -214125,7 +220504,7 @@ static void fts5MultiIterAdvanced(
 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
 ** on the iterator instead. That function does the same as this one, except
 ** that it deals with more complicated cases as well.
-*/ 
+*/
 static int fts5MultiIterAdvanceRowid(
   Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
   int iChanged,                   /* Index of sub-iterator just advanced */
@@ -214176,14 +220555,14 @@ static void fts5MultiIterSetEof(Fts5Iter *pIter){
 }
 
 /*
-** Move the iterator to the next entry. 
+** Move the iterator to the next entry.
 **
-** If an error occurs, an error code is left in Fts5Index.rc. It is not 
-** considered an error if the iterator reaches EOF, or if it is already at 
+** If an error occurs, an error code is left in Fts5Index.rc. It is not
+** considered an error if the iterator reaches EOF, or if it is already at
 ** EOF when this function is called.
 */
 static void fts5MultiIterNext(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5Iter *pIter,
   int bFrom,                      /* True if argument iFrom is valid */
   i64 iFrom                       /* Advance at least as far as this */
@@ -214201,7 +220580,7 @@ static void fts5MultiIterNext(
       pSeg->xNext(p, pSeg, &bNewTerm);
     }
 
-    if( pSeg->pLeaf==0 || bNewTerm 
+    if( pSeg->pLeaf==0 || bNewTerm
      || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
     ){
       fts5MultiIterAdvanced(p, pIter, iFirst, 1);
@@ -214221,7 +220600,7 @@ static void fts5MultiIterNext(
 }
 
 static void fts5MultiIterNext2(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5Iter *pIter,
   int *pbNewTerm                  /* OUT: True if *might* be new term */
 ){
@@ -214235,7 +220614,7 @@ static void fts5MultiIterNext2(
 
       assert( p->rc==SQLITE_OK );
       pSeg->xNext(p, pSeg, &bNewTerm);
-      if( pSeg->pLeaf==0 || bNewTerm 
+      if( pSeg->pLeaf==0 || bNewTerm
        || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
       ){
         fts5MultiIterAdvanced(p, pIter, iFirst, 1);
@@ -214260,7 +220639,7 @@ static Fts5Iter *fts5MultiIterAlloc(
   int nSlot;                      /* Power of two >= nSeg */
 
   for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
-  pNew = fts5IdxMalloc(p, 
+  pNew = fts5IdxMalloc(p,
       sizeof(Fts5Iter) +                  /* pNew */
       sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
       sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
@@ -214275,8 +220654,8 @@ static Fts5Iter *fts5MultiIterAlloc(
 }
 
 static void fts5PoslistCallback(
-  Fts5Index *pUnused, 
-  void *pContext, 
+  Fts5Index *pUnused,
+  void *pContext,
   const u8 *pChunk, int nChunk
 ){
   UNUSED_PARAM(pUnused);
@@ -214313,8 +220692,8 @@ static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
 }
 
 static void fts5PoslistOffsetsCallback(
-  Fts5Index *pUnused, 
-  void *pContext, 
+  Fts5Index *pUnused,
+  void *pContext,
   const u8 *pChunk, int nChunk
 ){
   PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
@@ -214337,7 +220716,7 @@ static void fts5PoslistOffsetsCallback(
 
 static void fts5PoslistFilterCallback(
   Fts5Index *pUnused,
-  void *pContext, 
+  void *pContext,
   const u8 *pChunk, int nChunk
 ){
   PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
@@ -214482,7 +220861,7 @@ static int fts5IndexExtractCol(
   while( iCol>iCurrent ){
     /* Advance pointer p until it points to pEnd or an 0x01 byte that is
     ** not part of a varint. Note that it is not possible for a negative
-    ** or extremely large varint to occur within an uncorrupted position 
+    ** or extremely large varint to occur within an uncorrupted position
     ** list. So the last byte of each varint may be assumed to have a clear
     ** 0x80 bit.  */
     while( *p!=0x01 ){
@@ -214547,7 +220926,7 @@ static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
   assert( pIter->pColset==0 );
 
   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
-    /* All data is stored on the current page. Populate the output 
+    /* All data is stored on the current page. Populate the output
     ** variables to point into the body of the page object. */
     pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
   }else{
@@ -214583,13 +220962,13 @@ static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
 }
 
 /*
-** xSetOutputs callback used when: 
+** xSetOutputs callback used when:
 **
 **   * detail=col,
 **   * there is a column filter, and
-**   * the table contains 100 or fewer columns. 
+**   * the table contains 100 or fewer columns.
 **
-** The last point is to ensure all column numbers are stored as 
+** The last point is to ensure all column numbers are stored as
 ** single-byte varints.
 */
 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
@@ -214601,7 +220980,7 @@ static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
     fts5IterSetOutputs_Col(pIter, pSeg);
   }else{
     u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
-    u8 *pEnd = (u8*)&a[pSeg->nPos]; 
+    u8 *pEnd = (u8*)&a[pSeg->nPos];
     int iPrev = 0;
     int *aiCol = pIter->pColset->aiCol;
     int *aiColEnd = &aiCol[pIter->pColset->nCol];
@@ -214640,7 +221019,7 @@ static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
   assert( pColset );
 
   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
-    /* All data is stored on the current page. Populate the output 
+    /* All data is stored on the current page. Populate the output
     ** variables to point into the body of the page object. */
     const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
     if( pColset->nCol==1 ){
@@ -214704,7 +221083,7 @@ static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
 ** is zero or greater, data from the first nSegment segments on level iLevel
 ** is merged.
 **
-** The iterator initially points to the first term/rowid entry in the 
+** The iterator initially points to the first term/rowid entry in the
 ** iterated data.
 */
 static void fts5MultiIterNew(
@@ -214773,8 +221152,8 @@ static void fts5MultiIterNew(
     assert( iIter==nSeg );
   }
 
-  /* If the above was successful, each component iterators now points 
-  ** to the first entry in its segment. In this case initialize the 
+  /* If the above was successful, each component iterators now points
+  ** to the first entry in its segment. In this case initialize the
   ** aFirst[] array. Or, if an error has occurred, free the iterator
   ** object and set the output variable to NULL.  */
   if( p->rc==SQLITE_OK ){
@@ -214843,12 +221222,12 @@ static void fts5MultiIterNew2(
 }
 
 /*
-** Return true if the iterator is at EOF or if an error has occurred. 
+** Return true if the iterator is at EOF or if an error has occurred.
 ** False otherwise.
 */
 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
-  assert( p->rc 
-      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof 
+  assert( p->rc
+      || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
   );
   return (p->rc || pIter->base.bEof);
 }
@@ -214867,8 +221246,8 @@ static i64 fts5MultiIterRowid(Fts5Iter *pIter){
 ** Move the iterator to the next entry at or following iMatch.
 */
 static void fts5MultiIterNextFrom(
-  Fts5Index *p, 
-  Fts5Iter *pIter, 
+  Fts5Index *p,
+  Fts5Iter *pIter,
   i64 iMatch
 ){
   while( 1 ){
@@ -214882,7 +221261,7 @@ static void fts5MultiIterNextFrom(
 }
 
 /*
-** Return a pointer to a buffer containing the term associated with the 
+** Return a pointer to a buffer containing the term associated with the
 ** entry that the iterator currently points to.
 */
 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
@@ -214893,11 +221272,11 @@ static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
 
 /*
 ** Allocate a new segment-id for the structure pStruct. The new segment
-** id must be between 1 and 65335 inclusive, and must not be used by 
+** id must be between 1 and 65335 inclusive, and must not be used by
 ** any currently existing segment. If a free segment id cannot be found,
 ** SQLITE_FULL is returned.
 **
-** If an error has already occurred, this function is a no-op. 0 is 
+** If an error has already occurred, this function is a no-op. 0 is
 ** returned in this case.
 */
 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
@@ -214966,10 +221345,10 @@ static void fts5IndexDiscardData(Fts5Index *p){
 }
 
 /*
-** Return the size of the prefix, in bytes, that buffer 
+** Return the size of the prefix, in bytes, that buffer
 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
 **
-** Buffer (pNew/<length-unknown>) is guaranteed to be greater 
+** Buffer (pNew/<length-unknown>) is guaranteed to be greater
 ** than buffer (pOld/nOld).
 */
 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
@@ -214981,7 +221360,7 @@ static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
 }
 
 static void fts5WriteDlidxClear(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5SegWriter *pWriter,
   int bFlush                      /* If true, write dlidx to disk */
 ){
@@ -214992,7 +221371,7 @@ static void fts5WriteDlidxClear(
     if( pDlidx->buf.n==0 ) break;
     if( bFlush ){
       assert( pDlidx->pgno!=0 );
-      fts5DataWrite(p, 
+      fts5DataWrite(p,
           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
           pDlidx->buf.p, pDlidx->buf.n
       );
@@ -215046,8 +221425,8 @@ static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
 }
 
 /*
-** This function is called whenever processing of the doclist for the 
-** last term on leaf page (pWriter->iBtPage) is completed. 
+** This function is called whenever processing of the doclist for the
+** last term on leaf page (pWriter->iBtPage) is completed.
 **
 ** The doclist-index for that term is currently stored in-memory within the
 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
@@ -215132,8 +221511,8 @@ static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
 ** doclist-index.
 */
 static void fts5WriteDlidxAppend(
-  Fts5Index *p, 
-  Fts5SegWriter *pWriter, 
+  Fts5Index *p,
+  Fts5SegWriter *pWriter,
   i64 iRowid
 ){
   int i;
@@ -215146,11 +221525,11 @@ static void fts5WriteDlidxAppend(
     if( pDlidx->buf.n>=p->pConfig->pgsz ){
       /* The current doclist-index page is full. Write it to disk and push
       ** a copy of iRowid (which will become the first rowid on the next
-      ** doclist-index leaf page) up into the next level of the b-tree 
+      ** doclist-index leaf page) up into the next level of the b-tree
       ** hierarchy. If the node being flushed is currently the root node,
       ** also push its first rowid upwards. */
       pDlidx->buf.p[0] = 0x01;    /* Not the root node */
-      fts5DataWrite(p, 
+      fts5DataWrite(p,
           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
           pDlidx->buf.p, pDlidx->buf.n
       );
@@ -215234,13 +221613,13 @@ static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
 ** Append term pTerm/nTerm to the segment being written by the writer passed
 ** as the second argument.
 **
-** If an error occurs, set the Fts5Index.rc error code. If an error has 
+** If an error occurs, set the Fts5Index.rc error code. If an error has
 ** already occurred, this function is a no-op.
 */
 static void fts5WriteAppendTerm(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5SegWriter *pWriter,
-  int nTerm, const u8 *pTerm 
+  int nTerm, const u8 *pTerm
 ){
   int nPrefix;                    /* Bytes of prefix compression for term */
   Fts5PageWriter *pPage = &pWriter->writer;
@@ -215259,7 +221638,7 @@ static void fts5WriteAppendTerm(
     }
     fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
   }
-  
+
   /* TODO1: Updating pgidx here. */
   pPgidx->n += sqlite3Fts5PutVarint(
       &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
@@ -215275,11 +221654,11 @@ static void fts5WriteAppendTerm(
     if( pPage->pgno!=1 ){
       /* This is the first term on a leaf that is not the leftmost leaf in
       ** the segment b-tree. In this case it is necessary to add a term to
-      ** the b-tree hierarchy that is (a) larger than the largest term 
+      ** the b-tree hierarchy that is (a) larger than the largest term
       ** already written to the segment and (b) smaller than or equal to
       ** this term. In other words, a prefix of (pTerm/nTerm) that is one
       ** byte longer than the longest prefix (pTerm/nTerm) shares with the
-      ** previous term. 
+      ** previous term.
       **
       ** Usually, the previous term is available in pPage->term. The exception
       ** is if this is the first term written in an incremental-merge step.
@@ -215316,10 +221695,10 @@ static void fts5WriteAppendTerm(
 }
 
 /*
-** Append a rowid and position-list size field to the writers output. 
+** Append a rowid and position-list size field to the writers output.
 */
 static void fts5WriteAppendRowid(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5SegWriter *pWriter,
   i64 iRowid
 ){
@@ -215330,7 +221709,7 @@ static void fts5WriteAppendRowid(
       fts5WriteFlushLeaf(p, pWriter);
     }
 
-    /* If this is to be the first rowid written to the page, set the 
+    /* If this is to be the first rowid written to the page, set the
     ** rowid-pointer in the page-header. Also append a value to the dlidx
     ** buffer, in case a doclist-index is required.  */
     if( pWriter->bFirstRowidInPage ){
@@ -215352,18 +221731,18 @@ static void fts5WriteAppendRowid(
 }
 
 static void fts5WriteAppendPoslistData(
-  Fts5Index *p, 
-  Fts5SegWriter *pWriter, 
-  const u8 *aData, 
+  Fts5Index *p,
+  Fts5SegWriter *pWriter,
+  const u8 *aData,
   int nData
 ){
   Fts5PageWriter *pPage = &pWriter->writer;
   const u8 *a = aData;
   int n = nData;
-  
+
   assert( p->pConfig->pgsz>0 );
-  while( p->rc==SQLITE_OK 
-     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz 
+  while( p->rc==SQLITE_OK
+     && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
   ){
     int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
     int nCopy = 0;
@@ -215386,7 +221765,7 @@ static void fts5WriteAppendPoslistData(
 ** allocations associated with the writer.
 */
 static void fts5WriteFinish(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5SegWriter *pWriter,         /* Writer object */
   int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
 ){
@@ -215414,8 +221793,8 @@ static void fts5WriteFinish(
 }
 
 static void fts5WriteInit(
-  Fts5Index *p, 
-  Fts5SegWriter *pWriter, 
+  Fts5Index *p,
+  Fts5SegWriter *pWriter,
   int iSegid
 ){
   const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
@@ -215438,7 +221817,7 @@ static void fts5WriteInit(
   if( p->pIdxWriter==0 ){
     Fts5Config *pConfig = p->pConfig;
     fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
-          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", 
+          "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
           pConfig->zDb, pConfig->zName
     ));
   }
@@ -215504,13 +221883,13 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
 
           /* Set up the new page-index array */
           fts5BufferAppendVarint(&p->rc, &buf, 4);
-          if( pSeg->iLeafPgno==pSeg->iTermLeafPgno 
+          if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
            && pSeg->iEndofDoclist<pData->szLeaf
            && pSeg->iPgidxOff<=pData->nn
           ){
             int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
             fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
-            fts5BufferAppendBlob(&p->rc, &buf, 
+            fts5BufferAppendBlob(&p->rc, &buf,
                 pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
             );
           }
@@ -215527,8 +221906,8 @@ static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
 }
 
 static void fts5MergeChunkCallback(
-  Fts5Index *p, 
-  void *pCtx, 
+  Fts5Index *p,
+  void *pCtx,
   const u8 *pChunk, int nChunk
 ){
   Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
@@ -215743,7 +222122,7 @@ static int fts5IndexMerge(
 ** segment. This function updates the write-counter accordingly and, if
 ** necessary, performs incremental merge work.
 **
-** If an error occurs, set the Fts5Index.rc error code. If an error has 
+** If an error occurs, set the Fts5Index.rc error code. If an error has
 ** already occurred, this function is a no-op.
 */
 static void fts5IndexAutomerge(
@@ -215794,12 +222173,12 @@ static int fts5IndexReturn(Fts5Index *p){
 typedef struct Fts5FlushCtx Fts5FlushCtx;
 struct Fts5FlushCtx {
   Fts5Index *pIdx;
-  Fts5SegWriter writer; 
+  Fts5SegWriter writer;
 };
 
 /*
 ** Buffer aBuf[] contains a list of varints, all small enough to fit
-** in a 32-bit integer. Return the size of the largest prefix of this 
+** in a 32-bit integer. Return the size of the largest prefix of this
 ** list nMax bytes or less in size.
 */
 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
@@ -215817,10 +222196,10 @@ static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
 }
 
 /*
-** Flush the contents of in-memory hash table iHash to a new level-0 
+** Flush the contents of in-memory hash table iHash to a new level-0
 ** segment on disk. Also update the corresponding structure record.
 **
-** If an error occurs, set the Fts5Index.rc error code. If an error has 
+** If an error occurs, set the Fts5Index.rc error code. If an error has
 ** already occurred, this function is a no-op.
 */
 static void fts5FlushOneHash(Fts5Index *p){
@@ -215877,13 +222256,13 @@ static void fts5FlushOneHash(Fts5Index *p){
         i64 iDelta = 0;
         int iOff = 0;
 
-        /* The entire doclist will not fit on this leaf. The following 
-        ** loop iterates through the poslists that make up the current 
+        /* The entire doclist will not fit on this leaf. The following
+        ** loop iterates through the poslists that make up the current
         ** doclist.  */
         while( p->rc==SQLITE_OK && iOff<nDoclist ){
           iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
           iRowid += iDelta;
-          
+
           if( writer.bFirstRowidInPage ){
             fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
             pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
@@ -215987,7 +222366,7 @@ static void fts5IndexFlush(Fts5Index *p){
 }
 
 static Fts5Structure *fts5IndexOptimizeStruct(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5Structure *pStruct
 ){
   Fts5Structure *pNew = 0;
@@ -215998,7 +222377,7 @@ static Fts5Structure *fts5IndexOptimizeStruct(
   /* Figure out if this structure requires optimization. A structure does
   ** not require optimization if either:
   **
-  **  + it consists of fewer than two segments, or 
+  **  + it consists of fewer than two segments, or
   **  + all segments are on the same level, or
   **  + all segments except one are currently inputs to a merge operation.
   **
@@ -216075,7 +222454,7 @@ static int sqlite3Fts5IndexOptimize(Fts5Index *p){
     fts5StructureRelease(pNew);
   }
 
-  return fts5IndexReturn(p); 
+  return fts5IndexReturn(p);
 }
 
 /*
@@ -216159,7 +222538,7 @@ static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
 }
 
 static void fts5DoclistIterInit(
-  Fts5Buffer *pBuf, 
+  Fts5Buffer *pBuf,
   Fts5DoclistIter *pIter
 ){
   memset(pIter, 0, sizeof(*pIter));
@@ -216275,17 +222654,17 @@ static void fts5MergePrefixLists(
     Fts5Buffer out = {0, 0, 0};
     Fts5Buffer tmp = {0, 0, 0};
 
-    /* The maximum size of the output is equal to the sum of the two 
+    /* The maximum size of the output is equal to the sum of the two
     ** input sizes + 1 varint (9 bytes). The extra varint is because if the
     ** first rowid in one input is a large negative number, and the first in
     ** the other a non-negative number, the delta for the non-negative
     ** number will be larger on disk than the literal integer value
-    ** was.  
+    ** was.
     **
     ** Or, if the input position-lists are corrupt, then the output might
     ** include up to 2 extra 10-byte positions created by interpreting -1
     ** (the value PoslistNext64() uses for EOF) as a position and appending
-    ** it to the output. This can happen at most once for each input 
+    ** it to the output. This can happen at most once for each input
     ** position-list, hence two 10 byte paddings.  */
     if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return;
     fts5DoclistIterInit(p1, &i1);
@@ -216309,7 +222688,7 @@ static void fts5MergePrefixLists(
         assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
       }
       else{
-        /* Merge the two position lists. */ 
+        /* Merge the two position lists. */
         i64 iPos1 = 0;
         i64 iPos2 = 0;
         int iOff1 = 0;
@@ -216328,7 +222707,9 @@ static void fts5MergePrefixLists(
         ** at most 20 bytes of unexpected space. */
         fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
         fts5BufferZero(&tmp);
-        sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist + 10 + 10);
+        sqlite3Fts5BufferSize(&p->rc, &tmp,
+            i1.nPoslist + i2.nPoslist + 10 + 10 + FTS5_DATA_ZERO_PADDING
+        );
         if( p->rc ) break;
 
         sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
@@ -216402,9 +222783,10 @@ static void fts5MergePrefixLists(
     }
     assert_nc( out.n<=(p1->n+p2->n+9) );
 
-    fts5BufferSet(&p->rc, p1, out.n, out.p);
+    fts5BufferFree(p1);
     fts5BufferFree(&tmp);
-    fts5BufferFree(&out);
+    memset(&out.p[out.n], 0, FTS5_DATA_ZERO_PADDING);
+    *p1 = out;
   }
 }
 
@@ -216434,8 +222816,8 @@ static void fts5SetupPrefixIter(
   pStruct = fts5StructureRead(p);
 
   if( aBuf && pStruct ){
-    const int flags = FTS5INDEX_QUERY_SCAN 
-                    | FTS5INDEX_QUERY_SKIPEMPTY 
+    const int flags = FTS5INDEX_QUERY_SCAN
+                    | FTS5INDEX_QUERY_SKIPEMPTY
                     | FTS5INDEX_QUERY_NOOUTPUT;
     int i;
     i64 iLastRowid = 0;
@@ -216517,9 +222899,9 @@ static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
   }
 
   /* Flush the hash table to disk if required */
-  if( iRowid<p->iWriteRowid 
+  if( iRowid<p->iWriteRowid
    || (iRowid==p->iWriteRowid && p->bDelete==0)
-   || (p->nPendingData > p->pConfig->nHashSize) 
+   || (p->nPendingData > p->pConfig->nHashSize)
   ){
     fts5IndexFlush(p);
   }
@@ -216535,18 +222917,18 @@ static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
 static int sqlite3Fts5IndexSync(Fts5Index *p){
   assert( p->rc==SQLITE_OK );
   fts5IndexFlush(p);
-  fts5CloseReader(p);
+  sqlite3Fts5IndexCloseReader(p);
   return fts5IndexReturn(p);
 }
 
 /*
 ** Discard any data stored in the in-memory hash tables. Do not write it
 ** to the database. Additionally, assume that the contents of the %_data
-** table may have changed on disk. So any in-memory caches of %_data 
+** table may have changed on disk. So any in-memory caches of %_data
 ** records must be invalidated.
 */
 static int sqlite3Fts5IndexRollback(Fts5Index *p){
-  fts5CloseReader(p);
+  sqlite3Fts5IndexCloseReader(p);
   fts5IndexDiscardData(p);
   fts5StructureInvalidate(p);
   /* assert( p->rc==SQLITE_OK ); */
@@ -216561,6 +222943,7 @@ static int sqlite3Fts5IndexRollback(Fts5Index *p){
 static int sqlite3Fts5IndexReinit(Fts5Index *p){
   Fts5Structure s;
   fts5StructureInvalidate(p);
+  fts5IndexDiscardData(p);
   memset(&s, 0, sizeof(Fts5Structure));
   fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
   fts5StructureWrite(p, &s);
@@ -216575,8 +222958,8 @@ static int sqlite3Fts5IndexReinit(Fts5Index *p){
 ** Otherwise, set *pp to NULL and return an SQLite error code.
 */
 static int sqlite3Fts5IndexOpen(
-  Fts5Config *pConfig, 
-  int bCreate, 
+  Fts5Config *pConfig,
+  int bCreate,
   Fts5Index **pp,
   char **pzErr
 ){
@@ -216593,8 +222976,8 @@ static int sqlite3Fts5IndexOpen(
           pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
       );
       if( rc==SQLITE_OK ){
-        rc = sqlite3Fts5CreateTable(pConfig, "idx", 
-            "segid, term, pgno, PRIMARY KEY(segid, term)", 
+        rc = sqlite3Fts5CreateTable(pConfig, "idx",
+            "segid, term, pgno, PRIMARY KEY(segid, term)",
             1, pzErr
         );
       }
@@ -216634,13 +223017,13 @@ static int sqlite3Fts5IndexClose(Fts5Index *p){
 }
 
 /*
-** Argument p points to a buffer containing utf-8 text that is n bytes in 
+** Argument p points to a buffer containing utf-8 text that is n bytes in
 ** size. Return the number of bytes in the nChar character prefix of the
 ** buffer, or 0 if there are less than nChar characters in total.
 */
 static int sqlite3Fts5IndexCharlenToBytelen(
-  const char *p, 
-  int nByte, 
+  const char *p,
+  int nByte,
   int nChar
 ){
   int n = 0;
@@ -216648,9 +223031,13 @@ static int sqlite3Fts5IndexCharlenToBytelen(
   for(i=0; i<nChar; i++){
     if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
     if( (unsigned char)p[n++]>=0xc0 ){
+      if( n>=nByte ) return 0;
       while( (p[n] & 0xc0)==0x80 ){
         n++;
-        if( n>=nByte ) break;
+        if( n>=nByte ){
+          if( i+1==nChar ) break;
+          return 0;
+        }
       }
     }
   }
@@ -216662,7 +223049,7 @@ static int sqlite3Fts5IndexCharlenToBytelen(
 ** unicode characters in the string.
 */
 static int fts5IndexCharlen(const char *pIn, int nIn){
-  int nChar = 0;            
+  int nChar = 0;
   int i = 0;
   while( i<nIn ){
     if( (unsigned char)pIn[i++]>=0xc0 ){
@@ -216674,7 +223061,7 @@ static int fts5IndexCharlen(const char *pIn, int nIn){
 }
 
 /*
-** Insert or remove data to or from the index. Each time a document is 
+** Insert or remove data to or from the index. Each time a document is
 ** added to or removed from the index, this function is called one or more
 ** times.
 **
@@ -216705,7 +223092,7 @@ static int sqlite3Fts5IndexWrite(
     const int nChar = pConfig->aPrefix[i];
     int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
     if( nByte ){
-      rc = sqlite3Fts5HashWrite(p->pHash, 
+      rc = sqlite3Fts5HashWrite(p->pHash,
           p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
           nByte
       );
@@ -216716,7 +223103,7 @@ static int sqlite3Fts5IndexWrite(
 }
 
 /*
-** Open a new iterator to iterate though all rowid that match the 
+** Open a new iterator to iterate though all rowid that match the
 ** specified token or token prefix.
 */
 static int sqlite3Fts5IndexQuery(
@@ -216743,9 +223130,9 @@ static int sqlite3Fts5IndexQuery(
     ** satisfied by scanning multiple terms in the main index.
     **
     ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
-    ** prefix-query. Instead of using a prefix-index (if one exists), 
+    ** prefix-query. Instead of using a prefix-index (if one exists),
     ** evaluate the prefix query using the main FTS index. This is used
-    ** for internal sanity checking by the integrity-check in debug 
+    ** for internal sanity checking by the integrity-check in debug
     ** mode only.  */
 #ifdef SQLITE_DEBUG
     if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
@@ -216765,7 +223152,7 @@ static int sqlite3Fts5IndexQuery(
       Fts5Structure *pStruct = fts5StructureRead(p);
       buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
       if( pStruct ){
-        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, 
+        fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
             pColset, buf.p, nToken+1, -1, 0, &pRet
         );
         fts5StructureRelease(pStruct);
@@ -216786,7 +223173,7 @@ static int sqlite3Fts5IndexQuery(
     if( p->rc ){
       sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
       pRet = 0;
-      fts5CloseReader(p);
+      sqlite3Fts5IndexCloseReader(p);
     }
 
     *ppIter = (Fts5IndexIter*)pRet;
@@ -216799,7 +223186,7 @@ static int sqlite3Fts5IndexQuery(
 ** Return true if the iterator passed as the only argument is at EOF.
 */
 /*
-** Move to the next matching rowid. 
+** Move to the next matching rowid.
 */
 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
@@ -216859,12 +223246,12 @@ static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
     Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
     Fts5Index *pIndex = pIter->pIndex;
     fts5MultiIterFree(pIter);
-    fts5CloseReader(pIndex);
+    sqlite3Fts5IndexCloseReader(pIndex);
   }
 }
 
 /*
-** Read and decode the "averages" record from the database. 
+** Read and decode the "averages" record from the database.
 **
 ** Parameter anSize must point to an array of size nCol, where nCol is
 ** the number of user defined columns in the FTS table.
@@ -216890,7 +223277,7 @@ static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
 }
 
 /*
-** Replace the current "averages" record with the contents of the buffer 
+** Replace the current "averages" record with the contents of the buffer
 ** supplied as the second argument.
 */
 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
@@ -216908,7 +223295,7 @@ static int sqlite3Fts5IndexReads(Fts5Index *p){
 }
 
 /*
-** Set the 32-bit cookie value stored at the start of all structure 
+** Set the 32-bit cookie value stored at the start of all structure
 ** records to the value passed as the second argument.
 **
 ** Return SQLITE_OK if successful, or an SQLite error code if an error
@@ -216923,7 +223310,7 @@ static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
   assert( p->rc==SQLITE_OK );
   sqlite3Fts5Put32(aCookie, iNew);
 
-  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, 
+  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
       "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
   );
   if( rc==SQLITE_OK ){
@@ -216944,7 +223331,7 @@ static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
 
 /*************************************************************************
 **************************************************************************
-** Below this point is the implementation of the integrity-check 
+** Below this point is the implementation of the integrity-check
 ** functionality.
 */
 
@@ -216952,9 +223339,9 @@ static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
 ** Return a simple checksum value based on the arguments.
 */
 static u64 sqlite3Fts5IndexEntryCksum(
-  i64 iRowid, 
-  int iCol, 
-  int iPos, 
+  i64 iRowid,
+  int iCol,
+  int iPos,
   int iIdx,
   const char *pTerm,
   int nTerm
@@ -216970,15 +223357,15 @@ static u64 sqlite3Fts5IndexEntryCksum(
 
 #ifdef SQLITE_DEBUG
 /*
-** This function is purely an internal test. It does not contribute to 
+** This function is purely an internal test. It does not contribute to
 ** FTS functionality, or even the integrity-check, in any way.
 **
-** Instead, it tests that the same set of pgno/rowid combinations are 
+** Instead, it tests that the same set of pgno/rowid combinations are
 ** visited regardless of whether the doclist-index identified by parameters
 ** iSegid/iLeaf is iterated in forwards or reverse order.
 */
 static void fts5TestDlidxReverse(
-  Fts5Index *p, 
+  Fts5Index *p,
   int iSegid,                     /* Segment id to load from */
   int iLeaf                       /* Load doclist-index for this leaf */
 ){
@@ -217052,13 +223439,44 @@ static int fts5QueryCksum(
   return rc;
 }
 
+/*
+** Check if buffer z[], size n bytes, contains as series of valid utf-8
+** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
+** contain valid utf-8, return non-zero.
+*/
+static int fts5TestUtf8(const char *z, int n){
+  int i = 0;
+  assert_nc( n>0 );
+  while( i<n ){
+    if( (z[i] & 0x80)==0x00 ){
+      i++;
+    }else
+    if( (z[i] & 0xE0)==0xC0 ){
+      if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
+      i += 2;
+    }else
+    if( (z[i] & 0xF0)==0xE0 ){
+      if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
+      i += 3;
+    }else
+    if( (z[i] & 0xF8)==0xF0 ){
+      if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
+      if( (z[i+2] & 0xC0)!=0x80 ) return 1;
+      i += 3;
+    }else{
+      return 1;
+    }
+  }
+
+  return 0;
+}
 
 /*
-** This function is also purely an internal test. It does not contribute to 
+** This function is also purely an internal test. It does not contribute to
 ** FTS functionality, or even the integrity-check, in any way.
 */
 static void fts5TestTerm(
-  Fts5Index *p, 
+  Fts5Index *p,
   Fts5Buffer *pPrev,              /* Previous term */
   const char *z, int n,           /* Possibly new term to test */
   u64 expected,
@@ -217087,13 +223505,19 @@ static void fts5TestTerm(
     if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
 
     /* If this is a prefix query, check that the results returned if the
-    ** the index is disabled are the same. In both ASC and DESC order. 
+    ** the index is disabled are the same. In both ASC and DESC order.
     **
     ** This check may only be performed if the hash table is empty. This
     ** is because the hash table only supports a single scan query at
     ** a time, and the multi-iter loop from which this function is called
-    ** is already performing such a scan. */
-    if( p->nPendingData==0 ){
+    ** is already performing such a scan.
+    **
+    ** Also only do this if buffer zTerm contains nTerm bytes of valid
+    ** utf-8. Otherwise, the last part of the buffer contents might contain
+    ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
+    ** character stored in the main fts index, which will cause the
+    ** test to fail.  */
+    if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
       if( iIdx>0 && rc==SQLITE_OK ){
         int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
         ck2 = 0;
@@ -217118,7 +223542,7 @@ static void fts5TestTerm(
   }
   p->rc = rc;
 }
+
 #else
 # define fts5TestDlidxReverse(x,y,z)
 # define fts5TestTerm(u,v,w,x,y,z)
@@ -217226,12 +223650,12 @@ static void fts5IndexIntegrityCheckSegment(
     i64 iRow;                     /* Rowid for this leaf */
     Fts5Data *pLeaf;              /* Data for this leaf */
 
+    const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
     int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
-    const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
     int iIdxLeaf = sqlite3_column_int(pStmt, 2);
     int bIdxDlidx = sqlite3_column_int(pStmt, 3);
 
-    /* If the leaf in question has already been trimmed from the segment, 
+    /* If the leaf in question has already been trimmed from the segment,
     ** ignore this b-tree entry. Otherwise, load it into memory. */
     if( iIdxLeaf<pSeg->pgnoFirst ) continue;
     iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
@@ -217339,7 +223763,7 @@ static void fts5IndexIntegrityCheckSegment(
 
 
 /*
-** Run internal checks to ensure that the FTS index (a) is internally 
+** Run internal checks to ensure that the FTS index (a) is internally
 ** consistent and (b) contains entries for which the XOR of the checksums
 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
 **
@@ -217348,7 +223772,7 @@ static void fts5IndexIntegrityCheckSegment(
 ** error, or some other SQLite error code if another error (e.g. OOM)
 ** occurs.
 */
-static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
+static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum, int bUseCksum){
   int eDetail = p->pConfig->eDetail;
   u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
   Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
@@ -217361,7 +223785,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
   Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
 #endif
   const int flags = FTS5INDEX_QUERY_NOOUTPUT;
-  
+
   /* Load the FTS index structure */
   pStruct = fts5StructureRead(p);
 
@@ -217383,7 +223807,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
   **
   ** Two versions of the same checksum are calculated. The first (stack
   ** variable cksum2) based on entries extracted from the full-text index
-  ** while doing a linear scan of each individual index in turn. 
+  ** while doing a linear scan of each individual index in turn.
   **
   ** As each term visited by the linear scans, a separate query for the
   ** same term is performed. cksum3 is calculated based on the entries
@@ -217409,6 +223833,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
     }else{
       poslist.n = 0;
       fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
+      fts5BufferAppendBlob(&p->rc, &poslist, 4, (const u8*)"\0\0\0\0");
       while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
         int iCol = FTS5_POS2COLUMN(iPos);
         int iTokOff = FTS5_POS2OFFSET(iPos);
@@ -217419,7 +223844,7 @@ static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
   fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
 
   fts5MultiIterFree(pIter);
-  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
+  if( p->rc==SQLITE_OK && bUseCksum && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
 
   fts5StructureRelease(pStruct);
 #ifdef SQLITE_DEBUG
@@ -217485,12 +223910,12 @@ static void fts5DebugStructure(
 
   for(iLvl=0; iLvl<p->nLevel; iLvl++){
     Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
-    sqlite3Fts5BufferAppendPrintf(pRc, pBuf, 
+    sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
         " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
     );
     for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
       Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
-      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", 
+      sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
           pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
       );
     }
@@ -217503,7 +223928,7 @@ static void fts5DebugStructure(
 **
 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
 ** function appends a human-readable representation of the same object
-** to the buffer passed as the second argument. 
+** to the buffer passed as the second argument.
 */
 static void fts5DecodeStructure(
   int *pRc,                       /* IN/OUT: error code */
@@ -217526,9 +223951,9 @@ static void fts5DecodeStructure(
 /*
 ** This is part of the fts5_decode() debugging aid.
 **
-** Arguments pBlob/nBlob contain an "averages" record. This function 
-** appends a human-readable representation of record to the buffer passed 
-** as the second argument. 
+** Arguments pBlob/nBlob contain an "averages" record. This function
+** appends a human-readable representation of record to the buffer passed
+** as the second argument.
 */
 static void fts5DecodeAverages(
   int *pRc,                       /* IN/OUT: error code */
@@ -217567,7 +223992,7 @@ static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
 ** The start of buffer (a/n) contains the start of a doclist. The doclist
 ** may or may not finish within the buffer. This function appends a text
 ** representation of the part of the doclist that is present to buffer
-** pBuf. 
+** pBuf.
 **
 ** The return value is the number of bytes read from the input buffer.
 */
@@ -217597,7 +224022,7 @@ static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
 }
 
 /*
-** This function is part of the fts5_decode() debugging function. It is 
+** This function is part of the fts5_decode() debugging function. It is
 ** only ever used with detail=none tables.
 **
 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
@@ -217684,7 +224109,7 @@ static void fts5DecodeFunction(
     lvl.iLeafPgno = iPgno;
 
     for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
-      sqlite3Fts5BufferAppendPrintf(&rc, &s, 
+      sqlite3Fts5BufferAppendPrintf(&rc, &s,
           " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
       );
     }
@@ -217795,7 +224220,7 @@ static void fts5DecodeFunction(
       int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
       int nByte;                            /* Bytes of data */
       int iEnd;
-      
+
       iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
       iPgidxPrev += nByte;
       iOff = iPgidxPrev;
@@ -217835,7 +224260,7 @@ static void fts5DecodeFunction(
 
     fts5BufferFree(&term);
   }
-  
+
  decode_out:
   sqlite3_free(a);
   if( rc==SQLITE_OK ){
@@ -217863,7 +224288,7 @@ static void fts5RowidFunction(
       i64 iRowid;
       int segid, pgno;
       if( nArg!=3 ){
-        sqlite3_result_error(pCtx, 
+        sqlite3_result_error(pCtx,
             "should be: fts5_rowid('segment', segid, pgno))", -1
         );
       }else{
@@ -217873,7 +224298,7 @@ static void fts5RowidFunction(
         sqlite3_result_int64(pCtx, iRowid);
       }
     }else{
-      sqlite3_result_error(pCtx, 
+      sqlite3_result_error(pCtx,
         "first arg to fts5_rowid() must be 'segment'" , -1
       );
     }
@@ -217895,7 +224320,7 @@ static int sqlite3Fts5IndexInit(sqlite3 *db){
 
   if( rc==SQLITE_OK ){
     rc = sqlite3_create_function(
-        db, "fts5_decode_none", 2, 
+        db, "fts5_decode_none", 2,
         SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
     );
   }
@@ -217954,9 +224379,9 @@ typedef struct Fts5Sorter Fts5Sorter;
 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
 
 /*
-** NOTES ON TRANSACTIONS: 
+** NOTES ON TRANSACTIONS:
 **
-** SQLite invokes the following virtual table methods as transactions are 
+** SQLite invokes the following virtual table methods as transactions are
 ** opened and closed by the user:
 **
 **     xBegin():    Start of a new transaction.
@@ -217965,7 +224390,7 @@ typedef struct Fts5TokenizerModule Fts5TokenizerModule;
 **     xRollback(): Rollback the transaction.
 **
 ** Anything that is required as part of a commit that may fail is performed
-** in the xSync() callback. Current versions of SQLite ignore any errors 
+** in the xSync() callback. Current versions of SQLite ignore any errors
 ** returned by xCommit().
 **
 ** And as sub-transactions are opened/closed:
@@ -217974,9 +224399,9 @@ typedef struct Fts5TokenizerModule Fts5TokenizerModule;
 **     xRelease(int S):    Commit and close savepoint S.
 **     xRollbackTo(int S): Rollback to start of savepoint S.
 **
-** During a write-transaction the fts5_index.c module may cache some data 
+** During a write-transaction the fts5_index.c module may cache some data
 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
-** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() 
+** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
 ** is called.
 **
 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
@@ -217990,13 +224415,13 @@ struct Fts5TransactionState {
 };
 
 /*
-** A single object of this type is allocated when the FTS5 module is 
+** A single object of this type is allocated when the FTS5 module is
 ** registered with a database handle. It is used to store pointers to
 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
 */
 struct Fts5Global {
   fts5_api api;                   /* User visible part of object (see fts5.h) */
-  sqlite3 *db;                    /* Associated database connection */ 
+  sqlite3 *db;                    /* Associated database connection */
   i64 iNextId;                    /* Used to allocate unique cursor ids */
   Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
   Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
@@ -218052,7 +224477,7 @@ struct Fts5MatchPhrase {
 **
 ** aIdx[]:
 **   There is one entry in the aIdx[] array for each phrase in the query,
-**   the value of which is the offset within aPoslist[] following the last 
+**   the value of which is the offset within aPoslist[] following the last
 **   byte of the position list for the corresponding phrase.
 */
 struct Fts5Sorter {
@@ -218068,8 +224493,8 @@ struct Fts5Sorter {
 ** Virtual-table cursor object.
 **
 ** iSpecial:
-**   If this is a 'special' query (refer to function fts5SpecialMatch()), 
-**   then this variable contains the result of the query. 
+**   If this is a 'special' query (refer to function fts5SpecialMatch()),
+**   then this variable contains the result of the query.
 **
 ** iFirstRowid, iLastRowid:
 **   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
@@ -218120,7 +224545,7 @@ struct Fts5Cursor {
 };
 
 /*
-** Bits that make up the "idxNum" parameter passed indirectly by 
+** Bits that make up the "idxNum" parameter passed indirectly by
 ** xBestIndex() to xFilter().
 */
 #define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
@@ -218199,7 +224624,7 @@ static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
       assert( iSavepoint>=p->ts.iSavepoint );
       p->ts.iSavepoint = iSavepoint;
       break;
-      
+
     case FTS5_RELEASE:
       assert( p->ts.eState==1 );
       assert( iSavepoint>=0 );
@@ -218210,7 +224635,10 @@ static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
     case FTS5_ROLLBACKTO:
       assert( p->ts.eState==1 );
       assert( iSavepoint>=-1 );
-      assert( iSavepoint<=p->ts.iSavepoint );
+      /* The following assert() can fail if another vtab strikes an error
+      ** within an xSavepoint() call then SQLite calls xRollbackTo() - without
+      ** having called xSavepoint() on this vtab.  */
+      /* assert( iSavepoint<=p->ts.iSavepoint ); */
       p->ts.iSavepoint = iSavepoint;
       break;
   }
@@ -218227,7 +224655,7 @@ static int fts5IsContentless(Fts5FullTable *pTab){
 }
 
 /*
-** Delete a virtual table handle allocated by fts5InitVtab(). 
+** Delete a virtual table handle allocated by fts5InitVtab().
 */
 static void fts5FreeVtab(Fts5FullTable *pTab){
   if( pTab ){
@@ -218382,8 +224810,25 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
 #endif
 }
 
+static int fts5UsePatternMatch(
+  Fts5Config *pConfig,
+  struct sqlite3_index_constraint *p
+){
+  assert( FTS5_PATTERN_GLOB==SQLITE_INDEX_CONSTRAINT_GLOB );
+  assert( FTS5_PATTERN_LIKE==SQLITE_INDEX_CONSTRAINT_LIKE );
+  if( pConfig->ePattern==FTS5_PATTERN_GLOB && p->op==FTS5_PATTERN_GLOB ){
+    return 1;
+  }
+  if( pConfig->ePattern==FTS5_PATTERN_LIKE
+   && (p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB)
+  ){
+    return 1;
+  }
+  return 0;
+}
+
 /*
-** Implementation of the xBestIndex method for FTS5 tables. Within the 
+** Implementation of the xBestIndex method for FTS5 tables. Within the
 ** WHERE constraint, it searches for the following:
 **
 **   1. A MATCH constraint against the table column.
@@ -218398,7 +224843,7 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
 **   5. ORDER BY rank [ASC|DESC]
 **   6. ORDER BY rowid [ASC|DESC]
 **
-** Information for the xFilter call is passed via both the idxNum and 
+** Information for the xFilter call is passed via both the idxNum and
 ** idxStr variables. Specifically, idxNum is a bitmask of the following
 ** flags used to encode the ORDER BY clause:
 **
@@ -218411,7 +224856,9 @@ static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
 **
 **   Match against table column:            "m"
 **   Match against rank column:             "r"
-**   Match against other column:            "<column-number>"
+**   Match against other column:            "M<column-number>"
+**   LIKE  against other column:            "L<column-number>"
+**   GLOB  against other column:            "G<column-number>"
 **   Equality constraint against the rowid: "="
 **   A < or <= against the rowid:           "<"
 **   A > or >= against the rowid:           ">"
@@ -218472,7 +224919,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
     return SQLITE_ERROR;
   }
 
-  idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 6 + 1);
+  idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 8 + 1);
   if( idxStr==0 ) return SQLITE_NOMEM;
   pInfo->idxStr = idxStr;
   pInfo->needToFreeIdxStr = 1;
@@ -218485,7 +224932,7 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
     ){
       /* A MATCH operator or equivalent */
       if( p->usable==0 || iCol<0 ){
-        /* As there exists an unusable MATCH constraint this is an 
+        /* As there exists an unusable MATCH constraint this is an
         ** unusable plan. Set a prohibitively high cost. */
         pInfo->estimatedCost = 1e50;
         assert( iIdxStr < pInfo->nConstraint*6 + 1 );
@@ -218496,25 +224943,29 @@ static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
           if( bSeenRank ) continue;
           idxStr[iIdxStr++] = 'r';
           bSeenRank = 1;
-        }else{
+        }else if( iCol>=0 ){
           bSeenMatch = 1;
-          idxStr[iIdxStr++] = 'm';
-          if( iCol<nCol ){
-            sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
-            idxStr += strlen(&idxStr[iIdxStr]);
-            assert( idxStr[iIdxStr]=='\0' );
-          }
+          idxStr[iIdxStr++] = 'M';
+          sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
+          idxStr += strlen(&idxStr[iIdxStr]);
+          assert( idxStr[iIdxStr]=='\0' );
         }
         pInfo->aConstraintUsage[i].argvIndex = ++iCons;
         pInfo->aConstraintUsage[i].omit = 1;
       }
-    }
-    else if( p->usable && bSeenEq==0 
-      && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 
-    ){
-      idxStr[iIdxStr++] = '=';
-      bSeenEq = 1;
-      pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+    }else if( p->usable ){
+      if( iCol>=0 && iCol<nCol && fts5UsePatternMatch(pConfig, p) ){
+        assert( p->op==FTS5_PATTERN_LIKE || p->op==FTS5_PATTERN_GLOB );
+        idxStr[iIdxStr++] = p->op==FTS5_PATTERN_LIKE ? 'L' : 'G';
+        sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
+        idxStr += strlen(&idxStr[iIdxStr]);
+        pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+        assert( idxStr[iIdxStr]=='\0' );
+      }else if( bSeenEq==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0 ){
+        idxStr[iIdxStr++] = '=';
+        bSeenEq = 1;
+        pInfo->aConstraintUsage[i].argvIndex = ++iCons;
+      }
     }
   }
 
@@ -218618,15 +225069,15 @@ static int fts5StmtType(Fts5Cursor *pCsr){
 
 /*
 ** This function is called after the cursor passed as the only argument
-** is moved to point at a different row. It clears all cached data 
+** is moved to point at a different row. It clears all cached data
 ** specific to the previous row stored by the cursor object.
 */
 static void fts5CsrNewrow(Fts5Cursor *pCsr){
-  CsrFlagSet(pCsr, 
-      FTS5CSR_REQUIRE_CONTENT 
-    | FTS5CSR_REQUIRE_DOCSIZE 
-    | FTS5CSR_REQUIRE_INST 
-    | FTS5CSR_REQUIRE_POSLIST 
+  CsrFlagSet(pCsr,
+      FTS5CSR_REQUIRE_CONTENT
+    | FTS5CSR_REQUIRE_DOCSIZE
+    | FTS5CSR_REQUIRE_INST
+    | FTS5CSR_REQUIRE_POSLIST
   );
 }
 
@@ -218665,6 +225116,7 @@ static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
     sqlite3_free(pCsr->zRankArgs);
   }
 
+  sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
   memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
 }
 
@@ -218729,14 +225181,14 @@ static int fts5SorterNext(Fts5Cursor *pCsr){
 
 
 /*
-** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors 
+** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
 ** open on table pTab.
 */
 static void fts5TripCursors(Fts5FullTable *pTab){
   Fts5Cursor *pCsr;
   for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
     if( pCsr->ePlan==FTS5_PLAN_MATCH
-     && pCsr->base.pVtab==(sqlite3_vtab*)pTab 
+     && pCsr->base.pVtab==(sqlite3_vtab*)pTab
     ){
       CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
     }
@@ -218745,14 +225197,14 @@ static void fts5TripCursors(Fts5FullTable *pTab){
 
 /*
 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
-** argument, close and reopen all Fts5IndexIter iterators that the cursor 
+** argument, close and reopen all Fts5IndexIter iterators that the cursor
 ** is using. Then attempt to move the cursor to a rowid equal to or laster
-** (in the cursors sort order - ASC or DESC) than the current rowid. 
+** (in the cursors sort order - ASC or DESC) than the current rowid.
 **
 ** If the new rowid is not equal to the old, set output parameter *pbSkip
 ** to 1 before returning. Otherwise, leave it unchanged.
 **
-** Return SQLITE_OK if successful or if no reseek was required, or an 
+** Return SQLITE_OK if successful or if no reseek was required, or an
 ** error code if an error occurred.
 */
 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
@@ -218780,7 +225232,7 @@ static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
 
 
 /*
-** Advance the cursor to the next row in the table that matches the 
+** Advance the cursor to the next row in the table that matches the
 ** search criteria.
 **
 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
@@ -218792,7 +225244,7 @@ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
   int rc;
 
   assert( (pCsr->ePlan<3)==
-          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) 
+          (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
   );
   assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
 
@@ -218809,31 +225261,40 @@ static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
         rc = SQLITE_OK;
         break;
       }
-  
+
       case FTS5_PLAN_SORTED_MATCH: {
         rc = fts5SorterNext(pCsr);
         break;
       }
-  
-      default:
+
+      default: {
+        Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;
+        pConfig->bLock++;
         rc = sqlite3_step(pCsr->pStmt);
+        pConfig->bLock--;
         if( rc!=SQLITE_ROW ){
           CsrFlagSet(pCsr, FTS5CSR_EOF);
           rc = sqlite3_reset(pCsr->pStmt);
+          if( rc!=SQLITE_OK ){
+            pCursor->pVtab->zErrMsg = sqlite3_mprintf(
+                "%s", sqlite3_errmsg(pConfig->db)
+            );
+          }
         }else{
           rc = SQLITE_OK;
         }
         break;
+      }
     }
   }
-  
+
   return rc;
 }
 
 
 static int fts5PrepareStatement(
   sqlite3_stmt **ppStmt,
-  Fts5Config *pConfig, 
+  Fts5Config *pConfig,
   const char *zFmt,
   ...
 ){
@@ -218845,9 +225306,9 @@ static int fts5PrepareStatement(
   va_start(ap, zFmt);
   zSql = sqlite3_vmprintf(zFmt, ap);
   if( zSql==0 ){
-    rc = SQLITE_NOMEM; 
+    rc = SQLITE_NOMEM;
   }else{
-    rc = sqlite3_prepare_v3(pConfig->db, zSql, -1, 
+    rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
                             SQLITE_PREPARE_PERSISTENT, &pRet, 0);
     if( rc!=SQLITE_OK ){
       *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
@@ -218858,11 +225319,11 @@ static int fts5PrepareStatement(
   va_end(ap);
   *ppStmt = pRet;
   return rc;
-} 
+}
 
 static int fts5CursorFirstSorted(
-  Fts5FullTable *pTab, 
-  Fts5Cursor *pCsr, 
+  Fts5FullTable *pTab,
+  Fts5Cursor *pCsr,
   int bDesc
 ){
   Fts5Config *pConfig = pTab->p.pConfig;
@@ -218872,7 +225333,7 @@ static int fts5CursorFirstSorted(
   int rc;
   const char *zRank = pCsr->zRank;
   const char *zRankArgs = pCsr->zRankArgs;
-  
+
   nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
   pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
@@ -218883,7 +225344,7 @@ static int fts5CursorFirstSorted(
   /* TODO: It would be better to have some system for reusing statement
   ** handles here, rather than preparing a new one for each query. But that
   ** is not possible as SQLite reference counts the virtual table objects.
-  ** And since the statement required here reads from this very virtual 
+  ** And since the statement required here reads from this very virtual
   ** table, saving it creates a circular reference.
   **
   ** If SQLite a built-in statement cache, this wouldn't be a problem. */
@@ -218930,8 +225391,8 @@ static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
 ** parameters.
 */
 static int fts5SpecialMatch(
-  Fts5FullTable *pTab, 
-  Fts5Cursor *pCsr, 
+  Fts5FullTable *pTab,
+  Fts5Cursor *pCsr,
   const char *zQuery
 ){
   int rc = SQLITE_OK;             /* Return code */
@@ -219029,7 +225490,7 @@ static int fts5FindRankFunction(Fts5Cursor *pCsr){
 
 static int fts5CursorParseRank(
   Fts5Config *pConfig,
-  Fts5Cursor *pCsr, 
+  Fts5Cursor *pCsr,
   sqlite3_value *pRank
 ){
   int rc = SQLITE_OK;
@@ -219078,7 +225539,7 @@ static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
 ** This is the xFilter interface for the virtual table.  See
 ** the virtual table xFilter method documentation for additional
 ** information.
-** 
+**
 ** There are three possible query strategies:
 **
 **   1. Full-text search using a MATCH operator.
@@ -219108,6 +225569,13 @@ static int fts5FilterMethod(
   int iIdxStr = 0;
   Fts5Expr *pExpr = 0;
 
+  if( pConfig->bLock ){
+    pTab->p.base.zErrMsg = sqlite3_mprintf(
+        "recursively defined fts5 content table"
+    );
+    return SQLITE_ERROR;
+  }
+
   if( pCsr->ePlan ){
     fts5FreeCursorComponents(pCsr);
     memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
@@ -219130,19 +225598,14 @@ static int fts5FilterMethod(
       case 'r':
         pRank = apVal[i];
         break;
-      case 'm': {
+      case 'M': {
         const char *zText = (const char*)sqlite3_value_text(apVal[i]);
         if( zText==0 ) zText = "";
-
-        if( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' ){
-          iCol = 0;
-          do{
-            iCol = iCol*10 + (idxStr[iIdxStr]-'0');
-            iIdxStr++;
-          }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
-        }else{
-          iCol = pConfig->nCol;
-        }
+        iCol = 0;
+        do{
+          iCol = iCol*10 + (idxStr[iIdxStr]-'0');
+          iIdxStr++;
+        }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
 
         if( zText[0]=='*' ){
           /* The user has issued a query of the form "MATCH '*...'". This
@@ -219152,7 +225615,7 @@ static int fts5FilterMethod(
           goto filter_out;
         }else{
           char **pzErr = &pTab->p.base.zErrMsg;
-          rc = sqlite3Fts5ExprNew(pConfig, iCol, zText, &pExpr, pzErr);
+          rc = sqlite3Fts5ExprNew(pConfig, 0, iCol, zText, &pExpr, pzErr);
           if( rc==SQLITE_OK ){
             rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
             pExpr = 0;
@@ -219162,6 +225625,25 @@ static int fts5FilterMethod(
 
         break;
       }
+      case 'L':
+      case 'G': {
+        int bGlob = (idxStr[iIdxStr-1]=='G');
+        const char *zText = (const char*)sqlite3_value_text(apVal[i]);
+        iCol = 0;
+        do{
+          iCol = iCol*10 + (idxStr[iIdxStr]-'0');
+          iIdxStr++;
+        }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
+        if( zText ){
+          rc = sqlite3Fts5ExprPattern(pConfig, bGlob, iCol, zText, &pExpr);
+        }
+        if( rc==SQLITE_OK ){
+          rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
+          pExpr = 0;
+        }
+        if( rc!=SQLITE_OK ) goto filter_out;
+        break;
+      }
       case '=':
         pRowidEq = apVal[i];
         break;
@@ -219176,7 +225658,7 @@ static int fts5FilterMethod(
   bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
   pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
 
-  /* Set the cursor upper and lower rowid limits. Only some strategies 
+  /* Set the cursor upper and lower rowid limits. Only some strategies
   ** actually use them. This is ok, as the xBestIndex() method leaves the
   ** sqlite3_index_constraint.omit flag clear for range constraints
   ** on the rowid field.  */
@@ -219192,11 +225674,11 @@ static int fts5FilterMethod(
   }
 
   if( pTab->pSortCsr ){
-    /* If pSortCsr is non-NULL, then this call is being made as part of 
+    /* If pSortCsr is non-NULL, then this call is being made as part of
     ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
     ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
-    ** return results to the user for this query. The current cursor 
-    ** (pCursor) is used to execute the query issued by function 
+    ** return results to the user for this query. The current cursor
+    ** (pCursor) is used to execute the query issued by function
     ** fts5CursorFirstSorted() above.  */
     assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
     assert( nVal==0 && bOrderByRank==0 && bDesc==0 );
@@ -219252,8 +225734,8 @@ static int fts5FilterMethod(
   return rc;
 }
 
-/* 
-** This is the xEof method of the virtual table. SQLite calls this 
+/*
+** This is the xEof method of the virtual table. SQLite calls this
 ** routine to find out if it has reached the end of a result set.
 */
 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
@@ -219265,9 +225747,9 @@ static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
 ** Return the rowid that the cursor currently points to.
 */
 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
-  assert( pCsr->ePlan==FTS5_PLAN_MATCH 
-       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH 
-       || pCsr->ePlan==FTS5_PLAN_SOURCE 
+  assert( pCsr->ePlan==FTS5_PLAN_MATCH
+       || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
+       || pCsr->ePlan==FTS5_PLAN_SOURCE
   );
   if( pCsr->pSorter ){
     return pCsr->pSorter->iRowid;
@@ -219276,7 +225758,7 @@ static i64 fts5CursorRowid(Fts5Cursor *pCsr){
   }
 }
 
-/* 
+/*
 ** This is the xRowid method. The SQLite core calls this routine to
 ** retrieve the rowid for the current row of the result set. fts5
 ** exposes %_content.rowid as the rowid for the virtual table. The
@@ -219285,7 +225767,7 @@ static i64 fts5CursorRowid(Fts5Cursor *pCsr){
 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   int ePlan = pCsr->ePlan;
-  
+
   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
   switch( ePlan ){
     case FTS5_PLAN_SPECIAL:
@@ -219316,7 +225798,7 @@ static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
   int rc = SQLITE_OK;
 
-  /* If the cursor does not yet have a statement handle, obtain one now. */ 
+  /* If the cursor does not yet have a statement handle, obtain one now. */
   if( pCsr->pStmt==0 ){
     Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
     int eStmt = fts5StmtType(pCsr);
@@ -219328,10 +225810,13 @@ static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
   }
 
   if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
+    Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
     assert( pCsr->pExpr );
     sqlite3_reset(pCsr->pStmt);
     sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
+    pTab->pConfig->bLock++;
     rc = sqlite3_step(pCsr->pStmt);
+    pTab->pConfig->bLock--;
     if( rc==SQLITE_ROW ){
       rc = SQLITE_OK;
       CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
@@ -219339,6 +225824,10 @@ static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
       rc = sqlite3_reset(pCsr->pStmt);
       if( rc==SQLITE_OK ){
         rc = FTS5_CORRUPT;
+      }else if( pTab->pConfig->pzErrmsg ){
+        *pTab->pConfig->pzErrmsg = sqlite3_mprintf(
+            "%s", sqlite3_errmsg(pTab->pConfig->db)
+        );
       }
     }
   }
@@ -219360,7 +225849,7 @@ static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
 **     INSERT INTO fts(fts) VALUES($pCmd)
 **     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
 **
-** Argument pVal is the value assigned to column "fts" by the INSERT 
+** Argument pVal is the value assigned to column "fts" by the INSERT
 ** statement. This function returns SQLITE_OK if successful, or an SQLite
 ** error code if an error occurs.
 **
@@ -219379,7 +225868,7 @@ static int fts5SpecialInsert(
 
   if( 0==sqlite3_stricmp("delete-all", zCmd) ){
     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
-      fts5SetVtabError(pTab, 
+      fts5SetVtabError(pTab,
           "'delete-all' may only be used with a "
           "contentless or external content fts5 table"
       );
@@ -219389,7 +225878,7 @@ static int fts5SpecialInsert(
     }
   }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
     if( pConfig->eContent==FTS5_CONTENT_NONE ){
-      fts5SetVtabError(pTab, 
+      fts5SetVtabError(pTab,
           "'rebuild' may not be used with a contentless fts5 table"
       );
       rc = SQLITE_ERROR;
@@ -219402,7 +225891,8 @@ static int fts5SpecialInsert(
     int nMerge = sqlite3_value_int(pVal);
     rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
   }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
-    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
+    int iArg = sqlite3_value_int(pVal);
+    rc = sqlite3Fts5StorageIntegrity(pTab->pStorage, iArg);
 #ifdef SQLITE_DEBUG
   }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
     pConfig->bPrefixIndex = sqlite3_value_int(pVal);
@@ -219424,7 +225914,7 @@ static int fts5SpecialInsert(
 }
 
 static int fts5SpecialDelete(
-  Fts5FullTable *pTab, 
+  Fts5FullTable *pTab,
   sqlite3_value **apVal
 ){
   int rc = SQLITE_OK;
@@ -219437,9 +225927,9 @@ static int fts5SpecialDelete(
 }
 
 static void fts5StorageInsert(
-  int *pRc, 
-  Fts5FullTable *pTab, 
-  sqlite3_value **apVal, 
+  int *pRc,
+  Fts5FullTable *pTab,
+  sqlite3_value **apVal,
   i64 *piRowid
 ){
   int rc = *pRc;
@@ -219452,13 +225942,13 @@ static void fts5StorageInsert(
   *pRc = rc;
 }
 
-/* 
-** This function is the implementation of the xUpdate callback used by 
+/*
+** This function is the implementation of the xUpdate callback used by
 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
 ** inserted, updated or deleted.
 **
 ** A delete specifies a single argument - the rowid of the row to remove.
-** 
+**
 ** Update and insert operations pass:
 **
 **   1. The "old" rowid, or NULL.
@@ -219482,8 +225972,8 @@ static int fts5UpdateMethod(
 
   assert( pVtab->zErrMsg==0 );
   assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
-  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER 
-       || sqlite3_value_type(apVal[0])==SQLITE_NULL 
+  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
+       || sqlite3_value_type(apVal[0])==SQLITE_NULL
   );
   assert( pTab->p.pConfig->pzErrmsg==0 );
   pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
@@ -219492,13 +225982,13 @@ static int fts5UpdateMethod(
   fts5TripCursors(pTab);
 
   eType0 = sqlite3_value_type(apVal[0]);
-  if( eType0==SQLITE_NULL 
-   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL 
+  if( eType0==SQLITE_NULL
+   && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
   ){
     /* A "special" INSERT op. These are handled separately. */
     const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
-    if( pConfig->eContent!=FTS5_CONTENT_NORMAL 
-      && 0==sqlite3_stricmp("delete", z) 
+    if( pConfig->eContent!=FTS5_CONTENT_NORMAL
+      && 0==sqlite3_stricmp("delete", z)
     ){
       rc = fts5SpecialDelete(pTab, apVal);
     }else{
@@ -219506,7 +225996,7 @@ static int fts5UpdateMethod(
     }
   }else{
     /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
-    ** any conflict on the rowid value must be detected before any 
+    ** any conflict on the rowid value must be detected before any
     ** modifications are made to the database file. There are 4 cases:
     **
     **   1) DELETE
@@ -219528,7 +226018,7 @@ static int fts5UpdateMethod(
     ** This is not suported.  */
     if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
       pTab->p.base.zErrMsg = sqlite3_mprintf(
-          "cannot %s contentless fts5 table: %s", 
+          "cannot %s contentless fts5 table: %s",
           (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
       );
       rc = SQLITE_ERROR;
@@ -219548,7 +226038,7 @@ static int fts5UpdateMethod(
         rc = SQLITE_MISMATCH;
       }
 
-      else if( eType0!=SQLITE_INTEGER ){     
+      else if( eType0!=SQLITE_INTEGER ){
         /* If this is a REPLACE, first remove the current entry (if any) */
         if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
           i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
@@ -219590,7 +226080,7 @@ static int fts5UpdateMethod(
 }
 
 /*
-** Implementation of xSync() method. 
+** Implementation of xSync() method.
 */
 static int fts5SyncMethod(sqlite3_vtab *pVtab){
   int rc;
@@ -219604,7 +226094,7 @@ static int fts5SyncMethod(sqlite3_vtab *pVtab){
 }
 
 /*
-** Implementation of xBegin() method. 
+** Implementation of xBegin() method.
 */
 static int fts5BeginMethod(sqlite3_vtab *pVtab){
   fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
@@ -219648,8 +226138,8 @@ static int fts5ApiColumnCount(Fts5Context *pCtx){
 }
 
 static int fts5ApiColumnTotalSize(
-  Fts5Context *pCtx, 
-  int iCol, 
+  Fts5Context *pCtx,
+  int iCol,
   sqlite3_int64 *pnToken
 ){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
@@ -219664,8 +226154,8 @@ static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
 }
 
 static int fts5ApiTokenize(
-  Fts5Context *pCtx, 
-  const char *pText, int nText, 
+  Fts5Context *pCtx,
+  const char *pText, int nText,
   void *pUserData,
   int (*xToken)(void*, int, const char*, int, int, int)
 ){
@@ -219687,15 +226177,15 @@ static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
 }
 
 static int fts5ApiColumnText(
-  Fts5Context *pCtx, 
-  int iCol, 
-  const char **pz, 
+  Fts5Context *pCtx,
+  int iCol,
+  const char **pz,
   int *pn
 ){
   int rc = SQLITE_OK;
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
-  if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab)) 
-   || pCsr->ePlan==FTS5_PLAN_SPECIAL 
+  if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
+   || pCsr->ePlan==FTS5_PLAN_SPECIAL
   ){
     *pz = 0;
     *pn = 0;
@@ -219710,8 +226200,8 @@ static int fts5ApiColumnText(
 }
 
 static int fts5CsrPoslist(
-  Fts5Cursor *pCsr, 
-  int iPhrase, 
+  Fts5Cursor *pCsr,
+  int iPhrase,
   const u8 **pa,
   int *pn
 ){
@@ -219766,7 +226256,7 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){
   Fts5PoslistReader *aIter;       /* One iterator for each phrase */
   int nIter;                      /* Number of iterators/phrases */
   int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
-  
+
   nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
   if( pCsr->aInstIter==0 ){
     sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
@@ -219781,7 +226271,7 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){
     /* Initialize all iterators */
     for(i=0; i<nIter && rc==SQLITE_OK; i++){
       const u8 *a;
-      int n; 
+      int n;
       rc = fts5CsrPoslist(pCsr, i, &a, &n);
       if( rc==SQLITE_OK ){
         sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
@@ -219793,8 +226283,8 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){
         int *aInst;
         int iBest = -1;
         for(i=0; i<nIter; i++){
-          if( (aIter[i].bEof==0) 
-              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) 
+          if( (aIter[i].bEof==0)
+              && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
             ){
             iBest = i;
           }
@@ -219836,7 +226326,7 @@ static int fts5CacheInstArray(Fts5Cursor *pCsr){
 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   int rc = SQLITE_OK;
-  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
+  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
    || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
     *pnInst = pCsr->nInstCount;
   }
@@ -219844,16 +226334,16 @@ static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
 }
 
 static int fts5ApiInst(
-  Fts5Context *pCtx, 
-  int iIdx, 
-  int *piPhrase, 
-  int *piCol, 
+  Fts5Context *pCtx,
+  int iIdx,
+  int *piPhrase,
+  int *piCol,
   int *piOff
 ){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
   int rc = SQLITE_OK;
-  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
-   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) 
+  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
+   || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
   ){
     if( iIdx<0 || iIdx>=pCsr->nInstCount ){
       rc = SQLITE_RANGE;
@@ -220002,8 +226492,8 @@ static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
 }
 
 static void fts5ApiPhraseNext(
-  Fts5Context *pUnused, 
-  Fts5PhraseIter *pIter, 
+  Fts5Context *pUnused,
+  Fts5PhraseIter *pIter,
   int *piCol, int *piOff
 ){
   UNUSED_PARAM(pUnused);
@@ -220024,9 +226514,9 @@ static void fts5ApiPhraseNext(
 }
 
 static int fts5ApiPhraseFirst(
-  Fts5Context *pCtx, 
-  int iPhrase, 
-  Fts5PhraseIter *pIter, 
+  Fts5Context *pCtx,
+  int iPhrase,
+  Fts5PhraseIter *pIter,
   int *piCol, int *piOff
 ){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
@@ -220042,8 +226532,8 @@ static int fts5ApiPhraseFirst(
 }
 
 static void fts5ApiPhraseNextColumn(
-  Fts5Context *pCtx, 
-  Fts5PhraseIter *pIter, 
+  Fts5Context *pCtx,
+  Fts5PhraseIter *pIter,
   int *piCol
 ){
   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
@@ -220072,9 +226562,9 @@ static void fts5ApiPhraseNextColumn(
 }
 
 static int fts5ApiPhraseFirstColumn(
-  Fts5Context *pCtx, 
-  int iPhrase, 
-  Fts5PhraseIter *pIter, 
+  Fts5Context *pCtx,
+  int iPhrase,
+  Fts5PhraseIter *pIter,
   int *piCol
 ){
   int rc = SQLITE_OK;
@@ -220115,7 +226605,7 @@ static int fts5ApiPhraseFirstColumn(
 }
 
 
-static int fts5ApiQueryPhrase(Fts5Context*, int, void*, 
+static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
     int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
 );
 
@@ -220146,8 +226636,8 @@ static const Fts5ExtensionApi sFts5Api = {
 ** Implementation of API function xQueryPhrase().
 */
 static int fts5ApiQueryPhrase(
-  Fts5Context *pCtx, 
-  int iPhrase, 
+  Fts5Context *pCtx,
+  int iPhrase,
   void *pUserData,
   int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
 ){
@@ -220229,7 +226719,7 @@ static void fts5ApiCallback(
 
 
 /*
-** Given cursor id iId, return a pointer to the corresponding Fts5Table 
+** Given cursor id iId, return a pointer to the corresponding Fts5Table
 ** object. Or NULL If the cursor id does not exist.
 */
 static Fts5Table *sqlite3Fts5TableFromCsrid(
@@ -220312,7 +226802,7 @@ static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
   return rc;
 }
 
-/* 
+/*
 ** This is the xColumn method, called by SQLite to request a value from
 ** the row that the supplied cursor currently points to.
 */
@@ -220325,7 +226815,7 @@ static int fts5ColumnMethod(
   Fts5Config *pConfig = pTab->p.pConfig;
   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
   int rc = SQLITE_OK;
-  
+
   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
 
   if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
@@ -220345,7 +226835,7 @@ static int fts5ColumnMethod(
     /* The value of the "rank" column. */
     if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
       fts5PoslistBlob(pCtx, pCsr);
-    }else if( 
+    }else if(
         pCsr->ePlan==FTS5_PLAN_MATCH
      || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
     ){
@@ -220354,10 +226844,12 @@ static int fts5ColumnMethod(
       }
     }
   }else if( !fts5IsContentless(pTab) ){
+    pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
     rc = fts5SeekCursor(pCsr, 1);
     if( rc==SQLITE_OK ){
       sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
     }
+    pConfig->pzErrmsg = 0;
   }
   return rc;
 }
@@ -220479,7 +226971,7 @@ static int fts5CreateAux(
 }
 
 /*
-** Register a new tokenizer. This is the implementation of the 
+** Register a new tokenizer. This is the implementation of the
 ** fts5_api.xCreateTokenizer() method.
 */
 static int fts5CreateTokenizer(
@@ -220518,7 +227010,7 @@ static int fts5CreateTokenizer(
 }
 
 static Fts5TokenizerModule *fts5LocateTokenizer(
-  Fts5Global *pGlobal, 
+  Fts5Global *pGlobal,
   const char *zName
 ){
   Fts5TokenizerModule *pMod = 0;
@@ -220535,7 +227027,7 @@ static Fts5TokenizerModule *fts5LocateTokenizer(
 }
 
 /*
-** Find a tokenizer. This is the implementation of the 
+** Find a tokenizer. This is the implementation of the
 ** fts5_api.xFindTokenizer() method.
 */
 static int fts5FindTokenizer(
@@ -220560,11 +227052,10 @@ static int fts5FindTokenizer(
 }
 
 static int sqlite3Fts5GetTokenizer(
-  Fts5Global *pGlobal, 
+  Fts5Global *pGlobal,
   const char **azArg,
   int nArg,
-  Fts5Tokenizer **ppTok,
-  fts5_tokenizer **ppTokApi,
+  Fts5Config *pConfig,
   char **pzErr
 ){
   Fts5TokenizerModule *pMod;
@@ -220576,16 +227067,22 @@ static int sqlite3Fts5GetTokenizer(
     rc = SQLITE_ERROR;
     *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
   }else{
-    rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
-    *ppTokApi = &pMod->x;
-    if( rc!=SQLITE_OK && pzErr ){
-      *pzErr = sqlite3_mprintf("error in tokenizer constructor");
+    rc = pMod->x.xCreate(
+        pMod->pUserData, &azArg[1], (nArg?nArg-1:0), &pConfig->pTok
+    );
+    pConfig->pTokApi = &pMod->x;
+    if( rc!=SQLITE_OK ){
+      if( pzErr ) *pzErr = sqlite3_mprintf("error in tokenizer constructor");
+    }else{
+      pConfig->ePattern = sqlite3Fts5TokenizerPattern(
+          pMod->x.xCreate, pConfig->pTok
+      );
     }
   }
 
   if( rc!=SQLITE_OK ){
-    *ppTokApi = 0;
-    *ppTok = 0;
+    pConfig->pTokApi = 0;
+    pConfig->pTok = 0;
   }
 
   return rc;
@@ -220634,7 +227131,7 @@ static void fts5SourceIdFunc(
 ){
   assert( nArg==0 );
   UNUSED_PARAM2(nArg, apUnused);
-  sqlite3_result_text(pCtx, "fts5: 2019-10-10 20:19:45 18db032d058f1436ce3dea84081f4ee5a0f2259ad97301d43c426bc7f3df1b0b", -1, SQLITE_TRANSIENT);
+  sqlite3_result_text(pCtx, "fts5: 2020-12-01 16:14:00 a26b6597e3ae272231b96f9982c3bcc17ddec2f2b6eb4df06a224b91089fed5b", -1, SQLITE_TRANSIENT);
 }
 
 /*
@@ -220730,7 +227227,7 @@ static int fts5Init(sqlite3 *db){
 ** this module is being built as part of the SQLite core (SQLITE_CORE is
 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
 **
-** Or, if this module is being built as a loadable extension, 
+** Or, if this module is being built as a loadable extension,
 ** sqlite3Fts5Init() is omitted and the two standard entry points
 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
 */
@@ -220789,19 +227286,19 @@ struct Fts5Storage {
   Fts5Index *pIndex;
   int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
   i64 nTotalRow;                  /* Total number of rows in FTS table */
-  i64 *aTotalSize;                /* Total sizes of each column */ 
+  i64 *aTotalSize;                /* Total sizes of each column */
   sqlite3_stmt *aStmt[11];
 };
 
 
-#if FTS5_STMT_SCAN_ASC!=0 
-# error "FTS5_STMT_SCAN_ASC mismatch" 
+#if FTS5_STMT_SCAN_ASC!=0
+# error "FTS5_STMT_SCAN_ASC mismatch"
 #endif
-#if FTS5_STMT_SCAN_DESC!=1 
-# error "FTS5_STMT_SCAN_DESC mismatch" 
+#if FTS5_STMT_SCAN_DESC!=1
+# error "FTS5_STMT_SCAN_DESC mismatch"
 #endif
 #if FTS5_STMT_LOOKUP!=2
-# error "FTS5_STMT_LOOKUP mismatch" 
+# error "FTS5_STMT_LOOKUP mismatch"
 #endif
 
 #define FTS5_STMT_INSERT_CONTENT  3
@@ -220827,12 +227324,12 @@ static int fts5StorageGetStmt(
 ){
   int rc = SQLITE_OK;
 
-  /* If there is no %_docsize table, there should be no requests for 
+  /* If there is no %_docsize table, there should be no requests for
   ** statements to operate on it.  */
   assert( p->pConfig->bColumnsize || (
-        eStmt!=FTS5_STMT_REPLACE_DOCSIZE 
-     && eStmt!=FTS5_STMT_DELETE_DOCSIZE 
-     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE 
+        eStmt!=FTS5_STMT_REPLACE_DOCSIZE
+     && eStmt!=FTS5_STMT_DELETE_DOCSIZE
+     && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
   ));
 
   assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
@@ -220858,26 +227355,26 @@ static int fts5StorageGetStmt(
 
     switch( eStmt ){
       case FTS5_STMT_SCAN:
-        zSql = sqlite3_mprintf(azStmt[eStmt], 
+        zSql = sqlite3_mprintf(azStmt[eStmt],
             pC->zContentExprlist, pC->zContent
         );
         break;
 
       case FTS5_STMT_SCAN_ASC:
       case FTS5_STMT_SCAN_DESC:
-        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, 
+        zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
             pC->zContent, pC->zContentRowid, pC->zContentRowid,
             pC->zContentRowid
         );
         break;
 
       case FTS5_STMT_LOOKUP:
-        zSql = sqlite3_mprintf(azStmt[eStmt], 
+        zSql = sqlite3_mprintf(azStmt[eStmt],
             pC->zContentExprlist, pC->zContent, pC->zContentRowid
         );
         break;
 
-      case FTS5_STMT_INSERT_CONTENT: 
+      case FTS5_STMT_INSERT_CONTENT:
       case FTS5_STMT_REPLACE_CONTENT: {
         size_t nCol = pC->nCol + 1;
         char *zBind;
@@ -220951,7 +227448,7 @@ static int fts5ExecPrintf(
 ** code otherwise.
 */
 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
-  int rc = fts5ExecPrintf(pConfig->db, 0, 
+  int rc = fts5ExecPrintf(pConfig->db, 0,
       "DROP TABLE IF EXISTS %Q.'%q_data';"
       "DROP TABLE IF EXISTS %Q.'%q_idx';"
       "DROP TABLE IF EXISTS %Q.'%q_config';",
@@ -220960,13 +227457,13 @@ static int sqlite3Fts5DropAll(Fts5Config *pConfig){
       pConfig->zDb, pConfig->zName
   );
   if( rc==SQLITE_OK && pConfig->bColumnsize ){
-    rc = fts5ExecPrintf(pConfig->db, 0, 
+    rc = fts5ExecPrintf(pConfig->db, 0,
         "DROP TABLE IF EXISTS %Q.'%q_docsize';",
         pConfig->zDb, pConfig->zName
     );
   }
   if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
-    rc = fts5ExecPrintf(pConfig->db, 0, 
+    rc = fts5ExecPrintf(pConfig->db, 0,
         "DROP TABLE IF EXISTS %Q.'%q_content';",
         pConfig->zDb, pConfig->zName
     );
@@ -220981,7 +227478,7 @@ static void fts5StorageRenameOne(
   const char *zName               /* New name of FTS5 table */
 ){
   if( *pRc==SQLITE_OK ){
-    *pRc = fts5ExecPrintf(pConfig->db, 0, 
+    *pRc = fts5ExecPrintf(pConfig->db, 0,
         "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
         pConfig->zDb, pConfig->zName, zTail, zName, zTail
     );
@@ -221019,7 +227516,7 @@ static int sqlite3Fts5CreateTable(
   char *zErr = 0;
 
   rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
-      pConfig->zDb, pConfig->zName, zPost, zDefn, 
+      pConfig->zDb, pConfig->zName, zPost, zDefn,
 #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
       bWithout?" WITHOUT ROWID":
 #endif
@@ -221027,7 +227524,7 @@ static int sqlite3Fts5CreateTable(
   );
   if( zErr ){
     *pzErr = sqlite3_mprintf(
-        "fts5: error creating shadow table %q_%s: %s", 
+        "fts5: error creating shadow table %q_%s: %s",
         pConfig->zName, zPost, zErr
     );
     sqlite3_free(zErr);
@@ -221038,15 +227535,15 @@ static int sqlite3Fts5CreateTable(
 
 /*
 ** Open a new Fts5Index handle. If the bCreate argument is true, create
-** and initialize the underlying tables 
+** and initialize the underlying tables
 **
 ** If successful, set *pp to point to the new object and return SQLITE_OK.
 ** Otherwise, set *pp to NULL and return an SQLite error code.
 */
 static int sqlite3Fts5StorageOpen(
-  Fts5Config *pConfig, 
-  Fts5Index *pIndex, 
-  int bCreate, 
+  Fts5Config *pConfig,
+  Fts5Index *pIndex,
+  int bCreate,
   Fts5Storage **pp,
   char **pzErr                    /* OUT: Error message */
 ){
@@ -221158,8 +227655,8 @@ static int fts5StorageInsertCallback(
 ** remove the %_content row at this time though.
 */
 static int fts5StorageDeleteFromIndex(
-  Fts5Storage *p, 
-  i64 iDel, 
+  Fts5Storage *p,
+  i64 iDel,
   sqlite3_value **apVal
 ){
   Fts5Config *pConfig = p->pConfig;
@@ -221193,13 +227690,20 @@ static int fts5StorageDeleteFromIndex(
         nText = sqlite3_value_bytes(apVal[iCol-1]);
       }
       ctx.szCol = 0;
-      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, 
+      rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
           zText, nText, (void*)&ctx, fts5StorageInsertCallback
       );
       p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
+      if( p->aTotalSize[iCol-1]<0 ){
+        rc = FTS5_CORRUPT;
+      }
     }
   }
-  p->nTotalRow--;
+  if( rc==SQLITE_OK && p->nTotalRow<1 ){
+    rc = FTS5_CORRUPT;
+  }else{
+    p->nTotalRow--;
+  }
 
   rc2 = sqlite3_reset(pSeek);
   if( rc==SQLITE_OK ) rc = rc2;
@@ -221236,7 +227740,7 @@ static int fts5StorageInsertDocsize(
 }
 
 /*
-** Load the contents of the "averages" record from disk into the 
+** Load the contents of the "averages" record from disk into the
 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
 ** argument bCache is true, set the p->bTotalsValid flag to indicate
 ** that the contents of aTotalSize[] and nTotalRow are valid until
@@ -221255,7 +227759,7 @@ static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
 }
 
 /*
-** Store the current contents of the p->nTotalRow and p->aTotalSize[] 
+** Store the current contents of the p->nTotalRow and p->aTotalSize[]
 ** variables in the "averages" record on disk.
 **
 ** Return SQLITE_OK if successful, or an SQLite error code if an error
@@ -221328,9 +227832,11 @@ static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
   Fts5Config *pConfig = p->pConfig;
   int rc;
 
+  p->bTotalsValid = 0;
+
   /* Delete the contents of the %_data and %_docsize tables. */
   rc = fts5ExecPrintf(pConfig->db, 0,
-      "DELETE FROM %Q.'%q_data';" 
+      "DELETE FROM %Q.'%q_data';"
       "DELETE FROM %Q.'%q_idx';",
       pConfig->zDb, pConfig->zName,
       pConfig->zDb, pConfig->zName
@@ -221379,10 +227885,11 @@ static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
     for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
       ctx.szCol = 0;
       if( pConfig->abUnindexed[ctx.iCol]==0 ){
-        rc = sqlite3Fts5Tokenize(pConfig, 
+        const char *zText = (const char*)sqlite3_column_text(pScan, ctx.iCol+1);
+        int nText = sqlite3_column_bytes(pScan, ctx.iCol+1);
+        rc = sqlite3Fts5Tokenize(pConfig,
             FTS5_TOKENIZE_DOCUMENT,
-            (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
-            sqlite3_column_bytes(pScan, ctx.iCol+1),
+            zText, nText,
             (void*)&ctx,
             fts5StorageInsertCallback
         );
@@ -221450,8 +227957,8 @@ static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
 ** Insert a new row into the FTS content table.
 */
 static int sqlite3Fts5StorageContentInsert(
-  Fts5Storage *p, 
-  sqlite3_value **apVal, 
+  Fts5Storage *p,
+  sqlite3_value **apVal,
   i64 *piRowid
 ){
   Fts5Config *pConfig = p->pConfig;
@@ -221485,8 +227992,8 @@ static int sqlite3Fts5StorageContentInsert(
 ** Insert new entries into the FTS index and %_docsize table.
 */
 static int sqlite3Fts5StorageIndexInsert(
-  Fts5Storage *p, 
-  sqlite3_value **apVal, 
+  Fts5Storage *p,
+  sqlite3_value **apVal,
   i64 iRowid
 ){
   Fts5Config *pConfig = p->pConfig;
@@ -221504,10 +228011,11 @@ static int sqlite3Fts5StorageIndexInsert(
   for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
     ctx.szCol = 0;
     if( pConfig->abUnindexed[ctx.iCol]==0 ){
-      rc = sqlite3Fts5Tokenize(pConfig, 
+      const char *zText = (const char*)sqlite3_value_text(apVal[ctx.iCol+2]);
+      int nText = sqlite3_value_bytes(apVal[ctx.iCol+2]);
+      rc = sqlite3Fts5Tokenize(pConfig,
           FTS5_TOKENIZE_DOCUMENT,
-          (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
-          sqlite3_value_bytes(apVal[ctx.iCol+2]),
+          zText, nText,
           (void*)&ctx,
           fts5StorageInsertCallback
       );
@@ -221531,7 +228039,7 @@ static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
   char *zSql;
   int rc;
 
-  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", 
+  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
       pConfig->zDb, pConfig->zName, zSuffix
   );
   if( zSql==0 ){
@@ -221638,13 +228146,14 @@ static int fts5StorageIntegrityCallback(
 ** some other SQLite error code if an error occurs while attempting to
 ** determine this.
 */
-static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
+static int sqlite3Fts5StorageIntegrity(Fts5Storage *p, int iArg){
   Fts5Config *pConfig = p->pConfig;
-  int rc;                         /* Return code */
+  int rc = SQLITE_OK;             /* Return code */
   int *aColSize;                  /* Array of size pConfig->nCol */
   i64 *aTotalSize;                /* Array of size pConfig->nCol */
   Fts5IntegrityCtx ctx;
   sqlite3_stmt *pScan;
+  int bUseCksum;
 
   memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
   ctx.pConfig = p->pConfig;
@@ -221653,82 +228162,88 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
   aColSize = (int*)&aTotalSize[pConfig->nCol];
   memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
 
-  /* Generate the expected index checksum based on the contents of the
-  ** %_content table. This block stores the checksum in ctx.cksum. */
-  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
-  if( rc==SQLITE_OK ){
-    int rc2;
-    while( SQLITE_ROW==sqlite3_step(pScan) ){
-      int i;
-      ctx.iRowid = sqlite3_column_int64(pScan, 0);
-      ctx.szCol = 0;
-      if( pConfig->bColumnsize ){
-        rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
-      }
-      if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
-        rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
-      }
-      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
-        if( pConfig->abUnindexed[i] ) continue;
-        ctx.iCol = i;
+  bUseCksum = (pConfig->eContent==FTS5_CONTENT_NORMAL
+           || (pConfig->eContent==FTS5_CONTENT_EXTERNAL && iArg)
+  );
+  if( bUseCksum ){
+    /* Generate the expected index checksum based on the contents of the
+    ** %_content table. This block stores the checksum in ctx.cksum. */
+    rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
+    if( rc==SQLITE_OK ){
+      int rc2;
+      while( SQLITE_ROW==sqlite3_step(pScan) ){
+        int i;
+        ctx.iRowid = sqlite3_column_int64(pScan, 0);
         ctx.szCol = 0;
-        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
-          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
-        }
-        if( rc==SQLITE_OK ){
-          rc = sqlite3Fts5Tokenize(pConfig, 
-              FTS5_TOKENIZE_DOCUMENT,
-              (const char*)sqlite3_column_text(pScan, i+1),
-              sqlite3_column_bytes(pScan, i+1),
-              (void*)&ctx,
-              fts5StorageIntegrityCallback
-          );
+        if( pConfig->bColumnsize ){
+          rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
         }
-        if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
-          rc = FTS5_CORRUPT;
+        if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
+          rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
         }
-        aTotalSize[i] += ctx.szCol;
-        if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
-          sqlite3Fts5TermsetFree(ctx.pTermset);
-          ctx.pTermset = 0;
+        for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
+          if( pConfig->abUnindexed[i] ) continue;
+          ctx.iCol = i;
+          ctx.szCol = 0;
+          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+            rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
+          }
+          if( rc==SQLITE_OK ){
+            const char *zText = (const char*)sqlite3_column_text(pScan, i+1);
+            int nText = sqlite3_column_bytes(pScan, i+1);
+            rc = sqlite3Fts5Tokenize(pConfig,
+                FTS5_TOKENIZE_DOCUMENT,
+                zText, nText,
+                (void*)&ctx,
+                fts5StorageIntegrityCallback
+            );
+          }
+          if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
+            rc = FTS5_CORRUPT;
+          }
+          aTotalSize[i] += ctx.szCol;
+          if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
+            sqlite3Fts5TermsetFree(ctx.pTermset);
+            ctx.pTermset = 0;
+          }
         }
-      }
-      sqlite3Fts5TermsetFree(ctx.pTermset);
-      ctx.pTermset = 0;
+        sqlite3Fts5TermsetFree(ctx.pTermset);
+        ctx.pTermset = 0;
 
-      if( rc!=SQLITE_OK ) break;
+        if( rc!=SQLITE_OK ) break;
+      }
+      rc2 = sqlite3_reset(pScan);
+      if( rc==SQLITE_OK ) rc = rc2;
     }
-    rc2 = sqlite3_reset(pScan);
-    if( rc==SQLITE_OK ) rc = rc2;
-  }
 
-  /* Test that the "totals" (sometimes called "averages") record looks Ok */
-  if( rc==SQLITE_OK ){
-    int i;
-    rc = fts5StorageLoadTotals(p, 0);
-    for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
-      if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
+    /* Test that the "totals" (sometimes called "averages") record looks Ok */
+    if( rc==SQLITE_OK ){
+      int i;
+      rc = fts5StorageLoadTotals(p, 0);
+      for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
+        if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
+      }
     }
-  }
 
-  /* Check that the %_docsize and %_content tables contain the expected
-  ** number of rows.  */
-  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
-    i64 nRow = 0;
-    rc = fts5StorageCount(p, "content", &nRow);
-    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
-  }
-  if( rc==SQLITE_OK && pConfig->bColumnsize ){
-    i64 nRow = 0;
-    rc = fts5StorageCount(p, "docsize", &nRow);
-    if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
+    /* Check that the %_docsize and %_content tables contain the expected
+    ** number of rows.  */
+    if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
+      i64 nRow = 0;
+      rc = fts5StorageCount(p, "content", &nRow);
+      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
+    }
+    if( rc==SQLITE_OK && pConfig->bColumnsize ){
+      i64 nRow = 0;
+      rc = fts5StorageCount(p, "docsize", &nRow);
+      if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
+    }
   }
 
   /* Pass the expected checksum down to the FTS index module. It will
   ** verify, amongst other things, that it matches the checksum generated by
   ** inspecting the index itself.  */
   if( rc==SQLITE_OK ){
-    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
+    rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum, bUseCksum);
   }
 
   sqlite3_free(aTotalSize);
@@ -221740,13 +228255,13 @@ static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
 ** %_content table.
 */
 static int sqlite3Fts5StorageStmt(
-  Fts5Storage *p, 
-  int eStmt, 
-  sqlite3_stmt **pp, 
+  Fts5Storage *p,
+  int eStmt,
+  sqlite3_stmt **pp,
   char **pzErrMsg
 ){
   int rc;
-  assert( eStmt==FTS5_STMT_SCAN_ASC 
+  assert( eStmt==FTS5_STMT_SCAN_ASC
        || eStmt==FTS5_STMT_SCAN_DESC
        || eStmt==FTS5_STMT_LOOKUP
   );
@@ -221764,8 +228279,8 @@ static int sqlite3Fts5StorageStmt(
 ** must match that passed to the sqlite3Fts5StorageStmt() call.
 */
 static void sqlite3Fts5StorageStmtRelease(
-  Fts5Storage *p, 
-  int eStmt, 
+  Fts5Storage *p,
+  int eStmt,
   sqlite3_stmt *pStmt
 ){
   assert( eStmt==FTS5_STMT_SCAN_ASC
@@ -221848,7 +228363,7 @@ static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
   int rc = fts5StorageLoadTotals(p, 0);
   if( rc==SQLITE_OK ){
-    /* nTotalRow being zero does not necessarily indicate a corrupt 
+    /* nTotalRow being zero does not necessarily indicate a corrupt
     ** database - it might be that the FTS5 table really does contain zero
     ** rows. However this function is only called from the xRowCount() API,
     ** and there is no way for that API to be invoked if the table contains
@@ -221882,7 +228397,7 @@ static int sqlite3Fts5StorageRollback(Fts5Storage *p){
 }
 
 static int sqlite3Fts5StorageConfigValue(
-  Fts5Storage *p, 
+  Fts5Storage *p,
   const char *z,
   sqlite3_value *pVal,
   int iVal
@@ -221932,7 +228447,7 @@ static int sqlite3Fts5StorageConfigValue(
 
 /*
 ** For tokenizers with no "unicode" modifier, the set of token characters
-** is the same as the set of ASCII range alphanumeric characters. 
+** is the same as the set of ASCII range alphanumeric characters.
 */
 static const unsigned char aAsciiTokenChar[128] = {
   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
@@ -221951,8 +228466,8 @@ struct AsciiTokenizer {
 };
 
 static void fts5AsciiAddExceptions(
-  AsciiTokenizer *p, 
-  const char *zArg, 
+  AsciiTokenizer *p,
+  const char *zArg,
   int bTokenChars
 ){
   int i;
@@ -221974,7 +228489,7 @@ static void fts5AsciiDelete(Fts5Tokenizer *p){
 ** Create an "ascii" tokenizer.
 */
 static int fts5AsciiCreate(
-  void *pUnused, 
+  void *pUnused,
   const char **azArg, int nArg,
   Fts5Tokenizer **ppOut
 ){
@@ -222077,7 +228592,7 @@ static int fts5AsciiTokenize(
     rc = xToken(pCtx, 0, pFold, nByte, is, ie);
     is = ie+1;
   }
-  
+
   if( pFold!=aFold ) sqlite3_free(pFold);
   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   return rc;
@@ -222182,7 +228697,7 @@ static int fts5UnicodeAddExceptions(
           p->aTokenChar[iCode] = (unsigned char)bTokenChars;
         }else{
           bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
-          assert( (bToken==0 || bToken==1) ); 
+          assert( (bToken==0 || bToken==1) );
           assert( (bTokenChars==0 || bTokenChars==1) );
           if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
             int i;
@@ -222261,12 +228776,12 @@ static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
 ** Create a "unicode61" tokenizer.
 */
 static int fts5UnicodeCreate(
-  void *pUnused, 
+  void *pUnused,
   const char **azArg, int nArg,
   Fts5Tokenizer **ppOut
 ){
   int rc = SQLITE_OK;             /* Return code */
-  Unicode61Tokenizer *p = 0;      /* New tokenizer object */ 
+  Unicode61Tokenizer *p = 0;      /* New tokenizer object */
 
   UNUSED_PARAM(pUnused);
 
@@ -222337,7 +228852,7 @@ static int fts5UnicodeCreate(
 
 /*
 ** Return true if, for the purposes of tokenizing with the tokenizer
-** passed as the first argument, codepoint iCode is considered a token 
+** passed as the first argument, codepoint iCode is considered a token
 ** character (not a separator).
 */
 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
@@ -222429,7 +228944,7 @@ static int fts5UnicodeTokenize(
         }
       }else if( a[*zCsr]==0 ){
         /* An ascii-range separator character. End of token. */
-        break; 
+        break;
       }else{
  ascii_tokenchar:
         if( *zCsr>='A' && *zCsr<='Z' ){
@@ -222443,9 +228958,9 @@ static int fts5UnicodeTokenize(
     }
 
     /* Invoke the token callback */
-    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); 
+    rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
   }
-  
+
  tokenize_done:
   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
   return rc;
@@ -222483,7 +228998,7 @@ static void fts5PorterDelete(Fts5Tokenizer *pTok){
 ** Create a "porter" tokenizer.
 */
 static int fts5PorterCreate(
-  void *pCtx, 
+  void *pCtx,
   const char **azArg, int nArg,
   Fts5Tokenizer **ppOut
 ){
@@ -222627,7 +229142,7 @@ static int fts5Porter_Ostar(char *zStem, int nStem){
 /* porter rule condition: (m > 1 and (*S or *T)) */
 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
   assert( nStem>0 );
-  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') 
+  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
       && fts5Porter_MGt1(zStem, nStem);
 }
 
@@ -222652,16 +229167,16 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
   int ret = 0;
   int nBuf = *pnBuf;
   switch( aBuf[nBuf-2] ){
-    
-    case 'a': 
+
+    case 'a':
       if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
           *pnBuf = nBuf - 2;
         }
       }
       break;
-  
-    case 'c': 
+
+    case 'c':
       if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
           *pnBuf = nBuf - 4;
@@ -222672,24 +229187,24 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'e': 
+
+    case 'e':
       if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
           *pnBuf = nBuf - 2;
         }
       }
       break;
-  
-    case 'i': 
+
+    case 'i':
       if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
           *pnBuf = nBuf - 2;
         }
       }
       break;
-  
-    case 'l': 
+
+    case 'l':
       if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
           *pnBuf = nBuf - 4;
@@ -222700,8 +229215,8 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'n': 
+
+    case 'n':
       if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
@@ -222720,8 +229235,8 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'o': 
+
+    case 'o':
       if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
@@ -222732,16 +229247,16 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 's': 
+
+    case 's':
       if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
         }
       }
       break;
-  
-    case 't': 
+
+    case 't':
       if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
@@ -222752,76 +229267,76 @@ static int fts5PorterStep4(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'u': 
+
+    case 'u':
       if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
         }
       }
       break;
-  
-    case 'v': 
+
+    case 'v':
       if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
         }
       }
       break;
-  
-    case 'z': 
+
+    case 'z':
       if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
         }
       }
       break;
-  
+
   }
   return ret;
 }
-  
+
 
 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
   int ret = 0;
   int nBuf = *pnBuf;
   switch( aBuf[nBuf-2] ){
-    
-    case 'a': 
+
+    case 'a':
       if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
         memcpy(&aBuf[nBuf-2], "ate", 3);
         *pnBuf = nBuf - 2 + 3;
         ret = 1;
       }
       break;
-  
-    case 'b': 
+
+    case 'b':
       if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
         memcpy(&aBuf[nBuf-2], "ble", 3);
         *pnBuf = nBuf - 2 + 3;
         ret = 1;
       }
       break;
-  
-    case 'i': 
+
+    case 'i':
       if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
         memcpy(&aBuf[nBuf-2], "ize", 3);
         *pnBuf = nBuf - 2 + 3;
         ret = 1;
       }
       break;
-  
+
   }
   return ret;
 }
-  
+
 
 static int fts5PorterStep2(char *aBuf, int *pnBuf){
   int ret = 0;
   int nBuf = *pnBuf;
   switch( aBuf[nBuf-2] ){
-    
-    case 'a': 
+
+    case 'a':
       if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
           memcpy(&aBuf[nBuf-7], "ate", 3);
@@ -222834,8 +229349,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'c': 
+
+    case 'c':
       if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
           memcpy(&aBuf[nBuf-4], "ence", 4);
@@ -222848,8 +229363,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'e': 
+
+    case 'e':
       if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
           memcpy(&aBuf[nBuf-4], "ize", 3);
@@ -222857,8 +229372,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'g': 
+
+    case 'g':
       if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
           memcpy(&aBuf[nBuf-4], "log", 3);
@@ -222866,8 +229381,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'l': 
+
+    case 'l':
       if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
           memcpy(&aBuf[nBuf-3], "ble", 3);
@@ -222895,8 +229410,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'o': 
+
+    case 'o':
       if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
           memcpy(&aBuf[nBuf-7], "ize", 3);
@@ -222914,8 +229429,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 's': 
+
+    case 's':
       if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
           memcpy(&aBuf[nBuf-5], "al", 2);
@@ -222938,8 +229453,8 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 't': 
+
+    case 't':
       if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
           memcpy(&aBuf[nBuf-5], "al", 2);
@@ -222957,18 +229472,18 @@ static int fts5PorterStep2(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
+
   }
   return ret;
 }
-  
+
 
 static int fts5PorterStep3(char *aBuf, int *pnBuf){
   int ret = 0;
   int nBuf = *pnBuf;
   switch( aBuf[nBuf-2] ){
-    
-    case 'a': 
+
+    case 'a':
       if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
           memcpy(&aBuf[nBuf-4], "ic", 2);
@@ -222976,16 +229491,16 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 's': 
+
+    case 's':
       if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
           *pnBuf = nBuf - 4;
         }
       }
       break;
-  
-    case 't': 
+
+    case 't':
       if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
           memcpy(&aBuf[nBuf-5], "ic", 2);
@@ -222998,24 +229513,24 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'u': 
+
+    case 'u':
       if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
         }
       }
       break;
-  
-    case 'v': 
+
+    case 'v':
       if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
           *pnBuf = nBuf - 5;
         }
       }
       break;
-  
-    case 'z': 
+
+    case 'z':
       if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
           memcpy(&aBuf[nBuf-5], "al", 2);
@@ -223023,18 +229538,18 @@ static int fts5PorterStep3(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
+
   }
   return ret;
 }
-  
+
 
 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
   int ret = 0;
   int nBuf = *pnBuf;
   switch( aBuf[nBuf-2] ){
-    
-    case 'e': 
+
+    case 'e':
       if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
           memcpy(&aBuf[nBuf-3], "ee", 2);
@@ -223047,8 +229562,8 @@ static int fts5PorterStep1B(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
-    case 'n': 
+
+    case 'n':
       if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
         if( fts5Porter_Vowel(aBuf, nBuf-3) ){
           *pnBuf = nBuf - 3;
@@ -223056,12 +229571,12 @@ static int fts5PorterStep1B(char *aBuf, int *pnBuf){
         }
       }
       break;
-  
+
   }
   return ret;
 }
-  
-/* 
+
+/*
 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
 ***************************************************************************
 **************************************************************************/
@@ -223070,7 +229585,7 @@ static void fts5PorterStep1A(char *aBuf, int *pnBuf){
   int nBuf = *pnBuf;
   if( aBuf[nBuf-1]=='s' ){
     if( aBuf[nBuf-2]=='e' ){
-      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') 
+      if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
        || (nBuf>3 && aBuf[nBuf-3]=='i' )
       ){
         *pnBuf = nBuf-2;
@@ -223085,11 +229600,11 @@ static void fts5PorterStep1A(char *aBuf, int *pnBuf){
 }
 
 static int fts5PorterCb(
-  void *pCtx, 
+  void *pCtx,
   int tflags,
-  const char *pToken, 
-  int nToken, 
-  int iStart, 
+  const char *pToken,
+  int nToken,
+  int iStart,
   int iEnd
 ){
   PorterContext *p = (PorterContext*)pCtx;
@@ -223107,8 +229622,8 @@ static int fts5PorterCb(
   if( fts5PorterStep1B(aBuf, &nBuf) ){
     if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
       char c = aBuf[nBuf-1];
-      if( fts5PorterIsVowel(c, 0)==0 
-       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] 
+      if( fts5PorterIsVowel(c, 0)==0
+       && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
       ){
         nBuf--;
       }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
@@ -223130,7 +229645,7 @@ static int fts5PorterCb(
   /* Step 5a. */
   assert( nBuf>0 );
   if( aBuf[nBuf-1]=='e' ){
-    if( fts5Porter_MGt1(aBuf, nBuf-1) 
+    if( fts5Porter_MGt1(aBuf, nBuf-1)
      || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
     ){
       nBuf--;
@@ -223138,8 +229653,8 @@ static int fts5PorterCb(
   }
 
   /* Step 5b. */
-  if( nBuf>1 && aBuf[nBuf-1]=='l' 
-   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) 
+  if( nBuf>1 && aBuf[nBuf-1]=='l'
+   && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
   ){
     nBuf--;
   }
@@ -223170,6 +229685,133 @@ static int fts5PorterTokenize(
   );
 }
 
+/**************************************************************************
+** Start of trigram implementation.
+*/
+typedef struct TrigramTokenizer TrigramTokenizer;
+struct TrigramTokenizer {
+  int bFold;                      /* True to fold to lower-case */
+};
+
+/*
+** Free a trigram tokenizer.
+*/
+static void fts5TriDelete(Fts5Tokenizer *p){
+  sqlite3_free(p);
+}
+
+/*
+** Allocate a trigram tokenizer.
+*/
+static int fts5TriCreate(
+  void *pUnused,
+  const char **azArg,
+  int nArg,
+  Fts5Tokenizer **ppOut
+){
+  int rc = SQLITE_OK;
+  TrigramTokenizer *pNew = (TrigramTokenizer*)sqlite3_malloc(sizeof(*pNew));
+  UNUSED_PARAM(pUnused);
+  if( pNew==0 ){
+    rc = SQLITE_NOMEM;
+  }else{
+    int i;
+    pNew->bFold = 1;
+    for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
+      const char *zArg = azArg[i+1];
+      if( 0==sqlite3_stricmp(azArg[i], "case_sensitive") ){
+        if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
+          rc = SQLITE_ERROR;
+        }else{
+          pNew->bFold = (zArg[0]=='0');
+        }
+      }else{
+        rc = SQLITE_ERROR;
+      }
+    }
+    if( rc!=SQLITE_OK ){
+      fts5TriDelete((Fts5Tokenizer*)pNew);
+      pNew = 0;
+    }
+  }
+  *ppOut = (Fts5Tokenizer*)pNew;
+  return rc;
+}
+
+/*
+** Trigram tokenizer tokenize routine.
+*/
+static int fts5TriTokenize(
+  Fts5Tokenizer *pTok,
+  void *pCtx,
+  int unusedFlags,
+  const char *pText, int nText,
+  int (*xToken)(void*, int, const char*, int, int, int)
+){
+  TrigramTokenizer *p = (TrigramTokenizer*)pTok;
+  int rc = SQLITE_OK;
+  char aBuf[32];
+  const unsigned char *zIn = (const unsigned char*)pText;
+  const unsigned char *zEof = &zIn[nText];
+  u32 iCode;
+
+  UNUSED_PARAM(unusedFlags);
+  while( 1 ){
+    char *zOut = aBuf;
+    int iStart = zIn - (const unsigned char*)pText;
+    const unsigned char *zNext;
+
+    READ_UTF8(zIn, zEof, iCode);
+    if( iCode==0 ) break;
+    zNext = zIn;
+    if( zIn<zEof ){
+      if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+      WRITE_UTF8(zOut, iCode);
+      READ_UTF8(zIn, zEof, iCode);
+      if( iCode==0 ) break;
+    }else{
+      break;
+    }
+    if( zIn<zEof ){
+      if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+      WRITE_UTF8(zOut, iCode);
+      READ_UTF8(zIn, zEof, iCode);
+      if( iCode==0 ) break;
+      if( p->bFold ) iCode = sqlite3Fts5UnicodeFold(iCode, 0);
+      WRITE_UTF8(zOut, iCode);
+    }else{
+      break;
+    }
+    rc = xToken(pCtx, 0, aBuf, zOut-aBuf, iStart, iStart + zOut-aBuf);
+    if( rc!=SQLITE_OK ) break;
+    zIn = zNext;
+  }
+
+  return rc;
+}
+
+/*
+** Argument xCreate is a pointer to a constructor function for a tokenizer.
+** pTok is a tokenizer previously created using the same method. This function
+** returns one of FTS5_PATTERN_NONE, FTS5_PATTERN_LIKE or FTS5_PATTERN_GLOB
+** indicating the style of pattern matching that the tokenizer can support.
+** In practice, this is:
+**
+**     "trigram" tokenizer, case_sensitive=1 - FTS5_PATTERN_GLOB
+**     "trigram" tokenizer, case_sensitive=0 (the default) - FTS5_PATTERN_LIKE
+**     all other tokenizers - FTS5_PATTERN_NONE
+*/
+static int sqlite3Fts5TokenizerPattern(
+    int (*xCreate)(void*, const char**, int, Fts5Tokenizer**),
+    Fts5Tokenizer *pTok
+){
+  if( xCreate==fts5TriCreate ){
+    TrigramTokenizer *p = (TrigramTokenizer*)pTok;
+    return p->bFold ? FTS5_PATTERN_LIKE : FTS5_PATTERN_GLOB;
+  }
+  return FTS5_PATTERN_NONE;
+}
+
 /*
 ** Register all built-in tokenizers with FTS5.
 */
@@ -223182,8 +229824,9 @@ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
     { "unicode",   {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
     { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
     { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
+    { "trigram",   {fts5TriCreate, fts5TriDelete, fts5TriTokenize}},
   };
-  
+
   int rc = SQLITE_OK;             /* Return code */
   unsigned int i;                 /* To iterate through builtin functions */
 
@@ -223231,46 +229874,46 @@ static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
 */
 static int fts5_remove_diacritic(int c, int bComplex){
   static const unsigned short aDia[] = {
-        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
-     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
-     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
-     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
-     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896, 
-     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106, 
-     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344, 
-     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198, 
-     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468, 
-    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704, 
-    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914, 
-    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218, 
-    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554, 
-    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766, 
-    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118, 
-    63182, 63242, 63274, 63310, 63368, 63390, 
+        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
+     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
+     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
+     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
+     3456,  3696,  3712,  3728,  3744,  3766,  3832,  3896,
+     3912,  3928,  3944,  3968,  4008,  4040,  4056,  4106,
+     4138,  4170,  4202,  4234,  4266,  4296,  4312,  4344,
+     4408,  4424,  4442,  4472,  4488,  4504,  6148,  6198,
+     6264,  6280,  6360,  6429,  6505,  6529, 61448, 61468,
+    61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
+    61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
+    61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
+    62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
+    62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
+    62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
+    63182, 63242, 63274, 63310, 63368, 63390,
   };
 #define HIBIT ((unsigned char)0x80)
   static const unsigned char aChar[] = {
-    '\0',      'a',       'c',       'e',       'i',       'n',       
-    'o',       'u',       'y',       'y',       'a',       'c',       
-    'd',       'e',       'e',       'g',       'h',       'i',       
-    'j',       'k',       'l',       'n',       'o',       'r',       
-    's',       't',       'u',       'u',       'w',       'y',       
-    'z',       'o',       'u',       'a',       'i',       'o',       
-    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',       
-    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',       
-    'e',       'i',       'o',       'r',       'u',       's',       
-    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',       
-    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',      
-    '\0',      '\0',      '\0',      '\0',      'a',       'b',       
-    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT, 
-    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT, 
-    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',       
-    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',       
-    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',       
-    'w',       'x',       'y',       'z',       'h',       't',       
-    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT, 
-    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT, 
-    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',       
+    '\0',      'a',       'c',       'e',       'i',       'n',
+    'o',       'u',       'y',       'y',       'a',       'c',
+    'd',       'e',       'e',       'g',       'h',       'i',
+    'j',       'k',       'l',       'n',       'o',       'r',
+    's',       't',       'u',       'u',       'w',       'y',
+    'z',       'o',       'u',       'a',       'i',       'o',
+    'u',       'u'|HIBIT, 'a'|HIBIT, 'g',       'k',       'o',
+    'o'|HIBIT, 'j',       'g',       'n',       'a'|HIBIT, 'a',
+    'e',       'i',       'o',       'r',       'u',       's',
+    't',       'h',       'a',       'e',       'o'|HIBIT, 'o',
+    'o'|HIBIT, 'y',       '\0',      '\0',      '\0',      '\0',
+    '\0',      '\0',      '\0',      '\0',      'a',       'b',
+    'c'|HIBIT, 'd',       'd',       'e'|HIBIT, 'e',       'e'|HIBIT,
+    'f',       'g',       'h',       'h',       'i',       'i'|HIBIT,
+    'k',       'l',       'l'|HIBIT, 'l',       'm',       'n',
+    'o'|HIBIT, 'p',       'r',       'r'|HIBIT, 'r',       's',
+    's'|HIBIT, 't',       'u',       'u'|HIBIT, 'v',       'w',
+    'w',       'x',       'y',       'z',       'h',       't',
+    'w',       'y',       'a',       'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
+    'e',       'e'|HIBIT, 'e'|HIBIT, 'i',       'o',       'o'|HIBIT,
+    'o'|HIBIT, 'o'|HIBIT, 'u',       'u'|HIBIT, 'u'|HIBIT, 'y',
   };
 
   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
@@ -223400,22 +230043,23 @@ SQLITE_PRIVATE int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
     {42926, 80, 1},        {42928, 92, 1},        {42929, 86, 1},
     {42930, 90, 1},        {42931, 68, 1},        {42932, 1, 12},
     {42946, 0, 1},         {42948, 178, 1},       {42949, 82, 1},
-    {42950, 96, 1},        {43888, 94, 80},       {65313, 14, 26},
+    {42950, 96, 1},        {42951, 1, 4},         {42997, 0, 1},
+    {43888, 94, 80},       {65313, 14, 26},
   };
   static const unsigned short aiOff[] = {
-   1,     2,     8,     15,    16,    26,    28,    32,    
-   34,    37,    38,    40,    48,    63,    64,    69,    
-   71,    79,    80,    116,   202,   203,   205,   206,   
-   207,   209,   210,   211,   213,   214,   217,   218,   
-   219,   775,   928,   7264,  10792, 10795, 23217, 23221, 
-   23228, 23229, 23231, 23254, 23256, 23275, 23278, 26672, 
-   30152, 30204, 35267, 54721, 54753, 54754, 54756, 54787, 
-   54793, 54809, 57153, 57274, 57921, 58019, 58363, 59314, 
-   59315, 59324, 59325, 59326, 59332, 59356, 61722, 62528, 
-   65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424, 
-   65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480, 
-   65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528, 
-   65529, 
+   1,     2,     8,     15,    16,    26,    28,    32,
+   34,    37,    38,    40,    48,    63,    64,    69,
+   71,    79,    80,    116,   202,   203,   205,   206,
+   207,   209,   210,   211,   213,   214,   217,   218,
+   219,   775,   928,   7264,  10792, 10795, 23217, 23221,
+   23228, 23229, 23231, 23254, 23256, 23275, 23278, 26672,
+   30152, 30204, 35267, 54721, 54753, 54754, 54756, 54787,
+   54793, 54809, 57153, 57274, 57921, 58019, 58363, 59314,
+   59315, 59324, 59325, 59326, 59332, 59356, 61722, 62528,
+   65268, 65341, 65373, 65406, 65408, 65410, 65415, 65424,
+   65436, 65439, 65450, 65462, 65472, 65476, 65478, 65480,
+   65482, 65488, 65506, 65511, 65514, 65521, 65527, 65528,
+   65529,
   };
 
   int ret = c;
@@ -223453,7 +230097,7 @@ SQLITE_PRIVATE int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
       ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
     }
   }
-  
+
   else if( c>=66560 && c<66600 ){
     ret = c + 40;
   }
@@ -223477,7 +230121,7 @@ SQLITE_PRIVATE int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
 }
 
 
-static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){ 
+static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
   aArray[0] = 1;
   switch( zCat[0] ){
     case 'C':
@@ -223487,7 +230131,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'n': aArray[3] = 1; break;
             case 's': aArray[4] = 1; break;
             case 'o': aArray[31] = 1; break;
-            case '*': 
+            case '*':
               aArray[1] = 1;
               aArray[2] = 1;
               aArray[3] = 1;
@@ -223505,7 +230149,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 't': aArray[8] = 1; break;
             case 'u': aArray[9] = 1; break;
             case 'C': aArray[30] = 1; break;
-            case '*': 
+            case '*':
               aArray[5] = 1;
               aArray[6] = 1;
               aArray[7] = 1;
@@ -223521,7 +230165,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'c': aArray[10] = 1; break;
             case 'e': aArray[11] = 1; break;
             case 'n': aArray[12] = 1; break;
-            case '*': 
+            case '*':
               aArray[10] = 1;
               aArray[11] = 1;
               aArray[12] = 1;
@@ -223534,7 +230178,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'd': aArray[13] = 1; break;
             case 'l': aArray[14] = 1; break;
             case 'o': aArray[15] = 1; break;
-            case '*': 
+            case '*':
               aArray[13] = 1;
               aArray[14] = 1;
               aArray[15] = 1;
@@ -223551,7 +230195,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'i': aArray[20] = 1; break;
             case 'o': aArray[21] = 1; break;
             case 's': aArray[22] = 1; break;
-            case '*': 
+            case '*':
               aArray[16] = 1;
               aArray[17] = 1;
               aArray[18] = 1;
@@ -223569,7 +230213,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'k': aArray[24] = 1; break;
             case 'm': aArray[25] = 1; break;
             case 'o': aArray[26] = 1; break;
-            case '*': 
+            case '*':
               aArray[23] = 1;
               aArray[24] = 1;
               aArray[25] = 1;
@@ -223583,7 +230227,7 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
             case 'l': aArray[27] = 1; break;
             case 'p': aArray[28] = 1; break;
             case 's': aArray[29] = 1; break;
-            case '*': 
+            case '*':
               aArray[27] = 1;
               aArray[28] = 1;
               aArray[29] = 1;
@@ -223596,453 +230240,461 @@ static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
 }
 
 static const u16 aFts5UnicodeBlock[] = {
-    0,     1533,  2167,  2178,  2178,  2178,  2178,  2178,  2178,  2178,  
-    2178,  2178,  2178,  2178,  2178,  2181,  2183,  
+    0,     1543,  2209,  2220,  2222,  2222,  2222,  2222,  2222,  2222,
+    2222,  2222,  2222,  2222,  2222,  2225,  2227,
   };
 static const u16 aFts5UnicodeMap[] = {
-    0,     32,    33,    36,    37,    40,    41,    42,    43,    44,    
-    45,    46,    48,    58,    60,    63,    65,    91,    92,    93,    
-    94,    95,    96,    97,    123,   124,   125,   126,   127,   160,   
-    161,   162,   166,   167,   168,   169,   170,   171,   172,   173,   
-    174,   175,   176,   177,   178,   180,   181,   182,   184,   185,   
-    186,   187,   188,   191,   192,   215,   216,   223,   247,   248,   
-    256,   312,   313,   329,   330,   377,   383,   385,   387,   388,   
-    391,   394,   396,   398,   402,   403,   405,   406,   409,   412,   
-    414,   415,   417,   418,   423,   427,   428,   431,   434,   436,   
-    437,   440,   442,   443,   444,   446,   448,   452,   453,   454,   
-    455,   456,   457,   458,   459,   460,   461,   477,   478,   496,   
-    497,   498,   499,   500,   503,   505,   506,   564,   570,   572,   
-    573,   575,   577,   580,   583,   584,   592,   660,   661,   688,   
-    706,   710,   722,   736,   741,   748,   749,   750,   751,   768,   
-    880,   884,   885,   886,   890,   891,   894,   895,   900,   902,   
-    903,   904,   908,   910,   912,   913,   931,   940,   975,   977,   
-    978,   981,   984,   1008,  1012,  1014,  1015,  1018,  1020,  1021,  
-    1072,  1120,  1154,  1155,  1160,  1162,  1217,  1231,  1232,  1329,  
-    1369,  1370,  1376,  1417,  1418,  1421,  1423,  1425,  1470,  1471,  
-    1472,  1473,  1475,  1476,  1478,  1479,  1488,  1519,  1523,  1536,  
-    1542,  1545,  1547,  1548,  1550,  1552,  1563,  1564,  1566,  1568,  
-    1600,  1601,  1611,  1632,  1642,  1646,  1648,  1649,  1748,  1749,  
-    1750,  1757,  1758,  1759,  1765,  1767,  1769,  1770,  1774,  1776,  
-    1786,  1789,  1791,  1792,  1807,  1808,  1809,  1810,  1840,  1869,  
-    1958,  1969,  1984,  1994,  2027,  2036,  2038,  2039,  2042,  2045,  
-    2046,  2048,  2070,  2074,  2075,  2084,  2085,  2088,  2089,  2096,  
-    2112,  2137,  2142,  2144,  2208,  2230,  2259,  2274,  2275,  2307,  
-    2308,  2362,  2363,  2364,  2365,  2366,  2369,  2377,  2381,  2382,  
-    2384,  2385,  2392,  2402,  2404,  2406,  2416,  2417,  2418,  2433,  
-    2434,  2437,  2447,  2451,  2474,  2482,  2486,  2492,  2493,  2494,  
-    2497,  2503,  2507,  2509,  2510,  2519,  2524,  2527,  2530,  2534,  
-    2544,  2546,  2548,  2554,  2555,  2556,  2557,  2558,  2561,  2563,  
-    2565,  2575,  2579,  2602,  2610,  2613,  2616,  2620,  2622,  2625,  
-    2631,  2635,  2641,  2649,  2654,  2662,  2672,  2674,  2677,  2678,  
-    2689,  2691,  2693,  2703,  2707,  2730,  2738,  2741,  2748,  2749,  
-    2750,  2753,  2759,  2761,  2763,  2765,  2768,  2784,  2786,  2790,  
-    2800,  2801,  2809,  2810,  2817,  2818,  2821,  2831,  2835,  2858,  
-    2866,  2869,  2876,  2877,  2878,  2879,  2880,  2881,  2887,  2891,  
-    2893,  2902,  2903,  2908,  2911,  2914,  2918,  2928,  2929,  2930,  
-    2946,  2947,  2949,  2958,  2962,  2969,  2972,  2974,  2979,  2984,  
-    2990,  3006,  3008,  3009,  3014,  3018,  3021,  3024,  3031,  3046,  
-    3056,  3059,  3065,  3066,  3072,  3073,  3076,  3077,  3086,  3090,  
-    3114,  3133,  3134,  3137,  3142,  3146,  3157,  3160,  3168,  3170,  
-    3174,  3191,  3192,  3199,  3200,  3201,  3202,  3204,  3205,  3214,  
-    3218,  3242,  3253,  3260,  3261,  3262,  3263,  3264,  3270,  3271,  
-    3274,  3276,  3285,  3294,  3296,  3298,  3302,  3313,  3328,  3330,  
-    3333,  3342,  3346,  3387,  3389,  3390,  3393,  3398,  3402,  3405,  
-    3406,  3407,  3412,  3415,  3416,  3423,  3426,  3430,  3440,  3449,  
-    3450,  3458,  3461,  3482,  3507,  3517,  3520,  3530,  3535,  3538,  
-    3542,  3544,  3558,  3570,  3572,  3585,  3633,  3634,  3636,  3647,  
-    3648,  3654,  3655,  3663,  3664,  3674,  3713,  3716,  3718,  3724,  
-    3749,  3751,  3761,  3762,  3764,  3773,  3776,  3782,  3784,  3792,  
-    3804,  3840,  3841,  3844,  3859,  3860,  3861,  3864,  3866,  3872,  
-    3882,  3892,  3893,  3894,  3895,  3896,  3897,  3898,  3899,  3900,  
-    3901,  3902,  3904,  3913,  3953,  3967,  3968,  3973,  3974,  3976,  
-    3981,  3993,  4030,  4038,  4039,  4046,  4048,  4053,  4057,  4096,  
-    4139,  4141,  4145,  4146,  4152,  4153,  4155,  4157,  4159,  4160,  
-    4170,  4176,  4182,  4184,  4186,  4190,  4193,  4194,  4197,  4199,  
-    4206,  4209,  4213,  4226,  4227,  4229,  4231,  4237,  4238,  4239,  
-    4240,  4250,  4253,  4254,  4256,  4295,  4301,  4304,  4347,  4348,  
-    4349,  4352,  4682,  4688,  4696,  4698,  4704,  4746,  4752,  4786,  
-    4792,  4800,  4802,  4808,  4824,  4882,  4888,  4957,  4960,  4969,  
-    4992,  5008,  5024,  5112,  5120,  5121,  5741,  5742,  5743,  5760,  
-    5761,  5787,  5788,  5792,  5867,  5870,  5873,  5888,  5902,  5906,  
-    5920,  5938,  5941,  5952,  5970,  5984,  5998,  6002,  6016,  6068,  
-    6070,  6071,  6078,  6086,  6087,  6089,  6100,  6103,  6104,  6107,  
-    6108,  6109,  6112,  6128,  6144,  6150,  6151,  6155,  6158,  6160,  
-    6176,  6211,  6212,  6272,  6277,  6279,  6313,  6314,  6320,  6400,  
-    6432,  6435,  6439,  6441,  6448,  6450,  6451,  6457,  6464,  6468,  
-    6470,  6480,  6512,  6528,  6576,  6608,  6618,  6622,  6656,  6679,  
-    6681,  6683,  6686,  6688,  6741,  6742,  6743,  6744,  6752,  6753,  
-    6754,  6755,  6757,  6765,  6771,  6783,  6784,  6800,  6816,  6823,  
-    6824,  6832,  6846,  6912,  6916,  6917,  6964,  6965,  6966,  6971,  
-    6972,  6973,  6978,  6979,  6981,  6992,  7002,  7009,  7019,  7028,  
-    7040,  7042,  7043,  7073,  7074,  7078,  7080,  7082,  7083,  7086,  
-    7088,  7098,  7142,  7143,  7144,  7146,  7149,  7150,  7151,  7154,  
-    7164,  7168,  7204,  7212,  7220,  7222,  7227,  7232,  7245,  7248,  
-    7258,  7288,  7294,  7296,  7312,  7357,  7360,  7376,  7379,  7380,  
-    7393,  7394,  7401,  7405,  7406,  7412,  7413,  7415,  7416,  7418,  
-    7424,  7468,  7531,  7544,  7545,  7579,  7616,  7675,  7680,  7830,  
-    7838,  7936,  7944,  7952,  7960,  7968,  7976,  7984,  7992,  8000,  
-    8008,  8016,  8025,  8027,  8029,  8031,  8033,  8040,  8048,  8064,  
-    8072,  8080,  8088,  8096,  8104,  8112,  8118,  8120,  8124,  8125,  
-    8126,  8127,  8130,  8134,  8136,  8140,  8141,  8144,  8150,  8152,  
-    8157,  8160,  8168,  8173,  8178,  8182,  8184,  8188,  8189,  8192,  
-    8203,  8208,  8214,  8216,  8217,  8218,  8219,  8221,  8222,  8223,  
-    8224,  8232,  8233,  8234,  8239,  8240,  8249,  8250,  8251,  8255,  
-    8257,  8260,  8261,  8262,  8263,  8274,  8275,  8276,  8277,  8287,  
-    8288,  8294,  8304,  8305,  8308,  8314,  8317,  8318,  8319,  8320,  
-    8330,  8333,  8334,  8336,  8352,  8400,  8413,  8417,  8418,  8421,  
-    8448,  8450,  8451,  8455,  8456,  8458,  8459,  8462,  8464,  8467,  
-    8468,  8469,  8470,  8472,  8473,  8478,  8484,  8485,  8486,  8487,  
-    8488,  8489,  8490,  8494,  8495,  8496,  8500,  8501,  8505,  8506,  
-    8508,  8510,  8512,  8517,  8519,  8522,  8523,  8524,  8526,  8527,  
-    8528,  8544,  8579,  8581,  8585,  8586,  8592,  8597,  8602,  8604,  
-    8608,  8609,  8611,  8612,  8614,  8615,  8622,  8623,  8654,  8656,  
-    8658,  8659,  8660,  8661,  8692,  8960,  8968,  8969,  8970,  8971,  
-    8972,  8992,  8994,  9001,  9002,  9003,  9084,  9085,  9115,  9140,  
-    9180,  9186,  9280,  9312,  9372,  9450,  9472,  9655,  9656,  9665,  
-    9666,  9720,  9728,  9839,  9840,  10088, 10089, 10090, 10091, 10092, 
-    10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101, 10102, 
-    10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217, 10218, 
-    10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627, 10628, 
-    10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637, 10638, 
-    10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647, 10648, 
-    10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750, 11008, 
-    11056, 11077, 11079, 11085, 11126, 11160, 11264, 11312, 11360, 11363, 
-    11365, 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 
-    11393, 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 
-    11520, 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 
-    11696, 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 
-    11780, 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 
-    11800, 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 
-    11812, 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 
-    11836, 11840, 11841, 11842, 11843, 11904, 11931, 12032, 12272, 12288, 
-    12289, 12292, 12293, 12294, 12295, 12296, 12297, 12298, 12299, 12300, 
-    12301, 12302, 12303, 12304, 12305, 12306, 12308, 12309, 12310, 12311, 
-    12312, 12313, 12314, 12315, 12316, 12317, 12318, 12320, 12321, 12330, 
-    12334, 12336, 12337, 12342, 12344, 12347, 12348, 12349, 12350, 12353, 
-    12441, 12443, 12445, 12447, 12448, 12449, 12539, 12540, 12543, 12549, 
-    12593, 12688, 12690, 12694, 12704, 12736, 12784, 12800, 12832, 12842, 
-    12872, 12880, 12881, 12896, 12928, 12938, 12977, 12992, 13312, 19893, 
-    19904, 19968, 40943, 40960, 40981, 40982, 42128, 42192, 42232, 42238, 
-    42240, 42508, 42509, 42512, 42528, 42538, 42560, 42606, 42607, 42608, 
-    42611, 42612, 42622, 42623, 42624, 42652, 42654, 42656, 42726, 42736, 
-    42738, 42752, 42775, 42784, 42786, 42800, 42802, 42864, 42865, 42873, 
-    42878, 42888, 42889, 42891, 42895, 42896, 42900, 42902, 42923, 42927, 
-    42928, 42933, 42934, 42946, 42949, 42999, 43000, 43002, 43003, 43010, 
-    43011, 43014, 43015, 43019, 43020, 43043, 43045, 43047, 43048, 43056, 
-    43062, 43064, 43065, 43072, 43124, 43136, 43138, 43188, 43204, 43214, 
-    43216, 43232, 43250, 43256, 43259, 43260, 43261, 43263, 43264, 43274, 
-    43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395, 43396, 
-    43443, 43444, 43446, 43450, 43452, 43454, 43457, 43471, 43472, 43486, 
-    43488, 43493, 43494, 43495, 43504, 43514, 43520, 43561, 43567, 43569, 
-    43571, 43573, 43584, 43587, 43588, 43596, 43597, 43600, 43612, 43616, 
-    43632, 43633, 43639, 43642, 43643, 43644, 43645, 43646, 43696, 43697, 
-    43698, 43701, 43703, 43705, 43710, 43712, 43713, 43714, 43739, 43741, 
-    43742, 43744, 43755, 43756, 43758, 43760, 43762, 43763, 43765, 43766, 
-    43777, 43785, 43793, 43808, 43816, 43824, 43867, 43868, 43872, 43888, 
-    43968, 44003, 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 
-    44032, 55203, 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 
-    63744, 64112, 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 
-    64318, 64320, 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 
-    65008, 65020, 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 
-    65073, 65075, 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 
-    65085, 65086, 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 
-    65096, 65097, 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 
-    65117, 65118, 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 
-    65142, 65279, 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 
-    65293, 65294, 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 
-    65342, 65343, 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 
-    65377, 65378, 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 
-    65482, 65490, 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 
-    65517, 65529, 65532, 0,     13,    40,    60,    63,    80,    128,   
-    256,   263,   311,   320,   373,   377,   394,   396,   400,   416,   
-    464,   509,   640,   672,   736,   737,   768,   800,   813,   833,   
-    834,   842,   848,   886,   896,   927,   928,   968,   976,   977,   
-    1024,  1064,  1104,  1184,  1200,  1240,  1280,  1328,  1391,  1536,  
-    1856,  1888,  2048,  2056,  2058,  2103,  2108,  2111,  2135,  2136,  
-    2144,  2167,  2169,  2176,  2215,  2272,  2292,  2299,  2304,  2326,  
-    2335,  2336,  2367,  2432,  2492,  2494,  2496,  2514,  2560,  2561,  
-    2565,  2572,  2576,  2581,  2585,  2616,  2623,  2624,  2640,  2656,  
-    2685,  2687,  2688,  2717,  2752,  2760,  2761,  2789,  2795,  2800,  
-    2816,  2873,  2880,  2904,  2912,  2936,  2944,  2969,  2985,  3072,  
-    3200,  3264,  3322,  3328,  3364,  3376,  3680,  3840,  3869,  3879,  
-    3888,  3910,  3921,  3925,  4064,  4096,  4097,  4098,  4099,  4152,  
-    4167,  4178,  4198,  4223,  4226,  4227,  4272,  4275,  4279,  4281,  
-    4283,  4285,  4286,  4301,  4304,  4336,  4352,  4355,  4391,  4396,  
-    4397,  4406,  4416,  4420,  4421,  4432,  4467,  4468,  4470,  4480,  
-    4482,  4483,  4531,  4534,  4543,  4545,  4549,  4553,  4557,  4560,  
-    4570,  4571,  4572,  4573,  4577,  4608,  4627,  4652,  4655,  4658,  
-    4660,  4661,  4662,  4664,  4670,  4736,  4744,  4746,  4751,  4767,  
-    4777,  4784,  4831,  4832,  4835,  4848,  4864,  4866,  4869,  4879,  
-    4883,  4906,  4914,  4917,  4923,  4925,  4926,  4928,  4929,  4935,  
-    4939,  4944,  4951,  4957,  4962,  4966,  4976,  5120,  5173,  5176,  
-    5184,  5186,  5189,  5190,  5191,  5195,  5200,  5211,  5213,  5214,  
-    5215,  5248,  5296,  5299,  5305,  5306,  5307,  5311,  5313,  5314,  
-    5316,  5318,  5319,  5328,  5504,  5551,  5554,  5560,  5564,  5566,  
-    5567,  5569,  5592,  5596,  5632,  5680,  5683,  5691,  5693,  5694,  
-    5695,  5697,  5700,  5712,  5728,  5760,  5803,  5804,  5805,  5806,  
-    5808,  5814,  5815,  5816,  5824,  5888,  5917,  5920,  5922,  5926,  
-    5927,  5936,  5946,  5948,  5951,  6144,  6188,  6191,  6200,  6201,  
-    6203,  6304,  6336,  6368,  6378,  6399,  6560,  6570,  6609,  6612,  
-    6618,  6620,  6624,  6625,  6626,  6627,  6628,  6656,  6657,  6667,  
-    6707,  6713,  6714,  6715,  6719,  6727,  6736,  6737,  6743,  6745,  
-    6748,  6794,  6807,  6808,  6810,  6813,  6814,  6848,  7168,  7178,  
-    7215,  7216,  7224,  7230,  7231,  7232,  7233,  7248,  7258,  7280,  
-    7282,  7314,  7337,  7338,  7345,  7346,  7348,  7349,  7424,  7432,  
-    7435,  7473,  7482,  7484,  7487,  7494,  7495,  7504,  7520,  7527,  
-    7530,  7562,  7568,  7571,  7573,  7574,  7575,  7576,  7584,  7904,  
-    7923,  7925,  7927,  8128,  8149,  8157,  8161,  8191,  8192,  9216,  
-    9328,  9344,  12288, 13360, 17408, 26624, 27200, 27232, 27246, 27344, 
-    27376, 27381, 27392, 27440, 27447, 27452, 27456, 27460, 27461, 27472, 
-    27483, 27491, 27517, 28224, 28256, 28288, 28311, 28416, 28495, 28496, 
-    28497, 28559, 28563, 28640, 28642, 28643, 28672, 34807, 34816, 45056, 
-    45392, 45412, 45424, 48128, 48240, 48256, 48272, 48284, 48285, 48287, 
-    48288, 53248, 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 
-    53635, 53637, 53644, 53674, 53678, 53760, 53826, 53829, 53984, 54016, 
-    54112, 54272, 54298, 54324, 54350, 54358, 54376, 54402, 54428, 54430, 
-    54434, 54437, 54441, 54446, 54454, 54459, 54461, 54469, 54480, 54506, 
-    54532, 54535, 54541, 54550, 54558, 54584, 54587, 54592, 54598, 54602, 
-    54610, 54636, 54662, 54688, 54714, 54740, 54766, 54792, 54818, 54844, 
-    54870, 54896, 54922, 54952, 54977, 54978, 55003, 55004, 55010, 55035, 
-    55036, 55061, 55062, 55068, 55093, 55094, 55119, 55120, 55126, 55151, 
-    55152, 55177, 55178, 55184, 55209, 55210, 55235, 55236, 55242, 55246, 
-    55296, 55808, 55863, 55867, 55917, 55925, 55926, 55940, 55941, 55943, 
-    55963, 55969, 57344, 57352, 57371, 57379, 57382, 57600, 57648, 57655, 
-    57664, 57678, 57679, 58048, 58092, 58096, 58111, 59392, 59591, 59600, 
-    59648, 59682, 59716, 59723, 59728, 59742, 60529, 60588, 60589, 60592, 
-    60593, 60673, 60718, 60719, 60928, 60933, 60961, 60964, 60967, 60969, 
-    60980, 60985, 60987, 60994, 60999, 61001, 61003, 61005, 61009, 61012, 
-    61015, 61017, 61019, 61021, 61023, 61025, 61028, 61031, 61036, 61044, 
-    61049, 61054, 61056, 61067, 61089, 61093, 61099, 61168, 61440, 61488, 
-    61600, 61617, 61633, 61649, 61696, 61712, 61808, 61926, 61968, 62016, 
-    62032, 62048, 62208, 62459, 62464, 63200, 63216, 63232, 63360, 63456, 
-    63488, 63504, 63568, 63584, 63632, 63744, 63757, 63859, 63866, 63909, 
-    63918, 63949, 64096, 64112, 64120, 64128, 64144, 0,     42710, 42752, 
-    46900, 46912, 47133, 47136, 52897, 52912, 60384, 63488, 1,     32,    
-    256,   0,     65533, 
+    0,     32,    33,    36,    37,    40,    41,    42,    43,    44,
+    45,    46,    48,    58,    60,    63,    65,    91,    92,    93,
+    94,    95,    96,    97,    123,   124,   125,   126,   127,   160,
+    161,   162,   166,   167,   168,   169,   170,   171,   172,   173,
+    174,   175,   176,   177,   178,   180,   181,   182,   184,   185,
+    186,   187,   188,   191,   192,   215,   216,   223,   247,   248,
+    256,   312,   313,   329,   330,   377,   383,   385,   387,   388,
+    391,   394,   396,   398,   402,   403,   405,   406,   409,   412,
+    414,   415,   417,   418,   423,   427,   428,   431,   434,   436,
+    437,   440,   442,   443,   444,   446,   448,   452,   453,   454,
+    455,   456,   457,   458,   459,   460,   461,   477,   478,   496,
+    497,   498,   499,   500,   503,   505,   506,   564,   570,   572,
+    573,   575,   577,   580,   583,   584,   592,   660,   661,   688,
+    706,   710,   722,   736,   741,   748,   749,   750,   751,   768,
+    880,   884,   885,   886,   890,   891,   894,   895,   900,   902,
+    903,   904,   908,   910,   912,   913,   931,   940,   975,   977,
+    978,   981,   984,   1008,  1012,  1014,  1015,  1018,  1020,  1021,
+    1072,  1120,  1154,  1155,  1160,  1162,  1217,  1231,  1232,  1329,
+    1369,  1370,  1376,  1417,  1418,  1421,  1423,  1425,  1470,  1471,
+    1472,  1473,  1475,  1476,  1478,  1479,  1488,  1519,  1523,  1536,
+    1542,  1545,  1547,  1548,  1550,  1552,  1563,  1564,  1566,  1568,
+    1600,  1601,  1611,  1632,  1642,  1646,  1648,  1649,  1748,  1749,
+    1750,  1757,  1758,  1759,  1765,  1767,  1769,  1770,  1774,  1776,
+    1786,  1789,  1791,  1792,  1807,  1808,  1809,  1810,  1840,  1869,
+    1958,  1969,  1984,  1994,  2027,  2036,  2038,  2039,  2042,  2045,
+    2046,  2048,  2070,  2074,  2075,  2084,  2085,  2088,  2089,  2096,
+    2112,  2137,  2142,  2144,  2208,  2230,  2259,  2274,  2275,  2307,
+    2308,  2362,  2363,  2364,  2365,  2366,  2369,  2377,  2381,  2382,
+    2384,  2385,  2392,  2402,  2404,  2406,  2416,  2417,  2418,  2433,
+    2434,  2437,  2447,  2451,  2474,  2482,  2486,  2492,  2493,  2494,
+    2497,  2503,  2507,  2509,  2510,  2519,  2524,  2527,  2530,  2534,
+    2544,  2546,  2548,  2554,  2555,  2556,  2557,  2558,  2561,  2563,
+    2565,  2575,  2579,  2602,  2610,  2613,  2616,  2620,  2622,  2625,
+    2631,  2635,  2641,  2649,  2654,  2662,  2672,  2674,  2677,  2678,
+    2689,  2691,  2693,  2703,  2707,  2730,  2738,  2741,  2748,  2749,
+    2750,  2753,  2759,  2761,  2763,  2765,  2768,  2784,  2786,  2790,
+    2800,  2801,  2809,  2810,  2817,  2818,  2821,  2831,  2835,  2858,
+    2866,  2869,  2876,  2877,  2878,  2879,  2880,  2881,  2887,  2891,
+    2893,  2901,  2903,  2908,  2911,  2914,  2918,  2928,  2929,  2930,
+    2946,  2947,  2949,  2958,  2962,  2969,  2972,  2974,  2979,  2984,
+    2990,  3006,  3008,  3009,  3014,  3018,  3021,  3024,  3031,  3046,
+    3056,  3059,  3065,  3066,  3072,  3073,  3076,  3077,  3086,  3090,
+    3114,  3133,  3134,  3137,  3142,  3146,  3157,  3160,  3168,  3170,
+    3174,  3191,  3192,  3199,  3200,  3201,  3202,  3204,  3205,  3214,
+    3218,  3242,  3253,  3260,  3261,  3262,  3263,  3264,  3270,  3271,
+    3274,  3276,  3285,  3294,  3296,  3298,  3302,  3313,  3328,  3330,
+    3332,  3342,  3346,  3387,  3389,  3390,  3393,  3398,  3402,  3405,
+    3406,  3407,  3412,  3415,  3416,  3423,  3426,  3430,  3440,  3449,
+    3450,  3457,  3458,  3461,  3482,  3507,  3517,  3520,  3530,  3535,
+    3538,  3542,  3544,  3558,  3570,  3572,  3585,  3633,  3634,  3636,
+    3647,  3648,  3654,  3655,  3663,  3664,  3674,  3713,  3716,  3718,
+    3724,  3749,  3751,  3761,  3762,  3764,  3773,  3776,  3782,  3784,
+    3792,  3804,  3840,  3841,  3844,  3859,  3860,  3861,  3864,  3866,
+    3872,  3882,  3892,  3893,  3894,  3895,  3896,  3897,  3898,  3899,
+    3900,  3901,  3902,  3904,  3913,  3953,  3967,  3968,  3973,  3974,
+    3976,  3981,  3993,  4030,  4038,  4039,  4046,  4048,  4053,  4057,
+    4096,  4139,  4141,  4145,  4146,  4152,  4153,  4155,  4157,  4159,
+    4160,  4170,  4176,  4182,  4184,  4186,  4190,  4193,  4194,  4197,
+    4199,  4206,  4209,  4213,  4226,  4227,  4229,  4231,  4237,  4238,
+    4239,  4240,  4250,  4253,  4254,  4256,  4295,  4301,  4304,  4347,
+    4348,  4349,  4352,  4682,  4688,  4696,  4698,  4704,  4746,  4752,
+    4786,  4792,  4800,  4802,  4808,  4824,  4882,  4888,  4957,  4960,
+    4969,  4992,  5008,  5024,  5112,  5120,  5121,  5741,  5742,  5743,
+    5760,  5761,  5787,  5788,  5792,  5867,  5870,  5873,  5888,  5902,
+    5906,  5920,  5938,  5941,  5952,  5970,  5984,  5998,  6002,  6016,
+    6068,  6070,  6071,  6078,  6086,  6087,  6089,  6100,  6103,  6104,
+    6107,  6108,  6109,  6112,  6128,  6144,  6150,  6151,  6155,  6158,
+    6160,  6176,  6211,  6212,  6272,  6277,  6279,  6313,  6314,  6320,
+    6400,  6432,  6435,  6439,  6441,  6448,  6450,  6451,  6457,  6464,
+    6468,  6470,  6480,  6512,  6528,  6576,  6608,  6618,  6622,  6656,
+    6679,  6681,  6683,  6686,  6688,  6741,  6742,  6743,  6744,  6752,
+    6753,  6754,  6755,  6757,  6765,  6771,  6783,  6784,  6800,  6816,
+    6823,  6824,  6832,  6846,  6847,  6912,  6916,  6917,  6964,  6965,
+    6966,  6971,  6972,  6973,  6978,  6979,  6981,  6992,  7002,  7009,
+    7019,  7028,  7040,  7042,  7043,  7073,  7074,  7078,  7080,  7082,
+    7083,  7086,  7088,  7098,  7142,  7143,  7144,  7146,  7149,  7150,
+    7151,  7154,  7164,  7168,  7204,  7212,  7220,  7222,  7227,  7232,
+    7245,  7248,  7258,  7288,  7294,  7296,  7312,  7357,  7360,  7376,
+    7379,  7380,  7393,  7394,  7401,  7405,  7406,  7412,  7413,  7415,
+    7416,  7418,  7424,  7468,  7531,  7544,  7545,  7579,  7616,  7675,
+    7680,  7830,  7838,  7936,  7944,  7952,  7960,  7968,  7976,  7984,
+    7992,  8000,  8008,  8016,  8025,  8027,  8029,  8031,  8033,  8040,
+    8048,  8064,  8072,  8080,  8088,  8096,  8104,  8112,  8118,  8120,
+    8124,  8125,  8126,  8127,  8130,  8134,  8136,  8140,  8141,  8144,
+    8150,  8152,  8157,  8160,  8168,  8173,  8178,  8182,  8184,  8188,
+    8189,  8192,  8203,  8208,  8214,  8216,  8217,  8218,  8219,  8221,
+    8222,  8223,  8224,  8232,  8233,  8234,  8239,  8240,  8249,  8250,
+    8251,  8255,  8257,  8260,  8261,  8262,  8263,  8274,  8275,  8276,
+    8277,  8287,  8288,  8294,  8304,  8305,  8308,  8314,  8317,  8318,
+    8319,  8320,  8330,  8333,  8334,  8336,  8352,  8400,  8413,  8417,
+    8418,  8421,  8448,  8450,  8451,  8455,  8456,  8458,  8459,  8462,
+    8464,  8467,  8468,  8469,  8470,  8472,  8473,  8478,  8484,  8485,
+    8486,  8487,  8488,  8489,  8490,  8494,  8495,  8496,  8500,  8501,
+    8505,  8506,  8508,  8510,  8512,  8517,  8519,  8522,  8523,  8524,
+    8526,  8527,  8528,  8544,  8579,  8581,  8585,  8586,  8592,  8597,
+    8602,  8604,  8608,  8609,  8611,  8612,  8614,  8615,  8622,  8623,
+    8654,  8656,  8658,  8659,  8660,  8661,  8692,  8960,  8968,  8969,
+    8970,  8971,  8972,  8992,  8994,  9001,  9002,  9003,  9084,  9085,
+    9115,  9140,  9180,  9186,  9280,  9312,  9372,  9450,  9472,  9655,
+    9656,  9665,  9666,  9720,  9728,  9839,  9840,  10088, 10089, 10090,
+    10091, 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100,
+    10101, 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216,
+    10217, 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496,
+    10627, 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636,
+    10637, 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646,
+    10647, 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749,
+    10750, 11008, 11056, 11077, 11079, 11085, 11126, 11159, 11264, 11312,
+    11360, 11363, 11365, 11367, 11374, 11377, 11378, 11380, 11381, 11383,
+    11388, 11390, 11393, 11394, 11492, 11493, 11499, 11503, 11506, 11513,
+    11517, 11518, 11520, 11559, 11565, 11568, 11631, 11632, 11647, 11648,
+    11680, 11688, 11696, 11704, 11712, 11720, 11728, 11736, 11744, 11776,
+    11778, 11779, 11780, 11781, 11782, 11785, 11786, 11787, 11788, 11789,
+    11790, 11799, 11800, 11802, 11803, 11804, 11805, 11806, 11808, 11809,
+    11810, 11811, 11812, 11813, 11814, 11815, 11816, 11817, 11818, 11823,
+    11824, 11834, 11836, 11840, 11841, 11842, 11843, 11856, 11858, 11904,
+    11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
+    12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
+    12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
+    12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
+    12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
+    12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
+    12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
+    12977, 12992, 13312, 19903, 19904, 19968, 40956, 40960, 40981, 40982,
+    42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528, 42538,
+    42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624, 42652,
+    42654, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
+    42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42895, 42896,
+    42900, 42902, 42923, 42927, 42928, 42933, 42934, 42946, 42949, 42952,
+    42953, 42997, 42999, 43000, 43002, 43003, 43010, 43011, 43014, 43015,
+    43019, 43020, 43043, 43045, 43047, 43048, 43052, 43056, 43062, 43064,
+    43065, 43072, 43124, 43136, 43138, 43188, 43204, 43214, 43216, 43232,
+    43250, 43256, 43259, 43260, 43261, 43263, 43264, 43274, 43302, 43310,
+    43312, 43335, 43346, 43359, 43360, 43392, 43395, 43396, 43443, 43444,
+    43446, 43450, 43452, 43454, 43457, 43471, 43472, 43486, 43488, 43493,
+    43494, 43495, 43504, 43514, 43520, 43561, 43567, 43569, 43571, 43573,
+    43584, 43587, 43588, 43596, 43597, 43600, 43612, 43616, 43632, 43633,
+    43639, 43642, 43643, 43644, 43645, 43646, 43696, 43697, 43698, 43701,
+    43703, 43705, 43710, 43712, 43713, 43714, 43739, 43741, 43742, 43744,
+    43755, 43756, 43758, 43760, 43762, 43763, 43765, 43766, 43777, 43785,
+    43793, 43808, 43816, 43824, 43867, 43868, 43872, 43881, 43882, 43888,
+    43968, 44003, 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016,
+    44032, 55203, 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743,
+    63744, 64112, 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312,
+    64318, 64320, 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914,
+    65008, 65020, 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072,
+    65073, 65075, 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084,
+    65085, 65086, 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095,
+    65096, 65097, 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116,
+    65117, 65118, 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136,
+    65142, 65279, 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292,
+    65293, 65294, 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341,
+    65342, 65343, 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376,
+    65377, 65378, 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474,
+    65482, 65490, 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513,
+    65517, 65529, 65532, 0,     13,    40,    60,    63,    80,    128,
+    256,   263,   311,   320,   373,   377,   394,   396,   400,   416,
+    464,   509,   640,   672,   736,   737,   768,   800,   813,   833,
+    834,   842,   848,   886,   896,   927,   928,   968,   976,   977,
+    1024,  1064,  1104,  1184,  1200,  1240,  1280,  1328,  1391,  1536,
+    1856,  1888,  2048,  2056,  2058,  2103,  2108,  2111,  2135,  2136,
+    2144,  2167,  2169,  2176,  2215,  2272,  2292,  2299,  2304,  2326,
+    2335,  2336,  2367,  2432,  2492,  2494,  2496,  2514,  2560,  2561,
+    2565,  2572,  2576,  2581,  2585,  2616,  2623,  2624,  2640,  2656,
+    2685,  2687,  2688,  2717,  2752,  2760,  2761,  2789,  2795,  2800,
+    2816,  2873,  2880,  2904,  2912,  2936,  2944,  2969,  2985,  3072,
+    3200,  3264,  3322,  3328,  3364,  3376,  3680,  3712,  3755,  3757,
+    3760,  3840,  3869,  3879,  3888,  3910,  3921,  3925,  4016,  4037,
+    4064,  4096,  4097,  4098,  4099,  4152,  4167,  4178,  4198,  4223,
+    4226,  4227,  4272,  4275,  4279,  4281,  4283,  4285,  4286,  4301,
+    4304,  4336,  4352,  4355,  4391,  4396,  4397,  4406,  4416,  4420,
+    4421,  4423,  4432,  4467,  4468,  4470,  4480,  4482,  4483,  4531,
+    4534,  4543,  4545,  4549,  4553,  4557,  4558,  4559,  4560,  4570,
+    4571,  4572,  4573,  4577,  4608,  4627,  4652,  4655,  4658,  4660,
+    4661,  4662,  4664,  4670,  4736,  4744,  4746,  4751,  4767,  4777,
+    4784,  4831,  4832,  4835,  4848,  4864,  4866,  4869,  4879,  4883,
+    4906,  4914,  4917,  4923,  4925,  4926,  4928,  4929,  4935,  4939,
+    4944,  4951,  4957,  4962,  4966,  4976,  5120,  5173,  5176,  5184,
+    5186,  5189,  5190,  5191,  5195,  5200,  5210,  5213,  5214,  5215,
+    5248,  5296,  5299,  5305,  5306,  5307,  5311,  5313,  5314,  5316,
+    5318,  5319,  5328,  5504,  5551,  5554,  5560,  5564,  5566,  5567,
+    5569,  5592,  5596,  5632,  5680,  5683,  5691,  5693,  5694,  5695,
+    5697,  5700,  5712,  5728,  5760,  5803,  5804,  5805,  5806,  5808,
+    5814,  5815,  5816,  5824,  5888,  5917,  5920,  5922,  5926,  5927,
+    5936,  5946,  5948,  5951,  6144,  6188,  6191,  6200,  6201,  6203,
+    6304,  6336,  6368,  6378,  6399,  6409,  6412,  6421,  6424,  6448,
+    6455,  6459,  6461,  6462,  6463,  6464,  6465,  6466,  6467,  6468,
+    6480,  6560,  6570,  6609,  6612,  6618,  6620,  6624,  6625,  6626,
+    6627,  6628,  6656,  6657,  6667,  6707,  6713,  6714,  6715,  6719,
+    6727,  6736,  6737,  6743,  6745,  6748,  6794,  6807,  6808,  6810,
+    6813,  6814,  6848,  7168,  7178,  7215,  7216,  7224,  7230,  7231,
+    7232,  7233,  7248,  7258,  7280,  7282,  7314,  7337,  7338,  7345,
+    7346,  7348,  7349,  7424,  7432,  7435,  7473,  7482,  7484,  7487,
+    7494,  7495,  7504,  7520,  7527,  7530,  7562,  7568,  7571,  7573,
+    7574,  7575,  7576,  7584,  7904,  7923,  7925,  7927,  8112,  8128,
+    8149,  8157,  8161,  8191,  8192,  9216,  9328,  9344,  12288, 13360,
+    17408, 26624, 27200, 27232, 27246, 27344, 27376, 27381, 27392, 27440,
+    27447, 27452, 27456, 27460, 27461, 27472, 27483, 27491, 27517, 28224,
+    28256, 28288, 28311, 28416, 28495, 28496, 28497, 28559, 28563, 28640,
+    28642, 28643, 28644, 28656, 28672, 34807, 34816, 36096, 36104, 45056,
+    45392, 45412, 45424, 48128, 48240, 48256, 48272, 48284, 48285, 48287,
+    48288, 53248, 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627,
+    53635, 53637, 53644, 53674, 53678, 53760, 53826, 53829, 53984, 54016,
+    54112, 54272, 54298, 54324, 54350, 54358, 54376, 54402, 54428, 54430,
+    54434, 54437, 54441, 54446, 54454, 54459, 54461, 54469, 54480, 54506,
+    54532, 54535, 54541, 54550, 54558, 54584, 54587, 54592, 54598, 54602,
+    54610, 54636, 54662, 54688, 54714, 54740, 54766, 54792, 54818, 54844,
+    54870, 54896, 54922, 54952, 54977, 54978, 55003, 55004, 55010, 55035,
+    55036, 55061, 55062, 55068, 55093, 55094, 55119, 55120, 55126, 55151,
+    55152, 55177, 55178, 55184, 55209, 55210, 55235, 55236, 55242, 55246,
+    55296, 55808, 55863, 55867, 55917, 55925, 55926, 55940, 55941, 55943,
+    55963, 55969, 57344, 57352, 57371, 57379, 57382, 57600, 57648, 57655,
+    57664, 57678, 57679, 58048, 58092, 58096, 58111, 59392, 59591, 59600,
+    59648, 59682, 59716, 59723, 59728, 59742, 60529, 60588, 60589, 60592,
+    60593, 60673, 60718, 60719, 60928, 60933, 60961, 60964, 60967, 60969,
+    60980, 60985, 60987, 60994, 60999, 61001, 61003, 61005, 61009, 61012,
+    61015, 61017, 61019, 61021, 61023, 61025, 61028, 61031, 61036, 61044,
+    61049, 61054, 61056, 61067, 61089, 61093, 61099, 61168, 61440, 61488,
+    61600, 61617, 61633, 61649, 61696, 61709, 61926, 61968, 62016, 62032,
+    62048, 62208, 62459, 62464, 63200, 63216, 63232, 63360, 63456, 63488,
+    63504, 63568, 63584, 63632, 63664, 63744, 63866, 63949, 64096, 64112,
+    64120, 64128, 64144, 64176, 64192, 64208, 64256, 64404, 64496, 0,
+    42717, 42752, 46900, 46912, 47133, 47136, 52897, 52912, 60384, 63488,
+    0,     4938,  1,     32,    256,   0,     65533,
   };
 static const u16 aFts5UnicodeData[] = {
-    1025,  61,    117,   55,    117,   54,    50,    53,    57,    53,    
-    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,    
-    56,    48,    56,    837,   54,    57,    50,    57,    1057,  61,    
-    53,    151,   58,    53,    56,    58,    39,    52,    57,    34,    
-    58,    56,    58,    57,    79,    56,    37,    85,    56,    47,    
-    39,    51,    111,   53,    745,   57,    233,   773,   57,    261,   
-    1822,  37,    542,   37,    1534,  222,   69,    73,    37,    126,   
-    126,   73,    69,    137,   37,    73,    37,    105,   101,   73,    
-    37,    73,    37,    190,   158,   37,    126,   126,   73,    37,    
-    126,   94,    37,    39,    94,    69,    135,   41,    40,    37,    
-    41,    40,    37,    41,    40,    37,    542,   37,    606,   37,    
-    41,    40,    37,    126,   73,    37,    1886,  197,   73,    37,    
-    73,    69,    126,   105,   37,    286,   2181,  39,    869,   582,   
-    152,   390,   472,   166,   248,   38,    56,    38,    568,   3596,  
-    158,   38,    56,    94,    38,    101,   53,    41,    88,    41,    
-    53,    105,   41,    73,    37,    553,   297,   1125,  94,    37,    
-    105,   101,   798,   133,   94,    57,    126,   94,    37,    1641,  
-    1541,  1118,  58,    172,   75,    1790,  478,   37,    3102,  1225,  
-    38,    213,   1317,  53,    49,    90,    55,    1452,  49,    44,    
-    53,    76,    53,    76,    53,    44,    871,   135,   85,    194,   
-    121,   85,    55,    85,    90,    364,   53,    34,    85,    1031,  
-    38,    327,   684,   333,   149,   71,    44,    3175,  53,    39,    
-    236,   34,    58,    204,   70,    76,    58,    140,   71,    333,   
-    103,   90,    39,    469,   34,    39,    44,    967,   876,   2855,  
-    364,   39,    333,   1063,  300,   70,    58,    117,   38,    44,    
-    87,    711,   140,   38,    300,   38,    108,   38,    172,   501,   
-    807,   108,   53,    359,   679,   263,   492,   34,    1036,  42,    
-    1735,  44,    42,    44,    39,    106,   268,   138,   44,    74,    
-    39,    236,   327,   76,    85,    333,   53,    38,    487,   44,    
-    74,    263,   71,    711,   231,   39,    135,   44,    39,    106,   
-    140,   74,    74,    44,    39,    42,    71,    103,   76,    333,   
-    71,    87,    207,   58,    55,    39,    53,    44,    76,    42,    
-    199,   71,    711,   231,   71,    71,    71,    44,    106,   76,    
-    76,    108,   44,    135,   39,    333,   76,    103,   44,    53,    
-    76,    42,    295,   103,   711,   231,   71,    167,   44,    39,    
-    106,   172,   76,    42,    74,    44,    39,    71,    76,    333,   
-    53,    55,    39,    204,   44,    74,    263,   71,    711,   231,   
-    71,    167,   44,    39,    42,    44,    42,    140,   74,    74,    
-    44,    44,    42,    71,    103,   76,    333,   58,    39,    207,   
-    44,    39,    199,   103,   135,   71,    39,    71,    71,    103,   
-    391,   74,    44,    74,    106,   106,   44,    39,    42,    333,   
-    111,   218,   55,    58,    44,    106,   44,    263,   103,   743,   
-    519,   39,    108,   138,   108,   140,   76,    103,   71,    76,    
-    333,   53,    239,   58,    39,    44,    74,    53,    263,   103,   
-    743,   327,   167,   44,    39,    42,    44,    170,   44,    74,    
-    74,    76,    74,    39,    71,    76,    333,   71,    76,    74,    
-    263,   103,   1319,  76,    39,    106,   140,   106,   106,   44,    
-    39,    58,    103,   42,    239,   103,   76,    333,   303,   58,    
-    199,   74,    583,   775,   295,   39,    231,   44,    106,   108,   
-    44,    266,   333,   74,    53,    1543,  44,    71,    236,   55,    
-    199,   38,    268,   53,    333,   85,    71,    39,    167,   775,   
-    39,    327,   44,    71,    300,   39,    167,   38,    204,   333,   
-    135,   39,    122,   501,   58,    53,    122,   76,    218,   333,   
-    335,   58,    44,    58,    44,    58,    44,    54,    50,    54,    
-    50,    74,    263,   1159,  460,   42,    172,   53,    76,    167,   
-    364,   1164,  282,   44,    218,   90,    181,   154,   85,    1383,  
-    74,    140,   42,    204,   42,    76,    74,    76,    39,    333,   
-    213,   199,   74,    76,    135,   108,   39,    106,   71,    234,   
-    103,   140,   423,   44,    74,    76,    202,   44,    39,    42,    
-    333,   106,   44,    90,    1225,  41,    41,    1381,  53,    38,    
-    101,   10535, 135,   231,   39,    135,   1319,  135,   1063,  135,   
-    231,   39,    135,   487,   1831,  135,   2151,  108,   309,   655,   
-    519,   346,   2761,  197,   49,    19847, 58,    53,    551,   61,    
-    839,   54,    50,    2407,  117,   110,   263,   423,   135,   108,   
-    583,   108,   85,    583,   76,    423,   103,   76,    1671,  76,    
-    42,    236,   266,   44,    74,    364,   117,   38,    117,   55,    
-    39,    44,    333,   335,   213,   49,    149,   108,   34,    333,   
-    1127,  38,    1703,  167,   76,    1095,  44,    39,    2247,  999,   
-    108,   138,   76,    106,   74,    44,    202,   108,   58,    85,    
-    333,   967,   167,   1415,  839,   333,   47,    1114,  743,   76,    
-    74,    44,    85,    1703,  42,    44,    42,    236,   44,    42,    
-    44,    74,    268,   202,   332,   44,    333,   333,   245,   38,    
-    213,   460,   43,    140,   42,    1511,  44,    42,    172,   42,    
-    44,    170,   44,    74,    231,   333,   245,   346,   300,   314,   
-    76,    42,    967,   42,    140,   74,    76,    42,    108,   71,    
-    333,   1415,  44,    42,    76,    106,   44,    42,    108,   74,    
-    149,   1159,  266,   268,   74,    76,    181,   333,   103,   333,   
-    967,   198,   85,    293,   1385,  105,   277,   108,   53,    428,   
-    42,    236,   135,   44,    199,   44,    71,    42,    76,    39,    
-    1413,  2022,  421,   38,    1093,  1190,  1868,  172,   4830,  261,   
-    3166,  261,   265,   197,   201,   261,   265,   261,   265,   197,   
-    201,   261,   41,    41,    41,    94,    229,   265,   453,   261,   
-    264,   261,   264,   261,   264,   165,   69,    137,   40,    56,    
-    37,    120,   101,   69,    137,   40,    120,   133,   69,    137,   
-    120,   261,   169,   120,   101,   69,    137,   40,    88,    381,   
-    162,   209,   85,    52,    51,    54,    84,    51,    54,    52,    
-    277,   59,    60,    162,   61,    309,   52,    51,    149,   80,    
-    117,   57,    54,    50,    373,   57,    53,    48,    341,   61,    
-    162,   322,   47,    38,    207,   121,   54,    50,    38,    335,   
-    121,   54,    50,    422,   1047,  428,   139,   44,    107,   396,   
-    90,    41,    154,   41,    90,    37,    105,   69,    105,   37,    
-    58,    41,    90,    57,    169,   218,   41,    58,    41,    58,    
-    41,    58,    137,   58,    37,    137,   37,    135,   37,    90,    
-    69,    73,    185,   94,    101,   58,    57,    90,    37,    58,    
-    527,   1134,  94,    142,   47,    90,    185,   186,   89,    154,   
-    57,    90,    57,    90,    57,    250,   57,    1018,  89,    90,    
-    57,    58,    57,    1018,  8601,  282,   54,    50,    54,    50,    
-    666,   89,    250,   54,    50,    2618,  57,    986,   825,   1306,  
-    217,   2234,  378,   1935,  2522,  719,   5882,  57,    314,   57,    
-    1754,  281,   3578,  57,    7962,  54,    50,    54,    50,    54,    
-    50,    54,    50,    54,    50,    54,    50,    54,    50,    975,   
-    1434,  185,   54,    50,    1017,  54,    50,    54,    50,    54,    
-    50,    54,    50,    54,    50,    537,   8218,  4217,  54,    50,    
-    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    
-    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,    
-    2041,  54,    50,    54,    50,    1049,  54,    50,    8281,  1562,  
-    697,   90,    217,   1274,  1050,  3354,  1513,  1509,  126,   73,    
-    69,    254,   105,   37,    94,    37,    94,    165,   70,    105,   
-    37,    3166,  37,    218,   158,   108,   94,    149,   47,    85,    
-    1221,  37,    37,    1799,  38,    53,    44,    743,   231,   231,   
-    231,   231,   231,   231,   231,   231,   1036,  85,    52,    51,    
-    52,    51,    117,   52,    51,    53,    52,    51,    309,   49,    
-    85,    49,    53,    52,    51,    85,    52,    51,    54,    50,    
-    54,    50,    54,    50,    54,    50,    181,   38,    341,   81,    
-    149,   49,    53,    54,    437,   858,   2874,  6874,  410,   61,    
-    117,   58,    38,    39,    46,    54,    50,    54,    50,    54,    
-    50,    54,    50,    54,    50,    90,    54,    50,    54,    50,    
-    54,    50,    54,    50,    49,    54,    82,    58,    302,   140,   
-    74,    49,    166,   90,    110,   38,    39,    53,    90,    2759,  
-    76,    88,    70,    39,    49,    2887,  53,    102,   39,    1383,  
-    3015,  90,    143,   346,   871,   1178,  519,   1018,  335,   986,   
-    271,   58,    495,   1050,  335,   1274,  495,   10266, 39,    39,    
-    2074,  39,    39,    679,   38,    36583, 1786,  1287,  198,   85,    
-    8583,  38,    117,   519,   333,   71,    1502,  39,    44,    107,   
-    53,    332,   53,    38,    926,   70,    76,    2247,  334,   76,    
-    213,   760,   294,   88,    478,   69,    2014,  38,    261,   190,   
-    350,   38,    88,    158,   39,    158,   69,    702,   137,   37,    
-    169,   37,    350,   126,   73,    39,    70,    37,    231,   44,    
-    103,   44,    135,   44,    743,   74,    76,    42,    154,   207,   
-    90,    55,    58,    1671,  149,   74,    1607,  522,   76,    85,    
-    333,   588,   199,   117,   39,    53,    71,    44,    333,   903,   
-    268,   85,    743,   364,   74,    53,    935,   108,   42,    1511,  
-    44,    74,    140,   74,    76,    106,   437,   38,    333,   85,    
-    167,   44,    38,    295,   333,   167,   1319,  204,   74,    76,    
-    74,    76,    103,   44,    263,   44,    42,    333,   149,   519,   
-    38,    199,   122,   39,    42,    44,    42,    1607,  44,    39,    
-    108,   71,    76,    167,   76,    39,    44,    39,    71,    38,    
-    85,    359,   42,    76,    74,    85,    39,    70,    42,    44,    
-    199,   199,   199,   231,   231,   1381,  56,    134,   261,   2565,  
-    1127,  74,    44,    74,    44,    74,    53,    42,    44,    333,   
-    39,    39,    743,   1575,  36,    68,    68,    36,    63,    63,    
-    11719, 3399,  229,   165,   39,    44,    327,   57,    423,   167,   
-    39,    71,    71,    3463,  536,   11623, 50,    54,    2055,  1735,  
-    391,   55,    58,    524,   245,   54,    50,    53,    524,   53,    
-    81,    80,    54,    50,    54,    50,    54,    50,    54,    50,    
-    54,    50,    54,    50,    54,    50,    54,    50,    85,    54,    
-    50,    149,   112,   117,   149,   49,    54,    50,    54,    50,    
-    54,    50,    117,   57,    49,    121,   53,    55,    85,    167,   
-    4327,  34,    117,   55,    117,   54,    50,    53,    57,    53,    
-    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,    
-    56,    48,    56,    837,   54,    57,    50,    57,    54,    50,    
-    53,    54,    50,    85,    327,   38,    1447,  70,    999,   199,   
-    199,   199,   103,   87,    57,    56,    58,    87,    58,    153,   
-    90,    98,    90,    391,   839,   615,   71,    487,   455,   3943,  
-    117,   1455,  314,   1710,  143,   570,   79,    122,   410,   58,    
-    1466,  44,    935,   1575,  44,    879,   1031,  143,   647,   46,    
-    263,   46,    1223,  172,   967,   53,    1159,  263,   53,    174,   
-    1289,  1285,  2503,  333,   1161,  1157,  1287,  1671,  53,    9959,  
-    711,   263,   199,   39,    1415,  71,    39,    743,   53,    271,   
-    743,   90,    239,   999,   303,   615,   71,    175,   711,   207,   
-    53,    839,   53,    1799,  79,    71,    527,   1487,  39,    108,   
-    76,    140,   135,   103,   935,   108,   44,    303,   309,   935,   
-    79,    53,    935,   111,   263,   58,    903,   76,    175,   245,   
-    1735,  245,   711,   271,   615,   271,   583,   149,   239,   2343,  
-    1641,  1637,  207,   1159,  140,   333,   1007,  935,   335,   39,    
-    711,   364,   143,   181,   743,   42,    44,    42,    1703,  492,   
-    245,   655,   333,   108,   42,    1447,  106,   140,   74,    76,    
-    85,    34,    149,   34,    807,   333,   108,   1159,  172,   42,    
-    268,   333,   149,   39,    74,    1127,  44,    85,    39,    76,    
-    42,    1543,  106,   300,   74,    135,   149,   140,   53,    333,   
-    39,    53,    39,    117,   655,   583,   807,   106,   108,   74,    
-    44,    42,    76,    213,   44,    231,   39,    135,   487,   327,   
-    53,    1511,  44,    106,   268,   333,   76,    74,    263,   71,    
-    711,   231,   71,    167,   76,    39,    74,    44,    138,   74,    
-    106,   39,    42,    167,   74,    236,   172,   1703,  106,   268,   
-    74,    108,   42,    44,    135,   181,   333,   53,    53,    44,    
-    39,    1543,  106,   204,   42,    44,    138,   76,    42,    76,    
-    71,    53,    39,    333,   1511,  106,   140,   138,   76,    42,    
-    76,    757,   135,   76,    1543,  106,   268,   74,    44,    42,    
-    76,    117,   39,    333,   437,   1383,  44,    42,    44,    74,    
-    204,   42,    44,    39,    333,   871,   108,   74,    140,   42,    
-    172,   333,   79,    117,   58,    1415,  106,   300,   42,    76,    
-    53,    1033,  1029,  333,   303,   39,    263,   1255,  106,   140,   
-    76,    138,   44,    39,    53,    39,    42,    39,    332,   1287,  
-    204,   42,    39,    140,   277,   44,    39,    204,   74,    108,   
-    1479,  428,   42,    76,    117,   39,    181,   1831,  295,   1191,  
-    42,    236,   204,   42,    44,    39,    181,   333,   623,   85,    
-    967,   716,   42,    236,   42,    76,    42,    76,    231,   71,    
-    1223,  204,   44,    76,    236,   39,    44,    333,   199,   71,    
-    1031,  170,   76,    74,    44,    42,    44,    39,    333,   615,   
-    76,    74,    85,    687,   282,   151,   570,   53,    29511, 3566,  
-    181,   6279,  34279, 290,   18663, 18215, 999,   333,   85,    967,   
-    172,   53,    1543,  236,   181,   154,   134,   53,    58,    333,   
-    239,   679,   615,   1033,  1029,  751,   149,   2407,  44,    39,    
-    1770,  140,   422,   70,    53,    38,    39,    39,    24167, 9191,  
-    103,   135,   12679, 3431,  423,   295,   327,   58,    76,    53,    
-    130,   7898,  1274,  1946,  74,    108,   122,   202,   258,   268,   
-    90,    236,   986,   140,   1914,  2138,  108,   58,    655,   2810,  
-    815,   841,   837,   841,   229,   581,   841,   837,   41,    73,    
-    41,    73,    137,   265,   133,   37,    229,   357,   841,   837,   
-    73,    137,   265,   233,   837,   73,    137,   169,   41,    233,   
-    837,   841,   837,   841,   837,   841,   837,   841,   837,   841,   
-    837,   841,   901,   809,   57,    805,   57,    197,   809,   57,    
-    805,   57,    197,   809,   57,    805,   57,    197,   809,   57,    
-    805,   57,    197,   809,   57,    805,   57,    197,   94,    1613,  
-    16410, 1772,  154,   1612,  282,   44,    474,   44,    90,    181,   
-    172,   492,   236,   556,   236,   76,    172,   1447,  236,   230,   
-    333,   39,    58,    1415,  140,   333,   55,    6311,  303,   236,   
-    1097,  1093,  236,   38,    333,   85,    1903,  58,    111,   55,    
-    143,   1455,  58,    495,   135,   871,   71,    39,    39,    327,   
-    135,   39,    39,    39,    39,    39,    39,    103,   71,    39,    
-    39,    39,    39,    39,    39,    71,    39,    135,   231,   135,   
-    135,   39,    327,   551,   103,   167,   551,   89,    1434,  3226,  
-    506,   506,   506,   1210,  431,   3002,  1978,  954,   1434,  314,   
-    90,    218,   8058,  184,   23258, 442,   378,   3738,  2874,  410,   
-    410,   1818,  346,   1306,  986,   410,   3258,  154,   1338,  218,   
-    954,   4346,  474,   154,   122,   122,   218,   39,    39,    39,    
-    39,    39,    39,    39,    39,    39,    39,    17351, 34,    3074,  
-    7692,  63,    63,    
+    1025,  61,    117,   55,    117,   54,    50,    53,    57,    53,
+    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,
+    56,    48,    56,    837,   54,    57,    50,    57,    1057,  61,
+    53,    151,   58,    53,    56,    58,    39,    52,    57,    34,
+    58,    56,    58,    57,    79,    56,    37,    85,    56,    47,
+    39,    51,    111,   53,    745,   57,    233,   773,   57,    261,
+    1822,  37,    542,   37,    1534,  222,   69,    73,    37,    126,
+    126,   73,    69,    137,   37,    73,    37,    105,   101,   73,
+    37,    73,    37,    190,   158,   37,    126,   126,   73,    37,
+    126,   94,    37,    39,    94,    69,    135,   41,    40,    37,
+    41,    40,    37,    41,    40,    37,    542,   37,    606,   37,
+    41,    40,    37,    126,   73,    37,    1886,  197,   73,    37,
+    73,    69,    126,   105,   37,    286,   2181,  39,    869,   582,
+    152,   390,   472,   166,   248,   38,    56,    38,    568,   3596,
+    158,   38,    56,    94,    38,    101,   53,    41,    88,    41,
+    53,    105,   41,    73,    37,    553,   297,   1125,  94,    37,
+    105,   101,   798,   133,   94,    57,    126,   94,    37,    1641,
+    1541,  1118,  58,    172,   75,    1790,  478,   37,    3102,  1225,
+    38,    213,   1317,  53,    49,    90,    55,    1452,  49,    44,
+    53,    76,    53,    76,    53,    44,    871,   135,   85,    194,
+    121,   85,    55,    85,    90,    364,   53,    34,    85,    1031,
+    38,    327,   684,   333,   149,   71,    44,    3175,  53,    39,
+    236,   34,    58,    204,   70,    76,    58,    140,   71,    333,
+    103,   90,    39,    469,   34,    39,    44,    967,   876,   2855,
+    364,   39,    333,   1063,  300,   70,    58,    117,   38,    44,
+    87,    711,   140,   38,    300,   38,    108,   38,    172,   501,
+    807,   108,   53,    359,   679,   583,   492,   34,    1036,  42,
+    1735,  44,    42,    44,    39,    106,   268,   138,   44,    74,
+    39,    236,   327,   76,    85,    333,   53,    38,    487,   44,
+    74,    263,   71,    711,   231,   39,    135,   44,    39,    106,
+    140,   74,    74,    44,    39,    42,    71,    103,   76,    333,
+    71,    87,    207,   58,    55,    39,    53,    44,    76,    42,
+    199,   71,    711,   231,   71,    71,    71,    44,    106,   76,
+    76,    108,   44,    135,   39,    333,   76,    103,   44,    53,
+    76,    42,    295,   103,   711,   231,   71,    167,   44,    39,
+    106,   172,   76,    42,    74,    44,    39,    71,    76,    333,
+    53,    55,    39,    204,   44,    74,    263,   71,    711,   231,
+    71,    167,   44,    39,    42,    44,    42,    140,   74,    74,
+    44,    76,    42,    71,    103,   76,    333,   58,    39,    207,
+    44,    39,    199,   103,   135,   71,    39,    71,    71,    103,
+    391,   74,    44,    74,    106,   106,   44,    39,    42,    333,
+    111,   218,   55,    58,    44,    106,   44,    263,   103,   743,
+    519,   39,    108,   138,   108,   140,   76,    103,   71,    76,
+    333,   53,    239,   58,    39,    44,    74,    53,    263,   103,
+    743,   327,   167,   44,    39,    42,    44,    170,   44,    74,
+    74,    76,    74,    39,    71,    76,    333,   71,    76,    74,
+    295,   103,   1319,  76,    39,    106,   140,   106,   106,   44,
+    39,    58,    103,   42,    239,   103,   76,    333,   303,   58,
+    199,   44,    74,    583,   775,   295,   39,    231,   44,    106,
+    108,   44,    266,   333,   74,    53,    1543,  44,    71,    236,
+    55,    199,   38,    268,   53,    333,   85,    71,    39,    167,
+    775,   39,    327,   44,    71,    300,   39,    167,   38,    204,
+    333,   135,   39,    122,   501,   58,    53,    122,   76,    218,
+    333,   335,   58,    44,    58,    44,    58,    44,    54,    50,
+    54,    50,    74,    263,   1159,  460,   42,    172,   53,    76,
+    167,   364,   1164,  282,   44,    218,   90,    181,   154,   85,
+    1383,  74,    140,   42,    204,   42,    76,    74,    76,    39,
+    333,   213,   199,   74,    76,    135,   108,   39,    106,   71,
+    234,   103,   140,   423,   44,    74,    76,    202,   44,    39,
+    42,    333,   106,   44,    90,    1225,  41,    41,    1381,  53,
+    38,    101,   10535, 135,   231,   39,    135,   1319,  135,   1063,
+    135,   231,   39,    135,   487,   1831,  135,   2151,  108,   309,
+    655,   519,   346,   2761,  197,   49,    19847, 58,    53,    551,
+    61,    839,   54,    50,    2407,  117,   110,   263,   423,   135,
+    108,   583,   108,   85,    583,   76,    423,   103,   76,    1671,
+    76,    42,    236,   266,   44,    74,    364,   117,   38,    117,
+    55,    39,    44,    333,   335,   213,   49,    149,   108,   34,
+    333,   1127,  38,    1703,  167,   76,    1095,  44,    39,    2247,
+    999,   108,   138,   76,    106,   74,    44,    202,   108,   58,
+    85,    333,   967,   167,   1415,  839,   333,   47,    1114,  743,
+    76,    74,    44,    85,    1703,  42,    44,    42,    236,   44,
+    42,    44,    74,    268,   202,   332,   44,    333,   333,   245,
+    38,    213,   460,   43,    76,    140,   42,    1511,  44,    42,
+    172,   42,    44,    170,   44,    74,    231,   333,   245,   346,
+    300,   314,   76,    42,    967,   42,    140,   74,    76,    42,
+    108,   71,    333,   1415,  44,    42,    76,    106,   44,    42,
+    108,   74,    149,   1159,  266,   268,   74,    76,    181,   333,
+    103,   333,   967,   198,   85,    293,   1385,  105,   277,   108,
+    53,    428,   42,    236,   135,   44,    199,   44,    71,    42,
+    76,    39,    1413,  2022,  421,   38,    1093,  1190,  1868,  172,
+    4830,  261,   3166,  261,   265,   197,   201,   261,   265,   261,
+    265,   197,   201,   261,   41,    41,    41,    94,    229,   265,
+    453,   261,   264,   261,   264,   261,   264,   165,   69,    137,
+    40,    56,    37,    120,   101,   69,    137,   40,    120,   133,
+    69,    137,   120,   261,   169,   120,   101,   69,    137,   40,
+    88,    381,   162,   209,   85,    52,    51,    54,    84,    51,
+    54,    52,    277,   59,    60,    162,   61,    309,   52,    51,
+    149,   80,    117,   57,    54,    50,    373,   57,    53,    48,
+    341,   61,    162,   322,   47,    38,    207,   121,   54,    50,
+    38,    335,   121,   54,    50,    422,   1047,  428,   139,   44,
+    107,   396,   90,    41,    154,   41,    90,    37,    105,   69,
+    105,   37,    58,    41,    90,    57,    169,   218,   41,    58,
+    41,    58,    41,    58,    137,   58,    37,    137,   37,    135,
+    37,    90,    69,    73,    185,   94,    101,   58,    57,    90,
+    37,    58,    527,   1134,  94,    142,   47,    90,    185,   186,
+    89,    154,   57,    90,    57,    90,    57,    250,   57,    1018,
+    89,    90,    57,    58,    57,    1018,  8601,  282,   54,    50,
+    54,    50,    666,   89,    250,   54,    50,    2618,  57,    986,
+    825,   1306,  217,   2234,  378,   1935,  2522,  719,   5882,  57,
+    314,   57,    1754,  281,   3578,  57,    7962,  54,    50,    54,
+    50,    54,    50,    54,    50,    54,    50,    54,    50,    54,
+    50,    975,   1434,  185,   54,    50,    1017,  54,    50,    54,
+    50,    54,    50,    54,    50,    54,    50,    537,   8218,  4217,
+    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,
+    54,    50,    54,    50,    54,    50,    54,    50,    54,    50,
+    54,    50,    2041,  54,    50,    54,    50,    1049,  54,    50,
+    8281,  1562,  697,   90,    217,   1274,  1050,  3386,  1513,  1509,
+    126,   73,    69,    254,   105,   37,    94,    37,    94,    165,
+    70,    105,   37,    3166,  37,    218,   158,   108,   94,    149,
+    47,    85,    1221,  37,    37,    1799,  38,    53,    44,    743,
+    231,   231,   231,   231,   231,   231,   231,   231,   1036,  85,
+    52,    51,    52,    51,    117,   52,    51,    53,    52,    51,
+    309,   49,    85,    49,    53,    52,    51,    85,    52,    51,
+    54,    50,    54,    50,    54,    50,    54,    50,    181,   38,
+    341,   81,    149,   49,    53,    54,    437,   90,    53,    858,
+    2874,  6874,  410,   61,    117,   58,    38,    39,    46,    54,
+    50,    54,    50,    54,    50,    54,    50,    54,    50,    90,
+    54,    50,    54,    50,    54,    50,    54,    50,    49,    54,
+    82,    58,    302,   140,   74,    49,    166,   90,    110,   38,
+    39,    53,    90,    2759,  76,    88,    70,    39,    49,    2887,
+    53,    102,   39,    1383,  3015,  90,    143,   346,   1031,  1178,
+    519,   1018,  335,   986,   271,   58,    495,   1050,  335,   1274,
+    495,   10266, 39,    39,    2074,  39,    39,    679,   38,    36583,
+    1786,  1287,  198,   85,    8583,  38,    117,   519,   333,   71,
+    1502,  39,    44,    107,   53,    332,   53,    38,    926,   70,
+    76,    2247,  334,   76,    213,   760,   294,   88,    478,   69,
+    2014,  38,    261,   190,   350,   38,    88,    158,   39,    158,
+    69,    702,   137,   37,    169,   37,    350,   126,   105,   37,
+    94,    94,    39,    70,    37,    231,   44,    103,   44,    135,
+    44,    743,   74,    76,    42,    154,   44,    207,   90,    55,
+    58,    1671,  149,   74,    1607,  522,   76,    85,    333,   588,
+    199,   117,   39,    53,    71,    44,    333,   903,   268,   85,
+    743,   364,   74,    53,    935,   108,   42,    1511,  44,    74,
+    140,   74,    76,    106,   437,   38,    333,   85,    167,   44,
+    38,    295,   333,   167,   1319,  204,   74,    76,    74,    76,
+    103,   44,    263,   44,    42,    333,   149,   519,   38,    199,
+    122,   39,    42,    44,    42,    1607,  44,    39,    108,   71,
+    76,    167,   76,    39,    44,    39,    71,    38,    85,    359,
+    42,    76,    74,    85,    39,    70,    42,    44,    199,   199,
+    199,   231,   231,   1381,  56,    134,   293,   38,    88,    2565,
+    1127,  74,    44,    74,    44,    74,    53,    42,    44,    333,
+    39,    39,    743,   1575,  36,    68,    68,    36,    63,    63,
+    11719, 3399,  229,   165,   39,    44,    327,   57,    423,   167,
+    39,    71,    71,    3463,  536,   11623, 50,    54,    2055,  1735,
+    391,   55,    58,    524,   245,   54,    50,    53,    524,   53,
+    81,    80,    54,    50,    54,    50,    54,    50,    54,    50,
+    54,    50,    54,    50,    54,    50,    54,    50,    85,    54,
+    50,    149,   112,   117,   149,   49,    54,    50,    54,    50,
+    54,    50,    117,   57,    49,    121,   53,    55,    85,    167,
+    4327,  34,    117,   55,    117,   54,    50,    53,    57,    53,
+    49,    85,    333,   85,    121,   85,    841,   54,    53,    50,
+    56,    48,    56,    837,   54,    57,    50,    57,    54,    50,
+    53,    54,    50,    85,    327,   38,    1447,  70,    999,   199,
+    199,   199,   103,   87,    57,    56,    58,    87,    58,    153,
+    90,    98,    90,    391,   839,   615,   71,    487,   455,   3943,
+    117,   1455,  314,   1710,  143,   570,   79,    122,   442,   58,
+    1466,  44,    935,   1575,  44,    879,   1031,  143,   647,   46,
+    263,   46,    1223,  172,   967,   53,    1159,  263,   53,    174,
+    1289,  1285,  2503,  333,   1161,  1157,  1287,  1671,  53,    9959,
+    711,   263,   199,   39,    1415,  71,    39,    743,   53,    271,
+    743,   90,    239,   999,   303,   615,   71,    175,   711,   207,
+    53,    839,   53,    1799,  79,    71,    527,   1487,  39,    108,
+    76,    140,   135,   103,   935,   108,   44,    303,   309,   935,
+    79,    53,    935,   111,   263,   58,    903,   76,    175,   245,
+    1735,  245,   711,   271,   615,   271,   583,   149,   239,   2343,
+    1641,  1637,  207,   1159,  140,   333,   1007,  1351,  76,    49,
+    71,    935,   335,   39,    711,   364,   143,   181,   679,   239,
+    743,   42,    44,    42,    1703,  492,   245,   655,   333,   108,
+    42,    1447,  106,   140,   74,    76,    85,    34,    149,   34,
+    807,   333,   108,   1159,  172,   42,    268,   333,   149,   39,
+    74,    39,    1127,  44,    85,    39,    76,    42,    1543,  106,
+    300,   74,    135,   149,   140,   53,    42,    44,    333,   39,
+    53,    39,    117,   655,   583,   807,   106,   108,   74,    44,
+    42,    76,    213,   44,    231,   39,    135,   487,   327,   53,
+    1511,  44,    106,   268,   333,   76,    74,    263,   71,    711,
+    231,   71,    167,   76,    39,    74,    44,    138,   74,    106,
+    39,    42,    167,   74,    236,   172,   1703,  106,   268,   74,
+    108,   42,    44,    135,   181,   333,   85,    53,    44,    103,
+    1543,  106,   204,   42,    44,    138,   76,    42,    76,    71,
+    53,    39,    333,   1511,  106,   140,   138,   76,    42,    76,
+    757,   135,   76,    1543,  106,   268,   74,    44,    42,    76,
+    117,   39,    333,   437,   1383,  44,    42,    44,    74,    204,
+    42,    44,    39,    333,   871,   108,   74,    140,   42,    172,
+    333,   79,    117,   58,    1415,  106,   300,   42,    76,    53,
+    1033,  1029,  333,   303,   263,   39,    263,   71,    775,   202,
+    74,    76,    42,    44,    39,    42,    39,    42,    44,    117,
+    333,   263,   1255,  106,   140,   76,    138,   44,    39,    53,
+    39,    42,    39,    332,   1287,  204,   42,    39,    140,   277,
+    44,    39,    204,   74,    108,   1479,  428,   42,    76,    117,
+    39,    181,   1831,  295,   1191,  42,    236,   204,   42,    44,
+    39,    181,   333,   623,   85,    967,   716,   42,    236,   42,
+    76,    42,    76,    231,   71,    1223,  204,   44,    76,    236,
+    39,    44,    333,   199,   71,    1031,  170,   76,    74,    44,
+    42,    44,    39,    333,   615,   76,    74,    85,    39,    687,
+    282,   151,   570,   53,    29511, 3566,  181,   6279,  34279, 290,
+    18663, 18215, 999,   333,   85,    967,   172,   53,    1543,  236,
+    181,   154,   134,   53,    58,    333,   239,   679,   615,   1033,
+    1029,  751,   149,   2407,  44,    39,    1770,  140,   422,   70,
+    53,    38,    44,    74,    39,    39,    39623, 39,    39,    9191,
+    103,   135,   12679, 3431,  423,   295,   327,   58,    76,    53,
+    130,   7898,  1274,  1946,  74,    108,   122,   202,   258,   268,
+    90,    236,   986,   140,   1914,  2138,  108,   58,    655,   2810,
+    815,   841,   837,   841,   229,   581,   841,   837,   41,    73,
+    41,    73,    137,   265,   133,   37,    229,   357,   841,   837,
+    73,    137,   265,   233,   837,   73,    137,   169,   41,    233,
+    837,   841,   837,   841,   837,   841,   837,   841,   837,   841,
+    837,   841,   901,   809,   57,    805,   57,    197,   809,   57,
+    805,   57,    197,   809,   57,    805,   57,    197,   809,   57,
+    805,   57,    197,   809,   57,    805,   57,    197,   94,    1613,
+    16410, 1772,  154,   1612,  282,   44,    474,   44,    90,    181,
+    172,   492,   236,   556,   236,   76,    172,   1447,  236,   230,
+    333,   39,    58,    1415,  140,   333,   55,    6311,  303,   236,
+    1097,  1093,  236,   38,    333,   85,    1903,  58,    111,   55,
+    143,   1455,  58,    495,   135,   871,   71,    39,    39,    327,
+    135,   39,    39,    39,    39,    39,    39,    103,   71,    39,
+    39,    39,    39,    39,    39,    71,    39,    135,   231,   135,
+    135,   39,    327,   551,   103,   167,   551,   89,    1434,  3226,
+    506,   506,   506,   1210,  431,   5178,  954,   1434,  314,   90,
+    218,   8058,  184,   23322, 442,   442,   3738,  2874,  410,   410,
+    1818,  346,   1306,  986,   90,    3898,  2650,  4346,  474,   186,
+    122,   250,   826,   250,   122,   250,   4730,  1786,  333,   39,
+    39,    39,    39,    39,    39,    39,    39,    39,    39,    17351,
+    39,    39,    34,    3074,  7692,  63,    63,
   };
 
-static int sqlite3Fts5UnicodeCategory(u32 iCode) { 
+static int sqlite3Fts5UnicodeCategory(u32 iCode) {
   int iRes = -1;
   int iHi;
   int iLo;
@@ -224084,6 +230736,7 @@ static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
     }
     iTbl++;
   }
+  aAscii[0] = 0;                  /* 0x00 is never a token character */
 }
 
 
@@ -224393,7 +231046,7 @@ static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
       v >>= 7;
     }
     return 9;
-  }    
+  }
   n = 0;
   do{
     buf[n++] = (u8)((v & 0x7f) | 0x80);
@@ -224445,7 +231098,7 @@ static int sqlite3Fts5GetVarintLen(u32 iVal){
 ******************************************************************************
 **
 ** This is an SQLite virtual table module implementing direct access to an
-** existing FTS5 index. The module may create several different types of 
+** existing FTS5 index. The module may create several different types of
 ** tables:
 **
 ** col:
@@ -224453,21 +231106,21 @@ static int sqlite3Fts5GetVarintLen(u32 iVal){
 **
 **   One row for each term/column combination. The value of $doc is set to
 **   the number of fts5 rows that contain at least one instance of term
-**   $term within column $col. Field $cnt is set to the total number of 
-**   instances of term $term in column $col (in any row of the fts5 table). 
+**   $term within column $col. Field $cnt is set to the total number of
+**   instances of term $term in column $col (in any row of the fts5 table).
 **
 ** row:
 **     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
 **
 **   One row for each term in the database. The value of $doc is set to
 **   the number of fts5 rows that contain at least one instance of term
-**   $term. Field $cnt is set to the total number of instances of term 
+**   $term. Field $cnt is set to the total number of instances of term
 **   $term in the database.
 **
 ** instance:
 **     CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
 **
-**   One row for each term instance in the database. 
+**   One row for each term instance in the database.
 */
 
 
@@ -224484,6 +231137,7 @@ struct Fts5VocabTable {
   sqlite3 *db;                    /* Database handle */
   Fts5Global *pGlobal;            /* FTS5 global object for this database */
   int eType;                      /* FTS5_VOCAB_COL, ROW or INSTANCE */
+  unsigned bBusy;                 /* True if busy */
 };
 
 struct Fts5VocabCursor {
@@ -224528,7 +231182,7 @@ struct Fts5VocabCursor {
 
 
 /*
-** Translate a string containing an fts5vocab table type to an 
+** Translate a string containing an fts5vocab table type to an
 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
 ** and return SQLITE_ERROR.
@@ -224607,7 +231261,7 @@ static int fts5VocabInitVtab(
   char **pzErr                    /* Write any error message here */
 ){
   const char *const azSchema[] = {
-    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")", 
+    "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")",
     "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")",
     "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
   };
@@ -224626,10 +231280,10 @@ static int fts5VocabInitVtab(
     const char *zDb = bDb ? argv[3] : argv[1];
     const char *zTab = bDb ? argv[4] : argv[3];
     const char *zType = bDb ? argv[5] : argv[4];
-    size_t nDb = strlen(zDb)+1; 
+    size_t nDb = strlen(zDb)+1;
     size_t nTab = strlen(zTab)+1;
     int eType = 0;
-    
+
     rc = fts5VocabTableType(zType, pzErr, &eType);
     if( rc==SQLITE_OK ){
       assert( eType>=0 && eType<ArraySize(azSchema) );
@@ -224681,7 +231335,7 @@ static int fts5VocabCreateMethod(
   return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
 }
 
-/* 
+/*
 ** Implementation of the xBestIndex method.
 **
 ** Only constraints of the form:
@@ -224690,7 +231344,7 @@ static int fts5VocabCreateMethod(
 **     term == ?
 **     term >= ?
 **
-** are interpreted. Less-than and less-than-or-equal are treated 
+** are interpreted. Less-than and less-than-or-equal are treated
 ** identically, as are greater-than and greater-than-or-equal.
 */
 static int fts5VocabBestIndexMethod(
@@ -224741,8 +231395,8 @@ static int fts5VocabBestIndexMethod(
   ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
   ** sqlite3_index_info.orderByConsumed flag to tell the core the results
   ** are already in sorted order.  */
-  if( pInfo->nOrderBy==1 
-   && pInfo->aOrderBy[0].iColumn==0 
+  if( pInfo->nOrderBy==1
+   && pInfo->aOrderBy[0].iColumn==0
    && pInfo->aOrderBy[0].desc==0
   ){
     pInfo->orderByConsumed = 1;
@@ -224756,7 +231410,7 @@ static int fts5VocabBestIndexMethod(
 ** Implementation of xOpen method.
 */
 static int fts5VocabOpenMethod(
-  sqlite3_vtab *pVTab, 
+  sqlite3_vtab *pVTab,
   sqlite3_vtab_cursor **ppCsr
 ){
   Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
@@ -224766,6 +231420,12 @@ static int fts5VocabOpenMethod(
   sqlite3_stmt *pStmt = 0;
   char *zSql = 0;
 
+  if( pTab->bBusy ){
+    pVTab->zErrMsg = sqlite3_mprintf(
+       "recursive definition for %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
+    );
+    return SQLITE_ERROR;
+  }
   zSql = sqlite3Fts5Mprintf(&rc,
       "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
       pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
@@ -224777,10 +231437,12 @@ static int fts5VocabOpenMethod(
   assert( rc==SQLITE_OK || pStmt==0 );
   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
 
+  pTab->bBusy = 1;
   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
     i64 iId = sqlite3_column_int64(pStmt, 0);
     pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
   }
+  pTab->bBusy = 0;
 
   if( rc==SQLITE_OK ){
     if( pFts5==0 ){
@@ -224840,7 +231502,7 @@ static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
 
 static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
   int rc = SQLITE_OK;
-  
+
   if( sqlite3Fts5IterEof(pCsr->pIter) ){
     pCsr->bEof = 1;
   }else{
@@ -224866,11 +231528,11 @@ static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
   Fts5IndexIter *pIter = pCsr->pIter;
   i64 *pp = &pCsr->iInstPos;
   int *po = &pCsr->iInstOff;
-  
+
   assert( sqlite3Fts5IterEof(pIter)==0 );
   assert( pCsr->bEof==0 );
   while( eDetail==FTS5_DETAIL_NONE
-      || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp) 
+      || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
   ){
     pCsr->iInstPos = 0;
     pCsr->iInstOff = 0;
@@ -224995,8 +231657,8 @@ static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
 
         if( rc==SQLITE_OK ){
           zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
-          if( nTerm!=pCsr->term.n 
-          || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm)) 
+          if( nTerm!=pCsr->term.n
+          || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
           ){
             break;
           }
@@ -225075,8 +231737,8 @@ static int fts5VocabFilterMethod(
   if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
     rc = fts5VocabInstanceNewTerm(pCsr);
   }
-  if( rc==SQLITE_OK && !pCsr->bEof 
-   && (eType!=FTS5_VOCAB_INSTANCE 
+  if( rc==SQLITE_OK && !pCsr->bEof
+   && (eType!=FTS5_VOCAB_INSTANCE
     || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
   ){
     rc = fts5VocabNextMethod(pCursor);
@@ -225085,8 +231747,8 @@ static int fts5VocabFilterMethod(
   return rc;
 }
 
-/* 
-** This is the xEof method of the virtual table. SQLite calls this 
+/*
+** This is the xEof method of the virtual table. SQLite calls this
 ** routine to find out if it has reached the end of a result set.
 */
 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
@@ -225161,13 +231823,13 @@ static int fts5VocabColumnMethod(
   return SQLITE_OK;
 }
 
-/* 
+/*
 ** This is the xRowid method. The SQLite core calls this routine to
 ** retrieve the rowid for the current row of the result set. The
 ** rowid should be written to *pRowid.
 */
 static int fts5VocabRowidMethod(
-  sqlite3_vtab_cursor *pCursor, 
+  sqlite3_vtab_cursor *pCursor,
   sqlite_int64 *pRowid
 ){
   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
@@ -225208,7 +231870,7 @@ static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
 }
 
 
-    
+
 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
 
 /************** End of fts5.c ************************************************/
@@ -225383,8 +232045,9 @@ static int stmtColumn(
       sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
       break;
     }
-    case STMT_COLUMN_MEM: {
-      i = SQLITE_STMTSTATUS_MEMUSED + 
+    default: {
+      assert( i==STMT_COLUMN_MEM );
+      i = SQLITE_STMTSTATUS_MEMUSED +
             STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
       /* Fall thru */
     }
@@ -225424,11 +232087,11 @@ static int stmtEof(sqlite3_vtab_cursor *cur){
 /*
 ** This method is called to "rewind" the stmt_cursor object back
 ** to the first row of output.  This method is always called at least
-** once prior to any call to stmtColumn() or stmtRowid() or 
+** once prior to any call to stmtColumn() or stmtRowid() or
 ** stmtEof().
 */
 static int stmtFilter(
-  sqlite3_vtab_cursor *pVtabCursor, 
+  sqlite3_vtab_cursor *pVtabCursor,
   int idxNum, const char *idxStr,
   int argc, sqlite3_value **argv
 ){
@@ -225454,7 +232117,7 @@ static int stmtBestIndex(
 }
 
 /*
-** This following structure defines all the methods for the 
+** This following structure defines all the methods for the
 ** stmt virtual table.
 */
 static const sqlite3_module stmtModule = {
@@ -225499,8 +232162,8 @@ SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
 __declspec(dllexport)
 #endif
 SQLITE_API int sqlite3_stmt_init(
-  sqlite3 *db, 
-  char **pzErrMsg, 
+  sqlite3 *db,
+  char **pzErrMsg,
   const sqlite3_api_routines *pApi
 ){
   int rc = SQLITE_OK;
@@ -225514,9 +232177,9 @@ SQLITE_API int sqlite3_stmt_init(
 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
 
 /************** End of stmt.c ************************************************/
-#if __LINE__!=225517
+#if __LINE__!=232180
 #undef SQLITE_SOURCE_ID
-#define SQLITE_SOURCE_ID      "2019-10-10 20:19:45 18db032d058f1436ce3dea84081f4ee5a0f2259ad97301d43c426bc7f3dfalt2"
+#define SQLITE_SOURCE_ID      "2020-12-01 16:14:00 a26b6597e3ae272231b96f9982c3bcc17ddec2f2b6eb4df06a224b91089falt2"
 #endif
 /* Return the source-id for this library */
 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
similarity index 92%
rename from pkgs/sqlite3.30.1.2/compat/sqlite3/sqlite3.h
rename to pkgs/sqlite3.34.0/compat/sqlite3/sqlite3.h
index 23fb8a8..6f8eae0 100644 (file)
@@ -108,7 +108,7 @@ extern "C" {
 ** be held constant and Z will be incremented or else Y will be incremented
 ** and Z will be reset to zero.
 **
-** Since [version 3.6.18] ([dateof:3.6.18]), 
+** Since [version 3.6.18] ([dateof:3.6.18]),
 ** SQLite source code has been stored in the
 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
@@ -123,9 +123,9 @@ extern "C" {
 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
 ** [sqlite_version()] and [sqlite_source_id()].
 */
-#define SQLITE_VERSION        "3.30.1.2"
-#define SQLITE_VERSION_NUMBER 3030001
-#define SQLITE_SOURCE_ID      "2019-10-10 20:19:45 18db032d058f1436ce3dea84081f4ee5a0f2259ad97301d43c426bc7f3df1b0b"
+#define SQLITE_VERSION        "3.34.0"
+#define SQLITE_VERSION_NUMBER 3034000
+#define SQLITE_SOURCE_ID      "2020-12-01 16:14:00 a26b6597e3ae272231b96f9982c3bcc17ddec2f2b6eb4df06a224b91089fed5b"
 
 /*
 ** CAPI3REF: Run-Time Library Version Numbers
@@ -151,8 +151,8 @@ extern "C" {
 ** function is provided for use in DLLs since DLL users usually do not have
 ** direct access to string constants within the DLL.  ^The
 ** sqlite3_libversion_number() function returns an integer equal to
-** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns 
-** a pointer to a string constant whose value is the same as the 
+** [SQLITE_VERSION_NUMBER].  ^(The sqlite3_sourceid() function returns
+** a pointer to a string constant whose value is the same as the
 ** [SQLITE_SOURCE_ID] C preprocessor macro.  Except if SQLite is built
 ** using an edited copy of [the amalgamation], then the last four characters
 ** of the hash might be different from [SQLITE_SOURCE_ID].)^
@@ -167,20 +167,20 @@ SQLITE_API int sqlite3_libversion_number(void);
 /*
 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
 **
-** ^The sqlite3_compileoption_used() function returns 0 or 1 
-** indicating whether the specified option was defined at 
-** compile time.  ^The SQLITE_ prefix may be omitted from the 
-** option name passed to sqlite3_compileoption_used().  
+** ^The sqlite3_compileoption_used() function returns 0 or 1
+** indicating whether the specified option was defined at
+** compile time.  ^The SQLITE_ prefix may be omitted from the
+** option name passed to sqlite3_compileoption_used().
 **
 ** ^The sqlite3_compileoption_get() function allows iterating
 ** over the list of options that were defined at compile time by
 ** returning the N-th compile time option string.  ^If N is out of range,
-** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
-** prefix is omitted from any strings returned by 
+** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
+** prefix is omitted from any strings returned by
 ** sqlite3_compileoption_get().
 **
 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
-** and sqlite3_compileoption_get() may be omitted by specifying the 
+** and sqlite3_compileoption_get() may be omitted by specifying the
 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
 **
 ** See also: SQL functions [sqlite_compileoption_used()] and
@@ -204,7 +204,7 @@ SQLITE_API const char *sqlite3_compileoption_get(int N);
 ** SQLite can be compiled with or without mutexes.  When
 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
 ** are enabled and SQLite is threadsafe.  When the
-** [SQLITE_THREADSAFE] macro is 0, 
+** [SQLITE_THREADSAFE] macro is 0,
 ** the mutexes are omitted.  Without the mutexes, it is not safe
 ** to use SQLite concurrently from more than one thread.
 **
@@ -261,14 +261,14 @@ typedef struct sqlite3 sqlite3;
 **
 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
-** sqlite3_uint64 and sqlite_uint64 types can store integer values 
+** sqlite3_uint64 and sqlite_uint64 types can store integer values
 ** between 0 and +18446744073709551615 inclusive.
 */
 #ifdef SQLITE_INT64_TYPE
   typedef SQLITE_INT64_TYPE sqlite_int64;
 # ifdef SQLITE_UINT64_TYPE
     typedef SQLITE_UINT64_TYPE sqlite_uint64;
-# else  
+# else
     typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
 # endif
 #elif defined(_MSC_VER) || defined(__BORLANDC__)
@@ -299,26 +299,22 @@ typedef sqlite_uint64 sqlite3_uint64;
 ** the [sqlite3] object is successfully destroyed and all associated
 ** resources are deallocated.
 **
-** ^If the database connection is associated with unfinalized prepared
-** statements or unfinished sqlite3_backup objects then sqlite3_close()
-** will leave the database connection open and return [SQLITE_BUSY].
-** ^If sqlite3_close_v2() is called with unfinalized prepared statements
-** and/or unfinished sqlite3_backups, then the database connection becomes
-** an unusable "zombie" which will automatically be deallocated when the
-** last prepared statement is finalized or the last sqlite3_backup is
-** finished.  The sqlite3_close_v2() interface is intended for use with
-** host languages that are garbage collected, and where the order in which
-** destructors are called is arbitrary.
-**
-** Applications should [sqlite3_finalize | finalize] all [prepared statements],
-** [sqlite3_blob_close | close] all [BLOB handles], and 
+** Ideally, applications should [sqlite3_finalize | finalize] all
+** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
-** with the [sqlite3] object prior to attempting to close the object.  ^If
-** sqlite3_close_v2() is called on a [database connection] that still has
-** outstanding [prepared statements], [BLOB handles], and/or
-** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
-** of resources is deferred until all [prepared statements], [BLOB handles],
-** and [sqlite3_backup] objects are also destroyed.
+** with the [sqlite3] object prior to attempting to close the object.
+** ^If the database connection is associated with unfinalized prepared
+** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
+** sqlite3_close() will leave the database connection open and return
+** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
+** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
+** it returns [SQLITE_OK] regardless, but instead of deallocating the database
+** connection immediately, it marks the database connection as an unusable
+** "zombie" and makes arrangements to automatically deallocate the database
+** connection after all prepared statements are finalized, all BLOB handles
+** are closed, and all backups have finished. The sqlite3_close_v2() interface
+** is intended for use with host languages that are garbage collected, and
+** where the order in which destructors are called is arbitrary.
 **
 ** ^If an [sqlite3] object is destroyed while a transaction is open,
 ** the transaction is automatically rolled back.
@@ -348,7 +344,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);
 ** The sqlite3_exec() interface is a convenience wrapper around
 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
 ** that allows an application to run multiple statements of SQL
-** without having to use a lot of C code. 
+** without having to use a lot of C code.
 **
 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
 ** semicolon-separate SQL statements passed into its 2nd argument,
@@ -388,7 +384,7 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**);
 ** from [sqlite3_column_name()].
 **
 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
-** to an empty string, or a pointer that contains only whitespace and/or 
+** to an empty string, or a pointer that contains only whitespace and/or
 ** SQL comments, then no SQL statements are evaluated and the database
 ** is not changed.
 **
@@ -507,17 +503,22 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_IOERR_BEGIN_ATOMIC      (SQLITE_IOERR | (29<<8))
 #define SQLITE_IOERR_COMMIT_ATOMIC     (SQLITE_IOERR | (30<<8))
 #define SQLITE_IOERR_ROLLBACK_ATOMIC   (SQLITE_IOERR | (31<<8))
+#define SQLITE_IOERR_DATA              (SQLITE_IOERR | (32<<8))
+#define SQLITE_IOERR_CORRUPTFS         (SQLITE_IOERR | (33<<8))
 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
 #define SQLITE_LOCKED_VTAB             (SQLITE_LOCKED |  (2<<8))
 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
+#define SQLITE_BUSY_TIMEOUT            (SQLITE_BUSY   |  (3<<8))
 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
 #define SQLITE_CANTOPEN_DIRTYWAL       (SQLITE_CANTOPEN | (5<<8)) /* Not Used */
+#define SQLITE_CANTOPEN_SYMLINK        (SQLITE_CANTOPEN | (6<<8))
 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
 #define SQLITE_CORRUPT_SEQUENCE        (SQLITE_CORRUPT | (2<<8))
+#define SQLITE_CORRUPT_INDEX           (SQLITE_CORRUPT | (3<<8))
 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
@@ -535,11 +536,13 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
+#define SQLITE_CONSTRAINT_PINNED       (SQLITE_CONSTRAINT |(11<<8))
 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
 #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
+#define SQLITE_OK_SYMLINK              (SQLITE_OK | (2<<8))
 
 /*
 ** CAPI3REF: Flags For File Open Operations
@@ -562,14 +565,18 @@ SQLITE_API int sqlite3_exec(
 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
-#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
+#define SQLITE_OPEN_SUPER_JOURNAL    0x00004000  /* VFS only */
 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
+#define SQLITE_OPEN_NOFOLLOW         0x01000000  /* Ok for sqlite3_open_v2() */
 
 /* Reserved:                         0x00F00000 */
+/* Legacy compatibility: */
+#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
+
 
 /*
 ** CAPI3REF: Device Characteristics
@@ -666,7 +673,7 @@ SQLITE_API int sqlite3_exec(
 /*
 ** CAPI3REF: OS Interface Open File Handle
 **
-** An [sqlite3_file] object represents an open file in the 
+** An [sqlite3_file] object represents an open file in the
 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
 ** implementations will
 ** want to subclass this object by appending additional fields
@@ -688,7 +695,7 @@ struct sqlite3_file {
 ** This object defines the methods used to perform various operations
 ** against the open file represented by the [sqlite3_file] object.
 **
-** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
+** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
@@ -838,7 +845,7 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
 ** extends and truncates the database file in chunks of a size specified
-** by the user. The fourth argument to [sqlite3_file_control()] should 
+** by the user. The fourth argument to [sqlite3_file_control()] should
 ** point to an integer (type int) containing the new chunk-size to use
 ** for the nominated database. Allocating database file space in large
 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
@@ -861,24 +868,24 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_SYNC]]
 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
 ** sent to the VFS immediately before the xSync method is invoked on a
-** database file descriptor. Or, if the xSync method is not invoked 
-** because the user has configured SQLite with 
-** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
+** database file descriptor. Or, if the xSync method is not invoked
+** because the user has configured SQLite with
+** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
 ** of the xSync method. In most cases, the pointer argument passed with
 ** this file-control is NULL. However, if the database file is being synced
 ** as part of a multi-database commit, the argument points to a nul-terminated
-** string containing the transactions master-journal file name. VFSes that 
-** do not need this signal should silently ignore this opcode. Applications 
-** should not call [sqlite3_file_control()] with this opcode as doing so may 
-** disrupt the operation of the specialized VFSes that do require it.  
+** string containing the transactions super-journal file name. VFSes that
+** do not need this signal should silently ignore this opcode. Applications
+** should not call [sqlite3_file_control()] with this opcode as doing so may
+** disrupt the operation of the specialized VFSes that do require it.
 **
 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
 ** and sent to the VFS after a transaction has been committed immediately
 ** but before the database is unlocked. VFSes that do not need this signal
 ** should silently ignore this opcode. Applications should not call
-** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
-** operation of the specialized VFSes that do require it.  
+** [sqlite3_file_control()] with this opcode as doing so may disrupt the
+** operation of the specialized VFSes that do require it.
 **
 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
@@ -926,13 +933,13 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
 ** a write transaction to indicate that, unless it is rolled back for some
-** reason, the entire database file will be overwritten by the current 
+** reason, the entire database file will be overwritten by the current
 ** transaction. This is used by VACUUM operations.
 **
 ** <li>[[SQLITE_FCNTL_VFSNAME]]
 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
-** final bottom-level VFS are written into memory obtained from 
+** final bottom-level VFS are written into memory obtained from
 ** [sqlite3_malloc()] and the result is stored in the char* variable
 ** that the fourth parameter of [sqlite3_file_control()] points to.
 ** The caller is responsible for freeing the memory when done.  As with
@@ -951,7 +958,7 @@ struct sqlite3_io_methods {
 ** upper-most shim only.
 **
 ** <li>[[SQLITE_FCNTL_PRAGMA]]
-** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
+** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
 ** file control is sent to the open [sqlite3_file] object corresponding
 ** to the database file to which the pragma statement refers. ^The argument
 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
@@ -962,7 +969,7 @@ struct sqlite3_io_methods {
 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
 ** or the equivalent and that string will become the result of the pragma or
 ** the error message if the pragma fails. ^If the
-** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
+** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
 ** file control returns [SQLITE_OK], then the parser assumes that the
 ** VFS has handled the PRAGMA itself and the parser generates a no-op
@@ -979,16 +986,16 @@ struct sqlite3_io_methods {
 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
 ** file-control may be invoked by SQLite on the database file handle
 ** shortly after it is opened in order to provide a custom VFS with access
-** to the connections busy-handler callback. The argument is of type (void **)
+** to the connection's busy-handler callback. The argument is of type (void**)
 ** - an array of two (void *) values. The first (void *) actually points
-** to a function of type (int (*)(void *)). In order to invoke the connections
+** to a function of type (int (*)(void *)). In order to invoke the connection's
 ** busy-handler, this function should be invoked with the second (void *) in
 ** the array as the only argument. If it returns non-zero, then the operation
 ** should be retried. If it returns zero, the custom VFS should abandon the
 ** current operation.
 **
 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
-** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
+** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
 ** to have SQLite generate a
 ** temporary filename using the same algorithm that is followed to generate
 ** temporary filenames for TEMP tables and other internal uses.  The
@@ -1002,7 +1009,7 @@ struct sqlite3_io_methods {
 ** The argument is a pointer to a value of type sqlite3_int64 that
 ** is an advisory maximum number of bytes in the file to memory map.  The
 ** pointer is overwritten with the old value.  The limit is not changed if
-** the value originally pointed to is negative, and so the current limit 
+** the value originally pointed to is negative, and so the current limit
 ** can be queried by passing in a pointer to a negative number.  This
 ** file-control is used internally to implement [PRAGMA mmap_size].
 **
@@ -1046,7 +1053,7 @@ struct sqlite3_io_methods {
 ** <li>[[SQLITE_FCNTL_RBU]]
 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
 ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
-** this opcode.  
+** this opcode.
 **
 ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
 ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
@@ -1063,7 +1070,7 @@ struct sqlite3_io_methods {
 **
 ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
 ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to 
+** operations since the previous successful call to
 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
 ** This file control returns [SQLITE_OK] if and only if the writes were
 ** all performed successfully and have been committed to persistent storage.
@@ -1075,7 +1082,7 @@ struct sqlite3_io_methods {
 **
 ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
 ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
-** operations since the previous successful call to 
+** operations since the previous successful call to
 ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
 ** ^This file control takes the file descriptor out of batch write mode
 ** so that all subsequent write operations are independent.
@@ -1083,10 +1090,12 @@ struct sqlite3_io_methods {
 ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
 **
 ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
-** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
-** a file lock using the xLock or xShmLock methods of the VFS to wait
-** for up to M milliseconds before failing, where M is the single 
-** unsigned integer parameter.
+** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
+** to block for up to M milliseconds before failing when attempting to
+** obtain a file lock using the xLock or xShmLock methods of the VFS.
+** The parameter is a pointer to a 32-bit signed integer that contains
+** the value that M is to be set to. Before returning, the 32-bit signed
+** integer is overwritten with the previous value of M.
 **
 ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
 ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
@@ -1101,12 +1110,23 @@ struct sqlite3_io_methods {
 ** not provide a mechanism to detect changes to MAIN only.  Also, the
 ** [sqlite3_total_changes()] interface responds to internal changes only and
 ** omits changes made by other database connections.  The
-** [PRAGMA data_version] command provide a mechanism to detect changes to
+** [PRAGMA data_version] command provides a mechanism to detect changes to
 ** a single attached database that occur due to other database connections,
 ** but omits changes implemented by the database connection on which it is
 ** called.  This file control is the only mechanism to detect changes that
 ** happen either internally or externally and that are associated with
 ** a particular attached database.
+**
+** <li>[[SQLITE_FCNTL_CKPT_START]]
+** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
+** in wal mode before the client starts to copy pages from the wal
+** file to the database file.
+**
+** <li>[[SQLITE_FCNTL_CKPT_DONE]]
+** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
+** in wal mode after the client has finished copying pages from the wal
+** file to the database file, but before the *-shm file is updated to
+** record the fact that the pages have been checkpointed.
 ** </ul>
 */
 #define SQLITE_FCNTL_LOCKSTATE               1
@@ -1144,6 +1164,9 @@ struct sqlite3_io_methods {
 #define SQLITE_FCNTL_LOCK_TIMEOUT           34
 #define SQLITE_FCNTL_DATA_VERSION           35
 #define SQLITE_FCNTL_SIZE_LIMIT             36
+#define SQLITE_FCNTL_CKPT_DONE              37
+#define SQLITE_FCNTL_RESERVE_BYTES          38
+#define SQLITE_FCNTL_CKPT_START             39
 
 /* deprecated names */
 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
@@ -1189,10 +1212,10 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6].  Additional fields
 ** may be appended to the sqlite3_vfs object and the iVersion value
 ** may increase again in future versions of SQLite.
-** Note that the structure
-** of the sqlite3_vfs object changes in the transition from
+** Note that due to an oversight, the structure
+** of the sqlite3_vfs object changed in the transition from
 ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
-** and yet the iVersion field was not modified.
+** and yet the iVersion field was not increased.
 **
 ** The szOsFile field is the size of the subclassed [sqlite3_file]
 ** structure used by this VFS.  mxPathname is the maximum length of
@@ -1227,14 +1250,14 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** the [sqlite3_file] can safely store a pointer to the
 ** filename if it needs to remember the filename for some reason.
 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
-** must invent its own temporary name for the file.  ^Whenever the 
+** must invent its own temporary name for the file.  ^Whenever the
 ** xFilename parameter is NULL it will also be the case that the
 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
 **
 ** The flags argument to xOpen() includes all bits set in
 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
 ** or [sqlite3_open16()] is used, then flags includes at least
-** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
+** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
 ** If xOpen() opens a file read-only then it sets *pOutFlags to
 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
 **
@@ -1248,7 +1271,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
-** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
+** <li>  [SQLITE_OPEN_SUPER_JOURNAL]
 ** <li>  [SQLITE_OPEN_WAL]
 ** </ul>)^
 **
@@ -1276,14 +1299,14 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
-** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
+** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
 ** be created, and that it is an error if it already exists.
-** It is <i>not</i> used to indicate the file should be opened 
+** It is <i>not</i> used to indicate the file should be opened
 ** for exclusive access.
 **
 ** ^At least szOsFile bytes of memory are allocated by SQLite
-** to hold the  [sqlite3_file] structure passed as the third
+** to hold the [sqlite3_file] structure passed as the third
 ** argument to xOpen.  The xOpen method does not have to
 ** allocate the structure; it should just fill it in.  Note that
 ** the xOpen method must set the sqlite3_file.pMethods to either
@@ -1303,7 +1326,7 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** non-zero error code if there is an I/O error or if the name of
 ** the file given in the second argument is illegal.  If SQLITE_OK
 ** is returned, then non-zero or zero is written into *pResOut to indicate
-** whether or not the file is accessible.  
+** whether or not the file is accessible.
 **
 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
 ** output buffer xFullPathname.  The exact size of the output buffer
@@ -1323,16 +1346,16 @@ typedef struct sqlite3_api_routines sqlite3_api_routines;
 ** method returns a Julian Day Number for the current date and time as
 ** a floating point value.
 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
-** Day Number multiplied by 86400000 (the number of milliseconds in 
-** a 24-hour day).  
+** Day Number multiplied by 86400000 (the number of milliseconds in
+** a 24-hour day).
 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
-** date and time if that method is available (if iVersion is 2 or 
+** date and time if that method is available (if iVersion is 2 or
 ** greater and the function pointer is not NULL) and will fall back
 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
 **
 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
 ** are not used by the SQLite core.  These optional interfaces are provided
-** by some VFSes to facilitate testing of the VFS code. By overriding 
+** by some VFSes to facilitate testing of the VFS code. By overriding
 ** system calls with functions under its control, a test program can
 ** simulate faults and error conditions that would otherwise be difficult
 ** or impossible to induce.  The set of system calls that can be overridden
@@ -1379,7 +1402,7 @@ struct sqlite3_vfs {
   /*
   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
   ** New fields may be appended in future versions.  The iVersion
-  ** value will increment whenever this happens. 
+  ** value will increment whenever this happens.
   */
 };
 
@@ -1423,7 +1446,7 @@ struct sqlite3_vfs {
 ** </ul>
 **
 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
-** was given on the corresponding lock.  
+** was given on the corresponding lock.
 **
 ** The xShmLock method can transition between unlocked and SHARED or
 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
@@ -1568,7 +1591,7 @@ SQLITE_API int sqlite3_config(int, ...);
 ** [database connection] (specified in the first argument).
 **
 ** The second argument to sqlite3_db_config(D,V,...)  is the
-** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
+** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
 ** that indicates what aspect of the [database connection] is being configured.
 ** Subsequent arguments vary depending on the configuration verb.
 **
@@ -1586,7 +1609,7 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
 ** This object is used in only one place in the SQLite interface.
 ** A pointer to an instance of this object is the argument to
 ** [sqlite3_config()] when the configuration option is
-** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
+** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
 ** By creating an instance of this object
 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
 ** during configuration, an application can specify an alternative
@@ -1616,17 +1639,17 @@ SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
 ** allocators round up memory allocations at least to the next multiple
 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
 ** Every memory allocation request coming in through [sqlite3_malloc()]
-** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
+** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
 ** that causes the corresponding memory allocation to fail.
 **
 ** The xInit method initializes the memory allocator.  For example,
-** it might allocate any require mutexes or initialize internal data
+** it might allocate any required mutexes or initialize internal data
 ** structures.  The xShutdown method is invoked (indirectly) by
 ** [sqlite3_shutdown()] and should deallocate any resources acquired
 ** by xInit.  The pAppData pointer is used as the only parameter to
 ** xInit and xShutdown.
 **
-** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
+** SQLite holds the [SQLITE_MUTEX_STATIC_MAIN] mutex when it invokes
 ** the xInit method, so the xInit method need not be threadsafe.  The
 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
 ** not need to be threadsafe either.  For all other methods, SQLite
@@ -1674,7 +1697,7 @@ struct sqlite3_mem_methods {
 ** by a single thread.   ^If SQLite is compiled with
 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 ** it is not possible to change the [threading mode] from its default
-** value of Single-thread and so [sqlite3_config()] will return 
+** value of Single-thread and so [sqlite3_config()] will return
 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
 ** configuration option.</dd>
 **
@@ -1709,7 +1732,7 @@ struct sqlite3_mem_methods {
 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
 **
 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
-** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
+** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
 ** The argument specifies
 ** alternative low-level memory allocation routines to be used in place of
@@ -1742,6 +1765,7 @@ struct sqlite3_mem_methods {
 ** memory allocation statistics. ^(When memory allocation statistics are
 ** disabled, the following SQLite interfaces become non-operational:
 **   <ul>
+**   <li> [sqlite3_hard_heap_limit64()]
 **   <li> [sqlite3_memory_used()]
 **   <li> [sqlite3_memory_highwater()]
 **   <li> [sqlite3_soft_heap_limit64()]
@@ -1759,8 +1783,8 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
 ** that SQLite can use for the database page cache with the default page
-** cache implementation.  
-** This configuration option is a no-op if an application-define page
+** cache implementation.
+** This configuration option is a no-op if an application-defined page
 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
@@ -1787,7 +1811,7 @@ struct sqlite3_mem_methods {
 ** additional cache line. </dd>
 **
 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
-** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
+** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
 ** that SQLite will use for all of its dynamic memory allocation needs
 ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
@@ -1842,7 +1866,7 @@ struct sqlite3_mem_methods {
 ** configuration on individual connections.)^ </dd>
 **
 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
-** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
+** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
 ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
 ** the interface to a custom page cache implementation.)^
 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
@@ -1856,7 +1880,7 @@ struct sqlite3_mem_methods {
 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
 ** global [error log].
 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
-** function with a call signature of void(*)(void*,int,const char*), 
+** function with a call signature of void(*)(void*,int,const char*),
 ** and a pointer to void. ^If the function pointer is not NULL, it is
 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
@@ -1965,7 +1989,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
-** becomes the [statement journal] spill-to-disk threshold.  
+** becomes the [statement journal] spill-to-disk threshold.
 ** [Statement journals] are held in memory until their size (in bytes)
 ** exceeds this threshold, at which point they are written to disk.
 ** Or if the threshold is -1, statement journals are always held
@@ -1987,7 +2011,7 @@ struct sqlite3_mem_methods {
 ** than the configured sorter-reference size threshold - then a reference
 ** is stored in each sorted record and the required column values loaded
 ** from the database as records are returned in sorted order. The default
-** value for this option is to never use this optimization. Specifying a 
+** value for this option is to never use this optimization. Specifying a
 ** negative value for this option restores the default behaviour.
 ** This option is only available if SQLite is compiled with the
 ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
@@ -2015,7 +2039,7 @@ struct sqlite3_mem_methods {
 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
-/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
+/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
@@ -2050,7 +2074,7 @@ struct sqlite3_mem_methods {
 ** <dl>
 ** [[SQLITE_DBCONFIG_LOOKASIDE]]
 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
-** <dd> ^This option takes three additional arguments that determine the 
+** <dd> ^This option takes three additional arguments that determine the
 ** [lookaside memory allocator] configuration for the [database connection].
 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
 ** pointer to a memory buffer to use for lookaside memory.
@@ -2068,7 +2092,7 @@ struct sqlite3_mem_methods {
 ** when the "current value" returned by
 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
 ** Any attempt to change the lookaside memory configuration when lookaside
-** memory is in use leaves the configuration unchanged and returns 
+** memory is in use leaves the configuration unchanged and returns
 ** [SQLITE_BUSY].)^</dd>
 **
 ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
@@ -2145,11 +2169,11 @@ struct sqlite3_mem_methods {
 ** until after the database connection closes.
 ** </dd>
 **
-** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]] 
+** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
 ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
-** <dd> Usually, when a database in wal mode is closed or detached from a 
-** database handle, SQLite checks if this will mean that there are now no 
-** connections at all to the database. If so, it performs a checkpoint 
+** <dd> Usually, when a database in wal mode is closed or detached from a
+** database handle, SQLite checks if this will mean that there are now no
+** connections at all to the database. If so, it performs a checkpoint
 ** operation before closing the connection. This option may be used to
 ** override this behaviour. The first parameter passed to this operation
 ** is an integer - positive to disable checkpoints-on-close, or zero (the
@@ -2168,7 +2192,7 @@ struct sqlite3_mem_methods {
 ** slower.  But the QPSG has the advantage of more predictable behavior.  With
 ** the QPSG active, SQLite will always use the same query plan in the field as
 ** was used during testing in the lab.
-** The first argument to this setting is an integer which is 0 to disable 
+** The first argument to this setting is an integer which is 0 to disable
 ** the QPSG, positive to enable QPSG, or negative to leave the setting
 ** unchanged. The second parameter is a pointer to an integer into which
 ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
@@ -2176,15 +2200,15 @@ struct sqlite3_mem_methods {
 ** </dd>
 **
 ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
-** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not 
+** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
 ** include output for any operations performed by trigger programs. This
 ** option is used to set or clear (the default) a flag that governs this
 ** behavior. The first parameter passed to this operation is an integer -
 ** positive to enable output for trigger programs, or zero to disable it,
 ** or negative to leave the setting unchanged.
-** The second parameter is a pointer to an integer into which is written 
-** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if 
-** it is not disabled, 1 if it is.  
+** The second parameter is a pointer to an integer into which is written
+** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
+** it is not disabled, 1 if it is.
 ** </dd>
 **
 ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
@@ -2198,7 +2222,7 @@ struct sqlite3_mem_methods {
 **      database, or calling sqlite3_table_column_metadata(), ignoring any
 **      errors.  This step is only necessary if the application desires to keep
 **      the database in WAL mode after the reset if it was in WAL mode before
-**      the reset.  
+**      the reset.
 ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
 ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
 ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
@@ -2210,7 +2234,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
 ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
 ** "defensive" flag for a database connection.  When the defensive
-** flag is enabled, language features that allow ordinary SQL to 
+** flag is enabled, language features that allow ordinary SQL to
 ** deliberately corrupt the database file are disabled.  The disabled
 ** features include but are not limited to the following:
 ** <ul>
@@ -2225,7 +2249,7 @@ struct sqlite3_mem_methods {
 ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
 ** "writable_schema" flag. This has the same effect and is logically equivalent
 ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
-** The first argument to this setting is an integer which is 0 to disable 
+** The first argument to this setting is an integer which is 0 to disable
 ** the writable_schema, positive to enable writable_schema, or negative to
 ** leave the setting unchanged. The second parameter is a pointer to an
 ** integer into which is written 0 or 1 to indicate whether the writable_schema
@@ -2245,7 +2269,7 @@ struct sqlite3_mem_methods {
 ** [[SQLITE_DBCONFIG_DQS_DML]]
 ** <dt>SQLITE_DBCONFIG_DQS_DML</td>
 ** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
-** the legacy [double-quoted string literal] misfeature for DML statement
+** the legacy [double-quoted string literal] misfeature for DML statements
 ** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
 ** default value of this setting is determined by the [-DSQLITE_DQS]
 ** compile-time option.
@@ -2259,6 +2283,48 @@ struct sqlite3_mem_methods {
 ** default value of this setting is determined by the [-DSQLITE_DQS]
 ** compile-time option.
 ** </dd>
+**
+** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
+** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
+** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
+** assume that database schemas are untainted by malicious content.
+** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
+** takes additional defensive steps to protect the application from harm
+** including:
+** <ul>
+** <li> Prohibit the use of SQL functions inside triggers, views,
+** CHECK constraints, DEFAULT clauses, expression indexes,
+** partial indexes, or generated columns
+** unless those functions are tagged with [SQLITE_INNOCUOUS].
+** <li> Prohibit the use of virtual tables inside of triggers or views
+** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
+** </ul>
+** This setting defaults to "on" for legacy compatibility, however
+** all applications are advised to turn it off if possible. This setting
+** can also be controlled using the [PRAGMA trusted_schema] statement.
+** </dd>
+**
+** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
+** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
+** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
+** the legacy file format flag.  When activated, this flag causes all newly
+** created database file to have a schema format version number (the 4-byte
+** integer found at offset 44 into the database header) of 1.  This in turn
+** means that the resulting database file will be readable and writable by
+** any SQLite version back to 3.0.0 ([dateof:3.0.0]).  Without this setting,
+** newly created databases are generally not understandable by SQLite versions
+** prior to 3.3.0 ([dateof:3.3.0]).  As these words are written, there
+** is now scarcely any need to generated database files that are compatible
+** all the way back to version 3.0.0, and so this setting is of little
+** practical use, but is provided so that SQLite can continue to claim the
+** ability to generate new database files that are compatible with  version
+** 3.0.0.
+** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
+** the [VACUUM] command will fail with an obscure error when attempting to
+** process a table with generated columns and a descending index.  This is
+** not considered a bug since SQLite versions 3.3.0 and earlier do not support
+** either generated columns or decending indexes.
+** </dd>
 ** </dl>
 */
 #define SQLITE_DBCONFIG_MAINDBNAME            1000 /* const char* */
@@ -2277,7 +2343,9 @@ struct sqlite3_mem_methods {
 #define SQLITE_DBCONFIG_DQS_DML               1013 /* int int* */
 #define SQLITE_DBCONFIG_DQS_DDL               1014 /* int int* */
 #define SQLITE_DBCONFIG_ENABLE_VIEW           1015 /* int int* */
-#define SQLITE_DBCONFIG_MAX                   1015 /* Largest DBCONFIG */
+#define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    1016 /* int int* */
+#define SQLITE_DBCONFIG_TRUSTED_SCHEMA        1017 /* int int* */
+#define SQLITE_DBCONFIG_MAX                   1017 /* Largest DBCONFIG */
 
 /*
 ** CAPI3REF: Enable Or Disable Extended Result Codes
@@ -2304,8 +2372,8 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
 ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
 ** the most recent successful [INSERT] into a rowid table or [virtual table]
 ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
-** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred 
-** on the database connection D, then sqlite3_last_insert_rowid(D) returns 
+** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
+** on the database connection D, then sqlite3_last_insert_rowid(D) returns
 ** zero.
 **
 ** As well as being set automatically as rows are inserted into database
@@ -2315,15 +2383,15 @@ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
 ** Some virtual table implementations may INSERT rows into rowid tables as
 ** part of committing a transaction (e.g. to flush data accumulated in memory
 ** to disk). In this case subsequent calls to this function return the rowid
-** associated with these internal INSERT operations, which leads to 
+** associated with these internal INSERT operations, which leads to
 ** unintuitive results. Virtual table implementations that do write to rowid
-** tables in this way can avoid this problem by restoring the original 
-** rowid value using [sqlite3_set_last_insert_rowid()] before returning 
+** tables in this way can avoid this problem by restoring the original
+** rowid value using [sqlite3_set_last_insert_rowid()] before returning
 ** control to the user.
 **
-** ^(If an [INSERT] occurs within a trigger then this routine will 
-** return the [rowid] of the inserted row as long as the trigger is 
-** running. Once the trigger program ends, the value returned 
+** ^(If an [INSERT] occurs within a trigger then this routine will
+** return the [rowid] of the inserted row as long as the trigger is
+** running. Once the trigger program ends, the value returned
 ** by this routine reverts to what it was before the trigger was fired.)^
 **
 ** ^An [INSERT] that fails due to a constraint violation is not a
@@ -2356,7 +2424,7 @@ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
 ** METHOD: sqlite3
 **
 ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
-** set the value returned by calling sqlite3_last_insert_rowid(D) to R 
+** set the value returned by calling sqlite3_last_insert_rowid(D) to R
 ** without inserting a row into the database.
 */
 SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
@@ -2372,37 +2440,37 @@ SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
 ** returned by this function.
 **
 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
-** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
+** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
-** 
-** Changes to a view that are intercepted by 
-** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
-** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
-** DELETE statement run on a view is always zero. Only changes made to real 
+**
+** Changes to a view that are intercepted by
+** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
+** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
+** DELETE statement run on a view is always zero. Only changes made to real
 ** tables are counted.
 **
 ** Things are more complicated if the sqlite3_changes() function is
 ** executed while a trigger program is running. This may happen if the
 ** program uses the [changes() SQL function], or if some other callback
 ** function invokes sqlite3_changes() directly. Essentially:
-** 
+**
 ** <ul>
 **   <li> ^(Before entering a trigger program the value returned by
-**        sqlite3_changes() function is saved. After the trigger program 
+**        sqlite3_changes() function is saved. After the trigger program
 **        has finished, the original value is restored.)^
-** 
-**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
-**        statement sets the value returned by sqlite3_changes() 
-**        upon completion as normal. Of course, this value will not include 
-**        any changes performed by sub-triggers, as the sqlite3_changes() 
+**
+**   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
+**        statement sets the value returned by sqlite3_changes()
+**        upon completion as normal. Of course, this value will not include
+**        any changes performed by sub-triggers, as the sqlite3_changes()
 **        value will be saved and restored after each sub-trigger has run.)^
 ** </ul>
-** 
+**
 ** ^This means that if the changes() SQL function (or similar) is used
-** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
+** by the first INSERT, UPDATE or DELETE statement within a trigger, it
 ** returns the value as set when the calling statement began executing.
-** ^If it is used by the second or subsequent such statement within a trigger 
-** program, the value returned reflects the number of rows modified by the 
+** ^If it is used by the second or subsequent such statement within a trigger
+** program, the value returned reflects the number of rows modified by the
 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
 **
 ** If a separate thread makes changes on the same database connection
@@ -2430,10 +2498,10 @@ SQLITE_API sqlite3_uint64 sqlite3_changes(sqlite3*);
 ** since the database connection was opened, including those executed as
 ** part of trigger programs. ^Executing any other type of SQL statement
 ** does not affect the value returned by sqlite3_total_changes().
-** 
+**
 ** ^Changes made as part of [foreign key actions] are included in the
 ** count, but those made as part of REPLACE constraint resolution are
-** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
+** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
 ** are not counted.
 **
 ** The [sqlite3_total_changes(D)] interface only reports the number
@@ -2442,7 +2510,7 @@ SQLITE_API sqlite3_uint64 sqlite3_changes(sqlite3*);
 ** To detect changes against a database file from other database
 ** connections use the [PRAGMA data_version] command or the
 ** [SQLITE_FCNTL_DATA_VERSION] [file control].
-** 
+**
 ** If a separate thread makes changes on the same database connection
 ** while [sqlite3_total_changes()] is running then the value
 ** returned is unpredictable and not meaningful.
@@ -2486,8 +2554,8 @@ SQLITE_API sqlite3_uint64 sqlite3_total_changes(sqlite3*);
 **
 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
-** that are started after the sqlite3_interrupt() call and before the 
-** running statements reaches zero are interrupted as if they had been
+** that are started after the sqlite3_interrupt() call and before the
+** running statement count reaches zero are interrupted as if they had been
 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
 ** that are started after the running statement count reaches zero are
 ** not effected by the sqlite3_interrupt().
@@ -2518,7 +2586,7 @@ SQLITE_API void sqlite3_interrupt(sqlite3*);
 ** ^These routines do not parse the SQL statements thus
 ** will not detect syntactically incorrect SQL.
 **
-** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
+** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
 ** automatically by sqlite3_complete16().  If that initialization fails,
 ** then the return value from sqlite3_complete16() will be non-zero
@@ -2563,7 +2631,7 @@ SQLITE_API int sqlite3_complete16(const void *sql);
 ** The presence of a busy handler does not guarantee that it will be invoked
 ** when there is lock contention. ^If SQLite determines that invoking the busy
 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
-** to the application instead of invoking the 
+** to the application instead of invoking the
 ** busy handler.
 ** Consider a scenario where one process is holding a read lock that
 ** it is trying to promote to a reserved lock and
@@ -2588,7 +2656,7 @@ SQLITE_API int sqlite3_complete16(const void *sql);
 ** database connection that invoked the busy handler.  In other words,
 ** the busy handler is not reentrant.  Any such actions
 ** result in undefined behavior.
-** 
+**
 ** A busy handler must not close the database connection
 ** or [prepared statement] that invoked the busy handler.
 */
@@ -2655,9 +2723,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
 **        Cindy       | 21
 ** </pre></blockquote>
 **
-** There are two column (M==2) and three rows (N==3).  Thus the
+** There are two columns (M==2) and three rows (N==3).  Thus the
 ** result table has 8 entries.  Suppose the result table is stored
-** in an array names azResult.  Then azResult holds this content:
+** in an array named azResult.  Then azResult holds this content:
 **
 ** <blockquote><pre>
 **        azResult&#91;0] = "Name";
@@ -2706,7 +2774,7 @@ SQLITE_API void sqlite3_free_table(char **result);
 ** These routines are work-alikes of the "printf()" family of functions
 ** from the standard C library.
 ** These routines understand most of the common formatting options from
-** the standard library printf() 
+** the standard library printf()
 ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
 ** See the [built-in printf()] documentation for details.
 **
@@ -2750,7 +2818,7 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
 **
 ** The SQLite core uses these three routines for all of its own
 ** internal memory allocation needs. "Core" in the previous sentence
-** does not include operating-system specific VFS implementation.  The
+** does not include operating-system specific [VFS] implementation.  The
 ** Windows VFS uses native malloc() and free() for some operations.
 **
 ** ^The sqlite3_malloc() routine returns a pointer to a block
@@ -2811,19 +2879,6 @@ SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
 ** option is used.
 **
-** In SQLite version 3.5.0 and 3.5.1, it was possible to define
-** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
-** implementation of these routines to be omitted.  That capability
-** is no longer provided.  Only built-in memory allocators can be used.
-**
-** Prior to SQLite version 3.7.10, the Windows OS interface layer called
-** the system malloc() and free() directly when converting
-** filenames between the UTF-8 encoding used by SQLite
-** and whatever filename encoding is used by the particular Windows
-** installation.  Memory allocation errors were detected, but
-** they were reported back as [SQLITE_CANTOPEN] or
-** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
-**
 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
 ** must be either NULL or else pointers obtained from a prior
 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
@@ -2872,7 +2927,7 @@ SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
 ** select random [ROWID | ROWIDs] when inserting new records into a table that
 ** already uses the largest possible [ROWID].  The PRNG is also used for
-** the build-in random() and randomblob() SQL functions.  This interface allows
+** the built-in random() and randomblob() SQL functions.  This interface allows
 ** applications to access the same PRNG for other purposes.
 **
 ** ^A call to this routine stores N bytes of randomness into buffer P.
@@ -2915,7 +2970,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P);
 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
 ** authorizer will fail with an error message explaining that
-** access is denied. 
+** access is denied.
 **
 ** ^The first parameter to the authorizer callback is a copy of the third
 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
@@ -2968,7 +3023,7 @@ SQLITE_API void sqlite3_randomness(int N, void *P);
 ** database connections for the meaning of "modify" in this paragraph.
 **
 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
-** statement might be re-prepared during [sqlite3_step()] due to a 
+** statement might be re-prepared during [sqlite3_step()] due to a
 ** schema change.  Hence, the application should ensure that the
 ** correct authorizer callback remains in place during the [sqlite3_step()].
 **
@@ -3116,7 +3171,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 ** execution of the prepared statement, such as at the start of each
 ** trigger subprogram. ^The P argument is a pointer to the
 ** [prepared statement]. ^The X argument is a pointer to a string which
-** is the unexpanded SQL text of the prepared statement or an SQL comment 
+** is the unexpanded SQL text of the prepared statement or an SQL comment
 ** that indicates the invocation of a trigger.  ^The callback can compute
 ** the same text that would have been returned by the legacy [sqlite3_trace()]
 ** interface by using the X argument when X begins with "--" and invoking
@@ -3132,7 +3187,7 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 **
 ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
-** statement generates a single row of result.  
+** statement generates a single row of result.
 ** ^The P argument is a pointer to the [prepared statement] and the
 ** X argument is unused.
 **
@@ -3159,10 +3214,10 @@ SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 ** M argument should be the bitwise OR-ed combination of
 ** zero or more [SQLITE_TRACE] constants.
 **
-** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides 
+** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
 ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
 **
-** ^The X callback is invoked whenever any of the events identified by 
+** ^The X callback is invoked whenever any of the events identified by
 ** mask M occur.  ^The integer return value from the callback is currently
 ** ignored, though this may change in future releases.  Callback
 ** implementations should return zero to ensure future compatibility.
@@ -3194,8 +3249,8 @@ SQLITE_API int sqlite3_trace_v2(
 ** database connection D.  An example use for this
 ** interface is to keep a GUI updated during a large query.
 **
-** ^The parameter P is passed through as the only parameter to the 
-** callback function X.  ^The parameter N is the approximate number of 
+** ^The parameter P is passed through as the only parameter to the
+** callback function X.  ^The parameter N is the approximate number of
 ** [virtual machine instructions] that are evaluated between successive
 ** invocations of the callback X.  ^If N is less than one then the progress
 ** handler is disabled.
@@ -3222,7 +3277,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** CAPI3REF: Opening A New Database Connection
 ** CONSTRUCTOR: sqlite3
 **
-** ^These routines open an SQLite database file as specified by the 
+** ^These routines open an SQLite database file as specified by the
 ** filename argument. ^The filename argument is interpreted as UTF-8 for
 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
@@ -3246,10 +3301,8 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** The sqlite3_open_v2() interface works like sqlite3_open()
 ** except that it accepts two additional parameters for additional control
 ** over the new database connection.  ^(The flags parameter to
-** sqlite3_open_v2() can take one of
-** the following three values, optionally combined with the 
-** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
-** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
+** sqlite3_open_v2() must include, at a minimum, one of the following
+** three flag combinations:)^
 **
 ** <dl>
 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
@@ -3267,23 +3320,51 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** sqlite3_open() and sqlite3_open16().</dd>)^
 ** </dl>
 **
+** In addition to the required flags, the following optional flags are
+** also supported:
+**
+** <dl>
+** ^(<dt>[SQLITE_OPEN_URI]</dt>
+** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
+** <dd>The database will be opened as an in-memory database.  The database
+** is named by the "filename" argument for the purposes of cache-sharing,
+** if shared cache mode is enabled, but the "filename" is otherwise ignored.
+** </dd>)^
+**
+** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
+** <dd>The new database connection will use the "multi-thread"
+** [threading mode].)^  This means that separate threads are allowed
+** to use SQLite at the same time, as long as each thread is using
+** a different [database connection].
+**
+** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
+** <dd>The new database connection will use the "serialized"
+** [threading mode].)^  This means the multiple threads can safely
+** attempt to use the same database connection at the same time.
+** (Mutexes will block any actual concurrency, but in this mode
+** there is no harm in trying.)
+**
+** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
+** <dd>The database is opened [shared cache] enabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
+** <dd>The database is opened [shared cache] disabled, overriding
+** the default shared cache setting provided by
+** [sqlite3_enable_shared_cache()].)^
+**
+** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
+** <dd>The database filename is not allowed to be a symbolic link</dd>
+** </dl>)^
+**
 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
-** combinations shown above optionally combined with other
+** required combinations shown above optionally combined with other
 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
 ** then the behavior is undefined.
 **
-** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
-** opens in the multi-thread [threading mode] as long as the single-thread
-** mode has not been set at compile-time or start-time.  ^If the
-** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
-** in the serialized [threading mode] unless single-thread was
-** previously selected at compile-time or start-time.
-** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
-** eligible to use [shared cache mode], regardless of whether or not shared
-** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
-** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
-** participate in [shared cache mode] even if it is enabled.
-**
 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
 ** [sqlite3_vfs] object that defines the operating system interface that
 ** the new database connection should use.  ^If the fourth parameter is
@@ -3315,17 +3396,17 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 ** information.
 **
 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
-** authority, then it must be either an empty string or the string 
-** "localhost". ^If the authority is not an empty string or "localhost", an 
-** error is returned to the caller. ^The fragment component of a URI, if 
+** authority, then it must be either an empty string or the string
+** "localhost". ^If the authority is not an empty string or "localhost", an
+** error is returned to the caller. ^The fragment component of a URI, if
 ** present, is ignored.
 **
 ** ^SQLite uses the path component of the URI as the name of the disk file
-** which contains the database. ^If the path begins with a '/' character, 
-** then it is interpreted as an absolute path. ^If the path does not begin 
+** which contains the database. ^If the path begins with a '/' character,
+** then it is interpreted as an absolute path. ^If the path does not begin
 ** with a '/' (meaning that the authority section is omitted from the URI)
-** then the path is interpreted as a relative path. 
-** ^(On windows, the first component of an absolute path 
+** then the path is interpreted as a relative path.
+** ^(On windows, the first component of an absolute path
 ** is a drive specification (e.g. "C:").)^
 **
 ** [[core URI query parameters]]
@@ -3345,13 +3426,13 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **
 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
 **     "rwc", or "memory". Attempting to set it to any other value is
-**     an error)^. 
-**     ^If "ro" is specified, then the database is opened for read-only 
-**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
-**     third argument to sqlite3_open_v2(). ^If the mode option is set to 
-**     "rw", then the database is opened for read-write (but not create) 
-**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
-**     been set. ^Value "rwc" is equivalent to setting both 
+**     an error)^.
+**     ^If "ro" is specified, then the database is opened for read-only
+**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
+**     third argument to sqlite3_open_v2(). ^If the mode option is set to
+**     "rw", then the database is opened for read-write (but not create)
+**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
+**     been set. ^Value "rwc" is equivalent to setting both
 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
 **     set to "memory" then a pure [in-memory database] that never reads
 **     or writes from disk is used. ^It is an error to specify a value for
@@ -3361,7 +3442,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
 **     "private". ^Setting it to "shared" is equivalent to setting the
 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
-**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
+**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
 **     a URI filename, its value overrides any behavior requested by setting
@@ -3387,7 +3468,7 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **     property on a database file that does in fact change can result
 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
 **     See also: [SQLITE_IOCAP_IMMUTABLE].
-**       
+**
 ** </ul>
 **
 ** ^Specifying an unknown parameter in the query component of a URI is not an
@@ -3399,36 +3480,36 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 **
 ** <table border="1" align=center cellpadding=5>
 ** <tr><th> URI filenames <th> Results
-** <tr><td> file:data.db <td> 
+** <tr><td> file:data.db <td>
 **          Open the file "data.db" in the current directory.
 ** <tr><td> file:/home/fred/data.db<br>
-**          file:///home/fred/data.db <br> 
-**          file://localhost/home/fred/data.db <br> <td> 
+**          file:///home/fred/data.db <br>
+**          file://localhost/home/fred/data.db <br> <td>
 **          Open the database file "/home/fred/data.db".
-** <tr><td> file://darkstar/home/fred/data.db <td> 
+** <tr><td> file://darkstar/home/fred/data.db <td>
 **          An error. "darkstar" is not a recognized authority.
-** <tr><td style="white-space:nowrap"> 
+** <tr><td style="white-space:nowrap">
 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
-**          C:. Note that the %20 escaping in this example is not strictly 
+**          C:. Note that the %20 escaping in this example is not strictly
 **          necessary - space characters can be used literally
 **          in URI filenames.
-** <tr><td> file:data.db?mode=ro&cache=private <td> 
+** <tr><td> file:data.db?mode=ro&cache=private <td>
 **          Open file "data.db" in the current directory for read-only access.
 **          Regardless of whether or not shared-cache mode is enabled by
 **          default, use a private cache.
 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
 **          that uses dot-files in place of posix advisory locking.
-** <tr><td> file:data.db?mode=readonly <td> 
+** <tr><td> file:data.db?mode=readonly <td>
 **          An error. "readonly" is not a valid option for the "mode" parameter.
 ** </table>
 **
 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
 ** query components of a URI. A hexadecimal escape sequence consists of a
-** percent sign - "%" - followed by exactly two hexadecimal digits 
+** percent sign - "%" - followed by exactly two hexadecimal digits
 ** specifying an octet value. ^Before the path or query components of a
-** URI filename are interpreted, they are encoded using UTF-8 and all 
+** URI filename are interpreted, they are encoded using UTF-8 and all
 ** hexadecimal escape sequences replaced by a single byte containing the
 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
 ** the results are undefined.
@@ -3463,17 +3544,27 @@ SQLITE_API int sqlite3_open_v2(
 /*
 ** CAPI3REF: Obtain Values For URI Parameters
 **
-** These are utility routines, useful to VFS implementations, that check
-** to see if a database file was a URI that contained a specific query 
+** These are utility routines, useful to [VFS|custom VFS implementations],
+** that check if a database file was a URI that contained a specific query
 ** parameter, and if so obtains the value of that query parameter.
 **
-** If F is the database filename pointer passed into the xOpen() method of 
-** a VFS implementation when the flags parameter to xOpen() has one or 
-** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
-** P is the name of the query parameter, then
+** The first parameter to these interfaces (hereafter referred to
+** as F) must be one of:
+** <ul>
+** <li> A database filename pointer created by the SQLite core and
+** passed into the xOpen() method of a VFS implemention, or
+** <li> A filename obtained from [sqlite3_db_filename()], or
+** <li> A new filename constructed using [sqlite3_create_filename()].
+** </ul>
+** If the F parameter is not one of the above, then the behavior is
+** undefined and probably undesirable.  Older versions of SQLite were
+** more tolerant of invalid F parameters than newer versions.
+**
+** If F is a suitable filename (as described in the previous paragraph)
+** and if P is the name of the query parameter, then
 ** sqlite3_uri_parameter(F,P) returns the value of the P
-** parameter if it exists or a NULL pointer if P does not appear as a 
-** query parameter on F.  If P is a query parameter of F
+** parameter if it exists or a NULL pointer if P does not appear as a
+** query parameter on F.  If P is a query parameter of F and it
 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
 ** a pointer to an empty string.
 **
@@ -3481,41 +3572,160 @@ SQLITE_API int sqlite3_open_v2(
 ** parameter and returns true (1) or false (0) according to the value
 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
 ** value of query parameter P is one of "yes", "true", or "on" in any
-** case or if the value begins with a non-zero number.  The 
+** case or if the value begins with a non-zero number.  The
 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
 ** query parameter P is one of "no", "false", or "off" in any case or
 ** if the value begins with a numeric zero.  If P is not a query
-** parameter on F or if the value of P is does not match any of the
+** parameter on F or if the value of P does not match any of the
 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
 **
 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
 ** 64-bit signed integer and returns that integer, or D if P does not
 ** exist.  If the value of P is something other than an integer, then
 ** zero is returned.
-** 
+**
+** The sqlite3_uri_key(F,N) returns a pointer to the name (not
+** the value) of the N-th query parameter for filename F, or a NULL
+** pointer if N is less than zero or greater than the number of query
+** parameters minus 1.  The N value is zero-based so N should be 0 to obtain
+** the name of the first query parameter, 1 for the second parameter, and
+** so forth.
+**
 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
-** is not a database file pathname pointer that SQLite passed into the xOpen
-** VFS method, then the behavior of this routine is undefined and probably
-** undesirable.
+** is not a database file pathname pointer that the SQLite core passed
+** into the xOpen VFS method, then the behavior of this routine is undefined
+** and probably undesirable.
+**
+** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
+** parameter can also be the name of a rollback journal file or WAL file
+** in addition to the main database file.  Prior to version 3.31.0, these
+** routines would only work if F was the name of the main database file.
+** When the F parameter is the name of the rollback journal or WAL file,
+** it has access to all the same query parameters as were found on the
+** main database file.
 **
 ** See the [URI filename] documentation for additional information.
 */
 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
+SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
 
+/*
+** CAPI3REF:  Translate filenames
+**
+** These routines are available to [VFS|custom VFS implementations] for
+** translating filenames between the main database file, the journal file,
+** and the WAL file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
+** returns the name of the corresponding database file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** passed by the SQLite core into the VFS, or if F is a database filename
+** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
+** returns the name of the corresponding rollback journal file.
+**
+** If F is the name of an sqlite database file, journal file, or WAL file
+** that was passed by the SQLite core into the VFS, or if F is a database
+** filename obtained from [sqlite3_db_filename()], then
+** sqlite3_filename_wal(F) returns the name of the corresponding
+** WAL file.
+**
+** In all of the above, if F is not the name of a database, journal or WAL
+** filename passed into the VFS from the SQLite core and F is not the
+** return value from [sqlite3_db_filename()], then the result is
+** undefined and is likely a memory access violation.
+*/
+SQLITE_API const char *sqlite3_filename_database(const char*);
+SQLITE_API const char *sqlite3_filename_journal(const char*);
+SQLITE_API const char *sqlite3_filename_wal(const char*);
+
+/*
+** CAPI3REF:  Database File Corresponding To A Journal
+**
+** ^If X is the name of a rollback or WAL-mode journal file that is
+** passed into the xOpen method of [sqlite3_vfs], then
+** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
+** object that represents the main database file.
+**
+** This routine is intended for use in custom [VFS] implementations
+** only.  It is not a general-purpose interface.
+** The argument sqlite3_file_object(X) must be a filename pointer that
+** has been passed into [sqlite3_vfs].xOpen method where the
+** flags parameter to xOpen contains one of the bits
+** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL].  Any other use
+** of this routine results in undefined and probably undesirable
+** behavior.
+*/
+SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
+
+/*
+** CAPI3REF: Create and Destroy VFS Filenames
+**
+** These interfces are provided for use by [VFS shim] implementations and
+** are not useful outside of that context.
+**
+** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
+** database filename D with corresponding journal file J and WAL file W and
+** with N URI parameters key/values pairs in the array P.  The result from
+** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
+** is safe to pass to routines like:
+** <ul>
+** <li> [sqlite3_uri_parameter()],
+** <li> [sqlite3_uri_boolean()],
+** <li> [sqlite3_uri_int64()],
+** <li> [sqlite3_uri_key()],
+** <li> [sqlite3_filename_database()],
+** <li> [sqlite3_filename_journal()], or
+** <li> [sqlite3_filename_wal()].
+** </ul>
+** If a memory allocation error occurs, sqlite3_create_filename() might
+** return a NULL pointer.  The memory obtained from sqlite3_create_filename(X)
+** must be released by a corresponding call to sqlite3_free_filename(Y).
+**
+** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
+** of 2*N pointers to strings.  Each pair of pointers in this array corresponds
+** to a key and value for a query parameter.  The P parameter may be a NULL
+** pointer if N is zero.  None of the 2*N pointers in the P array may be
+** NULL pointers and key pointers should not be empty strings.
+** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
+** be NULL pointers, though they can be empty strings.
+**
+** The sqlite3_free_filename(Y) routine releases a memory allocation
+** previously obtained from sqlite3_create_filename().  Invoking
+** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
+**
+** If the Y parameter to sqlite3_free_filename(Y) is anything other
+** than a NULL pointer or a pointer previously acquired from
+** sqlite3_create_filename(), then bad things such as heap
+** corruption or segfaults may occur. The value Y should not be
+** used again after sqlite3_free_filename(Y) has been called.  This means
+** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
+** then the corresponding [sqlite3_module.xClose() method should also be
+** invoked prior to calling sqlite3_free_filename(Y).
+*/
+SQLITE_API char *sqlite3_create_filename(
+  const char *zDatabase,
+  const char *zJournal,
+  const char *zWal,
+  int nParam,
+  const char **azParam
+);
+SQLITE_API void sqlite3_free_filename(char*);
 
 /*
 ** CAPI3REF: Error Codes And Messages
 ** METHOD: sqlite3
 **
-** ^If the most recent sqlite3_* API call associated with 
+** ^If the most recent sqlite3_* API call associated with
 ** [database connection] D failed, then the sqlite3_errcode(D) interface
 ** returns the numeric [result code] or [extended result code] for that
 ** API call.
 ** ^The sqlite3_extended_errcode()
-** interface is the same except that it always returns the 
+** interface is the same except that it always returns the
 ** [extended result code] even when extended result codes are
 ** disabled.
 **
@@ -3572,7 +3782,7 @@ SQLITE_API const char *sqlite3_errstr(int);
 ** has been compiled into binary form and is ready to be evaluated.
 **
 ** Think of each SQL statement as a separate computer program.  The
-** original SQL text is source code.  A prepared statement object 
+** original SQL text is source code.  A prepared statement object
 ** is the compiled object code.  All SQL must be converted into a
 ** prepared statement before it can be run.
 **
@@ -3602,7 +3812,7 @@ typedef struct sqlite3_stmt sqlite3_stmt;
 ** new limit for that construct.)^
 **
 ** ^If the new limit is a negative number, the limit is unchanged.
-** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
+** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
 ** [limits | hard upper bound]
 ** set at compile-time by a C preprocessor macro called
 ** [limits | SQLITE_MAX_<i>NAME</i>].
@@ -3610,7 +3820,7 @@ typedef struct sqlite3_stmt sqlite3_stmt;
 ** ^Attempts to increase a limit above its hard upper bound are
 ** silently truncated to the hard upper bound.
 **
-** ^Regardless of whether or not the limit was changed, the 
+** ^Regardless of whether or not the limit was changed, the
 ** [sqlite3_limit()] interface returns the prior value of the limit.
 ** ^Hence, to find the current value of a limit without changing it,
 ** simply invoke this interface with the third parameter set to -1.
@@ -3715,7 +3925,7 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
 ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
 ** that the prepared statement will be retained for a long time and
 ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
-** and [sqlite3_prepare16_v3()] assume that the prepared statement will 
+** and [sqlite3_prepare16_v3()] assume that the prepared statement will
 ** be used just once or at most a few times and then destroyed using
 ** [sqlite3_finalize()] relatively soon. The current implementation acts
 ** on this hint by avoiding the use of [lookaside memory] so as not to
@@ -3822,12 +4032,12 @@ SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
 ** </li>
 **
 ** <li>
-** ^If the specific value bound to [parameter | host parameter] in the 
+** ^If the specific value bound to a [parameter | host parameter] in the
 ** WHERE clause might influence the choice of query plan for a statement,
-** then the statement will be automatically recompiled, as if there had been 
-** a schema change, on the first  [sqlite3_step()] call following any change
-** to the [sqlite3_bind_text | bindings] of that [parameter]. 
-** ^The specific value of WHERE-clause [parameter] might influence the 
+** then the statement will be automatically recompiled, as if there had been
+** a schema change, on the first [sqlite3_step()] call following any change
+** to the [sqlite3_bind_text | bindings] of that [parameter].
+** ^The specific value of a WHERE-clause [parameter] might influence the
 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
 ** or [GLOB] operator or if the parameter is compared to an indexed column
 ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
@@ -3936,8 +4146,8 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** the content of the database file.
 **
 ** Note that [application-defined SQL functions] or
-** [virtual tables] might change the database indirectly as a side effect.  
-** ^(For example, if an application defines a function "eval()" that 
+** [virtual tables] might change the database indirectly as a side effect.
+** ^(For example, if an application defines a function "eval()" that
 ** calls [sqlite3_exec()], then the following SQL statement would
 ** change the database file through side-effects:
 **
@@ -3951,10 +4161,10 @@ SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
 ** since the statements themselves do not actually modify the database but
-** rather they control the timing of when other statements modify the 
+** rather they control the timing of when other statements modify the
 ** database.  ^The [ATTACH] and [DETACH] statements also cause
 ** sqlite3_stmt_readonly() to return true since, while those statements
-** change the configuration of a database connection, they do not make 
+** change the configuration of a database connection, they do not make
 ** changes to the content of the database files on disk.
 ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
 ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
@@ -3980,18 +4190,18 @@ SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
 ** METHOD: sqlite3_stmt
 **
 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
-** [prepared statement] S has been stepped at least once using 
+** [prepared statement] S has been stepped at least once using
 ** [sqlite3_step(S)] but has neither run to completion (returned
 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
-** interface returns false if S is a NULL pointer.  If S is not a 
+** interface returns false if S is a NULL pointer.  If S is not a
 ** NULL pointer and is not a pointer to a valid [prepared statement]
 ** object, then the behavior is undefined and probably undesirable.
 **
 ** This interface can be used in combination [sqlite3_next_stmt()]
-** to locate all prepared statements associated with a database 
+** to locate all prepared statements associated with a database
 ** connection that are in need of being reset.  This can be used,
-** for example, in diagnostic routines to search for prepared 
+** for example, in diagnostic routines to search for prepared
 ** statements that are holding a transaction open.
 */
 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
@@ -4010,7 +4220,7 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 ** will accept either a protected or an unprotected sqlite3_value.
 ** Every interface that accepts sqlite3_value arguments specifies
 ** whether or not it requires a protected sqlite3_value.  The
-** [sqlite3_value_dup()] interface can be used to construct a new 
+** [sqlite3_value_dup()] interface can be used to construct a new
 ** protected sqlite3_value from an unprotected sqlite3_value.
 **
 ** The terms "protected" and "unprotected" refer to whether or not
@@ -4018,7 +4228,7 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 ** sqlite3_value object but no mutex is held for an unprotected
 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
-** or if SQLite is run in one of reduced mutex modes 
+** or if SQLite is run in one of reduced mutex modes
 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
 ** then there is no distinction between protected and unprotected
 ** sqlite3_value objects and they can be used interchangeably.  However,
@@ -4087,12 +4297,30 @@ typedef struct sqlite3_context sqlite3_context;
 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
 ** for "?NNN" parameters is the value of NNN.
 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
-** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
+** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
 **
 ** ^The third argument is the value to bind to the parameter.
 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
 ** is ignored and the end result is the same as sqlite3_bind_null().
+** ^If the third parameter to sqlite3_bind_text() is not NULL, then
+** it should be a pointer to well-formed UTF8 text.
+** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
+** it should be a pointer to well-formed UTF16 text.
+** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
+** it should be a pointer to a well-formed unicode string that is
+** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
+** otherwise.
+**
+** [[byte-order determination rules]] ^The byte-order of
+** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
+** found in first character, which is removed, or in the absence of a BOM
+** the byte order is the native byte order of the host
+** machine for sqlite3_bind_text16() or the byte order specified in
+** the 6th parameter for sqlite3_bind_text64().)^
+** ^If UTF16 input text contains invalid unicode
+** characters, then SQLite might change those invalid characters
+** into the unicode replacement character: U+FFFD.
 **
 ** ^(In those routines that have a fourth argument, its value is the
 ** number of bytes in the parameter.  To be clear: the value is the
@@ -4106,7 +4334,7 @@ typedef struct sqlite3_context sqlite3_context;
 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
 ** that parameter must be the byte offset
 ** where the NUL terminator would occur assuming the string were NUL
-** terminated.  If any NUL characters occur at byte offsets less than 
+** terminated.  If any NUL characters occurs at byte offsets less than
 ** the value of the fourth parameter then the resulting string value will
 ** contain embedded NULs.  The result of expressions involving strings
 ** with embedded NULs is undefined.
@@ -4268,7 +4496,7 @@ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
 ** METHOD: sqlite3_stmt
 **
 ** ^Return the number of columns in the result set returned by the
-** [prepared statement]. ^If this routine returns 0, that means the 
+** [prepared statement]. ^If this routine returns 0, that means the
 ** [prepared statement] returns no data (for example an [UPDATE]).
 ** ^However, just because this routine returns a positive number does not
 ** mean that one or more rows of data will be returned.  ^A SELECT statement
@@ -4336,7 +4564,7 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
 **
 ** ^If the Nth column returned by the statement is an expression or
 ** subquery and is not a column value, then all of these functions return
-** NULL.  ^These routine might also return NULL if a memory allocation error
+** NULL.  ^These routines might also return NULL if a memory allocation error
 ** occurs.  ^Otherwise, they return the name of the attached database, table,
 ** or column that query result column was extracted from.
 **
@@ -4346,10 +4574,6 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
 ** ^These APIs are only available if the library was compiled with the
 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
 **
-** If two or more threads call one or more of these routines against the same
-** prepared statement and column at the same time then the results are
-** undefined.
-**
 ** If two or more threads call one or more
 ** [sqlite3_column_database_name | column metadata interfaces]
 ** for the same [prepared statement] and result column
@@ -4454,7 +4678,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
 ** For all versions of SQLite up to and including 3.6.23.1, a call to
 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
 ** other than [SQLITE_ROW] before any subsequent invocation of
-** sqlite3_step().  Failure to reset the prepared statement using 
+** sqlite3_step().  Failure to reset the prepared statement using
 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
 ** sqlite3_step().  But after [version 3.6.23.1] ([dateof:3.6.23.1],
 ** sqlite3_step() began
@@ -4486,7 +4710,7 @@ SQLITE_API int sqlite3_step(sqlite3_stmt*);
 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
 ** current row of the result set of [prepared statement] P.
 ** ^If prepared statement P does not have results ready to return
-** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
+** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
 ** interfaces) then sqlite3_data_count(P) returns 0.
 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
@@ -4545,7 +4769,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
 ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
 ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
-** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an 
+** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
 ** [sqlite3_value|unprotected sqlite3_value] object.
 ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
 ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
@@ -4593,7 +4817,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** The return value of sqlite3_column_type() can be used to decide which
 ** of the first six interface should be used to extract the column value.
 ** The value returned by sqlite3_column_type() is only meaningful if no
-** automatic type conversions have occurred for the value in question.  
+** automatic type conversions have occurred for the value in question.
 ** After a type conversion, the result of calling sqlite3_column_type()
 ** is undefined, though harmless.  Future
 ** versions of SQLite may change the behavior of sqlite3_column_type()
@@ -4621,7 +4845,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** the number of bytes in that string.
 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
 **
-** ^The values returned by [sqlite3_column_bytes()] and 
+** ^The values returned by [sqlite3_column_bytes()] and
 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
 ** of the string.  ^For clarity: the values returned by
 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
@@ -4640,7 +4864,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
 ** Hence, the sqlite3_column_value() interface
-** is normally only useful within the implementation of 
+** is normally only useful within the implementation of
 ** [application-defined SQL functions] or [virtual tables], not within
 ** top-level application code.
 **
@@ -4810,15 +5034,13 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 /*
 ** CAPI3REF: Create Or Redefine SQL Functions
 ** KEYWORDS: {function creation routines}
-** KEYWORDS: {application-defined SQL function}
-** KEYWORDS: {application-defined SQL functions}
 ** METHOD: sqlite3
 **
 ** ^These functions (collectively known as "function creation routines")
 ** are used to add SQL functions or aggregates or to redefine the behavior
 ** of existing SQL functions or aggregates. The only differences between
-** the three "sqlite3_create_function*" routines are the text encoding 
-** expected for the second parameter (the name of the function being 
+** the three "sqlite3_create_function*" routines are the text encoding
+** expected for the second parameter (the name of the function being
 ** created) and the presence or absence of a destructor callback for
 ** the application data pointer. Function sqlite3_create_window_function()
 ** is similar, but allows the user to supply the extra callback functions
@@ -4832,7 +5054,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** ^The second parameter is the name of the SQL function to be created or
 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
 ** representation, exclusive of the zero-terminator.  ^Note that the name
-** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
+** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
 ** ^Any attempt to create a function with a longer name
 ** will result in [SQLITE_MISUSE] being returned.
 **
@@ -4847,7 +5069,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** ^The fourth parameter, eTextRep, specifies what
 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
 ** its parameters.  The application should set this parameter to
-** [SQLITE_UTF16LE] if the function implementation invokes 
+** [SQLITE_UTF16LE] if the function implementation invokes
 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
 ** implementation invokes [sqlite3_value_text16be()] on an input, or
 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
@@ -4867,9 +5089,20 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 **
 ** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
 ** flag, which if present prevents the function from being invoked from
-** within VIEWs or TRIGGERs.  For security reasons, the [SQLITE_DIRECTONLY]
-** flag is recommended for any application-defined SQL function that has
-** side-effects.
+** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
+** index expressions, or the WHERE clause of partial indexes.
+**
+** <span style="background-color:#ffff90;">
+** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
+** all application-defined SQL functions that do not need to be
+** used inside of triggers, view, CHECK constraints, or other elements of
+** the database schema.  This flags is especially recommended for SQL
+** functions that have side effects or reveal internal application state.
+** Without this flag, an attacker might be able to modify the schema of
+** a database file to include invocations of the function with parameters
+** chosen by the attacker, which the application will then execute when
+** the database file is opened and read.
+** </span>
 **
 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
 ** function can gain access to this pointer using [sqlite3_user_data()].)^
@@ -4884,21 +5117,21 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** SQL function or aggregate, pass NULL pointers for all three function
 ** callbacks.
 **
-** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue 
+** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
 ** and xInverse) passed to sqlite3_create_window_function are pointers to
 ** C-language callbacks that implement the new function. xStep and xFinal
 ** must both be non-NULL. xValue and xInverse may either both be NULL, in
-** which case a regular aggregate function is created, or must both be 
+** which case a regular aggregate function is created, or must both be
 ** non-NULL, in which case the new function may be used as either an aggregate
 ** or aggregate window function. More details regarding the implementation
-** of aggregate window functions are 
+** of aggregate window functions are
 ** [user-defined window functions|available here].
 **
 ** ^(If the final parameter to sqlite3_create_function_v2() or
 ** sqlite3_create_window_function() is not NULL, then it is destructor for
-** the application data pointer. The destructor is invoked when the function 
-** is deleted, either by being overloaded or when the database connection 
-** closes.)^ ^The destructor is also invoked if the call to 
+** the application data pointer. The destructor is invoked when the function
+** is deleted, either by being overloaded or when the database connection
+** closes.)^ ^The destructor is also invoked if the call to
 ** sqlite3_create_function_v2() fails.  ^When the destructor callback is
 ** invoked, it is passed a single argument which is a copy of the application
 ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
@@ -4911,7 +5144,7 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 ** nArg parameter is a better match than a function implementation with
 ** a negative nArg.  ^A function where the preferred text encoding
 ** matches the database encoding is a better
-** match than a function where the encoding is different.  
+** match than a function where the encoding is different.
 ** ^A function where the encoding difference is between UTF16le and UTF16be
 ** is a closer match than a function where the encoding difference is
 ** between UTF8 and UTF16.
@@ -4985,23 +5218,58 @@ SQLITE_API int sqlite3_create_window_function(
 /*
 ** CAPI3REF: Function Flags
 **
-** These constants may be ORed together with the 
+** These constants may be ORed together with the
 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
 ** [sqlite3_create_function_v2()].
 **
-** The SQLITE_DETERMINISTIC flag means that the new function will always
-** maps the same inputs into the same output.  The abs() function is
-** deterministic, for example, but randomblob() is not.
+** <dl>
+** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
+** The SQLITE_DETERMINISTIC flag means that the new function always gives
+** the same output when the input parameters are the same.
+** The [abs|abs() function] is deterministic, for example, but
+** [randomblob|randomblob()] is not.  Functions must
+** be deterministic in order to be used in certain contexts such as
+** with the WHERE clause of [partial indexes] or in [generated columns].
+** SQLite might also optimize deterministic functions by factoring them
+** out of inner loops.
+** </dd>
 **
+** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
 ** The SQLITE_DIRECTONLY flag means that the function may only be invoked
-** from top-level SQL, and cannot be used in VIEWs or TRIGGERs.  This is
-** a security feature which is recommended for all 
-** [application-defined SQL functions] that have side-effects.  This flag 
-** prevents an attacker from adding triggers and views to a schema then 
-** tricking a high-privilege application into causing unintended side-effects
-** while performing ordinary queries.
+** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], or [generated columns].
+** The SQLITE_DIRECTONLY flags is a security feature which is recommended
+** for all [application-defined SQL functions], and especially for functions
+** that have side-effects or that could potentially leak sensitive
+** information.
+** </dd>
 **
+** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
+** The SQLITE_INNOCUOUS flag means that the function is unlikely
+** to cause problems even if misused.  An innocuous function should have
+** no side effects and should not depend on any values other than its
+** input parameters. The [abs|abs() function] is an example of an
+** innocuous function.
+** The [load_extension() SQL function] is not innocuous because of its
+** side effects.
+** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
+** exactly the same.  The [random|random() function] is an example of a
+** function that is innocuous but not deterministic.
+** <p>Some heightened security settings
+** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
+** disable the use of SQL functions inside views and triggers and in
+** schema structures such as [CHECK constraints], [DEFAULT clauses],
+** [expression indexes], [partial indexes], and [generated columns] unless
+** the function is tagged with SQLITE_INNOCUOUS.  Most built-in functions
+** are innocuous.  Developers are advised to avoid using the
+** SQLITE_INNOCUOUS flag for application-defined functions unless the
+** function has been carefully audited and found to be free of potentially
+** security-adverse side-effects and information-leaks.
+** </dd>
+**
+** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
 ** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
 ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
 ** Specifying this flag makes no difference for scalar or aggregate user
@@ -5009,17 +5277,20 @@ SQLITE_API int sqlite3_create_window_function(
 ** function, then any sub-types belonging to arguments passed to the window
 ** function may be discarded before the window function is called (i.e.
 ** sqlite3_value_subtype() will always return 0).
+** </dd>
+** </dl>
 */
 #define SQLITE_DETERMINISTIC    0x000000800
 #define SQLITE_DIRECTONLY       0x000080000
 #define SQLITE_SUBTYPE          0x000100000
+#define SQLITE_INNOCUOUS        0x000200000
 
 /*
 ** CAPI3REF: Deprecated Functions
 ** DEPRECATED
 **
 ** These functions are [deprecated].  In order to maintain
-** backwards compatibility with older code, these functions continue 
+** backwards compatibility with older code, these functions continue
 ** to be supported.  However, new applications should avoid
 ** the use of these functions.  To encourage programmers to avoid
 ** these functions, we will not explain what they do.
@@ -5071,8 +5342,8 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 **
 ** These routines extract type, size, and content information from
 ** [protected sqlite3_value] objects.  Protected sqlite3_value objects
-** are used to pass parameter information into implementation of
-** [application-defined SQL functions] and [virtual tables].
+** are used to pass parameter information into the functions that
+** implement [application-defined SQL functions] and [virtual tables].
 **
 ** These routines work only with [protected sqlite3_value] objects.
 ** Any attempt to use these routines on an [unprotected sqlite3_value]
@@ -5087,11 +5358,11 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
 ** extract UTF-16 strings as big-endian and little-endian respectively.
 **
-** ^If [sqlite3_value] object V was initialized 
+** ^If [sqlite3_value] object V was initialized
 ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
 ** and if X and Y are strings that compare equal according to strcmp(X,Y),
 ** then sqlite3_value_pointer(V,Y) will return the pointer P.  ^Otherwise,
-** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer() 
+** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
 ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
 **
 ** ^(The sqlite3_value_type(V) interface returns the
@@ -5129,7 +5400,7 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6
 ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
 ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
 ** interfaces.  ^If X comes from an SQL literal value, or a table column,
-** and expression, then sqlite3_value_frombind(X) returns zero.
+** or an expression, then sqlite3_value_frombind(X) returns zero.
 **
 ** Please pay particular attention to the fact that the pointer returned
 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
@@ -5214,9 +5485,9 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);
 ** Implementations of aggregate SQL functions use this
 ** routine to allocate memory for storing their state.
 **
-** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
-** for a particular aggregate function, SQLite
-** allocates N of memory, zeroes out that memory, and returns a pointer
+** ^The first time the sqlite3_aggregate_context(C,N) routine is called
+** for a particular aggregate function, SQLite allocates
+** N bytes of memory, zeroes out that memory, and returns a pointer
 ** to the new memory. ^On second and subsequent calls to
 ** sqlite3_aggregate_context() for the same aggregate function instance,
 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
@@ -5227,19 +5498,19 @@ SQLITE_API void sqlite3_value_free(sqlite3_value*);
 ** In those cases, sqlite3_aggregate_context() might be called for the
 ** first time from within xFinal().)^
 **
-** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
+** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
 ** when first called if N is less than or equal to zero or if a memory
 ** allocate error occurs.
 **
 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
 ** determined by the N parameter on first successful call.  Changing the
-** value of N in subsequent call to sqlite3_aggregate_context() within
+** value of N in any subsequent call to sqlite3_aggregate_context() within
 ** the same aggregate function instance will not resize the memory
 ** allocation.)^  Within the xFinal callback, it is customary to set
-** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
+** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
 ** pointless memory allocations occur.
 **
-** ^SQLite automatically frees the memory allocated by 
+** ^SQLite automatically frees the memory allocated by
 ** sqlite3_aggregate_context() when the aggregate query concludes.
 **
 ** The first parameter must be a copy of the
@@ -5289,7 +5560,7 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
 ** some circumstances the associated metadata may be preserved.  An example
 ** of where this might be useful is in a regular-expression matching
 ** function. The compiled version of the regular expression can be stored as
-** metadata associated with the pattern string.  
+** metadata associated with the pattern string.
 ** Then as long as the pattern string remains the same,
 ** the compiled regular expression can be reused on multiple
 ** invocations of the same function.
@@ -5315,10 +5586,10 @@ SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
 **      SQL statement)^, or
 ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
 **       parameter)^, or
-** <li> ^(during the original sqlite3_set_auxdata() call when a memory 
+** <li> ^(during the original sqlite3_set_auxdata() call when a memory
 **      allocation error occurs.)^ </ul>
 **
-** Note the last bullet in particular.  The destructor X in 
+** Note the last bullet in particular.  The destructor X in
 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
 ** should be called near the end of the function implementation and the
@@ -5390,8 +5661,9 @@ typedef void (*sqlite3_destructor_type)(void*);
 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
 ** as the text of an error message.  ^SQLite interprets the error
 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
-** interprets the string from sqlite3_result_error16() as UTF-16 in native
-** byte order.  ^If the third parameter to sqlite3_result_error()
+** interprets the string from sqlite3_result_error16() as UTF-16 using
+** the same [byte-order determination rules] as [sqlite3_bind_text16()].
+** ^If the third parameter to sqlite3_result_error()
 ** or sqlite3_result_error16() is negative then SQLite takes as the error
 ** message all text up through the first zero character.
 ** ^If the third parameter to sqlite3_result_error() or
@@ -5459,6 +5731,25 @@ typedef void (*sqlite3_destructor_type)(void*);
 ** then SQLite makes a copy of the result into space obtained
 ** from [sqlite3_malloc()] before it returns.
 **
+** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
+** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
+** when the encoding is not UTF8, if the input UTF16 begins with a
+** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
+** string and the rest of the string is interpreted according to the
+** byte-order specified by the BOM.  ^The byte-order specified by
+** the BOM at the beginning of the text overrides the byte-order
+** specified by the interface procedure.  ^So, for example, if
+** sqlite3_result_text16le() is invoked with text that begins
+** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
+** first two bytes of input are skipped and the remaining input
+** is interpreted as UTF16BE text.
+**
+** ^For UTF16 input text to the sqlite3_result_text16(),
+** sqlite3_result_text16be(), sqlite3_result_text16le(), and
+** sqlite3_result_text64() routines, if the text contains invalid
+** UTF16 characters, the invalid characters might be converted
+** into the unicode replacement character, U+FFFD.
+**
 ** ^The sqlite3_result_value() interface sets the result of
 ** the application-defined function to be a copy of the
 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
@@ -5471,7 +5762,7 @@ typedef void (*sqlite3_destructor_type)(void*);
 **
 ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
 ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
-** also associates the host-language pointer P or type T with that 
+** also associates the host-language pointer P or type T with that
 ** NULL value such that the pointer can be retrieved within an
 ** [application-defined SQL function] using [sqlite3_value_pointer()].
 ** ^If the D parameter is not NULL, then it is a pointer to a destructor
@@ -5524,8 +5815,8 @@ SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
 ** METHOD: sqlite3_context
 **
 ** The sqlite3_result_subtype(C,T) function causes the subtype of
-** the result from the [application-defined SQL function] with 
-** [sqlite3_context] C to be the value T.  Only the lower 8 bits 
+** the result from the [application-defined SQL function] with
+** [sqlite3_context] C to be the value T.  Only the lower 8 bits
 ** of the subtype T are preserved in current versions of SQLite;
 ** higher order bits are discarded.
 ** The number of subtype bytes preserved by SQLite might increase
@@ -5555,7 +5846,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** <li> [SQLITE_UTF16_ALIGNED].
 ** </ul>)^
 ** ^The eTextRep argument determines the encoding of strings passed
-** to the collating function callback, xCallback.
+** to the collating function callback, xCompare.
 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
 ** force strings to be UTF16 with native byte order.
 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
@@ -5564,18 +5855,19 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** ^The fourth argument, pArg, is an application data pointer that is passed
 ** through as the first argument to the collating function callback.
 **
-** ^The fifth argument, xCallback, is a pointer to the collating function.
+** ^The fifth argument, xCompare, is a pointer to the collating function.
 ** ^Multiple collating functions can be registered using the same name but
 ** with different eTextRep parameters and SQLite will use whichever
 ** function requires the least amount of data transformation.
-** ^If the xCallback argument is NULL then the collating function is
+** ^If the xCompare argument is NULL then the collating function is
 ** deleted.  ^When all collating functions having the same name are deleted,
 ** that collation is no longer usable.
 **
-** ^The collating function callback is invoked with a copy of the pArg 
+** ^The collating function callback is invoked with a copy of the pArg
 ** application data pointer and with two strings in the encoding specified
-** by the eTextRep argument.  The collating function must return an
-** integer that is negative, zero, or positive
+** by the eTextRep argument.  The two integer parameters to the collating
+** function callback are the length of the two strings, in bytes. The collating
+** function must return an integer that is negative, zero, or positive
 ** if the first string is less than, equal to, or greater than the second,
 ** respectively.  A collating function must always return the same answer
 ** given the same inputs.  If two or more collating functions are registered
@@ -5592,7 +5884,7 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** </ol>
 **
 ** If a collating function fails any of the above constraints and that
-** collating function is  registered and used, then the behavior of SQLite
+** collating function is registered and used, then the behavior of SQLite
 ** is undefined.
 **
 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
@@ -5602,38 +5894,38 @@ SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 ** calls to the collation creation functions or when the
 ** [database connection] is closed using [sqlite3_close()].
 **
-** ^The xDestroy callback is <u>not</u> called if the 
+** ^The xDestroy callback is <u>not</u> called if the
 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
-** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
+** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
 ** check the return code and dispose of the application data pointer
 ** themselves rather than expecting SQLite to deal with it for them.
-** This is different from every other SQLite interface.  The inconsistency 
-** is unfortunate but cannot be changed without breaking backwards 
+** This is different from every other SQLite interface.  The inconsistency
+** is unfortunate but cannot be changed without breaking backwards
 ** compatibility.
 **
 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
 */
 SQLITE_API int sqlite3_create_collation(
-  sqlite3*, 
-  const char *zName, 
-  int eTextRep, 
+  sqlite3*,
+  const char *zName,
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*)
 );
 /* A macro is more efficient than a wrapped call */
 #define sqlite3_create_collation(a,b,c,d,e) sqlite3_create_collation_v2(a,b,c,d,e,0)
 SQLITE_API int sqlite3_create_collation_v2(
-  sqlite3*, 
-  const char *zName, 
-  int eTextRep, 
+  sqlite3*,
+  const char *zName,
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*),
   void(*xDestroy)(void*)
 );
 SQLITE_API int sqlite3_create_collation16(
-  sqlite3*, 
+  sqlite3*,
   const void *zName,
-  int eTextRep, 
+  int eTextRep,
   void *pArg,
   int(*xCompare)(void*,int,const void*,int,const void*)
 );
@@ -5666,64 +5958,19 @@ SQLITE_API int sqlite3_create_collation16(
 ** [sqlite3_create_collation_v2()].
 */
 SQLITE_API int sqlite3_collation_needed(
-  sqlite3*, 
-  void*, 
+  sqlite3*,
+  void*,
   void(*)(void*,sqlite3*,int eTextRep,const char*)
 );
 SQLITE_API int sqlite3_collation_needed16(
-  sqlite3*, 
+  sqlite3*,
   void*,
   void(*)(void*,sqlite3*,int eTextRep,const void*)
 );
 
-#ifdef SQLITE_HAS_CODEC
-/*
-** Specify the key for an encrypted database.  This routine should be
-** called right after sqlite3_open().
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_key(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const void *pKey, int nKey     /* The key */
-);
-SQLITE_API int sqlite3_key_v2(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const char *zDbName,           /* Name of the database */
-  const void *pKey, int nKey     /* The key */
-);
-
-/*
-** Change the key on an open database.  If the current database is not
-** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
-** database is decrypted.
-**
-** The code to implement this API is not available in the public release
-** of SQLite.
-*/
-SQLITE_API int sqlite3_rekey(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const void *pKey, int nKey     /* The new key */
-);
-SQLITE_API int sqlite3_rekey_v2(
-  sqlite3 *db,                   /* Database to be rekeyed */
-  const char *zDbName,           /* Name of the database */
-  const void *pKey, int nKey     /* The new key */
-);
-
-/*
-** Specify the activation key for a SEE database.  Unless 
-** activated, none of the SEE routines will work.
-*/
-SQLITE_API void sqlite3_activate_see(
-  const char *zPassPhrase        /* Activation phrase */
-);
-#endif
-
 #ifdef SQLITE_ENABLE_CEROD
 /*
-** Specify the activation key for a CEROD database.  Unless 
+** Specify the activation key for a CEROD database.  Unless
 ** activated, none of the CEROD routines will work.
 */
 SQLITE_API void sqlite3_activate_cerod(
@@ -5779,7 +6026,7 @@ SQLITE_API int sqlite3_sleep(int);
 ** ^The [temp_store_directory pragma] may modify this variable and cause
 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 ** the [temp_store_directory pragma] always assumes that any string
-** that this variable points to is held in memory obtained from 
+** that this variable points to is held in memory obtained from
 ** [sqlite3_malloc] and the pragma may attempt to free that memory
 ** using [sqlite3_free].
 ** Hence, if this variable is modified directly, either it should be
@@ -5836,7 +6083,7 @@ SQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory;
 ** ^The [data_store_directory pragma] may modify this variable and cause
 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 ** the [data_store_directory pragma] always assumes that any string
-** that this variable points to is held in memory obtained from 
+** that this variable points to is held in memory obtained from
 ** [sqlite3_malloc] and the pragma may attempt to free that memory
 ** using [sqlite3_free].
 ** Hence, if this variable is modified directly, either it should be
@@ -5921,16 +6168,31 @@ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
 ** CAPI3REF: Return The Filename For A Database Connection
 ** METHOD: sqlite3
 **
-** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
-** associated with database N of connection D.  ^The main database file
-** has the name "main".  If there is no attached database N on the database
+** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
+** associated with database N of connection D.
+** ^If there is no attached database N on the database
 ** connection D, or if database N is a temporary or in-memory database, then
 ** this function will return either a NULL pointer or an empty string.
 **
+** ^The string value returned by this routine is owned and managed by
+** the database connection.  ^The value will be valid until the database N
+** is [DETACH]-ed or until the database connection closes.
+**
 ** ^The filename returned by this function is the output of the
 ** xFullPathname method of the [VFS].  ^In other words, the filename
 ** will be an absolute pathname, even if the filename used
 ** to open the database originally was a URI or relative pathname.
+**
+** If the filename pointer returned by this routine is not NULL, then it
+** can be used as the filename input parameter to these routines:
+** <ul>
+** <li> [sqlite3_uri_parameter()]
+** <li> [sqlite3_uri_boolean()]
+** <li> [sqlite3_uri_int64()]
+** <li> [sqlite3_filename_database()]
+** <li> [sqlite3_filename_journal()]
+** <li> [sqlite3_filename_wal()]
+** </ul>
 */
 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
 
@@ -5945,6 +6207,57 @@ SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
 
 /*
+** CAPI3REF: Determine the transaction state of a database
+** METHOD: sqlite3
+**
+** ^The sqlite3_txn_state(D,S) interface returns the current
+** [transaction state] of schema S in database connection D.  ^If S is NULL,
+** then the highest transaction state of any schema on database connection D
+** is returned.  Transaction states are (in order of lowest to highest):
+** <ol>
+** <li value="0"> SQLITE_TXN_NONE
+** <li value="1"> SQLITE_TXN_READ
+** <li value="2"> SQLITE_TXN_WRITE
+** </ol>
+** ^If the S argument to sqlite3_txn_state(D,S) is not the name of
+** a valid schema, then -1 is returned.
+*/
+SQLITE_API int sqlite3_txn_state(sqlite3*,const char *zSchema);
+
+/*
+** CAPI3REF: Allowed return values from [sqlite3_txn_state()]
+** KEYWORDS: {transaction state}
+**
+** These constants define the current transaction state of a database file.
+** ^The [sqlite3_txn_state(D,S)] interface returns one of these
+** constants in order to describe the transaction state of schema S
+** in [database connection] D.
+**
+** <dl>
+** [[SQLITE_TXN_NONE]] <dt>SQLITE_TXN_NONE</dt>
+** <dd>The SQLITE_TXN_NONE state means that no transaction is currently
+** pending.</dd>
+**
+** [[SQLITE_TXN_READ]] <dt>SQLITE_TXN_READ</dt>
+** <dd>The SQLITE_TXN_READ state means that the database is currently
+** in a read transaction.  Content has been read from the database file
+** but nothing in the database file has changed.  The transaction state
+** will advanced to SQLITE_TXN_WRITE if any changes occur and there are
+** no other conflicting concurrent write transactions.  The transaction
+** state will revert to SQLITE_TXN_NONE following a [ROLLBACK] or
+** [COMMIT].</dd>
+**
+** [[SQLITE_TXN_WRITE]] <dt>SQLITE_TXN_WRITE</dt>
+** <dd>The SQLITE_TXN_WRITE state means that the database is currently
+** in a write transaction.  Content has been written to the database file
+** but has not yet committed.  The transaction state will change to
+** to SQLITE_TXN_NONE at the next [ROLLBACK] or [COMMIT].</dd>
+*/
+#define SQLITE_TXN_NONE  0
+#define SQLITE_TXN_READ  1
+#define SQLITE_TXN_WRITE 2
+
+/*
 ** CAPI3REF: Find the next prepared statement
 ** METHOD: sqlite3
 **
@@ -6034,7 +6347,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 ** ^In the case of an update, this is the [rowid] after the update takes place.
 **
 ** ^(The update hook is not invoked when internal system tables are
-** modified (i.e. sqlite_master and sqlite_sequence).)^
+** modified (i.e. sqlite_sequence).)^
 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
 **
 ** ^In the current implementation, the update hook
@@ -6060,7 +6373,7 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 ** and [sqlite3_preupdate_hook()] interfaces.
 */
 SQLITE_API void *sqlite3_update_hook(
-  sqlite3*, 
+  sqlite3*,
   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
   void*
 );
@@ -6074,25 +6387,29 @@ SQLITE_API void *sqlite3_update_hook(
 ** and disabled if the argument is false.)^
 **
 ** ^Cache sharing is enabled and disabled for an entire process.
-** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]). 
+** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
 ** In prior versions of SQLite,
 ** sharing was enabled or disabled for each thread separately.
 **
 ** ^(The cache sharing mode set by this interface effects all subsequent
 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
-** Existing database connections continue use the sharing mode
+** Existing database connections continue to use the sharing mode
 ** that was in effect at the time they were opened.)^
 **
 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
 ** successfully.  An [error code] is returned otherwise.)^
 **
-** ^Shared cache is disabled by default. But this might change in
-** future releases of SQLite.  Applications that care about shared
-** cache setting should set it explicitly.
+** ^Shared cache is disabled by default. It is recommended that it stay
+** that way.  In other words, do not use this routine.  This interface
+** continues to be provided for historical compatibility, but its use is
+** discouraged.  Any use of shared cache is discouraged.  If shared cache
+** must be used, it is recommended that shared cache only be enabled for
+** individual database connections using the [sqlite3_open_v2()] interface
+** with the [SQLITE_OPEN_SHAREDCACHE] flag.
 **
 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
-** and will always return SQLITE_MISUSE. On those systems, 
-** shared cache mode should be enabled per-database connection via 
+** and will always return SQLITE_MISUSE. On those systems,
+** shared cache mode should be enabled per-database connection via
 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
 **
 ** This interface is threadsafe on processors where writing a
@@ -6135,6 +6452,9 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 /*
 ** CAPI3REF: Impose A Limit On Heap Size
 **
+** These interfaces impose limits on the amount of heap memory that will be
+** by all database connections within a single process.
+**
 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
 ** soft limit on the amount of heap memory that may be allocated by SQLite.
 ** ^SQLite strives to keep heap memory utilization below the soft heap
@@ -6142,23 +6462,44 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 ** as heap memory usages approaches the limit.
 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
 ** below the limit, it will exceed the limit rather than generate
-** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
+** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
 ** is advisory only.
 **
-** ^The return value from sqlite3_soft_heap_limit64() is the size of
-** the soft heap limit prior to the call, or negative in the case of an
-** error.  ^If the argument N is negative
-** then no change is made to the soft heap limit.  Hence, the current
-** size of the soft heap limit can be determined by invoking
-** sqlite3_soft_heap_limit64() with a negative argument.
-**
-** ^If the argument N is zero then the soft heap limit is disabled.
+** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
+** N bytes on the amount of memory that will be allocated.  ^The
+** sqlite3_hard_heap_limit64(N) interface is similar to
+** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
+** when the hard heap limit is reached.
 **
-** ^(The soft heap limit is not enforced in the current implementation
+** ^The return value from both sqlite3_soft_heap_limit64() and
+** sqlite3_hard_heap_limit64() is the size of
+** the heap limit prior to the call, or negative in the case of an
+** error.  ^If the argument N is negative
+** then no change is made to the heap limit.  Hence, the current
+** size of heap limits can be determined by invoking
+** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
+**
+** ^Setting the heap limits to zero disables the heap limiter mechanism.
+**
+** ^The soft heap limit may not be greater than the hard heap limit.
+** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
+** is invoked with a value of N that is greater than the hard heap limit,
+** the the soft heap limit is set to the value of the hard heap limit.
+** ^The soft heap limit is automatically enabled whenever the hard heap
+** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
+** the soft heap limit is outside the range of 1..N, then the soft heap
+** limit is set to N.  ^Invoking sqlite3_soft_heap_limit64(0) when the
+** hard heap limit is enabled makes the soft heap limit equal to the
+** hard heap limit.
+**
+** The memory allocation limits can also be adjusted using
+** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
+**
+** ^(The heap limits are not enforced in the current implementation
 ** if one or more of following conditions are true:
 **
 ** <ul>
-** <li> The soft heap limit is set to zero.
+** <li> The limit value is set to zero.
 ** <li> Memory accounting is disabled using a combination of the
 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
@@ -6169,21 +6510,11 @@ SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 **      from the heap.
 ** </ul>)^
 **
-** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]), 
-** the soft heap limit is enforced
-** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
-** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
-** the soft heap limit is enforced on every memory allocation.  Without
-** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
-** when memory is allocated by the page cache.  Testing suggests that because
-** the page cache is the predominate memory user in SQLite, most
-** applications will achieve adequate soft heap limit enforcement without
-** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
-**
-** The circumstances under which SQLite will enforce the soft heap limit may
+** The circumstances under which SQLite will enforce the heap limits may
 ** changes in future releases of SQLite.
 */
 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
+SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
 
 /*
 ** CAPI3REF: Deprecated Soft Heap Limit Interface
@@ -6208,7 +6539,7 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
 ** the final five arguments with appropriate values if the specified
 ** column exists.  ^The sqlite3_table_column_metadata() interface returns
-** SQLITE_ERROR and if the specified column does not exist.
+** SQLITE_ERROR if the specified column does not exist.
 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
 ** NULL pointer, then this routine simply checks for the existence of the
 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
@@ -6248,7 +6579,7 @@ SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
 **
 ** ^If the specified table is actually a view, an [error code] is returned.
 **
-** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
+** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
 ** is not a [WITHOUT ROWID] table and an
 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
 ** parameters are set for the explicitly declared column. ^(If there is no
@@ -6314,7 +6645,7 @@ SQLITE_API int sqlite3_table_column_metadata(
 ** prior to calling this API,
 ** otherwise an error will be returned.
 **
-** <b>Security warning:</b> It is recommended that the 
+** <b>Security warning:</b> It is recommended that the
 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
 ** interface.  The use of the [sqlite3_enable_load_extension()] interface
 ** should be avoided.  This will keep the SQL function [load_extension()]
@@ -6350,7 +6681,7 @@ SQLITE_API int sqlite3_load_extension(
 ** to enable or disable only the C-API.)^
 **
 ** <b>Security warning:</b> It is recommended that extension loading
-** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
+** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
 ** rather than this interface, so the [load_extension()] SQL function
 ** remains disabled. This will prevent SQL injections from giving attackers
 ** access to extension loading capabilities.
@@ -6401,7 +6732,7 @@ SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
 ** initialization routine X that was registered using a prior call to
 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
-** routine returns 1 if initialization routine X was successfully 
+** routine returns 1 if initialization routine X was successfully
 ** unregistered and it returns 0 if X was not on the list of initialization
 ** routines.
 */
@@ -6436,8 +6767,8 @@ typedef struct sqlite3_module sqlite3_module;
 ** CAPI3REF: Virtual Table Object
 ** KEYWORDS: sqlite3_module {virtual table module}
 **
-** This structure, sometimes called a "virtual table module", 
-** defines the implementation of a [virtual tables].  
+** This structure, sometimes called a "virtual table module",
+** defines the implementation of a [virtual table].
 ** This structure consists mostly of methods for the module.
 **
 ** ^A virtual table module is created by filling in a persistent
@@ -6476,7 +6807,7 @@ struct sqlite3_module {
                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
                        void **ppArg);
   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
-  /* The methods above are in version 1 of the sqlite_module object. Those 
+  /* The methods above are in version 1 of the sqlite_module object. Those
   ** below are for version 2 and greater. */
   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
   int (*xRelease)(sqlite3_vtab *pVTab, int);
@@ -6526,7 +6857,7 @@ struct sqlite3_module {
 ** required by SQLite. If the table has at least 64 columns and any column
 ** to the right of the first 63 is required, then bit 63 of colUsed is also
 ** set. In other words, column iCol may be required if the expression
-** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to 
+** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
 ** non-zero.
 **
 ** The [xBestIndex] method must fill aConstraintUsage[] with information
@@ -6534,7 +6865,13 @@ struct sqlite3_module {
 ** the right-hand side of the corresponding aConstraint[] is evaluated
 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
 ** is true, then the constraint is assumed to be fully handled by the
-** virtual table and is not checked again by SQLite.)^
+** virtual table and might not be checked again by the byte code.)^ ^(The
+** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
+** is left in its default setting of false, the constraint will always be
+** checked separately in byte code.  If the omit flag is change to true, then
+** the constraint may or may not be checked in byte code.  In other words,
+** when the omit flag is true there is no guarantee that the constraint will
+** not be checked again using byte code.)^
 **
 ** ^The idxNum and idxPtr values are recorded and passed into the
 ** [xFilter] method.
@@ -6547,17 +6884,17 @@ struct sqlite3_module {
 **
 ** ^The estimatedCost value is an estimate of the cost of a particular
 ** strategy. A cost of N indicates that the cost of the strategy is similar
-** to a linear scan of an SQLite table with N rows. A cost of log(N) 
+** to a linear scan of an SQLite table with N rows. A cost of log(N)
 ** indicates that the expense of the operation is similar to that of a
 ** binary search on a unique indexed field of an SQLite table with N rows.
 **
 ** ^The estimatedRows value is an estimate of the number of rows that
 ** will be returned by the strategy.
 **
-** The xBestIndex method may optionally populate the idxFlags field with a 
+** The xBestIndex method may optionally populate the idxFlags field with a
 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
-** assumes that the strategy may visit at most one row. 
+** assumes that the strategy may visit at most one row.
 **
 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
 ** SQLite also assumes that if a call to the xUpdate() method is made as
@@ -6570,14 +6907,14 @@ struct sqlite3_module {
 ** the xUpdate method are automatically rolled back by SQLite.
 **
 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
-** structure for SQLite [version 3.8.2] ([dateof:3.8.2]). 
+** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
 ** If a virtual table extension is
-** used with an SQLite version earlier than 3.8.2, the results of attempting 
-** to read or write the estimatedRows field are undefined (but are likely 
-** to included crashing the application). The estimatedRows field should
+** used with an SQLite version earlier than 3.8.2, the results of attempting
+** to read or write the estimatedRows field are undefined (but are likely
+** to include crashing the application). The estimatedRows field should
 ** therefore only be used if [sqlite3_libversion_number()] returns a
 ** value greater than or equal to 3008002. Similarly, the idxFlags field
-** was added for [version 3.9.0] ([dateof:3.9.0]). 
+** was added for [version 3.9.0] ([dateof:3.9.0]).
 ** It may therefore only be used if
 ** sqlite3_libversion_number() returns a value greater than or equal to
 ** 3009000.
@@ -6617,7 +6954,7 @@ struct sqlite3_index_info {
 /*
 ** CAPI3REF: Virtual Table Scan Flags
 **
-** Virtual table implementations are allowed to set the 
+** Virtual table implementations are allowed to set the
 ** [sqlite3_index_info].idxFlags field to some combination of
 ** these bits.
 */
@@ -6626,7 +6963,7 @@ struct sqlite3_index_info {
 /*
 ** CAPI3REF: Virtual Table Constraint Operator Codes
 **
-** These macros defined the allowed values for the
+** These macros define the allowed values for the
 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
 ** an operator that is part of a constraint term in the wHERE clause of
 ** a query that uses a [virtual table].
@@ -6657,7 +6994,7 @@ struct sqlite3_index_info {
 ** preexisting [virtual table] for the module.
 **
 ** ^The module name is registered on the [database connection] specified
-** by the first parameter.  ^The name of the module is given by the 
+** by the first parameter.  ^The name of the module is given by the
 ** second parameter.  ^The third parameter is a pointer to
 ** the implementation of the [virtual table module].   ^The fourth
 ** parameter is an arbitrary client data pointer that is passed through
@@ -6774,7 +7111,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
 ** METHOD: sqlite3
 **
 ** ^(Virtual tables can provide alternative implementations of functions
-** using the [xFindFunction] method of the [virtual table module].  
+** using the [xFindFunction] method of the [virtual table module].
 ** But global versions of those functions
 ** must exist in order to be overloaded.)^
 **
@@ -6825,7 +7162,7 @@ typedef struct sqlite3_blob sqlite3_blob;
 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
 ** </pre>)^
 **
-** ^(Parameter zDb is not the filename that contains the database, but 
+** ^(Parameter zDb is not the filename that contains the database, but
 ** rather the symbolic name of the database. For attached databases, this is
 ** the name that appears after the AS keyword in the [ATTACH] statement.
 ** For the main database file, the database name is "main". For TEMP
@@ -6838,28 +7175,28 @@ typedef struct sqlite3_blob sqlite3_blob;
 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
-** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
+** the API is not misused, it is always safe to call [sqlite3_blob_close()]
 ** on *ppBlob after this function it returns.
 **
 ** This function fails with SQLITE_ERROR if any of the following are true:
 ** <ul>
-**   <li> ^(Database zDb does not exist)^, 
-**   <li> ^(Table zTable does not exist within database zDb)^, 
-**   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
+**   <li> ^(Database zDb does not exist)^,
+**   <li> ^(Table zTable does not exist within database zDb)^,
+**   <li> ^(Table zTable is a WITHOUT ROWID table)^,
 **   <li> ^(Column zColumn does not exist)^,
 **   <li> ^(Row iRow is not present in the table)^,
 **   <li> ^(The specified column of row iRow contains a value that is not
 **         a TEXT or BLOB value)^,
-**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
+**   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
 **         constraint and the blob is being opened for read/write access)^,
-**   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
+**   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
 **         column zColumn is part of a [child key] definition and the blob is
 **         being opened for read/write access)^.
 ** </ul>
 **
-** ^Unless it returns SQLITE_MISUSE, this function sets the 
-** [database connection] error code and message accessible via 
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
+** ^Unless it returns SQLITE_MISUSE, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
 **
 ** A BLOB referenced by sqlite3_blob_open() may be read using the
 ** [sqlite3_blob_read()] interface and modified by using
@@ -6885,7 +7222,7 @@ typedef struct sqlite3_blob sqlite3_blob;
 ** blob.
 **
 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
-** and the built-in [zeroblob] SQL function may be used to create a 
+** and the built-in [zeroblob] SQL function may be used to create a
 ** zero-filled blob to read or write using the incremental-blob interface.
 **
 ** To avoid a resource leak, every open [BLOB handle] should eventually
@@ -6935,7 +7272,7 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
 ** DESTRUCTOR: sqlite3_blob
 **
 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
-** unconditionally.  Even if this routine returns an error code, the 
+** unconditionally.  Even if this routine returns an error code, the
 ** handle is still closed.)^
 **
 ** ^If the blob handle being closed was opened for read-write access, and if
@@ -6945,10 +7282,10 @@ SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
 ** code is returned and the transaction rolled back.
 **
 ** Calling this function with an argument that is not a NULL pointer or an
-** open blob handle results in undefined behaviour. ^Calling this routine 
-** with a null pointer (such as would be returned by a failed call to 
+** open blob handle results in undefined behaviour. ^Calling this routine
+** with a null pointer (such as would be returned by a failed call to
 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
-** is passed a valid open blob handle, the values returned by the 
+** is passed a valid open blob handle, the values returned by the
 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
 */
 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
@@ -6957,7 +7294,7 @@ SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
 ** CAPI3REF: Return The Size Of An Open BLOB
 ** METHOD: sqlite3_blob
 **
-** ^Returns the size in bytes of the BLOB accessible via the 
+** ^Returns the size in bytes of the BLOB accessible via the
 ** successfully opened [BLOB handle] in its only argument.  ^The
 ** incremental blob I/O routines can only read or overwriting existing
 ** blob content; they cannot change the size of a blob.
@@ -7008,9 +7345,9 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
 **
 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
-** ^Unless SQLITE_MISUSE is returned, this function sets the 
-** [database connection] error code and message accessible via 
-** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
+** ^Unless SQLITE_MISUSE is returned, this function sets the
+** [database connection] error code and message accessible via
+** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
 **
 ** ^If the [BLOB handle] passed as the first argument was not opened for
 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
@@ -7019,9 +7356,9 @@ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
 ** This function may only modify the contents of the BLOB; it is
 ** not possible to increase the size of a BLOB using this API.
 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
-** [SQLITE_ERROR] is returned and no data is written. The size of the 
-** BLOB (and hence the maximum value of N+iOffset) can be determined 
-** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
+** [SQLITE_ERROR] is returned and no data is written. The size of the
+** BLOB (and hence the maximum value of N+iOffset) can be determined
+** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
 ** than zero [SQLITE_ERROR] is returned and no data is written.
 **
 ** ^An attempt to write to an expired [BLOB handle] fails with an
@@ -7115,7 +7452,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
 ** <ul>
 ** <li>  SQLITE_MUTEX_FAST
 ** <li>  SQLITE_MUTEX_RECURSIVE
-** <li>  SQLITE_MUTEX_STATIC_MASTER
+** <li>  SQLITE_MUTEX_STATIC_MAIN
 ** <li>  SQLITE_MUTEX_STATIC_MEM
 ** <li>  SQLITE_MUTEX_STATIC_OPEN
 ** <li>  SQLITE_MUTEX_STATIC_PRNG
@@ -7173,7 +7510,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
 ** ^(Some systems (for example, Windows 95) do not support the operation
 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
 ** will always return SQLITE_BUSY. The SQLite core only ever uses
-** sqlite3_mutex_try() as an optimization so this is acceptable 
+** sqlite3_mutex_try() as an optimization so this is acceptable
 ** behavior.)^
 **
 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
@@ -7238,7 +7575,7 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
 ** The only difference is that the public sqlite3_XXX functions enumerated
 ** above silently ignore any invocations that pass a NULL pointer instead
 ** of a valid mutex handle. The implementations of the methods defined
-** by this structure are not required to handle this case, the results
+** by this structure are not required to handle this case. The results
 ** of passing a NULL pointer instead of a valid mutex handle are undefined
 ** (i.e. it is acceptable to provide an implementation that segfaults if
 ** it is passed a NULL pointer).
@@ -7317,7 +7654,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
 */
 #define SQLITE_MUTEX_FAST             0
 #define SQLITE_MUTEX_RECURSIVE        1
-#define SQLITE_MUTEX_STATIC_MASTER    2
+#define SQLITE_MUTEX_STATIC_MAIN      2
 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
@@ -7332,11 +7669,15 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
 #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
 #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
 
+/* Legacy compatibility: */
+#define SQLITE_MUTEX_STATIC_MASTER    2
+
+
 /*
 ** CAPI3REF: Retrieve the mutex for a database connection
 ** METHOD: sqlite3
 **
-** ^This interface returns a pointer the [sqlite3_mutex] object that 
+** ^This interface returns a pointer the [sqlite3_mutex] object that
 ** serializes access to the [database connection] given in the argument
 ** when the [threading mode] is Serialized.
 ** ^If the [threading mode] is Single-thread or Multi-thread then this
@@ -7363,7 +7704,7 @@ SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
 ** method becomes the return value of this routine.
 **
 ** A few opcodes for [sqlite3_file_control()] are handled directly
-** by the SQLite core and never invoke the 
+** by the SQLite core and never invoke the
 ** sqlite3_io_methods.xFileControl method.
 ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
 ** a pointer to the underlying [sqlite3_file] object to be written into
@@ -7427,7 +7768,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_PENDING_BYTE            11
 #define SQLITE_TESTCTRL_ASSERT                  12
 #define SQLITE_TESTCTRL_ALWAYS                  13
-#define SQLITE_TESTCTRL_RESERVE                 14
+#define SQLITE_TESTCTRL_RESERVE                 14  /* NOT USED */
 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
 #define SQLITE_TESTCTRL_ISKEYWORD               16  /* NOT USED */
 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17  /* NOT USED */
@@ -7445,12 +7786,14 @@ SQLITE_API int sqlite3_test_control(int op, ...);
 #define SQLITE_TESTCTRL_RESULT_INTREAL          27
 #define SQLITE_TESTCTRL_PRNG_SEED               28
 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS     29
-#define SQLITE_TESTCTRL_LAST                    29  /* Largest TESTCTRL */
+#define SQLITE_TESTCTRL_SEEK_COUNT              30
+#define SQLITE_TESTCTRL_TRACEFLAGS              31
+#define SQLITE_TESTCTRL_LAST                    31  /* Largest TESTCTRL */
 
 /*
 ** CAPI3REF: SQL Keyword Checking
 **
-** These routines provide access to the set of SQL language keywords 
+** These routines provide access to the set of SQL language keywords
 ** recognized by SQLite.  Applications can uses these routines to determine
 ** whether or not a specific identifier needs to be escaped (for example,
 ** by enclosing in double-quotes) so as not to confuse the parser.
@@ -7522,14 +7865,14 @@ typedef struct sqlite3_str sqlite3_str;
 **
 ** ^The [sqlite3_str_new(D)] interface allocates and initializes
 ** a new [sqlite3_str] object.  To avoid memory leaks, the object returned by
-** [sqlite3_str_new()] must be freed by a subsequent call to 
+** [sqlite3_str_new()] must be freed by a subsequent call to
 ** [sqlite3_str_finish(X)].
 **
 ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
 ** valid [sqlite3_str] object, though in the event of an out-of-memory
 ** error the returned object might be a special singleton that will
-** silently reject new text, always return SQLITE_NOMEM from 
-** [sqlite3_str_errcode()], always return 0 for 
+** silently reject new text, always return SQLITE_NOMEM from
+** [sqlite3_str_errcode()], always return 0 for
 ** [sqlite3_str_length()], and always return NULL from
 ** [sqlite3_str_finish(X)].  It is always safe to use the value
 ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
@@ -7565,9 +7908,9 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
 ** These interfaces add content to an sqlite3_str object previously obtained
 ** from [sqlite3_str_new()].
 **
-** ^The [sqlite3_str_appendf(X,F,...)] and 
+** ^The [sqlite3_str_appendf(X,F,...)] and
 ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
-** functionality of SQLite to append formatted text onto the end of 
+** functionality of SQLite to append formatted text onto the end of
 ** [sqlite3_str] object X.
 **
 ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
@@ -7584,7 +7927,7 @@ SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
 ** ^This method can be used, for example, to add whitespace indentation.
 **
 ** ^The [sqlite3_str_reset(X)] method resets the string under construction
-** inside [sqlite3_str] object X back to zero bytes in length.  
+** inside [sqlite3_str] object X back to zero bytes in length.
 **
 ** These methods do not return a result code.  ^If an error occurs, that fact
 ** is recorded in the [sqlite3_str] object and can be recovered by a
@@ -7686,7 +8029,7 @@ SQLITE_API int sqlite3_status64(
 ** <dd>This parameter records the largest memory allocation request
 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
 ** internal equivalents).  Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.  
+** *pHighwater parameter to [sqlite3_status()] is of interest.
 ** The value written into the *pCurrent parameter is undefined.</dd>)^
 **
 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
@@ -7695,11 +8038,11 @@ SQLITE_API int sqlite3_status64(
 **
 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
 ** <dd>This parameter returns the number of pages used out of the
-** [pagecache memory allocator] that was configured using 
+** [pagecache memory allocator] that was configured using
 ** [SQLITE_CONFIG_PAGECACHE].  The
 ** value returned is in pages, not in bytes.</dd>)^
 **
-** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
+** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
 ** <dd>This parameter returns the number of bytes of page cache
 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
@@ -7711,8 +8054,8 @@ SQLITE_API int sqlite3_status64(
 **
 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
 ** <dd>This parameter records the largest memory allocation request
-** handed to [pagecache memory allocator].  Only the value returned in the
-** *pHighwater parameter to [sqlite3_status()] is of interest.  
+** handed to the [pagecache memory allocator].  Only the value returned in the
+** *pHighwater parameter to [sqlite3_status()] is of interest.
 ** The value written into the *pCurrent parameter is undefined.</dd>)^
 **
 ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
@@ -7725,7 +8068,7 @@ SQLITE_API int sqlite3_status64(
 ** <dd>No longer used.</dd>
 **
 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
-** <dd>The *pHighwater parameter records the deepest parser stack. 
+** <dd>The *pHighwater parameter records the deepest parser stack.
 ** The *pCurrent value is undefined.  The *pHighwater value is only
 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
 ** </dl>
@@ -7747,12 +8090,12 @@ SQLITE_API int sqlite3_status64(
 ** CAPI3REF: Database Connection Status
 ** METHOD: sqlite3
 **
-** ^This interface is used to retrieve runtime status information 
+** ^This interface is used to retrieve runtime status information
 ** about a single [database connection].  ^The first argument is the
 ** database connection object to be interrogated.  ^The second argument
 ** is an integer constant, taken from the set of
 ** [SQLITE_DBSTATUS options], that
-** determines the parameter to interrogate.  The set of 
+** determines the parameter to interrogate.  The set of
 ** [SQLITE_DBSTATUS options] is likely
 ** to grow in future releases of SQLite.
 **
@@ -7787,7 +8130,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** checked out.</dd>)^
 **
 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
-** <dd>This parameter returns the number malloc attempts that were 
+** <dd>This parameter returns the number of malloc attempts that were
 ** satisfied using lookaside memory. Only the high-water value is meaningful;
 ** the current value is always zero.)^
 **
@@ -7812,7 +8155,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** memory used by all pager caches associated with the database connection.)^
 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
 **
-** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] 
+** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
 ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
 ** pager cache is shared between two or more connections the bytes of heap
@@ -7827,7 +8170,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
 ** <dd>This parameter returns the approximate number of bytes of heap
 ** memory used to store the schema for all databases associated
-** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
+** with the connection - main, temp, and any [ATTACH]-ed databases.)^
 ** ^The full amount of memory used by the schemas is reported, even if the
 ** schema memory is shared with other database connections due to
 ** [shared cache mode] being enabled.
@@ -7842,13 +8185,13 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 **
 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
 ** <dd>This parameter returns the number of pager cache hits that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
 ** is always 0.
 ** </dd>
 **
 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
 ** <dd>This parameter returns the number of pager cache misses that have
-** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
+** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
 ** is always 0.
 ** </dd>
 **
@@ -7869,7 +8212,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** cache overflowing. Transactions are more efficient if they are written
 ** to disk all at once. When pages spill mid-transaction, that introduces
 ** additional overhead. This parameter can be used help identify
-** inefficiencies that can be resolve by increasing the cache size.
+** inefficiencies that can be resolved by increasing the cache size.
 ** </dd>
 **
 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
@@ -7906,7 +8249,7 @@ SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int r
 ** statements.  For example, if the number of table steps greatly exceeds
 ** the number of table searches or result rows, that would tend to indicate
 ** that the prepared statement is using a full table scan rather than
-** an index.  
+** an index.
 **
 ** ^(This interface is used to retrieve and reset counter values from
 ** a [prepared statement].  The first argument is the prepared statement
@@ -7933,7 +8276,7 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
 ** <dd>^This is the number of times that SQLite has stepped forward in
 ** a table as part of a full table scan.  Large numbers for this counter
-** may indicate opportunities for performance improvement through 
+** may indicate opportunities for performance improvement through
 ** careful use of indices.</dd>
 **
 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
@@ -7951,14 +8294,14 @@ SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
 ** <dd>^This is the number of virtual machine operations executed
 ** by the prepared statement if that number is less than or equal
-** to 2147483647.  The number of virtual machine operations can be 
+** to 2147483647.  The number of virtual machine operations can be
 ** used as a proxy for the total work done by the prepared statement.
 ** If the number of virtual machine operations exceeds 2147483647
 ** then the value returned by this statement status code is undefined.
 **
 ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
 ** <dd>^This is the number of times that the prepare statement has been
-** automatically regenerated due to schema changes or change to 
+** automatically regenerated due to schema changes or changes to
 ** [bound parameters] that might affect the query plan.
 **
 ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
@@ -8018,15 +8361,15 @@ struct sqlite3_pcache_page {
 ** KEYWORDS: {page cache}
 **
 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
-** register an alternative page cache implementation by passing in an 
+** register an alternative page cache implementation by passing in an
 ** instance of the sqlite3_pcache_methods2 structure.)^
-** In many applications, most of the heap memory allocated by 
+** In many applications, most of the heap memory allocated by
 ** SQLite is used for the page cache.
-** By implementing a 
+** By implementing a
 ** custom page cache using this API, an application can better control
-** the amount of memory consumed by SQLite, the way in which 
-** that memory is allocated and released, and the policies used to 
-** determine exactly which parts of a database file are cached and for 
+** the amount of memory consumed by SQLite, the way in which
+** that memory is allocated and released, and the policies used to
+** determine exactly which parts of a database file are cached and for
 ** how long.
 **
 ** The alternative page cache mechanism is an
@@ -8039,19 +8382,19 @@ struct sqlite3_pcache_page {
 ** [sqlite3_config()] returns.)^
 **
 ** [[the xInit() page cache method]]
-** ^(The xInit() method is called once for each effective 
+** ^(The xInit() method is called once for each effective
 ** call to [sqlite3_initialize()])^
 ** (usually only once during the lifetime of the process). ^(The xInit()
 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
-** The intent of the xInit() method is to set up global data structures 
-** required by the custom page cache implementation. 
-** ^(If the xInit() method is NULL, then the 
+** The intent of the xInit() method is to set up global data structures
+** required by the custom page cache implementation.
+** ^(If the xInit() method is NULL, then the
 ** built-in default page cache is used instead of the application defined
 ** page cache.)^
 **
 ** [[the xShutdown() page cache method]]
 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
-** It can be used to clean up 
+** It can be used to clean up
 ** any outstanding resources before process shutdown, if required.
 ** ^The xShutdown() method may be NULL.
 **
@@ -8070,7 +8413,7 @@ struct sqlite3_pcache_page {
 ** though this is not guaranteed. ^The
 ** first parameter, szPage, is the size in bytes of the pages that must
 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
-** second parameter szExtra is a number of bytes of extra storage 
+** second parameter szExtra is a number of bytes of extra storage
 ** associated with each page cache entry.  ^The szExtra parameter will
 ** a number less than 250.  SQLite will use the
 ** extra szExtra bytes on each page to store metadata about the underlying
@@ -8083,7 +8426,7 @@ struct sqlite3_pcache_page {
 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
 ** never invoke xUnpin() except to deliberately delete a page.
 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
-** false will always have the "discard" flag set to true.  
+** false will always have the "discard" flag set to true.
 ** ^Hence, a cache created with bPurgeable false will
 ** never contain any unpinned pages.
 **
@@ -8098,12 +8441,12 @@ struct sqlite3_pcache_page {
 ** [[the xPagecount() page cache methods]]
 ** The xPagecount() method must return the number of pages currently
 ** stored in the cache, both pinned and unpinned.
-** 
+**
 ** [[the xFetch() page cache methods]]
-** The xFetch() method locates a page in the cache and returns a pointer to 
+** The xFetch() method locates a page in the cache and returns a pointer to
 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
 ** The pBuf element of the returned sqlite3_pcache_page object will be a
-** pointer to a buffer of szPage bytes used to store the content of a 
+** pointer to a buffer of szPage bytes used to store the content of a
 ** single database page.  The pExtra element of sqlite3_pcache_page will be
 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
 ** for each entry in the page cache.
@@ -8129,7 +8472,7 @@ struct sqlite3_pcache_page {
 **
 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
-** failed.)^  In between the to xFetch() calls, SQLite may
+** failed.)^  In between the xFetch() calls, SQLite may
 ** attempt to unpin one or more cache pages by spilling the content of
 ** pinned pages to disk and synching the operating system disk cache.
 **
@@ -8142,8 +8485,8 @@ struct sqlite3_pcache_page {
 ** page cache implementation. ^The page cache implementation
 ** may choose to evict unpinned pages at any time.
 **
-** The cache must not perform any reference counting. A single 
-** call to xUnpin() unpins the page regardless of the number of prior calls 
+** The cache must not perform any reference counting. A single
+** call to xUnpin() unpins the page regardless of the number of prior calls
 ** to xFetch().
 **
 ** [[the xRekey() page cache methods]]
@@ -8183,7 +8526,7 @@ struct sqlite3_pcache_methods2 {
   int (*xPagecount)(sqlite3_pcache*);
   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
-  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
+  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
       unsigned oldKey, unsigned newKey);
   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
   void (*xDestroy)(sqlite3_pcache*);
@@ -8228,7 +8571,7 @@ typedef struct sqlite3_backup sqlite3_backup;
 **
 ** The backup API copies the content of one database into another.
 ** It is useful either for creating backups of databases or
-** for copying in-memory databases to or from persistent files. 
+** for copying in-memory databases to or from persistent files.
 **
 ** See Also: [Using the SQLite Online Backup API]
 **
@@ -8239,36 +8582,36 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** ^Thus, the backup may be performed on a live source database without
 ** preventing other database connections from
 ** reading or writing to the source database while the backup is underway.
-** 
-** ^(To perform a backup operation: 
+**
+** ^(To perform a backup operation:
 **   <ol>
 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
-**         backup, 
-**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
+**         backup,
+**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
 **         the data between the two databases, and finally
-**     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
-**         associated with the backup operation. 
+**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
+**         associated with the backup operation.
 **   </ol>)^
 ** There should be exactly one call to sqlite3_backup_finish() for each
 ** successful call to sqlite3_backup_init().
 **
 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
 **
-** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
-** [database connection] associated with the destination database 
+** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
+** [database connection] associated with the destination database
 ** and the database name, respectively.
 ** ^The database name is "main" for the main database, "temp" for the
 ** temporary database, or the name specified after the AS keyword in
 ** an [ATTACH] statement for an attached database.
-** ^The S and M arguments passed to 
+** ^The S and M arguments passed to
 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
 ** and database name of the source database, respectively.
 ** ^The source and destination [database connections] (parameters S and D)
 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
 ** an error.
 **
-** ^A call to sqlite3_backup_init() will fail, returning NULL, if 
-** there is already a read or read-write transaction open on the 
+** ^A call to sqlite3_backup_init() will fail, returning NULL, if
+** there is already a read or read-write transaction open on the
 ** destination database.
 **
 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
@@ -8280,14 +8623,14 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
 ** [sqlite3_backup] object.
 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
-** sqlite3_backup_finish() functions to perform the specified backup 
+** sqlite3_backup_finish() functions to perform the specified backup
 ** operation.
 **
 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
 **
-** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
+** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
 ** the source and destination databases specified by [sqlite3_backup] object B.
-** ^If N is negative, all remaining source pages are copied. 
+** ^If N is negative, all remaining source pages are copied.
 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
 ** are still more pages to be copied, then the function returns [SQLITE_OK].
 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
@@ -8309,8 +8652,8 @@ typedef struct sqlite3_backup sqlite3_backup;
 **
 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
 ** the [sqlite3_busy_handler | busy-handler function]
-** is invoked (if one is specified). ^If the 
-** busy-handler returns non-zero before the lock is available, then 
+** is invoked (if one is specified). ^If the
+** busy-handler returns non-zero before the lock is available, then
 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
 ** sqlite3_backup_step() can be retried later. ^If the source
 ** [database connection]
@@ -8318,15 +8661,15 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
-** [SQLITE_READONLY] is returned, then 
-** there is no point in retrying the call to sqlite3_backup_step(). These 
-** errors are considered fatal.)^  The application must accept 
-** that the backup operation has failed and pass the backup operation handle 
+** [SQLITE_READONLY] is returned, then
+** there is no point in retrying the call to sqlite3_backup_step(). These
+** errors are considered fatal.)^  The application must accept
+** that the backup operation has failed and pass the backup operation handle
 ** to the sqlite3_backup_finish() to release associated resources.
 **
 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
-** on the destination file. ^The exclusive lock is not released until either 
-** sqlite3_backup_finish() is called or the backup operation is complete 
+** on the destination file. ^The exclusive lock is not released until either
+** sqlite3_backup_finish() is called or the backup operation is complete
 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
 ** lasts for the duration of the sqlite3_backup_step() call.
@@ -8335,18 +8678,18 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** through the backup process.  ^If the source database is modified by an
 ** external process or via a database connection other than the one being
 ** used by the backup operation, then the backup will be automatically
-** restarted by the next call to sqlite3_backup_step(). ^If the source 
+** restarted by the next call to sqlite3_backup_step(). ^If the source
 ** database is modified by the using the same database connection as is used
 ** by the backup operation, then the backup database is automatically
 ** updated at the same time.
 **
 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
 **
-** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
+** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
 ** application wishes to abandon the backup operation, the application
 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
 ** ^The sqlite3_backup_finish() interfaces releases all
-** resources associated with the [sqlite3_backup] object. 
+** resources associated with the [sqlite3_backup] object.
 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
 ** active write-transaction on the destination database is rolled back.
 ** The [sqlite3_backup] object is invalid
@@ -8386,8 +8729,8 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** connections, then the source database connection may be used concurrently
 ** from within other threads.
 **
-** However, the application must guarantee that the destination 
-** [database connection] is not passed to any other API (by any thread) after 
+** However, the application must guarantee that the destination
+** [database connection] is not passed to any other API (by any thread) after
 ** sqlite3_backup_init() is called and before the corresponding call to
 ** sqlite3_backup_finish().  SQLite does not currently check to see
 ** if the application incorrectly accesses the destination [database connection]
@@ -8398,11 +8741,11 @@ typedef struct sqlite3_backup sqlite3_backup;
 ** If running in [shared cache mode], the application must
 ** guarantee that the shared cache used by the destination database
 ** is not accessed while the backup is running. In practice this means
-** that the application must guarantee that the disk file being 
+** that the application must guarantee that the disk file being
 ** backed up to is not accessed by any connection within the process,
 ** not just the specific connection that was passed to sqlite3_backup_init().
 **
-** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
+** The [sqlite3_backup] object itself is partially threadsafe. Multiple
 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
 ** APIs are not strictly speaking threadsafe. If they are invoked at the
@@ -8427,8 +8770,8 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** ^When running in shared-cache mode, a database operation may fail with
 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
 ** individual tables within the shared-cache cannot be obtained. See
-** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
-** ^This API may be used to register a callback that SQLite will invoke 
+** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
+** ^This API may be used to register a callback that SQLite will invoke
 ** when the connection currently holding the required lock relinquishes it.
 ** ^This API is only available if the library was compiled with the
 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
@@ -8436,18 +8779,18 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** See Also: [Using the SQLite Unlock Notification Feature].
 **
 ** ^Shared-cache locks are released when a database connection concludes
-** its current transaction, either by committing it or rolling it back. 
+** its current transaction, either by committing it or rolling it back.
 **
 ** ^When a connection (known as the blocked connection) fails to obtain a
 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
 ** identity of the database connection (the blocking connection) that
-** has locked the required resource is stored internally. ^After an 
+** has locked the required resource is stored internally. ^After an
 ** application receives an SQLITE_LOCKED error, it may call the
-** sqlite3_unlock_notify() method with the blocked connection handle as 
+** sqlite3_unlock_notify() method with the blocked connection handle as
 ** the first argument to register for a callback that will be invoked
 ** when the blocking connections current transaction is concluded. ^The
 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
-** call that concludes the blocking connections transaction.
+** call that concludes the blocking connection's transaction.
 **
 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
 ** there is a chance that the blocking connection will have already
@@ -8457,15 +8800,15 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** ^If the blocked connection is attempting to obtain a write-lock on a
 ** shared-cache table, and more than one other connection currently holds
-** a read-lock on the same table, then SQLite arbitrarily selects one of 
+** a read-lock on the same table, then SQLite arbitrarily selects one of
 ** the other connections to use as the blocking connection.
 **
-** ^(There may be at most one unlock-notify callback registered by a 
+** ^(There may be at most one unlock-notify callback registered by a
 ** blocked connection. If sqlite3_unlock_notify() is called when the
 ** blocked connection already has a registered unlock-notify callback,
 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
 ** called with a NULL pointer as its second argument, then any existing
-** unlock-notify callback is canceled. ^The blocked connections 
+** unlock-notify callback is canceled. ^The blocked connections
 ** unlock-notify callback may also be canceled by closing the blocked
 ** connection using [sqlite3_close()].
 **
@@ -8478,25 +8821,25 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** <b>Callback Invocation Details</b>
 **
-** When an unlock-notify callback is registered, the application provides a 
+** When an unlock-notify callback is registered, the application provides a
 ** single void* pointer that is passed to the callback when it is invoked.
 ** However, the signature of the callback function allows SQLite to pass
 ** it an array of void* context pointers. The first argument passed to
 ** an unlock-notify callback is a pointer to an array of void* pointers,
 ** and the second is the number of entries in the array.
 **
-** When a blocking connections transaction is concluded, there may be
+** When a blocking connection's transaction is concluded, there may be
 ** more than one blocked connection that has registered for an unlock-notify
 ** callback. ^If two or more such blocked connections have specified the
 ** same callback function, then instead of invoking the callback function
 ** multiple times, it is invoked once with the set of void* context pointers
 ** specified by the blocked connections bundled together into an array.
-** This gives the application an opportunity to prioritize any actions 
+** This gives the application an opportunity to prioritize any actions
 ** related to the set of unblocked database connections.
 **
 ** <b>Deadlock Detection</b>
 **
-** Assuming that after registering for an unlock-notify callback a 
+** Assuming that after registering for an unlock-notify callback a
 ** database waits for the callback to be issued before taking any further
 ** action (a reasonable assumption), then using this API may cause the
 ** application to deadlock. For example, if connection X is waiting for
@@ -8519,7 +8862,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 **
 ** <b>The "DROP TABLE" Exception</b>
 **
-** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
+** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
 ** always appropriate to call sqlite3_unlock_notify(). There is however,
 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
 ** SQLite checks if there are any currently executing SELECT statements
@@ -8532,7 +8875,7 @@ SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 ** One way around this problem is to check the extended error code returned
 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
-** the special "DROP TABLE/INDEX" case, the extended error code is just 
+** the special "DROP TABLE/INDEX" case, the extended error code is just
 ** SQLITE_LOCKED.)^
 */
 SQLITE_API int sqlite3_unlock_notify(
@@ -8623,8 +8966,8 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
 ** is invoked each time data is committed to a database in wal mode.
 **
-** ^(The callback is invoked by SQLite after the commit has taken place and 
-** the associated write-lock on the database released)^, so the implementation 
+** ^(The callback is invoked by SQLite after the commit has taken place and
+** the associated write-lock on the database released)^, so the implementation
 ** may read, write or [checkpoint] the database as required.
 **
 ** ^The first parameter passed to the callback function when it is invoked
@@ -8643,7 +8986,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** that does not correspond to any valid SQLite error code, the results
 ** are undefined.
 **
-** A single database handle may have at most a single write-ahead log callback 
+** A single database handle may have at most a single write-ahead log callback
 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
 ** previously registered write-ahead log callback. ^Note that the
 ** [sqlite3_wal_autocheckpoint()] interface and the
@@ -8651,7 +8994,7 @@ SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 ** overwrite any prior [sqlite3_wal_hook()] settings.
 */
 SQLITE_API void *sqlite3_wal_hook(
-  sqlite3*, 
+  sqlite3*,
   int(*)(void *,sqlite3*,const char*,int),
   void*
 );
@@ -8664,7 +9007,7 @@ SQLITE_API void *sqlite3_wal_hook(
 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
 ** to automatically [checkpoint]
 ** after committing a transaction if there are N or
-** more frames in the [write-ahead log] file.  ^Passing zero or 
+** more frames in the [write-ahead log] file.  ^Passing zero or
 ** a negative value as the nFrame parameter disables automatic
 ** checkpoints entirely.
 **
@@ -8694,7 +9037,7 @@ SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
 **
-** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
+** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
 ** [write-ahead log] for database X on [database connection] D to be
 ** transferred into the database file and for the write-ahead log to
 ** be reset.  See the [checkpointing] documentation for addition
@@ -8722,10 +9065,10 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 **
 ** <dl>
 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
-**   ^Checkpoint as many frames as possible without waiting for any database 
-**   readers or writers to finish, then sync the database file if all frames 
+**   ^Checkpoint as many frames as possible without waiting for any database
+**   readers or writers to finish, then sync the database file if all frames
 **   in the log were checkpointed. ^The [busy-handler callback]
-**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
+**   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
 **   ^On the other hand, passive mode might leave the checkpoint unfinished
 **   if there are concurrent readers or writers.
 **
@@ -8739,9 +9082,9 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 **
 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
 **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
-**   that after checkpointing the log file it blocks (calls the 
+**   that after checkpointing the log file it blocks (calls the
 **   [busy-handler callback])
-**   until all readers are reading from the database file only. ^This ensures 
+**   until all readers are reading from the database file only. ^This ensures
 **   that the next writer will restart the log file from the beginning.
 **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
 **   database writer attempts while it is pending, but does not impede readers.
@@ -8763,31 +9106,31 @@ SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
 **
 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
-** any other process is running a checkpoint operation at the same time, the 
-** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
+** any other process is running a checkpoint operation at the same time, the
+** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
 ** busy-handler configured, it will not be invoked in this case.
 **
-** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
+** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
 ** obtained immediately, and a busy-handler is configured, it is invoked and
 ** the writer lock retried until either the busy-handler returns 0 or the lock
 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
 ** database readers as described above. ^If the busy-handler returns 0 before
 ** the writer lock is obtained or while waiting for database readers, the
-** checkpoint operation proceeds from that point in the same way as 
-** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
+** checkpoint operation proceeds from that point in the same way as
+** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
 **
 ** ^If parameter zDb is NULL or points to a zero length string, then the
-** specified operation is attempted on all WAL databases [attached] to 
+** specified operation is attempted on all WAL databases [attached] to
 ** [database connection] db.  In this case the
-** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
-** an SQLITE_BUSY error is encountered when processing one or more of the 
-** attached WAL databases, the operation is still attempted on any remaining 
-** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
-** error occurs while processing an attached database, processing is abandoned 
-** and the error code is returned to the caller immediately. ^If no error 
-** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
+** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
+** an SQLITE_BUSY error is encountered when processing one or more of the
+** attached WAL databases, the operation is still attempted on any remaining
+** attached databases and SQLITE_BUSY is returned at the end. ^If any other
+** error occurs while processing an attached database, processing is abandoned
+** and the error code is returned to the caller immediately. ^If no error
+** (SQLITE_BUSY or otherwise) is encountered while processing the attached
 ** databases, SQLITE_OK is returned.
 **
 ** ^If database zDb is the name of an attached database that is not in WAL
@@ -8835,14 +9178,20 @@ SQLITE_API int sqlite3_wal_checkpoint_v2(
 ** If this interface is invoked outside the context of an xConnect or
 ** xCreate virtual table method then the behavior is undefined.
 **
-** At present, there is only one option that may be configured using
-** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
-** may be added in the future.
+** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
+** [database connection] in which the virtual table is being created and
+** which is passed in as the first argument to the [xConnect] or [xCreate]
+** method that is invoking sqlite3_vtab_config().  The C parameter is one
+** of the [virtual table configuration options].  The presence and meaning
+** of parameters after C depend on which [virtual table configuration option]
+** is used.
 */
 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 
 /*
 ** CAPI3REF: Virtual Table Configuration Options
+** KEYWORDS: {virtual table configuration options}
+** KEYWORDS: {virtual table configuration option}
 **
 ** These macros define the various options to the
 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
@@ -8850,7 +9199,7 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 **
 ** <dl>
 ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
-** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
+** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
 ** <dd>Calls of the form
 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
 ** where X is an integer.  If X is zero, then the [virtual table] whose
@@ -8864,24 +9213,46 @@ SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 ** If X is non-zero, then the virtual table implementation guarantees
 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
 ** any modifications to internal or persistent data structures have been made.
-** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
+** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
 ** is able to roll back a statement or database transaction, and abandon
-** or continue processing the current SQL statement as appropriate. 
+** or continue processing the current SQL statement as appropriate.
 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
 ** had been ABORT.
 **
 ** Virtual table implementations that are required to handle OR REPLACE
-** must do so within the [xUpdate] method. If a call to the 
-** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
-** CONFLICT policy is REPLACE, the virtual table implementation should 
+** must do so within the [xUpdate] method. If a call to the
+** [sqlite3_vtab_on_conflict()] function indicates that the current ON
+** CONFLICT policy is REPLACE, the virtual table implementation should
 ** silently replace the appropriate rows within the xUpdate callback and
 ** return SQLITE_OK. Or, if this is not possible, it may return
-** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
+** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
 ** constraint handling.
+** </dd>
+**
+** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** prohibits that virtual table from being used from within triggers and
+** views.
+** </dd>
+**
+** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
+** <dd>Calls of the form
+** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
+** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
+** identify that virtual table as being safe to use from within triggers
+** and views.  Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
+** virtual table can do no serious harm even if it is controlled by a
+** malicious hacker.  Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
+** flag unless absolutely necessary.
+** </dd>
 ** </dl>
 */
 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
+#define SQLITE_VTAB_INNOCUOUS          2
+#define SQLITE_VTAB_DIRECTONLY         3
 
 /*
 ** CAPI3REF: Determine The Virtual Table Conflict Policy
@@ -8899,10 +9270,11 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
 ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
 **
 ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
-** method of a [virtual table], then it returns true if and only if the
+** method of a [virtual table], then it might return true if the
 ** column is being fetched as part of an UPDATE operation during which the
-** column value will not change.  Applications might use this to substitute
-** a return value that is less expensive to compute and that the corresponding
+** column value will not change.  The virtual table implementation can use
+** this hint as permission to substitute a return value that is less
+** expensive to compute and that the corresponding
 ** [xUpdate] method understands as a "no-change" value.
 **
 ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
@@ -8911,6 +9283,12 @@ SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
 ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
 ** In that case, [sqlite3_value_nochange(X)] will return true for the
 ** same column in the [xUpdate] method.
+**
+** The sqlite3_vtab_nochange() routine is an optimization.  Virtual table
+** implementations should continue to give a correct answer even if the
+** sqlite3_vtab_nochange() interface were to always return false.  In the
+** current implementation, the sqlite3_vtab_nochange() interface does always
+** returns false for the enhanced [UPDATE FROM] statement.
 */
 SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 
@@ -8918,12 +9296,12 @@ SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
 ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
 **
 ** This function may only be called from within a call to the [xBestIndex]
-** method of a [virtual table]. 
+** method of a [virtual table].
 **
 ** The first argument must be the sqlite3_index_info object that is the
 ** first parameter to the xBestIndex() method. The second argument must be
 ** an index into the aConstraint[] array belonging to the sqlite3_index_info
-** structure passed to xBestIndex. This function returns a pointer to a buffer 
+** structure passed to xBestIndex. This function returns a pointer to a buffer
 ** containing the name of the collation sequence for the corresponding
 ** constraint.
 */
@@ -8961,15 +9339,15 @@ SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_
 **
 ** <dl>
 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
-** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
 ** set to the total number of times that the X-th loop has run.</dd>
 **
 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
-** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
+** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
 **
 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
-** <dd>^The "double" variable pointed to by the T parameter will be set to the
+** <dd>^The "double" variable pointed to by the V parameter will be set to the
 ** query planner's estimate for the average number of rows output from each
 ** iteration of the X-th loop.  If the query planner's estimates was accurate,
 ** then this value will approximate the quotient NVISIT/NLOOP and the
@@ -8977,17 +9355,17 @@ SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_
 ** be the NLOOP value for the current loop.
 **
 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
-** <dd>^The "const char *" variable pointed to by the T parameter will be set
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
 ** to a zero-terminated UTF-8 string containing the name of the index or table
 ** used for the X-th loop.
 **
 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
-** <dd>^The "const char *" variable pointed to by the T parameter will be set
+** <dd>^The "const char *" variable pointed to by the V parameter will be set
 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
 ** description for the X-th loop.
 **
 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
-** <dd>^The "int" variable pointed to by the T parameter will be set to the
+** <dd>^The "int" variable pointed to by the V parameter will be set to the
 ** "select-id" for the X-th loop.  The select-id identifies which query or
 ** subquery the loop is part of.  The main query has a select-id of zero.
 ** The select-id is the same value as is output in the first column
@@ -9037,7 +9415,7 @@ SQLITE_API int sqlite3_stmt_scanstatus(
   int idx,                  /* Index of loop to report on */
   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
   void *pOut                /* Result written here */
-);     
+);
 
 /*
 ** CAPI3REF: Zero Scan-Status Counters
@@ -9052,18 +9430,19 @@ SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
 
 /*
 ** CAPI3REF: Flush caches to disk mid-transaction
+** METHOD: sqlite3
 **
 ** ^If a write-transaction is open on [database connection] D when the
 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
-** pages in the pager-cache that are not currently in use are written out 
+** pages in the pager-cache that are not currently in use are written out
 ** to disk. A dirty page may be in use if a database cursor created by an
 ** active SQL statement is reading from it, or if it is page 1 of a database
 ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
 ** interface flushes caches for all schemas - "main", "temp", and
 ** any [attached] databases.
 **
-** ^If this function needs to obtain extra database locks before dirty pages 
-** can be flushed to disk, it does so. ^If those locks cannot be obtained 
+** ^If this function needs to obtain extra database locks before dirty pages
+** can be flushed to disk, it does so. ^If those locks cannot be obtained
 ** immediately and there is a busy-handler callback configured, it is invoked
 ** in the usual manner. ^If the required lock still cannot be obtained, then
 ** the database is skipped and an attempt made to flush any dirty pages
@@ -9084,6 +9463,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 
 /*
 ** CAPI3REF: The pre-update hook.
+** METHOD: sqlite3
 **
 ** ^These interfaces are only available if SQLite is compiled using the
 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
@@ -9101,7 +9481,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 **
 ** ^The preupdate hook only fires for changes to real database tables; the
 ** preupdate hook is not invoked for changes to [virtual tables] or to
-** system tables like sqlite_master or sqlite_stat1.
+** system tables like sqlite_sequence or sqlite_stat1.
 **
 ** ^The second parameter to the preupdate callback is a pointer to
 ** the [database connection] that registered the preupdate hook.
@@ -9110,21 +9490,21 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 ** kind of update operation that is about to occur.
 ** ^(The fourth parameter to the preupdate callback is the name of the
 ** database within the database connection that is being modified.  This
-** will be "main" for the main database or "temp" for TEMP tables or 
+** will be "main" for the main database or "temp" for TEMP tables or
 ** the name given after the AS keyword in the [ATTACH] statement for attached
 ** databases.)^
 ** ^The fifth parameter to the preupdate callback is the name of the
 ** table that is being modified.
 **
 ** For an UPDATE or DELETE operation on a [rowid table], the sixth
-** parameter passed to the preupdate callback is the initial [rowid] of the 
+** parameter passed to the preupdate callback is the initial [rowid] of the
 ** row being modified or deleted. For an INSERT operation on a rowid table,
-** or any operation on a WITHOUT ROWID table, the value of the sixth 
+** or any operation on a WITHOUT ROWID table, the value of the sixth
 ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
 ** seventh parameter is the final rowid value of the row being inserted
 ** or updated. The value of the seventh parameter passed to the callback
 ** function is not defined for operations on WITHOUT ROWID tables, or for
-** INSERT operations on rowid tables.
+** DELETE operations on rowid tables.
 **
 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
@@ -9158,7 +9538,7 @@ SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 **
 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
 ** callback was invoked as a result of a direct insert, update, or delete
-** operation; or 1 for inserts, updates, or deletes invoked by top-level 
+** operation; or 1 for inserts, updates, or deletes invoked by top-level
 ** triggers; or 2 for changes resulting from triggers called by top-level
 ** triggers; and so forth.
 **
@@ -9186,13 +9566,14 @@ SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
 
 /*
 ** CAPI3REF: Low-level system error code
+** METHOD: sqlite3
 **
 ** ^Attempt to return the underlying operating system error code or error
 ** number that caused the most recent I/O error or failure to open a file.
 ** The return value is OS-dependent.  For example, on unix systems, after
 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
 ** called to get back the underlying "errno" that caused the problem, such
-** as ENOSPC, EAUTH, EISDIR, and so forth.  
+** as ENOSPC, EAUTH, EISDIR, and so forth.
 */
 SQLITE_API int sqlite3_system_errno(sqlite3*);
 
@@ -9230,12 +9611,12 @@ typedef struct sqlite3_snapshot {
 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
 ** If there is not already a read-transaction open on schema S when
-** this function is called, one is opened automatically. 
+** this function is called, one is opened automatically.
 **
 ** The following must be true for this function to succeed. If any of
 ** the following statements are false when sqlite3_snapshot_get() is
 ** called, SQLITE_ERROR is returned. The final value of *P is undefined
-** in this case. 
+** in this case.
 **
 ** <ul>
 **   <li> The database handle must not be in [autocommit mode].
@@ -9247,13 +9628,13 @@ typedef struct sqlite3_snapshot {
 **
 **   <li> One or more transactions must have been written to the current wal
 **        file since it was created on disk (by any connection). This means
-**        that a snapshot cannot be taken on a wal mode database with no wal 
+**        that a snapshot cannot be taken on a wal mode database with no wal
 **        file immediately after it is first opened. At least one transaction
 **        must be written to it first.
 ** </ul>
 **
 ** This function may also return SQLITE_NOMEM.  If it is called with the
-** database handle in autocommit mode but fails for some other reason, 
+** database handle in autocommit mode but fails for some other reason,
 ** whether or not a read transaction is opened on schema S is undefined.
 **
 ** The [sqlite3_snapshot] object returned from a successful call to
@@ -9273,38 +9654,38 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
 ** CAPI3REF: Start a read transaction on an historical snapshot
 ** METHOD: sqlite3_snapshot
 **
-** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read 
-** transaction or upgrades an existing one for schema S of 
-** [database connection] D such that the read transaction refers to 
-** historical [snapshot] P, rather than the most recent change to the 
-** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK 
+** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
+** transaction or upgrades an existing one for schema S of
+** [database connection] D such that the read transaction refers to
+** historical [snapshot] P, rather than the most recent change to the
+** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
 ** on success or an appropriate [error code] if it fails.
 **
-** ^In order to succeed, the database connection must not be in 
+** ^In order to succeed, the database connection must not be in
 ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
 ** is already a read transaction open on schema S, then the database handle
 ** must have no active statements (SELECT statements that have been passed
-** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). 
+** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
 ** SQLITE_ERROR is returned if either of these conditions is violated, or
 ** if schema S does not exist, or if the snapshot object is invalid.
 **
 ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
-** snapshot has been overwritten by a [checkpoint]. In this case 
+** snapshot has been overwritten by a [checkpoint]. In this case
 ** SQLITE_ERROR_SNAPSHOT is returned.
 **
-** If there is already a read transaction open when this function is 
+** If there is already a read transaction open when this function is
 ** invoked, then the same read transaction remains open (on the same
 ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
 ** is returned. If another error code - for example SQLITE_PROTOCOL or an
 ** SQLITE_IOERR error code - is returned, then the final state of the
-** read transaction is undefined. If SQLITE_OK is returned, then the 
+** read transaction is undefined. If SQLITE_OK is returned, then the
 ** read transaction is now open on database snapshot P.
 **
 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
 ** database connection D does not know that the database file for
 ** schema S is in [WAL mode].  A database connection might not know
 ** that the database file is in [WAL mode] if there has been no prior
-** I/O on that database connection, or if the database entered [WAL mode] 
+** I/O on that database connection, or if the database entered [WAL mode]
 ** after the most recent I/O on the database connection.)^
 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
 ** database connection in order to make it ready to use snapshots.)
@@ -9336,17 +9717,17 @@ SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
 ** METHOD: sqlite3_snapshot
 **
 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
-** of two valid snapshot handles. 
+** of two valid snapshot handles.
 **
-** If the two snapshot handles are not associated with the same database 
-** file, the result of the comparison is undefined. 
+** If the two snapshot handles are not associated with the same database
+** file, the result of the comparison is undefined.
 **
 ** Additionally, the result of the comparison is only valid if both of the
 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
 ** last time the wal file was deleted. The wal file is deleted when the
 ** database is changed back to rollback mode or when the number of database
-** clients drops to zero. If either snapshot handle was obtained before the 
-** wal file was last deleted, the value returned by this function 
+** clients drops to zero. If either snapshot handle was obtained before the
+** wal file was last deleted, the value returned by this function
 ** is undefined.
 **
 ** Otherwise, this API returns a negative value if P1 refers to an older
@@ -9411,7 +9792,7 @@ SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const c
 ** representation of the database will usually only exist if there has
 ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
 ** values of D and S.
-** The size of the database is written into *P even if the 
+** The size of the database is written into *P even if the
 ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
 ** of the database exists.
 **
@@ -9448,7 +9829,7 @@ SQLITE_API unsigned char *sqlite3_serialize(
 /*
 ** CAPI3REF: Deserialize a database
 **
-** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the 
+** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
 ** [database connection] D to disconnect from database S and then
 ** reopen S as an in-memory database based on the serialization contained
 ** in P.  The serialized database P is N bytes in size.  M is the size of
@@ -9467,7 +9848,7 @@ SQLITE_API unsigned char *sqlite3_serialize(
 ** database is currently in a read transaction or is involved in a backup
 ** operation.
 **
-** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the 
+** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
 ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
 ** [sqlite3_free()] is invoked on argument P prior to returning.
 **
@@ -9582,7 +9963,7 @@ struct sqlite3_rtree_geometry {
 };
 
 /*
-** Register a 2nd-generation geometry callback named zScore that can be 
+** Register a 2nd-generation geometry callback named zScore that can be
 ** used as part of an R-Tree geometry query as follows:
 **
 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
@@ -9597,7 +9978,7 @@ SQLITE_API int sqlite3_rtree_query_callback(
 
 
 /*
-** A pointer to a structure of the following type is passed as the 
+** A pointer to a structure of the following type is passed as the
 ** argument to scored geometry callback registered using
 ** sqlite3_rtree_query_callback().
 **
@@ -9692,7 +10073,7 @@ typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
 ** is not possible for an application to register a pre-update hook on a
 ** database handle that has one or more session objects attached. Nor is
 ** it possible to create a session object attached to a database handle for
-** which a pre-update hook is already defined. The results of attempting 
+** which a pre-update hook is already defined. The results of attempting
 ** either of these things are undefined.
 **
 ** The session object will be used to create changesets for tables in
@@ -9710,13 +10091,13 @@ SQLITE_API int sqlite3session_create(
 ** CAPI3REF: Delete A Session Object
 ** DESTRUCTOR: sqlite3_session
 **
-** Delete a session object previously allocated using 
+** Delete a session object previously allocated using
 ** [sqlite3session_create()]. Once a session object has been deleted, the
 ** results of attempting to use pSession with any other session module
 ** function are undefined.
 **
 ** Session objects must be deleted before the database handle to which they
-** are attached is closed. Refer to the documentation for 
+** are attached is closed. Refer to the documentation for
 ** [sqlite3session_create()] for details.
 */
 SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
@@ -9734,10 +10115,10 @@ SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
 ** the eventual changesets.
 **
 ** Passing zero to this function disables the session. Passing a value
-** greater than zero enables it. Passing a value less than zero is a 
+** greater than zero enables it. Passing a value less than zero is a
 ** no-op, and may be used to query the current state of the session.
 **
-** The return value indicates the final state of the session object: 0 if 
+** The return value indicates the final state of the session object: 0 if
 ** the session is disabled, or 1 if it is enabled.
 */
 SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
@@ -9752,7 +10133,7 @@ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 ** <ul>
 **   <li> The session object "indirect" flag is set when the change is
 **        made, or
-**   <li> The change is made by an SQL trigger or foreign key action 
+**   <li> The change is made by an SQL trigger or foreign key action
 **        instead of directly as a result of a users SQL statement.
 ** </ul>
 **
@@ -9764,10 +10145,10 @@ SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 ** flag.  If the second argument passed to this function is zero, then the
 ** indirect flag is cleared. If it is greater than zero, the indirect flag
 ** is set. Passing a value less than zero does not modify the current value
-** of the indirect flag, and may be used to query the current state of the 
+** of the indirect flag, and may be used to query the current state of the
 ** indirect flag for the specified session object.
 **
-** The return value indicates the final state of the indirect flag: 0 if 
+** The return value indicates the final state of the indirect flag: 0 if
 ** it is clear, or 1 if it is set.
 */
 SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
@@ -9777,20 +10158,20 @@ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect)
 ** METHOD: sqlite3_session
 **
 ** If argument zTab is not NULL, then it is the name of a table to attach
-** to the session object passed as the first argument. All subsequent changes 
-** made to the table while the session object is enabled will be recorded. See 
+** to the session object passed as the first argument. All subsequent changes
+** made to the table while the session object is enabled will be recorded. See
 ** documentation for [sqlite3session_changeset()] for further details.
 **
 ** Or, if argument zTab is NULL, then changes are recorded for all tables
-** in the database. If additional tables are added to the database (by 
-** executing "CREATE TABLE" statements) after this call is made, changes for 
+** in the database. If additional tables are added to the database (by
+** executing "CREATE TABLE" statements) after this call is made, changes for
 ** the new tables are also recorded.
 **
 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
-** defined as part of their CREATE TABLE statement. It does not matter if the 
+** defined as part of their CREATE TABLE statement. It does not matter if the
 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
 ** KEY may consist of a single column, or may be a composite key.
-** 
+**
 ** It is not an error if the named table does not exist in the database. Nor
 ** is it an error if the named table does not have a PRIMARY KEY. However,
 ** no changes will be recorded in either of these scenarios.
@@ -9798,29 +10179,29 @@ SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect)
 ** Changes are not recorded for individual rows that have NULL values stored
 ** in one or more of their PRIMARY KEY columns.
 **
-** SQLITE_OK is returned if the call completes without error. Or, if an error 
+** SQLITE_OK is returned if the call completes without error. Or, if an error
 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
 **
 ** <h3>Special sqlite_stat1 Handling</h3>
 **
-** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to 
+** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
 ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
 **  <pre>
-**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)  
+**  &nbsp;     CREATE TABLE sqlite_stat1(tbl,idx,stat)
 **  </pre>
 **
-** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are 
-** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes 
+** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
+** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
 ** are recorded for rows for which (idx IS NULL) is true. However, for such
 ** rows a zero-length blob (SQL value X'') is stored in the changeset or
 ** patchset instead of a NULL value. This allows such changesets to be
 ** manipulated by legacy implementations of sqlite3changeset_invert(),
 ** concat() and similar.
 **
-** The sqlite3changeset_apply() function automatically converts the 
+** The sqlite3changeset_apply() function automatically converts the
 ** zero-length blob back to a NULL value when updating the sqlite_stat1
 ** table. However, if the application calls sqlite3changeset_new(),
-** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset 
+** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
 ** iterator directly (including on a changeset iterator passed to a
 ** conflict-handler callback) then the X'' value is returned. The application
 ** must translate X'' to NULL itself if required.
@@ -9839,10 +10220,10 @@ SQLITE_API int sqlite3session_attach(
 ** CAPI3REF: Set a table filter on a Session Object.
 ** METHOD: sqlite3_session
 **
-** The second argument (xFilter) is the "filter callback". For changes to rows 
+** The second argument (xFilter) is the "filter callback". For changes to rows
 ** in tables that are not attached to the Session object, the filter is called
-** to determine whether changes to the table's rows should be tracked or not. 
-** If xFilter returns 0, changes is not tracked. Note that once a table is 
+** to determine whether changes to the table's rows should be tracked or not.
+** If xFilter returns 0, changes are not tracked. Note that once a table is
 ** attached, xFilter will not be called again.
 */
 SQLITE_API void sqlite3session_table_filter(
@@ -9858,9 +10239,9 @@ SQLITE_API void sqlite3session_table_filter(
 ** CAPI3REF: Generate A Changeset From A Session Object
 ** METHOD: sqlite3_session
 **
-** Obtain a changeset containing changes to the tables attached to the 
-** session object passed as the first argument. If successful, 
-** set *ppChangeset to point to a buffer containing the changeset 
+** Obtain a changeset containing changes to the tables attached to the
+** session object passed as the first argument. If successful,
+** set *ppChangeset to point to a buffer containing the changeset
 ** and *pnChangeset to the size of the changeset in bytes before returning
 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
 ** zero and return an SQLite error code.
@@ -9875,7 +10256,7 @@ SQLITE_API void sqlite3session_table_filter(
 ** modifies the values of primary key columns. If such a change is made, it
 ** is represented in a changeset as a DELETE followed by an INSERT.
 **
-** Changes are not recorded for rows that have NULL values stored in one or 
+** Changes are not recorded for rows that have NULL values stored in one or
 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
 ** no corresponding change is present in the changesets returned by this
 ** function. If an existing row with one or more NULL values stored in
@@ -9928,14 +10309,14 @@ SQLITE_API void sqlite3session_table_filter(
 ** <ul>
 **   <li> For each record generated by an insert, the database is queried
 **        for a row with a matching primary key. If one is found, an INSERT
-**        change is added to the changeset. If no such row is found, no change 
+**        change is added to the changeset. If no such row is found, no change
 **        is added to the changeset.
 **
-**   <li> For each record generated by an update or delete, the database is 
+**   <li> For each record generated by an update or delete, the database is
 **        queried for a row with a matching primary key. If such a row is
 **        found and one or more of the non-primary key fields have been
-**        modified from their original values, an UPDATE change is added to 
-**        the changeset. Or, if no such row is found in the table, a DELETE 
+**        modified from their original values, an UPDATE change is added to
+**        the changeset. Or, if no such row is found in the table, a DELETE
 **        change is added to the changeset. If there is a row with a matching
 **        primary key in the database, but all fields contain their original
 **        values, no change is added to the changeset.
@@ -9943,7 +10324,7 @@ SQLITE_API void sqlite3session_table_filter(
 **
 ** This means, amongst other things, that if a row is inserted and then later
 ** deleted while a session object is active, neither the insert nor the delete
-** will be present in the changeset. Or if a row is deleted and then later a 
+** will be present in the changeset. Or if a row is deleted and then later a
 ** row with the same primary key values inserted while a session object is
 ** active, the resulting changeset will contain an UPDATE change instead of
 ** a DELETE and an INSERT.
@@ -9952,10 +10333,10 @@ SQLITE_API void sqlite3session_table_filter(
 ** it does not accumulate records when rows are inserted, updated or deleted.
 ** This may appear to have some counter-intuitive effects if a single row
 ** is written to more than once during a session. For example, if a row
-** is inserted while a session object is enabled, then later deleted while 
+** is inserted while a session object is enabled, then later deleted while
 ** the same session object is disabled, no INSERT record will appear in the
 ** changeset, even though the delete took place while the session was disabled.
-** Or, if one field of a row is updated while a session is disabled, and 
+** Or, if one field of a row is updated while a session is disabled, and
 ** another field of the same row is updated while the session is enabled, the
 ** resulting changeset will contain an UPDATE change that updates both fields.
 */
@@ -9976,7 +10357,7 @@ SQLITE_API int sqlite3session_changeset(
 ** an error).
 **
 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
-** attached to the same database handle as the session object that contains 
+** attached to the same database handle as the session object that contains
 ** a table compatible with the table attached to the session by this function.
 ** A table is considered compatible if it:
 **
@@ -9992,33 +10373,33 @@ SQLITE_API int sqlite3session_changeset(
 ** APIs, tables without PRIMARY KEYs are simply ignored.
 **
 ** This function adds a set of changes to the session object that could be
-** used to update the table in database zFrom (call this the "from-table") 
-** so that its content is the same as the table attached to the session 
+** used to update the table in database zFrom (call this the "from-table")
+** so that its content is the same as the table attached to the session
 ** object (call this the "to-table"). Specifically:
 **
 ** <ul>
-**   <li> For each row (primary key) that exists in the to-table but not in 
+**   <li> For each row (primary key) that exists in the to-table but not in
 **     the from-table, an INSERT record is added to the session object.
 **
-**   <li> For each row (primary key) that exists in the to-table but not in 
+**   <li> For each row (primary key) that exists in the to-table but not in
 **     the from-table, a DELETE record is added to the session object.
 **
-**   <li> For each row (primary key) that exists in both tables, but features 
+**   <li> For each row (primary key) that exists in both tables, but features
 **     different non-PK values in each, an UPDATE record is added to the
-**     session.  
+**     session.
 ** </ul>
 **
 ** To clarify, if this function is called and then a changeset constructed
-** using [sqlite3session_changeset()], then after applying that changeset to 
-** database zFrom the contents of the two compatible tables would be 
+** using [sqlite3session_changeset()], then after applying that changeset to
+** database zFrom the contents of the two compatible tables would be
 ** identical.
 **
 ** It an error if database zFrom does not exist or does not contain the
 ** required compatible table.
 **
-** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
+** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
-** may be set to point to a buffer containing an English language error 
+** may be set to point to a buffer containing an English language error
 ** message. It is the responsibility of the caller to free this buffer using
 ** sqlite3_free().
 */
@@ -10037,19 +10418,19 @@ SQLITE_API int sqlite3session_diff(
 ** The differences between a patchset and a changeset are that:
 **
 ** <ul>
-**   <li> DELETE records consist of the primary key fields only. The 
+**   <li> DELETE records consist of the primary key fields only. The
 **        original values of other fields are omitted.
-**   <li> The original values of any modified fields are omitted from 
+**   <li> The original values of any modified fields are omitted from
 **        UPDATE records.
 ** </ul>
 **
-** A patchset blob may be used with up to date versions of all 
-** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), 
+** A patchset blob may be used with up to date versions of all
+** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
 ** attempting to use a patchset blob with old versions of the
-** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. 
+** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
 **
-** Because the non-primary key "old.*" fields are omitted, no 
+** Because the non-primary key "old.*" fields are omitted, no
 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
 ** in the same way as for changesets.
@@ -10068,22 +10449,22 @@ SQLITE_API int sqlite3session_patchset(
 /*
 ** CAPI3REF: Test if a changeset has recorded any changes.
 **
-** Return non-zero if no changes to attached tables have been recorded by 
-** the session object passed as the first argument. Otherwise, if one or 
+** Return non-zero if no changes to attached tables have been recorded by
+** the session object passed as the first argument. Otherwise, if one or
 ** more changes have been recorded, return zero.
 **
 ** Even if this function returns zero, it is possible that calling
 ** [sqlite3session_changeset()] on the session handle may still return a
-** changeset that contains no changes. This can happen when a row in 
-** an attached table is modified and then later on the original values 
+** changeset that contains no changes. This can happen when a row in
+** an attached table is modified and then later on the original values
 ** are restored. However, if this function returns non-zero, then it is
-** guaranteed that a call to sqlite3session_changeset() will return a 
+** guaranteed that a call to sqlite3session_changeset() will return a
 ** changeset containing zero changes.
 */
 SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 
 /*
-** CAPI3REF: Create An Iterator To Traverse A Changeset 
+** CAPI3REF: Create An Iterator To Traverse A Changeset
 ** CONSTRUCTOR: sqlite3_changeset_iter
 **
 ** Create an iterator used to iterate through the contents of a changeset.
@@ -10091,7 +10472,7 @@ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
 ** SQLite error code is returned.
 **
-** The following functions can be used to advance and query a changeset 
+** The following functions can be used to advance and query a changeset
 ** iterator created by this function:
 **
 ** <ul>
@@ -10108,12 +10489,12 @@ SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
 **
 ** Assuming the changeset blob was created by one of the
 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
-** [sqlite3changeset_invert()] functions, all changes within the changeset 
-** that apply to a single table are grouped together. This means that when 
-** an application iterates through a changeset using an iterator created by 
-** this function, all changes that relate to a single table are visited 
-** consecutively. There is no chance that the iterator will visit a change 
-** the applies to table X, then one for table Y, and then later on visit 
+** [sqlite3changeset_invert()] functions, all changes within the changeset
+** that apply to a single table are grouped together. This means that when
+** an application iterates through a changeset using an iterator created by
+** this function, all changes that relate to a single table are visited
+** consecutively. There is no chance that the iterator will visit a change
+** the applies to table X, then one for table Y, and then later on visit
 ** another change for table X.
 **
 ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
@@ -10153,7 +10534,7 @@ SQLITE_API int sqlite3changeset_start_v2(
 ** CAPI3REF: Advance A Changeset Iterator
 ** METHOD: sqlite3_changeset_iter
 **
-** This function may only be used with iterators created by function
+** This function may only be used with iterators created by the function
 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
 ** is returned and the call has no effect.
@@ -10164,12 +10545,12 @@ SQLITE_API int sqlite3changeset_start_v2(
 ** point to the first change in the changeset. Each subsequent call advances
 ** the iterator to point to the next change in the changeset (if any). If
 ** no error occurs and the iterator points to a valid change after a call
-** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. 
+** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
 ** Otherwise, if all changes in the changeset have already been visited,
 ** SQLITE_DONE is returned.
 **
-** If an error occurs, an SQLite error code is returned. Possible error 
-** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or 
+** If an error occurs, an SQLite error code is returned. Possible error
+** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
 ** SQLITE_NOMEM.
 */
 SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
@@ -10187,14 +10568,14 @@ SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
 ** If argument pzTab is not NULL, then *pzTab is set to point to a
 ** nul-terminated utf-8 encoded string containing the name of the table
 ** affected by the current change. The buffer remains valid until either
-** sqlite3changeset_next() is called on the iterator or until the 
-** conflict-handler function returns. If pnCol is not NULL, then *pnCol is 
+** sqlite3changeset_next() is called on the iterator or until the
+** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
 ** set to the number of columns in the table affected by the change. If
 ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
 ** is an indirect change, or false (0) otherwise. See the documentation for
 ** [sqlite3session_indirect()] for a description of direct and indirect
-** changes. Finally, if pOp is not NULL, then *pOp is set to one of 
-** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the 
+** changes. Finally, if pOp is not NULL, then *pOp is set to one of
+** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
 ** type of change that the iterator currently points to.
 **
 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
@@ -10248,7 +10629,7 @@ SQLITE_API int sqlite3changeset_pk(
 ** The pIter argument passed to this function may either be an iterator
 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
 ** Furthermore, it may only be called if the type of change that the iterator
 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
@@ -10258,9 +10639,9 @@ SQLITE_API int sqlite3changeset_pk(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of 
+** sqlite3_value object containing the iVal'th value from the vector of
 ** original row values stored as part of the UPDATE or DELETE change and
-** returns SQLITE_OK. The name of the function comes from the fact that this 
+** returns SQLITE_OK. The name of the function comes from the fact that this
 ** is similar to the "old.*" columns available to update or delete triggers.
 **
 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
@@ -10279,7 +10660,7 @@ SQLITE_API int sqlite3changeset_old(
 ** The pIter argument passed to this function may either be an iterator
 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
-** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
+** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
 ** Furthermore, it may only be called if the type of change that the iterator
 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
@@ -10289,12 +10670,12 @@ SQLITE_API int sqlite3changeset_old(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the vector of 
+** sqlite3_value object containing the iVal'th value from the vector of
 ** new row values stored as part of the UPDATE or INSERT change and
 ** returns SQLITE_OK. If the change is an UPDATE and does not include
-** a new value for the requested column, *ppValue is set to NULL and 
-** SQLITE_OK returned. The name of the function comes from the fact that 
-** this is similar to the "new.*" columns available to update or delete 
+** a new value for the requested column, *ppValue is set to NULL and
+** SQLITE_OK returned. The name of the function comes from the fact that
+** this is similar to the "new.*" columns available to update or delete
 ** triggers.
 **
 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
@@ -10321,7 +10702,7 @@ SQLITE_API int sqlite3changeset_new(
 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 **
 ** If successful, this function sets *ppValue to point to a protected
-** sqlite3_value object containing the iVal'th value from the 
+** sqlite3_value object containing the iVal'th value from the
 ** "conflicting row" associated with the current conflict-handler callback
 ** and returns SQLITE_OK.
 **
@@ -10365,7 +10746,7 @@ SQLITE_API int sqlite3changeset_fk_conflicts(
 ** call has no effect.
 **
 ** If an error was encountered within a call to an sqlite3changeset_xxx()
-** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an 
+** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
 ** to that error is returned by this function. Otherwise, SQLITE_OK is
 ** returned. This is to allow the following pattern (pseudo-code):
@@ -10377,7 +10758,7 @@ SQLITE_API int sqlite3changeset_fk_conflicts(
 **   }
 **   rc = sqlite3changeset_finalize();
 **   if( rc!=SQLITE_OK ){
-**     // An error has occurred 
+**     // An error has occurred
 **   }
 ** </pre>
 */
@@ -10405,7 +10786,7 @@ SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
 ** zeroed and an SQLite error code returned.
 **
 ** It is the responsibility of the caller to eventually call sqlite3_free()
-** on the *ppOut pointer to free the buffer allocation following a successful 
+** on the *ppOut pointer to free the buffer allocation following a successful
 ** call to this function.
 **
 ** WARNING/TODO: This function currently assumes that the input is a valid
@@ -10419,11 +10800,11 @@ SQLITE_API int sqlite3changeset_invert(
 /*
 ** CAPI3REF: Concatenate Two Changeset Objects
 **
-** This function is used to concatenate two changesets, A and B, into a 
+** This function is used to concatenate two changesets, A and B, into a
 ** single changeset. The result is a changeset equivalent to applying
-** changeset A followed by changeset B. 
+** changeset A followed by changeset B.
 **
-** This function combines the two input changesets using an 
+** This function combines the two input changesets using an
 ** sqlite3_changegroup object. Calling it produces similar results as the
 ** following code fragment:
 **
@@ -10455,7 +10836,7 @@ SQLITE_API int sqlite3changeset_concat(
 /*
 ** CAPI3REF: Changegroup Handle
 **
-** A changegroup is an object used to combine two or more 
+** A changegroup is an object used to combine two or more
 ** [changesets] or [patchsets]
 */
 typedef struct sqlite3_changegroup sqlite3_changegroup;
@@ -10471,7 +10852,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 **
 ** If successful, this function returns SQLITE_OK and populates (*pp) with
 ** a pointer to a new sqlite3_changegroup object before returning. The caller
-** should eventually free the returned object using a call to 
+** should eventually free the returned object using a call to
 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
 **
@@ -10483,7 +10864,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 **   <li> Zero or more changesets (or patchsets) are added to the object
 **        by calling sqlite3changegroup_add().
 **
-**   <li> The result of combining all input changesets together is obtained 
+**   <li> The result of combining all input changesets together is obtained
 **        by the application via a call to sqlite3changegroup_output().
 **
 **   <li> The object is deleted using a call to sqlite3changegroup_delete().
@@ -10492,7 +10873,7 @@ typedef struct sqlite3_changegroup sqlite3_changegroup;
 ** Any number of calls to add() and output() may be made between the calls to
 ** new() and delete(), and in any order.
 **
-** As well as the regular sqlite3changegroup_add() and 
+** As well as the regular sqlite3changegroup_add() and
 ** sqlite3changegroup_output() functions, also available are the streaming
 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
 */
@@ -10503,7 +10884,7 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 ** METHOD: sqlite3_changegroup
 **
 ** Add all changes within the changeset (or patchset) in buffer pData (size
-** nData bytes) to the changegroup. 
+** nData bytes) to the changegroup.
 **
 ** If the buffer contains a patchset, then all prior calls to this function
 ** on the same changegroup object must also have specified patchsets. Or, if
@@ -10530,7 +10911,7 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 **       changeset was recorded immediately after the changesets already
 **       added to the changegroup.
 **   <tr><td>INSERT <td>UPDATE <td>
-**       The INSERT change remains in the changegroup. The values in the 
+**       The INSERT change remains in the changegroup. The values in the
 **       INSERT change are modified as if the row was inserted by the
 **       existing change and then updated according to the new change.
 **   <tr><td>INSERT <td>DELETE <td>
@@ -10541,17 +10922,17 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 **       changeset was recorded immediately after the changesets already
 **       added to the changegroup.
 **   <tr><td>UPDATE <td>UPDATE <td>
-**       The existing UPDATE remains within the changegroup. It is amended 
-**       so that the accompanying values are as if the row was updated once 
+**       The existing UPDATE remains within the changegroup. It is amended
+**       so that the accompanying values are as if the row was updated once
 **       by the existing change and then again by the new change.
 **   <tr><td>UPDATE <td>DELETE <td>
 **       The existing UPDATE is replaced by the new DELETE within the
 **       changegroup.
 **   <tr><td>DELETE <td>INSERT <td>
 **       If one or more of the column values in the row inserted by the
-**       new change differ from those in the row deleted by the existing 
+**       new change differ from those in the row deleted by the existing
 **       change, the existing DELETE is replaced by an UPDATE within the
-**       changegroup. Otherwise, if the inserted row is exactly the same 
+**       changegroup. Otherwise, if the inserted row is exactly the same
 **       as the deleted row, the existing DELETE is simply discarded.
 **   <tr><td>DELETE <td>UPDATE <td>
 **       The new change is ignored. This case does not occur if the new
@@ -10569,8 +10950,8 @@ SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
 ** returned. Or, if an out-of-memory condition occurs during processing, this
-** function returns SQLITE_NOMEM. In all cases, if an error occurs the
-** final contents of the changegroup is undefined.
+** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
+** of the final contents of the changegroup is undefined.
 **
 ** If no error occurs, SQLITE_OK is returned.
 */
@@ -10596,7 +10977,7 @@ SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pDa
 **
 ** If an error occurs, an SQLite error code is returned and the output
 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
-** is returned and the output variables are set to the size of and a 
+** is returned and the output variables are set to the size of and a
 ** pointer to the output buffer, respectively. In this case it is the
 ** responsibility of the caller to eventually free the buffer using a
 ** call to sqlite3_free().
@@ -10618,7 +10999,7 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **
 ** Apply a changeset or patchset to a database. These functions attempt to
 ** update the "main" database attached to handle db with the changes found in
-** the changeset passed via the second and third arguments. 
+** the changeset passed via the second and third arguments.
 **
 ** The fourth argument (xFilter) passed to these functions is the "filter
 ** callback". If it is not NULL, then for each table affected by at least one
@@ -10629,16 +11010,16 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** Otherwise, if the return value is non-zero or the xFilter argument to
 ** is NULL, all changes related to the table are attempted.
 **
-** For each table that is not excluded by the filter callback, this function 
-** tests that the target database contains a compatible table. A table is 
+** For each table that is not excluded by the filter callback, this function
+** tests that the target database contains a compatible table. A table is
 ** considered compatible if all of the following are true:
 **
 ** <ul>
-**   <li> The table has the same name as the name recorded in the 
+**   <li> The table has the same name as the name recorded in the
 **        changeset, and
-**   <li> The table has at least as many columns as recorded in the 
+**   <li> The table has at least as many columns as recorded in the
 **        changeset, and
-**   <li> The table has primary key columns in the same position as 
+**   <li> The table has primary key columns in the same position as
 **        recorded in the changeset.
 ** </ul>
 **
@@ -10647,11 +11028,11 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
 ** one such warning is issued for each table in the changeset.
 **
-** For each change for which there is a compatible table, an attempt is made 
-** to modify the table contents according to the UPDATE, INSERT or DELETE 
-** change. If a change cannot be applied cleanly, the conflict handler 
-** function passed as the fifth argument to sqlite3changeset_apply() may be 
-** invoked. A description of exactly when the conflict handler is invoked for 
+** For each change for which there is a compatible table, an attempt is made
+** to modify the table contents according to the UPDATE, INSERT or DELETE
+** change. If a change cannot be applied cleanly, the conflict handler
+** function passed as the fifth argument to sqlite3changeset_apply() may be
+** invoked. A description of exactly when the conflict handler is invoked for
 ** each type of change is below.
 **
 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
@@ -10659,23 +11040,23 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 ** argument are undefined.
 **
 ** Each time the conflict handler function is invoked, it must return one
-** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or 
+** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
 ** if the second argument passed to the conflict handler is either
 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
 ** returns an illegal value, any changes already made are rolled back and
-** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different 
+** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
 ** actions are taken by sqlite3changeset_apply() depending on the value
 ** returned by each invocation of the conflict-handler function. Refer to
-** the documentation for the three 
+** the documentation for the three
 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
 **
 ** <dl>
 ** <dt>DELETE Changes<dd>
-**   For each DELETE change, the function checks if the target database 
-**   contains a row with the same primary key value (or values) as the 
-**   original row values stored in the changeset. If it does, and the values 
-**   stored in all non-primary key columns also match the values stored in 
+**   For each DELETE change, the function checks if the target database
+**   contains a row with the same primary key value (or values) as the
+**   original row values stored in the changeset. If it does, and the values
+**   stored in all non-primary key columns also match the values stored in
 **   the changeset the row is deleted from the target database.
 **
 **   If a row with matching primary key values is found, but one or more of
@@ -10704,22 +11085,22 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **   database table, the trailing fields are populated with their default
 **   values.
 **
-**   If the attempt to insert the row fails because the database already 
+**   If the attempt to insert the row fails because the database already
 **   contains a row with the same primary key values, the conflict handler
-**   function is invoked with the second argument set to 
+**   function is invoked with the second argument set to
 **   [SQLITE_CHANGESET_CONFLICT].
 **
 **   If the attempt to insert the row fails because of some other constraint
-**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is 
+**   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
 **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
-**   This includes the case where the INSERT operation is re-attempted because 
-**   an earlier call to the conflict handler function returned 
+**   This includes the case where the INSERT operation is re-attempted because
+**   an earlier call to the conflict handler function returned
 **   [SQLITE_CHANGESET_REPLACE].
 **
 ** <dt>UPDATE Changes<dd>
-**   For each UPDATE change, the function checks if the target database 
-**   contains a row with the same primary key value (or values) as the 
-**   original row values stored in the changeset. If it does, and the values 
+**   For each UPDATE change, the function checks if the target database
+**   contains a row with the same primary key value (or values) as the
+**   original row values stored in the changeset. If it does, and the values
 **   stored in all modified non-primary key columns also match the values
 **   stored in the changeset the row is updated within the target database.
 **
@@ -10735,28 +11116,28 @@ SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
 **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 **   passed as the second argument.
 **
-**   If the UPDATE operation is attempted, but SQLite returns 
-**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with 
+**   If the UPDATE operation is attempted, but SQLite returns
+**   SQLITE_CONSTRAINT, the conflict-handler function is invoked with
 **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
-**   This includes the case where the UPDATE operation is attempted after 
+**   This includes the case where the UPDATE operation is attempted after
 **   an earlier call to the conflict handler function returned
-**   [SQLITE_CHANGESET_REPLACE].  
+**   [SQLITE_CHANGESET_REPLACE].
 ** </dl>
 **
 ** It is safe to execute SQL statements, including those that write to the
 ** table that the callback related to, from within the xConflict callback.
-** This can be used to further customize the applications conflict
+** This can be used to further customize the application's conflict
 ** resolution strategy.
 **
 ** All changes made by these functions are enclosed in a savepoint transaction.
 ** If any other error (aside from a constraint failure when attempting to
 ** write to the target database) occurs, then the savepoint transaction is
-** rolled back, restoring the target database to its original state, and an 
+** rolled back, restoring the target database to its original state, and an
 ** SQLite error code returned.
 **
 ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
 ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
-** may set (*ppRebase) to point to a "rebase" that may be used with the 
+** may set (*ppRebase) to point to a "rebase" that may be used with the
 ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
 ** is set to the size of the buffer in bytes. It is the responsibility of the
 ** caller to eventually free any such buffer using sqlite3_free(). The buffer
@@ -10817,7 +11198,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   SAVEPOINT is committed if the changeset or patchset is successfully
 **   applied, or rolled back if an error occurs. Specifying this flag
 **   causes the sessions module to omit this savepoint. In this case, if the
-**   caller has an open transaction or savepoint when apply_v2() is called, 
+**   caller has an open transaction or savepoint when apply_v2() is called,
 **   it may revert the partially applied changeset by rolling it back.
 **
 ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
@@ -10828,7 +11209,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT   0x0001
 #define SQLITE_CHANGESETAPPLY_INVERT        0x0002
 
-/* 
+/*
 ** CAPI3REF: Constants Passed To The Conflict Handler
 **
 ** Values that may be passed as the second argument to a conflict-handler.
@@ -10837,32 +11218,32 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** <dt>SQLITE_CHANGESET_DATA<dd>
 **   The conflict handler is invoked with CHANGESET_DATA as the second argument
 **   when processing a DELETE or UPDATE change if a row with the required
-**   PRIMARY KEY fields is present in the database, but one or more other 
-**   (non primary-key) fields modified by the update do not contain the 
+**   PRIMARY KEY fields is present in the database, but one or more other
+**   (non primary-key) fields modified by the update do not contain the
 **   expected "before" values.
-** 
+**
 **   The conflicting row, in this case, is the database row with the matching
 **   primary key.
-** 
+**
 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
 **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
 **   argument when processing a DELETE or UPDATE change if a row with the
 **   required PRIMARY KEY fields is not present in the database.
-** 
+**
 **   There is no conflicting row in this case. The results of invoking the
 **   sqlite3changeset_conflict() API are undefined.
-** 
+**
 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
 **   CHANGESET_CONFLICT is passed as the second argument to the conflict
-**   handler while processing an INSERT change if the operation would result 
+**   handler while processing an INSERT change if the operation would result
 **   in duplicate primary key values.
-** 
+**
 **   The conflicting row in this case is the database row with the matching
 **   primary key.
 **
 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
 **   If foreign key handling is enabled, and applying a changeset leaves the
-**   database in a state containing foreign key violations, the conflict 
+**   database in a state containing foreign key violations, the conflict
 **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
 **   exactly once before the changeset is committed. If the conflict handler
 **   returns CHANGESET_OMIT, the changes, including those that caused the
@@ -10872,12 +11253,12 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   No current or conflicting row information is provided. The only function
 **   it is possible to call on the supplied sqlite3_changeset_iter handle
 **   is sqlite3changeset_fk_conflicts().
-** 
+**
 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
-**   If any other constraint violation occurs while applying a change (i.e. 
-**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is 
+**   If any other constraint violation occurs while applying a change (i.e.
+**   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
 **   invoked with CHANGESET_CONSTRAINT as the second argument.
-** 
+**
 **   There is no conflicting row in this case. The results of invoking the
 **   sqlite3changeset_conflict() API are undefined.
 **
@@ -10889,7 +11270,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESET_CONSTRAINT  4
 #define SQLITE_CHANGESET_FOREIGN_KEY 5
 
-/* 
+/*
 ** CAPI3REF: Constants Returned By The Conflict Handler
 **
 ** A conflict handler callback must return one of the following three values.
@@ -10897,13 +11278,13 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** <dl>
 ** <dt>SQLITE_CHANGESET_OMIT<dd>
 **   If a conflict handler returns this value no special action is taken. The
-**   change that caused the conflict is not applied. The session module 
+**   change that caused the conflict is not applied. The session module
 **   continues to the next change in the changeset.
 **
 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
 **   This value may only be returned if the second argument to the conflict
 **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
-**   is not the case, any changes applied so far are rolled back and the 
+**   is not the case, any changes applied so far are rolled back and the
 **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
 **
 **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
@@ -10916,7 +11297,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   the original row is restored to the database before continuing.
 **
 ** <dt>SQLITE_CHANGESET_ABORT<dd>
-**   If this value is returned, any changes applied so far are rolled back 
+**   If this value is returned, any changes applied so far are rolled back
 **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
 ** </dl>
 */
@@ -10924,20 +11305,20 @@ SQLITE_API int sqlite3changeset_apply_v2(
 #define SQLITE_CHANGESET_REPLACE    1
 #define SQLITE_CHANGESET_ABORT      2
 
-/* 
+/*
 ** CAPI3REF: Rebasing changesets
 ** EXPERIMENTAL
 **
 ** Suppose there is a site hosting a database in state S0. And that
 ** modifications are made that move that database to state S1 and a
 ** changeset recorded (the "local" changeset). Then, a changeset based
-** on S0 is received from another site (the "remote" changeset) and 
-** applied to the database. The database is then in state 
+** on S0 is received from another site (the "remote" changeset) and
+** applied to the database. The database is then in state
 ** (S1+"remote"), where the exact state depends on any conflict
 ** resolution decisions (OMIT or REPLACE) made while applying "remote".
-** Rebasing a changeset is to update it to take those conflict 
+** Rebasing a changeset is to update it to take those conflict
 ** resolution decisions into account, so that the same conflicts
-** do not have to be resolved elsewhere in the network. 
+** do not have to be resolved elsewhere in the network.
 **
 ** For example, if both the local and remote changesets contain an
 ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
@@ -10956,7 +11337,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **
 ** <dl>
 ** <dt>Local INSERT<dd>
-**   This may only conflict with a remote INSERT. If the conflict 
+**   This may only conflict with a remote INSERT. If the conflict
 **   resolution was OMIT, then add an UPDATE change to the rebased
 **   changeset. Or, if the conflict resolution was REPLACE, add
 **   nothing to the rebased changeset.
@@ -10980,12 +11361,12 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **   the old.* values are rebased using the new.* values in the remote
 **   change. Or, if the resolution is REPLACE, then the change is copied
 **   into the rebased changeset with updates to columns also updated by
-**   the conflicting remote UPDATE removed. If this means no columns would 
+**   the conflicting remote UPDATE removed. If this means no columns would
 **   be updated, the change is omitted.
 ** </dl>
 **
-** A local change may be rebased against multiple remote changes 
-** simultaneously. If a single key is modified by multiple remote 
+** A local change may be rebased against multiple remote changes
+** simultaneously. If a single key is modified by multiple remote
 ** changesets, they are combined as follows before the local changeset
 ** is rebased:
 **
@@ -10998,10 +11379,10 @@ SQLITE_API int sqlite3changeset_apply_v2(
 **         of the OMIT resolutions.
 ** </ul>
 **
-** Note that conflict resolutions from multiple remote changesets are 
-** combined on a per-field basis, not per-row. This means that in the 
-** case of multiple remote UPDATE operations, some fields of a single 
-** local change may be rebased for REPLACE while others are rebased for 
+** Note that conflict resolutions from multiple remote changesets are
+** combined on a per-field basis, not per-row. This means that in the
+** case of multiple remote UPDATE operations, some fields of a single
+** local change may be rebased for REPLACE while others are rebased for
 ** OMIT.
 **
 ** In order to rebase a local changeset, the remote changeset must first
@@ -11009,7 +11390,7 @@ SQLITE_API int sqlite3changeset_apply_v2(
 ** the buffer of rebase information captured. Then:
 **
 ** <ol>
-**   <li> An sqlite3_rebaser object is created by calling 
+**   <li> An sqlite3_rebaser object is created by calling
 **        sqlite3rebaser_create().
 **   <li> The new object is configured with the rebase buffer obtained from
 **        sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
@@ -11030,8 +11411,8 @@ typedef struct sqlite3_rebaser sqlite3_rebaser;
 **
 ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
 ** point to the new object and return SQLITE_OK. Otherwise, if an error
-** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew) 
-** to NULL. 
+** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
+** to NULL.
 */
 SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
 
@@ -11045,9 +11426,9 @@ SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
 ** sqlite3changeset_apply_v2().
 */
 SQLITE_API int sqlite3rebaser_configure(
-  sqlite3_rebaser*, 
+  sqlite3_rebaser*,
   int nRebase, const void *pRebase
-); 
+);
 
 /*
 ** CAPI3REF: Rebase a changeset
@@ -11055,9 +11436,9 @@ SQLITE_API int sqlite3rebaser_configure(
 **
 ** Argument pIn must point to a buffer containing a changeset nIn bytes
 ** in size. This function allocates and populates a buffer with a copy
-** of the changeset rebased rebased according to the configuration of the
+** of the changeset rebased according to the configuration of the
 ** rebaser object passed as the first argument. If successful, (*ppOut)
-** is set to point to the new buffer containing the rebased changeset and 
+** is set to point to the new buffer containing the rebased changeset and
 ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
 ** responsibility of the caller to eventually free the new buffer using
 ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
@@ -11065,8 +11446,8 @@ SQLITE_API int sqlite3rebaser_configure(
 */
 SQLITE_API int sqlite3rebaser_rebase(
   sqlite3_rebaser*,
-  int nIn, const void *pIn, 
-  int *pnOut, void **ppOut 
+  int nIn, const void *pIn,
+  int *pnOut, void **ppOut
 );
 
 /*
@@ -11077,30 +11458,30 @@ SQLITE_API int sqlite3rebaser_rebase(
 ** should be one call to this function for each successful invocation
 ** of sqlite3rebaser_create().
 */
-SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p); 
+SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 
 /*
 ** CAPI3REF: Streaming Versions of API functions.
 **
-** The six streaming API xxx_strm() functions serve similar purposes to the 
+** The six streaming API xxx_strm() functions serve similar purposes to the
 ** corresponding non-streaming API functions:
 **
 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
-**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] 
-**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2] 
-**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] 
-**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] 
-**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] 
-**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] 
-**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] 
+**   <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
+**   <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
+**   <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
+**   <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
+**   <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
+**   <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
+**   <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
 ** </table>
 **
 ** Non-streaming functions that accept changesets (or patchsets) as input
-** require that the entire changeset be stored in a single buffer in memory. 
-** Similarly, those that return a changeset or patchset do so by returning 
-** a pointer to a single large buffer allocated using sqlite3_malloc(). 
-** Normally this is convenient. However, if an application running in a 
+** require that the entire changeset be stored in a single buffer in memory.
+** Similarly, those that return a changeset or patchset do so by returning
+** a pointer to a single large buffer allocated using sqlite3_malloc().
+** Normally this is convenient. However, if an application running in a
 ** low-memory environment is required to handle very large changesets, the
 ** large contiguous memory allocations required can become onerous.
 **
@@ -11122,12 +11503,12 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 **  </pre>
 **
 ** Each time the xInput callback is invoked by the sessions module, the first
-** argument passed is a copy of the supplied pIn context pointer. The second 
-** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no 
-** error occurs the xInput method should copy up to (*pnData) bytes of data 
-** into the buffer and set (*pnData) to the actual number of bytes copied 
-** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) 
-** should be set to zero to indicate this. Or, if an error occurs, an SQLite 
+** argument passed is a copy of the supplied pIn context pointer. The second
+** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
+** error occurs the xInput method should copy up to (*pnData) bytes of data
+** into the buffer and set (*pnData) to the actual number of bytes copied
+** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
+** should be set to zero to indicate this. Or, if an error occurs, an SQLite
 ** error code should be returned. In all cases, if an xInput callback returns
 ** an error, all processing is abandoned and the streaming API function
 ** returns a copy of the error code to the caller.
@@ -11135,7 +11516,7 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
 ** invoked by the sessions module at any point during the lifetime of the
 ** iterator. If such an xInput callback returns an error, the iterator enters
-** an error state, whereby all subsequent calls to iterator functions 
+** an error state, whereby all subsequent calls to iterator functions
 ** immediately fail with the same error code as returned by xInput.
 **
 ** Similarly, streaming API functions that return changesets (or patchsets)
@@ -11165,7 +11546,7 @@ SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
 ** is immediately abandoned and the streaming API function returns a copy
 ** of the xOutput error code to the application.
 **
-** The sessions module never invokes an xOutput callback with the third 
+** The sessions module never invokes an xOutput callback with the third
 ** parameter set to a value less than or equal to zero. Other than this,
 ** no guarantees are made as to the size of the chunks of data returned.
 */
@@ -11236,12 +11617,12 @@ SQLITE_API int sqlite3session_patchset_strm(
   int (*xOutput)(void *pOut, const void *pData, int nData),
   void *pOut
 );
-SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*, 
+SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
     int (*xInput)(void *pIn, void *pData, int *pnData),
     void *pIn
 );
 SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
-    int (*xOutput)(void *pOut, const void *pData, int nData), 
+    int (*xOutput)(void *pOut, const void *pData, int nData),
     void *pOut
 );
 SQLITE_API int sqlite3rebaser_rebase_strm(
@@ -11256,16 +11637,16 @@ SQLITE_API int sqlite3rebaser_rebase_strm(
 ** CAPI3REF: Configure global parameters
 **
 ** The sqlite3session_config() interface is used to make global configuration
-** changes to the sessions module in order to tune it to the specific needs 
+** changes to the sessions module in order to tune it to the specific needs
 ** of the application.
 **
 ** The sqlite3session_config() interface is not threadsafe. If it is invoked
 ** while any other thread is inside any other sessions method then the
 ** results are undefined. Furthermore, if it is invoked after any sessions
-** related objects have been created, the results are also undefined. 
+** related objects have been created, the results are also undefined.
 **
 ** The first argument to the sqlite3session_config() function must be one
-** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The 
+** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
 ** interpretation of the (void*) value passed as the second parameter and
 ** the effect of calling this function depends on the value of the first
 ** parameter.
@@ -11315,7 +11696,7 @@ SQLITE_API int sqlite3session_config(int op, void *pArg);
 **
 ******************************************************************************
 **
-** Interfaces to extend FTS5. Using the interfaces defined in this file, 
+** Interfaces to extend FTS5. Using the interfaces defined in this file,
 ** FTS5 may be extended with:
 **
 **     * custom tokenizers, and
@@ -11359,19 +11740,19 @@ struct Fts5PhraseIter {
 ** EXTENSION API FUNCTIONS
 **
 ** xUserData(pFts):
-**   Return a copy of the context pointer the extension function was 
+**   Return a copy of the context pointer the extension function was
 **   registered with.
 **
 ** xColumnTotalSize(pFts, iCol, pnToken):
 **   If parameter iCol is less than zero, set output variable *pnToken
 **   to the total number of tokens in the FTS5 table. Or, if iCol is
 **   non-negative but less than the number of columns in the table, return
-**   the total number of tokens in column iCol, considering all rows in 
+**   the total number of tokens in column iCol, considering all rows in
 **   the FTS5 table.
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 ** xColumnCount(pFts):
@@ -11385,7 +11766,7 @@ struct Fts5PhraseIter {
 **
 **   If parameter iCol is greater than or equal to the number of columns
 **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
-**   an OOM condition or IO error), an appropriate SQLite error code is 
+**   an OOM condition or IO error), an appropriate SQLite error code is
 **   returned.
 **
 **   This function may be quite inefficient if used with an FTS5 table
@@ -11412,8 +11793,8 @@ struct Fts5PhraseIter {
 **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always returns 0.
 **
 ** xInst:
@@ -11428,7 +11809,7 @@ struct Fts5PhraseIter {
 **   code (i.e. SQLITE_NOMEM) if an error occurs.
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. 
+**   "detail=none" or "detail=column" option.
 **
 ** xRowid:
 **   Returns the rowid of the current row.
@@ -11444,11 +11825,11 @@ struct Fts5PhraseIter {
 **
 **   with $p set to a phrase equivalent to the phrase iPhrase of the
 **   current query is executed. Any column filter that applies to
-**   phrase iPhrase of the current query is included in $p. For each 
-**   row visited, the callback function passed as the fourth argument 
-**   is invoked. The context and API objects passed to the callback 
+**   phrase iPhrase of the current query is included in $p. For each
+**   row visited, the callback function passed as the fourth argument
+**   is invoked. The context and API objects passed to the callback
 **   function may be used to access the properties of each matched row.
-**   Invoking Api.xUserData() returns a copy of the pointer passed as 
+**   Invoking Api.xUserData() returns a copy of the pointer passed as
 **   the third argument to pUserData.
 **
 **   If the callback function returns any value other than SQLITE_OK, the
@@ -11463,14 +11844,14 @@ struct Fts5PhraseIter {
 **
 ** xSetAuxdata(pFts5, pAux, xDelete)
 **
-**   Save the pointer passed as the second argument as the extension function
+**   Save the pointer passed as the second argument as the extension function's
 **   "auxiliary data". The pointer may then be retrieved by the current or any
 **   future invocation of the same fts5 extension function made as part of
 **   the same MATCH query using the xGetAuxdata() API.
 **
 **   Each extension function is allocated a single auxiliary data slot for
-**   each FTS query (MATCH expression). If the extension function is invoked 
-**   more than once for a single FTS query, then all invocations share a 
+**   each FTS query (MATCH expression). If the extension function is invoked
+**   more than once for a single FTS query, then all invocations share a
 **   single auxiliary data context.
 **
 **   If there is already an auxiliary data pointer when this function is
@@ -11489,7 +11870,7 @@ struct Fts5PhraseIter {
 **
 ** xGetAuxdata(pFts5, bClear)
 **
-**   Returns the current auxiliary data pointer for the fts5 extension 
+**   Returns the current auxiliary data pointer for the fts5 extension
 **   function. See the xSetAuxdata() method for details.
 **
 **   If the bClear argument is non-zero, then the auxiliary data is cleared
@@ -11509,7 +11890,7 @@ struct Fts5PhraseIter {
 **   method, to iterate through all instances of a single query phrase within
 **   the current row. This is the same information as is accessible via the
 **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
-**   to use, this API may be faster under some circumstances. To iterate 
+**   to use, this API may be faster under some circumstances. To iterate
 **   through instances of phrase iPhrase, use the following code:
 **
 **       Fts5PhraseIter iter;
@@ -11527,8 +11908,8 @@ struct Fts5PhraseIter {
 **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" or "detail=column" option. If the FTS5 table is created 
-**   with either "detail=none" or "detail=column" and "content=" option 
+**   "detail=none" or "detail=column" option. If the FTS5 table is created
+**   with either "detail=none" or "detail=column" and "content=" option
 **   (i.e. if it is a contentless table), then this API always iterates
 **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
 **
@@ -11552,16 +11933,16 @@ struct Fts5PhraseIter {
 **       }
 **
 **   This API can be quite slow if used with an FTS5 table created with the
-**   "detail=none" option. If the FTS5 table is created with either 
-**   "detail=none" "content=" option (i.e. if it is a contentless table), 
-**   then this API always iterates through an empty set (all calls to 
+**   "detail=none" option. If the FTS5 table is created with either
+**   "detail=none" "content=" option (i.e. if it is a contentless table),
+**   then this API always iterates through an empty set (all calls to
 **   xPhraseFirstColumn() set iCol to -1).
 **
 **   The information accessed using this API and its companion
 **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
 **   (or xInst/xInstCount). The chief advantage of this API is that it is
 **   significantly more efficient than those alternatives when used with
-**   "detail=column" tables.  
+**   "detail=column" tables.
 **
 ** xPhraseNextColumn()
 **   See xPhraseFirstColumn above.
@@ -11575,7 +11956,7 @@ struct Fts5ExtensionApi {
   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
 
-  int (*xTokenize)(Fts5Context*, 
+  int (*xTokenize)(Fts5Context*,
     const char *pText, int nText, /* Text to tokenize */
     void *pCtx,                   /* Context passed to xToken() */
     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
@@ -11604,15 +11985,15 @@ struct Fts5ExtensionApi {
   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
 };
 
-/* 
+/*
 ** CUSTOM AUXILIARY FUNCTIONS
 *************************************************************************/
 
 /*************************************************************************
 ** CUSTOM TOKENIZERS
 **
-** Applications may also register custom tokenizer types. A tokenizer 
-** is registered by providing fts5 with a populated instance of the 
+** Applications may also register custom tokenizer types. A tokenizer
+** is registered by providing fts5 with a populated instance of the
 ** following structure. All structure methods must be defined, setting
 ** any member of the fts5_tokenizer struct to NULL leads to undefined
 ** behaviour. The structure methods are expected to function as follows:
@@ -11623,16 +12004,16 @@ struct Fts5ExtensionApi {
 **
 **   The first argument passed to this function is a copy of the (void*)
 **   pointer provided by the application when the fts5_tokenizer object
-**   was registered with FTS5 (the third argument to xCreateTokenizer()). 
+**   was registered with FTS5 (the third argument to xCreateTokenizer()).
 **   The second and third arguments are an array of nul-terminated strings
 **   containing the tokenizer arguments, if any, specified following the
 **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
 **   to create the FTS5 table.
 **
-**   The final argument is an output variable. If successful, (*ppOut) 
+**   The final argument is an output variable. If successful, (*ppOut)
 **   should be set to point to the new tokenizer handle and SQLITE_OK
 **   returned. If an error occurs, some value other than SQLITE_OK should
-**   be returned. In this case, fts5 assumes that the final value of *ppOut 
+**   be returned. In this case, fts5 assumes that the final value of *ppOut
 **   is undefined.
 **
 ** xDelete:
@@ -11641,7 +12022,7 @@ struct Fts5ExtensionApi {
 **   be invoked exactly once for each successful call to xCreate().
 **
 ** xTokenize:
-**   This function is expected to tokenize the nText byte string indicated 
+**   This function is expected to tokenize the nText byte string indicated
 **   by argument pText. pText may or may not be nul-terminated. The first
 **   argument passed to this function is a pointer to an Fts5Tokenizer object
 **   returned by an earlier call to xCreate().
@@ -11655,8 +12036,8 @@ struct Fts5ExtensionApi {
 **            determine the set of tokens to add to (or delete from) the
 **            FTS index.
 **
-**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
-**            against the FTS index. The tokenizer is being called to tokenize 
+**       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
+**            against the FTS index. The tokenizer is being called to tokenize
 **            a bareword or quoted string specified as part of the query.
 **
 **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
@@ -11664,10 +12045,10 @@ struct Fts5ExtensionApi {
 **            followed by a "*" character, indicating that the last token
 **            returned by the tokenizer will be treated as a token prefix.
 **
-**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
+**       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
 **            satisfy an fts5_api.xTokenize() request made by an auxiliary
 **            function. Or an fts5_api.xColumnSize() request made by the same
-**            on a columnsize=0 database.  
+**            on a columnsize=0 database.
 **   </ul>
 **
 **   For each token in the input string, the supplied callback xToken() must
@@ -11679,10 +12060,10 @@ struct Fts5ExtensionApi {
 **   which the token is derived within the input.
 **
 **   The second argument passed to the xToken() callback ("tflags") should
-**   normally be set to 0. The exception is if the tokenizer supports 
+**   normally be set to 0. The exception is if the tokenizer supports
 **   synonyms. In this case see the discussion below for details.
 **
-**   FTS5 assumes the xToken() callback is invoked for each token in the 
+**   FTS5 assumes the xToken() callback is invoked for each token in the
 **   order that they occur within the input text.
 **
 **   If an xToken() callback returns any value other than SQLITE_OK, then
@@ -11696,7 +12077,7 @@ struct Fts5ExtensionApi {
 ** SYNONYM SUPPORT
 **
 **   Custom tokenizers may also support synonyms. Consider a case in which a
-**   user wishes to query for a phrase such as "first place". Using the 
+**   user wishes to query for a phrase such as "first place". Using the
 **   built-in tokenizers, the FTS5 query 'first + place' will match instances
 **   of "first place" within the document set, but not alternative forms
 **   such as "1st place". In some applications, it would be better to match
@@ -11705,8 +12086,8 @@ struct Fts5ExtensionApi {
 **
 **   There are several ways to approach this in FTS5:
 **
-**   <ol><li> By mapping all synonyms to a single token. In this case, the 
-**            In the above example, this means that the tokenizer returns the
+**   <ol><li> By mapping all synonyms to a single token. In this case, using
+**            the above example, this means that the tokenizer returns the
 **            same token for inputs "first" and "1st". Say that token is in
 **            fact "first", so that when the user inserts the document "I won
 **            1st place" entries are added to the index for tokens "i", "won",
@@ -11716,34 +12097,34 @@ struct Fts5ExtensionApi {
 **
 **       <li> By querying the index for all synonyms of each query term
 **            separately. In this case, when tokenizing query text, the
-**            tokenizer may provide multiple synonyms for a single term 
-**            within the document. FTS5 then queries the index for each 
+**            tokenizer may provide multiple synonyms for a single term
+**            within the document. FTS5 then queries the index for each
 **            synonym individually. For example, faced with the query:
 **
 **   <codeblock>
 **     ... MATCH 'first place'</codeblock>
 **
 **            the tokenizer offers both "1st" and "first" as synonyms for the
-**            first token in the MATCH query and FTS5 effectively runs a query 
+**            first token in the MATCH query and FTS5 effectively runs a query
 **            similar to:
 **
 **   <codeblock>
 **     ... MATCH '(first OR 1st) place'</codeblock>
 **
 **            except that, for the purposes of auxiliary functions, the query
-**            still appears to contain just two phrases - "(first OR 1st)" 
+**            still appears to contain just two phrases - "(first OR 1st)"
 **            being treated as a single phrase.
 **
 **       <li> By adding multiple synonyms for a single term to the FTS index.
 **            Using this method, when tokenizing document text, the tokenizer
-**            provides multiple synonyms for each token. So that when a 
+**            provides multiple synonyms for each token. So that when a
 **            document such as "I won first place" is tokenized, entries are
 **            added to the FTS index for "i", "won", "first", "1st" and
 **            "place".
 **
 **            This way, even if the tokenizer does not provide synonyms
 **            when tokenizing query text (it should not - to do so would be
-**            inefficient), it doesn't matter if the user queries for 
+**            inefficient), it doesn't matter if the user queries for
 **            'first + place' or '1st + place', as there are entries in the
 **            FTS index corresponding to both forms of the first token.
 **   </ol>
@@ -11764,11 +12145,11 @@ struct Fts5ExtensionApi {
 **
 **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
 **   xToken() is called. Multiple synonyms may be specified for a single token
-**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
+**   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
 **   There is no limit to the number of synonyms that may be provided for a
 **   single token.
 **
-**   In many cases, method (1) above is the best approach. It does not add 
+**   In many cases, method (1) above is the best approach. It does not add
 **   extra data to the FTS index or require FTS5 to query for multiple terms,
 **   so it is efficient in terms of disk space and query speed. However, it
 **   does not support prefix queries very well. If, as suggested above, the
@@ -11780,18 +12161,18 @@ struct Fts5ExtensionApi {
 **   will not match documents that contain the token "1st" (as the tokenizer
 **   will probably not map "1s" to any prefix of "first").
 **
-**   For full prefix support, method (3) may be preferred. In this case, 
+**   For full prefix support, method (3) may be preferred. In this case,
 **   because the index contains entries for both "first" and "1st", prefix
 **   queries such as 'fi*' or '1s*' will match correctly. However, because
 **   extra entries are added to the FTS index, this method uses more space
 **   within the database.
 **
 **   Method (2) offers a midpoint between (1) and (3). Using this method,
-**   a query such as '1s*' will match documents that contain the literal 
+**   a query such as '1s*' will match documents that contain the literal
 **   token "1st", but not "first" (assuming the tokenizer is not able to
 **   provide synonyms for prefixes). However, a non-prefix query like '1st'
 **   will match against "1st" and "first". This method does not require
-**   extra disk space, as no extra entries are added to the FTS index. 
+**   extra disk space, as no extra entries are added to the FTS index.
 **   On the other hand, it may require more CPU cycles to run MATCH queries,
 **   as separate queries of the FTS index are required for each synonym.
 **
@@ -11805,10 +12186,10 @@ typedef struct fts5_tokenizer fts5_tokenizer;
 struct fts5_tokenizer {
   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
   void (*xDelete)(Fts5Tokenizer*);
-  int (*xTokenize)(Fts5Tokenizer*, 
+  int (*xTokenize)(Fts5Tokenizer*,
       void *pCtx,
       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
-      const char *pText, int nText, 
+      const char *pText, int nText,
       int (*xToken)(
         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
         int tflags,         /* Mask of FTS5_TOKEN_* flags */
@@ -324,6 +324,19 @@ struct sqlite3_api_routines {
   int (*value_frombind)(sqlite3_value*);
   /* Version 3.30.0 and later */
   int (*drop_modules)(sqlite3*,const char**);
+  /* Version 3.31.0 and later */
+  sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
+  const char *(*uri_key)(const char*,int);
+  const char *(*filename_database)(const char*);
+  const char *(*filename_journal)(const char*);
+  const char *(*filename_wal)(const char*);
+  /* Version 3.32.0 and later */
+  char *(*create_filename)(const char*,const char*,const char*,
+                           int,const char**);
+  void (*free_filename)(char*);
+  sqlite3_file *(*database_file_object)(const char*);
+  /* Version 3.34.0 and later */
+  int (*txn_state)(sqlite3*,const char*);
 };
 
 /*
@@ -638,10 +651,22 @@ typedef int (*sqlite3_loadext_entry)(
 /* Version 3.26.0 and later */
 #define sqlite3_normalized_sql         sqlite3_api->normalized_sql
 /* Version 3.28.0 and later */
-#define sqlite3_stmt_isexplain         sqlite3_api->isexplain
-#define sqlite3_value_frombind         sqlite3_api->frombind
+#define sqlite3_stmt_isexplain         sqlite3_api->stmt_isexplain
+#define sqlite3_value_frombind         sqlite3_api->value_frombind
 /* Version 3.30.0 and later */
 #define sqlite3_drop_modules           sqlite3_api->drop_modules
+/* Version 3.31.0 and later */
+#define sqlite3_hard_heap_limit64      sqlite3_api->hard_heap_limit64
+#define sqlite3_uri_key                sqlite3_api->uri_key
+#define sqlite3_filename_database      sqlite3_api->filename_database
+#define sqlite3_filename_journal       sqlite3_api->filename_journal
+#define sqlite3_filename_wal           sqlite3_api->filename_wal
+/* Version 3.32.0 and later */
+#define sqlite3_create_filename        sqlite3_api->create_filename
+#define sqlite3_free_filename          sqlite3_api->free_filename
+#define sqlite3_database_file_object   sqlite3_api->database_file_object
+/* Version 3.34.0 and later */
+#define sqlite3_txn_state              sqlite3_api->txn_state
 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
 
 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
similarity index 98%
rename from pkgs/sqlite3.30.1.2/configure
rename to pkgs/sqlite3.34.0/configure
index 89fc130..6868954 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for sqlite 3.30.1.2.
+# Generated by GNU Autoconf 2.69 for sqlite 3.34.0.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='sqlite'
 PACKAGE_TARNAME='sqlite'
-PACKAGE_VERSION='3.30.1.2'
-PACKAGE_STRING='sqlite 3.30.1.2'
+PACKAGE_VERSION='3.34.0'
+PACKAGE_STRING='sqlite 3.34.0'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -627,7 +627,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -635,6 +634,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1292,7 +1293,7 @@ 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 sqlite 3.30.1.2 to adapt to many kinds of systems.
+\`configure' configures sqlite 3.34.0 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1353,7 +1354,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of sqlite 3.30.1.2:";;
+     short | recursive ) echo "Configuration of sqlite 3.34.0:";;
    esac
   cat <<\_ACEOF
 
@@ -1455,7 +1456,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-sqlite configure 3.30.1.2
+sqlite configure 3.34.0
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1866,7 +1867,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by sqlite $as_me 3.30.1.2, which was
+It was created by sqlite $as_me 3.34.0, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3376,10 +3377,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3413,12 +3410,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -4994,7 +4985,7 @@ $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5609,7 +5600,7 @@ $as_echo "#define SQLITE_THREADSAFE 1" >>confdefs.h
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6083,7 +6074,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6108,7 +6099,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6257,14 +6248,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6345,14 +6336,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6367,7 +6358,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6443,39 +6434,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -6600,8 +6558,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -6628,7 +6586,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -6697,8 +6655,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -6714,8 +6672,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -6724,8 +6682,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -6753,8 +6711,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -6777,7 +6735,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -6787,9 +6745,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -6854,8 +6825,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -6872,11 +6843,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -6894,7 +6865,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -6902,32 +6873,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7236,7 +7181,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7306,13 +7251,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7412,7 +7357,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7449,8 +7394,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -7749,6 +7694,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8143,7 +8090,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8157,11 +8103,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8329,7 +8270,7 @@ fi
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8355,7 +8296,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8443,14 +8384,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8458,9 +8399,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -9031,7 +8972,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by sqlite $as_me 3.30.1.2, which was
+This file was extended by sqlite $as_me 3.34.0, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9084,7 +9025,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-sqlite config.status 3.30.1.2
+sqlite config.status 3.34.0
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/sqlite3.30.1.2/configure.ac
rename to pkgs/sqlite3.34.0/configure.ac
index bbb3ba0..c527d6a 100755 (executable)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so you can encode the package version directly into the source files.
 #-----------------------------------------------------------------------
 
-AC_INIT([sqlite], [3.30.1.2])
+AC_INIT([sqlite], [3.34.0])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
similarity index 97%
rename from pkgs/sqlite3.30.1.2/generic/tclsqlite3.c
rename to pkgs/sqlite3.34.0/generic/tclsqlite3.c
index 4b8c3c8..52d332a 100644 (file)
@@ -222,7 +222,7 @@ struct SqliteDb {
 struct IncrblobChannel {
   sqlite3_blob *pBlob;      /* sqlite3 blob handle */
   SqliteDb *pDb;            /* Associated database connection */
-  int iSeek;                /* Current seek offset */
+  Tcl_WideInt iSeek;        /* Current seek offset */
   Tcl_Channel channel;      /* Channel identifier */
   IncrblobChannel *pNext;   /* Linked list of all open incrblob channels */
   IncrblobChannel *pPrev;   /* Linked list of all open incrblob channels */
@@ -295,6 +295,18 @@ static int SQLITE_TCLAPI incrblobClose(
   return TCL_OK;
 }
 
+static int SQLITE_TCLAPI incrblobClose2(
+  void *instanceData,
+  Tcl_Interp *interp,
+  int flags
+){
+  if( (flags&(TCL_CLOSE_READ|TCL_CLOSE_WRITE))==0 ){
+    return incrblobClose(instanceData, interp);
+  }
+  return EINVAL;
+}
+
+
 /*
 ** Read data from an incremental blob channel.
 */
@@ -305,7 +317,7 @@ static int SQLITE_TCLAPI incrblobInput(
   int *errorCodePtr
 ){
   IncrblobChannel *p = (IncrblobChannel *)instanceData;
-  int nRead = bufSize;         /* Number of bytes to read */
+  Tcl_WideInt nRead = bufSize; /* Number of bytes to read */
   int nBlob;                   /* Total size of the blob */
   int rc;                      /* sqlite error code */
 
@@ -363,6 +375,32 @@ static int SQLITE_TCLAPI incrblobOutput(
 /*
 ** Seek an incremental blob channel.
 */
+static Tcl_WideInt SQLITE_TCLAPI incrblobWideSeek(
+  void *instanceData,
+  Tcl_WideInt offset,
+  int seekMode,
+  int *errorCodePtr
+){
+  IncrblobChannel *p = (IncrblobChannel *)instanceData;
+
+  switch( seekMode ){
+    case SEEK_SET:
+      p->iSeek = offset;
+      break;
+    case SEEK_CUR:
+      p->iSeek += offset;
+      break;
+    case SEEK_END:
+      p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
+      break;
+    default:
+         *errorCodePtr = EINVAL;
+      return -1;
+  }
+
+  return p->iSeek;
+}
+
 static int SQLITE_TCLAPI incrblobSeek(
   void *instanceData,
   long offset,
@@ -381,8 +419,9 @@ static int SQLITE_TCLAPI incrblobSeek(
     case SEEK_END:
       p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset;
       break;
-
-    default: assert(!"Bad seekMode");
+    default:
+         *errorCodePtr = EINVAL;
+      return -1;
   }
 
   return p->iSeek;
@@ -393,6 +432,8 @@ static void SQLITE_TCLAPI incrblobWatch(
   void *instanceData,
   int mode
 ){
+  (void)instanceData;
+  (void)mode;
   /* NO-OP */
 }
 static int SQLITE_TCLAPI incrblobHandle(
@@ -400,12 +441,16 @@ static int SQLITE_TCLAPI incrblobHandle(
   int dir,
   void **hPtr
 ){
+  (void)instanceData;
+  (void)dir;
+  (void)hPtr;
+
   return TCL_ERROR;
 }
 
 static Tcl_ChannelType IncrblobChannelType = {
   "incrblob",                        /* typeName                             */
-  TCL_CHANNEL_VERSION_2,             /* version                              */
+  TCL_CHANNEL_VERSION_5,             /* version                              */
   incrblobClose,                     /* closeProc                            */
   incrblobInput,                     /* inputProc                            */
   incrblobOutput,                    /* outputProc                           */
@@ -414,11 +459,13 @@ static Tcl_ChannelType IncrblobChannelType = {
   0,                                 /* getOptionProc                        */
   incrblobWatch,                     /* watchProc (this is a no-op)          */
   incrblobHandle,                    /* getHandleProc (always returns error) */
-  0,                                 /* close2Proc                           */
+  incrblobClose2,                    /* close2Proc                           */
   0,                                 /* blockModeProc                        */
   0,                                 /* flushProc                            */
   0,                                 /* handlerProc                          */
-  0,                                 /* wideSeekProc                         */
+  incrblobWideSeek,                  /* wideSeekProc                         */
+  0,
+  0,
 };
 
 /*
@@ -485,13 +532,15 @@ static int createIncrblobChannel(
 ** or {...} or ; to be seen anywhere.  Most callback scripts consist
 ** of just a single procedure name and they meet this requirement.
 */
-static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){
+static int safeToUseEvalObjv(Tcl_Interp *dummy, Tcl_Obj *pCmd){
   /* We could try to do something with Tcl_Parse().  But we will instead
   ** just do a search for forbidden characters.  If any of the forbidden
   ** characters appear in pCmd, we will report the string as unsafe.
   */
   const char *z;
   int n;
+  (void)dummy;
+
   z = Tcl_GetStringFromObj(pCmd, &n);
   while( n-- > 0 ){
     int c = *(z++);
@@ -667,6 +716,8 @@ static int DbTraceHandler(
 ){
   SqliteDb *pDb = (SqliteDb*)cd;
   Tcl_DString str;
+  (void)type;
+  (void)pd;
 
   Tcl_DStringInit(&str);
   Tcl_DStringAppend(&str, pDb->zTrace, -1);
@@ -769,6 +820,7 @@ static int DbProfileHandler(
   Tcl_DString str;
   char zTm[100];
   sqlite3_stmt *pStmt = (sqlite3_stmt *)pd;
+  (void)type;
 
   sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", (Tcl_WideInt)(size_t)xd);
   Tcl_DStringInit(&str);
@@ -821,6 +873,7 @@ static int DbWalHandler(
   Tcl_Obj *p;
   SqliteDb *pDb = (SqliteDb*)clientData;
   Tcl_Interp *interp = pDb->interp;
+  (void)db;
   assert(pDb->pWalHook);
 
   assert( db==pDb->db );
@@ -937,6 +990,9 @@ static void tclCollateNeeded(
 ){
   SqliteDb *pDb = (SqliteDb *)pCtx;
   Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded);
+  (void)db;
+  (void)enc;
+
   Tcl_IncrRefCount(pScript);
   Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1));
   Tcl_EvalObjEx(pDb->interp, pScript, 0);
@@ -1068,7 +1124,7 @@ static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
         ** has no string representation. */
         eType = SQLITE_BLOB;
       }else if( (c=='b' && ((strcmp(zType,"boolean")==0)
-             || (strcmp(zType,"booleanString")==0)))
+             || (strcmp(zType,"booleanString")==0)) && pVar->bytes==0 )
              || (c=='w' && strcmp(zType,"wideInt")==0)
              || (c=='i' && strcmp(zType,"int")==0) 
       ){
@@ -1092,16 +1148,16 @@ static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){
           sqlite3_result_int64(context, v);
           break;
         }
-        /* fall-through */
       }
+      /* FALLTHRU */
       case SQLITE_FLOAT: {
         double r;
         if( TCL_OK==Tcl_GetDoubleFromObj(0, pVar, &r) ){
           sqlite3_result_double(context, r);
           break;
         }
-        /* fall-through */
       }
+      /* FALLTHRU */
       default: {
         data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
         sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT);
@@ -1483,7 +1539,7 @@ static int dbPrepareAndBind(
           Tcl_IncrRefCount(pVar);
           pPreStmt->apParm[iParm++] = pVar;
         }else if( c=='b' && (strcmp(zType,"boolean")==0 ||
-              strcmp(zType,"booleanString")==0) ){
+              strcmp(zType,"booleanString")==0) && pVar->bytes==0){
           Tcl_GetBooleanFromObj(interp, pVar, &n);
           sqlite3_bind_int(pStmt, i, n);
         }else if( c=='d' && strcmp(zType,"double")==0 ){
@@ -2392,23 +2448,25 @@ static int SQLITE_TCLAPI DbObjCmd(
       const char *zName;
       int op;
     } aDbConfig[] = {
+        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
+        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
+        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
         { "enable_fkey",        SQLITE_DBCONFIG_ENABLE_FKEY           },
+        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
         { "enable_trigger",     SQLITE_DBCONFIG_ENABLE_TRIGGER        },
         { "enable_view",        SQLITE_DBCONFIG_ENABLE_VIEW           },
         { "fts3_tokenizer",     SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER },
+        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
+        { "legacy_file_format", SQLITE_DBCONFIG_LEGACY_FILE_FORMAT    },
         { "load_extension",     SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION },
         { "no_ckpt_on_close",   SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE      },
-        { "enable_qpsg",        SQLITE_DBCONFIG_ENABLE_QPSG           },
-        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
         { "reset_database",     SQLITE_DBCONFIG_RESET_DATABASE        },
-        { "defensive",          SQLITE_DBCONFIG_DEFENSIVE             },
+        { "trigger_eqp",        SQLITE_DBCONFIG_TRIGGER_EQP           },
+        { "trusted_schema",     SQLITE_DBCONFIG_TRUSTED_SCHEMA        },
         { "writable_schema",    SQLITE_DBCONFIG_WRITABLE_SCHEMA       },
-        { "legacy_alter_table", SQLITE_DBCONFIG_LEGACY_ALTER_TABLE    },
-        { "dqs_dml",            SQLITE_DBCONFIG_DQS_DML               },
-        { "dqs_ddl",            SQLITE_DBCONFIG_DQS_DDL               },
     };
     Tcl_Obj *pResult;
-    int ii;
+    size_t ii;
     if( objc>4 ){
       Tcl_WrongNumArgs(interp, 2, objv, "?OPTION? ?BOOLEAN?");
       return TCL_ERROR;
@@ -2871,6 +2929,7 @@ deserialize_error:
   **         --argcount N           Function has exactly N arguments
   **         --deterministic        The function is pure
   **         --directonly           Prohibit use inside triggers and views
+  **         --innocuous            Has no side effects or information leaks
   **         --returntype TYPE      Specify the return type of the function
   */
   case DB_FUNCTION: {
@@ -2907,6 +2966,9 @@ deserialize_error:
       if( n>1 && strncmp(z, "-directonly",n)==0 ){
         flags |= SQLITE_DIRECTONLY;
       }else
+      if( n>1 && strncmp(z, "-innocuous",n)==0 ){
+        flags |= SQLITE_INNOCUOUS;
+      }else
       if( n>1 && strncmp(z, "-returntype", n)==0 ){
         const char *const azType[] = {"integer", "real", "text", "blob", "any", 0};
         assert( SQLITE_INTEGER==1 && SQLITE_FLOAT==2 && SQLITE_TEXT==3 );
@@ -2923,7 +2985,7 @@ deserialize_error:
       }else{
         Tcl_AppendResult(interp, "bad option \"", z,
             "\": must be -argcount, -deterministic, -directonly,"
-            " or -returntype", (char*)0
+            " -innocuous, or -returntype", (char*)0
         );
         return TCL_ERROR;
       }
@@ -3140,22 +3202,10 @@ deserialize_error:
   ** Change the encryption key on the currently open database.
   */
   case DB_REKEY: {
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-    int nKey;
-    void *pKey;
-#endif
     if( objc!=3 ){
       Tcl_WrongNumArgs(interp, 2, objv, "KEY");
       return TCL_ERROR;
     }
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-    pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey);
-    rc = sqlite3_rekey(pDb->db, pKey, nKey);
-    if( rc ){
-      Tcl_AppendResult(interp, sqlite3_errstr(rc), (char*)0);
-      rc = TCL_ERROR;
-    }
-#endif
     break;
   }
 
@@ -3721,10 +3771,8 @@ static int sqliteCmdUsage(
 ){
   Tcl_WrongNumArgs(interp, 1, objv,
     "HANDLE ?FILENAME? ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?"
+    " ?-nofollow BOOLEAN?"
     " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN? ?-uri BOOLEAN?"
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-    " ?-key CODECKEY?"
-#endif
   );
   return TCL_ERROR;
 }
@@ -3732,6 +3780,7 @@ static int sqliteCmdUsage(
 /*
 **   sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN?
 **                           ?-create BOOLEAN? ?-nomutex BOOLEAN?
+**                           ?-nofollow BOOLEAN?
 **
 ** This is the main Tcl command.  When the "sqlite" Tcl command is
 ** invoked, this routine runs to process that command.
@@ -3757,12 +3806,10 @@ static int SQLITE_TCLAPI DbMain(
   const char *zFile = 0;
   const char *zVfs = 0;
   int flags;
+  int bTranslateFileName = 1;
   Tcl_DString translatedFilename;
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-  void *pKey = 0;
-  int nKey = 0;
-#endif
   int rc;
+  (void)cd;
 
   /* In normal use, each TCL interpreter runs in a single thread.  So
   ** by default, we can turn off mutexing on SQLite database connections.
@@ -3788,11 +3835,7 @@ static int SQLITE_TCLAPI DbMain(
       return TCL_OK;
     }
     if( strcmp(zArg,"-has-codec")==0 ){
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-      Tcl_AppendResult(interp,"1",(char*)0);
-#else
       Tcl_AppendResult(interp,"0",(char*)0);
-#endif
       return TCL_OK;
     }
     if( zArg[0]=='-' ) return sqliteCmdUsage(interp, objv);
@@ -3807,9 +3850,7 @@ static int SQLITE_TCLAPI DbMain(
     if( i==objc-1 ) return sqliteCmdUsage(interp, objv);
     i++;
     if( strcmp(zArg,"-key")==0 ){
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-      pKey = Tcl_GetByteArrayFromObj(objv[i], &nKey);
-#endif
+      /* no-op */
     }else if( strcmp(zArg, "-vfs")==0 ){
       zVfs = Tcl_GetString(objv[i]);
     }else if( strcmp(zArg, "-readonly")==0 ){
@@ -3830,6 +3871,14 @@ static int SQLITE_TCLAPI DbMain(
       }else{
         flags &= ~SQLITE_OPEN_CREATE;
       }
+    }else if( strcmp(zArg, "-nofollow")==0 ){
+      int b;
+      if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
+      if( b ){
+        flags |= SQLITE_OPEN_NOFOLLOW;
+      }else{
+        flags &= ~SQLITE_OPEN_NOFOLLOW;
+      }
     }else if( strcmp(zArg, "-nomutex")==0 ){
       int b;
       if( Tcl_GetBooleanFromObj(interp, objv[i], &b) ) return TCL_ERROR;
@@ -3856,6 +3905,10 @@ static int SQLITE_TCLAPI DbMain(
       }else{
         flags &= ~SQLITE_OPEN_URI;
       }
+    }else if( strcmp(zArg, "-translatefilename")==0 ){
+      if( Tcl_GetBooleanFromObj(interp, objv[i], &bTranslateFileName) ){
+        return TCL_ERROR;
+      }
     }else{
       Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
       return TCL_ERROR;
@@ -3865,9 +3918,13 @@ static int SQLITE_TCLAPI DbMain(
   p = (SqliteDb*)Tcl_Alloc( sizeof(*p) );
   memset(p, 0, sizeof(*p));
   if( zFile==0 ) zFile = "";
-  zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
+  if( bTranslateFileName ){
+    zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename);
+  }
   rc = sqlite3_open_v2(zFile, &p->db, flags, zVfs);
-  Tcl_DStringFree(&translatedFilename);
+  if( bTranslateFileName ){
+    Tcl_DStringFree(&translatedFilename);
+  }
   if( p->db ){
     if( SQLITE_OK!=sqlite3_errcode(p->db) ){
       zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db));
@@ -3877,11 +3934,6 @@ static int SQLITE_TCLAPI DbMain(
   }else{
     zErrMsg = sqlite3_mprintf("%s", sqlite3_errstr(rc));
   }
-#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_CODEC_FROM_TCL)
-  if( p->db ){
-    sqlite3_key(p->db, pKey, nKey);
-  }
-#endif
   if( p->db==0 ){
     Tcl_AppendResult(interp, zErrMsg, (char*)0);
     Tcl_Free((char*)p);
@@ -3917,6 +3969,7 @@ typedef struct {
   const struct TclStubs *stubTable;
 } PrivateTclInterp;
 static const char *Tcl_InitStubs(Tcl_Interp *interp, const char *version, int exact) {
+  (void)exact;
   tclStubsPtr = ((PrivateTclInterp *)interp)->stubTable;
   if (tclStubsPtr->magic != TCL_STUB_MAGIC) {
     ((PrivateTclInterp *)interp)->result = (char *)"interpreter uses an incompatible stubs mechanism";
@@ -3968,15 +4021,15 @@ DLLEXPORT int Sqlite3_Init(Tcl_Interp *interp){
   return rc;
 }
 DLLEXPORT int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); }
-DLLEXPORT int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
-DLLEXPORT int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; }
+DLLEXPORT int Sqlite3_Unload(Tcl_Interp *interp, int flags){ (void)interp;(void)flags;return TCL_OK; }
+DLLEXPORT int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ (void)interp;(void)flags;return TCL_OK; }
 
 /* Because it accesses the file-system and uses persistent state, SQLite
 ** is not considered appropriate for safe interpreters.  Hence, we cause
 ** the _SafeInit() interfaces return TCL_ERROR.
 */
-DLLEXPORT int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_ERROR; }
-DLLEXPORT int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){return TCL_ERROR;}
+DLLEXPORT int Sqlite3_SafeInit(Tcl_Interp *interp){ (void)interp;return TCL_ERROR; }
+DLLEXPORT int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){(void)interp;(void)flags;return TCL_ERROR;}
 
 
 
similarity index 55%
rename from pkgs/sqlite3.30.1.2/tclconfig/install-sh
rename to pkgs/sqlite3.34.0/tclconfig/install-sh
index 7c34c3f..21b733a 100755 (executable)
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-04-20.01; # UTC
+scriptversion=2020-07-26.22; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -35,25 +35,21 @@ scriptversion=2011-04-20.01; # UTC
 # FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
+# '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.
 
+tab='  '
 nl='
 '
-IFS=" ""       $nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,22 +64,15 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
 mode=0755
 
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
 chgrpcmd=
 chmodcmd=$chmodprog
 chowncmd=
@@ -97,7 +86,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -120,7 +109,7 @@ Options:
   -m MODE       $chmodprog installed files to MODE.
   -o USER       $chownprog installed files to USER.
   -s            $stripprog installed files.
-  -S            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
   -t DIRECTORY  install into DIRECTORY.
   -T            report an error if DSTFILE is a directory.
 
@@ -138,45 +127,60 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-       shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-       shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
     -S) stripcmd="$stripprog $2"
-       shift;;
+        shift;;
 
-    -t) dst_arg=$2
-       shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)        shift
-       break;;
+    --) shift
+        break;;
 
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -190,6 +194,10 @@ if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
     fi
     shift # arg
     dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
   done
 fi
 
@@ -198,12 +206,21 @@ if test $# -eq 0; then
     echo "$0: no input file specified." >&2
     exit 1
   fi
-  # It's OK to call `install-sh -d' without argument.
+  # It's OK to call 'install-sh -d' without argument.
   # This can happen when creating conditional directories.
   exit 0
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -219,16 +236,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -236,9 +253,9 @@ fi
 
 for src
 do
-  # Protect names starting with `-'.
+  # Protect names problematic for 'test' and other utilities.
   case $src in
-    -*) src=./$src;;
+    -* | [=\(\)!]) src=./$src;;
   esac
 
   if test -n "$dir_arg"; then
@@ -260,185 +277,150 @@ do
       echo "$0: no destination specified." >&2
       exit 1
     fi
-
     dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
 
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
+    # If destination is a directory, append the input filename.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
-      dst=$dstdir/`basename "$src"`
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
   fi
 
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
   obsolete_mkdir_used=false
 
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
        else
-         mkdir_mode=
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
        fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
+       trap '' 0;;
     esac
 
     if
       $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
 
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # mkdir does not conform to POSIX,
       # or it failed possibly due to a race condition.  Create the
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -451,14 +433,25 @@ do
   else
 
     # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
 
     # Trap to clean up those temp files at exit.
     trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
 
     # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
 
     # and set any options; do chmod last to preserve setuid bits.
     #
@@ -473,15 +466,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -494,24 +484,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
@@ -520,9 +510,9 @@ do
 done
 
 # Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
+# eval: (add-hook 'before-save-hook 'time-stamp)
 # time-stamp-start: "scriptversion="
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
+# time-stamp-time-zone: "UTC0"
 # time-stamp-end: "; # UTC"
-# End:
+# End:
\ No newline at end of file
similarity index 95%
rename from pkgs/sqlite3.30.1.2/tclconfig/tcl.m4
rename to pkgs/sqlite3.34.0/tclconfig/tcl.m4
index 7d901f9..8d24e7f 100644 (file)
@@ -50,9 +50,9 @@ AC_DEFUN([TEA_PATH_TCLCONFIG], [
        # we reset no_tcl in case something fails here
        no_tcl=true
        AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
+           AS_HELP_STRING([--with-tcl],
                [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
+           [with_tclconfig="${withval}"])
        AC_MSG_CHECKING([for Tcl configuration])
        AC_CACHE_VAL(ac_cv_c_tclconfig,[
 
@@ -212,9 +212,9 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
        # we reset no_tk in case something fails here
        no_tk=true
        AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
+           AS_HELP_STRING([--with-tk],
                [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
+           [with_tkconfig="${withval}"])
        AC_MSG_CHECKING([for Tk configuration])
        AC_CACHE_VAL(ac_cv_c_tkconfig,[
 
@@ -266,9 +266,6 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
                        `ls -d /Library/Frameworks 2>/dev/null` \
                        `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
                        ; do
                    if test -f "$i/Tk.framework/tkConfig.sh" ; then
                        ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
@@ -285,10 +282,10 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                        `ls -d /usr/local/lib 2>/dev/null` \
                        `ls -d /usr/contrib/lib 2>/dev/null` \
                        `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
                        `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
@@ -375,10 +372,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
         AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -412,12 +405,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
     AC_SUBST(TCL_VERSION)
     AC_SUBST(TCL_PATCH_LEVEL)
     AC_SUBST(TCL_BIN_DIR)
@@ -493,10 +480,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
         AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
     # If the TK_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TK_LIB_SPEC will be set to the value
@@ -530,12 +513,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
        esac
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
     # TEA specific: Ensure windowingsystem is defined
     if test "${TEA_PLATFORM}" = "unix" ; then
        case ${TK_DEFS} in
@@ -592,14 +569,14 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -607,9 +584,9 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -650,14 +627,14 @@ AC_DEFUN([TEA_PROG_WISH], [
     if test -f "${TK_BIN_DIR}/Makefile" ; then
         # tkConfig.sh is in Tk build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             WISH_PROG="${TK_BIN_DIR}/wish"
@@ -665,9 +642,9 @@ AC_DEFUN([TEA_PROG_WISH], [
     else
         # tkConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
         else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
         fi
         list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
@@ -713,7 +690,7 @@ AC_DEFUN([TEA_PROG_WISH], [
 AC_DEFUN([TEA_ENABLE_SHARED], [
     AC_MSG_CHECKING([how to build libraries])
     AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
+       AS_HELP_STRING([--enable-shared],
            [build and link with shared libraries (default: on)]),
        [shared_ok=$enableval], [shared_ok=yes])
 
@@ -725,7 +702,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
     fi
 
     AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
+       AS_HELP_STRING([--enable-stubs],
            [build and link with stub libraries. Always true for shared builds (default: on)]),
        [stubs_ok=$enableval], [stubs_ok=yes])
 
@@ -797,7 +774,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
 
 AC_DEFUN([TEA_ENABLE_THREADS], [
     AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
+       AS_HELP_STRING([--enable-threads],
            [build with threads (default: on)]),
        [tcl_ok=$enableval], [tcl_ok=yes])
 
@@ -911,8 +888,6 @@ AC_DEFUN([TEA_ENABLE_THREADS], [
 #                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
 #              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
 #                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
 #------------------------------------------------------------------------
 
 AC_DEFUN([TEA_ENABLE_SYMBOLS], [
@@ -920,10 +895,9 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
     AC_REQUIRE([TEA_CONFIG_CFLAGS])
     AC_MSG_CHECKING([for build with symbols])
     AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
+       AS_HELP_STRING([--enable-symbols],
            [build with debugging symbols (default: off)]),
        [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -935,13 +909,8 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
            AC_MSG_RESULT([yes (standard debugging)])
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
     AC_SUBST(CFLAGS_DEFAULT)
     AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
 
     if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
        AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
@@ -976,7 +945,7 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
 
 AC_DEFUN([TEA_ENABLE_LANGINFO], [
     AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
+       AS_HELP_STRING([--enable-langinfo],
            [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
        [langinfo_ok=$enableval], [langinfo_ok=yes])
 
@@ -1108,7 +1077,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit support is requested])
     AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
+       AS_HELP_STRING([--enable-64bit],
            [enable 64bit support (default: off)]),
        [do64bit=$enableval], [do64bit=no])
     AC_MSG_RESULT([$do64bit])
@@ -1117,7 +1086,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
     AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
+       AS_HELP_STRING([--enable-64bit-vis],
            [enable 64bit Sparc VIS support (default: off)]),
        [do64bitVIS=$enableval], [do64bitVIS=no])
     AC_MSG_RESULT([$do64bitVIS])
@@ -1146,7 +1115,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if rpath support is requested])
     AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
+       AS_HELP_STRING([--disable-rpath],
            [disable rpath support (default: on)]),
        [doRpath=$enableval], [doRpath=yes])
     AC_MSG_RESULT([$doRpath])
@@ -1260,14 +1229,14 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -1336,11 +1305,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
                ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ], [
                AS_IF([test "$GCC" = yes], [
                    SHLIB_LD='${CC} -shared -Wl,-bexpall'
@@ -1349,7 +1318,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    LDFLAGS="$LDFLAGS -brtl"
                ])
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1385,19 +1354,6 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -1435,8 +1391,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ])
            AS_IF([test "$GCC" = yes], [
@@ -1455,7 +1411,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
                            AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
@@ -1476,8 +1432,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ]) ;;
        IRIX-5.*)
@@ -1486,16 +1442,16 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            ;;
        IRIX-6.*)
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            AS_IF([test "$GCC" = yes], [
                CFLAGS="$CFLAGS -mabi=n32"
                LDFLAGS="$LDFLAGS -mabi=n32"
@@ -1517,8 +1473,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
 
            # Check to enable 64-bit flags for compiler/linker
 
@@ -1533,7 +1489,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                ])
            ])
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -1543,8 +1499,19 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
            AS_IF([test $do64bit = yes], [
@@ -1574,8 +1541,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            LD_FLAGS="-Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            ;;
        OpenBSD-*)
            arch=`arch -s`
@@ -1590,10 +1557,10 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -1610,37 +1577,13 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            LDFLAGS="$LDFLAGS -export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
            LIBS=`echo $LIBS | sed s/-pthread//`
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -1774,7 +1717,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            ])
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
@@ -1827,11 +1770,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ], [
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1897,7 +1840,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                AS_IF([test "$do64bit_ok" = yes], [
                    AS_IF([test "$arch" = "sparcv9 sparc"], [
@@ -1924,8 +1867,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ])
            ;;
        UNIX_SV* | UnixWare-5*)
@@ -2091,6 +2034,8 @@ dnl # preprocessing tests use only CPPFLAGS.
     AC_SUBST(CFLAGS_DEBUG)
     AC_SUBST(CFLAGS_OPTIMIZE)
     AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
 
     AC_SUBST(STLIB_LD)
     AC_SUBST(SHLIB_LD)
@@ -2374,6 +2319,7 @@ AC_DEFUN([TEA_BLOCKING_STYLE], [
 #              HAVE_TM_GMTOFF
 #              HAVE_TM_TZADJ
 #              HAVE_TIMEZONE_VAR
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TIME_HANDLER], [
@@ -2381,7 +2327,7 @@ AC_DEFUN([TEA_TIME_HANDLER], [
     AC_HEADER_TIME
     AC_STRUCT_TIMEZONE
 
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
 
     AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
        AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
@@ -2449,6 +2395,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
     if test "$tcl_strtod" = 1; then
        AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
            AC_TRY_RUN([
+               #include <stdlib.h>
                extern double strtod();
                int main() {
                    char *infString="Inf", *nanString="NaN", *spaceString=" ";
@@ -2478,6 +2425,81 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 ])
 
 #--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
 # TEA_TCL_EARLY_FLAGS
 #
 #      Check for what flags are needed to be passed so the correct OS
@@ -2492,6 +2514,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 #              _ISOC99_SOURCE
 #              _LARGEFILE64_SOURCE
 #              _LARGEFILE_SOURCE64
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TCL_EARLY_FLAG],[
@@ -2912,7 +2935,7 @@ AC_DEFUN([TEA_ADD_LIBS], [
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3099,7 +3122,7 @@ AC_DEFUN([TEA_SETUP_COMPILER], [
 AC_DEFUN([TEA_MAKE_LIB], [
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        AC_EGREP_CPP([manifest needed], [
 #if defined(_MSC_VER) && _MSC_VER >= 1400
 print("manifest needed")
@@ -3114,7 +3137,7 @@ print("manifest needed")
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -3856,11 +3879,11 @@ AC_DEFUN([TEA_EXPORT_CONFIG], [
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
     else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
     $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
similarity index 95%
rename from pkgs/thread2.8.5/win/rules.vc
rename to pkgs/sqlite3.34.0/win/rules.vc
index 325357c..2061e9b 100644 (file)
@@ -6,7 +6,7 @@
 # compiler switches, defining common targets and macros. The Tcl makefile\r
 # directly includes this. Extensions include it via "rules-ext.vc".\r
 #\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
@@ -24,7 +24,7 @@ _RULES_VC = 1
 # For modifications that are not backward-compatible, you *must* change\r
 # the major version.\r
 RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
+RULES_VERSION_MINOR = 5\r
 \r
 # The PROJECT macro must be defined by parent makefile.\r
 !if "$(PROJECT)" == ""\r
@@ -985,6 +985,19 @@ VERSION         = $(DOTVERSION:.=)
 \r
 !endif # $(DOING_TCL) ... etc.\r
 \r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
 ################################################################\r
 # 10. Construct output directory and file paths\r
 # Figure-out how to name our intermediate and output directories.\r
@@ -1508,7 +1521,7 @@ GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)
 RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
            $(TCL_INCLUDES) \\r
            /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           /DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
            /DDOTVERSION=\"$(DOTVERSION)\" \\r
            /DVERSION=\"$(VERSION)\" \\r
            /DSUFX=\"$(SUFX)\" \\r
similarity index 98%
rename from pkgs/tdbc1.1.1/Makefile.in
rename to pkgs/tdbc1.1.2/Makefile.in
index 4a7665e..ee02c14 100644 (file)
@@ -101,8 +101,6 @@ CFLAGS_WARNING      = @CFLAGS_WARNING@
 EXEEXT         = @EXEEXT@
 LDFLAGS_DEFAULT        = @LDFLAGS_DEFAULT@
 MAKE_LIB       = @MAKE_LIB@
-MAKE_SHARED_LIB        = @MAKE_SHARED_LIB@
-MAKE_STATIC_LIB        = @MAKE_STATIC_LIB@
 MAKE_STUB_LIB  = @MAKE_STUB_LIB@
 OBJEXT         = @OBJEXT@
 RANLIB         = @RANLIB@
@@ -156,7 +154,7 @@ PKG_CFLAGS  = @PKG_CFLAGS@
 # you do not compile with a similar machine setup as the Tcl core was
 # compiled with.
 #DEFS          = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
-DEFS           = @DEFS@ $(PKG_CFLAGS)
+DEFS           = @DEFS@ $(PKG_CFLAGS) -DTCL_NO_DEPRECATED=1
 
 # Move pkgIndex.tcl to 'BINARIES' var if it is generated in the Makefile
 CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl tdbcConfig.sh
@@ -166,7 +164,10 @@ CPPFLAGS   = @CPPFLAGS@
 LIBS           = @PKG_LIBS@ @LIBS@
 AR             = @AR@
 CFLAGS         = @CFLAGS@
-COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LDFLAGS                = @LDFLAGS@
+LDFLAGS_DEFAULT                        = @LDFLAGS_DEFAULT@
+COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
+                         $(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
 
 GDB            = gdb
 VALGRIND       = valgrind
similarity index 98%
rename from pkgs/tdbc1.1.1/README
rename to pkgs/tdbc1.1.2/README
index 1e2a5f6..c921c92 100644 (file)
@@ -1,6 +1,6 @@
 README: tdbc
 
-    This is the 1.1.1 source distribution of Tcl Database Connectivity
+    This is the 1.1.2 source distribution of Tcl Database Connectivity
     (TDBC). TDBC is available from a Fossil version control repository
     at http://tdbc.tcl.tk/ .
 
similarity index 98%
rename from pkgs/tdbc1.1.1/configure
rename to pkgs/tdbc1.1.2/configure
index e5f6d7d..8711596 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for tdbc 1.1.1.
+# Generated by GNU Autoconf 2.69 for tdbc 1.1.2.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='tdbc'
 PACKAGE_TARNAME='tdbc'
-PACKAGE_VERSION='1.1.1'
-PACKAGE_STRING='tdbc 1.1.1'
+PACKAGE_VERSION='1.1.2'
+PACKAGE_STRING='tdbc 1.1.2'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -640,7 +640,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -648,6 +647,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1316,7 +1317,7 @@ 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 tdbc 1.1.1 to adapt to many kinds of systems.
+\`configure' configures tdbc 1.1.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1377,7 +1378,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of tdbc 1.1.1:";;
+     short | recursive ) echo "Configuration of tdbc 1.1.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1478,7 +1479,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-tdbc configure 1.1.1
+tdbc configure 1.1.2
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1843,7 +1844,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by tdbc $as_me 1.1.1, which was
+It was created by tdbc $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3353,10 +3354,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3390,12 +3387,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3698,7 +3689,7 @@ $as_echo_n "checking For TCLOO_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3712,7 +3703,7 @@ $as_echo "using TCLOO_STUB_LIB_PATH ${TCLOO_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3741,7 +3732,7 @@ $as_echo_n "checking For tcloo_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3755,7 +3746,7 @@ $as_echo "using tcloo_STUB_LIB_PATH ${tcloo_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5292,7 +5283,7 @@ if test "${TCL_MAJOR_VERSION}" -eq 8 ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6241,7 +6232,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6266,7 +6257,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6415,14 +6406,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6503,14 +6494,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6525,7 +6516,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6601,39 +6592,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -6758,8 +6716,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -6786,7 +6744,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -6855,8 +6813,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -6872,8 +6830,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -6882,8 +6840,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -6911,8 +6869,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -6935,7 +6893,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -6945,9 +6903,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -7012,8 +6983,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -7030,11 +7001,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -7052,7 +7023,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -7060,32 +7031,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7394,7 +7339,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7464,13 +7409,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7570,7 +7515,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7607,8 +7552,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -7907,6 +7852,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8301,7 +8248,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8315,11 +8261,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8349,7 +8290,7 @@ $as_echo "enabled $tcl_ok debugging" >&6; }
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8375,7 +8316,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8463,14 +8404,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8478,9 +8419,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -8537,11 +8478,11 @@ fi
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="${libdir}/tdbc${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval tdbc_LIB_FLAG="-ltdbc${PACKAGE_VERSION}${DBGX}"
-       eval tdbc_STUB_LIB_FLAG="-ltdbcstub${PACKAGE_VERSION}${DBGX}"
+       eval tdbc_LIB_FLAG="-ltdbc${PACKAGE_VERSION}"
+       eval tdbc_STUB_LIB_FLAG="-ltdbcstub${PACKAGE_VERSION}"
     else
-       eval tdbc_LIB_FLAG="-ltdbc`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval tdbc_STUB_LIB_FLAG="-ltdbcstub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval tdbc_LIB_FLAG="-ltdbc`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval tdbc_STUB_LIB_FLAG="-ltdbcstub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     tdbc_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${tdbc_LIB_FLAG}"
     tdbc_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${tdbc_LIB_FLAG}"
@@ -9111,7 +9052,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by tdbc $as_me 1.1.1, which was
+This file was extended by tdbc $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9164,7 +9105,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-tdbc config.status 1.1.1
+tdbc config.status 1.1.2
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/tdbc1.1.1/configure.ac
rename to pkgs/tdbc1.1.2/configure.ac
index 2e8af69..f64a6a7 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([tdbc], [1.1.1])
+AC_INIT([tdbc], [1.1.2])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
similarity index 99%
rename from pkgs/tdbc1.1.1/generic/tdbc.c
rename to pkgs/tdbc1.1.2/generic/tdbc.c
index a74b4a0..a211cfb 100644 (file)
@@ -159,11 +159,13 @@ Tdbc_MapSqlState(const char* sqlstate)
 
 static int
 TdbcMapSqlStateObjCmd(
-    ClientData unused,         /* No client data */
+    ClientData dummy,          /* No client data */
     Tcl_Interp* interp,                /* Tcl interpreter */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
+    (void)dummy;
+
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "sqlstate");
        return TCL_ERROR;
similarity index 96%
rename from pkgs/tdbc1.1.1/generic/tdbc.h
rename to pkgs/tdbc1.1.2/generic/tdbc.h
index b17ed4a..6da6265 100644 (file)
@@ -59,8 +59,8 @@ DLLIMPORT int         Tdbc_Init(Tcl_Interp* interp);
  * appear near the top of configure.ac.
  */
 
-#define        TDBC_VERSION    "1.1.1"
-#define TDBC_PATCHLEVEL "1.1.1"
+#define        TDBC_VERSION    "1.1.2"
+#define TDBC_PATCHLEVEL "1.1.2"
 
 /*
  * Include the Stubs declarations for the public API, generated from
similarity index 99%
rename from pkgs/tdbc1.1.1/generic/tdbcTokenize.c
rename to pkgs/tdbc1.1.2/generic/tdbcTokenize.c
index 19e113a..27aaaeb 100644 (file)
@@ -188,13 +188,13 @@ Tdbc_TokenizeSql(
 
 MODULE_SCOPE int
 TdbcTokenizeObjCmd(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Obj* retval;
+    (void)dummy;
 
     /* Check param count */
 
similarity index 81%
rename from pkgs/itcl4.2.0/tclconfig/README.txt
rename to pkgs/tdbc1.1.2/tclconfig/README.txt
index 59b5a3e..715cb9d 100644 (file)
@@ -3,10 +3,10 @@ Architecture (TEA) extension.  For more information on TEA see:
 
        http://www.tcl.tk/doc/tea/
 
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
 
-       http://tcl.sourceforge.net/
+       https://core.tcl-lang.org/tclconfig
 
 This package is a freely available open source package.  You can do
 virtually anything you like with it, such as modifying it, redistributing
similarity index 55%
rename from pkgs/itcl4.2.0/tclconfig/install-sh
rename to pkgs/tdbc1.1.2/tclconfig/install-sh
index 7c34c3f..21b733a 100644 (file)
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-04-20.01; # UTC
+scriptversion=2020-07-26.22; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -35,25 +35,21 @@ scriptversion=2011-04-20.01; # UTC
 # FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
+# '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.
 
+tab='  '
 nl='
 '
-IFS=" ""       $nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,22 +64,15 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
 mode=0755
 
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
 chgrpcmd=
 chmodcmd=$chmodprog
 chowncmd=
@@ -97,7 +86,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -120,7 +109,7 @@ Options:
   -m MODE       $chmodprog installed files to MODE.
   -o USER       $chownprog installed files to USER.
   -s            $stripprog installed files.
-  -S            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
   -t DIRECTORY  install into DIRECTORY.
   -T            report an error if DSTFILE is a directory.
 
@@ -138,45 +127,60 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-       shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-       shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
     -S) stripcmd="$stripprog $2"
-       shift;;
+        shift;;
 
-    -t) dst_arg=$2
-       shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)        shift
-       break;;
+    --) shift
+        break;;
 
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -190,6 +194,10 @@ if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
     fi
     shift # arg
     dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
   done
 fi
 
@@ -198,12 +206,21 @@ if test $# -eq 0; then
     echo "$0: no input file specified." >&2
     exit 1
   fi
-  # It's OK to call `install-sh -d' without argument.
+  # It's OK to call 'install-sh -d' without argument.
   # This can happen when creating conditional directories.
   exit 0
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -219,16 +236,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -236,9 +253,9 @@ fi
 
 for src
 do
-  # Protect names starting with `-'.
+  # Protect names problematic for 'test' and other utilities.
   case $src in
-    -*) src=./$src;;
+    -* | [=\(\)!]) src=./$src;;
   esac
 
   if test -n "$dir_arg"; then
@@ -260,185 +277,150 @@ do
       echo "$0: no destination specified." >&2
       exit 1
     fi
-
     dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
 
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
+    # If destination is a directory, append the input filename.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
-      dst=$dstdir/`basename "$src"`
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
   fi
 
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
   obsolete_mkdir_used=false
 
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
        else
-         mkdir_mode=
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
        fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
+       trap '' 0;;
     esac
 
     if
       $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
 
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # mkdir does not conform to POSIX,
       # or it failed possibly due to a race condition.  Create the
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -451,14 +433,25 @@ do
   else
 
     # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
 
     # Trap to clean up those temp files at exit.
     trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
 
     # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
 
     # and set any options; do chmod last to preserve setuid bits.
     #
@@ -473,15 +466,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -494,24 +484,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
@@ -520,9 +510,9 @@ do
 done
 
 # Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
+# eval: (add-hook 'before-save-hook 'time-stamp)
 # time-stamp-start: "scriptversion="
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
+# time-stamp-time-zone: "UTC0"
 # time-stamp-end: "; # UTC"
-# End:
+# End:
\ No newline at end of file
similarity index 95%
rename from pkgs/itcl4.2.0/tclconfig/tcl.m4
rename to pkgs/tdbc1.1.2/tclconfig/tcl.m4
index 7d901f9..8d24e7f 100644 (file)
@@ -50,9 +50,9 @@ AC_DEFUN([TEA_PATH_TCLCONFIG], [
        # we reset no_tcl in case something fails here
        no_tcl=true
        AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
+           AS_HELP_STRING([--with-tcl],
                [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
+           [with_tclconfig="${withval}"])
        AC_MSG_CHECKING([for Tcl configuration])
        AC_CACHE_VAL(ac_cv_c_tclconfig,[
 
@@ -212,9 +212,9 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
        # we reset no_tk in case something fails here
        no_tk=true
        AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
+           AS_HELP_STRING([--with-tk],
                [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
+           [with_tkconfig="${withval}"])
        AC_MSG_CHECKING([for Tk configuration])
        AC_CACHE_VAL(ac_cv_c_tkconfig,[
 
@@ -266,9 +266,6 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
                        `ls -d /Library/Frameworks 2>/dev/null` \
                        `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
                        ; do
                    if test -f "$i/Tk.framework/tkConfig.sh" ; then
                        ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
@@ -285,10 +282,10 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                        `ls -d /usr/local/lib 2>/dev/null` \
                        `ls -d /usr/contrib/lib 2>/dev/null` \
                        `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
                        `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
@@ -375,10 +372,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
         AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -412,12 +405,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
     AC_SUBST(TCL_VERSION)
     AC_SUBST(TCL_PATCH_LEVEL)
     AC_SUBST(TCL_BIN_DIR)
@@ -493,10 +480,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
         AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
     # If the TK_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TK_LIB_SPEC will be set to the value
@@ -530,12 +513,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
        esac
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
     # TEA specific: Ensure windowingsystem is defined
     if test "${TEA_PLATFORM}" = "unix" ; then
        case ${TK_DEFS} in
@@ -592,14 +569,14 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -607,9 +584,9 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -650,14 +627,14 @@ AC_DEFUN([TEA_PROG_WISH], [
     if test -f "${TK_BIN_DIR}/Makefile" ; then
         # tkConfig.sh is in Tk build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             WISH_PROG="${TK_BIN_DIR}/wish"
@@ -665,9 +642,9 @@ AC_DEFUN([TEA_PROG_WISH], [
     else
         # tkConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
         else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
         fi
         list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
@@ -713,7 +690,7 @@ AC_DEFUN([TEA_PROG_WISH], [
 AC_DEFUN([TEA_ENABLE_SHARED], [
     AC_MSG_CHECKING([how to build libraries])
     AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
+       AS_HELP_STRING([--enable-shared],
            [build and link with shared libraries (default: on)]),
        [shared_ok=$enableval], [shared_ok=yes])
 
@@ -725,7 +702,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
     fi
 
     AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
+       AS_HELP_STRING([--enable-stubs],
            [build and link with stub libraries. Always true for shared builds (default: on)]),
        [stubs_ok=$enableval], [stubs_ok=yes])
 
@@ -797,7 +774,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
 
 AC_DEFUN([TEA_ENABLE_THREADS], [
     AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
+       AS_HELP_STRING([--enable-threads],
            [build with threads (default: on)]),
        [tcl_ok=$enableval], [tcl_ok=yes])
 
@@ -911,8 +888,6 @@ AC_DEFUN([TEA_ENABLE_THREADS], [
 #                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
 #              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
 #                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
 #------------------------------------------------------------------------
 
 AC_DEFUN([TEA_ENABLE_SYMBOLS], [
@@ -920,10 +895,9 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
     AC_REQUIRE([TEA_CONFIG_CFLAGS])
     AC_MSG_CHECKING([for build with symbols])
     AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
+       AS_HELP_STRING([--enable-symbols],
            [build with debugging symbols (default: off)]),
        [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -935,13 +909,8 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
            AC_MSG_RESULT([yes (standard debugging)])
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
     AC_SUBST(CFLAGS_DEFAULT)
     AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
 
     if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
        AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
@@ -976,7 +945,7 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
 
 AC_DEFUN([TEA_ENABLE_LANGINFO], [
     AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
+       AS_HELP_STRING([--enable-langinfo],
            [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
        [langinfo_ok=$enableval], [langinfo_ok=yes])
 
@@ -1108,7 +1077,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit support is requested])
     AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
+       AS_HELP_STRING([--enable-64bit],
            [enable 64bit support (default: off)]),
        [do64bit=$enableval], [do64bit=no])
     AC_MSG_RESULT([$do64bit])
@@ -1117,7 +1086,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
     AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
+       AS_HELP_STRING([--enable-64bit-vis],
            [enable 64bit Sparc VIS support (default: off)]),
        [do64bitVIS=$enableval], [do64bitVIS=no])
     AC_MSG_RESULT([$do64bitVIS])
@@ -1146,7 +1115,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if rpath support is requested])
     AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
+       AS_HELP_STRING([--disable-rpath],
            [disable rpath support (default: on)]),
        [doRpath=$enableval], [doRpath=yes])
     AC_MSG_RESULT([$doRpath])
@@ -1260,14 +1229,14 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -1336,11 +1305,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
                ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ], [
                AS_IF([test "$GCC" = yes], [
                    SHLIB_LD='${CC} -shared -Wl,-bexpall'
@@ -1349,7 +1318,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    LDFLAGS="$LDFLAGS -brtl"
                ])
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1385,19 +1354,6 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -1435,8 +1391,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ])
            AS_IF([test "$GCC" = yes], [
@@ -1455,7 +1411,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
                            AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
@@ -1476,8 +1432,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ]) ;;
        IRIX-5.*)
@@ -1486,16 +1442,16 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            ;;
        IRIX-6.*)
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            AS_IF([test "$GCC" = yes], [
                CFLAGS="$CFLAGS -mabi=n32"
                LDFLAGS="$LDFLAGS -mabi=n32"
@@ -1517,8 +1473,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
 
            # Check to enable 64-bit flags for compiler/linker
 
@@ -1533,7 +1489,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                ])
            ])
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -1543,8 +1499,19 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
            AS_IF([test $do64bit = yes], [
@@ -1574,8 +1541,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            LD_FLAGS="-Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            ;;
        OpenBSD-*)
            arch=`arch -s`
@@ -1590,10 +1557,10 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -1610,37 +1577,13 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            LDFLAGS="$LDFLAGS -export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
            LIBS=`echo $LIBS | sed s/-pthread//`
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -1774,7 +1717,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            ])
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
@@ -1827,11 +1770,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ], [
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1897,7 +1840,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                AS_IF([test "$do64bit_ok" = yes], [
                    AS_IF([test "$arch" = "sparcv9 sparc"], [
@@ -1924,8 +1867,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ])
            ;;
        UNIX_SV* | UnixWare-5*)
@@ -2091,6 +2034,8 @@ dnl # preprocessing tests use only CPPFLAGS.
     AC_SUBST(CFLAGS_DEBUG)
     AC_SUBST(CFLAGS_OPTIMIZE)
     AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
 
     AC_SUBST(STLIB_LD)
     AC_SUBST(SHLIB_LD)
@@ -2374,6 +2319,7 @@ AC_DEFUN([TEA_BLOCKING_STYLE], [
 #              HAVE_TM_GMTOFF
 #              HAVE_TM_TZADJ
 #              HAVE_TIMEZONE_VAR
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TIME_HANDLER], [
@@ -2381,7 +2327,7 @@ AC_DEFUN([TEA_TIME_HANDLER], [
     AC_HEADER_TIME
     AC_STRUCT_TIMEZONE
 
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
 
     AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
        AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
@@ -2449,6 +2395,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
     if test "$tcl_strtod" = 1; then
        AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
            AC_TRY_RUN([
+               #include <stdlib.h>
                extern double strtod();
                int main() {
                    char *infString="Inf", *nanString="NaN", *spaceString=" ";
@@ -2478,6 +2425,81 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 ])
 
 #--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
 # TEA_TCL_EARLY_FLAGS
 #
 #      Check for what flags are needed to be passed so the correct OS
@@ -2492,6 +2514,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 #              _ISOC99_SOURCE
 #              _LARGEFILE64_SOURCE
 #              _LARGEFILE_SOURCE64
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TCL_EARLY_FLAG],[
@@ -2912,7 +2935,7 @@ AC_DEFUN([TEA_ADD_LIBS], [
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3099,7 +3122,7 @@ AC_DEFUN([TEA_SETUP_COMPILER], [
 AC_DEFUN([TEA_MAKE_LIB], [
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        AC_EGREP_CPP([manifest needed], [
 #if defined(_MSC_VER) && _MSC_VER >= 1400
 print("manifest needed")
@@ -3114,7 +3137,7 @@ print("manifest needed")
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -3856,11 +3879,11 @@ AC_DEFUN([TEA_EXPORT_CONFIG], [
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
     else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
     $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
similarity index 94%
rename from pkgs/tdbc1.1.1/win/makefile.vc
rename to pkgs/tdbc1.1.2/win/makefile.vc
index f9ad562..5c9641a 100644 (file)
@@ -8,7 +8,7 @@
 #   nmake /s /nologo /f makefile.vc INSTALLDIR=c:\path\to\installdir\r
 #\r
 # For other build options (debug, static etc.)\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
similarity index 94%
rename from pkgs/sqlite3.30.1.2/win/rules-ext.vc
rename to pkgs/tdbc1.1.2/win/rules-ext.vc
index 531e070..6da5689 100644 (file)
@@ -31,7 +31,7 @@ macro to the name of the project makefile.
 # We extract version numbers using the nmakehlp program. For now use\r
 # the local copy of nmakehlp. Once we locate Tcl, we will use that\r
 # one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
 !endif\r
 \r
 # First locate the Tcl directory that we are working with.\r
similarity index 89%
rename from pkgs/sqlite3.30.1.2/win/rules.vc
rename to pkgs/tdbc1.1.2/win/rules.vc
index 325357c..13e3879 100644 (file)
@@ -6,7 +6,7 @@
 # compiler switches, defining common targets and macros. The Tcl makefile\r
 # directly includes this. Extensions include it via "rules-ext.vc".\r
 #\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
@@ -24,7 +24,7 @@ _RULES_VC = 1
 # For modifications that are not backward-compatible, you *must* change\r
 # the major version.\r
 RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
+RULES_VERSION_MINOR = 8\r
 \r
 # The PROJECT macro must be defined by parent makefile.\r
 !if "$(PROJECT)" == ""\r
@@ -302,7 +302,7 @@ TCLDIR          = $(_INSTALLDIR)\..
 _TCLDIR                = $(_INSTALLDIR)\..\r
 _TCL_H          = $(_TCLDIR)\include\tcl.h\r
 \r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !if [echo _TCLDIR = \> nmakehlp.out] \\r
    || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
@@ -313,7 +313,7 @@ TCLINSTALL      = 0
 TCLDIR         = $(_TCLDIR)\r
 _TCL_H          = $(_TCLDIR)\generic\tcl.h\r
 \r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !endif # TCLDIR\r
 \r
@@ -415,9 +415,6 @@ _INSTALLDIR=$(_INSTALLDIR)\lib
 # NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
 # MACHINE - same as $(ARCH) - legacy\r
 # _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
 \r
 cc32           = $(CC)   # built-in default.\r
 link32         = link\r
@@ -503,10 +500,6 @@ _VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -ou
 _VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
 !endif\r
 \r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
 ################################################################\r
 # 4. Build the nmakehlp program\r
 # This is a helper app we need to overcome nmake's limiting\r
@@ -514,7 +507,7 @@ CFG_ENCODING        = \"cp1252\"
 # information about supported compiler options etc.\r
 #\r
 # Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
+# in its own source. It will be kept updated there.\r
 #\r
 # Extensions built against an installed Tcl will use the installed\r
 # copy of Tcl's nmakehlp.c if there is one and their own version\r
@@ -537,7 +530,7 @@ NMAKEHLPC = nmakehlp.c
 !if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
 !endif\r
-!else # ! $(TCLINSTALL)\r
+!else # !$(TCLINSTALL)\r
 !if exist("$(_TCLDIR)\win\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
 !endif\r
@@ -659,8 +652,130 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 !endif\r
 !endif\r
 \r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
 ########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
 # Based on this, we will construct the actual switches to be passed to the\r
 # compiler and linker using the macros defined in the previous section.\r
 # The following macros are defined by this section based on OPTS\r
@@ -674,9 +789,10 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
 #           0 -> link to static C runtime for static Tcl build.\r
 #           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
 # TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
 # USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
 #           0 -> Use the non-thread allocator.\r
 # UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
@@ -685,7 +801,9 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
 #           configuration (ignored for Tcl itself)\r
 # _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
 # Further, LINKERFLAGS are modified based on above.\r
 \r
 # Default values for all the above\r
@@ -728,11 +846,8 @@ MSVCRT             = 0
 !else\r
 !if [nmakehlp -f $(OPTS) "msvcrt"]\r
 !message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
 !else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
 MSVCRT         = 0\r
 !endif\r
 !endif\r
@@ -741,24 +856,26 @@ MSVCRT            = 0
 !if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
 !message *** Doing staticpkg\r
 TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
 !endif\r
 \r
 !if [nmakehlp -f $(OPTS) "nothreads"]\r
 !message *** Compile explicitly for non-threaded tcl\r
 TCL_THREADS = 0\r
 USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
 !endif\r
 \r
+!if $(TCL_MAJOR_VERSION) == 8\r
 !if [nmakehlp -f $(OPTS) "time64bit"]\r
 !message *** Force 64-bit time_t\r
 _USE_64BIT_TIME_T = 1\r
 !endif\r
 \r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
 # Yes, it's weird that the "symbols" option controls DEBUG and\r
 # the "pdbs" option controls SYMBOLS. That's historical.\r
 !if [nmakehlp -f $(OPTS) "symbols"]\r
@@ -842,7 +959,7 @@ This compiler does not support profile guided optimization.
 !endif\r
 \r
 ################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
+# 8. Parse the STATS macro to configure code instrumentation\r
 # The following macros are set by this section:\r
 # TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
 #                 0 -> disables\r
@@ -872,7 +989,7 @@ TCL_COMPILE_DEBUG   = 0
 !endif\r
 \r
 ####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
 # The following macros are set by this section:\r
 # WARNINGS - compiler switches that control the warnings level\r
 # TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
@@ -904,86 +1021,6 @@ WARNINGS              = $(WARNINGS) -Wp64
 \r
 !endif\r
 \r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
 \r
 ################################################################\r
 # 10. Construct output directory and file paths\r
@@ -1029,7 +1066,7 @@ BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)
 BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
 !endif\r
 \r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
 SUFX       = $(SUFX:g=)\r
 !endif\r
 \r
@@ -1080,20 +1117,35 @@ OUT_DIR     = $(TMP_DIR)
 # The name of the stubs library for the project being built\r
 STUBPREFIX      = $(PROJECT)stub\r
 \r
+#\r
 # Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
+#\r
 \r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
 TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
 TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
 TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
 TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
 TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
 \r
 TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
 TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
 TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
 \r
-!else # ! $(DOING_TCL)\r
+!else # !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 \r
@@ -1115,6 +1167,7 @@ TCLIMPLIB = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\lib\r
 TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
 TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
 \r
@@ -1134,6 +1187,7 @@ TCLIMPLIB = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\library\r
 TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = $(_TCLDIR)\tools\r
 TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
 \r
@@ -1166,7 +1220,8 @@ WISH              = $(OUT_DIR)\$(WISHNAME)
 TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
 TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
 \r
 !else # effectively NEED_TK\r
 \r
@@ -1181,7 +1236,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
 !else # Building against Tk sources\r
+\r
 WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
 TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
@@ -1192,7 +1250,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
 !endif # TKINSTALL\r
+\r
 tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
 \r
 !endif # $(DOING_TK)\r
@@ -1233,6 +1294,7 @@ BIN_INSTALL_DIR           = $(_INSTALLDIR)\bin
 DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
 !if $(DOING_TCL)\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
 !else # DOING_TK\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
 !endif\r
@@ -1277,7 +1339,15 @@ INCLUDE_INSTALL_DIR      = $(_INSTALLDIR)\..\include
 # baselibs - minimum Windows libraries required. Parent makefile can\r
 #    define PRJ_LIBS before including rules.rc if additional libs are needed\r
 \r
-OPTDEFINES     = /DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) /DSTDC_HEADERS\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
 \r
 !if $(TCL_MEM_DEBUG)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
@@ -1293,6 +1363,11 @@ OPTDEFINES       = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1
 !endif\r
 !if $(STATIC_BUILD)\r
 OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
 !endif\r
 !if $(TCL_NO_DEPRECATED)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
@@ -1301,7 +1376,7 @@ OPTDEFINES        = $(OPTDEFINES) /DTCL_NO_DEPRECATED
 !if $(USE_STUBS)\r
 # Note we do not define USE_TCL_STUBS even when building tk since some\r
 # test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
 !if $(NEED_TK)\r
 USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
@@ -1322,15 +1397,20 @@ OPTDEFINES      = $(OPTDEFINES) /DTCL_CFG_PROFILED
 OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
 !endif\r
 !if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
 !endif\r
 \r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
 !if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
 !endif\r
 \r
 # _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
 COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
 \r
 # Like the TEA system only set this non empty for non-Tk extensions\r
 # Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
@@ -1455,18 +1535,6 @@ lflags   = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)
 lflags = $(lflags) -nodefaultlib:libucrt.lib\r
 !endif\r
 \r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
 dlllflags = $(lflags) -dll\r
 conlflags = $(lflags) -subsystem:console\r
 guilflags = $(lflags) -subsystem:windows\r
@@ -1508,7 +1576,7 @@ GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)
 RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
            $(TCL_INCLUDES) \\r
            /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           /DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
            /DDOTVERSION=\"$(DOTVERSION)\" \\r
            /DVERSION=\"$(VERSION)\" \\r
            /DSUFX=\"$(SUFX)\" \\r
@@ -1524,11 +1592,11 @@ default-target: $(DEFAULT_BUILD_TARGET)
 !if $(MULTIPLATFORM_INSTALL)\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !else\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !endif\r
 \r
 default-pkgindex-tea:\r
@@ -1574,6 +1642,8 @@ default-install-pdbs:
        @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
        @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
 \r
+# "emacs font-lock highlighting fix\r
+\r
 default-install-docs-html:\r
        @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
        @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
@@ -1636,7 +1706,7 @@ default-shell: default-setup $(PROJECT)
 !ifdef RCFILE\r
 \r
 # Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
+# and only the "main" rc must be passed to the resource compiler\r
 $(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
        $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
 \r
@@ -1690,7 +1760,7 @@ DISABLE_IMPLICIT_RULES = 0
 \r
 !if !$(DISABLE_IMPLICIT_RULES)\r
 # Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
+# main application, the makefile should define explicit rules.\r
 \r
 {$(ROOT)}.c{$(TMP_DIR)}.obj::\r
        $(CCPKGCMD) @<<\r
@@ -1731,15 +1801,15 @@ $<
 # When building an extension, certain configuration options should\r
 # match the ones used when Tcl was built. Here we check and\r
 # warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 !if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
 TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
 !endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
 !endif\r
 !endif # TCLINSTALL\r
 \r
@@ -1760,7 +1830,7 @@ TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"
 \r
 !endif # TCLNMAKECONFIG\r
 \r
-!endif # ! $(DOING_TCL)\r
+!endif # !$(DOING_TCL)\r
 \r
 \r
 #----------------------------------------------------------\r
similarity index 93%
rename from pkgs/tdbcmysql1.1.1/win/targets.vc
rename to pkgs/tdbc1.1.2/win/targets.vc
index 7f1d388..077e8f7 100644 (file)
@@ -4,7 +4,7 @@
 # Part of the nmake based build system for Tcl and its extensions.\r
 # This file defines some standard targets for the convenience of extensions\r
 # and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
 \r
 $(PROJECT): setup pkgindex $(PRJLIB)\r
 \r
diff --git a/pkgs/tdbcmysql1.1.1/win/rules.vc b/pkgs/tdbcmysql1.1.1/win/rules.vc
deleted file mode 100644 (file)
index b1a0346..0000000
+++ /dev/null
@@ -1,1807 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# rules.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file does all the hard work in terms of parsing build options,\r
-# compiler switches, defining common targets and macros. The Tcl makefile\r
-# directly includes this. Extensions include it via "rules-ext.vc".\r
-#\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
-# detailed documentation.\r
-#\r
-# See the file "license.terms" for information on usage and redistribution\r
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
-#\r
-# Copyright (c) 2001-2003 David Gravereaux.\r
-# Copyright (c) 2003-2008 Patrick Thoyts\r
-# Copyright (c) 2017      Ashok P. Nadkarni\r
-#------------------------------------------------------------------------------\r
-\r
-!ifndef _RULES_VC\r
-_RULES_VC = 1\r
-\r
-# The following macros define the version of the rules.vc nmake build system\r
-# For modifications that are not backward-compatible, you *must* change\r
-# the major version.\r
-RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
-\r
-# The PROJECT macro must be defined by parent makefile.\r
-!if "$(PROJECT)" == ""\r
-!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
-!endif\r
-\r
-!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
-PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
-!endif\r
-\r
-# Also special case Tcl and Tk to save some typing later\r
-DOING_TCL = 0\r
-DOING_TK  = 0\r
-!if "$(PROJECT)" == "tcl"\r
-DOING_TCL = 1\r
-!elseif "$(PROJECT)" == "tk"\r
-DOING_TK = 1\r
-!endif\r
-\r
-!ifndef NEED_TK\r
-# Backwards compatibility\r
-!ifdef PROJECT_REQUIRES_TK\r
-NEED_TK = $(PROJECT_REQUIRES_TK)\r
-!else\r
-NEED_TK = 0\r
-!endif\r
-!endif\r
-\r
-!ifndef NEED_TCL_SOURCE\r
-NEED_TCL_SOURCE = 0\r
-!endif\r
-\r
-!ifdef NEED_TK_SOURCE\r
-!if $(NEED_TK_SOURCE)\r
-NEED_TK = 1\r
-!endif\r
-!else\r
-NEED_TK_SOURCE = 0\r
-!endif\r
-\r
-################################################################\r
-# Nmake is a pretty weak environment in syntax and capabilities\r
-# so this file is necessarily verbose. It's broken down into\r
-# the following parts.\r
-#\r
-# 0. Sanity check that compiler environment is set up and initialize\r
-#    any built-in settings from the parent makefile\r
-# 1. First define the external tools used for compiling, copying etc.\r
-#    as this is independent of everything else.\r
-# 2. Figure out our build structure in terms of the directory, whether\r
-#    we are building Tcl or an extension, etc.\r
-# 3. Determine the compiler and linker versions\r
-# 4. Build the nmakehlp helper application\r
-# 5. Determine the supported compiler options and features\r
-# 6. Parse the OPTS macro value for user-specified build configuration\r
-# 7. Parse the STATS macro value for statistics instrumentation\r
-# 8. Parse the CHECKS macro for additional compilation checks\r
-# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
-# 10. Based on this selected configuration, construct the output\r
-#     directory and file paths\r
-# 11. Construct the paths where the package is to be installed\r
-# 12. Set up the actual options passed to compiler and linker based\r
-#     on the information gathered above.\r
-# 13. Define some standard build targets and implicit rules. These may\r
-#     be optionally disabled by the parent makefile.\r
-# 14. (For extensions only.) Compare the configuration of the target\r
-#     Tcl and the extensions and warn against discrepancies.\r
-#\r
-# One final note about the macro names used. They are as they are\r
-# for historical reasons. We would like legacy extensions to\r
-# continue to work with this make include file so be wary of\r
-# changing them for consistency or clarity.\r
-\r
-# 0. Sanity check compiler environment\r
-\r
-# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
-# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
-\r
-!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
-MSG = ^\r
-Visual C++ compiler environment not initialized.\r
-!error $(MSG)\r
-!endif\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-\r
-################################################################\r
-# 1. Define external programs being used\r
-\r
-#----------------------------------------------------------\r
-# Set the proper copy method to avoid overwrite questions\r
-# to the user when copying files and selecting the right\r
-# "delete all" method.\r
-#----------------------------------------------------------\r
-\r
-RMDIR  = rmdir /S /Q\r
-CPY    = xcopy /i /y >NUL\r
-CPYDIR  = xcopy /e /i /y >NUL\r
-COPY   = copy /y >NUL\r
-MKDIR   = mkdir\r
-\r
-######################################################################\r
-# 2. Figure out our build environment in terms of what we're building.\r
-#\r
-# (a) Tcl itself\r
-# (b) Tk\r
-# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
-# (d) a Tcl extension using libraries/includes from Tcl source directory\r
-#\r
-# This last is needed because some extensions still need\r
-# some Tcl interfaces that are not publicly exposed.\r
-#\r
-# The fragment will set the following macros:\r
-# ROOT - root of this module sources\r
-# COMPATDIR - source directory that holds compatibility sources\r
-# DOCDIR - source directory containing documentation files\r
-# GENERICDIR - platform-independent source directory\r
-# WINDIR - Windows-specific source directory\r
-# TESTDIR - directory containing test files\r
-# TOOLSDIR - directory containing build tools\r
-# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
-#    when building Tcl itself.\r
-# _INSTALLDIR - native form of the installation path. For Tcl\r
-#    this will be the root of the Tcl installation. For extensions\r
-#    this will be the lib directory under the root.\r
-# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
-#    headers and libraries from an installed Tcl, and 0 if built against\r
-#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
-#    named.\r
-# _TCL_H - native path to the tcl.h file\r
-#\r
-# If Tk is involved, also sets the following\r
-# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
-#    Tk itself.\r
-# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
-# _TK_H - native path to the tk.h file\r
-\r
-# Root directory for sources and assumed subdirectories\r
-ROOT = $(MAKEDIR)\..\r
-# The following paths CANNOT have spaces in them as they appear on the\r
-# left side of implicit rules.\r
-!ifndef COMPATDIR\r
-COMPATDIR      = $(ROOT)\compat\r
-!endif\r
-!ifndef DOCDIR\r
-DOCDIR         = $(ROOT)\doc\r
-!endif\r
-!ifndef GENERICDIR\r
-GENERICDIR     = $(ROOT)\generic\r
-!endif\r
-!ifndef TOOLSDIR\r
-TOOLSDIR       = $(ROOT)\tools\r
-!endif\r
-!ifndef TESTDIR\r
-TESTDIR        = $(ROOT)\tests\r
-!endif\r
-!ifndef LIBDIR\r
-!if exist("$(ROOT)\library")\r
-LIBDIR          = $(ROOT)\library\r
-!else\r
-LIBDIR          = $(ROOT)\lib\r
-!endif\r
-!endif\r
-!ifndef DEMODIR\r
-!if exist("$(LIBDIR)\demos")\r
-DEMODIR                = $(LIBDIR)\demos\r
-!else\r
-DEMODIR                = $(ROOT)\demos\r
-!endif\r
-!endif # ifndef DEMODIR\r
-# Do NOT enclose WINDIR in a !ifndef because Windows always defines\r
-# WINDIR env var to point to c:\windows!\r
-# TBD - This is a potentially dangerous conflict, rename WINDIR to\r
-# something else\r
-WINDIR         = $(ROOT)\win\r
-\r
-!ifndef RCDIR\r
-!if exist("$(WINDIR)\rc")\r
-RCDIR           = $(WINDIR)\rc\r
-!else\r
-RCDIR           = $(WINDIR)\r
-!endif\r
-!endif\r
-RCDIR = $(RCDIR:/=\)\r
-\r
-# The target directory where the built packages and binaries will be installed.\r
-# INSTALLDIR is the (optional) path specified by the user.\r
-# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
-!ifdef INSTALLDIR\r
-### Fix the path separators.\r
-_INSTALLDIR    = $(INSTALLDIR:/=\)\r
-!else\r
-### Assume the normal default.\r
-_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
-!endif\r
-\r
-!if $(DOING_TCL)\r
-\r
-# BEGIN Case 2(a) - Building Tcl itself\r
-\r
-# Only need to define _TCL_H\r
-_TCL_H = ..\generic\tcl.h\r
-\r
-# END Case 2(a) - Building Tcl itself\r
-\r
-!elseif $(DOING_TK)\r
-\r
-# BEGIN Case 2(b) - Building Tk\r
-\r
-TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
-!if "$(TCLDIR)" == ""\r
-!if [echo TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-!endif # TCLDIR == ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
-!if !exist("$(_TCL_H)")\r
-!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
-!endif\r
-\r
-_TK_H = ..\generic\tk.h\r
-\r
-# END Case 2(b) - Building Tk\r
-\r
-!else\r
-\r
-# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
-\r
-# If command line has specified Tcl location through TCLDIR, use it\r
-# else default to the INSTALLDIR setting\r
-!if "$(TCLDIR)" != ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
-TCLINSTALL     = 1\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
-TCLINSTALL     = 0\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-!endif\r
-\r
-!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
-\r
-TCLINSTALL     = 1\r
-TCLDIR          = $(_INSTALLDIR)\..\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TCLDIR                = $(_INSTALLDIR)\..\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-\r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!if [echo _TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TCLINSTALL      = 0\r
-TCLDIR         = $(_TCLDIR)\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-\r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!endif # TCLDIR\r
-\r
-!ifndef _TCL_H\r
-MSG =^\r
-Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-# Now do the same to locate Tk headers and libs if project requires Tk\r
-!if $(NEED_TK)\r
-\r
-!if "$(TKDIR)" != ""\r
-\r
-_TKDIR = $(TKDIR:/=\)\r
-!if exist("$(_TKDIR)\include\tk.h")\r
-TKINSTALL      = 1\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-!elseif exist("$(_TKDIR)\generic\tk.h")\r
-TKINSTALL      = 0\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-!endif\r
-\r
-!else # TKDIR not defined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-TKINSTALL      = 1\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TKDIR         = $(_INSTALLDIR)\..\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-TKDIR          = $(_TKDIR)\r
-\r
-!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!if [echo _TKDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
-!error *** Could not locate Tk source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TKINSTALL      = 0\r
-TKDIR          = $(_TKDIR)\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-\r
-!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!endif # TKDIR\r
-\r
-!ifndef _TK_H\r
-MSG =^\r
-Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-!endif # NEED_TK\r
-\r
-!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tcl.^\r
-*** Please set the TCLDIR macro to point to the Tcl sources.\r
-!error $(MSG)\r
-!endif\r
-\r
-!if $(NEED_TK_SOURCE)\r
-!if $(TKINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tk.^\r
-*** Please set the TKDIR macro to point to the Tk sources.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-\r
-# If INSTALLDIR set to Tcl installation root dir then reset to the\r
-# lib dir for installing extensions\r
-!if exist("$(_INSTALLDIR)\include\tcl.h")\r
-_INSTALLDIR=$(_INSTALLDIR)\lib\r
-!endif\r
-\r
-# END Case 2(c) or (d) - Building an extension\r
-!endif # if $(DOING_TCL)\r
-\r
-################################################################\r
-# 3. Determine compiler version and architecture\r
-# In this section, we figure out the compiler version and the\r
-# architecture for which we are building. This sets the\r
-# following macros:\r
-# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
-#     This is also printed by the compiler in dotted form 19.10 etc.\r
-# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
-#     compiler version 1200. This is kept only for legacy reasons as it\r
-#     does not make sense for recent Microsoft compilers. Only used for\r
-#     output directory names.\r
-# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
-# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
-# MACHINE - same as $(ARCH) - legacy\r
-# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
-\r
-cc32           = $(CC)   # built-in default.\r
-link32         = link\r
-lib32          = lib\r
-rc32           = $(RC)   # built-in default.\r
-\r
-#----------------------------------------------------------------\r
-# Figure out the compiler architecture and version by writing\r
-# the C macros to a file, preprocessing them with the C\r
-# preprocessor and reading back the created file\r
-\r
-_HASH=^#\r
-_VC_MANIFEST_EMBED_EXE=\r
-_VC_MANIFEST_EMBED_DLL=\r
-VCVER=0\r
-!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
-    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
-    && ![echo ARCH=IX86 >> vercl.x] \\r
-    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
-    && ![echo ARCH=AMD64 >> vercl.x] \\r
-    && ![echo $(_HASH)endif >> vercl.x] \\r
-    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
-!include vercl.i\r
-!if $(VCVERSION) < 1900\r
-!if ![echo VCVER= ^\> vercl.vc] \\r
-    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
-!include vercl.vc\r
-!endif\r
-!else\r
-# The simple calculation above does not apply to new Visual Studio releases\r
-# Keep the compiler version in its native form.\r
-VCVER = $(VCVERSION)\r
-!endif\r
-!endif\r
-\r
-!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# The MACHINE macro is used by legacy makefiles so set it as well\r
-!ifdef MACHINE\r
-!if "$(MACHINE)" == "x86"\r
-!undef MACHINE\r
-MACHINE = IX86\r
-!elseif "$(MACHINE)" == "x64"\r
-!undef MACHINE\r
-MACHINE = AMD64\r
-!endif\r
-!if "$(MACHINE)" != "$(ARCH)"\r
-!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
-!endif\r
-!else\r
-MACHINE=$(ARCH)\r
-!endif\r
-\r
-#---------------------------------------------------------------\r
-# The PLATFORM_IDENTIFY macro matches the values returned by\r
-# the Tcl platform::identify command\r
-!if "$(MACHINE)" == "AMD64"\r
-PLATFORM_IDENTIFY = win32-x86_64\r
-!else\r
-PLATFORM_IDENTIFY = win32-ix86\r
-!endif\r
-\r
-# The MULTIPLATFORM macro controls whether binary extensions are installed\r
-# in platform-specific directories. Intended to be set/used by extensions.\r
-!ifndef MULTIPLATFORM_INSTALL\r
-MULTIPLATFORM_INSTALL = 0\r
-!endif\r
-\r
-#------------------------------------------------------------\r
-# Figure out the *host* architecture by reading the registry\r
-\r
-!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
-NATIVE_ARCH=IX86\r
-!else\r
-NATIVE_ARCH=AMD64\r
-!endif\r
-\r
-# Since MSVC8 we must deal with manifest resources.\r
-!if $(VCVERSION) >= 1400\r
-_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
-_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
-!endif\r
-\r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
-################################################################\r
-# 4. Build the nmakehlp program\r
-# This is a helper app we need to overcome nmake's limiting\r
-# environment. We will call out to it to get various bits of\r
-# information about supported compiler options etc.\r
-#\r
-# Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
-#\r
-# Extensions built against an installed Tcl will use the installed\r
-# copy of Tcl's nmakehlp.c if there is one and their own version\r
-# otherwise. In the latter case, they would also be using their own\r
-# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
-# or rules.vc.\r
-#\r
-# Extensions built against Tcl sources will use the one from the Tcl source.\r
-#\r
-# When building an extension using a sufficiently new version of Tcl,\r
-# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
-# copy of nmakehlp.c to be used.\r
-\r
-!ifndef NMAKEHLPC\r
-# Default to the one in the current directory (the extension's own nmakehlp.c)\r
-NMAKEHLPC = nmakehlp.c\r
-\r
-!if !$(DOING_TCL)\r
-!if $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
-!endif\r
-!else # ! $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
-!endif\r
-!endif # $(TCLINSTALL)\r
-!endif # !$(DOING_TCL)\r
-\r
-!endif # NMAKEHLPC\r
-\r
-# We always build nmakehlp even if it exists since we do not know\r
-# what source it was built from.\r
-!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
-!endif\r
-\r
-################################################################\r
-# 5. Test for compiler features\r
-# Visual C++ compiler options have changed over the years. Check\r
-# which options are supported by the compiler in use.\r
-#\r
-# The following macros are set:\r
-# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
-# DEBUGFLAGS - the compiler flags to be used for debug builds\r
-# LINKERFLAGS - Flags passed to the linker\r
-#\r
-# Note that these are the compiler settings *available*, not those\r
-# that will be *used*. The latter depends on the OPTS macro settings\r
-# which we have not yet parsed.\r
-#\r
-# Also note that some of the flags in OPTIMIZATIONS are not really\r
-# related to optimization. They are placed there only for legacy reasons\r
-# as some extensions expect them to be included in that macro.\r
-\r
-# -Op improves float consistency. Note only needed for older compilers\r
-# Newer compilers do not need or support this option.\r
-!if [nmakehlp -c -Op]\r
-FPOPTS  = -Op\r
-!endif\r
-\r
-# Strict floating point semantics - present in newer compilers in lieu of -Op\r
-!if [nmakehlp -c -fp:strict]\r
-FPOPTS  = $(FPOPTS) -fp:strict\r
-!endif\r
-\r
-!if "$(MACHINE)" == "IX86"\r
-### test for pentium errata\r
-!if [nmakehlp -c -QI0f]\r
-!message *** Compiler has 'Pentium 0x0f fix'\r
-FPOPTS  = $(FPOPTS) -QI0f\r
-!else\r
-!message *** Compiler does not have 'Pentium 0x0f fix'\r
-!endif\r
-!endif\r
-\r
-### test for optimizations\r
-# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
-# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
-# stack probe at *every* function entry, not just those with more than\r
-# a page of stack allocation resulting in a performance hit.  However,\r
-# /O2 documentation is misleading as its stack probes are simply the\r
-# default page size locals allocation probes and not what is implied\r
-# by an explicit /Gs option.\r
-\r
-OPTIMIZATIONS = $(FPOPTS)\r
-\r
-!if [nmakehlp -c -O2]\r
-OPTIMIZING = 1\r
-OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
-!else\r
-# Legacy, really. All modern compilers support this\r
-!message *** Compiler does not have 'Optimizations'\r
-OPTIMIZING = 0\r
-!endif\r
-\r
-# Checks for buffer overflows in local arrays\r
-!if [nmakehlp -c -GS]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
-!endif\r
-\r
-# Link time optimization. Note that this option (potentially) makes\r
-# generated libraries only usable by the specific VC++ version that\r
-# created it. Requires /LTCG linker option\r
-!if [nmakehlp -c -GL]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
-CC_GL_OPT_ENABLED = 1\r
-!else\r
-# In newer compilers -GL and -YX are incompatible.\r
-!if [nmakehlp -c -YX]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
-!endif\r
-!endif # [nmakehlp -c -GL]\r
-\r
-DEBUGFLAGS     = $(FPOPTS)\r
-\r
-# Run time error checks. Not available or valid in a release, non-debug build\r
-# RTC is for modern compilers, -GZ is legacy\r
-!if [nmakehlp -c -RTC1]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
-!elseif [nmakehlp -c -GZ]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# Linker flags\r
-\r
-# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
-# if the linker supports a specific option. Without these flags link will\r
-# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
-# They are not passed through to the actual application / extension\r
-# link rules.\r
-!ifndef LINKER_TESTFLAGS\r
-LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
-!endif\r
-\r
-LINKERFLAGS     =\r
-\r
-# If compiler has enabled link time optimization, linker must too with -ltcg\r
-!ifdef CC_GL_OPT_ENABLED\r
-!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
-!endif\r
-!endif\r
-\r
-########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
-# Based on this, we will construct the actual switches to be passed to the\r
-# compiler and linker using the macros defined in the previous section.\r
-# The following macros are defined by this section based on OPTS\r
-# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
-#                1 -> build as a static library and shell\r
-# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
-# DEBUG - 1 -> debug build, 0 -> release builds\r
-# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
-# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
-# PGO     - 1 -> profile based optimization, 0 -> no\r
-# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
-#           0 -> link to static C runtime for static Tcl build.\r
-#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
-# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
-# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
-#           0 -> Use the non-thread allocator.\r
-# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
-#           C runtime, 0 -> use the debug C runtime.\r
-# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
-# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
-#           configuration (ignored for Tcl itself)\r
-# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
-# Further, LINKERFLAGS are modified based on above.\r
-\r
-# Default values for all the above\r
-STATIC_BUILD   = 0\r
-TCL_THREADS    = 1\r
-DEBUG          = 0\r
-SYMBOLS                = 0\r
-PROFILE                = 0\r
-PGO            = 0\r
-MSVCRT         = 1\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-USE_THREAD_ALLOC = 1\r
-UNCHECKED      = 0\r
-CONFIG_CHECK    = 1\r
-!if $(DOING_TCL)\r
-USE_STUBS       = 0\r
-!else\r
-USE_STUBS       = 1\r
-!endif\r
-\r
-# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
-# set the above macros based on OPTS content\r
-!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
-\r
-# OPTS are specified, parse them\r
-\r
-!if [nmakehlp -f $(OPTS) "static"]\r
-!message *** Doing static\r
-STATIC_BUILD   = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nostubs"]\r
-!message *** Not using stubs\r
-USE_STUBS      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-!message *** Doing nomsvcrt\r
-MSVCRT         = 0\r
-!else\r
-!if [nmakehlp -f $(OPTS) "msvcrt"]\r
-!message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
-!else\r
-MSVCRT         = 0\r
-!endif\r
-!endif\r
-!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-\r
-!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
-!message *** Doing staticpkg\r
-TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nothreads"]\r
-!message *** Compile explicitly for non-threaded tcl\r
-TCL_THREADS = 0\r
-USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "time64bit"]\r
-!message *** Force 64-bit time_t\r
-_USE_64BIT_TIME_T = 1\r
-!endif\r
-\r
-# Yes, it's weird that the "symbols" option controls DEBUG and\r
-# the "pdbs" option controls SYMBOLS. That's historical.\r
-!if [nmakehlp -f $(OPTS) "symbols"]\r
-!message *** Doing symbols\r
-DEBUG          = 1\r
-!else\r
-DEBUG          = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pdbs"]\r
-!message *** Doing pdbs\r
-SYMBOLS                = 1\r
-!else\r
-SYMBOLS                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "profile"]\r
-!message *** Doing profile\r
-PROFILE                = 1\r
-!else\r
-PROFILE                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pgi"]\r
-!message *** Doing profile guided optimization instrumentation\r
-PGO            = 1\r
-!elseif [nmakehlp -f $(OPTS) "pgo"]\r
-!message *** Doing profile guided optimization\r
-PGO            = 2\r
-!else\r
-PGO            = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "loimpact"]\r
-!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
-!endif\r
-\r
-# TBD - should get rid of this option\r
-!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
-!message *** Doing thrdalloc\r
-USE_THREAD_ALLOC = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "tclalloc"]\r
-USE_THREAD_ALLOC = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "unchecked"]\r
-!message *** Doing unchecked\r
-UNCHECKED = 1\r
-!else\r
-UNCHECKED = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
-CONFIG_CHECK = 1\r
-!else\r
-CONFIG_CHECK = 0\r
-!endif\r
-\r
-!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
-\r
-# Set linker flags based on above\r
-\r
-!if $(PGO) > 1\r
-!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!elseif $(PGO) > 0\r
-!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
-# The following macros are set by this section:\r
-# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
-#                 0 -> disables\r
-# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
-#                     0 -> disables\r
-\r
-# Default both are off\r
-TCL_MEM_DEBUG      = 0\r
-TCL_COMPILE_DEBUG   = 0\r
-\r
-!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
-\r
-!if [nmakehlp -f $(STATS) "memdbg"]\r
-!message *** Doing memdbg\r
-TCL_MEM_DEBUG      = 1\r
-!else\r
-TCL_MEM_DEBUG      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(STATS) "compdbg"]\r
-!message *** Doing compdbg\r
-TCL_COMPILE_DEBUG   = 1\r
-!else\r
-TCL_COMPILE_DEBUG   = 0\r
-!endif\r
-\r
-!endif\r
-\r
-####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
-# The following macros are set by this section:\r
-# WARNINGS - compiler switches that control the warnings level\r
-# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
-#                     0 -> enable deprecated functions\r
-\r
-# Defaults - Permit deprecated functions and warning level 3\r
-TCL_NO_DEPRECATED          = 0\r
-WARNINGS                   = -W3\r
-\r
-!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
-\r
-!if [nmakehlp -f $(CHECKS) "nodep"]\r
-!message *** Doing nodep check\r
-TCL_NO_DEPRECATED          = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
-!message *** Doing full warnings check\r
-WARNINGS                   = -W4\r
-!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
-!endif\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
-!message *** Doing 64bit portability warnings\r
-WARNINGS                   = $(WARNINGS) -Wp64\r
-!endif\r
-\r
-!endif\r
-\r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
-\r
-################################################################\r
-# 10. Construct output directory and file paths\r
-# Figure-out how to name our intermediate and output directories.\r
-# In order to avoid inadvertent mixing of object files built using\r
-# different compilers, build configurations etc.,\r
-#\r
-# Naming convention (suffixes):\r
-#   t = full thread support. (Not used for Tcl >= 8.7)\r
-#   s = static library (as opposed to an import library)\r
-#   g = linked to the debug enabled C run-time.\r
-#   x = special static build when it links to the dynamic C run-time.\r
-#\r
-# The following macros are set in this section:\r
-# SUFX - the suffix to use for binaries based on above naming convention\r
-# BUILDDIRTOP - the toplevel default output directory\r
-#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
-# TMP_DIR - directory where object files are created\r
-# OUT_DIR - directory where output executables are created\r
-# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
-# parent makefile (or command line). The default values are\r
-# based on BUILDDIRTOP.\r
-# STUBPREFIX - name of the stubs library for this project\r
-# PRJIMPLIB - output path of the generated project import library\r
-# PRJLIBNAME - name of generated project library\r
-# PRJLIB     - output path of generated project library\r
-# PRJSTUBLIBNAME - name of the generated project stubs library\r
-# PRJSTUBLIB - output path of the generated project stubs library\r
-# RESFILE - output resource file (only if not static build)\r
-\r
-SUFX       = tsgx\r
-\r
-!if $(DEBUG)\r
-BUILDDIRTOP = Debug\r
-!else\r
-BUILDDIRTOP = Release\r
-!endif\r
-\r
-!if "$(MACHINE)" != "IX86"\r
-BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
-!endif\r
-!if $(VCVER) > 6\r
-BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
-!endif\r
-\r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
-SUFX       = $(SUFX:g=)\r
-!endif\r
-\r
-TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
-\r
-!if !$(STATIC_BUILD)\r
-TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
-SUFX       = $(SUFX:s=)\r
-EXT        = dll\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!else\r
-TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
-EXT        = lib\r
-!if !$(MSVCRT)\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!endif\r
-!endif\r
-\r
-!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
-TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
-SUFX       = $(SUFX:t=)\r
-!endif\r
-\r
-!ifndef TMP_DIR\r
-TMP_DIR            = $(TMP_DIRFULL)\r
-!ifndef OUT_DIR\r
-OUT_DIR            = .\$(BUILDDIRTOP)\r
-!endif\r
-!else\r
-!ifndef OUT_DIR\r
-OUT_DIR            = $(TMP_DIR)\r
-!endif\r
-!endif\r
-\r
-# Relative paths -> absolute\r
-!if [echo OUT_DIR = \> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
-!endif\r
-!if [echo TMP_DIR = \>> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
-!endif\r
-!include nmakehlp.out\r
-\r
-# The name of the stubs library for the project being built\r
-STUBPREFIX      = $(PROJECT)stub\r
-\r
-# Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
-\r
-TCLSHNAME       = $(PROJECT)sh$(TCL_VERSION)$(SUFX).exe\r
-TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
-TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
-\r
-TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
-TCL_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-\r
-# When building extensions, we need to locate tclsh. Depending on version\r
-# of Tcl we are building against, this may or may not have a "t" suffix.\r
-# Try various possibilities in turn.\r
-TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist("$(TCLSH)") && $(TCL_THREADS)\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist("$(TCLSH)")\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-\r
-TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\lib\r
-TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
-TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
-\r
-!else # Building against Tcl sources\r
-\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist($(TCLSH)) && $(TCL_THREADS)\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist($(TCLSH))\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\library\r
-TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = $(_TCLDIR)\tools\r
-TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
-\r
-!endif # TCLINSTALL\r
-\r
-tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
-\r
-!endif # $(DOING_TCL)\r
-\r
-# We need a tclsh that will run on the host machine as part of the build.\r
-# IX86 runs on all architectures.\r
-!ifndef TCLSH_NATIVE\r
-!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
-TCLSH_NATIVE   = $(TCLSH)\r
-!else\r
-!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
-!endif\r
-!endif\r
-\r
-# Do the same for Tk and Tk extensions that require the Tk libraries\r
-!if $(DOING_TK) || $(NEED_TK)\r
-WISHNAMEPREFIX = wish\r
-WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
-TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
-TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
-\r
-!if $(DOING_TK)\r
-WISH           = $(OUT_DIR)\$(WISHNAME)\r
-TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
-TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # effectively NEED_TK\r
-\r
-!if $(TKINSTALL) # Building against installed Tk\r
-WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\include"\r
-!else # Building against Tk sources\r
-WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
-!endif # TKINSTALL\r
-tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
-\r
-!endif # $(DOING_TK)\r
-!endif # $(DOING_TK) || $(NEED_TK)\r
-\r
-# Various output paths\r
-PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
-\r
-PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
-\r
-# If extension parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
-!ifdef RCFILE\r
-RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
-!else\r
-RESFILE = $(TMP_DIR)\$(PROJECT).res\r
-!endif\r
-!endif\r
-\r
-###################################################################\r
-# 11. Construct the paths for the installation directories\r
-# The following macros get defined in this section:\r
-# LIB_INSTALL_DIR - where libraries should be installed\r
-# BIN_INSTALL_DIR - where the executables should be installed\r
-# DOC_INSTALL_DIR - where documentation should be installed\r
-# SCRIPT_INSTALL_DIR - where scripts should be installed\r
-# INCLUDE_INSTALL_DIR - where C include files should be installed\r
-# DEMO_INSTALL_DIR - where demos should be installed\r
-# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
-\r
-!if $(DOING_TCL) || $(DOING_TK)\r
-LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
-BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
-DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
-!if $(DOING_TCL)\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!else # DOING_TK\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
-\r
-!else # extension other than Tk\r
-\r
-PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
-!if $(MULTIPLATFORM_INSTALL)\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-!else\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-!endif\r
-DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
-DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
-\r
-!endif\r
-\r
-###################################################################\r
-# 12. Set up actual options to be passed to the compiler and linker\r
-# Now we have all the information we need, set up the actual flags and\r
-# options that we will pass to the compiler and linker. The main\r
-# makefile should use these in combination with whatever other flags\r
-# and switches are specific to it.\r
-# The following macros are defined, names are for historical compatibility:\r
-# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
-# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
-# crt - Compiler switch that selects the appropriate C runtime\r
-# cdebug - Compiler switches related to debug AND optimizations\r
-# cwarn - Compiler switches that set warning levels\r
-# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
-# ldebug - Linker switches controlling debug information and optimization\r
-# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
-# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
-# conlflags - complete linker switches for console program (subsumes lflags)\r
-# guilflags - complete linker switches for GUI program (subsumes lflags)\r
-# baselibs - minimum Windows libraries required. Parent makefile can\r
-#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
-\r
-OPTDEFINES     = -DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) -DSTDC_HEADERS\r
-\r
-!if $(TCL_MEM_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_MEM_DEBUG\r
-!endif\r
-!if $(TCL_COMPILE_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS\r
-!endif\r
-!if $(TCL_THREADS) && $(TCL_VERSION) <= 86\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_THREADS=1\r
-!if $(USE_THREAD_ALLOC)\r
-OPTDEFINES     = $(OPTDEFINES) -DUSE_THREAD_ALLOC=1\r
-!endif\r
-!endif\r
-!if $(STATIC_BUILD)\r
-OPTDEFINES     = $(OPTDEFINES) -DSTATIC_BUILD\r
-!endif\r
-!if $(TCL_NO_DEPRECATED)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_NO_DEPRECATED\r
-!endif\r
-\r
-!if $(USE_STUBS)\r
-# Note we do not define USE_TCL_STUBS even when building tk since some\r
-# test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
-USE_STUBS_DEFS  = -DUSE_TCL_STUBS -DUSE_TCLOO_STUBS\r
-!if $(NEED_TK)\r
-USE_STUBS_DEFS  = $(USE_STUBS_DEFS) -DUSE_TK_STUBS\r
-!endif\r
-!endif\r
-!endif # USE_STUBS\r
-\r
-!if !$(DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DNDEBUG\r
-!if $(OPTIMIZING)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_OPTIMIZED\r
-!endif\r
-!endif\r
-!if $(PROFILE)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_PROFILED\r
-!endif\r
-!if "$(MACHINE)" == "AMD64"\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_DO64BIT\r
-!endif\r
-!if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) -DNO_STRTOI64\r
-!endif\r
-\r
-!if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) -D_USE_64BIT_TIME_T\r
-!endif\r
-\r
-# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
-COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
-\r
-# Following is primarily for the benefit of extensions. Tcl 8.5 builds\r
-# Tcl without /DUNICODE, while 8.6 builds with it defined. When building\r
-# an extension, it is advisable (but not mandated) to use the same Windows\r
-# API as the Tcl build. This is accordingly defaulted below. A particular\r
-# extension can override this by pre-definining USE_WIDECHAR_API.\r
-!ifndef USE_WIDECHAR_API\r
-!if $(TCL_VERSION) > 85\r
-USE_WIDECHAR_API = 1\r
-!else\r
-USE_WIDECHAR_API = 0\r
-!endif\r
-!endif\r
-\r
-!if $(USE_WIDECHAR_API)\r
-COMPILERFLAGS = $(COMPILERFLAGS) /DUNICODE /D_UNICODE\r
-!endif\r
-\r
-# Like the TEA system only set this non empty for non-Tk extensions\r
-# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
-# so we pass both\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-PKGNAMEFLAGS = -DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
-               -DMODULE_SCOPE=extern\r
-!endif\r
-\r
-# crt picks the C run time based on selected OPTS\r
-!if $(MSVCRT)\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MDd\r
-!else\r
-crt = -MD\r
-!endif\r
-!else\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MTd\r
-!else\r
-crt = -MT\r
-!endif\r
-!endif\r
-\r
-# cdebug includes compiler options for debugging as well as optimization.\r
-!if $(DEBUG)\r
-\r
-# In debugging mode, optimizations need to be disabled\r
-cdebug = -Zi -Od $(DEBUGFLAGS)\r
-\r
-!else\r
-\r
-cdebug = $(OPTIMIZATIONS)\r
-!if $(SYMBOLS)\r
-cdebug = $(cdebug) -Zi\r
-!endif\r
-\r
-!endif # $(DEBUG)\r
-\r
-# cwarn includes default warning levels.\r
-cwarn = $(WARNINGS)\r
-\r
-!if "$(MACHINE)" == "AMD64"\r
-# Disable pointer<->int warnings related to cast between different sizes\r
-# There are a gadzillion of these due to use of ClientData and\r
-# clutter up compiler\r
-# output increasing chance of a real warning getting lost. So disable them.\r
-# Eventually some day, Tcl will be 64-bit clean.\r
-cwarn = $(cwarn) -wd4311 -wd4312\r
-!endif\r
-\r
-### Common compiler options that are architecture specific\r
-!if "$(MACHINE)" == "ARM"\r
-carch = -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
-!else\r
-carch =\r
-!endif\r
-\r
-!if $(DEBUG)\r
-# Turn warnings into errors\r
-cwarn = $(cwarn) -WX\r
-!endif\r
-\r
-INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WINDIR)" -I"$(COMPATDIR)"\r
-!endif\r
-\r
-# These flags are defined roughly in the order of the pre-reform\r
-# rules.vc/makefile.vc to help visually compare that the pre- and\r
-# post-reform build logs\r
-\r
-# cflags contains generic flags used for building practically all object files\r
-cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
-\r
-# appcflags contains $(cflags) and flags for building the application\r
-# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
-# flags used for building shared object files The two differ in the\r
-# BUILD_$(PROJECT) macro which should be defined only for the shared\r
-# library *implementation* and not for its caller interface\r
-\r
-appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
-appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
-pkgcflags = $(appcflags) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-\r
-# stubscflags contains $(cflags) plus flags used for building a stubs\r
-# library for the package.  Note: -DSTATIC_BUILD is defined in\r
-# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
-# library. However the stubs library is ALWAYS static hence included\r
-# here irrespective of the OPTS setting.\r
-#\r
-# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
-# without stating why. Tcl itself compiled stubs libs with this flag.\r
-# so we do not remove it from cflags. -GL may prevent extensions\r
-# compiled with one VC version to fail to link against stubs library\r
-# compiled with another VC version. Check for this and fix accordingly.\r
-stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl -DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
-\r
-# Link flags\r
-\r
-!if $(DEBUG)\r
-ldebug = -debug -debugtype:cv\r
-!else\r
-ldebug = -release -opt:ref -opt:icf,3\r
-!if $(SYMBOLS)\r
-ldebug = $(ldebug) -debug -debugtype:cv\r
-!endif\r
-!endif\r
-\r
-# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
-!if $(PROFILE)\r
-ldebug= $(ldebug) -profile\r
-!endif\r
-\r
-### Declarations common to all linker versions\r
-lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-lflags = $(lflags) -nodefaultlib:libucrt.lib\r
-!endif\r
-\r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
-dlllflags = $(lflags) -dll\r
-conlflags = $(lflags) -subsystem:console\r
-guilflags = $(lflags) -subsystem:windows\r
-\r
-# Libraries that are required for every image.\r
-# Extensions should define any additional libraries with $(PRJ_LIBS)\r
-winlibs   = kernel32.lib advapi32.lib\r
-\r
-!if $(NEED_TK)\r
-winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
-!endif\r
-\r
-# Avoid 'unresolved external symbol __security_cookie' errors.\r
-# c.f. http://support.microsoft.com/?id=894573\r
-!if "$(MACHINE)" == "AMD64"\r
-!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
-winlibs   = $(winlibs) bufferoverflowU.lib\r
-!endif\r
-!endif\r
-\r
-baselibs = $(winlibs) $(PRJ_LIBS)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-baselibs   = $(baselibs) ucrt.lib\r
-!endif\r
-\r
-################################################################\r
-# 13. Define standard commands, common make targets and implicit rules\r
-\r
-CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
-CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
-CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
-\r
-LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
-DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-\r
-CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
-           $(TCL_INCLUDES) \\r
-           -DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           -DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
-           -DDOTVERSION=\"$(DOTVERSION)\" \\r
-           -DVERSION=\"$(VERSION)\" \\r
-           -DSUFX=\"$(SUFX)\" \\r
-           -DPROJECT=\"$(PROJECT)\" \\r
-           -DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
-\r
-!ifndef DEFAULT_BUILD_TARGET\r
-DEFAULT_BUILD_TARGET = $(PROJECT)\r
-!endif\r
-\r
-default-target: $(DEFAULT_BUILD_TARGET)\r
-\r
-!if $(MULTIPLATFORM_INSTALL)\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!else\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!endif\r
-\r
-default-pkgindex-tea:\r
-       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
-@PACKAGE_VERSION@    $(DOTVERSION)\r
-@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
-@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
-@PKG_LIB_FILE@       $(PRJLIBNAME)\r
-<<\r
-\r
-default-install: default-install-binaries default-install-libraries\r
-!if $(SYMBOLS)\r
-default-install: default-install-pdbs\r
-!endif\r
-\r
-# Again to deal with historical brokenness, there is some confusion\r
-# in terminlogy. For extensions, the "install-binaries" was used to\r
-# locate target directory for *binary shared libraries* and thus\r
-# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
-# for executables (exes). On the other hand the "install-libraries"\r
-# target is for *scripts* and should have been called "install-scripts".\r
-default-install-binaries: $(PRJLIB)\r
-       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
-\r
-# Alias for default-install-scripts\r
-default-install-libraries: default-install-scripts\r
-\r
-default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
-       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
-       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
-       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
-       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
-\r
-default-install-stubs:\r
-       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
-       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
-\r
-default-install-pdbs:\r
-       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
-\r
-default-install-docs-html:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-docs-n:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-demos:\r
-       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
-       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
-       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
-\r
-default-clean:\r
-       @echo Cleaning $(TMP_DIR)\* ...\r
-       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
-       @echo Cleaning $(WINDIR)\nmakehlp.obj, nmakehlp.exe ...\r
-       @if exist $(WINDIR)\nmakehlp.obj del $(WINDIR)\nmakehlp.obj\r
-       @if exist $(WINDIR)\nmakehlp.exe del $(WINDIR)\nmakehlp.exe\r
-       @if exist $(WINDIR)\nmakehlp.out del $(WINDIR)\nmakehlp.out\r
-       @echo Cleaning $(WINDIR)\nmhlp-out.txt ...\r
-       @if exist $(WINDIR)\nmhlp-out.txt del $(WINDIR)\nmhlp-out.txt\r
-       @echo Cleaning $(WINDIR)\_junk.pch ...\r
-       @if exist $(WINDIR)\_junk.pch del $(WINDIR)\_junk.pch\r
-       @echo Cleaning $(WINDIR)\vercl.x, vercl.i ...\r
-       @if exist $(WINDIR)\vercl.x del $(WINDIR)\vercl.x\r
-       @if exist $(WINDIR)\vercl.i del $(WINDIR)\vercl.i\r
-       @echo Cleaning $(WINDIR)\versions.vc, version.vc ...\r
-       @if exist $(WINDIR)\versions.vc del $(WINDIR)\versions.vc\r
-       @if exist $(WINDIR)\version.vc del $(WINDIR)\version.vc\r
-\r
-default-hose: default-clean\r
-       @echo Hosing $(OUT_DIR)\* ...\r
-       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
-\r
-# Only for backward compatibility\r
-default-distclean: default-hose\r
-\r
-default-setup:\r
-       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
-       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
-\r
-!if "$(TESTPAT)" != ""\r
-TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
-!endif\r
-\r
-default-test: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
-\r
-default-shell: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       $(DEBUGGER) $(TCLSH)\r
-\r
-# Generation of Windows version resource\r
-!ifdef RCFILE\r
-\r
-# Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
-$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
-       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
-\r
-!else\r
-\r
-# If parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
-\r
-$(TMP_DIR)\$(PROJECT).rc:\r
-       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
-#include <winver.h>\r
-\r
-VS_VERSION_INFO VERSIONINFO\r
- FILEVERSION   COMMAVERSION\r
- PRODUCTVERSION        COMMAVERSION\r
- FILEFLAGSMASK 0x3fL\r
-#ifdef DEBUG\r
- FILEFLAGS     VS_FF_DEBUG\r
-#else\r
- FILEFLAGS     0x0L\r
-#endif\r
- FILEOS                VOS_NT_WINDOWS32\r
- FILETYPE      VFT_DLL\r
- FILESUBTYPE   0x0L\r
-BEGIN\r
-    BLOCK "StringFileInfo"\r
-    BEGIN\r
-        BLOCK "040904b0"\r
-        BEGIN\r
-            VALUE "FileDescription",  "Tcl extension " PROJECT\r
-            VALUE "OriginalFilename", PRJLIBNAME\r
-            VALUE "FileVersion",      DOTVERSION\r
-            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
-            VALUE "ProductVersion",   DOTVERSION\r
-        END\r
-    END\r
-    BLOCK "VarFileInfo"\r
-    BEGIN\r
-        VALUE "Translation", 0x409, 1200\r
-    END\r
-END\r
-\r
-<<\r
-\r
-!endif # ifdef RCFILE\r
-\r
-!ifndef DISABLE_IMPLICIT_RULES\r
-DISABLE_IMPLICIT_RULES = 0\r
-!endif\r
-\r
-!if !$(DISABLE_IMPLICIT_RULES)\r
-# Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
-\r
-{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(WINDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(WINDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-.SUFFIXES:\r
-.SUFFIXES:.c .rc\r
-\r
-!endif\r
-\r
-################################################################\r
-# 14. Sanity check selected options against Tcl build options\r
-# When building an extension, certain configuration options should\r
-# match the ones used when Tcl was built. Here we check and\r
-# warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
-TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
-!endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
-!endif\r
-!endif # TCLINSTALL\r
-\r
-!if $(CONFIG_CHECK)\r
-!ifdef TCLNMAKECONFIG\r
-!include $(TCLNMAKECONFIG)\r
-\r
-!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
-!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
-!endif\r
-!if defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
-!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
-!endif\r
-!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
-!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
-!endif\r
-!endif\r
-\r
-!endif # TCLNMAKECONFIG\r
-\r
-!endif # ! $(DOING_TCL)\r
-\r
-\r
-#----------------------------------------------------------\r
-# Display stats being used.\r
-#----------------------------------------------------------\r
-\r
-!if !$(DOING_TCL)\r
-!message *** Building against Tcl at '$(_TCLDIR)'\r
-!endif\r
-!if !$(DOING_TK) && $(NEED_TK)\r
-!message *** Building against Tk at '$(_TKDIR)'\r
-!endif\r
-!message *** Intermediate directory will be '$(TMP_DIR)'\r
-!message *** Output directory will be '$(OUT_DIR)'\r
-!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
-!message *** Suffix for binaries will be '$(SUFX)'\r
-!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
-\r
-!endif # ifdef _RULES_VC\r
similarity index 98%
rename from pkgs/tdbcmysql1.1.1/Makefile.in
rename to pkgs/tdbcmysql1.1.2/Makefile.in
index 3d74fac..b552d88 100644 (file)
@@ -101,8 +101,6 @@ CFLAGS_WARNING      = @CFLAGS_WARNING@
 EXEEXT         = @EXEEXT@
 LDFLAGS_DEFAULT        = @LDFLAGS_DEFAULT@
 MAKE_LIB       = @MAKE_LIB@
-MAKE_SHARED_LIB        = @MAKE_SHARED_LIB@
-MAKE_STATIC_LIB        = @MAKE_STATIC_LIB@
 MAKE_STUB_LIB  = @MAKE_STUB_LIB@
 OBJEXT         = @OBJEXT@
 RANLIB         = @RANLIB@
@@ -162,7 +160,7 @@ PKG_CFLAGS  = @PKG_CFLAGS@
 # you do not compile with a similar machine setup as the Tcl core was
 # compiled with.
 #DEFS          = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
-DEFS           = @DEFS@ $(PKG_CFLAGS)
+DEFS           = @DEFS@ $(PKG_CFLAGS) -DTCL_NO_DEPRECATED=1
 
 # Move pkgIndex.tcl to 'BINARIES' var if it is generated in the Makefile
 CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl
@@ -172,7 +170,10 @@ CPPFLAGS   = @CPPFLAGS@
 LIBS           = @PKG_LIBS@ @LIBS@
 AR             = @AR@
 CFLAGS         = @CFLAGS@
-COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LDFLAGS                = @LDFLAGS@
+LDFLAGS_DEFAULT                        = @LDFLAGS_DEFAULT@
+COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
+                         $(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
 
 GDB            = gdb
 VALGRIND       = valgrind
similarity index 97%
rename from pkgs/tdbcmysql1.1.1/README
rename to pkgs/tdbcmysql1.1.2/README
index 4c30d58..7e4b7be 100644 (file)
@@ -1,6 +1,6 @@
 README: tdbcmysql
 
-    This is the 1.1.1 source distribution of the driver for Tcl
+    This is the 1.1.2 source distribution of the driver for Tcl
     Database Connectivity (TDBC) to access MySQL databases.. TDBC and
     its drivers are available from a Fossil version control repository
     at http://tdbc.tcl.tk/
similarity index 98%
rename from pkgs/tdbcmysql1.1.1/configure
rename to pkgs/tdbcmysql1.1.2/configure
index 8b49795..87aa8da 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for tdbcmysql 1.1.1.
+# Generated by GNU Autoconf 2.69 for tdbcmysql 1.1.2.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='tdbcmysql'
 PACKAGE_TARNAME='tdbcmysql'
-PACKAGE_VERSION='1.1.1'
-PACKAGE_STRING='tdbcmysql 1.1.1'
+PACKAGE_VERSION='1.1.2'
+PACKAGE_STRING='tdbcmysql 1.1.2'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -627,7 +627,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -635,6 +634,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1304,7 +1305,7 @@ 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 tdbcmysql 1.1.1 to adapt to many kinds of systems.
+\`configure' configures tdbcmysql 1.1.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1365,7 +1366,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of tdbcmysql 1.1.1:";;
+     short | recursive ) echo "Configuration of tdbcmysql 1.1.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1466,7 +1467,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-tdbcmysql configure 1.1.1
+tdbcmysql configure 1.1.2
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2068,7 +2069,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by tdbcmysql $as_me 1.1.1, which was
+It was created by tdbcmysql $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3578,10 +3579,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3615,12 +3612,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3926,7 +3917,7 @@ $as_echo_n "checking For TDBC_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3940,7 +3931,7 @@ $as_echo "using TDBC_STUB_LIB_PATH ${TDBC_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3969,7 +3960,7 @@ $as_echo_n "checking For tdbc_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3983,7 +3974,7 @@ $as_echo "using tdbc_STUB_LIB_PATH ${tdbc_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5600,7 +5591,7 @@ if test "${TCL_MAJOR_VERSION}" -eq 8 ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5625,7 +5616,7 @@ if test "x${TEA_PLATFORM}" = "xwindows" -a "x${GCC}" != "xyes" ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5637,7 +5628,7 @@ else
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6585,7 +6576,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6610,7 +6601,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6759,14 +6750,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6847,14 +6838,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6869,7 +6860,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6945,39 +6936,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -7102,8 +7060,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -7130,7 +7088,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -7199,8 +7157,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -7216,8 +7174,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -7226,8 +7184,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -7255,8 +7213,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -7279,7 +7237,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -7289,9 +7247,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -7356,8 +7327,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -7374,11 +7345,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -7396,7 +7367,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -7404,32 +7375,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7738,7 +7683,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7808,13 +7753,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7914,7 +7859,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7951,8 +7896,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -8251,6 +8196,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8645,7 +8592,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8659,11 +8605,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8771,7 +8712,7 @@ fi
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8797,7 +8738,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8885,14 +8826,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8900,9 +8841,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -9473,7 +9414,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by tdbcmysql $as_me 1.1.1, which was
+This file was extended by tdbcmysql $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9526,7 +9467,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-tdbcmysql config.status 1.1.1
+tdbcmysql config.status 1.1.2
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/tdbcmysql1.1.1/configure.ac
rename to pkgs/tdbcmysql1.1.2/configure.ac
index 5938038..42662a7 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([tdbcmysql], [1.1.1])
+AC_INIT([tdbcmysql], [1.1.2])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
similarity index 99%
rename from pkgs/tdbcmysql1.1.1/generic/tdbcmysql.c
rename to pkgs/tdbcmysql1.1.2/generic/tdbcmysql.c
index 0e396a7..d8c3479 100644 (file)
@@ -229,7 +229,7 @@ typedef struct ResultSetData {
 #define DecrResultSetRefCount(x)               \
     do {                                       \
        ResultSetData* rs = (x);                \
-       if ((rs->refCount--) <= 0) {            \
+       if (rs->refCount-- <= 1) {              \
            DeleteResultSet(rs);                \
        }                                       \
     } while(0)
@@ -1444,7 +1444,7 @@ ConnectionConstructor(
 
 static int
 ConnectionBegintransactionMethod(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1454,6 +1454,7 @@ ConnectionBegintransactionMethod(
                                /* The current connection object */
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1508,7 +1509,7 @@ ConnectionBegintransactionMethod(
 
 static int
 ConnectionColumnsMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Completion type */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1529,6 +1530,7 @@ ConnectionColumnsMethod(
     Tcl_Obj* name;             /* Name of a column */
     Tcl_Obj* attrs;            /* Attributes of the column */
     Tcl_HashEntry* entry;      /* Hash entry for data type */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1610,7 +1612,7 @@ ConnectionColumnsMethod(
 
 static int
 ConnectionCommitMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1622,6 +1624,7 @@ ConnectionCommitMethod(
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
     my_bool rc;                        /* MySQL status return */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1685,7 +1688,7 @@ ConnectionCommitMethod(
  */
 
 static int ConnectionConfigureMethod(
-     ClientData clientData,
+     ClientData dummy,
      Tcl_Interp* interp,
      Tcl_ObjectContext objectContext,
      int objc,
@@ -1697,6 +1700,8 @@ static int ConnectionConfigureMethod(
                                /* Number of arguments to skip */
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
+    (void)dummy;
+
                                /* Instance data */
     return ConfigureConnection(cdata, interp, objc, objv, skip);
 }
@@ -1731,7 +1736,7 @@ static int ConnectionConfigureMethod(
 
 static int
 ConnectionEvaldirectMethod(
-    ClientData clientData,          /* Unused */
+    ClientData dummy,       /* Unused */
     Tcl_Interp* interp,                     /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                       /* Parameter count */
@@ -1750,6 +1755,7 @@ ConnectionEvaldirectMethod(
     Tcl_Obj* rowObj;           /* One row of the result set as a Tcl list */
     Tcl_Obj* fieldObj;         /* One field of the row */
     int i;
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1834,7 +1840,7 @@ ConnectionEvaldirectMethod(
 
 static int
 ConnectionNeedCollationInfoMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1845,6 +1851,7 @@ ConnectionNeedCollationInfoMethod(
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -1878,7 +1885,7 @@ ConnectionNeedCollationInfoMethod(
 
 static int
 ConnectionRollbackMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1890,6 +1897,7 @@ ConnectionRollbackMethod(
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
     my_bool rc;                /* Result code from MySQL operations */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1946,7 +1954,7 @@ ConnectionRollbackMethod(
 
 static int
 ConnectionSetCollationInfoMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1962,6 +1970,7 @@ ConnectionSetCollationInfoMethod(
     unsigned int collationNum;
     int i;
     int t;
+    (void)dummy;
 
     if (objc <= 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "{collationNum size}...");
@@ -2032,7 +2041,7 @@ ConnectionSetCollationInfoMethod(
 
 static int
 ConnectionTablesMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -2051,6 +2060,7 @@ ConnectionTablesMethod(
     MYSQL_ROW row = NULL;      /* Row in the result set */
     int status = TCL_OK;       /* Return status */
     Tcl_Obj* retval = NULL;    /* List of table names */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2134,10 +2144,12 @@ DeleteCmd (
 
 static int
 CloneCmd(
-    Tcl_Interp* interp,                /* Tcl interpreter */
+    Tcl_Interp* dummy,         /* Tcl interpreter */
     ClientData oldClientData,  /* Environment handle to be discarded */
     ClientData* newClientData  /* New environment handle to be used */
 ) {
+    (void)dummy;
+
     *newClientData = oldClientData;
     return TCL_OK;
 }
@@ -2205,6 +2217,9 @@ CloneConnection(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("MYSQL connections are not clonable", -1));
     return TCL_ERROR;
@@ -2324,6 +2339,7 @@ ResultDescToTcl(
     int isNew;                 /* Flag == 1 if a result column is unique */
     Tcl_HashEntry* entry;      /* Hash table entry for a column name */
     int count;                 /* Number used to disambiguate a column name */
+    (void)flags;
 
     Tcl_InitHashTable(&names, TCL_STRING_KEYS);
     if (result != NULL) {
@@ -2383,13 +2399,12 @@ ResultDescToTcl(
 
 static int
 StatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current statement object */
     int skip = Tcl_ObjectContextSkippedArgs(context);
@@ -2407,6 +2422,7 @@ StatementConstructor(
     int tokenLen;              /* Length of a token */
     int nParams;               /* Number of parameters of the statement */
     int i;
+    (void)dummy;
 
     /* Find the connection object, and get its data. */
 
@@ -2545,7 +2561,7 @@ StatementConstructor(
 
 static int
 StatementParamsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2566,6 +2582,7 @@ StatementParamsMethod(
     Tcl_Obj* retVal;           /* Return value from this command */
     Tcl_HashEntry* typeHashEntry;
     int i;
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -2633,7 +2650,7 @@ StatementParamsMethod(
 
 static int
 StatementParamtypeMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2667,6 +2684,7 @@ StatementParamtypeMethod(
     Tcl_Obj* errorObj;         /* Error message */
 
     int i;
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2817,6 +2835,9 @@ CloneStatement(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("MySQL statements are not clonable", -1));
     return TCL_ERROR;
@@ -2847,13 +2868,12 @@ CloneStatement(
 
 static int
 ResultSetConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current result set object */
     int skip = Tcl_ObjectContextSkippedArgs(context);
@@ -2876,6 +2896,7 @@ ResultSetConstructor(
     unsigned long* resultLengths;
                                /* Lengths of the columns of the result set */
     int i;
+    (void)dummy;
 
     /* Check parameter count */
 
@@ -3185,7 +3206,7 @@ ResultSetConstructor(
 
 static int
 ResultSetColumnsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3197,6 +3218,7 @@ ResultSetColumnsMethod(
     ResultSetData* rdata = (ResultSetData*)
        Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
     StatementData* sdata = (StatementData*) rdata->sdata;
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "?pattern?");
@@ -3422,18 +3444,18 @@ ResultSetNextrowMethod(
 
 static int
 ResultSetRowcountMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current result set object */
     ResultSetData* rdata = (ResultSetData*)
        Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
                                /* Data pertaining to the current result set */
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -3527,6 +3549,9 @@ CloneResultSet(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("MySQL result sets are not clonable",
                                      -1));
similarity index 81%
rename from pkgs/tdbc1.1.1/tclconfig/README.txt
rename to pkgs/tdbcmysql1.1.2/tclconfig/README.txt
index 59b5a3e..715cb9d 100644 (file)
@@ -3,10 +3,10 @@ Architecture (TEA) extension.  For more information on TEA see:
 
        http://www.tcl.tk/doc/tea/
 
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
 
-       http://tcl.sourceforge.net/
+       https://core.tcl-lang.org/tclconfig
 
 This package is a freely available open source package.  You can do
 virtually anything you like with it, such as modifying it, redistributing
similarity index 55%
rename from pkgs/tdbcmysql1.1.1/tclconfig/install-sh
rename to pkgs/tdbcmysql1.1.2/tclconfig/install-sh
index 7c34c3f..21b733a 100644 (file)
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-04-20.01; # UTC
+scriptversion=2020-07-26.22; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -35,25 +35,21 @@ scriptversion=2011-04-20.01; # UTC
 # FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
+# '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.
 
+tab='  '
 nl='
 '
-IFS=" ""       $nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,22 +64,15 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
 mode=0755
 
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
 chgrpcmd=
 chmodcmd=$chmodprog
 chowncmd=
@@ -97,7 +86,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -120,7 +109,7 @@ Options:
   -m MODE       $chmodprog installed files to MODE.
   -o USER       $chownprog installed files to USER.
   -s            $stripprog installed files.
-  -S            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
   -t DIRECTORY  install into DIRECTORY.
   -T            report an error if DSTFILE is a directory.
 
@@ -138,45 +127,60 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-       shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-       shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
     -S) stripcmd="$stripprog $2"
-       shift;;
+        shift;;
 
-    -t) dst_arg=$2
-       shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)        shift
-       break;;
+    --) shift
+        break;;
 
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -190,6 +194,10 @@ if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
     fi
     shift # arg
     dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
   done
 fi
 
@@ -198,12 +206,21 @@ if test $# -eq 0; then
     echo "$0: no input file specified." >&2
     exit 1
   fi
-  # It's OK to call `install-sh -d' without argument.
+  # It's OK to call 'install-sh -d' without argument.
   # This can happen when creating conditional directories.
   exit 0
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -219,16 +236,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -236,9 +253,9 @@ fi
 
 for src
 do
-  # Protect names starting with `-'.
+  # Protect names problematic for 'test' and other utilities.
   case $src in
-    -*) src=./$src;;
+    -* | [=\(\)!]) src=./$src;;
   esac
 
   if test -n "$dir_arg"; then
@@ -260,185 +277,150 @@ do
       echo "$0: no destination specified." >&2
       exit 1
     fi
-
     dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
 
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
+    # If destination is a directory, append the input filename.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
-      dst=$dstdir/`basename "$src"`
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
   fi
 
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
   obsolete_mkdir_used=false
 
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
        else
-         mkdir_mode=
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
        fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
+       trap '' 0;;
     esac
 
     if
       $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
 
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # mkdir does not conform to POSIX,
       # or it failed possibly due to a race condition.  Create the
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -451,14 +433,25 @@ do
   else
 
     # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
 
     # Trap to clean up those temp files at exit.
     trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
 
     # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
 
     # and set any options; do chmod last to preserve setuid bits.
     #
@@ -473,15 +466,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -494,24 +484,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
@@ -520,9 +510,9 @@ do
 done
 
 # Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
+# eval: (add-hook 'before-save-hook 'time-stamp)
 # time-stamp-start: "scriptversion="
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
+# time-stamp-time-zone: "UTC0"
 # time-stamp-end: "; # UTC"
-# End:
+# End:
\ No newline at end of file
similarity index 95%
rename from pkgs/tdbcmysql1.1.1/tclconfig/tcl.m4
rename to pkgs/tdbcmysql1.1.2/tclconfig/tcl.m4
index 7d901f9..8d24e7f 100644 (file)
@@ -50,9 +50,9 @@ AC_DEFUN([TEA_PATH_TCLCONFIG], [
        # we reset no_tcl in case something fails here
        no_tcl=true
        AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
+           AS_HELP_STRING([--with-tcl],
                [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
+           [with_tclconfig="${withval}"])
        AC_MSG_CHECKING([for Tcl configuration])
        AC_CACHE_VAL(ac_cv_c_tclconfig,[
 
@@ -212,9 +212,9 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
        # we reset no_tk in case something fails here
        no_tk=true
        AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
+           AS_HELP_STRING([--with-tk],
                [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
+           [with_tkconfig="${withval}"])
        AC_MSG_CHECKING([for Tk configuration])
        AC_CACHE_VAL(ac_cv_c_tkconfig,[
 
@@ -266,9 +266,6 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
                        `ls -d /Library/Frameworks 2>/dev/null` \
                        `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
                        ; do
                    if test -f "$i/Tk.framework/tkConfig.sh" ; then
                        ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
@@ -285,10 +282,10 @@ AC_DEFUN([TEA_PATH_TKCONFIG], [
                        `ls -d /usr/local/lib 2>/dev/null` \
                        `ls -d /usr/contrib/lib 2>/dev/null` \
                        `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
                        `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
                        `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
@@ -375,10 +372,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
         AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -412,12 +405,6 @@ AC_DEFUN([TEA_LOAD_TCLCONFIG], [
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
     AC_SUBST(TCL_VERSION)
     AC_SUBST(TCL_PATCH_LEVEL)
     AC_SUBST(TCL_BIN_DIR)
@@ -493,10 +480,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
         AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
     # If the TK_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TK_LIB_SPEC will be set to the value
@@ -530,12 +513,6 @@ AC_DEFUN([TEA_LOAD_TKCONFIG], [
        esac
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
     # TEA specific: Ensure windowingsystem is defined
     if test "${TEA_PLATFORM}" = "unix" ; then
        case ${TK_DEFS} in
@@ -592,14 +569,14 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -607,9 +584,9 @@ AC_DEFUN([TEA_PROG_TCLSH], [
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -650,14 +627,14 @@ AC_DEFUN([TEA_PROG_WISH], [
     if test -f "${TK_BIN_DIR}/Makefile" ; then
         # tkConfig.sh is in Tk build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             WISH_PROG="${TK_BIN_DIR}/wish"
@@ -665,9 +642,9 @@ AC_DEFUN([TEA_PROG_WISH], [
     else
         # tkConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
         else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
         fi
         list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
@@ -713,7 +690,7 @@ AC_DEFUN([TEA_PROG_WISH], [
 AC_DEFUN([TEA_ENABLE_SHARED], [
     AC_MSG_CHECKING([how to build libraries])
     AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
+       AS_HELP_STRING([--enable-shared],
            [build and link with shared libraries (default: on)]),
        [shared_ok=$enableval], [shared_ok=yes])
 
@@ -725,7 +702,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
     fi
 
     AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
+       AS_HELP_STRING([--enable-stubs],
            [build and link with stub libraries. Always true for shared builds (default: on)]),
        [stubs_ok=$enableval], [stubs_ok=yes])
 
@@ -797,7 +774,7 @@ AC_DEFUN([TEA_ENABLE_SHARED], [
 
 AC_DEFUN([TEA_ENABLE_THREADS], [
     AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
+       AS_HELP_STRING([--enable-threads],
            [build with threads (default: on)]),
        [tcl_ok=$enableval], [tcl_ok=yes])
 
@@ -911,8 +888,6 @@ AC_DEFUN([TEA_ENABLE_THREADS], [
 #                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
 #              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
 #                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
 #------------------------------------------------------------------------
 
 AC_DEFUN([TEA_ENABLE_SYMBOLS], [
@@ -920,10 +895,9 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
     AC_REQUIRE([TEA_CONFIG_CFLAGS])
     AC_MSG_CHECKING([for build with symbols])
     AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
+       AS_HELP_STRING([--enable-symbols],
            [build with debugging symbols (default: off)]),
        [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -935,13 +909,8 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
            AC_MSG_RESULT([yes (standard debugging)])
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
     AC_SUBST(CFLAGS_DEFAULT)
     AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
 
     if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
        AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
@@ -976,7 +945,7 @@ AC_DEFUN([TEA_ENABLE_SYMBOLS], [
 
 AC_DEFUN([TEA_ENABLE_LANGINFO], [
     AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
+       AS_HELP_STRING([--enable-langinfo],
            [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
        [langinfo_ok=$enableval], [langinfo_ok=yes])
 
@@ -1108,7 +1077,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit support is requested])
     AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
+       AS_HELP_STRING([--enable-64bit],
            [enable 64bit support (default: off)]),
        [do64bit=$enableval], [do64bit=no])
     AC_MSG_RESULT([$do64bit])
@@ -1117,7 +1086,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
     AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
+       AS_HELP_STRING([--enable-64bit-vis],
            [enable 64bit Sparc VIS support (default: off)]),
        [do64bitVIS=$enableval], [do64bitVIS=no])
     AC_MSG_RESULT([$do64bitVIS])
@@ -1146,7 +1115,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
 
     AC_MSG_CHECKING([if rpath support is requested])
     AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
+       AS_HELP_STRING([--disable-rpath],
            [disable rpath support (default: on)]),
        [doRpath=$enableval], [doRpath=yes])
     AC_MSG_RESULT([$doRpath])
@@ -1260,14 +1229,14 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -1336,11 +1305,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
                ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ], [
                AS_IF([test "$GCC" = yes], [
                    SHLIB_LD='${CC} -shared -Wl,-bexpall'
@@ -1349,7 +1318,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    LDFLAGS="$LDFLAGS -brtl"
                ])
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1385,19 +1354,6 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -1435,8 +1391,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ])
            AS_IF([test "$GCC" = yes], [
@@ -1455,7 +1411,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
                            AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
@@ -1476,8 +1432,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
            ]) ;;
        IRIX-5.*)
@@ -1486,16 +1442,16 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            ;;
        IRIX-6.*)
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
            AS_IF([test "$GCC" = yes], [
                CFLAGS="$CFLAGS -mabi=n32"
                LDFLAGS="$LDFLAGS -mabi=n32"
@@ -1517,8 +1473,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
 
            # Check to enable 64-bit flags for compiler/linker
 
@@ -1533,7 +1489,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                ])
            ])
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -1543,8 +1499,19 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
            AS_IF([test $do64bit = yes], [
@@ -1574,8 +1541,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} -shared'
            LD_FLAGS="-Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            ;;
        OpenBSD-*)
            arch=`arch -s`
@@ -1590,10 +1557,10 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -1610,37 +1577,13 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            LDFLAGS="$LDFLAGS -export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
            LIBS=`echo $LIBS | sed s/-pthread//`
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -1774,7 +1717,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            ])
            SHLIB_SUFFIX=".so"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
@@ -1827,11 +1770,11 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ], [
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            ])
            ;;
@@ -1897,7 +1840,7 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            AS_IF([test "$GCC" = yes], [
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                AS_IF([test "$do64bit_ok" = yes], [
                    AS_IF([test "$arch" = "sparcv9 sparc"], [
@@ -1924,8 +1867,8 @@ AC_DEFUN([TEA_CONFIG_CFLAGS], [
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
            ])
            ;;
        UNIX_SV* | UnixWare-5*)
@@ -2091,6 +2034,8 @@ dnl # preprocessing tests use only CPPFLAGS.
     AC_SUBST(CFLAGS_DEBUG)
     AC_SUBST(CFLAGS_OPTIMIZE)
     AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
 
     AC_SUBST(STLIB_LD)
     AC_SUBST(SHLIB_LD)
@@ -2374,6 +2319,7 @@ AC_DEFUN([TEA_BLOCKING_STYLE], [
 #              HAVE_TM_GMTOFF
 #              HAVE_TM_TZADJ
 #              HAVE_TIMEZONE_VAR
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TIME_HANDLER], [
@@ -2381,7 +2327,7 @@ AC_DEFUN([TEA_TIME_HANDLER], [
     AC_HEADER_TIME
     AC_STRUCT_TIMEZONE
 
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
 
     AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
        AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
@@ -2449,6 +2395,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
     if test "$tcl_strtod" = 1; then
        AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
            AC_TRY_RUN([
+               #include <stdlib.h>
                extern double strtod();
                int main() {
                    char *infString="Inf", *nanString="NaN", *spaceString=" ";
@@ -2478,6 +2425,81 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 ])
 
 #--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
 # TEA_TCL_EARLY_FLAGS
 #
 #      Check for what flags are needed to be passed so the correct OS
@@ -2492,6 +2514,7 @@ AC_DEFUN([TEA_BUGGY_STRTOD], [
 #              _ISOC99_SOURCE
 #              _LARGEFILE64_SOURCE
 #              _LARGEFILE_SOURCE64
+#
 #--------------------------------------------------------------------
 
 AC_DEFUN([TEA_TCL_EARLY_FLAG],[
@@ -2912,7 +2935,7 @@ AC_DEFUN([TEA_ADD_LIBS], [
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3099,7 +3122,7 @@ AC_DEFUN([TEA_SETUP_COMPILER], [
 AC_DEFUN([TEA_MAKE_LIB], [
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        AC_EGREP_CPP([manifest needed], [
 #if defined(_MSC_VER) && _MSC_VER >= 1400
 print("manifest needed")
@@ -3114,7 +3137,7 @@ print("manifest needed")
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -3856,11 +3879,11 @@ AC_DEFUN([TEA_EXPORT_CONFIG], [
     # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
     eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
     if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
     else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
     fi
     $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
     $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
similarity index 95%
rename from pkgs/tdbcmysql1.1.1/win/makefile.vc
rename to pkgs/tdbcmysql1.1.2/win/makefile.vc
index 2ce2d13..a879730 100644 (file)
@@ -8,7 +8,7 @@
 #   nmake /s /nologo /f makefile.vc INSTALLDIR=c:\path\to\installdir test\r
 #\r
 # For other build options (debug, static etc.)\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
similarity index 99%
rename from pkgs/tdbc1.1.1/win/nmakehlp.c
rename to pkgs/tdbcmysql1.1.2/win/nmakehlp.c
index c21de63..7536ede 100644 (file)
@@ -643,7 +643,7 @@ SubstituteFile(
        }
 
        /* debug: dump the list */
-#ifdef _DEBUG
+#ifndef NDEBUG
        {
            int n = 0;
            list_item_t *p = NULL;
@@ -708,7 +708,7 @@ QualifyPath(
 {
     char szCwd[MAX_PATH + 1];
 
-       GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
+    GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
     printf("%s\n", szCwd);
     return 0;
 }
similarity index 94%
rename from pkgs/tdbcodbc1.1.1/win/rules-ext.vc
rename to pkgs/tdbcmysql1.1.2/win/rules-ext.vc
index 531e070..6da5689 100644 (file)
@@ -31,7 +31,7 @@ macro to the name of the project makefile.
 # We extract version numbers using the nmakehlp program. For now use\r
 # the local copy of nmakehlp. Once we locate Tcl, we will use that\r
 # one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
 !endif\r
 \r
 # First locate the Tcl directory that we are working with.\r
diff --git a/pkgs/tdbcmysql1.1.2/win/rules.vc b/pkgs/tdbcmysql1.1.2/win/rules.vc
new file mode 100644 (file)
index 0000000..13e3879
--- /dev/null
@@ -0,0 +1,1852 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# rules.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file does all the hard work in terms of parsing build options,\r
+# compiler switches, defining common targets and macros. The Tcl makefile\r
+# directly includes this. Extensions include it via "rules-ext.vc".\r
+#\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
+# detailed documentation.\r
+#\r
+# See the file "license.terms" for information on usage and redistribution\r
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
+#\r
+# Copyright (c) 2001-2003 David Gravereaux.\r
+# Copyright (c) 2003-2008 Patrick Thoyts\r
+# Copyright (c) 2017      Ashok P. Nadkarni\r
+#------------------------------------------------------------------------------\r
+\r
+!ifndef _RULES_VC\r
+_RULES_VC = 1\r
+\r
+# The following macros define the version of the rules.vc nmake build system\r
+# For modifications that are not backward-compatible, you *must* change\r
+# the major version.\r
+RULES_VERSION_MAJOR = 1\r
+RULES_VERSION_MINOR = 8\r
+\r
+# The PROJECT macro must be defined by parent makefile.\r
+!if "$(PROJECT)" == ""\r
+!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
+!endif\r
+\r
+!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
+PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
+!endif\r
+\r
+# Also special case Tcl and Tk to save some typing later\r
+DOING_TCL = 0\r
+DOING_TK  = 0\r
+!if "$(PROJECT)" == "tcl"\r
+DOING_TCL = 1\r
+!elseif "$(PROJECT)" == "tk"\r
+DOING_TK = 1\r
+!endif\r
+\r
+!ifndef NEED_TK\r
+# Backwards compatibility\r
+!ifdef PROJECT_REQUIRES_TK\r
+NEED_TK = $(PROJECT_REQUIRES_TK)\r
+!else\r
+NEED_TK = 0\r
+!endif\r
+!endif\r
+\r
+!ifndef NEED_TCL_SOURCE\r
+NEED_TCL_SOURCE = 0\r
+!endif\r
+\r
+!ifdef NEED_TK_SOURCE\r
+!if $(NEED_TK_SOURCE)\r
+NEED_TK = 1\r
+!endif\r
+!else\r
+NEED_TK_SOURCE = 0\r
+!endif\r
+\r
+################################################################\r
+# Nmake is a pretty weak environment in syntax and capabilities\r
+# so this file is necessarily verbose. It's broken down into\r
+# the following parts.\r
+#\r
+# 0. Sanity check that compiler environment is set up and initialize\r
+#    any built-in settings from the parent makefile\r
+# 1. First define the external tools used for compiling, copying etc.\r
+#    as this is independent of everything else.\r
+# 2. Figure out our build structure in terms of the directory, whether\r
+#    we are building Tcl or an extension, etc.\r
+# 3. Determine the compiler and linker versions\r
+# 4. Build the nmakehlp helper application\r
+# 5. Determine the supported compiler options and features\r
+# 6. Parse the OPTS macro value for user-specified build configuration\r
+# 7. Parse the STATS macro value for statistics instrumentation\r
+# 8. Parse the CHECKS macro for additional compilation checks\r
+# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
+# 10. Based on this selected configuration, construct the output\r
+#     directory and file paths\r
+# 11. Construct the paths where the package is to be installed\r
+# 12. Set up the actual options passed to compiler and linker based\r
+#     on the information gathered above.\r
+# 13. Define some standard build targets and implicit rules. These may\r
+#     be optionally disabled by the parent makefile.\r
+# 14. (For extensions only.) Compare the configuration of the target\r
+#     Tcl and the extensions and warn against discrepancies.\r
+#\r
+# One final note about the macro names used. They are as they are\r
+# for historical reasons. We would like legacy extensions to\r
+# continue to work with this make include file so be wary of\r
+# changing them for consistency or clarity.\r
+\r
+# 0. Sanity check compiler environment\r
+\r
+# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
+# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
+\r
+!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
+MSG = ^\r
+Visual C++ compiler environment not initialized.\r
+!error $(MSG)\r
+!endif\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+\r
+################################################################\r
+# 1. Define external programs being used\r
+\r
+#----------------------------------------------------------\r
+# Set the proper copy method to avoid overwrite questions\r
+# to the user when copying files and selecting the right\r
+# "delete all" method.\r
+#----------------------------------------------------------\r
+\r
+RMDIR  = rmdir /S /Q\r
+CPY    = xcopy /i /y >NUL\r
+CPYDIR  = xcopy /e /i /y >NUL\r
+COPY   = copy /y >NUL\r
+MKDIR   = mkdir\r
+\r
+######################################################################\r
+# 2. Figure out our build environment in terms of what we're building.\r
+#\r
+# (a) Tcl itself\r
+# (b) Tk\r
+# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
+# (d) a Tcl extension using libraries/includes from Tcl source directory\r
+#\r
+# This last is needed because some extensions still need\r
+# some Tcl interfaces that are not publicly exposed.\r
+#\r
+# The fragment will set the following macros:\r
+# ROOT - root of this module sources\r
+# COMPATDIR - source directory that holds compatibility sources\r
+# DOCDIR - source directory containing documentation files\r
+# GENERICDIR - platform-independent source directory\r
+# WIN_DIR - Windows-specific source directory\r
+# TESTDIR - directory containing test files\r
+# TOOLSDIR - directory containing build tools\r
+# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
+#    when building Tcl itself.\r
+# _INSTALLDIR - native form of the installation path. For Tcl\r
+#    this will be the root of the Tcl installation. For extensions\r
+#    this will be the lib directory under the root.\r
+# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
+#    headers and libraries from an installed Tcl, and 0 if built against\r
+#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
+#    named.\r
+# _TCL_H - native path to the tcl.h file\r
+#\r
+# If Tk is involved, also sets the following\r
+# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
+#    Tk itself.\r
+# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
+# _TK_H - native path to the tk.h file\r
+\r
+# Root directory for sources and assumed subdirectories\r
+ROOT = $(MAKEDIR)\..\r
+# The following paths CANNOT have spaces in them as they appear on the\r
+# left side of implicit rules.\r
+!ifndef COMPATDIR\r
+COMPATDIR      = $(ROOT)\compat\r
+!endif\r
+!ifndef DOCDIR\r
+DOCDIR         = $(ROOT)\doc\r
+!endif\r
+!ifndef GENERICDIR\r
+GENERICDIR     = $(ROOT)\generic\r
+!endif\r
+!ifndef TOOLSDIR\r
+TOOLSDIR       = $(ROOT)\tools\r
+!endif\r
+!ifndef TESTDIR\r
+TESTDIR        = $(ROOT)\tests\r
+!endif\r
+!ifndef LIBDIR\r
+!if exist("$(ROOT)\library")\r
+LIBDIR          = $(ROOT)\library\r
+!else\r
+LIBDIR          = $(ROOT)\lib\r
+!endif\r
+!endif\r
+!ifndef DEMODIR\r
+!if exist("$(LIBDIR)\demos")\r
+DEMODIR                = $(LIBDIR)\demos\r
+!else\r
+DEMODIR                = $(ROOT)\demos\r
+!endif\r
+!endif # ifndef DEMODIR\r
+# Do NOT use WINDIR because it is Windows internal environment\r
+# variable to point to c:\windows!\r
+WIN_DIR                = $(ROOT)\win\r
+\r
+!ifndef RCDIR\r
+!if exist("$(WIN_DIR)\rc")\r
+RCDIR           = $(WIN_DIR)\rc\r
+!else\r
+RCDIR           = $(WIN_DIR)\r
+!endif\r
+!endif\r
+RCDIR = $(RCDIR:/=\)\r
+\r
+# The target directory where the built packages and binaries will be installed.\r
+# INSTALLDIR is the (optional) path specified by the user.\r
+# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
+!ifdef INSTALLDIR\r
+### Fix the path separators.\r
+_INSTALLDIR    = $(INSTALLDIR:/=\)\r
+!else\r
+### Assume the normal default.\r
+_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+\r
+# BEGIN Case 2(a) - Building Tcl itself\r
+\r
+# Only need to define _TCL_H\r
+_TCL_H = ..\generic\tcl.h\r
+\r
+# END Case 2(a) - Building Tcl itself\r
+\r
+!elseif $(DOING_TK)\r
+\r
+# BEGIN Case 2(b) - Building Tk\r
+\r
+TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
+!if "$(TCLDIR)" == ""\r
+!if [echo TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+!endif # TCLDIR == ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
+!if !exist("$(_TCL_H)")\r
+!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
+!endif\r
+\r
+_TK_H = ..\generic\tk.h\r
+\r
+# END Case 2(b) - Building Tk\r
+\r
+!else\r
+\r
+# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
+\r
+# If command line has specified Tcl location through TCLDIR, use it\r
+# else default to the INSTALLDIR setting\r
+!if "$(TCLDIR)" != ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
+TCLINSTALL     = 1\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
+TCLINSTALL     = 0\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+!endif\r
+\r
+!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
+\r
+TCLINSTALL     = 1\r
+TCLDIR          = $(_INSTALLDIR)\..\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TCLDIR                = $(_INSTALLDIR)\..\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!if [echo _TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TCLINSTALL      = 0\r
+TCLDIR         = $(_TCLDIR)\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!endif # TCLDIR\r
+\r
+!ifndef _TCL_H\r
+MSG =^\r
+Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+# Now do the same to locate Tk headers and libs if project requires Tk\r
+!if $(NEED_TK)\r
+\r
+!if "$(TKDIR)" != ""\r
+\r
+_TKDIR = $(TKDIR:/=\)\r
+!if exist("$(_TKDIR)\include\tk.h")\r
+TKINSTALL      = 1\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+!elseif exist("$(_TKDIR)\generic\tk.h")\r
+TKINSTALL      = 0\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+!endif\r
+\r
+!else # TKDIR not defined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+TKINSTALL      = 1\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TKDIR         = $(_INSTALLDIR)\..\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+TKDIR          = $(_TKDIR)\r
+\r
+!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!if [echo _TKDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
+!error *** Could not locate Tk source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TKINSTALL      = 0\r
+TKDIR          = $(_TKDIR)\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+\r
+!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!endif # TKDIR\r
+\r
+!ifndef _TK_H\r
+MSG =^\r
+Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+!endif # NEED_TK\r
+\r
+!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tcl.^\r
+*** Please set the TCLDIR macro to point to the Tcl sources.\r
+!error $(MSG)\r
+!endif\r
+\r
+!if $(NEED_TK_SOURCE)\r
+!if $(TKINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tk.^\r
+*** Please set the TKDIR macro to point to the Tk sources.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+\r
+# If INSTALLDIR set to Tcl installation root dir then reset to the\r
+# lib dir for installing extensions\r
+!if exist("$(_INSTALLDIR)\include\tcl.h")\r
+_INSTALLDIR=$(_INSTALLDIR)\lib\r
+!endif\r
+\r
+# END Case 2(c) or (d) - Building an extension\r
+!endif # if $(DOING_TCL)\r
+\r
+################################################################\r
+# 3. Determine compiler version and architecture\r
+# In this section, we figure out the compiler version and the\r
+# architecture for which we are building. This sets the\r
+# following macros:\r
+# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
+#     This is also printed by the compiler in dotted form 19.10 etc.\r
+# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
+#     compiler version 1200. This is kept only for legacy reasons as it\r
+#     does not make sense for recent Microsoft compilers. Only used for\r
+#     output directory names.\r
+# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
+# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
+# MACHINE - same as $(ARCH) - legacy\r
+# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
+\r
+cc32           = $(CC)   # built-in default.\r
+link32         = link\r
+lib32          = lib\r
+rc32           = $(RC)   # built-in default.\r
+\r
+#----------------------------------------------------------------\r
+# Figure out the compiler architecture and version by writing\r
+# the C macros to a file, preprocessing them with the C\r
+# preprocessor and reading back the created file\r
+\r
+_HASH=^#\r
+_VC_MANIFEST_EMBED_EXE=\r
+_VC_MANIFEST_EMBED_DLL=\r
+VCVER=0\r
+!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
+    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
+    && ![echo ARCH=IX86 >> vercl.x] \\r
+    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
+    && ![echo ARCH=AMD64 >> vercl.x] \\r
+    && ![echo $(_HASH)endif >> vercl.x] \\r
+    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
+!include vercl.i\r
+!if $(VCVERSION) < 1900\r
+!if ![echo VCVER= ^\> vercl.vc] \\r
+    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
+!include vercl.vc\r
+!endif\r
+!else\r
+# The simple calculation above does not apply to new Visual Studio releases\r
+# Keep the compiler version in its native form.\r
+VCVER = $(VCVERSION)\r
+!endif\r
+!endif\r
+\r
+!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# The MACHINE macro is used by legacy makefiles so set it as well\r
+!ifdef MACHINE\r
+!if "$(MACHINE)" == "x86"\r
+!undef MACHINE\r
+MACHINE = IX86\r
+!elseif "$(MACHINE)" == "x64"\r
+!undef MACHINE\r
+MACHINE = AMD64\r
+!endif\r
+!if "$(MACHINE)" != "$(ARCH)"\r
+!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
+!endif\r
+!else\r
+MACHINE=$(ARCH)\r
+!endif\r
+\r
+#---------------------------------------------------------------\r
+# The PLATFORM_IDENTIFY macro matches the values returned by\r
+# the Tcl platform::identify command\r
+!if "$(MACHINE)" == "AMD64"\r
+PLATFORM_IDENTIFY = win32-x86_64\r
+!else\r
+PLATFORM_IDENTIFY = win32-ix86\r
+!endif\r
+\r
+# The MULTIPLATFORM macro controls whether binary extensions are installed\r
+# in platform-specific directories. Intended to be set/used by extensions.\r
+!ifndef MULTIPLATFORM_INSTALL\r
+MULTIPLATFORM_INSTALL = 0\r
+!endif\r
+\r
+#------------------------------------------------------------\r
+# Figure out the *host* architecture by reading the registry\r
+\r
+!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
+NATIVE_ARCH=IX86\r
+!else\r
+NATIVE_ARCH=AMD64\r
+!endif\r
+\r
+# Since MSVC8 we must deal with manifest resources.\r
+!if $(VCVERSION) >= 1400\r
+_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
+_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
+!endif\r
+\r
+################################################################\r
+# 4. Build the nmakehlp program\r
+# This is a helper app we need to overcome nmake's limiting\r
+# environment. We will call out to it to get various bits of\r
+# information about supported compiler options etc.\r
+#\r
+# Tcl itself will always use the nmakehlp.c program which is\r
+# in its own source. It will be kept updated there.\r
+#\r
+# Extensions built against an installed Tcl will use the installed\r
+# copy of Tcl's nmakehlp.c if there is one and their own version\r
+# otherwise. In the latter case, they would also be using their own\r
+# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
+# or rules.vc.\r
+#\r
+# Extensions built against Tcl sources will use the one from the Tcl source.\r
+#\r
+# When building an extension using a sufficiently new version of Tcl,\r
+# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
+# copy of nmakehlp.c to be used.\r
+\r
+!ifndef NMAKEHLPC\r
+# Default to the one in the current directory (the extension's own nmakehlp.c)\r
+NMAKEHLPC = nmakehlp.c\r
+\r
+!if !$(DOING_TCL)\r
+!if $(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
+!endif\r
+!else # !$(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
+!endif\r
+!endif # $(TCLINSTALL)\r
+!endif # !$(DOING_TCL)\r
+\r
+!endif # NMAKEHLPC\r
+\r
+# We always build nmakehlp even if it exists since we do not know\r
+# what source it was built from.\r
+!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
+!endif\r
+\r
+################################################################\r
+# 5. Test for compiler features\r
+# Visual C++ compiler options have changed over the years. Check\r
+# which options are supported by the compiler in use.\r
+#\r
+# The following macros are set:\r
+# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
+# DEBUGFLAGS - the compiler flags to be used for debug builds\r
+# LINKERFLAGS - Flags passed to the linker\r
+#\r
+# Note that these are the compiler settings *available*, not those\r
+# that will be *used*. The latter depends on the OPTS macro settings\r
+# which we have not yet parsed.\r
+#\r
+# Also note that some of the flags in OPTIMIZATIONS are not really\r
+# related to optimization. They are placed there only for legacy reasons\r
+# as some extensions expect them to be included in that macro.\r
+\r
+# -Op improves float consistency. Note only needed for older compilers\r
+# Newer compilers do not need or support this option.\r
+!if [nmakehlp -c -Op]\r
+FPOPTS  = -Op\r
+!endif\r
+\r
+# Strict floating point semantics - present in newer compilers in lieu of -Op\r
+!if [nmakehlp -c -fp:strict]\r
+FPOPTS  = $(FPOPTS) -fp:strict\r
+!endif\r
+\r
+!if "$(MACHINE)" == "IX86"\r
+### test for pentium errata\r
+!if [nmakehlp -c -QI0f]\r
+!message *** Compiler has 'Pentium 0x0f fix'\r
+FPOPTS  = $(FPOPTS) -QI0f\r
+!else\r
+!message *** Compiler does not have 'Pentium 0x0f fix'\r
+!endif\r
+!endif\r
+\r
+### test for optimizations\r
+# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
+# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
+# stack probe at *every* function entry, not just those with more than\r
+# a page of stack allocation resulting in a performance hit.  However,\r
+# /O2 documentation is misleading as its stack probes are simply the\r
+# default page size locals allocation probes and not what is implied\r
+# by an explicit /Gs option.\r
+\r
+OPTIMIZATIONS = $(FPOPTS)\r
+\r
+!if [nmakehlp -c -O2]\r
+OPTIMIZING = 1\r
+OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
+!else\r
+# Legacy, really. All modern compilers support this\r
+!message *** Compiler does not have 'Optimizations'\r
+OPTIMIZING = 0\r
+!endif\r
+\r
+# Checks for buffer overflows in local arrays\r
+!if [nmakehlp -c -GS]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
+!endif\r
+\r
+# Link time optimization. Note that this option (potentially) makes\r
+# generated libraries only usable by the specific VC++ version that\r
+# created it. Requires /LTCG linker option\r
+!if [nmakehlp -c -GL]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
+CC_GL_OPT_ENABLED = 1\r
+!else\r
+# In newer compilers -GL and -YX are incompatible.\r
+!if [nmakehlp -c -YX]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
+!endif\r
+!endif # [nmakehlp -c -GL]\r
+\r
+DEBUGFLAGS     = $(FPOPTS)\r
+\r
+# Run time error checks. Not available or valid in a release, non-debug build\r
+# RTC is for modern compilers, -GZ is legacy\r
+!if [nmakehlp -c -RTC1]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
+!elseif [nmakehlp -c -GZ]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# Linker flags\r
+\r
+# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
+# if the linker supports a specific option. Without these flags link will\r
+# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
+# They are not passed through to the actual application / extension\r
+# link rules.\r
+!ifndef LINKER_TESTFLAGS\r
+LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
+!endif\r
+\r
+LINKERFLAGS     =\r
+\r
+# If compiler has enabled link time optimization, linker must too with -ltcg\r
+!ifdef CC_GL_OPT_ENABLED\r
+!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
+!endif\r
+!endif\r
+\r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
+########################################################################\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
+# Based on this, we will construct the actual switches to be passed to the\r
+# compiler and linker using the macros defined in the previous section.\r
+# The following macros are defined by this section based on OPTS\r
+# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
+#                1 -> build as a static library and shell\r
+# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
+# DEBUG - 1 -> debug build, 0 -> release builds\r
+# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
+# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
+# PGO     - 1 -> profile based optimization, 0 -> no\r
+# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
+#           0 -> link to static C runtime for static Tcl build.\r
+#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
+# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
+# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
+#           0 -> Use the non-thread allocator.\r
+# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
+#           C runtime, 0 -> use the debug C runtime.\r
+# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
+# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
+#           configuration (ignored for Tcl itself)\r
+# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
+# Further, LINKERFLAGS are modified based on above.\r
+\r
+# Default values for all the above\r
+STATIC_BUILD   = 0\r
+TCL_THREADS    = 1\r
+DEBUG          = 0\r
+SYMBOLS                = 0\r
+PROFILE                = 0\r
+PGO            = 0\r
+MSVCRT         = 1\r
+TCL_USE_STATIC_PACKAGES        = 0\r
+USE_THREAD_ALLOC = 1\r
+UNCHECKED      = 0\r
+CONFIG_CHECK    = 1\r
+!if $(DOING_TCL)\r
+USE_STUBS       = 0\r
+!else\r
+USE_STUBS       = 1\r
+!endif\r
+\r
+# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
+# set the above macros based on OPTS content\r
+!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
+\r
+# OPTS are specified, parse them\r
+\r
+!if [nmakehlp -f $(OPTS) "static"]\r
+!message *** Doing static\r
+STATIC_BUILD   = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nostubs"]\r
+!message *** Not using stubs\r
+USE_STUBS      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+!message *** Doing nomsvcrt\r
+MSVCRT         = 0\r
+!else\r
+!if [nmakehlp -f $(OPTS) "msvcrt"]\r
+!message *** Doing msvcrt\r
+!else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
+MSVCRT         = 0\r
+!endif\r
+!endif\r
+!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+\r
+!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
+!message *** Doing staticpkg\r
+TCL_USE_STATIC_PACKAGES        = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nothreads"]\r
+!message *** Compile explicitly for non-threaded tcl\r
+TCL_THREADS = 0\r
+USE_THREAD_ALLOC= 0\r
+!endif\r
+\r
+!if $(TCL_MAJOR_VERSION) == 8\r
+!if [nmakehlp -f $(OPTS) "time64bit"]\r
+!message *** Force 64-bit time_t\r
+_USE_64BIT_TIME_T = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
+# Yes, it's weird that the "symbols" option controls DEBUG and\r
+# the "pdbs" option controls SYMBOLS. That's historical.\r
+!if [nmakehlp -f $(OPTS) "symbols"]\r
+!message *** Doing symbols\r
+DEBUG          = 1\r
+!else\r
+DEBUG          = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pdbs"]\r
+!message *** Doing pdbs\r
+SYMBOLS                = 1\r
+!else\r
+SYMBOLS                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "profile"]\r
+!message *** Doing profile\r
+PROFILE                = 1\r
+!else\r
+PROFILE                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pgi"]\r
+!message *** Doing profile guided optimization instrumentation\r
+PGO            = 1\r
+!elseif [nmakehlp -f $(OPTS) "pgo"]\r
+!message *** Doing profile guided optimization\r
+PGO            = 2\r
+!else\r
+PGO            = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "loimpact"]\r
+!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
+!endif\r
+\r
+# TBD - should get rid of this option\r
+!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
+!message *** Doing thrdalloc\r
+USE_THREAD_ALLOC = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "tclalloc"]\r
+USE_THREAD_ALLOC = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "unchecked"]\r
+!message *** Doing unchecked\r
+UNCHECKED = 1\r
+!else\r
+UNCHECKED = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
+CONFIG_CHECK = 1\r
+!else\r
+CONFIG_CHECK = 0\r
+!endif\r
+\r
+!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
+\r
+# Set linker flags based on above\r
+\r
+!if $(PGO) > 1\r
+!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!elseif $(PGO) > 0\r
+!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+################################################################\r
+# 8. Parse the STATS macro to configure code instrumentation\r
+# The following macros are set by this section:\r
+# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
+#                 0 -> disables\r
+# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
+#                     0 -> disables\r
+\r
+# Default both are off\r
+TCL_MEM_DEBUG      = 0\r
+TCL_COMPILE_DEBUG   = 0\r
+\r
+!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
+\r
+!if [nmakehlp -f $(STATS) "memdbg"]\r
+!message *** Doing memdbg\r
+TCL_MEM_DEBUG      = 1\r
+!else\r
+TCL_MEM_DEBUG      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(STATS) "compdbg"]\r
+!message *** Doing compdbg\r
+TCL_COMPILE_DEBUG   = 1\r
+!else\r
+TCL_COMPILE_DEBUG   = 0\r
+!endif\r
+\r
+!endif\r
+\r
+####################################################################\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
+# The following macros are set by this section:\r
+# WARNINGS - compiler switches that control the warnings level\r
+# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
+#                     0 -> enable deprecated functions\r
+\r
+# Defaults - Permit deprecated functions and warning level 3\r
+TCL_NO_DEPRECATED          = 0\r
+WARNINGS                   = -W3\r
+\r
+!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
+\r
+!if [nmakehlp -f $(CHECKS) "nodep"]\r
+!message *** Doing nodep check\r
+TCL_NO_DEPRECATED          = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
+!message *** Doing full warnings check\r
+WARNINGS                   = -W4\r
+!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
+!endif\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
+!message *** Doing 64bit portability warnings\r
+WARNINGS                   = $(WARNINGS) -Wp64\r
+!endif\r
+\r
+!endif\r
+\r
+\r
+################################################################\r
+# 10. Construct output directory and file paths\r
+# Figure-out how to name our intermediate and output directories.\r
+# In order to avoid inadvertent mixing of object files built using\r
+# different compilers, build configurations etc.,\r
+#\r
+# Naming convention (suffixes):\r
+#   t = full thread support. (Not used for Tcl >= 8.7)\r
+#   s = static library (as opposed to an import library)\r
+#   g = linked to the debug enabled C run-time.\r
+#   x = special static build when it links to the dynamic C run-time.\r
+#\r
+# The following macros are set in this section:\r
+# SUFX - the suffix to use for binaries based on above naming convention\r
+# BUILDDIRTOP - the toplevel default output directory\r
+#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
+# TMP_DIR - directory where object files are created\r
+# OUT_DIR - directory where output executables are created\r
+# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
+# parent makefile (or command line). The default values are\r
+# based on BUILDDIRTOP.\r
+# STUBPREFIX - name of the stubs library for this project\r
+# PRJIMPLIB - output path of the generated project import library\r
+# PRJLIBNAME - name of generated project library\r
+# PRJLIB     - output path of generated project library\r
+# PRJSTUBLIBNAME - name of the generated project stubs library\r
+# PRJSTUBLIB - output path of the generated project stubs library\r
+# RESFILE - output resource file (only if not static build)\r
+\r
+SUFX       = tsgx\r
+\r
+!if $(DEBUG)\r
+BUILDDIRTOP = Debug\r
+!else\r
+BUILDDIRTOP = Release\r
+!endif\r
+\r
+!if "$(MACHINE)" != "IX86"\r
+BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
+!endif\r
+!if $(VCVER) > 6\r
+BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
+!endif\r
+\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
+SUFX       = $(SUFX:g=)\r
+!endif\r
+\r
+TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
+\r
+!if !$(STATIC_BUILD)\r
+TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
+SUFX       = $(SUFX:s=)\r
+EXT        = dll\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!else\r
+TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
+EXT        = lib\r
+!if !$(MSVCRT)\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!endif\r
+!endif\r
+\r
+!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
+TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
+SUFX       = $(SUFX:t=)\r
+!endif\r
+\r
+!ifndef TMP_DIR\r
+TMP_DIR            = $(TMP_DIRFULL)\r
+!ifndef OUT_DIR\r
+OUT_DIR            = .\$(BUILDDIRTOP)\r
+!endif\r
+!else\r
+!ifndef OUT_DIR\r
+OUT_DIR            = $(TMP_DIR)\r
+!endif\r
+!endif\r
+\r
+# Relative paths -> absolute\r
+!if [echo OUT_DIR = \> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
+!endif\r
+!if [echo TMP_DIR = \>> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
+!endif\r
+!include nmakehlp.out\r
+\r
+# The name of the stubs library for the project being built\r
+STUBPREFIX      = $(PROJECT)stub\r
+\r
+#\r
+# Set up paths to various Tcl executables and libraries needed by extensions\r
+#\r
+\r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
+TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
+TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
+\r
+TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
+TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+\r
+!else # !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+\r
+# When building extensions, we need to locate tclsh. Depending on version\r
+# of Tcl we are building against, this may or may not have a "t" suffix.\r
+# Try various possibilities in turn.\r
+TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist("$(TCLSH)")\r
+TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+\r
+TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\lib\r
+TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
+TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
+\r
+!else # Building against Tcl sources\r
+\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist($(TCLSH))\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\library\r
+TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = $(_TCLDIR)\tools\r
+TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
+\r
+!endif # TCLINSTALL\r
+\r
+tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
+\r
+!endif # $(DOING_TCL)\r
+\r
+# We need a tclsh that will run on the host machine as part of the build.\r
+# IX86 runs on all architectures.\r
+!ifndef TCLSH_NATIVE\r
+!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
+TCLSH_NATIVE   = $(TCLSH)\r
+!else\r
+!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
+!endif\r
+!endif\r
+\r
+# Do the same for Tk and Tk extensions that require the Tk libraries\r
+!if $(DOING_TK) || $(NEED_TK)\r
+WISHNAMEPREFIX = wish\r
+WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
+TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
+TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
+\r
+!if $(DOING_TK)\r
+WISH           = $(OUT_DIR)\$(WISHNAME)\r
+TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
+TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
+\r
+!else # effectively NEED_TK\r
+\r
+!if $(TKINSTALL) # Building against installed Tk\r
+WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
+!else # Building against Tk sources\r
+\r
+WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
+!endif # TKINSTALL\r
+\r
+tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
+\r
+!endif # $(DOING_TK)\r
+!endif # $(DOING_TK) || $(NEED_TK)\r
+\r
+# Various output paths\r
+PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
+\r
+PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
+\r
+# If extension parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
+!ifdef RCFILE\r
+RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
+!else\r
+RESFILE = $(TMP_DIR)\$(PROJECT).res\r
+!endif\r
+!endif\r
+\r
+###################################################################\r
+# 11. Construct the paths for the installation directories\r
+# The following macros get defined in this section:\r
+# LIB_INSTALL_DIR - where libraries should be installed\r
+# BIN_INSTALL_DIR - where the executables should be installed\r
+# DOC_INSTALL_DIR - where documentation should be installed\r
+# SCRIPT_INSTALL_DIR - where scripts should be installed\r
+# INCLUDE_INSTALL_DIR - where C include files should be installed\r
+# DEMO_INSTALL_DIR - where demos should be installed\r
+# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
+\r
+!if $(DOING_TCL) || $(DOING_TK)\r
+LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
+BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
+DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
+!if $(DOING_TCL)\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
+!else # DOING_TK\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!endif\r
+DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
+\r
+!else # extension other than Tk\r
+\r
+PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
+!if $(MULTIPLATFORM_INSTALL)\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+!else\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+!endif\r
+DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
+DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
+\r
+!endif\r
+\r
+###################################################################\r
+# 12. Set up actual options to be passed to the compiler and linker\r
+# Now we have all the information we need, set up the actual flags and\r
+# options that we will pass to the compiler and linker. The main\r
+# makefile should use these in combination with whatever other flags\r
+# and switches are specific to it.\r
+# The following macros are defined, names are for historical compatibility:\r
+# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
+# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
+# crt - Compiler switch that selects the appropriate C runtime\r
+# cdebug - Compiler switches related to debug AND optimizations\r
+# cwarn - Compiler switches that set warning levels\r
+# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
+# ldebug - Linker switches controlling debug information and optimization\r
+# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
+# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
+# conlflags - complete linker switches for console program (subsumes lflags)\r
+# guilflags - complete linker switches for GUI program (subsumes lflags)\r
+# baselibs - minimum Windows libraries required. Parent makefile can\r
+#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
+\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
+\r
+!if $(TCL_MEM_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
+!endif\r
+!if $(TCL_COMPILE_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_COMPILE_DEBUG /DTCL_COMPILE_STATS\r
+!endif\r
+!if $(TCL_THREADS) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_THREADS=1\r
+!if $(USE_THREAD_ALLOC) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1\r
+!endif\r
+!endif\r
+!if $(STATIC_BUILD)\r
+OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
+!endif\r
+!if $(TCL_NO_DEPRECATED)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
+!endif\r
+\r
+!if $(USE_STUBS)\r
+# Note we do not define USE_TCL_STUBS even when building tk since some\r
+# test targets in tk do not use stubs\r
+!if !$(DOING_TCL)\r
+USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
+!if $(NEED_TK)\r
+USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
+!endif\r
+!endif\r
+!endif # USE_STUBS\r
+\r
+!if !$(DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DNDEBUG\r
+!if $(OPTIMIZING)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_OPTIMIZED\r
+!endif\r
+!endif\r
+!if $(PROFILE)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_PROFILED\r
+!endif\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
+!endif\r
+!if $(VCVERSION) < 1300\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
+!endif\r
+\r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
+!if "$(_USE_64BIT_TIME_T)" == "1"\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
+!endif\r
+\r
+# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
+COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
+\r
+# Like the TEA system only set this non empty for non-Tk extensions\r
+# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
+# so we pass both\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+PKGNAMEFLAGS = /DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
+               /DMODULE_SCOPE=extern\r
+!endif\r
+\r
+# crt picks the C run time based on selected OPTS\r
+!if $(MSVCRT)\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MDd\r
+!else\r
+crt = -MD\r
+!endif\r
+!else\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MTd\r
+!else\r
+crt = -MT\r
+!endif\r
+!endif\r
+\r
+# cdebug includes compiler options for debugging as well as optimization.\r
+!if $(DEBUG)\r
+\r
+# In debugging mode, optimizations need to be disabled\r
+cdebug = -Zi -Od $(DEBUGFLAGS)\r
+\r
+!else\r
+\r
+cdebug = $(OPTIMIZATIONS)\r
+!if $(SYMBOLS)\r
+cdebug = $(cdebug) -Zi\r
+!endif\r
+\r
+!endif # $(DEBUG)\r
+\r
+# cwarn includes default warning levels.\r
+cwarn = $(WARNINGS)\r
+\r
+!if "$(MACHINE)" == "AMD64"\r
+# Disable pointer<->int warnings related to cast between different sizes\r
+# There are a gadzillion of these due to use of ClientData and\r
+# clutter up compiler\r
+# output increasing chance of a real warning getting lost. So disable them.\r
+# Eventually some day, Tcl will be 64-bit clean.\r
+cwarn = $(cwarn) -wd4311 -wd4312\r
+!endif\r
+\r
+### Common compiler options that are architecture specific\r
+!if "$(MACHINE)" == "ARM"\r
+carch = /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
+!else\r
+carch =\r
+!endif\r
+\r
+!if $(DEBUG)\r
+# Turn warnings into errors\r
+cwarn = $(cwarn) -WX\r
+!endif\r
+\r
+INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WIN_DIR)" -I"$(COMPATDIR)"\r
+!endif\r
+\r
+# These flags are defined roughly in the order of the pre-reform\r
+# rules.vc/makefile.vc to help visually compare that the pre- and\r
+# post-reform build logs\r
+\r
+# cflags contains generic flags used for building practically all object files\r
+cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
+\r
+# appcflags contains $(cflags) and flags for building the application\r
+# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
+# flags used for building shared object files The two differ in the\r
+# BUILD_$(PROJECT) macro which should be defined only for the shared\r
+# library *implementation* and not for its caller interface\r
+\r
+appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
+appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
+pkgcflags = $(appcflags) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+\r
+# stubscflags contains $(cflags) plus flags used for building a stubs\r
+# library for the package.  Note: /DSTATIC_BUILD is defined in\r
+# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
+# library. However the stubs library is ALWAYS static hence included\r
+# here irrespective of the OPTS setting.\r
+#\r
+# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
+# without stating why. Tcl itself compiled stubs libs with this flag.\r
+# so we do not remove it from cflags. -GL may prevent extensions\r
+# compiled with one VC version to fail to link against stubs library\r
+# compiled with another VC version. Check for this and fix accordingly.\r
+stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl /DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
+\r
+# Link flags\r
+\r
+!if $(DEBUG)\r
+ldebug = -debug -debugtype:cv\r
+!else\r
+ldebug = -release -opt:ref -opt:icf,3\r
+!if $(SYMBOLS)\r
+ldebug = $(ldebug) -debug -debugtype:cv\r
+!endif\r
+!endif\r
+\r
+# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
+!if $(PROFILE)\r
+ldebug= $(ldebug) -profile\r
+!endif\r
+\r
+### Declarations common to all linker versions\r
+lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+lflags = $(lflags) -nodefaultlib:libucrt.lib\r
+!endif\r
+\r
+dlllflags = $(lflags) -dll\r
+conlflags = $(lflags) -subsystem:console\r
+guilflags = $(lflags) -subsystem:windows\r
+\r
+# Libraries that are required for every image.\r
+# Extensions should define any additional libraries with $(PRJ_LIBS)\r
+winlibs   = kernel32.lib advapi32.lib\r
+\r
+!if $(NEED_TK)\r
+winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
+!endif\r
+\r
+# Avoid 'unresolved external symbol __security_cookie' errors.\r
+# c.f. http://support.microsoft.com/?id=894573\r
+!if "$(MACHINE)" == "AMD64"\r
+!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
+winlibs   = $(winlibs) bufferoverflowU.lib\r
+!endif\r
+!endif\r
+\r
+baselibs = $(winlibs) $(PRJ_LIBS)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+baselibs   = $(baselibs) ucrt.lib\r
+!endif\r
+\r
+################################################################\r
+# 13. Define standard commands, common make targets and implicit rules\r
+\r
+CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
+CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
+CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
+\r
+LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
+DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+\r
+CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
+           $(TCL_INCLUDES) \\r
+           /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
+           /DDOTVERSION=\"$(DOTVERSION)\" \\r
+           /DVERSION=\"$(VERSION)\" \\r
+           /DSUFX=\"$(SUFX)\" \\r
+           /DPROJECT=\"$(PROJECT)\" \\r
+           /DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
+\r
+!ifndef DEFAULT_BUILD_TARGET\r
+DEFAULT_BUILD_TARGET = $(PROJECT)\r
+!endif\r
+\r
+default-target: $(DEFAULT_BUILD_TARGET)\r
+\r
+!if $(MULTIPLATFORM_INSTALL)\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!else\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!endif\r
+\r
+default-pkgindex-tea:\r
+       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
+@PACKAGE_VERSION@    $(DOTVERSION)\r
+@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
+@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
+@PKG_LIB_FILE@       $(PRJLIBNAME)\r
+<<\r
+\r
+default-install: default-install-binaries default-install-libraries\r
+!if $(SYMBOLS)\r
+default-install: default-install-pdbs\r
+!endif\r
+\r
+# Again to deal with historical brokenness, there is some confusion\r
+# in terminlogy. For extensions, the "install-binaries" was used to\r
+# locate target directory for *binary shared libraries* and thus\r
+# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
+# for executables (exes). On the other hand the "install-libraries"\r
+# target is for *scripts* and should have been called "install-scripts".\r
+default-install-binaries: $(PRJLIB)\r
+       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
+\r
+# Alias for default-install-scripts\r
+default-install-libraries: default-install-scripts\r
+\r
+default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
+       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
+       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
+       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
+       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
+\r
+default-install-stubs:\r
+       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
+       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
+       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
+\r
+default-install-pdbs:\r
+       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
+\r
+# "emacs font-lock highlighting fix\r
+\r
+default-install-docs-html:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-docs-n:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-demos:\r
+       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
+       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
+       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
+\r
+default-clean:\r
+       @echo Cleaning $(TMP_DIR)\* ...\r
+       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
+       @echo Cleaning $(WIN_DIR)\nmakehlp.obj, nmakehlp.exe ...\r
+       @if exist $(WIN_DIR)\nmakehlp.obj del $(WIN_DIR)\nmakehlp.obj\r
+       @if exist $(WIN_DIR)\nmakehlp.exe del $(WIN_DIR)\nmakehlp.exe\r
+       @if exist $(WIN_DIR)\nmakehlp.out del $(WIN_DIR)\nmakehlp.out\r
+       @echo Cleaning $(WIN_DIR)\nmhlp-out.txt ...\r
+       @if exist $(WIN_DIR)\nmhlp-out.txt del $(WIN_DIR)\nmhlp-out.txt\r
+       @echo Cleaning $(WIN_DIR)\_junk.pch ...\r
+       @if exist $(WIN_DIR)\_junk.pch del $(WIN_DIR)\_junk.pch\r
+       @echo Cleaning $(WIN_DIR)\vercl.x, vercl.i ...\r
+       @if exist $(WIN_DIR)\vercl.x del $(WIN_DIR)\vercl.x\r
+       @if exist $(WIN_DIR)\vercl.i del $(WIN_DIR)\vercl.i\r
+       @echo Cleaning $(WIN_DIR)\versions.vc, version.vc ...\r
+       @if exist $(WIN_DIR)\versions.vc del $(WIN_DIR)\versions.vc\r
+       @if exist $(WIN_DIR)\version.vc del $(WIN_DIR)\version.vc\r
+\r
+default-hose: default-clean\r
+       @echo Hosing $(OUT_DIR)\* ...\r
+       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
+\r
+# Only for backward compatibility\r
+default-distclean: default-hose\r
+\r
+default-setup:\r
+       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
+       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
+\r
+!if "$(TESTPAT)" != ""\r
+TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
+!endif\r
+\r
+default-test: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
+\r
+default-shell: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       $(DEBUGGER) $(TCLSH)\r
+\r
+# Generation of Windows version resource\r
+!ifdef RCFILE\r
+\r
+# Note: don't use $** in below rule because there may be other dependencies\r
+# and only the "main" rc must be passed to the resource compiler\r
+$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
+       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
+\r
+!else\r
+\r
+# If parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
+\r
+$(TMP_DIR)\$(PROJECT).rc:\r
+       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
+#include <winver.h>\r
+\r
+VS_VERSION_INFO VERSIONINFO\r
+ FILEVERSION   COMMAVERSION\r
+ PRODUCTVERSION        COMMAVERSION\r
+ FILEFLAGSMASK 0x3fL\r
+#ifdef DEBUG\r
+ FILEFLAGS     VS_FF_DEBUG\r
+#else\r
+ FILEFLAGS     0x0L\r
+#endif\r
+ FILEOS                VOS_NT_WINDOWS32\r
+ FILETYPE      VFT_DLL\r
+ FILESUBTYPE   0x0L\r
+BEGIN\r
+    BLOCK "StringFileInfo"\r
+    BEGIN\r
+        BLOCK "040904b0"\r
+        BEGIN\r
+            VALUE "FileDescription",  "Tcl extension " PROJECT\r
+            VALUE "OriginalFilename", PRJLIBNAME\r
+            VALUE "FileVersion",      DOTVERSION\r
+            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
+            VALUE "ProductVersion",   DOTVERSION\r
+        END\r
+    END\r
+    BLOCK "VarFileInfo"\r
+    BEGIN\r
+        VALUE "Translation", 0x409, 1200\r
+    END\r
+END\r
+\r
+<<\r
+\r
+!endif # ifdef RCFILE\r
+\r
+!ifndef DISABLE_IMPLICIT_RULES\r
+DISABLE_IMPLICIT_RULES = 0\r
+!endif\r
+\r
+!if !$(DISABLE_IMPLICIT_RULES)\r
+# Implicit rule definitions - only for building library objects. For stubs and\r
+# main application, the makefile should define explicit rules.\r
+\r
+{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(WIN_DIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(WIN_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+.SUFFIXES:\r
+.SUFFIXES:.c .rc\r
+\r
+!endif\r
+\r
+################################################################\r
+# 14. Sanity check selected options against Tcl build options\r
+# When building an extension, certain configuration options should\r
+# match the ones used when Tcl was built. Here we check and\r
+# warn on a mismatch.\r
+!if !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
+!endif\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
+!endif\r
+!endif # TCLINSTALL\r
+\r
+!if $(CONFIG_CHECK)\r
+!ifdef TCLNMAKECONFIG\r
+!include $(TCLNMAKECONFIG)\r
+\r
+!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
+!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
+!endif\r
+!if $(TCL_VERSION) < 87 && defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
+!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
+!endif\r
+!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
+!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
+!endif\r
+!endif\r
+\r
+!endif # TCLNMAKECONFIG\r
+\r
+!endif # !$(DOING_TCL)\r
+\r
+\r
+#----------------------------------------------------------\r
+# Display stats being used.\r
+#----------------------------------------------------------\r
+\r
+!if !$(DOING_TCL)\r
+!message *** Building against Tcl at '$(_TCLDIR)'\r
+!endif\r
+!if !$(DOING_TK) && $(NEED_TK)\r
+!message *** Building against Tk at '$(_TKDIR)'\r
+!endif\r
+!message *** Intermediate directory will be '$(TMP_DIR)'\r
+!message *** Output directory will be '$(OUT_DIR)'\r
+!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
+!message *** Suffix for binaries will be '$(SUFX)'\r
+!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
+\r
+!endif # ifdef _RULES_VC\r
similarity index 93%
rename from pkgs/tdbc1.1.1/win/targets.vc
rename to pkgs/tdbcmysql1.1.2/win/targets.vc
index 7f1d388..077e8f7 100644 (file)
@@ -4,7 +4,7 @@
 # Part of the nmake based build system for Tcl and its extensions.\r
 # This file defines some standard targets for the convenience of extensions\r
 # and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
 \r
 $(PROJECT): setup pkgindex $(PRJLIB)\r
 \r
diff --git a/pkgs/tdbcodbc1.1.1/tclconfig/install-sh b/pkgs/tdbcodbc1.1.1/tclconfig/install-sh
deleted file mode 100644 (file)
index 7c34c3f..0000000
+++ /dev/null
@@ -1,528 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2011-04-20.01; # UTC
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# 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.
-
-nl='
-'
-IFS=" ""       $nl"
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
-
-# Put in absolute file names if you don't have them in your path;
-# or use environment vars.
-
-chgrpprog=${CHGRPPROG-chgrp}
-chmodprog=${CHMODPROG-chmod}
-chownprog=${CHOWNPROG-chown}
-cmpprog=${CMPPROG-cmp}
-cpprog=${CPPROG-cp}
-mkdirprog=${MKDIRPROG-mkdir}
-mvprog=${MVPROG-mv}
-rmprog=${RMPROG-rm}
-stripprog=${STRIPPROG-strip}
-
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
-posix_mkdir=
-
-# Desired mode of installed file.
-mode=0755
-
-chgrpcmd=
-chmodcmd=$chmodprog
-chowncmd=
-mvcmd=$mvprog
-rmcmd="$rmprog -f"
-stripcmd=
-
-src=
-dst=
-dir_arg=
-dst_arg=
-
-copy_on_change=false
-no_target_directory=
-
-usage="\
-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
-   or: $0 [OPTION]... SRCFILES... DIRECTORY
-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
-   or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
-     --help     display this help and exit.
-     --version  display version info and exit.
-
-  -c            (ignored)
-  -C            install only if different (preserve the last data modification time)
-  -d            create directories instead of installing files.
-  -g GROUP      $chgrpprog installed files to GROUP.
-  -m MODE       $chmodprog installed files to MODE.
-  -o USER       $chownprog installed files to USER.
-  -s            $stripprog installed files.
-  -S            $stripprog installed files.
-  -t DIRECTORY  install into DIRECTORY.
-  -T            report an error if DSTFILE is a directory.
-
-Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
-  RMPROG STRIPPROG
-"
-
-while test $# -ne 0; do
-  case $1 in
-    -c) ;;
-
-    -C) copy_on_change=true;;
-
-    -d) dir_arg=true;;
-
-    -g) chgrpcmd="$chgrpprog $2"
-       shift;;
-
-    --help) echo "$usage"; exit $?;;
-
-    -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
-
-    -o) chowncmd="$chownprog $2"
-       shift;;
-
-    -s) stripcmd=$stripprog;;
-
-    -S) stripcmd="$stripprog $2"
-       shift;;
-
-    -t) dst_arg=$2
-       shift;;
-
-    -T) no_target_directory=true;;
-
-    --version) echo "$0 $scriptversion"; exit $?;;
-
-    --)        shift
-       break;;
-
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
-
-    *)  break;;
-  esac
-  shift
-done
-
-if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
-  # When -d is used, all remaining arguments are directories to create.
-  # When -t is used, the destination is already specified.
-  # Otherwise, the last argument is the destination.  Remove it from $@.
-  for arg
-  do
-    if test -n "$dst_arg"; then
-      # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dst_arg"
-      shift # fnord
-    fi
-    shift # arg
-    dst_arg=$arg
-  done
-fi
-
-if test $# -eq 0; then
-  if test -z "$dir_arg"; then
-    echo "$0: no input file specified." >&2
-    exit 1
-  fi
-  # It's OK to call `install-sh -d' without argument.
-  # This can happen when creating conditional directories.
-  exit 0
-fi
-
-if test -z "$dir_arg"; then
-  do_exit='(exit $ret); exit $ret'
-  trap "ret=129; $do_exit" 1
-  trap "ret=130; $do_exit" 2
-  trap "ret=141; $do_exit" 13
-  trap "ret=143; $do_exit" 15
-
-  # Set umask so as not to create temps with too-generous modes.
-  # However, 'strip' requires both read and write access to temps.
-  case $mode in
-    # Optimize common cases.
-    *644) cp_umask=133;;
-    *755) cp_umask=22;;
-
-    *[0-7])
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw='% 200'
-      fi
-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
-    *)
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw=,u+rw
-      fi
-      cp_umask=$mode$u_plus_rw;;
-  esac
-fi
-
-for src
-do
-  # Protect names starting with `-'.
-  case $src in
-    -*) src=./$src;;
-  esac
-
-  if test -n "$dir_arg"; then
-    dst=$src
-    dstdir=$dst
-    test -d "$dstdir"
-    dstdir_status=$?
-  else
-
-    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
-    # might cause directories to be created, which would be especially bad
-    # if $src (and thus $dsttmp) contains '*'.
-    if test ! -f "$src" && test ! -d "$src"; then
-      echo "$0: $src does not exist." >&2
-      exit 1
-    fi
-
-    if test -z "$dst_arg"; then
-      echo "$0: no destination specified." >&2
-      exit 1
-    fi
-
-    dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
-
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
-    if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
-      fi
-      dstdir=$dst
-      dst=$dstdir/`basename "$src"`
-      dstdir_status=0
-    else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
-      test -d "$dstdir"
-      dstdir_status=$?
-    fi
-  fi
-
-  obsolete_mkdir_used=false
-
-  if test $dstdir_status != 0; then
-    case $posix_mkdir in
-      '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
-       else
-         mkdir_mode=
-       fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
-    esac
-
-    if
-      $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
-      )
-    then :
-    else
-
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
-      # or it failed possibly due to a race condition.  Create the
-      # directory the slow way, step by step, checking for races as we go.
-
-      case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
-      esac
-
-      eval "$initialize_posix_glob"
-
-      oIFS=$IFS
-      IFS=/
-      $posix_glob set -f
-      set fnord $dstdir
-      shift
-      $posix_glob set +f
-      IFS=$oIFS
-
-      prefixes=
-
-      for d
-      do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
-      done
-
-      if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
-      fi
-    fi
-  fi
-
-  if test -n "$dir_arg"; then
-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
-  else
-
-    # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
-
-    # Trap to clean up those temp files at exit.
-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
-
-    # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
-
-    # 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 $cpprog $src $dsttmp" command.
-    #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
-
-    # If -C, don't bother to copy if it wouldn't change the file.
-    if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
-       set X $old && old=:$2:$4:$5:$6 &&
-       set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
-       test "$old" = "$new" &&
-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
-    then
-      rm -f "$dsttmp"
-    else
-      # Rename the file to the real destination.
-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
-
-      # The rename failed, perhaps because mv can't rename something else
-      # to itself, or perhaps because mv is so ancient that it does not
-      # support -f.
-      {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
-      }
-    fi || exit 1
-
-    trap '' 0
-  fi
-done
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/pkgs/tdbcodbc1.1.1/tclconfig/tcl.m4 b/pkgs/tdbcodbc1.1.1/tclconfig/tcl.m4
deleted file mode 100644 (file)
index 7d901f9..0000000
+++ /dev/null
@@ -1,4033 +0,0 @@
-# tcl.m4 --
-#
-#      This file provides a set of autoconf macros to help TEA-enable
-#      a Tcl extension.
-#
-# Copyright (c) 1999-2000 Ajuba Solutions.
-# Copyright (c) 2002-2005 ActiveState Corporation.
-#
-# See the file "license.terms" for information on usage and redistribution
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-
-AC_PREREQ(2.57)
-
-# Possible values for key variables defined:
-#
-# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
-# TEA_PLATFORM        - windows unix
-# TEA_TK_EXTENSION    - True if this is a Tk extension
-#
-
-#------------------------------------------------------------------------
-# TEA_PATH_TCLCONFIG --
-#
-#      Locate the tclConfig.sh file and perform a sanity check on
-#      the Tcl compile flags
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tcl=...
-#
-#      Defines the following vars:
-#              TCL_BIN_DIR     Full path to the directory containing
-#                              the tclConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TCLCONFIG], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-    #
-    # Ok, lets find the tcl configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tcl
-    #
-
-    if test x"${no_tcl}" = x ; then
-       # we reset no_tcl in case something fails here
-       no_tcl=true
-       AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
-               [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
-       AC_MSG_CHECKING([for Tcl configuration])
-       AC_CACHE_VAL(ac_cv_c_tclconfig,[
-
-           # First check to see if --with-tcl was specified.
-           if test x"${with_tclconfig}" != x ; then
-               case "${with_tclconfig}" in
-                   */tclConfig.sh )
-                       if test -f "${with_tclconfig}"; then
-                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
-                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tclconfig}/tclConfig.sh" ; then
-                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tcl installation
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ../tcl \
-                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tcl \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tcl \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tcl \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tclconfig}" = x ; then
-           TCL_BIN_DIR="# no Tcl configs found"
-           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
-       else
-           no_tcl=
-           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
-           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_TKCONFIG --
-#
-#      Locate the tkConfig.sh file
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tk=...
-#
-#      Defines the following vars:
-#              TK_BIN_DIR      Full path to the directory containing
-#                              the tkConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TKCONFIG], [
-    #
-    # Ok, lets find the tk configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tk
-    #
-
-    if test x"${no_tk}" = x ; then
-       # we reset no_tk in case something fails here
-       no_tk=true
-       AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
-               [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
-       AC_MSG_CHECKING([for Tk configuration])
-       AC_CACHE_VAL(ac_cv_c_tkconfig,[
-
-           # First check to see if --with-tkconfig was specified.
-           if test x"${with_tkconfig}" != x ; then
-               case "${with_tkconfig}" in
-                   */tkConfig.sh )
-                       if test -f "${with_tkconfig}"; then
-                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
-                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tkconfig}/tkConfig.sh" ; then
-                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tk library
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ../tk \
-                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tk \
-                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tk \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tk \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tkconfig}" = x ; then
-           TK_BIN_DIR="# no Tk configs found"
-           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
-       else
-           no_tk=
-           TK_BIN_DIR="${ac_cv_c_tkconfig}"
-           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TCLCONFIG --
-#
-#      Load the tclConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TCL_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_BIN_DIR
-#              TCL_SRC_DIR
-#              TCL_LIB_FILE
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TCLCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
-
-    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TCL_BIN_DIR}/tclConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
-    # If the TCL_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TCL_LIB_SPEC will be set to the value
-    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
-    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
-        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
-        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tcl was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tcl.framework installed in an arbitrary location.
-       case ${TCL_DEFS} in
-           *TCL_FRAMEWORK*)
-               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
-                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
-                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
-                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
-                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
-                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
-    AC_SUBST(TCL_VERSION)
-    AC_SUBST(TCL_PATCH_LEVEL)
-    AC_SUBST(TCL_BIN_DIR)
-    AC_SUBST(TCL_SRC_DIR)
-
-    AC_SUBST(TCL_LIB_FILE)
-    AC_SUBST(TCL_LIB_FLAG)
-    AC_SUBST(TCL_LIB_SPEC)
-
-    AC_SUBST(TCL_STUB_LIB_FILE)
-    AC_SUBST(TCL_STUB_LIB_FLAG)
-    AC_SUBST(TCL_STUB_LIB_SPEC)
-
-    AC_MSG_CHECKING([platform])
-    hold_cc=$CC; CC="$TCL_CC"
-    AC_TRY_COMPILE(,[
-           #ifdef _WIN32
-               #error win32
-           #endif
-       ], [
-           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
-           TEA_PLATFORM="${TEA_PLATFORM-unix}"
-           CYGPATH=echo
-       ], [
-           TEA_PLATFORM="windows"
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
-    )
-    CC=$hold_cc
-    AC_MSG_RESULT($TEA_PLATFORM)
-
-    # The BUILD_$pkg is to define the correct extern storage class
-    # handling when making this package
-    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
-           [Building extension source?])
-    # Do this here as we have fully defined TEA_PLATFORM now
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       EXEEXT=".exe"
-       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
-    fi
-
-    # TEA specific:
-    AC_SUBST(CLEANFILES)
-    AC_SUBST(TCL_LIBS)
-    AC_SUBST(TCL_DEFS)
-    AC_SUBST(TCL_EXTRA_CFLAGS)
-    AC_SUBST(TCL_LD_FLAGS)
-    AC_SUBST(TCL_SHLIB_LD_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TKCONFIG --
-#
-#      Load the tkConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TK_BIN_DIR
-#
-# Results:
-#
-#      Sets the following vars that should be in tkConfig.sh:
-#              TK_BIN_DIR
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TKCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
-
-    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TK_BIN_DIR}/tkConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
-    # If the TK_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TK_LIB_SPEC will be set to the value
-    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
-    # instead of TK_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
-        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
-        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tk was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tk.framework installed in an arbitrary location.
-       case ${TK_DEFS} in
-           *TK_FRAMEWORK*)
-               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
-                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
-                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
-                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
-                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
-                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
-    # TEA specific: Ensure windowingsystem is defined
-    if test "${TEA_PLATFORM}" = "unix" ; then
-       case ${TK_DEFS} in
-           *MAC_OSX_TK*)
-               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
-               TEA_WINDOWINGSYSTEM="aqua"
-               ;;
-           *)
-               TEA_WINDOWINGSYSTEM="x11"
-               ;;
-       esac
-    elif test "${TEA_PLATFORM}" = "windows" ; then
-       TEA_WINDOWINGSYSTEM="win32"
-    fi
-
-    AC_SUBST(TK_VERSION)
-    AC_SUBST(TK_BIN_DIR)
-    AC_SUBST(TK_SRC_DIR)
-
-    AC_SUBST(TK_LIB_FILE)
-    AC_SUBST(TK_LIB_FLAG)
-    AC_SUBST(TK_LIB_SPEC)
-
-    AC_SUBST(TK_STUB_LIB_FILE)
-    AC_SUBST(TK_STUB_LIB_FLAG)
-    AC_SUBST(TK_STUB_LIB_SPEC)
-
-    # TEA specific:
-    AC_SUBST(TK_LIBS)
-    AC_SUBST(TK_XINCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_TCLSH
-#      Determine the fully qualified path name of the tclsh executable
-#      in the Tcl build directory or the tclsh installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the tclsh executable even if tclsh has not yet been
-#      built in the build directory. The tclsh found is always
-#      associated with a tclConfig.sh file. This tclsh should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCLSH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_TCLSH], [
-    AC_MSG_CHECKING([for tclsh])
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        # tclConfig.sh is in Tcl build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
-          fi
-        else
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
-        fi
-    else
-        # tclConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-        else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
-        fi
-        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${TCLSH_PROG}" ; then
-                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
-    fi
-    AC_MSG_RESULT([${TCLSH_PROG}])
-    AC_SUBST(TCLSH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_WISH
-#      Determine the fully qualified path name of the wish executable
-#      in the Tk build directory or the wish installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the wish executable even if wish has not yet been
-#      built in the build directory. The wish found is always
-#      associated with a tkConfig.sh file. This wish should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              WISH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_WISH], [
-    AC_MSG_CHECKING([for wish])
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        # tkConfig.sh is in Tk build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
-          fi
-        else
-            WISH_PROG="${TK_BIN_DIR}/wish"
-        fi
-    else
-        # tkConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-        else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
-        fi
-        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${WISH_PROG}" ; then
-                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
-    fi
-    AC_MSG_RESULT([${WISH_PROG}])
-    AC_SUBST(WISH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SHARED --
-#
-#      Allows the building of shared libraries
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-shared=yes|no
-#              --enable-stubs=yes|no
-#
-#      Defines the following vars:
-#              STATIC_BUILD    Used for building import/export libraries
-#                              on Windows.
-#
-#      Sets the following vars:
-#              SHARED_BUILD    Value of 1 or 0
-#               STUBS_BUILD     Value if 1 or 0
-#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
-#                                AND TEA_WINDOWING_SYSTEM != ""
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ENABLE_SHARED], [
-    AC_MSG_CHECKING([how to build libraries])
-    AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
-           [build and link with shared libraries (default: on)]),
-       [shared_ok=$enableval], [shared_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       shared_ok=$enableval
-    else
-       shared_ok=yes
-    fi
-
-    AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
-           [build and link with stub libraries. Always true for shared builds (default: on)]),
-       [stubs_ok=$enableval], [stubs_ok=yes])
-
-    if test "${enable_stubs+set}" = set; then
-       enableval="$enable_stubs"
-       stubs_ok=$enableval
-    else
-       stubs_ok=yes
-    fi
-
-    # Stubs are always enabled for shared builds
-    if test "$shared_ok" = "yes" ; then
-       AC_MSG_RESULT([shared])
-       SHARED_BUILD=1
-        STUBS_BUILD=1
-    else
-       AC_MSG_RESULT([static])
-       SHARED_BUILD=0
-       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
-        if test "$stubs_ok" = "yes" ; then
-          STUBS_BUILD=1
-        else
-          STUBS_BUILD=0
-        fi
-    fi
-    if test "${STUBS_BUILD}" = "1" ; then
-      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
-      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
-      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
-        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
-      fi
-    fi
-
-    AC_SUBST(SHARED_BUILD)
-    AC_SUBST(STUBS_BUILD)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_THREADS --
-#
-#      Specify if thread support should be enabled.  If "yes" is specified
-#      as an arg (optional), threads are enabled by default, "no" means
-#      threads are disabled.  "yes" is the default.
-#
-#      TCL_THREADS is checked so that if you are compiling an extension
-#      against a threaded core, your extension must be compiled threaded
-#      as well.
-#
-#      Note that it is legal to have a thread enabled extension run in a
-#      threaded or non-threaded Tcl core, but a non-threaded extension may
-#      only run in a non-threaded Tcl core.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-threads
-#
-#      Sets the following vars:
-#              THREADS_LIBS    Thread library(s)
-#
-#      Defines the following vars:
-#              TCL_THREADS
-#              _REENTRANT
-#              _THREAD_SAFE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_THREADS], [
-    AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
-           [build with threads (default: on)]),
-       [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_threads+set}" = set; then
-       enableval="$enable_threads"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
-    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
-       TCL_THREADS=1
-
-       if test "${TEA_PLATFORM}" != "windows" ; then
-           # We are always OK on Windows, so check what this platform wants:
-
-           # USE_THREAD_ALLOC tells us to try the special thread-based
-           # allocator that significantly reduces lock contention
-           AC_DEFINE(USE_THREAD_ALLOC, 1,
-               [Do we want to use the threaded memory allocator?])
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           if test "`uname -s`" = "SunOS" ; then
-               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-                       [Do we really want to follow the standard? Yes we do!])
-           fi
-           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
-           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
-           if test "$tcl_ok" = "no"; then
-               # Check a little harder for __pthread_mutex_init in the same
-               # library, as some systems hide it there until pthread.h is
-               # defined.  We could alternatively do an AC_TRY_COMPILE with
-               # pthread.h, but that will work with libpthread really doesn't
-               # exist, like AIX 4.2.  [Bug: 4359]
-               AC_CHECK_LIB(pthread, __pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-           fi
-
-           if test "$tcl_ok" = "yes"; then
-               # The space is needed
-               THREADS_LIBS=" -lpthread"
-           else
-               AC_CHECK_LIB(pthreads, pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-               if test "$tcl_ok" = "yes"; then
-                   # The space is needed
-                   THREADS_LIBS=" -lpthreads"
-               else
-                   AC_CHECK_LIB(c, pthread_mutex_init,
-                       tcl_ok=yes, tcl_ok=no)
-                   if test "$tcl_ok" = "no"; then
-                       AC_CHECK_LIB(c_r, pthread_mutex_init,
-                           tcl_ok=yes, tcl_ok=no)
-                       if test "$tcl_ok" = "yes"; then
-                           # The space is needed
-                           THREADS_LIBS=" -pthread"
-                       else
-                           TCL_THREADS=0
-                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
-                       fi
-                   fi
-               fi
-           fi
-       fi
-    else
-       TCL_THREADS=0
-    fi
-    # Do checking message here to not mess up interleaved configure output
-    AC_MSG_CHECKING([for building with threads])
-    if test "${TCL_THREADS}" = 1; then
-       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
-       AC_MSG_RESULT([yes (default)])
-    else
-       AC_MSG_RESULT([no])
-    fi
-    # TCL_THREADS sanity checking.  See if our request for building with
-    # threads is the same as the way Tcl was built.  If not, warn the user.
-    case ${TCL_DEFS} in
-       *THREADS=1*)
-           if test "${TCL_THREADS}" = "0"; then
-               AC_MSG_WARN([
-    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
-    that IS thread-enabled.  It is recommended to use --enable-threads.])
-           fi
-           ;;
-    esac
-    AC_SUBST(TCL_THREADS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SYMBOLS --
-#
-#      Specify if debugging symbols should be used.
-#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
-#
-# Arguments:
-#      none
-#
-#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
-#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
-#      Requires the following vars to be set in the Makefile:
-#              CFLAGS_DEFAULT
-#              LDFLAGS_DEFAULT
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-symbols
-#
-#      Defines the following vars:
-#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
-#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
-#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
-#                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_SYMBOLS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_CONFIG_CFLAGS])
-    AC_MSG_CHECKING([for build with symbols])
-    AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
-           [build with debugging symbols (default: off)]),
-       [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
-    if test "$tcl_ok" = "no"; then
-       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
-       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
-       AC_MSG_RESULT([no])
-    else
-       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
-       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
-       if test "$tcl_ok" = "yes"; then
-           AC_MSG_RESULT([yes (standard debugging)])
-       fi
-    fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-    AC_SUBST(CFLAGS_DEFAULT)
-    AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
-
-    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
-       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
-    fi
-
-    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
-       if test "$tcl_ok" = "all"; then
-           AC_MSG_RESULT([enabled symbols mem debugging])
-       else
-           AC_MSG_RESULT([enabled $tcl_ok debugging])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_LANGINFO --
-#
-#      Allows use of modern nl_langinfo check for better l10n.
-#      This is only relevant for Unix.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-langinfo=yes|no (default is yes)
-#
-#      Defines the following vars:
-#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_LANGINFO], [
-    AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
-           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
-       [langinfo_ok=$enableval], [langinfo_ok=yes])
-
-    HAVE_LANGINFO=0
-    if test "$langinfo_ok" = "yes"; then
-       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
-    fi
-    AC_MSG_CHECKING([whether to use nl_langinfo])
-    if test "$langinfo_ok" = "yes"; then
-       AC_CACHE_VAL(tcl_cv_langinfo_h, [
-           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
-                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
-       AC_MSG_RESULT([$tcl_cv_langinfo_h])
-       if test $tcl_cv_langinfo_h = yes; then
-           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
-       fi
-    else
-       AC_MSG_RESULT([$langinfo_ok])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_SYSTEM
-#
-#      Determine what the system is (some things cannot be easily checked
-#      on a feature-driven basis, alas). This can usually be done via the
-#      "uname" command.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Defines the following var:
-#
-#      system -        System/platform/version identification code.
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_SYSTEM], [
-    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
-       # TEA specific:
-       if test "${TEA_PLATFORM}" = "windows" ; then
-           tcl_cv_sys_version=windows
-       else
-           tcl_cv_sys_version=`uname -s`-`uname -r`
-           if test "$?" -ne 0 ; then
-               AC_MSG_WARN([can't find uname command])
-               tcl_cv_sys_version=unknown
-           else
-               if test "`uname -s`" = "AIX" ; then
-                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
-               fi
-               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
-                   tcl_cv_sys_version=NetBSD-Debian
-               fi
-           fi
-       fi
-    ])
-    system=$tcl_cv_sys_version
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_CFLAGS
-#
-#      Try to determine the proper flags to pass to the compiler
-#      for building shared libraries and other such nonsense.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substitutes the following vars:
-#
-#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
-#       LDFLAGS -      Flags to pass to the compiler when linking object
-#                       files into an executable application binary such
-#                       as tclsh.
-#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
-#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
-#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile.
-#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
-#                       of a shared library (may request position-independent
-#                       code, among other things).
-#       SHLIB_LD -      Base command to use for combining object files
-#                       into a shared library.
-#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
-#                       creating shared libraries.  This symbol typically
-#                       goes at the end of the "ld" commands that build
-#                       shared libraries. The value of the symbol defaults to
-#                       "${LIBS}" if all of the dependent libraries should
-#                       be specified when creating a shared library.  If
-#                       dependent libraries should not be specified (as on
-#                       SunOS 4.x, where they cause the link to fail, or in
-#                       general if Tcl and Tk aren't themselves shared
-#                       libraries), then this symbol has an empty string
-#                       as its value.
-#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
-#                       extensions.  An empty string means we don't know how
-#                       to use shared libraries on this platform.
-#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
-#                       in a static or shared library name, using the $PACKAGE_VERSION variable
-#                       to put the version in the right place.  This is used
-#                       by platforms that need non-standard library names.
-#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
-#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
-#                       on AIX, since a shared library needs to have
-#                       a .a extension whereas shared objects for loadable
-#                       extensions have a .so extension.  Defaults to
-#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
-#      CFLAGS_DEBUG -
-#                      Flags used when running the compiler in debug mode
-#      CFLAGS_OPTIMIZE -
-#                      Flags used when running the compiler in optimize mode
-#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_CFLAGS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-
-    # Step 0.a: Enable 64 bit support?
-
-    AC_MSG_CHECKING([if 64bit support is requested])
-    AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
-           [enable 64bit support (default: off)]),
-       [do64bit=$enableval], [do64bit=no])
-    AC_MSG_RESULT([$do64bit])
-
-    # Step 0.b: Enable Solaris 64 bit VIS support?
-
-    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
-    AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
-           [enable 64bit Sparc VIS support (default: off)]),
-       [do64bitVIS=$enableval], [do64bitVIS=no])
-    AC_MSG_RESULT([$do64bitVIS])
-    # Force 64bit on with VIS
-    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
-
-    # Step 0.c: Check if visibility support is available. Do this here so
-    # that platform specific alternatives can be used below if this fails.
-
-    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
-       tcl_cv_cc_visibility_hidden, [
-       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
-       AC_TRY_LINK([
-           extern __attribute__((__visibility__("hidden"))) void f(void);
-           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
-           tcl_cv_cc_visibility_hidden=no)
-       CFLAGS=$hold_cflags])
-    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
-       AC_DEFINE(MODULE_SCOPE,
-           [extern __attribute__((__visibility__("hidden")))],
-           [Compiler support for module scope symbols])
-       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
-    ])
-
-    # Step 0.d: Disable -rpath support?
-
-    AC_MSG_CHECKING([if rpath support is requested])
-    AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
-           [disable rpath support (default: on)]),
-       [doRpath=$enableval], [doRpath=yes])
-    AC_MSG_RESULT([$doRpath])
-
-    # Set the variable "system" to hold the name and version number
-    # for the system.
-
-    TEA_CONFIG_SYSTEM
-
-    # Require ranlib early so we can override it in special cases below.
-
-    AC_REQUIRE([AC_PROG_RANLIB])
-
-    # Set configuration options based on system name and version.
-    # This is similar to Tcl's unix/tcl.m4 except that we've added a
-    # "windows" case and removed some core-only vars.
-
-    do64bit_ok=no
-    # default to '{$LIBS}' and set to "" on per-platform necessary basis
-    SHLIB_LD_LIBS='${LIBS}'
-    # When ld needs options to work in 64-bit mode, put them in
-    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
-    # is disabled by the user. [Bug 1016796]
-    LDFLAGS_ARCH=""
-    UNSHARED_LIB_SUFFIX=""
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
-    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
-    TCL_LIB_VERSIONS_OK=ok
-    CFLAGS_DEBUG=-g
-    AS_IF([test "$GCC" = yes], [
-       CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
-    ], [
-       CFLAGS_OPTIMIZE=-O
-       CFLAGS_WARNING=""
-    ])
-    AC_CHECK_TOOL(AR, ar)
-    STLIB_LD='${AR} cr'
-    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
-    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
-    case $system in
-       # TEA specific:
-       windows)
-           MACHINE="X86"
-           if test "$do64bit" != "no" ; then
-               case "$do64bit" in
-                   amd64|x64|yes)
-                       MACHINE="AMD64" ; # default to AMD64 64-bit build
-                       ;;
-                   ia64)
-                       MACHINE="IA64"
-                       ;;
-               esac
-           fi
-
-           if test "$GCC" != "yes" ; then
-               if test "${SHARED_BUILD}" = "0" ; then
-                   runtime=-MT
-               else
-                   runtime=-MD
-               fi
-               case "x`echo \${VisualStudioVersion}`" in
-                   x1[[4-9]]*)
-                       lflags="${lflags} -nodefaultlib:libucrt.lib"
-                       TEA_ADD_LIBS([ucrt.lib])
-                   ;;
-                   *)
-                   ;;
-               esac
-
-                if test "$do64bit" != "no" ; then
-                   CC="cl.exe"
-                   RC="rc.exe"
-                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
-                   LINKBIN="link.exe"
-                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-                   # Avoid 'unresolved external symbol __security_cookie'
-                   # errors, c.f. http://support.microsoft.com/?id=894573
-                   TEA_ADD_LIBS([bufferoverflowU.lib])
-               else
-                   RC="rc"
-                   lflags="${lflags} -nologo"
-                   LINKBIN="link"
-                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-               fi
-           fi
-
-           if test "$GCC" = "yes"; then
-               # mingw gcc mode
-               AC_CHECK_TOOL(RC, windres)
-               CFLAGS_DEBUG="-g"
-               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-               SHLIB_LD='${CC} -shared'
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
-               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
-
-               AC_CACHE_CHECK(for cross-compile version of gcc,
-                       ac_cv_cross,
-                       AC_TRY_COMPILE([
-                           #ifdef _WIN32
-                               #error cross-compiler
-                           #endif
-                       ], [],
-                       ac_cv_cross=yes,
-                       ac_cv_cross=no)
-                     )
-                     if test "$ac_cv_cross" = "yes"; then
-                       case "$do64bit" in
-                           amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
-                               LD="x86_64-w64-mingw32-ld"
-                               AR="x86_64-w64-mingw32-ar"
-                               RANLIB="x86_64-w64-mingw32-ranlib"
-                               RC="x86_64-w64-mingw32-windres"
-                           ;;
-                           *)
-                               CC="i686-w64-mingw32-gcc"
-                               LD="i686-w64-mingw32-ld"
-                               AR="i686-w64-mingw32-ar"
-                               RANLIB="i686-w64-mingw32-ranlib"
-                               RC="i686-w64-mingw32-windres"
-                           ;;
-                       esac
-               fi
-
-           else
-               SHLIB_LD="${LINKBIN} -dll ${lflags}"
-               # link -lib only works when -lib is the first arg
-               STLIB_LD="${LINKBIN} -lib ${lflags}"
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
-               PATHTYPE=-w
-               # For information on what debugtype is most useful, see:
-               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
-               # and also
-               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
-               # This essentially turns it all on.
-               LDFLAGS_DEBUG="-debug -debugtype:cv"
-               LDFLAGS_OPTIMIZE="-release"
-               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
-               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
-           fi
-
-           SHLIB_SUFFIX=".dll"
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
-
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       AIX-*)
-           AS_IF([test "$GCC" != "yes"], [
-               # AIX requires the _r compiler when gcc isn't being used
-               case "${CC}" in
-                   *_r|*_r\ *)
-                       # ok ...
-                       ;;
-                   *)
-                       # Make sure only first arg gets _r
-                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
-                       ;;
-               esac
-               AC_MSG_RESULT([Using $CC for compiling with threads])
-           ])
-           LIBS="$LIBS -lc"
-           SHLIB_CFLAGS=""
-           SHLIB_SUFFIX=".so"
-
-           LD_LIBRARY_PATH_VAR="LIBPATH"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS -q64"
-                   LDFLAGS_ARCH="-q64"
-                   RANLIB="${RANLIB} -X64"
-                   AR="${AR} -X64"
-                   SHLIB_LD_FLAGS="-b64"
-               ])
-           ])
-
-           AS_IF([test "`uname -m`" = ia64], [
-               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
-               ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ], [
-               AS_IF([test "$GCC" = yes], [
-                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
-               ], [
-                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
-                   LDFLAGS="$LDFLAGS -brtl"
-               ])
-               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       BeOS*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} -nostart'
-           SHLIB_SUFFIX=".so"
-
-           #-----------------------------------------------------------
-           # Check for inet_ntoa in -lbind, for BeOS (which also needs
-           # -lsocket, even if the network functions are in -lnet which
-           # is always linked to, for compatibility.
-           #-----------------------------------------------------------
-           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
-           ;;
-       BSD/OS-2.1*|BSD/OS-3*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="shlicc -r"
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       BSD/OS-4.*)
-           SHLIB_CFLAGS="-export-dynamic -fPIC"
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       CYGWIN_*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".dll"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
-           EXEEXT=".exe"
-           do64bit_ok=yes
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       dgux*)
-           SHLIB_CFLAGS="-K PIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       Haiku*)
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
-           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
-           ;;
-       HP-UX-*.11.*)
-           # Use updated header definitions where possible
-           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
-           # TEA specific: Needed by Tcl, but not most extensions
-           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
-           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
-
-           AS_IF([test "`uname -m`" = ia64], [
-               SHLIB_SUFFIX=".so"
-           ], [
-               SHLIB_SUFFIX=".sl"
-           ])
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ])
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               CFLAGS="$CFLAGS -z"
-           ])
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = "yes"], [
-               AS_IF([test "$GCC" = yes], [
-                   case `${CC} -dumpmachine` in
-                       hppa64*)
-                           # 64-bit gcc in use.  Fix flags for GNU ld.
-                           do64bit_ok=yes
-                           SHLIB_LD='${CC} -shared'
-                           AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-                           ;;
-                       *)
-                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
-                           ;;
-                   esac
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS +DD64"
-                   LDFLAGS_ARCH="+DD64"
-               ])
-           ]) ;;
-       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
-           SHLIB_SUFFIX=".sl"
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               SHLIB_LD_LIBS=""
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ]) ;;
-       IRIX-5.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AC_LIBOBJ(mkstemp)
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           ;;
-       IRIX-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [
-               CFLAGS="$CFLAGS -mabi=n32"
-               LDFLAGS="$LDFLAGS -mabi=n32"
-           ], [
-               case $system in
-                   IRIX-6.3)
-                       # Use to build 6.2 compatible binaries on 6.3.
-                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
-                       ;;
-                   *)
-                       CFLAGS="$CFLAGS -n32"
-                       ;;
-               esac
-               LDFLAGS="$LDFLAGS -n32"
-           ])
-           ;;
-       IRIX64-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-
-           # Check to enable 64-bit flags for compiler/linker
-
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported by gcc])
-               ], [
-                   do64bit_ok=yes
-                   SHLIB_LD="ld -64 -shared -rdata_shared"
-                   CFLAGS="$CFLAGS -64"
-                   LDFLAGS_ARCH="-64"
-               ])
-           ])
-           ;;
-       Linux*|GNU*|NetBSD-Debian)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-
-           # TEA specific:
-           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
-           AS_IF([test $do64bit = yes], [
-               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
-                   hold_cflags=$CFLAGS
-                   CFLAGS="$CFLAGS -m64"
-                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
-                   CFLAGS=$hold_cflags])
-               AS_IF([test $tcl_cv_cc_m64 = yes], [
-                   CFLAGS="$CFLAGS -m64"
-                   do64bit_ok=yes
-               ])
-          ])
-
-           # The combo of gcc + glibc has a bug related to inlining of
-           # functions like strtod(). The -fno-builtin flag should address
-           # this problem but it does not work. The -fno-inline flag is kind
-           # of overkill but it works. Disable inlining only when one of the
-           # files in compat/*.c is being linked in.
-
-           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
-           ;;
-       Lynx*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           CFLAGS_OPTIMIZE=-02
-           SHLIB_LD='${CC} -shared'
-           LD_FLAGS="-Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           ;;
-       OpenBSD-*)
-           arch=`arch -s`
-           case "$arch" in
-           alpha|sparc64)
-               SHLIB_CFLAGS="-fPIC"
-               ;;
-           *)
-               SHLIB_CFLAGS="-fpic"
-               ;;
-           esac
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
-           CFLAGS_OPTIMIZE="-O2"
-           # On OpenBSD:       Compile with -pthread
-           #           Don't link with -lpthread
-           LIBS=`echo $LIBS | sed s/-lpthread//`
-           CFLAGS="$CFLAGS -pthread"
-           # OpenBSD doesn't do version numbers with dots.
-           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       NetBSD-*)
-           # NetBSD has ELF and can use 'cc -shared' to build shared libs
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           # The -pthread needs to go in the CFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS -pthread"
-           LDFLAGS="$LDFLAGS -pthread"
-           ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
-       Darwin-*)
-           CFLAGS_OPTIMIZE="-Os"
-           SHLIB_CFLAGS="-fno-common"
-           # To avoid discrepancies between what headers configure sees during
-           # preprocessing tests and compiling tests, move any -isysroot and
-           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
-           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
-           CFLAGS="`echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
-           AS_IF([test $do64bit = yes], [
-               case `arch` in
-                   ppc)
-                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
-                               tcl_cv_cc_arch_ppc64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
-                                   tcl_cv_cc_arch_ppc64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           do64bit_ok=yes
-                       ]);;
-                   i386)
-                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
-                               tcl_cv_cc_arch_x86_64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
-                                   tcl_cv_cc_arch_x86_64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           do64bit_ok=yes
-                       ]);;
-                   *)
-                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
-               esac
-           ], [
-               # Check for combined 32-bit and 64-bit fat build
-               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
-                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
-                   fat_32_64=yes])
-           ])
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
-           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_single_module = yes], [
-               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
-           ])
-           # TEA specific: link shlib with current and compatibility version flags
-           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
-           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
-           SHLIB_SUFFIX=".dylib"
-           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
-           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
-                   tcl_cv_ld_search_paths_first, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
-                       tcl_cv_ld_search_paths_first=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-           ])
-           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
-                   [Compiler support for module scope symbols])
-               tcl_cv_cc_visibility_hidden=yes
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
-           # TEA specific: for combined 32 & 64 bit fat builds of Tk
-           # extensions, verify that 64-bit build is possible.
-           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
-                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
-                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
-                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
-                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
-                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
-                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
-                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
-                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               # remove 64-bit arch flags from CFLAGS et al. if configuration
-               # does not support 64-bit.
-               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
-                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
-                   for v in CFLAGS CPPFLAGS LDFLAGS; do
-                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
-                   done])
-           ])
-           ;;
-       OS/390-*)
-           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
-           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
-               [Should OS/390 do the right thing with sockets?])
-           ;;
-       OSF1-V*)
-           # Digital OSF/1
-           SHLIB_CFLAGS=""
-           AS_IF([test "$SHARED_BUILD" = 1], [
-               SHLIB_LD='ld -shared -expect_unresolved "*"'
-           ], [
-               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
-           ])
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
-               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
-           # see pthread_intro(3) for pthread support on osf1, k.furukawa
-           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
-           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
-           LIBS=`echo $LIBS | sed s/-lpthreads//`
-           AS_IF([test "$GCC" = yes], [
-               LIBS="$LIBS -lpthread -lmach -lexc"
-           ], [
-               CFLAGS="$CFLAGS -pthread"
-               LDFLAGS="$LDFLAGS -pthread"
-           ])
-           ;;
-       QNX-6*)
-           # QNX RTP
-           # This may work for all QNX, but it was only reported for v6.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="ld -Bshareable -x"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SCO_SV-3.2*)
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_CFLAGS="-fPIC -melf"
-               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
-           ], [
-               SHLIB_CFLAGS="-Kpic -belf"
-               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
-           ])
-           SHLIB_LD="ld -G"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SunOS-5.[[0-6]])
-           # Careful to not let 5.10+ fall into this case
-
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       SunOS-5*)
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               arch=`isainfo`
-               AS_IF([test "$arch" = "sparcv9 sparc"], [
-                   AS_IF([test "$GCC" = yes], [
-                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
-                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
-                       ], [
-                           do64bit_ok=yes
-                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
-                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
-                           SHLIB_CFLAGS="-fPIC"
-                       ])
-                   ], [
-                       do64bit_ok=yes
-                       AS_IF([test "$do64bitVIS" = yes], [
-                           CFLAGS="$CFLAGS -xarch=v9a"
-                           LDFLAGS_ARCH="-xarch=v9a"
-                       ], [
-                           CFLAGS="$CFLAGS -xarch=v9"
-                           LDFLAGS_ARCH="-xarch=v9"
-                       ])
-                       # Solaris 64 uses this as well
-                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
-                   ])
-               ], [AS_IF([test "$arch" = "amd64 i386"], [
-                   AS_IF([test "$GCC" = yes], [
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               do64bit_ok=yes
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
-                       esac
-                   ], [
-                       do64bit_ok=yes
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               CFLAGS="$CFLAGS -xarch=amd64"
-                               LDFLAGS="$LDFLAGS -xarch=amd64";;
-                       esac
-                   ])
-               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
-           ])
-
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-               AS_IF([test "$do64bit_ok" = yes], [
-                   AS_IF([test "$arch" = "sparcv9 sparc"], [
-                       # We need to specify -static-libgcc or we need to
-                       # add the path to the sparv9 libgcc.
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
-                       # for finding sparcv9 libgcc, get the regular libgcc
-                       # path, remove so name and append 'sparcv9'
-                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
-                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
-                   ], [AS_IF([test "$arch" = "amd64 i386"], [
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
-                   ])])
-               ])
-           ], [
-               case $system in
-                   SunOS-5.[[1-9]][[0-9]]*)
-                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
-                   *)
-                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
-               esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ])
-           ;;
-       UNIX_SV* | UnixWare-5*)
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
-           # that don't grok the -Bexport option.  Test that it does.
-           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_Bexport = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-    esac
-
-    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
-       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
-    ])
-
-dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
-dnl # until the end of configure, as configure's compile and link tests use
-dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
-dnl # preprocessing tests use only CPPFLAGS.
-    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
-
-    # Add in the arch flags late to ensure it wasn't removed.
-    # Not necessary in TEA, but this is aligned with core
-    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
-
-    # If we're running gcc, then change the C flags for compiling shared
-    # libraries to the right flags for gcc, instead of those for the
-    # standard manufacturer compiler.
-
-    AS_IF([test "$GCC" = yes], [
-       case $system in
-           AIX-*) ;;
-           BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
-           IRIX*) ;;
-           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
-           Darwin-*) ;;
-           SCO_SV-3.2*) ;;
-           windows) ;;
-           *) SHLIB_CFLAGS="-fPIC" ;;
-       esac])
-
-    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-       AC_DEFINE(MODULE_SCOPE, [extern],
-           [No Compiler support for module scope symbols])
-    ])
-
-    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
-    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
-
-    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
-       AC_CACHE_CHECK(for SEH support in compiler,
-           tcl_cv_seh,
-       AC_TRY_RUN([
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-
-           int main(int argc, char** argv) {
-               int a, b = 0;
-               __try {
-                   a = 666 / b;
-               }
-               __except (EXCEPTION_EXECUTE_HANDLER) {
-                   return 0;
-               }
-               return 1;
-           }
-       ],
-           tcl_cv_seh=yes,
-           tcl_cv_seh=no,
-           tcl_cv_seh=no)
-       )
-       if test "$tcl_cv_seh" = "no" ; then
-           AC_DEFINE(HAVE_NO_SEH, 1,
-                   [Defined when mingw does not support SEH])
-       fi
-
-       #
-       # Check to see if the excpt.h include file provided contains the
-       # definition for EXCEPTION_DISPOSITION; if not, which is the case
-       # with Cygwin's version as of 2002-04-10, define it to be int,
-       # sufficient for getting the current code to work.
-       #
-       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
-           tcl_cv_eh_disposition,
-           AC_TRY_COMPILE([
-#          define WIN32_LEAN_AND_MEAN
-#          include <windows.h>
-#          undef WIN32_LEAN_AND_MEAN
-           ],[
-               EXCEPTION_DISPOSITION x;
-           ],
-               tcl_cv_eh_disposition=yes,
-               tcl_cv_eh_disposition=no)
-       )
-       if test "$tcl_cv_eh_disposition" = "no" ; then
-       AC_DEFINE(EXCEPTION_DISPOSITION, int,
-               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
-       fi
-
-       # Check to see if winnt.h defines CHAR, SHORT, and LONG
-       # even if VOID has already been #defined. The win32api
-       # used by mingw and cygwin is known to do this.
-
-       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
-           tcl_cv_winnt_ignore_void,
-           AC_TRY_COMPILE([
-#define VOID void
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-           ], [
-               CHAR c;
-               SHORT s;
-               LONG l;
-           ],
-        tcl_cv_winnt_ignore_void=yes,
-        tcl_cv_winnt_ignore_void=no)
-       )
-       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
-           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
-                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
-       fi
-    fi
-
-       # See if the compiler supports casting to a union type.
-       # This is used to stop gcc from printing a compiler
-       # warning when initializing a union member.
-
-       AC_CACHE_CHECK(for cast to union support,
-           tcl_cv_cast_to_union,
-           AC_TRY_COMPILE([],
-           [
-                 union foo { int i; double d; };
-                 union foo f = (union foo) (int) 0;
-           ],
-           tcl_cv_cast_to_union=yes,
-           tcl_cv_cast_to_union=no)
-       )
-       if test "$tcl_cv_cast_to_union" = "yes"; then
-           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
-                   [Defined when compiler supports casting to union type.])
-       fi
-
-       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
-
-    AC_SUBST(CFLAGS_DEBUG)
-    AC_SUBST(CFLAGS_OPTIMIZE)
-    AC_SUBST(CFLAGS_WARNING)
-
-    AC_SUBST(STLIB_LD)
-    AC_SUBST(SHLIB_LD)
-
-    AC_SUBST(SHLIB_LD_LIBS)
-    AC_SUBST(SHLIB_CFLAGS)
-
-    AC_SUBST(LD_LIBRARY_PATH_VAR)
-
-    # These must be called after we do the basic CFLAGS checks and
-    # verify any possible 64-bit or similar switches are necessary
-    TEA_TCL_EARLY_FLAGS
-    TEA_TCL_64BIT_FLAGS
-])
-
-#--------------------------------------------------------------------
-# TEA_SERIAL_PORT
-#
-#      Determine which interface to use to talk to the serial port.
-#      Note that #include lines must begin in leftmost column for
-#      some compilers to recognize them as preprocessor directives,
-#      and some build environments have stdin not pointing at a
-#      pseudo-terminal (usually /dev/null instead.)
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines only one of the following vars:
-#              HAVE_SYS_MODEM_H
-#              USE_TERMIOS
-#              USE_TERMIO
-#              USE_SGTTY
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_SERIAL_PORT], [
-    AC_CHECK_HEADERS(sys/modem.h)
-    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
-    AC_TRY_RUN([
-#include <termios.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termio.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termios.h>
-#include <errno.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <termio.h>
-#include <errno.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-#include <errno.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
-    fi])
-    case $tcl_cv_api_serial in
-       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
-       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
-       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_PATH_X
-#
-#      Locate the X11 header files and the X11 library archive.  Try
-#      the ac_path_x macro first, but if it doesn't find the X stuff
-#      (e.g. because there's no xmkmf program) then check through
-#      a list of possible directories.  Under some conditions the
-#      autoconf macro will return an include directory that contains
-#      no include files, so double-check its result just to be safe.
-#
-#      This should be called after TEA_CONFIG_CFLAGS as setting the
-#      LIBS line can confuse some configure macro magic.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets the following vars:
-#              XINCLUDES
-#              XLIBSW
-#              PKG_LIBS (appends to)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_X], [
-    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
-       TEA_PATH_UNIX_X
-    fi
-])
-
-AC_DEFUN([TEA_PATH_UNIX_X], [
-    AC_PATH_X
-    not_really_there=""
-    if test "$no_x" = ""; then
-       if test "$x_includes" = ""; then
-           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
-       else
-           if test ! -r $x_includes/X11/Xlib.h; then
-               not_really_there="yes"
-           fi
-       fi
-    fi
-    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
-       AC_MSG_CHECKING([for X11 header files])
-       found_xincludes="no"
-       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
-       if test "$found_xincludes" = "no"; then
-           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
-           for i in $dirs ; do
-               if test -r $i/X11/Xlib.h; then
-                   AC_MSG_RESULT([$i])
-                   XINCLUDES=" -I$i"
-                   found_xincludes="yes"
-                   break
-               fi
-           done
-       fi
-    else
-       if test "$x_includes" != ""; then
-           XINCLUDES="-I$x_includes"
-           found_xincludes="yes"
-       fi
-    fi
-    if test "$found_xincludes" = "no"; then
-       AC_MSG_RESULT([couldn't find any!])
-    fi
-
-    if test "$no_x" = yes; then
-       AC_MSG_CHECKING([for X11 libraries])
-       XLIBSW=nope
-       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
-       for i in $dirs ; do
-           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
-               AC_MSG_RESULT([$i])
-               XLIBSW="-L$i -lX11"
-               x_libraries="$i"
-               break
-           fi
-       done
-    else
-       if test "$x_libraries" = ""; then
-           XLIBSW=-lX11
-       else
-           XLIBSW="-L$x_libraries -lX11"
-       fi
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_MSG_RESULT([could not find any!  Using -lX11.])
-       XLIBSW=-lX11
-    fi
-    # TEA specific:
-    if test x"${XLIBSW}" != x ; then
-       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BLOCKING_STYLE
-#
-#      The statements below check for systems where POSIX-style
-#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
-#      On these systems (mostly older ones), use the old BSD-style
-#      FIONBIO approach instead.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              HAVE_SYS_IOCTL_H
-#              HAVE_SYS_FILIO_H
-#              USE_FIONBIO
-#              O_NONBLOCK
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BLOCKING_STYLE], [
-    AC_CHECK_HEADERS(sys/ioctl.h)
-    AC_CHECK_HEADERS(sys/filio.h)
-    TEA_CONFIG_SYSTEM
-    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
-    case $system in
-       OSF*)
-           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
-           AC_MSG_RESULT([FIONBIO])
-           ;;
-       *)
-           AC_MSG_RESULT([O_NONBLOCK])
-           ;;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_TIME_HANDLER
-#
-#      Checks how the system deals with time.h, what time structures
-#      are used on the system, and what fields the structures have.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              USE_DELTA_FOR_TZ
-#              HAVE_TM_GMTOFF
-#              HAVE_TM_TZADJ
-#              HAVE_TIMEZONE_VAR
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TIME_HANDLER], [
-    AC_CHECK_HEADERS(sys/time.h)
-    AC_HEADER_TIME
-    AC_STRUCT_TIMEZONE
-
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
-
-    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
-           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
-    if test $tcl_cv_member_tm_tzadj = yes ; then
-       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
-    fi
-
-    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
-           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
-    if test $tcl_cv_member_tm_gmtoff = yes ; then
-       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
-    fi
-
-    #
-    # Its important to include time.h in this check, as some systems
-    # (like convex) have timezone functions, etc.
-    #
-    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
-       AC_TRY_COMPILE([#include <time.h>],
-           [extern long timezone;
-           timezone += 1;
-           exit (0);],
-           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
-    if test $tcl_cv_timezone_long = yes ; then
-       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-    else
-       #
-       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
-       #
-       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
-           AC_TRY_COMPILE([#include <time.h>],
-               [extern time_t timezone;
-               timezone += 1;
-               exit (0);],
-               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
-       if test $tcl_cv_timezone_time = yes ; then
-           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BUGGY_STRTOD
-#
-#      Under Solaris 2.4, strtod returns the wrong value for the
-#      terminating character under some conditions.  Check for this
-#      and if the problem exists use a substitute procedure
-#      "fixstrtod" (provided by Tcl) that corrects the error.
-#      Also, on Compaq's Tru64 Unix 5.0,
-#      strtod(" ") returns 0.0 instead of a failure to convert.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Might defines some of the following vars:
-#              strtod (=fixstrtod)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BUGGY_STRTOD], [
-    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
-    if test "$tcl_strtod" = 1; then
-       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
-           AC_TRY_RUN([
-               extern double strtod();
-               int main() {
-                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
-                   char *term;
-                   double value;
-                   value = strtod(infString, &term);
-                   if ((term != infString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(nanString, &term);
-                   if ((term != nanString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(spaceString, &term);
-                   if (term == (spaceString+1)) {
-                       exit(1);
-                   }
-                   exit(0);
-               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
-                   tcl_cv_strtod_buggy=buggy)])
-       if test "$tcl_cv_strtod_buggy" = buggy; then
-           AC_LIBOBJ([fixstrtod])
-           USE_COMPAT=1
-           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_EARLY_FLAGS
-#
-#      Check for what flags are needed to be passed so the correct OS
-#      features are available.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              _ISOC99_SOURCE
-#              _LARGEFILE64_SOURCE
-#              _LARGEFILE_SOURCE64
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_EARLY_FLAG],[
-    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
-       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
-           AC_TRY_COMPILE([[#define ]$1[ 1
-]$2], $3,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
-    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
-       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
-       tcl_flags="$tcl_flags $1"
-    fi
-])
-
-AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
-    AC_MSG_CHECKING([for required early compiler flags])
-    tcl_flags=""
-    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
-       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
-       [struct stat64 buf; int i = stat64("/", &buf);])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
-       [char *p = (char *)open64;])
-    if test "x${tcl_flags}" = "x" ; then
-       AC_MSG_RESULT([none])
-    else
-       AC_MSG_RESULT([${tcl_flags}])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_64BIT_FLAGS
-#
-#      Check for what is defined in the way of 64-bit features.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              TCL_WIDE_INT_IS_LONG
-#              TCL_WIDE_INT_TYPE
-#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
-#              HAVE_STRUCT_STAT64
-#              HAVE_TYPE_OFF64_T
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
-    AC_MSG_CHECKING([for 64-bit integer type])
-    AC_CACHE_VAL(tcl_cv_type_64bit,[
-       tcl_cv_type_64bit=none
-       # See if the compiler knows natively about __int64
-       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
-           tcl_type_64bit=__int64, tcl_type_64bit="long long")
-       # See if we could use long anyway  Note that we substitute in the
-       # type that is our current guess for a 64-bit type inside this check
-       # program, so it should be modified only carefully...
-        AC_TRY_COMPILE(,[switch (0) {
-            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
-        }],tcl_cv_type_64bit=${tcl_type_64bit})])
-    if test "${tcl_cv_type_64bit}" = none ; then
-       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
-       AC_MSG_RESULT([yes])
-    elif test "${tcl_cv_type_64bit}" = "__int64" \
-               -a "${TEA_PLATFORM}" = "windows" ; then
-       # TEA specific: We actually want to use the default tcl.h checks in
-       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
-       AC_MSG_RESULT([using Tcl header defaults])
-    else
-       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
-           [What type should be used to define wide integers?])
-       AC_MSG_RESULT([${tcl_cv_type_64bit}])
-
-       # Now check for auxiliary declarations
-       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 p;],
-               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
-       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
-            p = readdir64(d); rewinddir64(d); closedir64(d);],
-               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
-       if test "x${tcl_cv_DIR64}" = "xyes" ; then
-           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
-           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
-],
-               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
-       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
-       fi
-
-       AC_CHECK_FUNCS(open64 lseek64)
-       AC_MSG_CHECKING([for off64_t])
-       AC_CACHE_VAL(tcl_cv_type_off64_t,[
-           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
-],
-               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
-       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
-       dnl functions lseek64 and open64 are defined.
-       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
-               test "x${ac_cv_func_lseek64}" = "xyes" && \
-               test "x${ac_cv_func_open64}" = "xyes" ; then
-           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
-           AC_MSG_RESULT([yes])
-       else
-           AC_MSG_RESULT([no])
-       fi
-    fi
-])
-
-##
-## Here ends the standard Tcl configuration bits and starts the
-## TEA specific functions
-##
-
-#------------------------------------------------------------------------
-# TEA_INIT --
-#
-#      Init various Tcl Extension Architecture (TEA) variables.
-#      This should be the first called TEA_* macro.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              CYGPATH
-#              EXEEXT
-#      Defines only:
-#              TEA_VERSION
-#              TEA_INITED
-#              TEA_PLATFORM (windows or unix)
-#
-# "cygpath" is used on windows to generate native path names for include
-# files. These variables should only be used with the compiler and linker
-# since they generate native path names.
-#
-# EXEEXT
-#      Select the executable extension based on the host type.  This
-#      is a lightweight replacement for AC_EXEEXT that doesn't require
-#      a compiler.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INIT], [
-    TEA_VERSION="3.13"
-
-    AC_MSG_CHECKING([TEA configuration])
-    if test x"${PACKAGE_NAME}" = x ; then
-       AC_MSG_ERROR([
-The PACKAGE_NAME variable must be defined by your TEA configure.ac])
-    fi
-    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
-
-    # If the user did not set CFLAGS, set it now to keep macros
-    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
-    if test "${CFLAGS+set}" != "set" ; then
-       CFLAGS=""
-    fi
-
-    case "`uname -s`" in
-       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
-           EXEEXT=".exe"
-           TEA_PLATFORM="windows"
-           ;;
-       *CYGWIN_*)
-           EXEEXT=".exe"
-           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
-           ;;
-       *)
-           CYGPATH=echo
-           # Maybe we are cross-compiling....
-           case ${host_alias} in
-               *mingw32*)
-               EXEEXT=".exe"
-               TEA_PLATFORM="windows"
-               ;;
-           *)
-               EXEEXT=""
-               TEA_PLATFORM="unix"
-               ;;
-           esac
-           ;;
-    esac
-
-    # Check if exec_prefix is set. If not use fall back to prefix.
-    # Note when adjusted, so that TEA_PREFIX can correct for this.
-    # This is needed for recursive configures, since autoconf propagates
-    # $prefix, but not $exec_prefix (doh!).
-    if test x$exec_prefix = xNONE ; then
-       exec_prefix_default=yes
-       exec_prefix=$prefix
-    fi
-
-    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
-
-    AC_SUBST(EXEEXT)
-    AC_SUBST(CYGPATH)
-
-    # This package name must be replaced statically for AC_SUBST to work
-    AC_SUBST(PKG_LIB_FILE)
-    # Substitute STUB_LIB_FILE in case package creates a stub library too.
-    AC_SUBST(PKG_STUB_LIB_FILE)
-
-    # We AC_SUBST these here to ensure they are subst'ed,
-    # in case the user doesn't call TEA_ADD_...
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-    AC_SUBST(PKG_TCL_SOURCES)
-    AC_SUBST(PKG_HEADERS)
-    AC_SUBST(PKG_INCLUDES)
-    AC_SUBST(PKG_LIBS)
-    AC_SUBST(PKG_CFLAGS)
-
-    # Configure the installer.
-    TEA_INSTALLER
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_SOURCES
-#              PKG_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       case $i in
-           [\$]*)
-               # allow $-var names
-               PKG_SOURCES="$PKG_SOURCES $i"
-               PKG_OBJECTS="$PKG_OBJECTS $i"
-               ;;
-           *)
-               # check for existence - allows for generic/win/unix VPATH
-               # To add more dirs here (like 'src'), you have to update VPATH
-               # in Makefile.in as well
-               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-                   -a ! -f "${srcdir}/macosx/$i" \
-                   ; then
-                   AC_MSG_ERROR([could not find source file '$i'])
-               fi
-               PKG_SOURCES="$PKG_SOURCES $i"
-               # this assumes it is in a VPATH dir
-               i=`basename $i`
-               # handle user calling this before or after TEA_SETUP_COMPILER
-               if test x"${OBJEXT}" != x ; then
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-               else
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-               fi
-               PKG_OBJECTS="$PKG_OBJECTS $j"
-               ;;
-       esac
-    done
-    AC_SUBST(PKG_SOURCES)
-    AC_SUBST(PKG_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_STUB_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_STUB_SOURCES
-#              PKG_STUB_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_STUB_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence - allows for generic/win/unix VPATH
-       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-           -a ! -f "${srcdir}/macosx/$i" \
-           ; then
-           AC_MSG_ERROR([could not find stub source file '$i'])
-       fi
-       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
-       # this assumes it is in a VPATH dir
-       i=`basename $i`
-       # handle user calling this before or after TEA_SETUP_COMPILER
-       if test x"${OBJEXT}" != x ; then
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-       else
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-       fi
-       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
-    done
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_TCL_SOURCES --
-#
-#      Specify one or more Tcl source files.  These should be platform
-#      independent runtime files.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_TCL_SOURCES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_TCL_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
-       fi
-       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
-    done
-    AC_SUBST(PKG_TCL_SOURCES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_HEADERS --
-#
-#      Specify one or more source headers.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_HEADERS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_HEADERS], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
-       fi
-       PKG_HEADERS="$PKG_HEADERS $i"
-    done
-    AC_SUBST(PKG_HEADERS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_INCLUDES --
-#
-#      Specify one or more include dirs.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_INCLUDES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_INCLUDES], [
-    vars="$@"
-    for i in $vars; do
-       PKG_INCLUDES="$PKG_INCLUDES $i"
-    done
-    AC_SUBST(PKG_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_LIBS --
-#
-#      Specify one or more libraries.  Users should check for
-#      the right platform before adding to their list.  For Windows,
-#      libraries provided in "foo.lib" format will be converted to
-#      "-lfoo" when using GCC (mingw).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_LIBS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_LIBS], [
-    vars="$@"
-    for i in $vars; do
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
-           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
-       fi
-       PKG_LIBS="$PKG_LIBS $i"
-    done
-    AC_SUBST(PKG_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CFLAGS --
-#
-#      Specify one or more CFLAGS.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_CFLAGS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CFLAGS], [
-    PKG_CFLAGS="$PKG_CFLAGS $@"
-    AC_SUBST(PKG_CFLAGS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CLEANFILES --
-#
-#      Specify one or more CLEANFILES.
-#
-# Arguments:
-#      one or more file names to clean target
-#
-# Results:
-#
-#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CLEANFILES], [
-    CLEANFILES="$CLEANFILES $@"
-])
-
-#------------------------------------------------------------------------
-# TEA_PREFIX --
-#
-#      Handle the --prefix=... option by defaulting to what Tcl gave
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      If --prefix or --exec-prefix was not specified, $prefix and
-#      $exec_prefix will be set to the values given to Tcl when it was
-#      configured.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_PREFIX], [
-    if test "${prefix}" = "NONE"; then
-       prefix_default=yes
-       if test x"${TCL_PREFIX}" != x; then
-           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
-           prefix=${TCL_PREFIX}
-       else
-           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
-           prefix=/usr/local
-       fi
-    fi
-    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
-       -o x"${exec_prefix_default}" = x"yes" ; then
-       if test x"${TCL_EXEC_PREFIX}" != x; then
-           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
-           exec_prefix=${TCL_EXEC_PREFIX}
-       else
-           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
-           exec_prefix=$prefix
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER_CC --
-#
-#      Do compiler checks the way we want.  This is just a replacement
-#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER_CC], [
-    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
-    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
-
-    AC_PROG_CC
-    AC_PROG_CPP
-
-    #--------------------------------------------------------------------
-    # Checks to see if the make program sets the $MAKE variable.
-    #--------------------------------------------------------------------
-
-    AC_PROG_MAKE_SET
-
-    #--------------------------------------------------------------------
-    # Find ranlib
-    #--------------------------------------------------------------------
-
-    AC_CHECK_TOOL(RANLIB, ranlib)
-
-    #--------------------------------------------------------------------
-    # Determines the correct binary file extension (.o, .obj, .exe etc.)
-    #--------------------------------------------------------------------
-
-    AC_OBJEXT
-    AC_EXEEXT
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER --
-#
-#      Do compiler checks that use the compiler.  This must go after
-#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER], [
-    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
-    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
-
-    #------------------------------------------------------------------------
-    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
-    # It makes compiling go faster.  (This is only a performance feature.)
-    #------------------------------------------------------------------------
-
-    if test -z "$no_pipe" -a -n "$GCC"; then
-       AC_CACHE_CHECK([if the compiler understands -pipe],
-           tcl_cv_cc_pipe, [
-           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
-           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
-           CFLAGS=$hold_cflags])
-       if test $tcl_cv_cc_pipe = yes; then
-           CFLAGS="$CFLAGS -pipe"
-       fi
-    fi
-
-    #--------------------------------------------------------------------
-    # Common compiler flag setup
-    #--------------------------------------------------------------------
-
-    AC_C_BIGENDIAN
-])
-
-#------------------------------------------------------------------------
-# TEA_MAKE_LIB --
-#
-#      Generate a line that can be used to build a shared/unshared library
-#      in a platform independent manner.
-#
-# Arguments:
-#      none
-#
-#      Requires:
-#
-# Results:
-#
-#      Defines the following vars:
-#      CFLAGS -        Done late here to note disturb other AC macros
-#       MAKE_LIB -      Command to execute to build the Tcl library;
-#                       differs depending on whether or not Tcl is being
-#                       compiled as a shared library.
-#      MAKE_SHARED_LIB Makefile rule for building a shared library
-#      MAKE_STATIC_LIB Makefile rule for building a static library
-#      MAKE_STUB_LIB   Makefile rule for building a stub library
-#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
-#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_MAKE_LIB], [
-    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
-       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
-       AC_EGREP_CPP([manifest needed], [
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-print("manifest needed")
-#endif
-       ], [
-       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
-       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
-       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
-       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
-       TEA_ADD_CLEANFILES([*.manifest])
-       ])
-       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
-    else
-       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
-       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
-    fi
-
-    if test "${SHARED_BUILD}" = "1" ; then
-       MAKE_LIB="${MAKE_SHARED_LIB} "
-    else
-       MAKE_LIB="${MAKE_STATIC_LIB} "
-    fi
-
-    #--------------------------------------------------------------------
-    # Shared libraries and static libraries have different names.
-    # Use the double eval to make sure any variables in the suffix is
-    # substituted. (@@@ Might not be necessary anymore)
-    #--------------------------------------------------------------------
-
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       if test "${SHARED_BUILD}" = "1" ; then
-           # We force the unresolved linking of symbols that are really in
-           # the private libraries of Tcl and Tk.
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
-           fi
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
-           if test "$GCC" = "yes"; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
-           fi
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-       else
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-           if test "$GCC" = "yes"; then
-               PKG_LIB_FILE=lib${PKG_LIB_FILE}
-           fi
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-       if test "$GCC" = "yes"; then
-           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
-       fi
-       # These aren't needed on Windows (either MSVC or gcc)
-       RANLIB=:
-       RANLIB_STUB=:
-    else
-       RANLIB_STUB="${RANLIB}"
-       if test "${SHARED_BUILD}" = "1" ; then
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
-           fi
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-           RANLIB=:
-       else
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-    fi
-
-    # These are escaped so that only CFLAGS is picked up at configure time.
-    # The other values will be substituted at make time.
-    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
-    if test "${SHARED_BUILD}" = "1" ; then
-       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
-    fi
-
-    AC_SUBST(MAKE_LIB)
-    AC_SUBST(MAKE_SHARED_LIB)
-    AC_SUBST(MAKE_STATIC_LIB)
-    AC_SUBST(MAKE_STUB_LIB)
-    AC_SUBST(RANLIB_STUB)
-    AC_SUBST(VC_MANIFEST_EMBED_DLL)
-    AC_SUBST(VC_MANIFEST_EMBED_EXE)
-])
-
-#------------------------------------------------------------------------
-# TEA_LIB_SPEC --
-#
-#      Compute the name of an existing object library located in libdir
-#      from the given base name and produce the appropriate linker flags.
-#
-# Arguments:
-#      basename        The base name of the library without version
-#                      numbers, extensions, or "lib" prefixes.
-#      extra_dir       Extra directory in which to search for the
-#                      library.  This location is used first, then
-#                      $prefix/$exec-prefix, then some defaults.
-#
-# Requires:
-#      TEA_INIT and TEA_PREFIX must be called first.
-#
-# Results:
-#
-#      Defines the following vars:
-#              ${basename}_LIB_NAME    The computed library name.
-#              ${basename}_LIB_SPEC    The computed linker flags.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LIB_SPEC], [
-    AC_MSG_CHECKING([for $1 library])
-
-    # Look in exec-prefix for the library (defined by TEA_PREFIX).
-
-    tea_lib_name_dir="${exec_prefix}/lib"
-
-    # Or in a user-specified location.
-
-    if test x"$2" != x ; then
-       tea_extra_lib_dir=$2
-    else
-       tea_extra_lib_dir=NONE
-    fi
-
-    for i in \
-           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
-       if test -f "$i" ; then
-           tea_lib_name_dir=`dirname $i`
-           $1_LIB_NAME=`basename $i`
-           $1_LIB_PATH_NAME=$i
-           break
-       fi
-    done
-
-    if test "${TEA_PLATFORM}" = "windows"; then
-       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
-    else
-       # Strip off the leading "lib" and trailing ".a" or ".so"
-
-       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
-       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
-    fi
-
-    if test "x${$1_LIB_NAME}" = x ; then
-       AC_MSG_ERROR([not found])
-    else
-       AC_MSG_RESULT([${$1_LIB_SPEC}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TCL_HEADERS --
-#
-#      Locate the private Tcl include files
-#
-# Arguments:
-#
-#      Requires:
-#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
-#                              already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_TOP_DIR_NATIVE
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
-    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
-    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
-    AC_MSG_CHECKING([for Tcl private include files])
-
-    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
-    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
-
-    # Check to see if tcl<Plat>Port.h isn't already with the public headers
-    # Don't look for tclInt.h because that resides with tcl.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
-       else
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TCL_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
-       if test "`uname -s`" = "Darwin"; then
-            # If Tcl was built as a framework, attempt to use
-            # the framework's Headers and PrivateHeaders directories
-            case ${TCL_DEFS} in
-               *TCL_FRAMEWORK*)
-                   if test -d "${TCL_BIN_DIR}/Headers" -a \
-                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
-                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
-                   else
-                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                   fi
-                   ;;
-           esac
-           result="Using ${TCL_INCLUDES}"
-       else
-           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
-               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
-           fi
-           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TCL_TOP_DIR_NATIVE)
-
-    AC_SUBST(TCL_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TCL_HEADERS --
-#
-#      Locate the installed public Tcl header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tclinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
-    AC_MSG_CHECKING([for Tcl public headers])
-
-    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tclh, [
-       # Use the value from --with-tclinclude, if it was given
-
-       if test x"${with_tclinclude}" != x ; then
-           if test -f "${with_tclinclude}/tcl.h" ; then
-               ac_cv_c_tclh=${with_tclinclude}
-           else
-               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tcl was built as a framework, attempt to use
-               # the framework's Headers directory
-               case ${TCL_DEFS} in
-                   *TCL_FRAMEWORK*)
-                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tcl is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TCL_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TCL_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tcl.h" ; then
-                   ac_cv_c_tclh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tclh}" = x ; then
-       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tclh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
-
-    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TCL_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TK_HEADERS --
-#
-#      Locate the private Tk include files
-#
-# Arguments:
-#
-#      Requires:
-#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
-#                               already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
-    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
-    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
-    AC_MSG_CHECKING([for Tk private include files])
-
-    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
-    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
-
-    # Check to see if tk<Plat>Port.h isn't already with the public headers
-    # Don't look for tkInt.h because that resides with tk.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
-       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
-       else
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TK_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
-       # Detect and add ttk subdir
-       if test -d "${TK_SRC_DIR}/generic/ttk"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
-       fi
-       if test "`uname -s`" = "Darwin"; then
-           # If Tk was built as a framework, attempt to use
-           # the framework's Headers and PrivateHeaders directories
-           case ${TK_DEFS} in
-               *TK_FRAMEWORK*)
-                       if test -d "${TK_BIN_DIR}/Headers" -a \
-                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
-                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
-                       else
-                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                       fi
-                       ;;
-           esac
-           result="Using ${TK_INCLUDES}"
-       else
-           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
-              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
-           fi
-           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TK_TOP_DIR_NATIVE)
-    AC_SUBST(TK_XLIB_DIR_NATIVE)
-
-    AC_SUBST(TK_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TK_HEADERS --
-#
-#      Locate the installed public Tk header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tkinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
-    AC_MSG_CHECKING([for Tk public headers])
-
-    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tkh, [
-       # Use the value from --with-tkinclude, if it was given
-
-       if test x"${with_tkinclude}" != x ; then
-           if test -f "${with_tkinclude}/tk.h" ; then
-               ac_cv_c_tkh=${with_tkinclude}
-           else
-               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tk was built as a framework, attempt to use
-               # the framework's Headers directory.
-               case ${TK_DEFS} in
-                   *TK_FRAMEWORK*)
-                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tk is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TK_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tk's --prefix location,
-           # relative to directory of tkConfig.sh, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
-               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TK_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tk.h" ; then
-                   ac_cv_c_tkh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tkh}" = x ; then
-       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tkh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
-
-    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TK_INCLUDES)
-
-    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-       # On Windows and Aqua, we need the X compat headers
-       AC_MSG_CHECKING([for X11 header files])
-       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
-           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
-           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-           AC_SUBST(TK_XINCLUDES)
-       fi
-       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_CONFIG --
-#
-#      Locate the ${1}Config.sh file and perform a sanity check on
-#      the ${1} compile flags.  These are used by packages like
-#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-$1=...
-#
-#      Defines the following vars:
-#              $1_BIN_DIR      Full path to the directory containing
-#                              the $1Config.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_CONFIG], [
-    #
-    # Ok, lets find the $1 configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-$1
-    #
-
-    if test x"${no_$1}" = x ; then
-       # we reset no_$1 in case something fails here
-       no_$1=true
-       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
-       AC_MSG_CHECKING([for $1 configuration])
-       AC_CACHE_VAL(ac_cv_c_$1config,[
-
-           # First check to see if --with-$1 was specified.
-           if test x"${with_$1config}" != x ; then
-               case ${with_$1config} in
-                   */$1Config.sh )
-                       if test -f ${with_$1config}; then
-                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
-                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
-                       fi;;
-               esac
-               if test -f "${with_$1config}/$1Config.sh" ; then
-                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
-               else
-                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
-               fi
-           fi
-
-           # then check for a private $1 installation
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in \
-                       ../$1 \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../$1 \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../$1 \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ${srcdir}/../$1 \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-                   if test -f "$i/unix/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_$1config}" = x ; then
-           $1_BIN_DIR="# no $1 configs found"
-           AC_MSG_WARN([Cannot find $1 configuration definitions])
-           exit 0
-       else
-           no_$1=
-           $1_BIN_DIR=${ac_cv_c_$1config}
-           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG --
-#
-#      Load the $1Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              $1_SRC_DIR
-#              $1_LIB_FILE
-#              $1_LIB_SPEC
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_CONFIG], [
-    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
-
-    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${$1_BIN_DIR}/$1Config.sh"
-    else
-        AC_MSG_RESULT([file not found])
-    fi
-
-    #
-    # If the $1_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable $1_LIB_SPEC will be set to the value
-    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
-    # instead of $1_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    #
-
-    if test -f "${$1_BIN_DIR}/Makefile" ; then
-       AC_MSG_WARN([Found Makefile - using build library specs for $1])
-        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
-        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
-        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
-        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
-        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
-    fi
-
-    AC_SUBST($1_VERSION)
-    AC_SUBST($1_BIN_DIR)
-    AC_SUBST($1_SRC_DIR)
-
-    AC_SUBST($1_LIB_FILE)
-    AC_SUBST($1_LIB_SPEC)
-
-    AC_SUBST($1_STUB_LIB_FILE)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    # Allow the caller to prevent this auto-check by specifying any 2nd arg
-    AS_IF([test "x$2" = x], [
-       # Check both upper and lower-case variants
-       # If a dev wanted non-stubs libs, this function could take an option
-       # to not use _STUB in the paths below
-       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
-           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
-           [TEA_LOAD_CONFIG_LIB($1_STUB)])
-    ])
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG_LIB --
-#
-#      Helper function to load correct library from another extension's
-#      ${PACKAGE}Config.sh.
-#
-# Results:
-#      Adds to LIBS the appropriate extension library
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
-    AC_MSG_CHECKING([For $1 library for LIBS])
-    # This simplifies the use of stub libraries by automatically adding
-    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
-    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
-    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
-    if test "x${$1_LIB_SPEC}" != "x" ; then
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
-           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
-           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
-       else
-           TEA_ADD_LIBS([${$1_LIB_SPEC}])
-           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
-       fi
-    else
-       AC_MSG_RESULT([file not found])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_EXPORT_CONFIG --
-#
-#      Define the data to insert into the ${PACKAGE}Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1
-#
-# Results:
-#      Substitutes the following vars:
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_EXPORT_CONFIG], [
-    #--------------------------------------------------------------------
-    # These are for $1Config.sh
-    #--------------------------------------------------------------------
-
-    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
-    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
-    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
-    else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-    fi
-    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
-    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
-    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
-    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
-
-    AC_SUBST($1_BUILD_LIB_SPEC)
-    AC_SUBST($1_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_PATH)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    AC_SUBST(MAJOR_VERSION)
-    AC_SUBST(MINOR_VERSION)
-    AC_SUBST(PATCHLEVEL)
-])
-
-
-#------------------------------------------------------------------------
-# TEA_INSTALLER --
-#
-#      Configure the installer.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              INSTALL
-#              INSTALL_DATA_DIR
-#              INSTALL_DATA
-#              INSTALL_PROGRAM
-#              INSTALL_SCRIPT
-#              INSTALL_LIBRARY
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INSTALLER], [
-    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
-    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
-    INSTALL_DATA='${INSTALL} -m 644'
-    INSTALL_PROGRAM='${INSTALL} -m 755'
-    INSTALL_SCRIPT='${INSTALL} -m 755'
-
-    TEA_CONFIG_SYSTEM
-    case $system in
-       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
-             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
-    esac
-
-    AC_SUBST(INSTALL)
-    AC_SUBST(INSTALL_DATA_DIR)
-    AC_SUBST(INSTALL_DATA)
-    AC_SUBST(INSTALL_PROGRAM)
-    AC_SUBST(INSTALL_SCRIPT)
-    AC_SUBST(INSTALL_LIBRARY)
-])
-
-###
-# Tip 430 - ZipFS Modifications
-###
-#------------------------------------------------------------------------
-# SC_ZIPFS_SUPPORT
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#              TCL_ZIPFS_FLAG
-#              ZIP_PROG
-#------------------------------------------------------------------------
-
-#------------------------------------------------------------------------
-# SC_PROG_ZIP
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              ZIP_PROG
-#       ZIP_PROG_OPTIONS
-#       ZIP_PROG_VFSSEARCH
-#       ZIP_INSTALL_OBJS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ZIPFS_SUPPORT], [
-    AC_MSG_CHECKING([for zipfs support])
-    ZIP_PROG=""
-    ZIP_PROG_OPTIONS=""
-    ZIP_PROG_VFSSEARCH=""
-    INSTALL_MSGS=""
-    # If our native tclsh processes the "install" command line option
-    # we can use it to mint zip files
-    AS_IF([$TCLSH_PROG install],[
-      ZIP_PROG=${TCLSH_PROG}
-      ZIP_PROG_OPTIONS="install mkzip"
-      ZIP_PROG_VFSSEARCH="."
-      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
-    ])
-    if test "x$ZIP_PROG" = "x" ; then
-        AC_CACHE_VAL(ac_cv_path_zip, [
-        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
-        for dir in $search_path ; do
-            for j in `ls -r $dir/zip 2> /dev/null` \
-                `ls -r $dir/zip 2> /dev/null` ; do
-            if test x"$ac_cv_path_zip" = x ; then
-                if test -f "$j" ; then
-                ac_cv_path_zip=$j
-                break
-                fi
-            fi
-            done
-        done
-        ])
-        if test -f "$ac_cv_path_zip" ; then
-            ZIP_PROG="$ac_cv_path_zip "
-            AC_MSG_RESULT([$ZIP_PROG])
-            ZIP_PROG_OPTIONS="-rq"
-            ZIP_PROG_VFSSEARCH="."
-            AC_MSG_RESULT([Found INFO Zip in environment])
-            # Use standard arguments for zip
-        fi
-    fi
-    if test "x$ZIP_PROG" = "x" ; then
-           # It is not an error if an installed version of Zip can't be located.
-        ZIP_PROG=""
-        ZIP_PROG_OPTIONS=""
-        ZIP_PROG_VFSSEARCH=""
-        TCL_ZIPFS_SUPPORT=0
-        TCL_ZIPFS_FLAG=
-    else
-        # ZIPFS Support
-       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
-       if test ${TCL_ZIP_FILE} = "" ; then
-          TCL_ZIPFS_SUPPORT=0
-          TCL_ZIPFS_FLAG=
-          INSTALL_LIBRARIES=install-libraries
-          INSTALL_MSGS=install-msgs
-       else
-           if test ${SHARED_BUILD} = 1 ; then
-              TCL_ZIPFS_SUPPORT=1
-              INSTALL_LIBRARIES=install-libraries-zipfs-shared
-           else
-              TCL_ZIPFS_SUPPORT=2
-              INSTALL_LIBRARIES=install-libraries-zipfs-static
-           fi
-          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
-       fi
-    fi
-
-    AC_SUBST(TCL_ZIP_FILE)
-    AC_SUBST(TCL_ZIPFS_SUPPORT)
-    AC_SUBST(TCL_ZIPFS_FLAG)
-    AC_SUBST(ZIP_PROG)
-    AC_SUBST(ZIP_PROG_OPTIONS)
-    AC_SUBST(ZIP_PROG_VFSSEARCH)
-    AC_SUBST(INSTALL_LIBRARIES)
-    AC_SUBST(INSTALL_MSGS)
-])
-
-# Local Variables:
-# mode: autoconf
-# End:
diff --git a/pkgs/tdbcodbc1.1.1/win/rules.vc b/pkgs/tdbcodbc1.1.1/win/rules.vc
deleted file mode 100644 (file)
index b1a0346..0000000
+++ /dev/null
@@ -1,1807 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# rules.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file does all the hard work in terms of parsing build options,\r
-# compiler switches, defining common targets and macros. The Tcl makefile\r
-# directly includes this. Extensions include it via "rules-ext.vc".\r
-#\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
-# detailed documentation.\r
-#\r
-# See the file "license.terms" for information on usage and redistribution\r
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
-#\r
-# Copyright (c) 2001-2003 David Gravereaux.\r
-# Copyright (c) 2003-2008 Patrick Thoyts\r
-# Copyright (c) 2017      Ashok P. Nadkarni\r
-#------------------------------------------------------------------------------\r
-\r
-!ifndef _RULES_VC\r
-_RULES_VC = 1\r
-\r
-# The following macros define the version of the rules.vc nmake build system\r
-# For modifications that are not backward-compatible, you *must* change\r
-# the major version.\r
-RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
-\r
-# The PROJECT macro must be defined by parent makefile.\r
-!if "$(PROJECT)" == ""\r
-!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
-!endif\r
-\r
-!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
-PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
-!endif\r
-\r
-# Also special case Tcl and Tk to save some typing later\r
-DOING_TCL = 0\r
-DOING_TK  = 0\r
-!if "$(PROJECT)" == "tcl"\r
-DOING_TCL = 1\r
-!elseif "$(PROJECT)" == "tk"\r
-DOING_TK = 1\r
-!endif\r
-\r
-!ifndef NEED_TK\r
-# Backwards compatibility\r
-!ifdef PROJECT_REQUIRES_TK\r
-NEED_TK = $(PROJECT_REQUIRES_TK)\r
-!else\r
-NEED_TK = 0\r
-!endif\r
-!endif\r
-\r
-!ifndef NEED_TCL_SOURCE\r
-NEED_TCL_SOURCE = 0\r
-!endif\r
-\r
-!ifdef NEED_TK_SOURCE\r
-!if $(NEED_TK_SOURCE)\r
-NEED_TK = 1\r
-!endif\r
-!else\r
-NEED_TK_SOURCE = 0\r
-!endif\r
-\r
-################################################################\r
-# Nmake is a pretty weak environment in syntax and capabilities\r
-# so this file is necessarily verbose. It's broken down into\r
-# the following parts.\r
-#\r
-# 0. Sanity check that compiler environment is set up and initialize\r
-#    any built-in settings from the parent makefile\r
-# 1. First define the external tools used for compiling, copying etc.\r
-#    as this is independent of everything else.\r
-# 2. Figure out our build structure in terms of the directory, whether\r
-#    we are building Tcl or an extension, etc.\r
-# 3. Determine the compiler and linker versions\r
-# 4. Build the nmakehlp helper application\r
-# 5. Determine the supported compiler options and features\r
-# 6. Parse the OPTS macro value for user-specified build configuration\r
-# 7. Parse the STATS macro value for statistics instrumentation\r
-# 8. Parse the CHECKS macro for additional compilation checks\r
-# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
-# 10. Based on this selected configuration, construct the output\r
-#     directory and file paths\r
-# 11. Construct the paths where the package is to be installed\r
-# 12. Set up the actual options passed to compiler and linker based\r
-#     on the information gathered above.\r
-# 13. Define some standard build targets and implicit rules. These may\r
-#     be optionally disabled by the parent makefile.\r
-# 14. (For extensions only.) Compare the configuration of the target\r
-#     Tcl and the extensions and warn against discrepancies.\r
-#\r
-# One final note about the macro names used. They are as they are\r
-# for historical reasons. We would like legacy extensions to\r
-# continue to work with this make include file so be wary of\r
-# changing them for consistency or clarity.\r
-\r
-# 0. Sanity check compiler environment\r
-\r
-# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
-# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
-\r
-!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
-MSG = ^\r
-Visual C++ compiler environment not initialized.\r
-!error $(MSG)\r
-!endif\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-\r
-################################################################\r
-# 1. Define external programs being used\r
-\r
-#----------------------------------------------------------\r
-# Set the proper copy method to avoid overwrite questions\r
-# to the user when copying files and selecting the right\r
-# "delete all" method.\r
-#----------------------------------------------------------\r
-\r
-RMDIR  = rmdir /S /Q\r
-CPY    = xcopy /i /y >NUL\r
-CPYDIR  = xcopy /e /i /y >NUL\r
-COPY   = copy /y >NUL\r
-MKDIR   = mkdir\r
-\r
-######################################################################\r
-# 2. Figure out our build environment in terms of what we're building.\r
-#\r
-# (a) Tcl itself\r
-# (b) Tk\r
-# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
-# (d) a Tcl extension using libraries/includes from Tcl source directory\r
-#\r
-# This last is needed because some extensions still need\r
-# some Tcl interfaces that are not publicly exposed.\r
-#\r
-# The fragment will set the following macros:\r
-# ROOT - root of this module sources\r
-# COMPATDIR - source directory that holds compatibility sources\r
-# DOCDIR - source directory containing documentation files\r
-# GENERICDIR - platform-independent source directory\r
-# WINDIR - Windows-specific source directory\r
-# TESTDIR - directory containing test files\r
-# TOOLSDIR - directory containing build tools\r
-# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
-#    when building Tcl itself.\r
-# _INSTALLDIR - native form of the installation path. For Tcl\r
-#    this will be the root of the Tcl installation. For extensions\r
-#    this will be the lib directory under the root.\r
-# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
-#    headers and libraries from an installed Tcl, and 0 if built against\r
-#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
-#    named.\r
-# _TCL_H - native path to the tcl.h file\r
-#\r
-# If Tk is involved, also sets the following\r
-# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
-#    Tk itself.\r
-# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
-# _TK_H - native path to the tk.h file\r
-\r
-# Root directory for sources and assumed subdirectories\r
-ROOT = $(MAKEDIR)\..\r
-# The following paths CANNOT have spaces in them as they appear on the\r
-# left side of implicit rules.\r
-!ifndef COMPATDIR\r
-COMPATDIR      = $(ROOT)\compat\r
-!endif\r
-!ifndef DOCDIR\r
-DOCDIR         = $(ROOT)\doc\r
-!endif\r
-!ifndef GENERICDIR\r
-GENERICDIR     = $(ROOT)\generic\r
-!endif\r
-!ifndef TOOLSDIR\r
-TOOLSDIR       = $(ROOT)\tools\r
-!endif\r
-!ifndef TESTDIR\r
-TESTDIR        = $(ROOT)\tests\r
-!endif\r
-!ifndef LIBDIR\r
-!if exist("$(ROOT)\library")\r
-LIBDIR          = $(ROOT)\library\r
-!else\r
-LIBDIR          = $(ROOT)\lib\r
-!endif\r
-!endif\r
-!ifndef DEMODIR\r
-!if exist("$(LIBDIR)\demos")\r
-DEMODIR                = $(LIBDIR)\demos\r
-!else\r
-DEMODIR                = $(ROOT)\demos\r
-!endif\r
-!endif # ifndef DEMODIR\r
-# Do NOT enclose WINDIR in a !ifndef because Windows always defines\r
-# WINDIR env var to point to c:\windows!\r
-# TBD - This is a potentially dangerous conflict, rename WINDIR to\r
-# something else\r
-WINDIR         = $(ROOT)\win\r
-\r
-!ifndef RCDIR\r
-!if exist("$(WINDIR)\rc")\r
-RCDIR           = $(WINDIR)\rc\r
-!else\r
-RCDIR           = $(WINDIR)\r
-!endif\r
-!endif\r
-RCDIR = $(RCDIR:/=\)\r
-\r
-# The target directory where the built packages and binaries will be installed.\r
-# INSTALLDIR is the (optional) path specified by the user.\r
-# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
-!ifdef INSTALLDIR\r
-### Fix the path separators.\r
-_INSTALLDIR    = $(INSTALLDIR:/=\)\r
-!else\r
-### Assume the normal default.\r
-_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
-!endif\r
-\r
-!if $(DOING_TCL)\r
-\r
-# BEGIN Case 2(a) - Building Tcl itself\r
-\r
-# Only need to define _TCL_H\r
-_TCL_H = ..\generic\tcl.h\r
-\r
-# END Case 2(a) - Building Tcl itself\r
-\r
-!elseif $(DOING_TK)\r
-\r
-# BEGIN Case 2(b) - Building Tk\r
-\r
-TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
-!if "$(TCLDIR)" == ""\r
-!if [echo TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-!endif # TCLDIR == ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
-!if !exist("$(_TCL_H)")\r
-!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
-!endif\r
-\r
-_TK_H = ..\generic\tk.h\r
-\r
-# END Case 2(b) - Building Tk\r
-\r
-!else\r
-\r
-# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
-\r
-# If command line has specified Tcl location through TCLDIR, use it\r
-# else default to the INSTALLDIR setting\r
-!if "$(TCLDIR)" != ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
-TCLINSTALL     = 1\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
-TCLINSTALL     = 0\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-!endif\r
-\r
-!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
-\r
-TCLINSTALL     = 1\r
-TCLDIR          = $(_INSTALLDIR)\..\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TCLDIR                = $(_INSTALLDIR)\..\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-\r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!if [echo _TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TCLINSTALL      = 0\r
-TCLDIR         = $(_TCLDIR)\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-\r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!endif # TCLDIR\r
-\r
-!ifndef _TCL_H\r
-MSG =^\r
-Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-# Now do the same to locate Tk headers and libs if project requires Tk\r
-!if $(NEED_TK)\r
-\r
-!if "$(TKDIR)" != ""\r
-\r
-_TKDIR = $(TKDIR:/=\)\r
-!if exist("$(_TKDIR)\include\tk.h")\r
-TKINSTALL      = 1\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-!elseif exist("$(_TKDIR)\generic\tk.h")\r
-TKINSTALL      = 0\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-!endif\r
-\r
-!else # TKDIR not defined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-TKINSTALL      = 1\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TKDIR         = $(_INSTALLDIR)\..\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-TKDIR          = $(_TKDIR)\r
-\r
-!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!if [echo _TKDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
-!error *** Could not locate Tk source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TKINSTALL      = 0\r
-TKDIR          = $(_TKDIR)\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-\r
-!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!endif # TKDIR\r
-\r
-!ifndef _TK_H\r
-MSG =^\r
-Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-!endif # NEED_TK\r
-\r
-!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tcl.^\r
-*** Please set the TCLDIR macro to point to the Tcl sources.\r
-!error $(MSG)\r
-!endif\r
-\r
-!if $(NEED_TK_SOURCE)\r
-!if $(TKINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tk.^\r
-*** Please set the TKDIR macro to point to the Tk sources.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-\r
-# If INSTALLDIR set to Tcl installation root dir then reset to the\r
-# lib dir for installing extensions\r
-!if exist("$(_INSTALLDIR)\include\tcl.h")\r
-_INSTALLDIR=$(_INSTALLDIR)\lib\r
-!endif\r
-\r
-# END Case 2(c) or (d) - Building an extension\r
-!endif # if $(DOING_TCL)\r
-\r
-################################################################\r
-# 3. Determine compiler version and architecture\r
-# In this section, we figure out the compiler version and the\r
-# architecture for which we are building. This sets the\r
-# following macros:\r
-# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
-#     This is also printed by the compiler in dotted form 19.10 etc.\r
-# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
-#     compiler version 1200. This is kept only for legacy reasons as it\r
-#     does not make sense for recent Microsoft compilers. Only used for\r
-#     output directory names.\r
-# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
-# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
-# MACHINE - same as $(ARCH) - legacy\r
-# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
-\r
-cc32           = $(CC)   # built-in default.\r
-link32         = link\r
-lib32          = lib\r
-rc32           = $(RC)   # built-in default.\r
-\r
-#----------------------------------------------------------------\r
-# Figure out the compiler architecture and version by writing\r
-# the C macros to a file, preprocessing them with the C\r
-# preprocessor and reading back the created file\r
-\r
-_HASH=^#\r
-_VC_MANIFEST_EMBED_EXE=\r
-_VC_MANIFEST_EMBED_DLL=\r
-VCVER=0\r
-!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
-    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
-    && ![echo ARCH=IX86 >> vercl.x] \\r
-    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
-    && ![echo ARCH=AMD64 >> vercl.x] \\r
-    && ![echo $(_HASH)endif >> vercl.x] \\r
-    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
-!include vercl.i\r
-!if $(VCVERSION) < 1900\r
-!if ![echo VCVER= ^\> vercl.vc] \\r
-    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
-!include vercl.vc\r
-!endif\r
-!else\r
-# The simple calculation above does not apply to new Visual Studio releases\r
-# Keep the compiler version in its native form.\r
-VCVER = $(VCVERSION)\r
-!endif\r
-!endif\r
-\r
-!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# The MACHINE macro is used by legacy makefiles so set it as well\r
-!ifdef MACHINE\r
-!if "$(MACHINE)" == "x86"\r
-!undef MACHINE\r
-MACHINE = IX86\r
-!elseif "$(MACHINE)" == "x64"\r
-!undef MACHINE\r
-MACHINE = AMD64\r
-!endif\r
-!if "$(MACHINE)" != "$(ARCH)"\r
-!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
-!endif\r
-!else\r
-MACHINE=$(ARCH)\r
-!endif\r
-\r
-#---------------------------------------------------------------\r
-# The PLATFORM_IDENTIFY macro matches the values returned by\r
-# the Tcl platform::identify command\r
-!if "$(MACHINE)" == "AMD64"\r
-PLATFORM_IDENTIFY = win32-x86_64\r
-!else\r
-PLATFORM_IDENTIFY = win32-ix86\r
-!endif\r
-\r
-# The MULTIPLATFORM macro controls whether binary extensions are installed\r
-# in platform-specific directories. Intended to be set/used by extensions.\r
-!ifndef MULTIPLATFORM_INSTALL\r
-MULTIPLATFORM_INSTALL = 0\r
-!endif\r
-\r
-#------------------------------------------------------------\r
-# Figure out the *host* architecture by reading the registry\r
-\r
-!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
-NATIVE_ARCH=IX86\r
-!else\r
-NATIVE_ARCH=AMD64\r
-!endif\r
-\r
-# Since MSVC8 we must deal with manifest resources.\r
-!if $(VCVERSION) >= 1400\r
-_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
-_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
-!endif\r
-\r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
-################################################################\r
-# 4. Build the nmakehlp program\r
-# This is a helper app we need to overcome nmake's limiting\r
-# environment. We will call out to it to get various bits of\r
-# information about supported compiler options etc.\r
-#\r
-# Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
-#\r
-# Extensions built against an installed Tcl will use the installed\r
-# copy of Tcl's nmakehlp.c if there is one and their own version\r
-# otherwise. In the latter case, they would also be using their own\r
-# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
-# or rules.vc.\r
-#\r
-# Extensions built against Tcl sources will use the one from the Tcl source.\r
-#\r
-# When building an extension using a sufficiently new version of Tcl,\r
-# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
-# copy of nmakehlp.c to be used.\r
-\r
-!ifndef NMAKEHLPC\r
-# Default to the one in the current directory (the extension's own nmakehlp.c)\r
-NMAKEHLPC = nmakehlp.c\r
-\r
-!if !$(DOING_TCL)\r
-!if $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
-!endif\r
-!else # ! $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
-!endif\r
-!endif # $(TCLINSTALL)\r
-!endif # !$(DOING_TCL)\r
-\r
-!endif # NMAKEHLPC\r
-\r
-# We always build nmakehlp even if it exists since we do not know\r
-# what source it was built from.\r
-!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
-!endif\r
-\r
-################################################################\r
-# 5. Test for compiler features\r
-# Visual C++ compiler options have changed over the years. Check\r
-# which options are supported by the compiler in use.\r
-#\r
-# The following macros are set:\r
-# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
-# DEBUGFLAGS - the compiler flags to be used for debug builds\r
-# LINKERFLAGS - Flags passed to the linker\r
-#\r
-# Note that these are the compiler settings *available*, not those\r
-# that will be *used*. The latter depends on the OPTS macro settings\r
-# which we have not yet parsed.\r
-#\r
-# Also note that some of the flags in OPTIMIZATIONS are not really\r
-# related to optimization. They are placed there only for legacy reasons\r
-# as some extensions expect them to be included in that macro.\r
-\r
-# -Op improves float consistency. Note only needed for older compilers\r
-# Newer compilers do not need or support this option.\r
-!if [nmakehlp -c -Op]\r
-FPOPTS  = -Op\r
-!endif\r
-\r
-# Strict floating point semantics - present in newer compilers in lieu of -Op\r
-!if [nmakehlp -c -fp:strict]\r
-FPOPTS  = $(FPOPTS) -fp:strict\r
-!endif\r
-\r
-!if "$(MACHINE)" == "IX86"\r
-### test for pentium errata\r
-!if [nmakehlp -c -QI0f]\r
-!message *** Compiler has 'Pentium 0x0f fix'\r
-FPOPTS  = $(FPOPTS) -QI0f\r
-!else\r
-!message *** Compiler does not have 'Pentium 0x0f fix'\r
-!endif\r
-!endif\r
-\r
-### test for optimizations\r
-# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
-# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
-# stack probe at *every* function entry, not just those with more than\r
-# a page of stack allocation resulting in a performance hit.  However,\r
-# /O2 documentation is misleading as its stack probes are simply the\r
-# default page size locals allocation probes and not what is implied\r
-# by an explicit /Gs option.\r
-\r
-OPTIMIZATIONS = $(FPOPTS)\r
-\r
-!if [nmakehlp -c -O2]\r
-OPTIMIZING = 1\r
-OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
-!else\r
-# Legacy, really. All modern compilers support this\r
-!message *** Compiler does not have 'Optimizations'\r
-OPTIMIZING = 0\r
-!endif\r
-\r
-# Checks for buffer overflows in local arrays\r
-!if [nmakehlp -c -GS]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
-!endif\r
-\r
-# Link time optimization. Note that this option (potentially) makes\r
-# generated libraries only usable by the specific VC++ version that\r
-# created it. Requires /LTCG linker option\r
-!if [nmakehlp -c -GL]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
-CC_GL_OPT_ENABLED = 1\r
-!else\r
-# In newer compilers -GL and -YX are incompatible.\r
-!if [nmakehlp -c -YX]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
-!endif\r
-!endif # [nmakehlp -c -GL]\r
-\r
-DEBUGFLAGS     = $(FPOPTS)\r
-\r
-# Run time error checks. Not available or valid in a release, non-debug build\r
-# RTC is for modern compilers, -GZ is legacy\r
-!if [nmakehlp -c -RTC1]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
-!elseif [nmakehlp -c -GZ]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# Linker flags\r
-\r
-# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
-# if the linker supports a specific option. Without these flags link will\r
-# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
-# They are not passed through to the actual application / extension\r
-# link rules.\r
-!ifndef LINKER_TESTFLAGS\r
-LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
-!endif\r
-\r
-LINKERFLAGS     =\r
-\r
-# If compiler has enabled link time optimization, linker must too with -ltcg\r
-!ifdef CC_GL_OPT_ENABLED\r
-!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
-!endif\r
-!endif\r
-\r
-########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
-# Based on this, we will construct the actual switches to be passed to the\r
-# compiler and linker using the macros defined in the previous section.\r
-# The following macros are defined by this section based on OPTS\r
-# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
-#                1 -> build as a static library and shell\r
-# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
-# DEBUG - 1 -> debug build, 0 -> release builds\r
-# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
-# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
-# PGO     - 1 -> profile based optimization, 0 -> no\r
-# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
-#           0 -> link to static C runtime for static Tcl build.\r
-#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
-# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
-# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
-#           0 -> Use the non-thread allocator.\r
-# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
-#           C runtime, 0 -> use the debug C runtime.\r
-# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
-# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
-#           configuration (ignored for Tcl itself)\r
-# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
-# Further, LINKERFLAGS are modified based on above.\r
-\r
-# Default values for all the above\r
-STATIC_BUILD   = 0\r
-TCL_THREADS    = 1\r
-DEBUG          = 0\r
-SYMBOLS                = 0\r
-PROFILE                = 0\r
-PGO            = 0\r
-MSVCRT         = 1\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-USE_THREAD_ALLOC = 1\r
-UNCHECKED      = 0\r
-CONFIG_CHECK    = 1\r
-!if $(DOING_TCL)\r
-USE_STUBS       = 0\r
-!else\r
-USE_STUBS       = 1\r
-!endif\r
-\r
-# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
-# set the above macros based on OPTS content\r
-!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
-\r
-# OPTS are specified, parse them\r
-\r
-!if [nmakehlp -f $(OPTS) "static"]\r
-!message *** Doing static\r
-STATIC_BUILD   = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nostubs"]\r
-!message *** Not using stubs\r
-USE_STUBS      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-!message *** Doing nomsvcrt\r
-MSVCRT         = 0\r
-!else\r
-!if [nmakehlp -f $(OPTS) "msvcrt"]\r
-!message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
-!else\r
-MSVCRT         = 0\r
-!endif\r
-!endif\r
-!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-\r
-!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
-!message *** Doing staticpkg\r
-TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nothreads"]\r
-!message *** Compile explicitly for non-threaded tcl\r
-TCL_THREADS = 0\r
-USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "time64bit"]\r
-!message *** Force 64-bit time_t\r
-_USE_64BIT_TIME_T = 1\r
-!endif\r
-\r
-# Yes, it's weird that the "symbols" option controls DEBUG and\r
-# the "pdbs" option controls SYMBOLS. That's historical.\r
-!if [nmakehlp -f $(OPTS) "symbols"]\r
-!message *** Doing symbols\r
-DEBUG          = 1\r
-!else\r
-DEBUG          = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pdbs"]\r
-!message *** Doing pdbs\r
-SYMBOLS                = 1\r
-!else\r
-SYMBOLS                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "profile"]\r
-!message *** Doing profile\r
-PROFILE                = 1\r
-!else\r
-PROFILE                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pgi"]\r
-!message *** Doing profile guided optimization instrumentation\r
-PGO            = 1\r
-!elseif [nmakehlp -f $(OPTS) "pgo"]\r
-!message *** Doing profile guided optimization\r
-PGO            = 2\r
-!else\r
-PGO            = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "loimpact"]\r
-!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
-!endif\r
-\r
-# TBD - should get rid of this option\r
-!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
-!message *** Doing thrdalloc\r
-USE_THREAD_ALLOC = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "tclalloc"]\r
-USE_THREAD_ALLOC = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "unchecked"]\r
-!message *** Doing unchecked\r
-UNCHECKED = 1\r
-!else\r
-UNCHECKED = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
-CONFIG_CHECK = 1\r
-!else\r
-CONFIG_CHECK = 0\r
-!endif\r
-\r
-!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
-\r
-# Set linker flags based on above\r
-\r
-!if $(PGO) > 1\r
-!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!elseif $(PGO) > 0\r
-!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
-# The following macros are set by this section:\r
-# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
-#                 0 -> disables\r
-# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
-#                     0 -> disables\r
-\r
-# Default both are off\r
-TCL_MEM_DEBUG      = 0\r
-TCL_COMPILE_DEBUG   = 0\r
-\r
-!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
-\r
-!if [nmakehlp -f $(STATS) "memdbg"]\r
-!message *** Doing memdbg\r
-TCL_MEM_DEBUG      = 1\r
-!else\r
-TCL_MEM_DEBUG      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(STATS) "compdbg"]\r
-!message *** Doing compdbg\r
-TCL_COMPILE_DEBUG   = 1\r
-!else\r
-TCL_COMPILE_DEBUG   = 0\r
-!endif\r
-\r
-!endif\r
-\r
-####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
-# The following macros are set by this section:\r
-# WARNINGS - compiler switches that control the warnings level\r
-# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
-#                     0 -> enable deprecated functions\r
-\r
-# Defaults - Permit deprecated functions and warning level 3\r
-TCL_NO_DEPRECATED          = 0\r
-WARNINGS                   = -W3\r
-\r
-!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
-\r
-!if [nmakehlp -f $(CHECKS) "nodep"]\r
-!message *** Doing nodep check\r
-TCL_NO_DEPRECATED          = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
-!message *** Doing full warnings check\r
-WARNINGS                   = -W4\r
-!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
-!endif\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
-!message *** Doing 64bit portability warnings\r
-WARNINGS                   = $(WARNINGS) -Wp64\r
-!endif\r
-\r
-!endif\r
-\r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
-\r
-################################################################\r
-# 10. Construct output directory and file paths\r
-# Figure-out how to name our intermediate and output directories.\r
-# In order to avoid inadvertent mixing of object files built using\r
-# different compilers, build configurations etc.,\r
-#\r
-# Naming convention (suffixes):\r
-#   t = full thread support. (Not used for Tcl >= 8.7)\r
-#   s = static library (as opposed to an import library)\r
-#   g = linked to the debug enabled C run-time.\r
-#   x = special static build when it links to the dynamic C run-time.\r
-#\r
-# The following macros are set in this section:\r
-# SUFX - the suffix to use for binaries based on above naming convention\r
-# BUILDDIRTOP - the toplevel default output directory\r
-#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
-# TMP_DIR - directory where object files are created\r
-# OUT_DIR - directory where output executables are created\r
-# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
-# parent makefile (or command line). The default values are\r
-# based on BUILDDIRTOP.\r
-# STUBPREFIX - name of the stubs library for this project\r
-# PRJIMPLIB - output path of the generated project import library\r
-# PRJLIBNAME - name of generated project library\r
-# PRJLIB     - output path of generated project library\r
-# PRJSTUBLIBNAME - name of the generated project stubs library\r
-# PRJSTUBLIB - output path of the generated project stubs library\r
-# RESFILE - output resource file (only if not static build)\r
-\r
-SUFX       = tsgx\r
-\r
-!if $(DEBUG)\r
-BUILDDIRTOP = Debug\r
-!else\r
-BUILDDIRTOP = Release\r
-!endif\r
-\r
-!if "$(MACHINE)" != "IX86"\r
-BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
-!endif\r
-!if $(VCVER) > 6\r
-BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
-!endif\r
-\r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
-SUFX       = $(SUFX:g=)\r
-!endif\r
-\r
-TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
-\r
-!if !$(STATIC_BUILD)\r
-TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
-SUFX       = $(SUFX:s=)\r
-EXT        = dll\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!else\r
-TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
-EXT        = lib\r
-!if !$(MSVCRT)\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!endif\r
-!endif\r
-\r
-!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
-TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
-SUFX       = $(SUFX:t=)\r
-!endif\r
-\r
-!ifndef TMP_DIR\r
-TMP_DIR            = $(TMP_DIRFULL)\r
-!ifndef OUT_DIR\r
-OUT_DIR            = .\$(BUILDDIRTOP)\r
-!endif\r
-!else\r
-!ifndef OUT_DIR\r
-OUT_DIR            = $(TMP_DIR)\r
-!endif\r
-!endif\r
-\r
-# Relative paths -> absolute\r
-!if [echo OUT_DIR = \> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
-!endif\r
-!if [echo TMP_DIR = \>> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
-!endif\r
-!include nmakehlp.out\r
-\r
-# The name of the stubs library for the project being built\r
-STUBPREFIX      = $(PROJECT)stub\r
-\r
-# Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
-\r
-TCLSHNAME       = $(PROJECT)sh$(TCL_VERSION)$(SUFX).exe\r
-TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
-TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
-\r
-TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
-TCL_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-\r
-# When building extensions, we need to locate tclsh. Depending on version\r
-# of Tcl we are building against, this may or may not have a "t" suffix.\r
-# Try various possibilities in turn.\r
-TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist("$(TCLSH)") && $(TCL_THREADS)\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist("$(TCLSH)")\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-\r
-TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\lib\r
-TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
-TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
-\r
-!else # Building against Tcl sources\r
-\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist($(TCLSH)) && $(TCL_THREADS)\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist($(TCLSH))\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\library\r
-TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = $(_TCLDIR)\tools\r
-TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
-\r
-!endif # TCLINSTALL\r
-\r
-tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
-\r
-!endif # $(DOING_TCL)\r
-\r
-# We need a tclsh that will run on the host machine as part of the build.\r
-# IX86 runs on all architectures.\r
-!ifndef TCLSH_NATIVE\r
-!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
-TCLSH_NATIVE   = $(TCLSH)\r
-!else\r
-!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
-!endif\r
-!endif\r
-\r
-# Do the same for Tk and Tk extensions that require the Tk libraries\r
-!if $(DOING_TK) || $(NEED_TK)\r
-WISHNAMEPREFIX = wish\r
-WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
-TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
-TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
-\r
-!if $(DOING_TK)\r
-WISH           = $(OUT_DIR)\$(WISHNAME)\r
-TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
-TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # effectively NEED_TK\r
-\r
-!if $(TKINSTALL) # Building against installed Tk\r
-WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\include"\r
-!else # Building against Tk sources\r
-WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
-!endif # TKINSTALL\r
-tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
-\r
-!endif # $(DOING_TK)\r
-!endif # $(DOING_TK) || $(NEED_TK)\r
-\r
-# Various output paths\r
-PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
-\r
-PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
-\r
-# If extension parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
-!ifdef RCFILE\r
-RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
-!else\r
-RESFILE = $(TMP_DIR)\$(PROJECT).res\r
-!endif\r
-!endif\r
-\r
-###################################################################\r
-# 11. Construct the paths for the installation directories\r
-# The following macros get defined in this section:\r
-# LIB_INSTALL_DIR - where libraries should be installed\r
-# BIN_INSTALL_DIR - where the executables should be installed\r
-# DOC_INSTALL_DIR - where documentation should be installed\r
-# SCRIPT_INSTALL_DIR - where scripts should be installed\r
-# INCLUDE_INSTALL_DIR - where C include files should be installed\r
-# DEMO_INSTALL_DIR - where demos should be installed\r
-# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
-\r
-!if $(DOING_TCL) || $(DOING_TK)\r
-LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
-BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
-DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
-!if $(DOING_TCL)\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!else # DOING_TK\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
-\r
-!else # extension other than Tk\r
-\r
-PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
-!if $(MULTIPLATFORM_INSTALL)\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-!else\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-!endif\r
-DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
-DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
-\r
-!endif\r
-\r
-###################################################################\r
-# 12. Set up actual options to be passed to the compiler and linker\r
-# Now we have all the information we need, set up the actual flags and\r
-# options that we will pass to the compiler and linker. The main\r
-# makefile should use these in combination with whatever other flags\r
-# and switches are specific to it.\r
-# The following macros are defined, names are for historical compatibility:\r
-# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
-# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
-# crt - Compiler switch that selects the appropriate C runtime\r
-# cdebug - Compiler switches related to debug AND optimizations\r
-# cwarn - Compiler switches that set warning levels\r
-# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
-# ldebug - Linker switches controlling debug information and optimization\r
-# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
-# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
-# conlflags - complete linker switches for console program (subsumes lflags)\r
-# guilflags - complete linker switches for GUI program (subsumes lflags)\r
-# baselibs - minimum Windows libraries required. Parent makefile can\r
-#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
-\r
-OPTDEFINES     = -DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) -DSTDC_HEADERS\r
-\r
-!if $(TCL_MEM_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_MEM_DEBUG\r
-!endif\r
-!if $(TCL_COMPILE_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS\r
-!endif\r
-!if $(TCL_THREADS) && $(TCL_VERSION) <= 86\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_THREADS=1\r
-!if $(USE_THREAD_ALLOC)\r
-OPTDEFINES     = $(OPTDEFINES) -DUSE_THREAD_ALLOC=1\r
-!endif\r
-!endif\r
-!if $(STATIC_BUILD)\r
-OPTDEFINES     = $(OPTDEFINES) -DSTATIC_BUILD\r
-!endif\r
-!if $(TCL_NO_DEPRECATED)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_NO_DEPRECATED\r
-!endif\r
-\r
-!if $(USE_STUBS)\r
-# Note we do not define USE_TCL_STUBS even when building tk since some\r
-# test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
-USE_STUBS_DEFS  = -DUSE_TCL_STUBS -DUSE_TCLOO_STUBS\r
-!if $(NEED_TK)\r
-USE_STUBS_DEFS  = $(USE_STUBS_DEFS) -DUSE_TK_STUBS\r
-!endif\r
-!endif\r
-!endif # USE_STUBS\r
-\r
-!if !$(DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DNDEBUG\r
-!if $(OPTIMIZING)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_OPTIMIZED\r
-!endif\r
-!endif\r
-!if $(PROFILE)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_PROFILED\r
-!endif\r
-!if "$(MACHINE)" == "AMD64"\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_DO64BIT\r
-!endif\r
-!if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) -DNO_STRTOI64\r
-!endif\r
-\r
-!if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) -D_USE_64BIT_TIME_T\r
-!endif\r
-\r
-# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
-COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
-\r
-# Following is primarily for the benefit of extensions. Tcl 8.5 builds\r
-# Tcl without /DUNICODE, while 8.6 builds with it defined. When building\r
-# an extension, it is advisable (but not mandated) to use the same Windows\r
-# API as the Tcl build. This is accordingly defaulted below. A particular\r
-# extension can override this by pre-definining USE_WIDECHAR_API.\r
-!ifndef USE_WIDECHAR_API\r
-!if $(TCL_VERSION) > 85\r
-USE_WIDECHAR_API = 1\r
-!else\r
-USE_WIDECHAR_API = 0\r
-!endif\r
-!endif\r
-\r
-!if $(USE_WIDECHAR_API)\r
-COMPILERFLAGS = $(COMPILERFLAGS) /DUNICODE /D_UNICODE\r
-!endif\r
-\r
-# Like the TEA system only set this non empty for non-Tk extensions\r
-# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
-# so we pass both\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-PKGNAMEFLAGS = -DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
-               -DMODULE_SCOPE=extern\r
-!endif\r
-\r
-# crt picks the C run time based on selected OPTS\r
-!if $(MSVCRT)\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MDd\r
-!else\r
-crt = -MD\r
-!endif\r
-!else\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MTd\r
-!else\r
-crt = -MT\r
-!endif\r
-!endif\r
-\r
-# cdebug includes compiler options for debugging as well as optimization.\r
-!if $(DEBUG)\r
-\r
-# In debugging mode, optimizations need to be disabled\r
-cdebug = -Zi -Od $(DEBUGFLAGS)\r
-\r
-!else\r
-\r
-cdebug = $(OPTIMIZATIONS)\r
-!if $(SYMBOLS)\r
-cdebug = $(cdebug) -Zi\r
-!endif\r
-\r
-!endif # $(DEBUG)\r
-\r
-# cwarn includes default warning levels.\r
-cwarn = $(WARNINGS)\r
-\r
-!if "$(MACHINE)" == "AMD64"\r
-# Disable pointer<->int warnings related to cast between different sizes\r
-# There are a gadzillion of these due to use of ClientData and\r
-# clutter up compiler\r
-# output increasing chance of a real warning getting lost. So disable them.\r
-# Eventually some day, Tcl will be 64-bit clean.\r
-cwarn = $(cwarn) -wd4311 -wd4312\r
-!endif\r
-\r
-### Common compiler options that are architecture specific\r
-!if "$(MACHINE)" == "ARM"\r
-carch = -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
-!else\r
-carch =\r
-!endif\r
-\r
-!if $(DEBUG)\r
-# Turn warnings into errors\r
-cwarn = $(cwarn) -WX\r
-!endif\r
-\r
-INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WINDIR)" -I"$(COMPATDIR)"\r
-!endif\r
-\r
-# These flags are defined roughly in the order of the pre-reform\r
-# rules.vc/makefile.vc to help visually compare that the pre- and\r
-# post-reform build logs\r
-\r
-# cflags contains generic flags used for building practically all object files\r
-cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
-\r
-# appcflags contains $(cflags) and flags for building the application\r
-# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
-# flags used for building shared object files The two differ in the\r
-# BUILD_$(PROJECT) macro which should be defined only for the shared\r
-# library *implementation* and not for its caller interface\r
-\r
-appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
-appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
-pkgcflags = $(appcflags) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-\r
-# stubscflags contains $(cflags) plus flags used for building a stubs\r
-# library for the package.  Note: -DSTATIC_BUILD is defined in\r
-# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
-# library. However the stubs library is ALWAYS static hence included\r
-# here irrespective of the OPTS setting.\r
-#\r
-# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
-# without stating why. Tcl itself compiled stubs libs with this flag.\r
-# so we do not remove it from cflags. -GL may prevent extensions\r
-# compiled with one VC version to fail to link against stubs library\r
-# compiled with another VC version. Check for this and fix accordingly.\r
-stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl -DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
-\r
-# Link flags\r
-\r
-!if $(DEBUG)\r
-ldebug = -debug -debugtype:cv\r
-!else\r
-ldebug = -release -opt:ref -opt:icf,3\r
-!if $(SYMBOLS)\r
-ldebug = $(ldebug) -debug -debugtype:cv\r
-!endif\r
-!endif\r
-\r
-# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
-!if $(PROFILE)\r
-ldebug= $(ldebug) -profile\r
-!endif\r
-\r
-### Declarations common to all linker versions\r
-lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-lflags = $(lflags) -nodefaultlib:libucrt.lib\r
-!endif\r
-\r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
-dlllflags = $(lflags) -dll\r
-conlflags = $(lflags) -subsystem:console\r
-guilflags = $(lflags) -subsystem:windows\r
-\r
-# Libraries that are required for every image.\r
-# Extensions should define any additional libraries with $(PRJ_LIBS)\r
-winlibs   = kernel32.lib advapi32.lib\r
-\r
-!if $(NEED_TK)\r
-winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
-!endif\r
-\r
-# Avoid 'unresolved external symbol __security_cookie' errors.\r
-# c.f. http://support.microsoft.com/?id=894573\r
-!if "$(MACHINE)" == "AMD64"\r
-!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
-winlibs   = $(winlibs) bufferoverflowU.lib\r
-!endif\r
-!endif\r
-\r
-baselibs = $(winlibs) $(PRJ_LIBS)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-baselibs   = $(baselibs) ucrt.lib\r
-!endif\r
-\r
-################################################################\r
-# 13. Define standard commands, common make targets and implicit rules\r
-\r
-CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
-CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
-CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
-\r
-LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
-DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-\r
-CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
-           $(TCL_INCLUDES) \\r
-           -DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           -DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
-           -DDOTVERSION=\"$(DOTVERSION)\" \\r
-           -DVERSION=\"$(VERSION)\" \\r
-           -DSUFX=\"$(SUFX)\" \\r
-           -DPROJECT=\"$(PROJECT)\" \\r
-           -DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
-\r
-!ifndef DEFAULT_BUILD_TARGET\r
-DEFAULT_BUILD_TARGET = $(PROJECT)\r
-!endif\r
-\r
-default-target: $(DEFAULT_BUILD_TARGET)\r
-\r
-!if $(MULTIPLATFORM_INSTALL)\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!else\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!endif\r
-\r
-default-pkgindex-tea:\r
-       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
-@PACKAGE_VERSION@    $(DOTVERSION)\r
-@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
-@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
-@PKG_LIB_FILE@       $(PRJLIBNAME)\r
-<<\r
-\r
-default-install: default-install-binaries default-install-libraries\r
-!if $(SYMBOLS)\r
-default-install: default-install-pdbs\r
-!endif\r
-\r
-# Again to deal with historical brokenness, there is some confusion\r
-# in terminlogy. For extensions, the "install-binaries" was used to\r
-# locate target directory for *binary shared libraries* and thus\r
-# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
-# for executables (exes). On the other hand the "install-libraries"\r
-# target is for *scripts* and should have been called "install-scripts".\r
-default-install-binaries: $(PRJLIB)\r
-       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
-\r
-# Alias for default-install-scripts\r
-default-install-libraries: default-install-scripts\r
-\r
-default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
-       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
-       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
-       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
-       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
-\r
-default-install-stubs:\r
-       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
-       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
-\r
-default-install-pdbs:\r
-       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
-\r
-default-install-docs-html:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-docs-n:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-demos:\r
-       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
-       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
-       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
-\r
-default-clean:\r
-       @echo Cleaning $(TMP_DIR)\* ...\r
-       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
-       @echo Cleaning $(WINDIR)\nmakehlp.obj, nmakehlp.exe ...\r
-       @if exist $(WINDIR)\nmakehlp.obj del $(WINDIR)\nmakehlp.obj\r
-       @if exist $(WINDIR)\nmakehlp.exe del $(WINDIR)\nmakehlp.exe\r
-       @if exist $(WINDIR)\nmakehlp.out del $(WINDIR)\nmakehlp.out\r
-       @echo Cleaning $(WINDIR)\nmhlp-out.txt ...\r
-       @if exist $(WINDIR)\nmhlp-out.txt del $(WINDIR)\nmhlp-out.txt\r
-       @echo Cleaning $(WINDIR)\_junk.pch ...\r
-       @if exist $(WINDIR)\_junk.pch del $(WINDIR)\_junk.pch\r
-       @echo Cleaning $(WINDIR)\vercl.x, vercl.i ...\r
-       @if exist $(WINDIR)\vercl.x del $(WINDIR)\vercl.x\r
-       @if exist $(WINDIR)\vercl.i del $(WINDIR)\vercl.i\r
-       @echo Cleaning $(WINDIR)\versions.vc, version.vc ...\r
-       @if exist $(WINDIR)\versions.vc del $(WINDIR)\versions.vc\r
-       @if exist $(WINDIR)\version.vc del $(WINDIR)\version.vc\r
-\r
-default-hose: default-clean\r
-       @echo Hosing $(OUT_DIR)\* ...\r
-       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
-\r
-# Only for backward compatibility\r
-default-distclean: default-hose\r
-\r
-default-setup:\r
-       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
-       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
-\r
-!if "$(TESTPAT)" != ""\r
-TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
-!endif\r
-\r
-default-test: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
-\r
-default-shell: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       $(DEBUGGER) $(TCLSH)\r
-\r
-# Generation of Windows version resource\r
-!ifdef RCFILE\r
-\r
-# Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
-$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
-       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
-\r
-!else\r
-\r
-# If parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
-\r
-$(TMP_DIR)\$(PROJECT).rc:\r
-       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
-#include <winver.h>\r
-\r
-VS_VERSION_INFO VERSIONINFO\r
- FILEVERSION   COMMAVERSION\r
- PRODUCTVERSION        COMMAVERSION\r
- FILEFLAGSMASK 0x3fL\r
-#ifdef DEBUG\r
- FILEFLAGS     VS_FF_DEBUG\r
-#else\r
- FILEFLAGS     0x0L\r
-#endif\r
- FILEOS                VOS_NT_WINDOWS32\r
- FILETYPE      VFT_DLL\r
- FILESUBTYPE   0x0L\r
-BEGIN\r
-    BLOCK "StringFileInfo"\r
-    BEGIN\r
-        BLOCK "040904b0"\r
-        BEGIN\r
-            VALUE "FileDescription",  "Tcl extension " PROJECT\r
-            VALUE "OriginalFilename", PRJLIBNAME\r
-            VALUE "FileVersion",      DOTVERSION\r
-            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
-            VALUE "ProductVersion",   DOTVERSION\r
-        END\r
-    END\r
-    BLOCK "VarFileInfo"\r
-    BEGIN\r
-        VALUE "Translation", 0x409, 1200\r
-    END\r
-END\r
-\r
-<<\r
-\r
-!endif # ifdef RCFILE\r
-\r
-!ifndef DISABLE_IMPLICIT_RULES\r
-DISABLE_IMPLICIT_RULES = 0\r
-!endif\r
-\r
-!if !$(DISABLE_IMPLICIT_RULES)\r
-# Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
-\r
-{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(WINDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(WINDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-.SUFFIXES:\r
-.SUFFIXES:.c .rc\r
-\r
-!endif\r
-\r
-################################################################\r
-# 14. Sanity check selected options against Tcl build options\r
-# When building an extension, certain configuration options should\r
-# match the ones used when Tcl was built. Here we check and\r
-# warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
-TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
-!endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
-!endif\r
-!endif # TCLINSTALL\r
-\r
-!if $(CONFIG_CHECK)\r
-!ifdef TCLNMAKECONFIG\r
-!include $(TCLNMAKECONFIG)\r
-\r
-!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
-!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
-!endif\r
-!if defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
-!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
-!endif\r
-!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
-!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
-!endif\r
-!endif\r
-\r
-!endif # TCLNMAKECONFIG\r
-\r
-!endif # ! $(DOING_TCL)\r
-\r
-\r
-#----------------------------------------------------------\r
-# Display stats being used.\r
-#----------------------------------------------------------\r
-\r
-!if !$(DOING_TCL)\r
-!message *** Building against Tcl at '$(_TCLDIR)'\r
-!endif\r
-!if !$(DOING_TK) && $(NEED_TK)\r
-!message *** Building against Tk at '$(_TKDIR)'\r
-!endif\r
-!message *** Intermediate directory will be '$(TMP_DIR)'\r
-!message *** Output directory will be '$(OUT_DIR)'\r
-!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
-!message *** Suffix for binaries will be '$(SUFX)'\r
-!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
-\r
-!endif # ifdef _RULES_VC\r
diff --git a/pkgs/tdbcodbc1.1.1/win/targets.vc b/pkgs/tdbcodbc1.1.1/win/targets.vc
deleted file mode 100644 (file)
index 7f1d388..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# targets.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file defines some standard targets for the convenience of extensions\r
-# and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
-\r
-$(PROJECT): setup pkgindex $(PRJLIB)\r
-\r
-!ifdef PRJ_STUBOBJS\r
-$(PROJECT): $(PRJSTUBLIB)\r
-$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
-       $(LIBCMD) $**\r
-\r
-$(PRJ_STUBOBJS):\r
-       $(CCSTUBSCMD) %s\r
-!endif # PRJ_STUBOBJS\r
-\r
-!ifdef PRJ_MANIFEST\r
-$(PROJECT): $(PRJLIB).manifest\r
-$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
-       @nmakehlp -s << $** >$@\r
-@MACHINE@        $(MACHINE:IX86=X86)\r
-<<\r
-!endif\r
-\r
-!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
-$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
-!if $(STATIC_BUILD)\r
-       $(LIBCMD) $**\r
-!else\r
-       $(DLLCMD) $**\r
-       $(_VC_MANIFEST_EMBED_DLL)\r
-!endif\r
-       -@del $*.exp\r
-!endif\r
-\r
-!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
-$(PRJ_OBJS): $(PRJ_HEADERS)\r
-!endif\r
-\r
-# If parent makefile has defined stub objects, add their installation\r
-# to the default install\r
-!if "$(PRJ_STUBOBJS)" != ""\r
-default-install: default-install-stubs\r
-!endif\r
-\r
-# Unlike the other default targets, these cannot be in rules.vc because\r
-# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
-# that the parent makefile will not define until after including rules-ext.vc\r
-!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
-default-install: default-install-headers\r
-default-install-headers:\r
-       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
-       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
-!endif\r
-\r
-!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
-DISABLE_STANDARD_TARGETS = 0\r
-!endif\r
-\r
-!if "$(DISABLE_TARGET_setup)" == ""\r
-DISABLE_TARGET_setup = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_install)" == ""\r
-DISABLE_TARGET_install = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_clean)" == ""\r
-DISABLE_TARGET_clean = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_test)" == ""\r
-DISABLE_TARGET_test = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_shell)" == ""\r
-DISABLE_TARGET_shell = 0\r
-!endif\r
-\r
-!if !$(DISABLE_STANDARD_TARGETS)\r
-!if !$(DISABLE_TARGET_setup)\r
-setup: default-setup\r
-!endif\r
-!if !$(DISABLE_TARGET_install)\r
-install: default-install\r
-!endif\r
-!if !$(DISABLE_TARGET_clean)\r
-clean: default-clean\r
-realclean: hose\r
-hose: default-hose\r
-distclean: realclean default-distclean\r
-!endif\r
-!if !$(DISABLE_TARGET_test)\r
-test: default-test\r
-!endif\r
-!if !$(DISABLE_TARGET_shell)\r
-shell: default-shell\r
-!endif\r
-!endif # DISABLE_STANDARD_TARGETS\r
similarity index 95%
rename from pkgs/tdbcodbc1.1.1/README
rename to pkgs/tdbcodbc1.1.2/README
index bbcb972..fbbf47d 100644 (file)
@@ -1,6 +1,6 @@
 README: tdbcodbc
 
-    This is the 1.1.1 source distribution of the bridge between Tcl
+    This is the 1.1.2 source distribution of the bridge between Tcl
     Database Connectivity (TDBC) and Open Database Connectivity
     (ODBC), a database-neutral API layer available on all Windows
     systems and many others.. TDBC and its drivers are available from
similarity index 98%
rename from pkgs/tdbcodbc1.1.1/configure
rename to pkgs/tdbcodbc1.1.2/configure
index 0795639..eb7bfa1 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for tdbcodbc 1.1.1.
+# Generated by GNU Autoconf 2.69 for tdbcodbc 1.1.2.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='tdbcodbc'
 PACKAGE_TARNAME='tdbcodbc'
-PACKAGE_VERSION='1.1.1'
-PACKAGE_STRING='tdbcodbc 1.1.1'
+PACKAGE_VERSION='1.1.2'
+PACKAGE_STRING='tdbcodbc 1.1.2'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -627,7 +627,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -635,6 +634,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1304,7 +1305,7 @@ 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 tdbcodbc 1.1.1 to adapt to many kinds of systems.
+\`configure' configures tdbcodbc 1.1.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1365,7 +1366,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of tdbcodbc 1.1.1:";;
+     short | recursive ) echo "Configuration of tdbcodbc 1.1.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1466,7 +1467,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-tdbcodbc configure 1.1.1
+tdbcodbc configure 1.1.2
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2068,7 +2069,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by tdbcodbc $as_me 1.1.1, which was
+It was created by tdbcodbc $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3578,10 +3579,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3615,12 +3612,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3926,7 +3917,7 @@ $as_echo_n "checking For TDBC_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3940,7 +3931,7 @@ $as_echo "using TDBC_STUB_LIB_PATH ${TDBC_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3969,7 +3960,7 @@ $as_echo_n "checking For tdbc_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3983,7 +3974,7 @@ $as_echo "using tdbc_STUB_LIB_PATH ${tdbc_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5600,7 +5591,7 @@ if test "${TCL_MAJOR_VERSION}" -eq 8 ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5625,7 +5616,7 @@ if test "x${TEA_PLATFORM}" = "xwindows" -a "x${GCC}" != "xyes" ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5637,7 +5628,7 @@ else
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6585,7 +6576,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6610,7 +6601,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6759,14 +6750,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6847,14 +6838,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6869,7 +6860,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6945,39 +6936,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -7102,8 +7060,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -7130,7 +7088,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -7199,8 +7157,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -7216,8 +7174,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -7226,8 +7184,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -7255,8 +7213,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -7279,7 +7237,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -7289,9 +7247,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -7356,8 +7327,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -7374,11 +7345,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -7396,7 +7367,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -7404,32 +7375,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7738,7 +7683,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7808,13 +7753,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7914,7 +7859,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7951,8 +7896,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -8251,6 +8196,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8645,7 +8592,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8659,11 +8605,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8802,7 +8743,7 @@ if test "x$ac_cv_lib_ws2_32_main" = xyes; then :
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lLiIbB$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -8846,7 +8787,7 @@ if test "x$ac_cv_lib_winsock_main" = xyes; then :
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lLiIbB$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -8867,7 +8808,7 @@ fi
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8893,7 +8834,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8981,14 +8922,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8996,9 +8937,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -9569,7 +9510,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by tdbcodbc $as_me 1.1.1, which was
+This file was extended by tdbcodbc $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9622,7 +9563,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-tdbcodbc config.status 1.1.1
+tdbcodbc config.status 1.1.2
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/tdbcodbc1.1.1/configure.ac
rename to pkgs/tdbcodbc1.1.2/configure.ac
index 8c03caa..3456090 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([tdbcodbc], [1.1.1])
+AC_INIT([tdbcodbc], [1.1.2])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
similarity index 99%
rename from pkgs/tdbcodbc1.1.1/generic/fakesql.h
rename to pkgs/tdbcodbc1.1.2/generic/fakesql.h
index 7bde20e..267d3c3 100644 (file)
@@ -69,7 +69,7 @@ typedef SQLSMALLINT SQLRETURN;
 /* TODO - Check how the SQLLEN and SQLULEN types are handled on
  *        64-bit Unix. */
 
-#if defined(__WIN64)
+#if defined(_WIN64)
 typedef Tcl_WideInt SQLLEN;
 typedef Tcl_WideUInt SQLULEN;
 #else
similarity index 97%
rename from pkgs/tdbcodbc1.1.1/generic/tdbcodbc.c
rename to pkgs/tdbcodbc1.1.2/generic/tdbcodbc.c
index e2d0586..cdaa571 100644 (file)
@@ -48,7 +48,7 @@ static Tcl_LoadHandle odbcInstLoadHandle = NULL;
                                /* Handle to the ODBC installer library */
 static SQLHENV hEnv = SQL_NULL_HENV;
                                /* Handle to the global ODBC environment */
-static int hEnvRefCount = 0;   /* Reference count on the global environment */
+static size_t hEnvRefCount = 0;        /* Reference count on the global environment */
 static size_t sizeofSQLWCHAR = sizeof(SQLWCHAR);
                                /* Preset, will be autodetected later */
 
@@ -92,7 +92,7 @@ enum LiteralIndex {
  */
 
 typedef struct PerInterpData {
-    int refCount;              /* Reference count */
+    size_t refCount;           /* Reference count */
     SQLHENV hEnv;              /* ODBC environment handle */
     Tcl_Obj* literals[LIT__END];
                                /* Literal pool */
@@ -122,7 +122,7 @@ typedef struct PerInterpData {
  */
 
 typedef struct ConnectionData {
-    int refCount;              /* Reference count. */
+    size_t refCount;           /* Reference count. */
     PerInterpData* pidata;     /* Per-interpreter data */
     Tcl_Obj* connectionString; /* Connection string actually used to
                                 * connect to the database */
@@ -168,7 +168,7 @@ typedef struct ConnectionData {
  */
 
 typedef struct StatementData {
-    int refCount;              /* Reference count */
+    size_t refCount;           /* Reference count */
     Tcl_Object connectionObject;
                                /* The connection object */
     ConnectionData* cdata;     /* Data for the connection to which this
@@ -178,10 +178,10 @@ typedef struct StatementData {
                                 * statement */
     SQLHSTMT hStmt;            /* Handle to the ODBC statement */
     SQLWCHAR* nativeSqlW;      /* SQL statement as wide chars */
-    int nativeSqlLen;          /* Length of the statement */
+    size_t nativeSqlLen;               /* Length of the statement */
     SQLWCHAR* nativeMatchPatternW;
                                /* Match pattern for metadata queries */
-    int nativeMatchPatLen;     /* Length of the match pattern */
+    size_t nativeMatchPatLen;  /* Length of the match pattern */
     struct ParamData* params;  /* Pointer to an array of ParamData
                                 * structures that describe the data types
                                 * of substituted parameters. */
@@ -300,7 +300,7 @@ typedef struct OdbcConstant {
  * Constants for the directions of parameter transmission
  */
 
-const static OdbcConstant OdbcParamDirections[] = {
+static const OdbcConstant OdbcParamDirections[] = {
     { "in",            PARAM_KNOWN | PARAM_IN, },
     { "out",           PARAM_KNOWN | PARAM_OUT },
     { "inout",         PARAM_KNOWN | PARAM_IN | PARAM_OUT },
@@ -311,7 +311,7 @@ const static OdbcConstant OdbcParamDirections[] = {
  * ODBC constants for the names of data types
  */
 
-const static OdbcConstant OdbcTypeNames[] = {
+static const OdbcConstant OdbcTypeNames[] = {
     { "bigint",                SQL_BIGINT },
     { "binary",                SQL_BINARY },
     { "bit",           SQL_BIT } ,
@@ -334,7 +334,7 @@ const static OdbcConstant OdbcTypeNames[] = {
     { NULL,            -1 }
 };
 
-const static OdbcConstant OdbcIsolationLevels[] = {
+static const OdbcConstant OdbcIsolationLevels[] = {
     { "readuncommitted",       SQL_TXN_READ_UNCOMMITTED },
     { "readcommitted",         SQL_TXN_READ_COMMITTED },
     { "repeatableread",                SQL_TXN_REPEATABLE_READ },
@@ -342,7 +342,7 @@ const static OdbcConstant OdbcIsolationLevels[] = {
     { NULL,                    0 }
 };
 
-const static OdbcConstant OdbcErrorCodeNames[] = {
+static const OdbcConstant OdbcErrorCodeNames[] = {
     { "GENERAL_ERR",                   ODBC_ERROR_GENERAL_ERR },
     { "INVALID_BUFF_LEN",              ODBC_ERROR_INVALID_BUFF_LEN },
     { "INVALID_HWND",                  ODBC_ERROR_INVALID_HWND },
@@ -369,8 +369,8 @@ const static OdbcConstant OdbcErrorCodeNames[] = {
 
 /* Prototypes for static functions appearing in this file */
 
-static void DStringAppendWChars(Tcl_DString* ds, SQLWCHAR* ws, int len);
-static SQLWCHAR* GetWCharStringFromObj(Tcl_Obj* obj, int* lengthPtr);
+static void DStringAppendWChars(Tcl_DString* ds, SQLWCHAR* ws, size_t len);
+static SQLWCHAR* GetWCharStringFromObj(Tcl_Obj* obj, size_t* lengthPtr);
 
 static void TransferSQLError(Tcl_Interp* interp, SQLSMALLINT handleType,
                             SQLHANDLE handle, const char* info);
@@ -493,7 +493,7 @@ static int DriversObjCmd(ClientData clientData, Tcl_Interp* interp,
 \f
 /* Metadata type that holds connection data */
 
-const static Tcl_ObjectMetadataType connectionDataType = {
+static const Tcl_ObjectMetadataType connectionDataType = {
     TCL_OO_METADATA_VERSION_CURRENT,
                                /* version */
     "ConnectionData",          /* name */
@@ -504,7 +504,7 @@ const static Tcl_ObjectMetadataType connectionDataType = {
 
 /* Metadata type that holds statement data */
 
-const static Tcl_ObjectMetadataType statementDataType = {
+static const Tcl_ObjectMetadataType statementDataType = {
     TCL_OO_METADATA_VERSION_CURRENT,
                                /* version */
     "StatementData",           /* name */
@@ -515,7 +515,7 @@ const static Tcl_ObjectMetadataType statementDataType = {
 
 /* Metadata type for result set data */
 
-const static Tcl_ObjectMetadataType resultSetDataType = {
+static const Tcl_ObjectMetadataType resultSetDataType = {
     TCL_OO_METADATA_VERSION_CURRENT,
                                /* version */
     "ResultSetData",           /* name */
@@ -526,7 +526,7 @@ const static Tcl_ObjectMetadataType resultSetDataType = {
 
 /* Method types of the connection methods that are implemented in C */
 
-const static Tcl_MethodType ConnectionConstructorType = {
+static const Tcl_MethodType ConnectionConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -534,7 +534,7 @@ const static Tcl_MethodType ConnectionConstructorType = {
     DeleteCmd,                 /* deleteProc */
     CloneCmd                   /* cloneProc */
 };
-const static Tcl_MethodType ConnectionBeginTransactionMethodType = {
+static const Tcl_MethodType ConnectionBeginTransactionMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "begintransaction",                /* name */
@@ -543,7 +543,7 @@ const static Tcl_MethodType ConnectionBeginTransactionMethodType = {
     NULL,                      /* deleteProc */
     CloneCmd                   /* cloneProc */
 };
-const static Tcl_MethodType ConnectionConfigureMethodType = {
+static const Tcl_MethodType ConnectionConfigureMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "configure",               /* name */
@@ -551,7 +551,7 @@ const static Tcl_MethodType ConnectionConfigureMethodType = {
     NULL,                      /* deleteProc */
     CloneCmd                   /* cloneProc */
 };
-const static Tcl_MethodType ConnectionEndXcnMethodType = {
+static const Tcl_MethodType ConnectionEndXcnMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "endtransaction",          /* name */
@@ -559,7 +559,7 @@ const static Tcl_MethodType ConnectionEndXcnMethodType = {
     NULL,                      /* deleteProc */
     CloneCmd                   /* cloneProc */
 };
-const static Tcl_MethodType ConnectionHasBigintMethodType = {
+static const Tcl_MethodType ConnectionHasBigintMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "HasBigint",               /* name */
@@ -568,7 +568,7 @@ const static Tcl_MethodType ConnectionHasBigintMethodType = {
     NULL,                      /* deleteProc */
     CloneCmd                   /* cloneProc */
 };
-const static Tcl_MethodType ConnectionHasWvarcharMethodType = {
+static const Tcl_MethodType ConnectionHasWvarcharMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "HasWvarchar",             /* name */
@@ -583,7 +583,7 @@ const static Tcl_MethodType ConnectionHasWvarcharMethodType = {
  * 'rollback' are all special because they have non-NULL clientData.
  */
 
-const static Tcl_MethodType* ConnectionMethods[] = {
+static const Tcl_MethodType* ConnectionMethods[] = {
     &ConnectionBeginTransactionMethodType,
     &ConnectionConfigureMethodType,
     &ConnectionHasBigintMethodType,
@@ -593,7 +593,7 @@ const static Tcl_MethodType* ConnectionMethods[] = {
 
 /* Method types of the statement methods that are implemented in C */
 
-const static Tcl_MethodType StatementConstructorType = {
+static const Tcl_MethodType StatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -601,7 +601,7 @@ const static Tcl_MethodType StatementConstructorType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType StatementConnectionMethodType = {
+static const Tcl_MethodType StatementConnectionMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "connection",              /* name */
@@ -609,7 +609,7 @@ const static Tcl_MethodType StatementConnectionMethodType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType StatementParamListMethodType = {
+static const Tcl_MethodType StatementParamListMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "ParamList",               /* name */
@@ -617,7 +617,7 @@ const static Tcl_MethodType StatementParamListMethodType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType StatementParamtypeMethodType = {
+static const Tcl_MethodType StatementParamtypeMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "paramtype",               /* name */
@@ -630,7 +630,7 @@ const static Tcl_MethodType StatementParamtypeMethodType = {
  * Methods to create on the statement class.
  */
 
-const static Tcl_MethodType* StatementMethods[] = {
+static const Tcl_MethodType* StatementMethods[] = {
     &StatementConnectionMethodType,
     &StatementParamListMethodType,
     &StatementParamtypeMethodType,
@@ -642,7 +642,7 @@ const static Tcl_MethodType* StatementMethods[] = {
  * used to query the names and attributes of database tables.
  */
 
-const static Tcl_MethodType TablesStatementConstructorType = {
+static const Tcl_MethodType TablesStatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -656,7 +656,7 @@ const static Tcl_MethodType TablesStatementConstructorType = {
  * used to query the names and attributes of database columns.
  */
 
-const static Tcl_MethodType ColumnsStatementConstructorType = {
+static const Tcl_MethodType ColumnsStatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -671,7 +671,7 @@ const static Tcl_MethodType ColumnsStatementConstructorType = {
  * used to query the names and attributes of primary keys.
  */
 
-const static Tcl_MethodType PrimarykeysStatementConstructorType = {
+static const Tcl_MethodType PrimarykeysStatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -686,7 +686,7 @@ const static Tcl_MethodType PrimarykeysStatementConstructorType = {
  * used to query the names and attributes of foreign keys.
  */
 
-const static Tcl_MethodType ForeignkeysStatementConstructorType = {
+static const Tcl_MethodType ForeignkeysStatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -701,7 +701,7 @@ const static Tcl_MethodType ForeignkeysStatementConstructorType = {
  * used to query the names and attributes of database types.
  */
 
-const static Tcl_MethodType TypesStatementConstructorType = {
+static const Tcl_MethodType TypesStatementConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -712,7 +712,7 @@ const static Tcl_MethodType TypesStatementConstructorType = {
 
 /* Method types of the result set methods that are implemented in C */
 
-const static Tcl_MethodType ResultSetConstructorType = {
+static const Tcl_MethodType ResultSetConstructorType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "CONSTRUCTOR",             /* name */
@@ -720,14 +720,14 @@ const static Tcl_MethodType ResultSetConstructorType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType ResultSetColumnsMethodType = {
+static const Tcl_MethodType ResultSetColumnsMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */    "columns",                     /* name */
     ResultSetColumnsMethod,    /* callProc */
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType ResultSetNextresultsMethodType = {
+static const Tcl_MethodType ResultSetNextresultsMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "nextresults",             /* name */
@@ -735,7 +735,7 @@ const static Tcl_MethodType ResultSetNextresultsMethodType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType ResultSetNextrowMethodType = {
+static const Tcl_MethodType ResultSetNextrowMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "nextrow",                 /* name */
@@ -743,7 +743,7 @@ const static Tcl_MethodType ResultSetNextrowMethodType = {
     NULL,                      /* deleteProc */
     NULL                       /* cloneProc */
 };
-const static Tcl_MethodType ResultSetRowcountMethodType = {
+static const Tcl_MethodType ResultSetRowcountMethodType = {
     TCL_OO_METHOD_VERSION_CURRENT,
                                /* version */
     "rowcount",                        /* name */
@@ -753,7 +753,7 @@ const static Tcl_MethodType ResultSetRowcountMethodType = {
 };
 
 
-const static Tcl_MethodType* ResultSetMethods[] = {
+static const Tcl_MethodType* ResultSetMethods[] = {
     &ResultSetColumnsMethodType,
     &ResultSetNextresultsMethodType,
     &ResultSetRowcountMethodType,
@@ -782,9 +782,9 @@ static void
 DStringAppendWChars(
     Tcl_DString* ds,           /* Output string */
     SQLWCHAR* ws,              /* Input string */
-    int len                    /* Length of the input string in characters */
+    size_t len                 /* Length of the input string in characters */
 ) {
-    int i;
+    size_t i;
     char buf[4] = "";
 
     if (sizeofSQLWCHAR == sizeof(unsigned short)) {
@@ -792,7 +792,7 @@ DStringAppendWChars(
 
        for (i = 0; i < len; ++i) {
            unsigned int ch;
-           int bytes;
+           size_t bytes;
 
            ch = ptr16[i];
            bytes = Tcl_UniCharToUtf(ch, buf);
@@ -803,7 +803,7 @@ DStringAppendWChars(
 
        for (i = 0; i < len; ++i) {
            unsigned int ch;
-           int bytes;
+           size_t bytes;
 
            ch = ptr32[i];
            if (ch > 0x10ffff) {
@@ -836,11 +836,11 @@ DStringAppendWChars(
 static SQLWCHAR*
 GetWCharStringFromObj(
     Tcl_Obj* obj,              /* Tcl object whose string rep is desired */
-    int* lengthPtr             /* Length of the string */
+    size_t* lengthPtr          /* Length of the string */
 ) {
-    int len;                   /* Length of the input string in bytes */
-    char* bytes = Tcl_GetStringFromObj(obj, &len);
+    char* bytes = Tcl_GetString(obj);
                                /* UTF-8 representation of the input string */
+    size_t len = obj->length;  /* Length of the input string in bytes */
     char* end = bytes + len;   /* End of UTF-8 representation */
     SQLWCHAR* retval;          /* Buffer to hold the converted string */
     SQLWCHAR* wcPtr;
@@ -866,12 +866,10 @@ GetWCharStringFromObj(
                ch = *bytes++ & 0x00ff;
            }
            uch = ch;
-#if TCL_UTF_MAX > 4
-           if (uch > 0xffff) {
+           if ((sizeof(Tcl_UniChar) > 2) && (uch > 0xffff)) {
                *ptr16++ = (((uch - 0x10000) >> 10) & 0x3ff) | 0xd800;
                uch = ((uch - 0x10000) & 0x3ff) | 0xdc00;
            }
-#endif
            if (uch > 0x7f) {
                shrink = 1;
            }
@@ -892,8 +890,7 @@ GetWCharStringFromObj(
                ch = *bytes++ & 0x00ff;
            }
            uch = ch;
-#if TCL_UTF_MAX <= 4
-           if ((uch & 0xfc00) == 0xd800) {
+           if ((sizeof(Tcl_UniChar) == 2) && ((uch & 0xfc00) == 0xd800)) {
                if (Tcl_UtfCharComplete(bytes, end - bytes)) {
                    len = Tcl_UtfToUniChar(bytes, &ch);
                    if ((ch & 0xfc00) == 0xdc00) {
@@ -902,7 +899,6 @@ GetWCharStringFromObj(
                    }
                }
            }
-#endif
            if (uch > 0x7f) {
                shrink = 1;
            }
@@ -1287,7 +1283,7 @@ static void
 DismissHEnv(void)
 {
     Tcl_MutexLock(&hEnvMutex);
-    if (--hEnvRefCount == 0) {
+    if (hEnvRefCount-- <= 1) {
        SQLFreeHandle(SQL_HANDLE_ENV, hEnv);
        hEnv = SQL_NULL_HANDLE;
        if (odbcInstLoadHandle != NULL) {
@@ -1560,7 +1556,7 @@ ConfigureConnection(
 
     /* Configuration options */
 
-    const static char* options[] = {
+    static const char* options[] = {
        "-encoding",
        "-isolation",
        "-parent",
@@ -1936,7 +1932,7 @@ ConnectionConstructor(
     HWND hParentWindow = NULL; /* Windows handle of the main window */
     SQLWCHAR* connectionStringReq;
                                /* Connection string requested by the caller */
-    int connectionStringReqLen;
+    size_t connectionStringReqLen;
                                /* Length of the requested connection string */
     SQLWCHAR connectionString[1025*2];
                                /* Connection string actually used */
@@ -2045,7 +2041,7 @@ ConnectionConstructor(
 
 static int
 ConnectionBeginTransactionMethod(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -2055,6 +2051,7 @@ ConnectionBeginTransactionMethod(
                                /* The current connection object */
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2112,7 +2109,7 @@ ConnectionBeginTransactionMethod(
 
 static int
 ConnectionConfigureMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -2123,6 +2120,7 @@ ConnectionConfigureMethod(
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2225,7 +2223,7 @@ ConnectionEndXcnMethod(
 
 static int
 ConnectionHasBigintMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -2237,6 +2235,7 @@ ConnectionHasBigintMethod(
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
     int flag;
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2277,7 +2276,7 @@ ConnectionHasBigintMethod(
 
 static int
 ConnectionHasWvarcharMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -2289,6 +2288,7 @@ ConnectionHasWvarcharMethod(
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
     int flag;
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2380,10 +2380,13 @@ DeleteCmd (
 
 static int
 CloneCmd(
-    Tcl_Interp* interp,                /* Tcl interpreter */
+    Tcl_Interp* dummy,         /* Tcl interpreter */
     ClientData oldClientData,  /* Environment handle to be discarded */
     ClientData* newClientData  /* New environment handle to be used */
 ) {
+    (void)dummy;
+    (void)oldClientData;
+
     *newClientData = GetHEnv(NULL);
     return TCL_OK;
 }
@@ -2455,6 +2458,9 @@ CloneConnection(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("ODBC connections are not clonable", -1));
     return TCL_ERROR;
@@ -2521,13 +2527,12 @@ NewStatement(
 
 static int
 StatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current statement object */
     int skip = Tcl_ObjectContextSkippedArgs(context);
@@ -2541,10 +2546,11 @@ StatementConstructor(
     Tcl_Obj** tokenv;          /* Exploded tokens from the list */
     Tcl_Obj* nativeSql;                /* SQL statement mapped to ODBC form */
     char* tokenStr;            /* Token string */
-    int tokenLen;              /* Length of a token */
+    size_t tokenLen;           /* Length of a token */
     RETCODE rc;                        /* Return code from ODBC */
     SQLSMALLINT nParams;       /* Number of parameters in the ODBC statement */
     int i, j;
+    (void)dummy;
 
     /* Find the connection object, and get its data. */
 
@@ -2591,7 +2597,8 @@ StatementConstructor(
     nativeSql = Tcl_NewObj();
     Tcl_IncrRefCount(nativeSql);
     for (i = 0; i < tokenc; ++i) {
-       tokenStr = Tcl_GetStringFromObj(tokenv[i], &tokenLen);
+       tokenStr = Tcl_GetString(tokenv[i]);
+       tokenLen = tokenv[i]->length;
 
        switch (tokenStr[0]) {
        case '$':
@@ -2726,7 +2733,7 @@ StatementConstructor(
 
 static int
 StatementConnectionMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2741,6 +2748,9 @@ StatementConnectionMethod(
                                /* The command representing the object */
     Tcl_Obj* retval = Tcl_NewObj();
                                /* The command name */
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     sdata = (StatementData*) Tcl_ObjectGetMetadata(thisObject,
                                                   &statementDataType);
@@ -2770,7 +2780,7 @@ StatementConnectionMethod(
 
 static int
 StatementParamListMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2783,6 +2793,9 @@ StatementParamListMethod(
     int nParams;               /* Parameter count for the current statement */
     int i;                     /* Current parameter index */
     Tcl_Obj* retval;           /* Return value from this command */
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     sdata = (StatementData*) Tcl_ObjectGetMetadata(thisObject,
                                                   &statementDataType);
@@ -2826,7 +2839,7 @@ StatementParamListMethod(
 
 static int
 StatementParamtypeMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2850,6 +2863,8 @@ StatementParamtypeMethod(
                                /* ODBC type of the parameter */
     int precision = 0;         /* Length of the parameter */
     int scale = 0;             /* Precision of the parameter */
+    (void)dummy;
+
     sdata = (StatementData*) Tcl_ObjectGetMetadata(thisObject,
                                                   &statementDataType);
     /* Check parameters */
@@ -2954,7 +2969,7 @@ StatementParamtypeMethod(
 
 static int
 TablesStatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2970,6 +2985,7 @@ TablesStatementConstructor(
     ConnectionData* cdata;     /* The connection object's data */
     StatementData* sdata;      /* The statement's object data */
     RETCODE rc;                        /* Return code from ODBC */
+    (void)dummy;
 
     /* Find the connection object, and get its data. */
 
@@ -3054,7 +3070,7 @@ TablesStatementConstructor(
 
 static int
 ColumnsStatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3070,6 +3086,7 @@ ColumnsStatementConstructor(
     ConnectionData* cdata;     /* The connection object's data */
     StatementData* sdata;      /* The statement's object data */
     RETCODE rc;                        /* Return code from ODBC */
+    (void)dummy;
 
 
     /* Check param count */
@@ -3157,7 +3174,7 @@ ColumnsStatementConstructor(
 
 static int
 PrimarykeysStatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3173,6 +3190,7 @@ PrimarykeysStatementConstructor(
     ConnectionData* cdata;     /* The connection object's data */
     StatementData* sdata;      /* The statement's object data */
     RETCODE rc;                        /* Return code from ODBC */
+    (void)dummy;
 
 
     /* Check param count */
@@ -3259,7 +3277,7 @@ PrimarykeysStatementConstructor(
 
 static int
 ForeignkeysStatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3275,8 +3293,7 @@ ForeignkeysStatementConstructor(
     ConnectionData* cdata;     /* The connection object's data */
     StatementData* sdata;      /* The statement's object data */
     RETCODE rc;                        /* Return code from ODBC */
-
-    const static char* options[] = {   /* Option table */
+    static const char* options[] = {   /* Option table */
        "-foreign",
        "-primary",
        NULL
@@ -3294,6 +3311,7 @@ ForeignkeysStatementConstructor(
                                /* Flags for whether given -keywords have been
                                 * seen. */
     Tcl_Obj* resultObj;                /* Interpreter result */
+    (void)dummy;
 
     /* Check param count */
 
@@ -3401,7 +3419,7 @@ ForeignkeysStatementConstructor(
 
 static int
 TypesStatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3418,6 +3436,7 @@ TypesStatementConstructor(
     StatementData* sdata;      /* The statement's object data */
     RETCODE rc;                        /* Return code from ODBC */
     int typeNum;               /* Data type number */
+    (void)dummy;
 
     /* Parse args */
 
@@ -3547,6 +3566,9 @@ CloneStatement(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("ODBC statements are not clonable", -1));
     return TCL_ERROR;
@@ -3577,7 +3599,7 @@ CloneStatement(
 
 static int
 ResultSetConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3602,7 +3624,7 @@ ResultSetConstructor(
     const char* paramName;     /* Name of a substituted parameter */
     Tcl_Obj* paramValObj;      /* Value of a substituted parameter */
     const char* paramVal;      /* Value of a substituted parameter */
-    int paramLen;              /* String length of the parameter value */
+    size_t paramLen;           /* String length of the parameter value */
     Tcl_DString paramExternal; /* Substituted parameter, converted to
                                 * system encoding */
     int paramExternalLen;      /* Length of the substituted parameter
@@ -3611,6 +3633,7 @@ ResultSetConstructor(
     unsigned char* byteArrayPtr; /* Pointer to a BINARY or VARBINARY
                                 * parameter, expressed as a byte array.*/
     int i;
+    (void)dummy;
 
     /* Check parameter count */
 
@@ -3849,7 +3872,8 @@ ResultSetConstructor(
                     * encoding and store in rdata->bindStrings[nBound].
                     */
                    dataType = SQL_C_CHAR;
-                   paramVal = Tcl_GetStringFromObj(paramValObj, &paramLen);
+                   paramVal = Tcl_GetString(paramValObj);
+                   paramLen = paramValObj->length;
                    Tcl_DStringInit(&paramExternal);
                    Tcl_UtfToExternalDString(NULL, paramVal, paramLen,
                                             &paramExternal);
@@ -3965,17 +3989,17 @@ ResultSetConstructor(
 
 static int
 ResultSetColumnsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current result set object */
     ResultSetData* rdata = (ResultSetData*)
        Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -4019,7 +4043,7 @@ ResultSetColumnsMethod(
 
 static int
 ResultSetNextresultsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -4039,6 +4063,9 @@ ResultSetNextresultsMethod(
     Tcl_Obj** literals = pidata->literals;
                                /* Literal pool */
     SQLRETURN rc;              /* Return code from ODBC operations */
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     /*
      * Once we are advancing the results, any data that we think we know
@@ -4506,18 +4533,18 @@ GetCell(
 
 static int
 ResultSetRowcountMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-
     Tcl_Object thisObject = Tcl_ObjectContextObject(context);
                                /* The current result set object */
     ResultSetData* rdata = (ResultSetData*)
        Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
                                /* Data pertaining to the current result set */
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -4602,6 +4629,9 @@ CloneResultSet(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("ODBC result sets are not clonable", -1));
     return TCL_ERROR;
@@ -4669,7 +4699,7 @@ DatasourcesObjCmd(
     PerInterpData* pidata = (PerInterpData*) clientData;
     SQLSMALLINT initDirection = SQL_FETCH_FIRST;
     SQLSMALLINT direction;
-    const static struct flag {
+    static const struct flag {
        const char* name;
        SQLSMALLINT value;
     } flags[] = {
@@ -4973,12 +5003,12 @@ DriversObjCmd(
 
 static int
 DatasourceObjCmdW(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-    const static struct flag {
+    static const struct flag {
        const char* name;
        WORD value;
     } flags[] = {
@@ -4991,14 +5021,13 @@ DatasourceObjCmdW(
        { NULL,                 0 }
     };
     int flagIndex;             /* Index of the subcommand */
-
     WCHAR* driverName;         /* Name of the ODBC driver */
     WCHAR* attributes;         /* NULL-delimited attribute values */
     char errorMessage[SQL_MAX_MESSAGE_LENGTH+1];
                                /* Error message from ODBC operations */
-    int driverNameLen;         /* Length of the driver name */
+    size_t driverNameLen;              /* Length of the driver name */
     Tcl_Obj* attrObj;          /* NULL-delimited attribute values */
-    int attrLen;               /* Length of the attribute values */
+    size_t attrLen;            /* Length of the attribute values */
     const char* sep;           /* Separator for attribute values */
     DWORD errorCode;           /* Error code */
     WORD errorMessageLen;      /* Length of the returned error message */
@@ -5011,6 +5040,7 @@ DatasourceObjCmdW(
     BOOL ok;
     int status = TCL_OK;
     int finished = 0;
+    (void)dummy;
 
     /* Check args */
 
@@ -5152,12 +5182,12 @@ DatasourceObjCmdW(
 
 static int
 DatasourceObjCmdA(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     int objc,                  /* Parameter count */
     Tcl_Obj *const objv[]      /* Parameter vector */
 ) {
-    const static struct flag {
+    static const struct flag {
        const char* name;
        WORD value;
     } flags[] = {
@@ -5180,9 +5210,9 @@ DatasourceObjCmdA(
                                /* Error message from ODBC operations */
     Tcl_DString errorMessageDS;        /* Error message in UTF-8 */
     char* p;
-    int driverNameLen;         /* Length of the driver name */
+    size_t driverNameLen;              /* Length of the driver name */
     Tcl_Obj* attrObj;          /* NULL-delimited attribute values */
-    int attrLen;               /* Length of the attribute values */
+    size_t attrLen;            /* Length of the attribute values */
     const char* sep;           /* Separator for attribute values */
     DWORD errorCode;           /* Error code */
     WORD errorMessageLen;      /* Length of the returned error message */
@@ -5193,6 +5223,7 @@ DatasourceObjCmdA(
     BOOL ok;
     int status = TCL_OK;
     int finished = 0;
+    (void)dummy;
 
     /* Check args */
 
@@ -5209,7 +5240,8 @@ DatasourceObjCmdA(
     /* Convert driver name to the appropriate encoding */
 
     Tcl_DStringInit(&driverNameDS);
-    p = Tcl_GetStringFromObj(objv[2], &driverNameLen);
+    p = Tcl_GetString(objv[2]);
+    driverNameLen = objv[2]->length;
     Tcl_UtfToExternalDString(NULL, p, driverNameLen, &driverNameDS);
     driverName = Tcl_DStringValue(&driverNameDS);
     driverNameLen = Tcl_DStringLength(&driverNameDS);
@@ -5229,7 +5261,8 @@ DatasourceObjCmdA(
     }
     Tcl_AppendToObj(attrObj, "\xc0\x80", 2);
     Tcl_DStringInit(&attributesDS);
-    p = Tcl_GetStringFromObj(attrObj, &attrLen);
+    p = Tcl_GetString(attrObj);
+    attrLen = attrObj->length;
     Tcl_UtfToExternalDString(NULL, p, attrLen, &attributesDS);
     attributes = Tcl_DStringValue(&attributesDS);
     attrLen = Tcl_DStringLength(&attributesDS);
similarity index 81%
rename from pkgs/tdbcodbc1.1.1/tclconfig/README.txt
rename to pkgs/tdbcodbc1.1.2/tclconfig/README.txt
index 59b5a3e..715cb9d 100644 (file)
@@ -3,10 +3,10 @@ Architecture (TEA) extension.  For more information on TEA see:
 
        http://www.tcl.tk/doc/tea/
 
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
 
-       http://tcl.sourceforge.net/
+       https://core.tcl-lang.org/tclconfig
 
 This package is a freely available open source package.  You can do
 virtually anything you like with it, such as modifying it, redistributing
diff --git a/pkgs/tdbcodbc1.1.2/tclconfig/install-sh b/pkgs/tdbcodbc1.1.2/tclconfig/install-sh
new file mode 100644 (file)
index 0000000..21b733a
--- /dev/null
@@ -0,0 +1,518 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2020-07-26.22; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# 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.
+
+tab='  '
+nl='
+'
+IFS=" $tab$nl"
+
+# Set DOITPROG to "echo" to test this script.
+
+doit=${DOITPROG-}
+doit_exec=${doit:-exec}
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+is_target_a_directory=possibly
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+        shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
+
+    -o) chowncmd="$chownprog $2"
+        shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -S) stripcmd="$stripprog $2"
+        shift;;
+
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
+
+    -T) is_target_a_directory=never;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --) shift
+        break;;
+
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename.
+    if test -d "$dst"; then
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
+      fi
+      dstdir=$dst
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
+      dstdir_status=0
+    else
+      dstdir=`dirname "$dst"`
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
+       else
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
+       fi
+       trap '' 0;;
+    esac
+
+    if
+      $posix_mkdir && (
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
+      esac
+
+      oIFS=$IFS
+      IFS=/
+      set -f
+      set fnord $dstdir
+      shift
+      set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # 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 $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       set +f &&
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC0"
+# time-stamp-end: "; # UTC"
+# End:
\ No newline at end of file
diff --git a/pkgs/tdbcodbc1.1.2/tclconfig/tcl.m4 b/pkgs/tdbcodbc1.1.2/tclconfig/tcl.m4
new file mode 100644 (file)
index 0000000..8d24e7f
--- /dev/null
@@ -0,0 +1,4056 @@
+# tcl.m4 --
+#
+#      This file provides a set of autoconf macros to help TEA-enable
+#      a Tcl extension.
+#
+# Copyright (c) 1999-2000 Ajuba Solutions.
+# Copyright (c) 2002-2005 ActiveState Corporation.
+#
+# See the file "license.terms" for information on usage and redistribution
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+AC_PREREQ(2.57)
+
+# Possible values for key variables defined:
+#
+# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
+# TEA_PLATFORM        - windows unix
+# TEA_TK_EXTENSION    - True if this is a Tk extension
+#
+
+#------------------------------------------------------------------------
+# TEA_PATH_TCLCONFIG --
+#
+#      Locate the tclConfig.sh file and perform a sanity check on
+#      the Tcl compile flags
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tcl=...
+#
+#      Defines the following vars:
+#              TCL_BIN_DIR     Full path to the directory containing
+#                              the tclConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TCLCONFIG], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+    #
+    # Ok, lets find the tcl configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tcl
+    #
+
+    if test x"${no_tcl}" = x ; then
+       # we reset no_tcl in case something fails here
+       no_tcl=true
+       AC_ARG_WITH(tcl,
+           AS_HELP_STRING([--with-tcl],
+               [directory containing tcl configuration (tclConfig.sh)]),
+           [with_tclconfig="${withval}"])
+       AC_MSG_CHECKING([for Tcl configuration])
+       AC_CACHE_VAL(ac_cv_c_tclconfig,[
+
+           # First check to see if --with-tcl was specified.
+           if test x"${with_tclconfig}" != x ; then
+               case "${with_tclconfig}" in
+                   */tclConfig.sh )
+                       if test -f "${with_tclconfig}"; then
+                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
+                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tclconfig}/tclConfig.sh" ; then
+                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tcl installation
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ../tcl \
+                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tcl \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tcl \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tcl \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tclconfig}" = x ; then
+           TCL_BIN_DIR="# no Tcl configs found"
+           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
+       else
+           no_tcl=
+           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
+           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_TKCONFIG --
+#
+#      Locate the tkConfig.sh file
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tk=...
+#
+#      Defines the following vars:
+#              TK_BIN_DIR      Full path to the directory containing
+#                              the tkConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TKCONFIG], [
+    #
+    # Ok, lets find the tk configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tk
+    #
+
+    if test x"${no_tk}" = x ; then
+       # we reset no_tk in case something fails here
+       no_tk=true
+       AC_ARG_WITH(tk,
+           AS_HELP_STRING([--with-tk],
+               [directory containing tk configuration (tkConfig.sh)]),
+           [with_tkconfig="${withval}"])
+       AC_MSG_CHECKING([for Tk configuration])
+       AC_CACHE_VAL(ac_cv_c_tkconfig,[
+
+           # First check to see if --with-tkconfig was specified.
+           if test x"${with_tkconfig}" != x ; then
+               case "${with_tkconfig}" in
+                   */tkConfig.sh )
+                       if test -f "${with_tkconfig}"; then
+                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
+                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tkconfig}/tkConfig.sh" ; then
+                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tk library
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ../tk \
+                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tk \
+                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tk \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tk \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tkconfig}" = x ; then
+           TK_BIN_DIR="# no Tk configs found"
+           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
+       else
+           no_tk=
+           TK_BIN_DIR="${ac_cv_c_tkconfig}"
+           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TCLCONFIG --
+#
+#      Load the tclConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TCL_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_BIN_DIR
+#              TCL_SRC_DIR
+#              TCL_LIB_FILE
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TCLCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
+
+    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TCL_BIN_DIR}/tclConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
+    fi
+
+    # If the TCL_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TCL_LIB_SPEC will be set to the value
+    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
+    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
+        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
+        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tcl was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tcl.framework installed in an arbitrary location.
+       case ${TCL_DEFS} in
+           *TCL_FRAMEWORK*)
+               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
+                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
+                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
+                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
+                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
+                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    AC_SUBST(TCL_VERSION)
+    AC_SUBST(TCL_PATCH_LEVEL)
+    AC_SUBST(TCL_BIN_DIR)
+    AC_SUBST(TCL_SRC_DIR)
+
+    AC_SUBST(TCL_LIB_FILE)
+    AC_SUBST(TCL_LIB_FLAG)
+    AC_SUBST(TCL_LIB_SPEC)
+
+    AC_SUBST(TCL_STUB_LIB_FILE)
+    AC_SUBST(TCL_STUB_LIB_FLAG)
+    AC_SUBST(TCL_STUB_LIB_SPEC)
+
+    AC_MSG_CHECKING([platform])
+    hold_cc=$CC; CC="$TCL_CC"
+    AC_TRY_COMPILE(,[
+           #ifdef _WIN32
+               #error win32
+           #endif
+       ], [
+           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
+           TEA_PLATFORM="${TEA_PLATFORM-unix}"
+           CYGPATH=echo
+       ], [
+           TEA_PLATFORM="windows"
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
+    )
+    CC=$hold_cc
+    AC_MSG_RESULT($TEA_PLATFORM)
+
+    # The BUILD_$pkg is to define the correct extern storage class
+    # handling when making this package
+    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
+           [Building extension source?])
+    # Do this here as we have fully defined TEA_PLATFORM now
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       EXEEXT=".exe"
+       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
+    fi
+
+    # TEA specific:
+    AC_SUBST(CLEANFILES)
+    AC_SUBST(TCL_LIBS)
+    AC_SUBST(TCL_DEFS)
+    AC_SUBST(TCL_EXTRA_CFLAGS)
+    AC_SUBST(TCL_LD_FLAGS)
+    AC_SUBST(TCL_SHLIB_LD_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TKCONFIG --
+#
+#      Load the tkConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TK_BIN_DIR
+#
+# Results:
+#
+#      Sets the following vars that should be in tkConfig.sh:
+#              TK_BIN_DIR
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TKCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
+
+    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TK_BIN_DIR}/tkConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
+    fi
+
+    # If the TK_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TK_LIB_SPEC will be set to the value
+    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
+    # instead of TK_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
+        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
+        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tk was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tk.framework installed in an arbitrary location.
+       case ${TK_DEFS} in
+           *TK_FRAMEWORK*)
+               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
+                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
+                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
+                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
+                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
+                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    # TEA specific: Ensure windowingsystem is defined
+    if test "${TEA_PLATFORM}" = "unix" ; then
+       case ${TK_DEFS} in
+           *MAC_OSX_TK*)
+               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
+               TEA_WINDOWINGSYSTEM="aqua"
+               ;;
+           *)
+               TEA_WINDOWINGSYSTEM="x11"
+               ;;
+       esac
+    elif test "${TEA_PLATFORM}" = "windows" ; then
+       TEA_WINDOWINGSYSTEM="win32"
+    fi
+
+    AC_SUBST(TK_VERSION)
+    AC_SUBST(TK_BIN_DIR)
+    AC_SUBST(TK_SRC_DIR)
+
+    AC_SUBST(TK_LIB_FILE)
+    AC_SUBST(TK_LIB_FLAG)
+    AC_SUBST(TK_LIB_SPEC)
+
+    AC_SUBST(TK_STUB_LIB_FILE)
+    AC_SUBST(TK_STUB_LIB_FLAG)
+    AC_SUBST(TK_STUB_LIB_SPEC)
+
+    # TEA specific:
+    AC_SUBST(TK_LIBS)
+    AC_SUBST(TK_XINCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_TCLSH
+#      Determine the fully qualified path name of the tclsh executable
+#      in the Tcl build directory or the tclsh installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the tclsh executable even if tclsh has not yet been
+#      built in the build directory. The tclsh found is always
+#      associated with a tclConfig.sh file. This tclsh should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCLSH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_TCLSH], [
+    AC_MSG_CHECKING([for tclsh])
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        # tclConfig.sh is in Tcl build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
+        fi
+    else
+        # tclConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+        else
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${TCLSH_PROG}" ; then
+                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
+    fi
+    AC_MSG_RESULT([${TCLSH_PROG}])
+    AC_SUBST(TCLSH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_WISH
+#      Determine the fully qualified path name of the wish executable
+#      in the Tk build directory or the wish installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the wish executable even if wish has not yet been
+#      built in the build directory. The wish found is always
+#      associated with a tkConfig.sh file. This wish should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              WISH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_WISH], [
+    AC_MSG_CHECKING([for wish])
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        # tkConfig.sh is in Tk build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            WISH_PROG="${TK_BIN_DIR}/wish"
+        fi
+    else
+        # tkConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+        else
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${WISH_PROG}" ; then
+                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
+    fi
+    AC_MSG_RESULT([${WISH_PROG}])
+    AC_SUBST(WISH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SHARED --
+#
+#      Allows the building of shared libraries
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-shared=yes|no
+#              --enable-stubs=yes|no
+#
+#      Defines the following vars:
+#              STATIC_BUILD    Used for building import/export libraries
+#                              on Windows.
+#
+#      Sets the following vars:
+#              SHARED_BUILD    Value of 1 or 0
+#               STUBS_BUILD     Value if 1 or 0
+#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
+#                                AND TEA_WINDOWING_SYSTEM != ""
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ENABLE_SHARED], [
+    AC_MSG_CHECKING([how to build libraries])
+    AC_ARG_ENABLE(shared,
+       AS_HELP_STRING([--enable-shared],
+           [build and link with shared libraries (default: on)]),
+       [shared_ok=$enableval], [shared_ok=yes])
+
+    if test "${enable_shared+set}" = set; then
+       enableval="$enable_shared"
+       shared_ok=$enableval
+    else
+       shared_ok=yes
+    fi
+
+    AC_ARG_ENABLE(stubs,
+       AS_HELP_STRING([--enable-stubs],
+           [build and link with stub libraries. Always true for shared builds (default: on)]),
+       [stubs_ok=$enableval], [stubs_ok=yes])
+
+    if test "${enable_stubs+set}" = set; then
+       enableval="$enable_stubs"
+       stubs_ok=$enableval
+    else
+       stubs_ok=yes
+    fi
+
+    # Stubs are always enabled for shared builds
+    if test "$shared_ok" = "yes" ; then
+       AC_MSG_RESULT([shared])
+       SHARED_BUILD=1
+        STUBS_BUILD=1
+    else
+       AC_MSG_RESULT([static])
+       SHARED_BUILD=0
+       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
+        if test "$stubs_ok" = "yes" ; then
+          STUBS_BUILD=1
+        else
+          STUBS_BUILD=0
+        fi
+    fi
+    if test "${STUBS_BUILD}" = "1" ; then
+      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
+      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
+      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
+        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
+      fi
+    fi
+
+    AC_SUBST(SHARED_BUILD)
+    AC_SUBST(STUBS_BUILD)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_THREADS --
+#
+#      Specify if thread support should be enabled.  If "yes" is specified
+#      as an arg (optional), threads are enabled by default, "no" means
+#      threads are disabled.  "yes" is the default.
+#
+#      TCL_THREADS is checked so that if you are compiling an extension
+#      against a threaded core, your extension must be compiled threaded
+#      as well.
+#
+#      Note that it is legal to have a thread enabled extension run in a
+#      threaded or non-threaded Tcl core, but a non-threaded extension may
+#      only run in a non-threaded Tcl core.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-threads
+#
+#      Sets the following vars:
+#              THREADS_LIBS    Thread library(s)
+#
+#      Defines the following vars:
+#              TCL_THREADS
+#              _REENTRANT
+#              _THREAD_SAFE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_THREADS], [
+    AC_ARG_ENABLE(threads,
+       AS_HELP_STRING([--enable-threads],
+           [build with threads (default: on)]),
+       [tcl_ok=$enableval], [tcl_ok=yes])
+
+    if test "${enable_threads+set}" = set; then
+       enableval="$enable_threads"
+       tcl_ok=$enableval
+    else
+       tcl_ok=yes
+    fi
+
+    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
+       TCL_THREADS=1
+
+       if test "${TEA_PLATFORM}" != "windows" ; then
+           # We are always OK on Windows, so check what this platform wants:
+
+           # USE_THREAD_ALLOC tells us to try the special thread-based
+           # allocator that significantly reduces lock contention
+           AC_DEFINE(USE_THREAD_ALLOC, 1,
+               [Do we want to use the threaded memory allocator?])
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           if test "`uname -s`" = "SunOS" ; then
+               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+                       [Do we really want to follow the standard? Yes we do!])
+           fi
+           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
+           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
+           if test "$tcl_ok" = "no"; then
+               # Check a little harder for __pthread_mutex_init in the same
+               # library, as some systems hide it there until pthread.h is
+               # defined.  We could alternatively do an AC_TRY_COMPILE with
+               # pthread.h, but that will work with libpthread really doesn't
+               # exist, like AIX 4.2.  [Bug: 4359]
+               AC_CHECK_LIB(pthread, __pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+           fi
+
+           if test "$tcl_ok" = "yes"; then
+               # The space is needed
+               THREADS_LIBS=" -lpthread"
+           else
+               AC_CHECK_LIB(pthreads, pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+               if test "$tcl_ok" = "yes"; then
+                   # The space is needed
+                   THREADS_LIBS=" -lpthreads"
+               else
+                   AC_CHECK_LIB(c, pthread_mutex_init,
+                       tcl_ok=yes, tcl_ok=no)
+                   if test "$tcl_ok" = "no"; then
+                       AC_CHECK_LIB(c_r, pthread_mutex_init,
+                           tcl_ok=yes, tcl_ok=no)
+                       if test "$tcl_ok" = "yes"; then
+                           # The space is needed
+                           THREADS_LIBS=" -pthread"
+                       else
+                           TCL_THREADS=0
+                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
+                       fi
+                   fi
+               fi
+           fi
+       fi
+    else
+       TCL_THREADS=0
+    fi
+    # Do checking message here to not mess up interleaved configure output
+    AC_MSG_CHECKING([for building with threads])
+    if test "${TCL_THREADS}" = 1; then
+       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
+       AC_MSG_RESULT([yes (default)])
+    else
+       AC_MSG_RESULT([no])
+    fi
+    # TCL_THREADS sanity checking.  See if our request for building with
+    # threads is the same as the way Tcl was built.  If not, warn the user.
+    case ${TCL_DEFS} in
+       *THREADS=1*)
+           if test "${TCL_THREADS}" = "0"; then
+               AC_MSG_WARN([
+    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
+    that IS thread-enabled.  It is recommended to use --enable-threads.])
+           fi
+           ;;
+    esac
+    AC_SUBST(TCL_THREADS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SYMBOLS --
+#
+#      Specify if debugging symbols should be used.
+#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
+#
+# Arguments:
+#      none
+#
+#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
+#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
+#      Requires the following vars to be set in the Makefile:
+#              CFLAGS_DEFAULT
+#              LDFLAGS_DEFAULT
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-symbols
+#
+#      Defines the following vars:
+#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
+#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
+#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
+#                              Sets to $(LDFLAGS_OPTIMIZE) if false
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_SYMBOLS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_CONFIG_CFLAGS])
+    AC_MSG_CHECKING([for build with symbols])
+    AC_ARG_ENABLE(symbols,
+       AS_HELP_STRING([--enable-symbols],
+           [build with debugging symbols (default: off)]),
+       [tcl_ok=$enableval], [tcl_ok=no])
+    if test "$tcl_ok" = "no"; then
+       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
+       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
+       AC_MSG_RESULT([no])
+    else
+       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
+       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
+       if test "$tcl_ok" = "yes"; then
+           AC_MSG_RESULT([yes (standard debugging)])
+       fi
+    fi
+    AC_SUBST(CFLAGS_DEFAULT)
+    AC_SUBST(LDFLAGS_DEFAULT)
+
+    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
+       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
+    fi
+
+    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
+       if test "$tcl_ok" = "all"; then
+           AC_MSG_RESULT([enabled symbols mem debugging])
+       else
+           AC_MSG_RESULT([enabled $tcl_ok debugging])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_LANGINFO --
+#
+#      Allows use of modern nl_langinfo check for better l10n.
+#      This is only relevant for Unix.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-langinfo=yes|no (default is yes)
+#
+#      Defines the following vars:
+#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_LANGINFO], [
+    AC_ARG_ENABLE(langinfo,
+       AS_HELP_STRING([--enable-langinfo],
+           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
+       [langinfo_ok=$enableval], [langinfo_ok=yes])
+
+    HAVE_LANGINFO=0
+    if test "$langinfo_ok" = "yes"; then
+       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
+    fi
+    AC_MSG_CHECKING([whether to use nl_langinfo])
+    if test "$langinfo_ok" = "yes"; then
+       AC_CACHE_VAL(tcl_cv_langinfo_h, [
+           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
+                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
+       AC_MSG_RESULT([$tcl_cv_langinfo_h])
+       if test $tcl_cv_langinfo_h = yes; then
+           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
+       fi
+    else
+       AC_MSG_RESULT([$langinfo_ok])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_SYSTEM
+#
+#      Determine what the system is (some things cannot be easily checked
+#      on a feature-driven basis, alas). This can usually be done via the
+#      "uname" command.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Defines the following var:
+#
+#      system -        System/platform/version identification code.
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_SYSTEM], [
+    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
+       # TEA specific:
+       if test "${TEA_PLATFORM}" = "windows" ; then
+           tcl_cv_sys_version=windows
+       else
+           tcl_cv_sys_version=`uname -s`-`uname -r`
+           if test "$?" -ne 0 ; then
+               AC_MSG_WARN([can't find uname command])
+               tcl_cv_sys_version=unknown
+           else
+               if test "`uname -s`" = "AIX" ; then
+                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
+               fi
+               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
+                   tcl_cv_sys_version=NetBSD-Debian
+               fi
+           fi
+       fi
+    ])
+    system=$tcl_cv_sys_version
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_CFLAGS
+#
+#      Try to determine the proper flags to pass to the compiler
+#      for building shared libraries and other such nonsense.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substitutes the following vars:
+#
+#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
+#       LDFLAGS -      Flags to pass to the compiler when linking object
+#                       files into an executable application binary such
+#                       as tclsh.
+#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
+#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
+#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile.
+#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
+#                       of a shared library (may request position-independent
+#                       code, among other things).
+#       SHLIB_LD -      Base command to use for combining object files
+#                       into a shared library.
+#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
+#                       creating shared libraries.  This symbol typically
+#                       goes at the end of the "ld" commands that build
+#                       shared libraries. The value of the symbol defaults to
+#                       "${LIBS}" if all of the dependent libraries should
+#                       be specified when creating a shared library.  If
+#                       dependent libraries should not be specified (as on
+#                       SunOS 4.x, where they cause the link to fail, or in
+#                       general if Tcl and Tk aren't themselves shared
+#                       libraries), then this symbol has an empty string
+#                       as its value.
+#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
+#                       extensions.  An empty string means we don't know how
+#                       to use shared libraries on this platform.
+#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
+#                       in a static or shared library name, using the $PACKAGE_VERSION variable
+#                       to put the version in the right place.  This is used
+#                       by platforms that need non-standard library names.
+#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
+#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
+#                       on AIX, since a shared library needs to have
+#                       a .a extension whereas shared objects for loadable
+#                       extensions have a .so extension.  Defaults to
+#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
+#      CFLAGS_DEBUG -
+#                      Flags used when running the compiler in debug mode
+#      CFLAGS_OPTIMIZE -
+#                      Flags used when running the compiler in optimize mode
+#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_CFLAGS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+
+    # Step 0.a: Enable 64 bit support?
+
+    AC_MSG_CHECKING([if 64bit support is requested])
+    AC_ARG_ENABLE(64bit,
+       AS_HELP_STRING([--enable-64bit],
+           [enable 64bit support (default: off)]),
+       [do64bit=$enableval], [do64bit=no])
+    AC_MSG_RESULT([$do64bit])
+
+    # Step 0.b: Enable Solaris 64 bit VIS support?
+
+    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
+    AC_ARG_ENABLE(64bit-vis,
+       AS_HELP_STRING([--enable-64bit-vis],
+           [enable 64bit Sparc VIS support (default: off)]),
+       [do64bitVIS=$enableval], [do64bitVIS=no])
+    AC_MSG_RESULT([$do64bitVIS])
+    # Force 64bit on with VIS
+    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
+
+    # Step 0.c: Check if visibility support is available. Do this here so
+    # that platform specific alternatives can be used below if this fails.
+
+    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
+       tcl_cv_cc_visibility_hidden, [
+       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
+       AC_TRY_LINK([
+           extern __attribute__((__visibility__("hidden"))) void f(void);
+           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
+           tcl_cv_cc_visibility_hidden=no)
+       CFLAGS=$hold_cflags])
+    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
+       AC_DEFINE(MODULE_SCOPE,
+           [extern __attribute__((__visibility__("hidden")))],
+           [Compiler support for module scope symbols])
+       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
+    ])
+
+    # Step 0.d: Disable -rpath support?
+
+    AC_MSG_CHECKING([if rpath support is requested])
+    AC_ARG_ENABLE(rpath,
+       AS_HELP_STRING([--disable-rpath],
+           [disable rpath support (default: on)]),
+       [doRpath=$enableval], [doRpath=yes])
+    AC_MSG_RESULT([$doRpath])
+
+    # Set the variable "system" to hold the name and version number
+    # for the system.
+
+    TEA_CONFIG_SYSTEM
+
+    # Require ranlib early so we can override it in special cases below.
+
+    AC_REQUIRE([AC_PROG_RANLIB])
+
+    # Set configuration options based on system name and version.
+    # This is similar to Tcl's unix/tcl.m4 except that we've added a
+    # "windows" case and removed some core-only vars.
+
+    do64bit_ok=no
+    # default to '{$LIBS}' and set to "" on per-platform necessary basis
+    SHLIB_LD_LIBS='${LIBS}'
+    # When ld needs options to work in 64-bit mode, put them in
+    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
+    # is disabled by the user. [Bug 1016796]
+    LDFLAGS_ARCH=""
+    UNSHARED_LIB_SUFFIX=""
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
+    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
+    TCL_LIB_VERSIONS_OK=ok
+    CFLAGS_DEBUG=-g
+    AS_IF([test "$GCC" = yes], [
+       CFLAGS_OPTIMIZE=-O2
+       CFLAGS_WARNING="-Wall"
+    ], [
+       CFLAGS_OPTIMIZE=-O
+       CFLAGS_WARNING=""
+    ])
+    AC_CHECK_TOOL(AR, ar)
+    STLIB_LD='${AR} cr'
+    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
+    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
+    case $system in
+       # TEA specific:
+       windows)
+           MACHINE="X86"
+           if test "$do64bit" != "no" ; then
+               case "$do64bit" in
+                   amd64|x64|yes)
+                       MACHINE="AMD64" ; # default to AMD64 64-bit build
+                       ;;
+                   ia64)
+                       MACHINE="IA64"
+                       ;;
+               esac
+           fi
+
+           if test "$GCC" != "yes" ; then
+               if test "${SHARED_BUILD}" = "0" ; then
+                   runtime=-MT
+               else
+                   runtime=-MD
+               fi
+               case "x`echo \${VisualStudioVersion}`" in
+                   x1[[4-9]]*)
+                       lflags="${lflags} -nodefaultlib:libucrt.lib"
+                       TEA_ADD_LIBS([ucrt.lib])
+                   ;;
+                   *)
+                   ;;
+               esac
+
+                if test "$do64bit" != "no" ; then
+                   CC="cl.exe"
+                   RC="rc.exe"
+                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
+                   LINKBIN="link.exe"
+                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+                   # Avoid 'unresolved external symbol __security_cookie'
+                   # errors, c.f. http://support.microsoft.com/?id=894573
+                   TEA_ADD_LIBS([bufferoverflowU.lib])
+               else
+                   RC="rc"
+                   lflags="${lflags} -nologo"
+                   LINKBIN="link"
+                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+               fi
+           fi
+
+           if test "$GCC" = "yes"; then
+               # mingw gcc mode
+               AC_CHECK_TOOL(RC, windres)
+               CFLAGS_DEBUG="-g"
+               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+               SHLIB_LD='${CC} -shared'
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
+               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
+
+               AC_CACHE_CHECK(for cross-compile version of gcc,
+                       ac_cv_cross,
+                       AC_TRY_COMPILE([
+                           #ifdef _WIN32
+                               #error cross-compiler
+                           #endif
+                       ], [],
+                       ac_cv_cross=yes,
+                       ac_cv_cross=no)
+                     )
+                     if test "$ac_cv_cross" = "yes"; then
+                       case "$do64bit" in
+                           amd64|x64|yes)
+                               CC="x86_64-w64-mingw32-${CC}"
+                               LD="x86_64-w64-mingw32-ld"
+                               AR="x86_64-w64-mingw32-ar"
+                               RANLIB="x86_64-w64-mingw32-ranlib"
+                               RC="x86_64-w64-mingw32-windres"
+                           ;;
+                           *)
+                               CC="i686-w64-mingw32-${CC}"
+                               LD="i686-w64-mingw32-ld"
+                               AR="i686-w64-mingw32-ar"
+                               RANLIB="i686-w64-mingw32-ranlib"
+                               RC="i686-w64-mingw32-windres"
+                           ;;
+                       esac
+               fi
+
+           else
+               SHLIB_LD="${LINKBIN} -dll ${lflags}"
+               # link -lib only works when -lib is the first arg
+               STLIB_LD="${LINKBIN} -lib ${lflags}"
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
+               PATHTYPE=-w
+               # For information on what debugtype is most useful, see:
+               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
+               # and also
+               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
+               # This essentially turns it all on.
+               LDFLAGS_DEBUG="-debug -debugtype:cv"
+               LDFLAGS_OPTIMIZE="-release"
+               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
+               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
+           fi
+
+           SHLIB_SUFFIX=".dll"
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
+
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       AIX-*)
+           AS_IF([test "$GCC" != "yes"], [
+               # AIX requires the _r compiler when gcc isn't being used
+               case "${CC}" in
+                   *_r|*_r\ *)
+                       # ok ...
+                       ;;
+                   *)
+                       # Make sure only first arg gets _r
+                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
+                       ;;
+               esac
+               AC_MSG_RESULT([Using $CC for compiling with threads])
+           ])
+           LIBS="$LIBS -lc"
+           SHLIB_CFLAGS=""
+           SHLIB_SUFFIX=".so"
+
+           LD_LIBRARY_PATH_VAR="LIBPATH"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS -q64"
+                   LDFLAGS_ARCH="-q64"
+                   RANLIB="${RANLIB} -X64"
+                   AR="${AR} -X64"
+                   SHLIB_LD_FLAGS="-b64"
+               ])
+           ])
+
+           AS_IF([test "`uname -m`" = ia64], [
+               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               AS_IF([test "$GCC" = yes], [
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               ], [
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
+               ])
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ], [
+               AS_IF([test "$GCC" = yes], [
+                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
+               ], [
+                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
+                   LDFLAGS="$LDFLAGS -brtl"
+               ])
+               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       BeOS*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} -nostart'
+           SHLIB_SUFFIX=".so"
+
+           #-----------------------------------------------------------
+           # Check for inet_ntoa in -lbind, for BeOS (which also needs
+           # -lsocket, even if the network functions are in -lnet which
+           # is always linked to, for compatibility.
+           #-----------------------------------------------------------
+           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
+           ;;
+       BSD/OS-2.1*|BSD/OS-3*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="shlicc -r"
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       BSD/OS-4.*)
+           SHLIB_CFLAGS="-export-dynamic -fPIC"
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       CYGWIN_*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".dll"
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
+           EXEEXT=".exe"
+           do64bit_ok=yes
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       dgux*)
+           SHLIB_CFLAGS="-K PIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       Haiku*)
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
+           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
+           ;;
+       HP-UX-*.11.*)
+           # Use updated header definitions where possible
+           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
+           # TEA specific: Needed by Tcl, but not most extensions
+           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
+           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
+
+           AS_IF([test "`uname -m`" = ia64], [
+               SHLIB_SUFFIX=".so"
+           ], [
+               SHLIB_SUFFIX=".sl"
+           ])
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ])
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               CFLAGS="$CFLAGS -z"
+           ])
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = "yes"], [
+               AS_IF([test "$GCC" = yes], [
+                   case `${CC} -dumpmachine` in
+                       hppa64*)
+                           # 64-bit gcc in use.  Fix flags for GNU ld.
+                           do64bit_ok=yes
+                           SHLIB_LD='${CC} -shared'
+                           AS_IF([test $doRpath = yes], [
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+                           ;;
+                       *)
+                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
+                           ;;
+                   esac
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS +DD64"
+                   LDFLAGS_ARCH="+DD64"
+               ])
+           ]) ;;
+       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
+           SHLIB_SUFFIX=".sl"
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               SHLIB_LD_LIBS=""
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ]) ;;
+       IRIX-5.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AC_LIBOBJ(mkstemp)
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           ;;
+       IRIX-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           AS_IF([test "$GCC" = yes], [
+               CFLAGS="$CFLAGS -mabi=n32"
+               LDFLAGS="$LDFLAGS -mabi=n32"
+           ], [
+               case $system in
+                   IRIX-6.3)
+                       # Use to build 6.2 compatible binaries on 6.3.
+                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
+                       ;;
+                   *)
+                       CFLAGS="$CFLAGS -n32"
+                       ;;
+               esac
+               LDFLAGS="$LDFLAGS -n32"
+           ])
+           ;;
+       IRIX64-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+
+           # Check to enable 64-bit flags for compiler/linker
+
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported by gcc])
+               ], [
+                   do64bit_ok=yes
+                   SHLIB_LD="ld -64 -shared -rdata_shared"
+                   CFLAGS="$CFLAGS -64"
+                   LDFLAGS_ARCH="-64"
+               ])
+           ])
+           ;;
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+
+           # TEA specific:
+           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
+           AS_IF([test $do64bit = yes], [
+               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
+                   hold_cflags=$CFLAGS
+                   CFLAGS="$CFLAGS -m64"
+                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
+                   CFLAGS=$hold_cflags])
+               AS_IF([test $tcl_cv_cc_m64 = yes], [
+                   CFLAGS="$CFLAGS -m64"
+                   do64bit_ok=yes
+               ])
+          ])
+
+           # The combo of gcc + glibc has a bug related to inlining of
+           # functions like strtod(). The -fno-builtin flag should address
+           # this problem but it does not work. The -fno-inline flag is kind
+           # of overkill but it works. Disable inlining only when one of the
+           # files in compat/*.c is being linked in.
+
+           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
+           ;;
+       Lynx*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           CFLAGS_OPTIMIZE=-02
+           SHLIB_LD='${CC} -shared'
+           LD_FLAGS="-Wl,--export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           ;;
+       OpenBSD-*)
+           arch=`arch -s`
+           case "$arch" in
+           alpha|sparc64)
+               SHLIB_CFLAGS="-fPIC"
+               ;;
+           *)
+               SHLIB_CFLAGS="-fpic"
+               ;;
+           esac
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
+           CFLAGS_OPTIMIZE="-O2"
+           # On OpenBSD:       Compile with -pthread
+           #           Don't link with -lpthread
+           LIBS=`echo $LIBS | sed s/-lpthread//`
+           CFLAGS="$CFLAGS -pthread"
+           # OpenBSD doesn't do version numbers with dots.
+           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       NetBSD-*)
+           # NetBSD has ELF and can use 'cc -shared' to build shared libs
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           # The -pthread needs to go in the CFLAGS, not LIBS
+           LIBS=`echo $LIBS | sed s/-pthread//`
+           CFLAGS="$CFLAGS -pthread"
+           LDFLAGS="$LDFLAGS -pthread"
+           ;;
+       Darwin-*)
+           CFLAGS_OPTIMIZE="-Os"
+           SHLIB_CFLAGS="-fno-common"
+           # To avoid discrepancies between what headers configure sees during
+           # preprocessing tests and compiling tests, move any -isysroot and
+           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
+           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
+           CFLAGS="`echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
+           AS_IF([test $do64bit = yes], [
+               case `arch` in
+                   ppc)
+                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
+                               tcl_cv_cc_arch_ppc64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
+                                   tcl_cv_cc_arch_ppc64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           do64bit_ok=yes
+                       ]);;
+                   i386)
+                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
+                               tcl_cv_cc_arch_x86_64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
+                                   tcl_cv_cc_arch_x86_64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           do64bit_ok=yes
+                       ]);;
+                   *)
+                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
+               esac
+           ], [
+               # Check for combined 32-bit and 64-bit fat build
+               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
+                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
+                   fat_32_64=yes])
+           ])
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
+           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_single_module = yes], [
+               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
+           ])
+           # TEA specific: link shlib with current and compatibility version flags
+           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
+           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
+           SHLIB_SUFFIX=".dylib"
+           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
+           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
+                   tcl_cv_ld_search_paths_first, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
+                       tcl_cv_ld_search_paths_first=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+           ])
+           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
+                   [Compiler support for module scope symbols])
+               tcl_cv_cc_visibility_hidden=yes
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
+           # TEA specific: for combined 32 & 64 bit fat builds of Tk
+           # extensions, verify that 64-bit build is possible.
+           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
+                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
+                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
+                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
+                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
+                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
+                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
+                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
+                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               # remove 64-bit arch flags from CFLAGS et al. if configuration
+               # does not support 64-bit.
+               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
+                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
+                   for v in CFLAGS CPPFLAGS LDFLAGS; do
+                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
+                   done])
+           ])
+           ;;
+       OS/390-*)
+           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
+           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
+               [Should OS/390 do the right thing with sockets?])
+           ;;
+       OSF1-V*)
+           # Digital OSF/1
+           SHLIB_CFLAGS=""
+           AS_IF([test "$SHARED_BUILD" = 1], [
+               SHLIB_LD='ld -shared -expect_unresolved "*"'
+           ], [
+               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
+           ])
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
+               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
+           # see pthread_intro(3) for pthread support on osf1, k.furukawa
+           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
+           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
+           LIBS=`echo $LIBS | sed s/-lpthreads//`
+           AS_IF([test "$GCC" = yes], [
+               LIBS="$LIBS -lpthread -lmach -lexc"
+           ], [
+               CFLAGS="$CFLAGS -pthread"
+               LDFLAGS="$LDFLAGS -pthread"
+           ])
+           ;;
+       QNX-6*)
+           # QNX RTP
+           # This may work for all QNX, but it was only reported for v6.
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD="ld -Bshareable -x"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SCO_SV-3.2*)
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_CFLAGS="-fPIC -melf"
+               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
+           ], [
+               SHLIB_CFLAGS="-Kpic -belf"
+               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
+           ])
+           SHLIB_LD="ld -G"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SunOS-5.[[0-6]])
+           # Careful to not let 5.10+ fall into this case
+
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       SunOS-5*)
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               arch=`isainfo`
+               AS_IF([test "$arch" = "sparcv9 sparc"], [
+                   AS_IF([test "$GCC" = yes], [
+                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
+                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
+                       ], [
+                           do64bit_ok=yes
+                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
+                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
+                           SHLIB_CFLAGS="-fPIC"
+                       ])
+                   ], [
+                       do64bit_ok=yes
+                       AS_IF([test "$do64bitVIS" = yes], [
+                           CFLAGS="$CFLAGS -xarch=v9a"
+                           LDFLAGS_ARCH="-xarch=v9a"
+                       ], [
+                           CFLAGS="$CFLAGS -xarch=v9"
+                           LDFLAGS_ARCH="-xarch=v9"
+                       ])
+                       # Solaris 64 uses this as well
+                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
+                   ])
+               ], [AS_IF([test "$arch" = "amd64 i386"], [
+                   AS_IF([test "$GCC" = yes], [
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               do64bit_ok=yes
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
+                       esac
+                   ], [
+                       do64bit_ok=yes
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               CFLAGS="$CFLAGS -xarch=amd64"
+                               LDFLAGS="$LDFLAGS -xarch=amd64";;
+                       esac
+                   ])
+               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
+           ])
+
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+               AS_IF([test "$do64bit_ok" = yes], [
+                   AS_IF([test "$arch" = "sparcv9 sparc"], [
+                       # We need to specify -static-libgcc or we need to
+                       # add the path to the sparv9 libgcc.
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
+                       # for finding sparcv9 libgcc, get the regular libgcc
+                       # path, remove so name and append 'sparcv9'
+                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
+                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
+                   ], [AS_IF([test "$arch" = "amd64 i386"], [
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
+                   ])])
+               ])
+           ], [
+               case $system in
+                   SunOS-5.[[1-9]][[0-9]]*)
+                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
+                   *)
+                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
+               esac
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ])
+           ;;
+       UNIX_SV* | UnixWare-5*)
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
+           # that don't grok the -Bexport option.  Test that it does.
+           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_Bexport = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+    esac
+
+    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
+       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
+    ])
+
+dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
+dnl # until the end of configure, as configure's compile and link tests use
+dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
+dnl # preprocessing tests use only CPPFLAGS.
+    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
+
+    # Add in the arch flags late to ensure it wasn't removed.
+    # Not necessary in TEA, but this is aligned with core
+    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
+
+    # If we're running gcc, then change the C flags for compiling shared
+    # libraries to the right flags for gcc, instead of those for the
+    # standard manufacturer compiler.
+
+    AS_IF([test "$GCC" = yes], [
+       case $system in
+           AIX-*) ;;
+           BSD/OS*) ;;
+           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
+           IRIX*) ;;
+           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
+           Darwin-*) ;;
+           SCO_SV-3.2*) ;;
+           windows) ;;
+           *) SHLIB_CFLAGS="-fPIC" ;;
+       esac])
+
+    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+       AC_DEFINE(MODULE_SCOPE, [extern],
+           [No Compiler support for module scope symbols])
+    ])
+
+    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
+    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
+
+    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
+       AC_CACHE_CHECK(for SEH support in compiler,
+           tcl_cv_seh,
+       AC_TRY_RUN([
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+
+           int main(int argc, char** argv) {
+               int a, b = 0;
+               __try {
+                   a = 666 / b;
+               }
+               __except (EXCEPTION_EXECUTE_HANDLER) {
+                   return 0;
+               }
+               return 1;
+           }
+       ],
+           tcl_cv_seh=yes,
+           tcl_cv_seh=no,
+           tcl_cv_seh=no)
+       )
+       if test "$tcl_cv_seh" = "no" ; then
+           AC_DEFINE(HAVE_NO_SEH, 1,
+                   [Defined when mingw does not support SEH])
+       fi
+
+       #
+       # Check to see if the excpt.h include file provided contains the
+       # definition for EXCEPTION_DISPOSITION; if not, which is the case
+       # with Cygwin's version as of 2002-04-10, define it to be int,
+       # sufficient for getting the current code to work.
+       #
+       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
+           tcl_cv_eh_disposition,
+           AC_TRY_COMPILE([
+#          define WIN32_LEAN_AND_MEAN
+#          include <windows.h>
+#          undef WIN32_LEAN_AND_MEAN
+           ],[
+               EXCEPTION_DISPOSITION x;
+           ],
+               tcl_cv_eh_disposition=yes,
+               tcl_cv_eh_disposition=no)
+       )
+       if test "$tcl_cv_eh_disposition" = "no" ; then
+       AC_DEFINE(EXCEPTION_DISPOSITION, int,
+               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
+       fi
+
+       # Check to see if winnt.h defines CHAR, SHORT, and LONG
+       # even if VOID has already been #defined. The win32api
+       # used by mingw and cygwin is known to do this.
+
+       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
+           tcl_cv_winnt_ignore_void,
+           AC_TRY_COMPILE([
+#define VOID void
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+           ], [
+               CHAR c;
+               SHORT s;
+               LONG l;
+           ],
+        tcl_cv_winnt_ignore_void=yes,
+        tcl_cv_winnt_ignore_void=no)
+       )
+       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
+           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
+                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
+       fi
+    fi
+
+       # See if the compiler supports casting to a union type.
+       # This is used to stop gcc from printing a compiler
+       # warning when initializing a union member.
+
+       AC_CACHE_CHECK(for cast to union support,
+           tcl_cv_cast_to_union,
+           AC_TRY_COMPILE([],
+           [
+                 union foo { int i; double d; };
+                 union foo f = (union foo) (int) 0;
+           ],
+           tcl_cv_cast_to_union=yes,
+           tcl_cv_cast_to_union=no)
+       )
+       if test "$tcl_cv_cast_to_union" = "yes"; then
+           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
+                   [Defined when compiler supports casting to union type.])
+       fi
+
+       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
+
+    AC_SUBST(CFLAGS_DEBUG)
+    AC_SUBST(CFLAGS_OPTIMIZE)
+    AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
+
+    AC_SUBST(STLIB_LD)
+    AC_SUBST(SHLIB_LD)
+
+    AC_SUBST(SHLIB_LD_LIBS)
+    AC_SUBST(SHLIB_CFLAGS)
+
+    AC_SUBST(LD_LIBRARY_PATH_VAR)
+
+    # These must be called after we do the basic CFLAGS checks and
+    # verify any possible 64-bit or similar switches are necessary
+    TEA_TCL_EARLY_FLAGS
+    TEA_TCL_64BIT_FLAGS
+])
+
+#--------------------------------------------------------------------
+# TEA_SERIAL_PORT
+#
+#      Determine which interface to use to talk to the serial port.
+#      Note that #include lines must begin in leftmost column for
+#      some compilers to recognize them as preprocessor directives,
+#      and some build environments have stdin not pointing at a
+#      pseudo-terminal (usually /dev/null instead.)
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines only one of the following vars:
+#              HAVE_SYS_MODEM_H
+#              USE_TERMIOS
+#              USE_TERMIO
+#              USE_SGTTY
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_SERIAL_PORT], [
+    AC_CHECK_HEADERS(sys/modem.h)
+    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
+    AC_TRY_RUN([
+#include <termios.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termio.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termios.h>
+#include <errno.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <termio.h>
+#include <errno.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+#include <errno.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
+    fi])
+    case $tcl_cv_api_serial in
+       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
+       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
+       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_PATH_X
+#
+#      Locate the X11 header files and the X11 library archive.  Try
+#      the ac_path_x macro first, but if it doesn't find the X stuff
+#      (e.g. because there's no xmkmf program) then check through
+#      a list of possible directories.  Under some conditions the
+#      autoconf macro will return an include directory that contains
+#      no include files, so double-check its result just to be safe.
+#
+#      This should be called after TEA_CONFIG_CFLAGS as setting the
+#      LIBS line can confuse some configure macro magic.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets the following vars:
+#              XINCLUDES
+#              XLIBSW
+#              PKG_LIBS (appends to)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_X], [
+    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
+       TEA_PATH_UNIX_X
+    fi
+])
+
+AC_DEFUN([TEA_PATH_UNIX_X], [
+    AC_PATH_X
+    not_really_there=""
+    if test "$no_x" = ""; then
+       if test "$x_includes" = ""; then
+           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
+       else
+           if test ! -r $x_includes/X11/Xlib.h; then
+               not_really_there="yes"
+           fi
+       fi
+    fi
+    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
+       AC_MSG_CHECKING([for X11 header files])
+       found_xincludes="no"
+       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
+       if test "$found_xincludes" = "no"; then
+           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
+           for i in $dirs ; do
+               if test -r $i/X11/Xlib.h; then
+                   AC_MSG_RESULT([$i])
+                   XINCLUDES=" -I$i"
+                   found_xincludes="yes"
+                   break
+               fi
+           done
+       fi
+    else
+       if test "$x_includes" != ""; then
+           XINCLUDES="-I$x_includes"
+           found_xincludes="yes"
+       fi
+    fi
+    if test "$found_xincludes" = "no"; then
+       AC_MSG_RESULT([couldn't find any!])
+    fi
+
+    if test "$no_x" = yes; then
+       AC_MSG_CHECKING([for X11 libraries])
+       XLIBSW=nope
+       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
+       for i in $dirs ; do
+           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
+               AC_MSG_RESULT([$i])
+               XLIBSW="-L$i -lX11"
+               x_libraries="$i"
+               break
+           fi
+       done
+    else
+       if test "$x_libraries" = ""; then
+           XLIBSW=-lX11
+       else
+           XLIBSW="-L$x_libraries -lX11"
+       fi
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_MSG_RESULT([could not find any!  Using -lX11.])
+       XLIBSW=-lX11
+    fi
+    # TEA specific:
+    if test x"${XLIBSW}" != x ; then
+       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BLOCKING_STYLE
+#
+#      The statements below check for systems where POSIX-style
+#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
+#      On these systems (mostly older ones), use the old BSD-style
+#      FIONBIO approach instead.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              HAVE_SYS_IOCTL_H
+#              HAVE_SYS_FILIO_H
+#              USE_FIONBIO
+#              O_NONBLOCK
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BLOCKING_STYLE], [
+    AC_CHECK_HEADERS(sys/ioctl.h)
+    AC_CHECK_HEADERS(sys/filio.h)
+    TEA_CONFIG_SYSTEM
+    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
+    case $system in
+       OSF*)
+           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
+           AC_MSG_RESULT([FIONBIO])
+           ;;
+       *)
+           AC_MSG_RESULT([O_NONBLOCK])
+           ;;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_TIME_HANDLER
+#
+#      Checks how the system deals with time.h, what time structures
+#      are used on the system, and what fields the structures have.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              USE_DELTA_FOR_TZ
+#              HAVE_TM_GMTOFF
+#              HAVE_TM_TZADJ
+#              HAVE_TIMEZONE_VAR
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TIME_HANDLER], [
+    AC_CHECK_HEADERS(sys/time.h)
+    AC_HEADER_TIME
+    AC_STRUCT_TIMEZONE
+
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
+
+    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
+           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
+    if test $tcl_cv_member_tm_tzadj = yes ; then
+       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
+    fi
+
+    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
+           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
+    if test $tcl_cv_member_tm_gmtoff = yes ; then
+       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
+    fi
+
+    #
+    # Its important to include time.h in this check, as some systems
+    # (like convex) have timezone functions, etc.
+    #
+    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
+       AC_TRY_COMPILE([#include <time.h>],
+           [extern long timezone;
+           timezone += 1;
+           exit (0);],
+           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
+    if test $tcl_cv_timezone_long = yes ; then
+       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+    else
+       #
+       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
+       #
+       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
+           AC_TRY_COMPILE([#include <time.h>],
+               [extern time_t timezone;
+               timezone += 1;
+               exit (0);],
+               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
+       if test $tcl_cv_timezone_time = yes ; then
+           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BUGGY_STRTOD
+#
+#      Under Solaris 2.4, strtod returns the wrong value for the
+#      terminating character under some conditions.  Check for this
+#      and if the problem exists use a substitute procedure
+#      "fixstrtod" (provided by Tcl) that corrects the error.
+#      Also, on Compaq's Tru64 Unix 5.0,
+#      strtod(" ") returns 0.0 instead of a failure to convert.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Might defines some of the following vars:
+#              strtod (=fixstrtod)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BUGGY_STRTOD], [
+    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
+    if test "$tcl_strtod" = 1; then
+       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
+           AC_TRY_RUN([
+               #include <stdlib.h>
+               extern double strtod();
+               int main() {
+                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
+                   char *term;
+                   double value;
+                   value = strtod(infString, &term);
+                   if ((term != infString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(nanString, &term);
+                   if ((term != nanString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(spaceString, &term);
+                   if (term == (spaceString+1)) {
+                       exit(1);
+                   }
+                   exit(0);
+               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
+                   tcl_cv_strtod_buggy=buggy)])
+       if test "$tcl_cv_strtod_buggy" = buggy; then
+           AC_LIBOBJ([fixstrtod])
+           USE_COMPAT=1
+           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_EARLY_FLAGS
+#
+#      Check for what flags are needed to be passed so the correct OS
+#      features are available.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              _ISOC99_SOURCE
+#              _LARGEFILE64_SOURCE
+#              _LARGEFILE_SOURCE64
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_EARLY_FLAG],[
+    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
+       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
+           AC_TRY_COMPILE([[#define ]$1[ 1
+]$2], $3,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
+    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
+       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
+       tcl_flags="$tcl_flags $1"
+    fi
+])
+
+AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
+    AC_MSG_CHECKING([for required early compiler flags])
+    tcl_flags=""
+    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
+       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
+       [struct stat64 buf; int i = stat64("/", &buf);])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
+       [char *p = (char *)open64;])
+    if test "x${tcl_flags}" = "x" ; then
+       AC_MSG_RESULT([none])
+    else
+       AC_MSG_RESULT([${tcl_flags}])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_64BIT_FLAGS
+#
+#      Check for what is defined in the way of 64-bit features.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              TCL_WIDE_INT_IS_LONG
+#              TCL_WIDE_INT_TYPE
+#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
+#              HAVE_STRUCT_STAT64
+#              HAVE_TYPE_OFF64_T
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
+    AC_MSG_CHECKING([for 64-bit integer type])
+    AC_CACHE_VAL(tcl_cv_type_64bit,[
+       tcl_cv_type_64bit=none
+       # See if the compiler knows natively about __int64
+       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
+           tcl_type_64bit=__int64, tcl_type_64bit="long long")
+       # See if we could use long anyway  Note that we substitute in the
+       # type that is our current guess for a 64-bit type inside this check
+       # program, so it should be modified only carefully...
+        AC_TRY_COMPILE(,[switch (0) {
+            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
+        }],tcl_cv_type_64bit=${tcl_type_64bit})])
+    if test "${tcl_cv_type_64bit}" = none ; then
+       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
+       AC_MSG_RESULT([yes])
+    elif test "${tcl_cv_type_64bit}" = "__int64" \
+               -a "${TEA_PLATFORM}" = "windows" ; then
+       # TEA specific: We actually want to use the default tcl.h checks in
+       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
+       AC_MSG_RESULT([using Tcl header defaults])
+    else
+       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
+           [What type should be used to define wide integers?])
+       AC_MSG_RESULT([${tcl_cv_type_64bit}])
+
+       # Now check for auxiliary declarations
+       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 p;],
+               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
+       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
+            p = readdir64(d); rewinddir64(d); closedir64(d);],
+               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
+       if test "x${tcl_cv_DIR64}" = "xyes" ; then
+           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
+           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
+],
+               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
+       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
+       fi
+
+       AC_CHECK_FUNCS(open64 lseek64)
+       AC_MSG_CHECKING([for off64_t])
+       AC_CACHE_VAL(tcl_cv_type_off64_t,[
+           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
+],
+               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
+       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
+       dnl functions lseek64 and open64 are defined.
+       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
+               test "x${ac_cv_func_lseek64}" = "xyes" && \
+               test "x${ac_cv_func_open64}" = "xyes" ; then
+           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
+           AC_MSG_RESULT([yes])
+       else
+           AC_MSG_RESULT([no])
+       fi
+    fi
+])
+
+##
+## Here ends the standard Tcl configuration bits and starts the
+## TEA specific functions
+##
+
+#------------------------------------------------------------------------
+# TEA_INIT --
+#
+#      Init various Tcl Extension Architecture (TEA) variables.
+#      This should be the first called TEA_* macro.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              CYGPATH
+#              EXEEXT
+#      Defines only:
+#              TEA_VERSION
+#              TEA_INITED
+#              TEA_PLATFORM (windows or unix)
+#
+# "cygpath" is used on windows to generate native path names for include
+# files. These variables should only be used with the compiler and linker
+# since they generate native path names.
+#
+# EXEEXT
+#      Select the executable extension based on the host type.  This
+#      is a lightweight replacement for AC_EXEEXT that doesn't require
+#      a compiler.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INIT], [
+    TEA_VERSION="3.13"
+
+    AC_MSG_CHECKING([TEA configuration])
+    if test x"${PACKAGE_NAME}" = x ; then
+       AC_MSG_ERROR([
+The PACKAGE_NAME variable must be defined by your TEA configure.ac])
+    fi
+    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
+
+    # If the user did not set CFLAGS, set it now to keep macros
+    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
+    if test "${CFLAGS+set}" != "set" ; then
+       CFLAGS=""
+    fi
+
+    case "`uname -s`" in
+       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
+           EXEEXT=".exe"
+           TEA_PLATFORM="windows"
+           ;;
+       *CYGWIN_*)
+           EXEEXT=".exe"
+           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
+           ;;
+       *)
+           CYGPATH=echo
+           # Maybe we are cross-compiling....
+           case ${host_alias} in
+               *mingw32*)
+               EXEEXT=".exe"
+               TEA_PLATFORM="windows"
+               ;;
+           *)
+               EXEEXT=""
+               TEA_PLATFORM="unix"
+               ;;
+           esac
+           ;;
+    esac
+
+    # Check if exec_prefix is set. If not use fall back to prefix.
+    # Note when adjusted, so that TEA_PREFIX can correct for this.
+    # This is needed for recursive configures, since autoconf propagates
+    # $prefix, but not $exec_prefix (doh!).
+    if test x$exec_prefix = xNONE ; then
+       exec_prefix_default=yes
+       exec_prefix=$prefix
+    fi
+
+    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
+
+    AC_SUBST(EXEEXT)
+    AC_SUBST(CYGPATH)
+
+    # This package name must be replaced statically for AC_SUBST to work
+    AC_SUBST(PKG_LIB_FILE)
+    # Substitute STUB_LIB_FILE in case package creates a stub library too.
+    AC_SUBST(PKG_STUB_LIB_FILE)
+
+    # We AC_SUBST these here to ensure they are subst'ed,
+    # in case the user doesn't call TEA_ADD_...
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+    AC_SUBST(PKG_TCL_SOURCES)
+    AC_SUBST(PKG_HEADERS)
+    AC_SUBST(PKG_INCLUDES)
+    AC_SUBST(PKG_LIBS)
+    AC_SUBST(PKG_CFLAGS)
+
+    # Configure the installer.
+    TEA_INSTALLER
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_SOURCES
+#              PKG_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       case $i in
+           [\$]*)
+               # allow $-var names
+               PKG_SOURCES="$PKG_SOURCES $i"
+               PKG_OBJECTS="$PKG_OBJECTS $i"
+               ;;
+           *)
+               # check for existence - allows for generic/win/unix VPATH
+               # To add more dirs here (like 'src'), you have to update VPATH
+               # in Makefile.in as well
+               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+                   -a ! -f "${srcdir}/macosx/$i" \
+                   ; then
+                   AC_MSG_ERROR([could not find source file '$i'])
+               fi
+               PKG_SOURCES="$PKG_SOURCES $i"
+               # this assumes it is in a VPATH dir
+               i=`basename $i`
+               # handle user calling this before or after TEA_SETUP_COMPILER
+               if test x"${OBJEXT}" != x ; then
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+               else
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+               fi
+               PKG_OBJECTS="$PKG_OBJECTS $j"
+               ;;
+       esac
+    done
+    AC_SUBST(PKG_SOURCES)
+    AC_SUBST(PKG_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_STUB_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_STUB_SOURCES
+#              PKG_STUB_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_STUB_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence - allows for generic/win/unix VPATH
+       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+           -a ! -f "${srcdir}/macosx/$i" \
+           ; then
+           AC_MSG_ERROR([could not find stub source file '$i'])
+       fi
+       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
+       # this assumes it is in a VPATH dir
+       i=`basename $i`
+       # handle user calling this before or after TEA_SETUP_COMPILER
+       if test x"${OBJEXT}" != x ; then
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+       else
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+       fi
+       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
+    done
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_TCL_SOURCES --
+#
+#      Specify one or more Tcl source files.  These should be platform
+#      independent runtime files.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_TCL_SOURCES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_TCL_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
+       fi
+       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
+    done
+    AC_SUBST(PKG_TCL_SOURCES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_HEADERS --
+#
+#      Specify one or more source headers.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_HEADERS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_HEADERS], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
+       fi
+       PKG_HEADERS="$PKG_HEADERS $i"
+    done
+    AC_SUBST(PKG_HEADERS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_INCLUDES --
+#
+#      Specify one or more include dirs.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_INCLUDES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_INCLUDES], [
+    vars="$@"
+    for i in $vars; do
+       PKG_INCLUDES="$PKG_INCLUDES $i"
+    done
+    AC_SUBST(PKG_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_LIBS --
+#
+#      Specify one or more libraries.  Users should check for
+#      the right platform before adding to their list.  For Windows,
+#      libraries provided in "foo.lib" format will be converted to
+#      "-lfoo" when using GCC (mingw).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_LIBS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_LIBS], [
+    vars="$@"
+    for i in $vars; do
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
+           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
+       fi
+       PKG_LIBS="$PKG_LIBS $i"
+    done
+    AC_SUBST(PKG_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CFLAGS --
+#
+#      Specify one or more CFLAGS.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_CFLAGS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CFLAGS], [
+    PKG_CFLAGS="$PKG_CFLAGS $@"
+    AC_SUBST(PKG_CFLAGS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CLEANFILES --
+#
+#      Specify one or more CLEANFILES.
+#
+# Arguments:
+#      one or more file names to clean target
+#
+# Results:
+#
+#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CLEANFILES], [
+    CLEANFILES="$CLEANFILES $@"
+])
+
+#------------------------------------------------------------------------
+# TEA_PREFIX --
+#
+#      Handle the --prefix=... option by defaulting to what Tcl gave
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      If --prefix or --exec-prefix was not specified, $prefix and
+#      $exec_prefix will be set to the values given to Tcl when it was
+#      configured.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_PREFIX], [
+    if test "${prefix}" = "NONE"; then
+       prefix_default=yes
+       if test x"${TCL_PREFIX}" != x; then
+           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
+           prefix=${TCL_PREFIX}
+       else
+           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
+           prefix=/usr/local
+       fi
+    fi
+    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
+       -o x"${exec_prefix_default}" = x"yes" ; then
+       if test x"${TCL_EXEC_PREFIX}" != x; then
+           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
+           exec_prefix=${TCL_EXEC_PREFIX}
+       else
+           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
+           exec_prefix=$prefix
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER_CC --
+#
+#      Do compiler checks the way we want.  This is just a replacement
+#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER_CC], [
+    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
+    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
+
+    AC_PROG_CC
+    AC_PROG_CPP
+
+    #--------------------------------------------------------------------
+    # Checks to see if the make program sets the $MAKE variable.
+    #--------------------------------------------------------------------
+
+    AC_PROG_MAKE_SET
+
+    #--------------------------------------------------------------------
+    # Find ranlib
+    #--------------------------------------------------------------------
+
+    AC_CHECK_TOOL(RANLIB, ranlib)
+
+    #--------------------------------------------------------------------
+    # Determines the correct binary file extension (.o, .obj, .exe etc.)
+    #--------------------------------------------------------------------
+
+    AC_OBJEXT
+    AC_EXEEXT
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER --
+#
+#      Do compiler checks that use the compiler.  This must go after
+#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER], [
+    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
+    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
+
+    #------------------------------------------------------------------------
+    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
+    # It makes compiling go faster.  (This is only a performance feature.)
+    #------------------------------------------------------------------------
+
+    if test -z "$no_pipe" -a -n "$GCC"; then
+       AC_CACHE_CHECK([if the compiler understands -pipe],
+           tcl_cv_cc_pipe, [
+           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
+           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
+           CFLAGS=$hold_cflags])
+       if test $tcl_cv_cc_pipe = yes; then
+           CFLAGS="$CFLAGS -pipe"
+       fi
+    fi
+
+    #--------------------------------------------------------------------
+    # Common compiler flag setup
+    #--------------------------------------------------------------------
+
+    AC_C_BIGENDIAN
+])
+
+#------------------------------------------------------------------------
+# TEA_MAKE_LIB --
+#
+#      Generate a line that can be used to build a shared/unshared library
+#      in a platform independent manner.
+#
+# Arguments:
+#      none
+#
+#      Requires:
+#
+# Results:
+#
+#      Defines the following vars:
+#      CFLAGS -        Done late here to note disturb other AC macros
+#       MAKE_LIB -      Command to execute to build the Tcl library;
+#                       differs depending on whether or not Tcl is being
+#                       compiled as a shared library.
+#      MAKE_SHARED_LIB Makefile rule for building a shared library
+#      MAKE_STATIC_LIB Makefile rule for building a static library
+#      MAKE_STUB_LIB   Makefile rule for building a stub library
+#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
+#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_MAKE_LIB], [
+    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
+       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       AC_EGREP_CPP([manifest needed], [
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+print("manifest needed")
+#endif
+       ], [
+       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
+       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
+       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
+       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
+       TEA_ADD_CLEANFILES([*.manifest])
+       ])
+       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
+    else
+       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
+    fi
+
+    if test "${SHARED_BUILD}" = "1" ; then
+       MAKE_LIB="${MAKE_SHARED_LIB} "
+    else
+       MAKE_LIB="${MAKE_STATIC_LIB} "
+    fi
+
+    #--------------------------------------------------------------------
+    # Shared libraries and static libraries have different names.
+    # Use the double eval to make sure any variables in the suffix is
+    # substituted. (@@@ Might not be necessary anymore)
+    #--------------------------------------------------------------------
+
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       if test "${SHARED_BUILD}" = "1" ; then
+           # We force the unresolved linking of symbols that are really in
+           # the private libraries of Tcl and Tk.
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
+           fi
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
+           if test "$GCC" = "yes"; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
+           fi
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+       else
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+           if test "$GCC" = "yes"; then
+               PKG_LIB_FILE=lib${PKG_LIB_FILE}
+           fi
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+       if test "$GCC" = "yes"; then
+           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
+       fi
+       # These aren't needed on Windows (either MSVC or gcc)
+       RANLIB=:
+       RANLIB_STUB=:
+    else
+       RANLIB_STUB="${RANLIB}"
+       if test "${SHARED_BUILD}" = "1" ; then
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
+           fi
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+           RANLIB=:
+       else
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+    fi
+
+    # These are escaped so that only CFLAGS is picked up at configure time.
+    # The other values will be substituted at make time.
+    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
+    if test "${SHARED_BUILD}" = "1" ; then
+       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
+    fi
+
+    AC_SUBST(MAKE_LIB)
+    AC_SUBST(MAKE_SHARED_LIB)
+    AC_SUBST(MAKE_STATIC_LIB)
+    AC_SUBST(MAKE_STUB_LIB)
+    AC_SUBST(RANLIB_STUB)
+    AC_SUBST(VC_MANIFEST_EMBED_DLL)
+    AC_SUBST(VC_MANIFEST_EMBED_EXE)
+])
+
+#------------------------------------------------------------------------
+# TEA_LIB_SPEC --
+#
+#      Compute the name of an existing object library located in libdir
+#      from the given base name and produce the appropriate linker flags.
+#
+# Arguments:
+#      basename        The base name of the library without version
+#                      numbers, extensions, or "lib" prefixes.
+#      extra_dir       Extra directory in which to search for the
+#                      library.  This location is used first, then
+#                      $prefix/$exec-prefix, then some defaults.
+#
+# Requires:
+#      TEA_INIT and TEA_PREFIX must be called first.
+#
+# Results:
+#
+#      Defines the following vars:
+#              ${basename}_LIB_NAME    The computed library name.
+#              ${basename}_LIB_SPEC    The computed linker flags.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LIB_SPEC], [
+    AC_MSG_CHECKING([for $1 library])
+
+    # Look in exec-prefix for the library (defined by TEA_PREFIX).
+
+    tea_lib_name_dir="${exec_prefix}/lib"
+
+    # Or in a user-specified location.
+
+    if test x"$2" != x ; then
+       tea_extra_lib_dir=$2
+    else
+       tea_extra_lib_dir=NONE
+    fi
+
+    for i in \
+           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
+       if test -f "$i" ; then
+           tea_lib_name_dir=`dirname $i`
+           $1_LIB_NAME=`basename $i`
+           $1_LIB_PATH_NAME=$i
+           break
+       fi
+    done
+
+    if test "${TEA_PLATFORM}" = "windows"; then
+       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
+    else
+       # Strip off the leading "lib" and trailing ".a" or ".so"
+
+       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
+       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
+    fi
+
+    if test "x${$1_LIB_NAME}" = x ; then
+       AC_MSG_ERROR([not found])
+    else
+       AC_MSG_RESULT([${$1_LIB_SPEC}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TCL_HEADERS --
+#
+#      Locate the private Tcl include files
+#
+# Arguments:
+#
+#      Requires:
+#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
+#                              already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_TOP_DIR_NATIVE
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
+    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
+    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
+    AC_MSG_CHECKING([for Tcl private include files])
+
+    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
+    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
+
+    # Check to see if tcl<Plat>Port.h isn't already with the public headers
+    # Don't look for tclInt.h because that resides with tcl.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
+       else
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TCL_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
+       if test "`uname -s`" = "Darwin"; then
+            # If Tcl was built as a framework, attempt to use
+            # the framework's Headers and PrivateHeaders directories
+            case ${TCL_DEFS} in
+               *TCL_FRAMEWORK*)
+                   if test -d "${TCL_BIN_DIR}/Headers" -a \
+                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
+                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
+                   else
+                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                   fi
+                   ;;
+           esac
+           result="Using ${TCL_INCLUDES}"
+       else
+           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
+               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
+           fi
+           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TCL_TOP_DIR_NATIVE)
+
+    AC_SUBST(TCL_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TCL_HEADERS --
+#
+#      Locate the installed public Tcl header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tclinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
+    AC_MSG_CHECKING([for Tcl public headers])
+
+    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tclh, [
+       # Use the value from --with-tclinclude, if it was given
+
+       if test x"${with_tclinclude}" != x ; then
+           if test -f "${with_tclinclude}/tcl.h" ; then
+               ac_cv_c_tclh=${with_tclinclude}
+           else
+               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tcl was built as a framework, attempt to use
+               # the framework's Headers directory
+               case ${TCL_DEFS} in
+                   *TCL_FRAMEWORK*)
+                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tcl is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TCL_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TCL_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tcl.h" ; then
+                   ac_cv_c_tclh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tclh}" = x ; then
+       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tclh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
+
+    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TCL_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TK_HEADERS --
+#
+#      Locate the private Tk include files
+#
+# Arguments:
+#
+#      Requires:
+#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
+#                               already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
+    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
+    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
+    AC_MSG_CHECKING([for Tk private include files])
+
+    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
+    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
+
+    # Check to see if tk<Plat>Port.h isn't already with the public headers
+    # Don't look for tkInt.h because that resides with tk.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
+       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
+       else
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TK_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
+       # Detect and add ttk subdir
+       if test -d "${TK_SRC_DIR}/generic/ttk"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
+       fi
+       if test "`uname -s`" = "Darwin"; then
+           # If Tk was built as a framework, attempt to use
+           # the framework's Headers and PrivateHeaders directories
+           case ${TK_DEFS} in
+               *TK_FRAMEWORK*)
+                       if test -d "${TK_BIN_DIR}/Headers" -a \
+                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
+                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
+                       else
+                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                       fi
+                       ;;
+           esac
+           result="Using ${TK_INCLUDES}"
+       else
+           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
+              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
+           fi
+           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TK_TOP_DIR_NATIVE)
+    AC_SUBST(TK_XLIB_DIR_NATIVE)
+
+    AC_SUBST(TK_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TK_HEADERS --
+#
+#      Locate the installed public Tk header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tkinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
+    AC_MSG_CHECKING([for Tk public headers])
+
+    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tkh, [
+       # Use the value from --with-tkinclude, if it was given
+
+       if test x"${with_tkinclude}" != x ; then
+           if test -f "${with_tkinclude}/tk.h" ; then
+               ac_cv_c_tkh=${with_tkinclude}
+           else
+               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tk was built as a framework, attempt to use
+               # the framework's Headers directory.
+               case ${TK_DEFS} in
+                   *TK_FRAMEWORK*)
+                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tk is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TK_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tk's --prefix location,
+           # relative to directory of tkConfig.sh, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
+               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TK_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tk.h" ; then
+                   ac_cv_c_tkh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tkh}" = x ; then
+       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tkh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
+
+    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TK_INCLUDES)
+
+    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+       # On Windows and Aqua, we need the X compat headers
+       AC_MSG_CHECKING([for X11 header files])
+       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
+           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
+           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+           AC_SUBST(TK_XINCLUDES)
+       fi
+       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_CONFIG --
+#
+#      Locate the ${1}Config.sh file and perform a sanity check on
+#      the ${1} compile flags.  These are used by packages like
+#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-$1=...
+#
+#      Defines the following vars:
+#              $1_BIN_DIR      Full path to the directory containing
+#                              the $1Config.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_CONFIG], [
+    #
+    # Ok, lets find the $1 configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-$1
+    #
+
+    if test x"${no_$1}" = x ; then
+       # we reset no_$1 in case something fails here
+       no_$1=true
+       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
+       AC_MSG_CHECKING([for $1 configuration])
+       AC_CACHE_VAL(ac_cv_c_$1config,[
+
+           # First check to see if --with-$1 was specified.
+           if test x"${with_$1config}" != x ; then
+               case ${with_$1config} in
+                   */$1Config.sh )
+                       if test -f ${with_$1config}; then
+                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
+                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
+                       fi;;
+               esac
+               if test -f "${with_$1config}/$1Config.sh" ; then
+                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
+               else
+                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
+               fi
+           fi
+
+           # then check for a private $1 installation
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in \
+                       ../$1 \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../$1 \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../$1 \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ${srcdir}/../$1 \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+                   if test -f "$i/unix/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_$1config}" = x ; then
+           $1_BIN_DIR="# no $1 configs found"
+           AC_MSG_WARN([Cannot find $1 configuration definitions])
+           exit 0
+       else
+           no_$1=
+           $1_BIN_DIR=${ac_cv_c_$1config}
+           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG --
+#
+#      Load the $1Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              $1_SRC_DIR
+#              $1_LIB_FILE
+#              $1_LIB_SPEC
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_CONFIG], [
+    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
+
+    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${$1_BIN_DIR}/$1Config.sh"
+    else
+        AC_MSG_RESULT([file not found])
+    fi
+
+    #
+    # If the $1_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable $1_LIB_SPEC will be set to the value
+    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
+    # instead of $1_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    #
+
+    if test -f "${$1_BIN_DIR}/Makefile" ; then
+       AC_MSG_WARN([Found Makefile - using build library specs for $1])
+        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
+        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
+        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
+        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
+        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
+    fi
+
+    AC_SUBST($1_VERSION)
+    AC_SUBST($1_BIN_DIR)
+    AC_SUBST($1_SRC_DIR)
+
+    AC_SUBST($1_LIB_FILE)
+    AC_SUBST($1_LIB_SPEC)
+
+    AC_SUBST($1_STUB_LIB_FILE)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    # Allow the caller to prevent this auto-check by specifying any 2nd arg
+    AS_IF([test "x$2" = x], [
+       # Check both upper and lower-case variants
+       # If a dev wanted non-stubs libs, this function could take an option
+       # to not use _STUB in the paths below
+       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
+           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
+           [TEA_LOAD_CONFIG_LIB($1_STUB)])
+    ])
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG_LIB --
+#
+#      Helper function to load correct library from another extension's
+#      ${PACKAGE}Config.sh.
+#
+# Results:
+#      Adds to LIBS the appropriate extension library
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
+    AC_MSG_CHECKING([For $1 library for LIBS])
+    # This simplifies the use of stub libraries by automatically adding
+    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
+    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
+    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
+    if test "x${$1_LIB_SPEC}" != "x" ; then
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
+           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
+           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
+       else
+           TEA_ADD_LIBS([${$1_LIB_SPEC}])
+           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
+       fi
+    else
+       AC_MSG_RESULT([file not found])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_EXPORT_CONFIG --
+#
+#      Define the data to insert into the ${PACKAGE}Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1
+#
+# Results:
+#      Substitutes the following vars:
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_EXPORT_CONFIG], [
+    #--------------------------------------------------------------------
+    # These are for $1Config.sh
+    #--------------------------------------------------------------------
+
+    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
+    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
+    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
+    else
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
+    fi
+    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
+    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
+    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
+    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
+
+    AC_SUBST($1_BUILD_LIB_SPEC)
+    AC_SUBST($1_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_PATH)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    AC_SUBST(MAJOR_VERSION)
+    AC_SUBST(MINOR_VERSION)
+    AC_SUBST(PATCHLEVEL)
+])
+
+
+#------------------------------------------------------------------------
+# TEA_INSTALLER --
+#
+#      Configure the installer.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              INSTALL
+#              INSTALL_DATA_DIR
+#              INSTALL_DATA
+#              INSTALL_PROGRAM
+#              INSTALL_SCRIPT
+#              INSTALL_LIBRARY
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INSTALLER], [
+    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
+    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
+    INSTALL_DATA='${INSTALL} -m 644'
+    INSTALL_PROGRAM='${INSTALL} -m 755'
+    INSTALL_SCRIPT='${INSTALL} -m 755'
+
+    TEA_CONFIG_SYSTEM
+    case $system in
+       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
+             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
+    esac
+
+    AC_SUBST(INSTALL)
+    AC_SUBST(INSTALL_DATA_DIR)
+    AC_SUBST(INSTALL_DATA)
+    AC_SUBST(INSTALL_PROGRAM)
+    AC_SUBST(INSTALL_SCRIPT)
+    AC_SUBST(INSTALL_LIBRARY)
+])
+
+###
+# Tip 430 - ZipFS Modifications
+###
+#------------------------------------------------------------------------
+# SC_ZIPFS_SUPPORT
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#              TCL_ZIPFS_FLAG
+#              ZIP_PROG
+#------------------------------------------------------------------------
+
+#------------------------------------------------------------------------
+# SC_PROG_ZIP
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              ZIP_PROG
+#       ZIP_PROG_OPTIONS
+#       ZIP_PROG_VFSSEARCH
+#       ZIP_INSTALL_OBJS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ZIPFS_SUPPORT], [
+    AC_MSG_CHECKING([for zipfs support])
+    ZIP_PROG=""
+    ZIP_PROG_OPTIONS=""
+    ZIP_PROG_VFSSEARCH=""
+    INSTALL_MSGS=""
+    # If our native tclsh processes the "install" command line option
+    # we can use it to mint zip files
+    AS_IF([$TCLSH_PROG install],[
+      ZIP_PROG=${TCLSH_PROG}
+      ZIP_PROG_OPTIONS="install mkzip"
+      ZIP_PROG_VFSSEARCH="."
+      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
+    ])
+    if test "x$ZIP_PROG" = "x" ; then
+        AC_CACHE_VAL(ac_cv_path_zip, [
+        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
+        for dir in $search_path ; do
+            for j in `ls -r $dir/zip 2> /dev/null` \
+                `ls -r $dir/zip 2> /dev/null` ; do
+            if test x"$ac_cv_path_zip" = x ; then
+                if test -f "$j" ; then
+                ac_cv_path_zip=$j
+                break
+                fi
+            fi
+            done
+        done
+        ])
+        if test -f "$ac_cv_path_zip" ; then
+            ZIP_PROG="$ac_cv_path_zip "
+            AC_MSG_RESULT([$ZIP_PROG])
+            ZIP_PROG_OPTIONS="-rq"
+            ZIP_PROG_VFSSEARCH="."
+            AC_MSG_RESULT([Found INFO Zip in environment])
+            # Use standard arguments for zip
+        fi
+    fi
+    if test "x$ZIP_PROG" = "x" ; then
+           # It is not an error if an installed version of Zip can't be located.
+        ZIP_PROG=""
+        ZIP_PROG_OPTIONS=""
+        ZIP_PROG_VFSSEARCH=""
+        TCL_ZIPFS_SUPPORT=0
+        TCL_ZIPFS_FLAG=
+    else
+        # ZIPFS Support
+       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
+       if test ${TCL_ZIP_FILE} = "" ; then
+          TCL_ZIPFS_SUPPORT=0
+          TCL_ZIPFS_FLAG=
+          INSTALL_LIBRARIES=install-libraries
+          INSTALL_MSGS=install-msgs
+       else
+           if test ${SHARED_BUILD} = 1 ; then
+              TCL_ZIPFS_SUPPORT=1
+              INSTALL_LIBRARIES=install-libraries-zipfs-shared
+           else
+              TCL_ZIPFS_SUPPORT=2
+              INSTALL_LIBRARIES=install-libraries-zipfs-static
+           fi
+          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
+       fi
+    fi
+
+    AC_SUBST(TCL_ZIP_FILE)
+    AC_SUBST(TCL_ZIPFS_SUPPORT)
+    AC_SUBST(TCL_ZIPFS_FLAG)
+    AC_SUBST(ZIP_PROG)
+    AC_SUBST(ZIP_PROG_OPTIONS)
+    AC_SUBST(ZIP_PROG_VFSSEARCH)
+    AC_SUBST(INSTALL_LIBRARIES)
+    AC_SUBST(INSTALL_MSGS)
+])
+
+# Local Variables:
+# mode: autoconf
+# End:
similarity index 96%
rename from pkgs/tdbcodbc1.1.1/win/makefile.vc
rename to pkgs/tdbcodbc1.1.2/win/makefile.vc
index 7f28a7b..f5f388d 100644 (file)
@@ -8,7 +8,7 @@
 #   nmake /s /nologo /f makefile.vc INSTALLDIR=c:\path\to\installdir test\r
 #\r
 # For other build options (debug, static etc.)\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
similarity index 99%
rename from pkgs/tdbcmysql1.1.1/win/nmakehlp.c
rename to pkgs/tdbcodbc1.1.2/win/nmakehlp.c
index c21de63..7536ede 100644 (file)
@@ -643,7 +643,7 @@ SubstituteFile(
        }
 
        /* debug: dump the list */
-#ifdef _DEBUG
+#ifndef NDEBUG
        {
            int n = 0;
            list_item_t *p = NULL;
@@ -708,7 +708,7 @@ QualifyPath(
 {
     char szCwd[MAX_PATH + 1];
 
-       GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
+    GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
     printf("%s\n", szCwd);
     return 0;
 }
similarity index 94%
rename from pkgs/tdbcmysql1.1.1/win/rules-ext.vc
rename to pkgs/tdbcodbc1.1.2/win/rules-ext.vc
index 531e070..6da5689 100644 (file)
@@ -31,7 +31,7 @@ macro to the name of the project makefile.
 # We extract version numbers using the nmakehlp program. For now use\r
 # the local copy of nmakehlp. Once we locate Tcl, we will use that\r
 # one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
 !endif\r
 \r
 # First locate the Tcl directory that we are working with.\r
diff --git a/pkgs/tdbcodbc1.1.2/win/rules.vc b/pkgs/tdbcodbc1.1.2/win/rules.vc
new file mode 100644 (file)
index 0000000..13e3879
--- /dev/null
@@ -0,0 +1,1852 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# rules.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file does all the hard work in terms of parsing build options,\r
+# compiler switches, defining common targets and macros. The Tcl makefile\r
+# directly includes this. Extensions include it via "rules-ext.vc".\r
+#\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
+# detailed documentation.\r
+#\r
+# See the file "license.terms" for information on usage and redistribution\r
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
+#\r
+# Copyright (c) 2001-2003 David Gravereaux.\r
+# Copyright (c) 2003-2008 Patrick Thoyts\r
+# Copyright (c) 2017      Ashok P. Nadkarni\r
+#------------------------------------------------------------------------------\r
+\r
+!ifndef _RULES_VC\r
+_RULES_VC = 1\r
+\r
+# The following macros define the version of the rules.vc nmake build system\r
+# For modifications that are not backward-compatible, you *must* change\r
+# the major version.\r
+RULES_VERSION_MAJOR = 1\r
+RULES_VERSION_MINOR = 8\r
+\r
+# The PROJECT macro must be defined by parent makefile.\r
+!if "$(PROJECT)" == ""\r
+!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
+!endif\r
+\r
+!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
+PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
+!endif\r
+\r
+# Also special case Tcl and Tk to save some typing later\r
+DOING_TCL = 0\r
+DOING_TK  = 0\r
+!if "$(PROJECT)" == "tcl"\r
+DOING_TCL = 1\r
+!elseif "$(PROJECT)" == "tk"\r
+DOING_TK = 1\r
+!endif\r
+\r
+!ifndef NEED_TK\r
+# Backwards compatibility\r
+!ifdef PROJECT_REQUIRES_TK\r
+NEED_TK = $(PROJECT_REQUIRES_TK)\r
+!else\r
+NEED_TK = 0\r
+!endif\r
+!endif\r
+\r
+!ifndef NEED_TCL_SOURCE\r
+NEED_TCL_SOURCE = 0\r
+!endif\r
+\r
+!ifdef NEED_TK_SOURCE\r
+!if $(NEED_TK_SOURCE)\r
+NEED_TK = 1\r
+!endif\r
+!else\r
+NEED_TK_SOURCE = 0\r
+!endif\r
+\r
+################################################################\r
+# Nmake is a pretty weak environment in syntax and capabilities\r
+# so this file is necessarily verbose. It's broken down into\r
+# the following parts.\r
+#\r
+# 0. Sanity check that compiler environment is set up and initialize\r
+#    any built-in settings from the parent makefile\r
+# 1. First define the external tools used for compiling, copying etc.\r
+#    as this is independent of everything else.\r
+# 2. Figure out our build structure in terms of the directory, whether\r
+#    we are building Tcl or an extension, etc.\r
+# 3. Determine the compiler and linker versions\r
+# 4. Build the nmakehlp helper application\r
+# 5. Determine the supported compiler options and features\r
+# 6. Parse the OPTS macro value for user-specified build configuration\r
+# 7. Parse the STATS macro value for statistics instrumentation\r
+# 8. Parse the CHECKS macro for additional compilation checks\r
+# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
+# 10. Based on this selected configuration, construct the output\r
+#     directory and file paths\r
+# 11. Construct the paths where the package is to be installed\r
+# 12. Set up the actual options passed to compiler and linker based\r
+#     on the information gathered above.\r
+# 13. Define some standard build targets and implicit rules. These may\r
+#     be optionally disabled by the parent makefile.\r
+# 14. (For extensions only.) Compare the configuration of the target\r
+#     Tcl and the extensions and warn against discrepancies.\r
+#\r
+# One final note about the macro names used. They are as they are\r
+# for historical reasons. We would like legacy extensions to\r
+# continue to work with this make include file so be wary of\r
+# changing them for consistency or clarity.\r
+\r
+# 0. Sanity check compiler environment\r
+\r
+# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
+# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
+\r
+!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
+MSG = ^\r
+Visual C++ compiler environment not initialized.\r
+!error $(MSG)\r
+!endif\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+\r
+################################################################\r
+# 1. Define external programs being used\r
+\r
+#----------------------------------------------------------\r
+# Set the proper copy method to avoid overwrite questions\r
+# to the user when copying files and selecting the right\r
+# "delete all" method.\r
+#----------------------------------------------------------\r
+\r
+RMDIR  = rmdir /S /Q\r
+CPY    = xcopy /i /y >NUL\r
+CPYDIR  = xcopy /e /i /y >NUL\r
+COPY   = copy /y >NUL\r
+MKDIR   = mkdir\r
+\r
+######################################################################\r
+# 2. Figure out our build environment in terms of what we're building.\r
+#\r
+# (a) Tcl itself\r
+# (b) Tk\r
+# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
+# (d) a Tcl extension using libraries/includes from Tcl source directory\r
+#\r
+# This last is needed because some extensions still need\r
+# some Tcl interfaces that are not publicly exposed.\r
+#\r
+# The fragment will set the following macros:\r
+# ROOT - root of this module sources\r
+# COMPATDIR - source directory that holds compatibility sources\r
+# DOCDIR - source directory containing documentation files\r
+# GENERICDIR - platform-independent source directory\r
+# WIN_DIR - Windows-specific source directory\r
+# TESTDIR - directory containing test files\r
+# TOOLSDIR - directory containing build tools\r
+# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
+#    when building Tcl itself.\r
+# _INSTALLDIR - native form of the installation path. For Tcl\r
+#    this will be the root of the Tcl installation. For extensions\r
+#    this will be the lib directory under the root.\r
+# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
+#    headers and libraries from an installed Tcl, and 0 if built against\r
+#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
+#    named.\r
+# _TCL_H - native path to the tcl.h file\r
+#\r
+# If Tk is involved, also sets the following\r
+# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
+#    Tk itself.\r
+# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
+# _TK_H - native path to the tk.h file\r
+\r
+# Root directory for sources and assumed subdirectories\r
+ROOT = $(MAKEDIR)\..\r
+# The following paths CANNOT have spaces in them as they appear on the\r
+# left side of implicit rules.\r
+!ifndef COMPATDIR\r
+COMPATDIR      = $(ROOT)\compat\r
+!endif\r
+!ifndef DOCDIR\r
+DOCDIR         = $(ROOT)\doc\r
+!endif\r
+!ifndef GENERICDIR\r
+GENERICDIR     = $(ROOT)\generic\r
+!endif\r
+!ifndef TOOLSDIR\r
+TOOLSDIR       = $(ROOT)\tools\r
+!endif\r
+!ifndef TESTDIR\r
+TESTDIR        = $(ROOT)\tests\r
+!endif\r
+!ifndef LIBDIR\r
+!if exist("$(ROOT)\library")\r
+LIBDIR          = $(ROOT)\library\r
+!else\r
+LIBDIR          = $(ROOT)\lib\r
+!endif\r
+!endif\r
+!ifndef DEMODIR\r
+!if exist("$(LIBDIR)\demos")\r
+DEMODIR                = $(LIBDIR)\demos\r
+!else\r
+DEMODIR                = $(ROOT)\demos\r
+!endif\r
+!endif # ifndef DEMODIR\r
+# Do NOT use WINDIR because it is Windows internal environment\r
+# variable to point to c:\windows!\r
+WIN_DIR                = $(ROOT)\win\r
+\r
+!ifndef RCDIR\r
+!if exist("$(WIN_DIR)\rc")\r
+RCDIR           = $(WIN_DIR)\rc\r
+!else\r
+RCDIR           = $(WIN_DIR)\r
+!endif\r
+!endif\r
+RCDIR = $(RCDIR:/=\)\r
+\r
+# The target directory where the built packages and binaries will be installed.\r
+# INSTALLDIR is the (optional) path specified by the user.\r
+# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
+!ifdef INSTALLDIR\r
+### Fix the path separators.\r
+_INSTALLDIR    = $(INSTALLDIR:/=\)\r
+!else\r
+### Assume the normal default.\r
+_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+\r
+# BEGIN Case 2(a) - Building Tcl itself\r
+\r
+# Only need to define _TCL_H\r
+_TCL_H = ..\generic\tcl.h\r
+\r
+# END Case 2(a) - Building Tcl itself\r
+\r
+!elseif $(DOING_TK)\r
+\r
+# BEGIN Case 2(b) - Building Tk\r
+\r
+TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
+!if "$(TCLDIR)" == ""\r
+!if [echo TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+!endif # TCLDIR == ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
+!if !exist("$(_TCL_H)")\r
+!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
+!endif\r
+\r
+_TK_H = ..\generic\tk.h\r
+\r
+# END Case 2(b) - Building Tk\r
+\r
+!else\r
+\r
+# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
+\r
+# If command line has specified Tcl location through TCLDIR, use it\r
+# else default to the INSTALLDIR setting\r
+!if "$(TCLDIR)" != ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
+TCLINSTALL     = 1\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
+TCLINSTALL     = 0\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+!endif\r
+\r
+!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
+\r
+TCLINSTALL     = 1\r
+TCLDIR          = $(_INSTALLDIR)\..\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TCLDIR                = $(_INSTALLDIR)\..\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!if [echo _TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TCLINSTALL      = 0\r
+TCLDIR         = $(_TCLDIR)\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!endif # TCLDIR\r
+\r
+!ifndef _TCL_H\r
+MSG =^\r
+Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+# Now do the same to locate Tk headers and libs if project requires Tk\r
+!if $(NEED_TK)\r
+\r
+!if "$(TKDIR)" != ""\r
+\r
+_TKDIR = $(TKDIR:/=\)\r
+!if exist("$(_TKDIR)\include\tk.h")\r
+TKINSTALL      = 1\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+!elseif exist("$(_TKDIR)\generic\tk.h")\r
+TKINSTALL      = 0\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+!endif\r
+\r
+!else # TKDIR not defined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+TKINSTALL      = 1\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TKDIR         = $(_INSTALLDIR)\..\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+TKDIR          = $(_TKDIR)\r
+\r
+!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!if [echo _TKDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
+!error *** Could not locate Tk source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TKINSTALL      = 0\r
+TKDIR          = $(_TKDIR)\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+\r
+!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!endif # TKDIR\r
+\r
+!ifndef _TK_H\r
+MSG =^\r
+Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+!endif # NEED_TK\r
+\r
+!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tcl.^\r
+*** Please set the TCLDIR macro to point to the Tcl sources.\r
+!error $(MSG)\r
+!endif\r
+\r
+!if $(NEED_TK_SOURCE)\r
+!if $(TKINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tk.^\r
+*** Please set the TKDIR macro to point to the Tk sources.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+\r
+# If INSTALLDIR set to Tcl installation root dir then reset to the\r
+# lib dir for installing extensions\r
+!if exist("$(_INSTALLDIR)\include\tcl.h")\r
+_INSTALLDIR=$(_INSTALLDIR)\lib\r
+!endif\r
+\r
+# END Case 2(c) or (d) - Building an extension\r
+!endif # if $(DOING_TCL)\r
+\r
+################################################################\r
+# 3. Determine compiler version and architecture\r
+# In this section, we figure out the compiler version and the\r
+# architecture for which we are building. This sets the\r
+# following macros:\r
+# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
+#     This is also printed by the compiler in dotted form 19.10 etc.\r
+# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
+#     compiler version 1200. This is kept only for legacy reasons as it\r
+#     does not make sense for recent Microsoft compilers. Only used for\r
+#     output directory names.\r
+# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
+# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
+# MACHINE - same as $(ARCH) - legacy\r
+# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
+\r
+cc32           = $(CC)   # built-in default.\r
+link32         = link\r
+lib32          = lib\r
+rc32           = $(RC)   # built-in default.\r
+\r
+#----------------------------------------------------------------\r
+# Figure out the compiler architecture and version by writing\r
+# the C macros to a file, preprocessing them with the C\r
+# preprocessor and reading back the created file\r
+\r
+_HASH=^#\r
+_VC_MANIFEST_EMBED_EXE=\r
+_VC_MANIFEST_EMBED_DLL=\r
+VCVER=0\r
+!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
+    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
+    && ![echo ARCH=IX86 >> vercl.x] \\r
+    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
+    && ![echo ARCH=AMD64 >> vercl.x] \\r
+    && ![echo $(_HASH)endif >> vercl.x] \\r
+    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
+!include vercl.i\r
+!if $(VCVERSION) < 1900\r
+!if ![echo VCVER= ^\> vercl.vc] \\r
+    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
+!include vercl.vc\r
+!endif\r
+!else\r
+# The simple calculation above does not apply to new Visual Studio releases\r
+# Keep the compiler version in its native form.\r
+VCVER = $(VCVERSION)\r
+!endif\r
+!endif\r
+\r
+!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# The MACHINE macro is used by legacy makefiles so set it as well\r
+!ifdef MACHINE\r
+!if "$(MACHINE)" == "x86"\r
+!undef MACHINE\r
+MACHINE = IX86\r
+!elseif "$(MACHINE)" == "x64"\r
+!undef MACHINE\r
+MACHINE = AMD64\r
+!endif\r
+!if "$(MACHINE)" != "$(ARCH)"\r
+!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
+!endif\r
+!else\r
+MACHINE=$(ARCH)\r
+!endif\r
+\r
+#---------------------------------------------------------------\r
+# The PLATFORM_IDENTIFY macro matches the values returned by\r
+# the Tcl platform::identify command\r
+!if "$(MACHINE)" == "AMD64"\r
+PLATFORM_IDENTIFY = win32-x86_64\r
+!else\r
+PLATFORM_IDENTIFY = win32-ix86\r
+!endif\r
+\r
+# The MULTIPLATFORM macro controls whether binary extensions are installed\r
+# in platform-specific directories. Intended to be set/used by extensions.\r
+!ifndef MULTIPLATFORM_INSTALL\r
+MULTIPLATFORM_INSTALL = 0\r
+!endif\r
+\r
+#------------------------------------------------------------\r
+# Figure out the *host* architecture by reading the registry\r
+\r
+!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
+NATIVE_ARCH=IX86\r
+!else\r
+NATIVE_ARCH=AMD64\r
+!endif\r
+\r
+# Since MSVC8 we must deal with manifest resources.\r
+!if $(VCVERSION) >= 1400\r
+_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
+_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
+!endif\r
+\r
+################################################################\r
+# 4. Build the nmakehlp program\r
+# This is a helper app we need to overcome nmake's limiting\r
+# environment. We will call out to it to get various bits of\r
+# information about supported compiler options etc.\r
+#\r
+# Tcl itself will always use the nmakehlp.c program which is\r
+# in its own source. It will be kept updated there.\r
+#\r
+# Extensions built against an installed Tcl will use the installed\r
+# copy of Tcl's nmakehlp.c if there is one and their own version\r
+# otherwise. In the latter case, they would also be using their own\r
+# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
+# or rules.vc.\r
+#\r
+# Extensions built against Tcl sources will use the one from the Tcl source.\r
+#\r
+# When building an extension using a sufficiently new version of Tcl,\r
+# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
+# copy of nmakehlp.c to be used.\r
+\r
+!ifndef NMAKEHLPC\r
+# Default to the one in the current directory (the extension's own nmakehlp.c)\r
+NMAKEHLPC = nmakehlp.c\r
+\r
+!if !$(DOING_TCL)\r
+!if $(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
+!endif\r
+!else # !$(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
+!endif\r
+!endif # $(TCLINSTALL)\r
+!endif # !$(DOING_TCL)\r
+\r
+!endif # NMAKEHLPC\r
+\r
+# We always build nmakehlp even if it exists since we do not know\r
+# what source it was built from.\r
+!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
+!endif\r
+\r
+################################################################\r
+# 5. Test for compiler features\r
+# Visual C++ compiler options have changed over the years. Check\r
+# which options are supported by the compiler in use.\r
+#\r
+# The following macros are set:\r
+# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
+# DEBUGFLAGS - the compiler flags to be used for debug builds\r
+# LINKERFLAGS - Flags passed to the linker\r
+#\r
+# Note that these are the compiler settings *available*, not those\r
+# that will be *used*. The latter depends on the OPTS macro settings\r
+# which we have not yet parsed.\r
+#\r
+# Also note that some of the flags in OPTIMIZATIONS are not really\r
+# related to optimization. They are placed there only for legacy reasons\r
+# as some extensions expect them to be included in that macro.\r
+\r
+# -Op improves float consistency. Note only needed for older compilers\r
+# Newer compilers do not need or support this option.\r
+!if [nmakehlp -c -Op]\r
+FPOPTS  = -Op\r
+!endif\r
+\r
+# Strict floating point semantics - present in newer compilers in lieu of -Op\r
+!if [nmakehlp -c -fp:strict]\r
+FPOPTS  = $(FPOPTS) -fp:strict\r
+!endif\r
+\r
+!if "$(MACHINE)" == "IX86"\r
+### test for pentium errata\r
+!if [nmakehlp -c -QI0f]\r
+!message *** Compiler has 'Pentium 0x0f fix'\r
+FPOPTS  = $(FPOPTS) -QI0f\r
+!else\r
+!message *** Compiler does not have 'Pentium 0x0f fix'\r
+!endif\r
+!endif\r
+\r
+### test for optimizations\r
+# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
+# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
+# stack probe at *every* function entry, not just those with more than\r
+# a page of stack allocation resulting in a performance hit.  However,\r
+# /O2 documentation is misleading as its stack probes are simply the\r
+# default page size locals allocation probes and not what is implied\r
+# by an explicit /Gs option.\r
+\r
+OPTIMIZATIONS = $(FPOPTS)\r
+\r
+!if [nmakehlp -c -O2]\r
+OPTIMIZING = 1\r
+OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
+!else\r
+# Legacy, really. All modern compilers support this\r
+!message *** Compiler does not have 'Optimizations'\r
+OPTIMIZING = 0\r
+!endif\r
+\r
+# Checks for buffer overflows in local arrays\r
+!if [nmakehlp -c -GS]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
+!endif\r
+\r
+# Link time optimization. Note that this option (potentially) makes\r
+# generated libraries only usable by the specific VC++ version that\r
+# created it. Requires /LTCG linker option\r
+!if [nmakehlp -c -GL]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
+CC_GL_OPT_ENABLED = 1\r
+!else\r
+# In newer compilers -GL and -YX are incompatible.\r
+!if [nmakehlp -c -YX]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
+!endif\r
+!endif # [nmakehlp -c -GL]\r
+\r
+DEBUGFLAGS     = $(FPOPTS)\r
+\r
+# Run time error checks. Not available or valid in a release, non-debug build\r
+# RTC is for modern compilers, -GZ is legacy\r
+!if [nmakehlp -c -RTC1]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
+!elseif [nmakehlp -c -GZ]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# Linker flags\r
+\r
+# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
+# if the linker supports a specific option. Without these flags link will\r
+# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
+# They are not passed through to the actual application / extension\r
+# link rules.\r
+!ifndef LINKER_TESTFLAGS\r
+LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
+!endif\r
+\r
+LINKERFLAGS     =\r
+\r
+# If compiler has enabled link time optimization, linker must too with -ltcg\r
+!ifdef CC_GL_OPT_ENABLED\r
+!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
+!endif\r
+!endif\r
+\r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
+########################################################################\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
+# Based on this, we will construct the actual switches to be passed to the\r
+# compiler and linker using the macros defined in the previous section.\r
+# The following macros are defined by this section based on OPTS\r
+# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
+#                1 -> build as a static library and shell\r
+# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
+# DEBUG - 1 -> debug build, 0 -> release builds\r
+# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
+# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
+# PGO     - 1 -> profile based optimization, 0 -> no\r
+# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
+#           0 -> link to static C runtime for static Tcl build.\r
+#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
+# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
+# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
+#           0 -> Use the non-thread allocator.\r
+# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
+#           C runtime, 0 -> use the debug C runtime.\r
+# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
+# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
+#           configuration (ignored for Tcl itself)\r
+# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
+# Further, LINKERFLAGS are modified based on above.\r
+\r
+# Default values for all the above\r
+STATIC_BUILD   = 0\r
+TCL_THREADS    = 1\r
+DEBUG          = 0\r
+SYMBOLS                = 0\r
+PROFILE                = 0\r
+PGO            = 0\r
+MSVCRT         = 1\r
+TCL_USE_STATIC_PACKAGES        = 0\r
+USE_THREAD_ALLOC = 1\r
+UNCHECKED      = 0\r
+CONFIG_CHECK    = 1\r
+!if $(DOING_TCL)\r
+USE_STUBS       = 0\r
+!else\r
+USE_STUBS       = 1\r
+!endif\r
+\r
+# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
+# set the above macros based on OPTS content\r
+!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
+\r
+# OPTS are specified, parse them\r
+\r
+!if [nmakehlp -f $(OPTS) "static"]\r
+!message *** Doing static\r
+STATIC_BUILD   = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nostubs"]\r
+!message *** Not using stubs\r
+USE_STUBS      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+!message *** Doing nomsvcrt\r
+MSVCRT         = 0\r
+!else\r
+!if [nmakehlp -f $(OPTS) "msvcrt"]\r
+!message *** Doing msvcrt\r
+!else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
+MSVCRT         = 0\r
+!endif\r
+!endif\r
+!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+\r
+!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
+!message *** Doing staticpkg\r
+TCL_USE_STATIC_PACKAGES        = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nothreads"]\r
+!message *** Compile explicitly for non-threaded tcl\r
+TCL_THREADS = 0\r
+USE_THREAD_ALLOC= 0\r
+!endif\r
+\r
+!if $(TCL_MAJOR_VERSION) == 8\r
+!if [nmakehlp -f $(OPTS) "time64bit"]\r
+!message *** Force 64-bit time_t\r
+_USE_64BIT_TIME_T = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
+# Yes, it's weird that the "symbols" option controls DEBUG and\r
+# the "pdbs" option controls SYMBOLS. That's historical.\r
+!if [nmakehlp -f $(OPTS) "symbols"]\r
+!message *** Doing symbols\r
+DEBUG          = 1\r
+!else\r
+DEBUG          = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pdbs"]\r
+!message *** Doing pdbs\r
+SYMBOLS                = 1\r
+!else\r
+SYMBOLS                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "profile"]\r
+!message *** Doing profile\r
+PROFILE                = 1\r
+!else\r
+PROFILE                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pgi"]\r
+!message *** Doing profile guided optimization instrumentation\r
+PGO            = 1\r
+!elseif [nmakehlp -f $(OPTS) "pgo"]\r
+!message *** Doing profile guided optimization\r
+PGO            = 2\r
+!else\r
+PGO            = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "loimpact"]\r
+!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
+!endif\r
+\r
+# TBD - should get rid of this option\r
+!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
+!message *** Doing thrdalloc\r
+USE_THREAD_ALLOC = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "tclalloc"]\r
+USE_THREAD_ALLOC = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "unchecked"]\r
+!message *** Doing unchecked\r
+UNCHECKED = 1\r
+!else\r
+UNCHECKED = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
+CONFIG_CHECK = 1\r
+!else\r
+CONFIG_CHECK = 0\r
+!endif\r
+\r
+!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
+\r
+# Set linker flags based on above\r
+\r
+!if $(PGO) > 1\r
+!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!elseif $(PGO) > 0\r
+!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+################################################################\r
+# 8. Parse the STATS macro to configure code instrumentation\r
+# The following macros are set by this section:\r
+# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
+#                 0 -> disables\r
+# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
+#                     0 -> disables\r
+\r
+# Default both are off\r
+TCL_MEM_DEBUG      = 0\r
+TCL_COMPILE_DEBUG   = 0\r
+\r
+!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
+\r
+!if [nmakehlp -f $(STATS) "memdbg"]\r
+!message *** Doing memdbg\r
+TCL_MEM_DEBUG      = 1\r
+!else\r
+TCL_MEM_DEBUG      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(STATS) "compdbg"]\r
+!message *** Doing compdbg\r
+TCL_COMPILE_DEBUG   = 1\r
+!else\r
+TCL_COMPILE_DEBUG   = 0\r
+!endif\r
+\r
+!endif\r
+\r
+####################################################################\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
+# The following macros are set by this section:\r
+# WARNINGS - compiler switches that control the warnings level\r
+# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
+#                     0 -> enable deprecated functions\r
+\r
+# Defaults - Permit deprecated functions and warning level 3\r
+TCL_NO_DEPRECATED          = 0\r
+WARNINGS                   = -W3\r
+\r
+!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
+\r
+!if [nmakehlp -f $(CHECKS) "nodep"]\r
+!message *** Doing nodep check\r
+TCL_NO_DEPRECATED          = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
+!message *** Doing full warnings check\r
+WARNINGS                   = -W4\r
+!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
+!endif\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
+!message *** Doing 64bit portability warnings\r
+WARNINGS                   = $(WARNINGS) -Wp64\r
+!endif\r
+\r
+!endif\r
+\r
+\r
+################################################################\r
+# 10. Construct output directory and file paths\r
+# Figure-out how to name our intermediate and output directories.\r
+# In order to avoid inadvertent mixing of object files built using\r
+# different compilers, build configurations etc.,\r
+#\r
+# Naming convention (suffixes):\r
+#   t = full thread support. (Not used for Tcl >= 8.7)\r
+#   s = static library (as opposed to an import library)\r
+#   g = linked to the debug enabled C run-time.\r
+#   x = special static build when it links to the dynamic C run-time.\r
+#\r
+# The following macros are set in this section:\r
+# SUFX - the suffix to use for binaries based on above naming convention\r
+# BUILDDIRTOP - the toplevel default output directory\r
+#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
+# TMP_DIR - directory where object files are created\r
+# OUT_DIR - directory where output executables are created\r
+# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
+# parent makefile (or command line). The default values are\r
+# based on BUILDDIRTOP.\r
+# STUBPREFIX - name of the stubs library for this project\r
+# PRJIMPLIB - output path of the generated project import library\r
+# PRJLIBNAME - name of generated project library\r
+# PRJLIB     - output path of generated project library\r
+# PRJSTUBLIBNAME - name of the generated project stubs library\r
+# PRJSTUBLIB - output path of the generated project stubs library\r
+# RESFILE - output resource file (only if not static build)\r
+\r
+SUFX       = tsgx\r
+\r
+!if $(DEBUG)\r
+BUILDDIRTOP = Debug\r
+!else\r
+BUILDDIRTOP = Release\r
+!endif\r
+\r
+!if "$(MACHINE)" != "IX86"\r
+BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
+!endif\r
+!if $(VCVER) > 6\r
+BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
+!endif\r
+\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
+SUFX       = $(SUFX:g=)\r
+!endif\r
+\r
+TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
+\r
+!if !$(STATIC_BUILD)\r
+TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
+SUFX       = $(SUFX:s=)\r
+EXT        = dll\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!else\r
+TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
+EXT        = lib\r
+!if !$(MSVCRT)\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!endif\r
+!endif\r
+\r
+!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
+TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
+SUFX       = $(SUFX:t=)\r
+!endif\r
+\r
+!ifndef TMP_DIR\r
+TMP_DIR            = $(TMP_DIRFULL)\r
+!ifndef OUT_DIR\r
+OUT_DIR            = .\$(BUILDDIRTOP)\r
+!endif\r
+!else\r
+!ifndef OUT_DIR\r
+OUT_DIR            = $(TMP_DIR)\r
+!endif\r
+!endif\r
+\r
+# Relative paths -> absolute\r
+!if [echo OUT_DIR = \> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
+!endif\r
+!if [echo TMP_DIR = \>> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
+!endif\r
+!include nmakehlp.out\r
+\r
+# The name of the stubs library for the project being built\r
+STUBPREFIX      = $(PROJECT)stub\r
+\r
+#\r
+# Set up paths to various Tcl executables and libraries needed by extensions\r
+#\r
+\r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
+TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
+TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
+\r
+TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
+TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+\r
+!else # !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+\r
+# When building extensions, we need to locate tclsh. Depending on version\r
+# of Tcl we are building against, this may or may not have a "t" suffix.\r
+# Try various possibilities in turn.\r
+TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist("$(TCLSH)")\r
+TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+\r
+TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\lib\r
+TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
+TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
+\r
+!else # Building against Tcl sources\r
+\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist($(TCLSH))\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\library\r
+TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = $(_TCLDIR)\tools\r
+TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
+\r
+!endif # TCLINSTALL\r
+\r
+tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
+\r
+!endif # $(DOING_TCL)\r
+\r
+# We need a tclsh that will run on the host machine as part of the build.\r
+# IX86 runs on all architectures.\r
+!ifndef TCLSH_NATIVE\r
+!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
+TCLSH_NATIVE   = $(TCLSH)\r
+!else\r
+!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
+!endif\r
+!endif\r
+\r
+# Do the same for Tk and Tk extensions that require the Tk libraries\r
+!if $(DOING_TK) || $(NEED_TK)\r
+WISHNAMEPREFIX = wish\r
+WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
+TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
+TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
+\r
+!if $(DOING_TK)\r
+WISH           = $(OUT_DIR)\$(WISHNAME)\r
+TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
+TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
+\r
+!else # effectively NEED_TK\r
+\r
+!if $(TKINSTALL) # Building against installed Tk\r
+WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
+!else # Building against Tk sources\r
+\r
+WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
+!endif # TKINSTALL\r
+\r
+tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
+\r
+!endif # $(DOING_TK)\r
+!endif # $(DOING_TK) || $(NEED_TK)\r
+\r
+# Various output paths\r
+PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
+\r
+PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
+\r
+# If extension parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
+!ifdef RCFILE\r
+RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
+!else\r
+RESFILE = $(TMP_DIR)\$(PROJECT).res\r
+!endif\r
+!endif\r
+\r
+###################################################################\r
+# 11. Construct the paths for the installation directories\r
+# The following macros get defined in this section:\r
+# LIB_INSTALL_DIR - where libraries should be installed\r
+# BIN_INSTALL_DIR - where the executables should be installed\r
+# DOC_INSTALL_DIR - where documentation should be installed\r
+# SCRIPT_INSTALL_DIR - where scripts should be installed\r
+# INCLUDE_INSTALL_DIR - where C include files should be installed\r
+# DEMO_INSTALL_DIR - where demos should be installed\r
+# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
+\r
+!if $(DOING_TCL) || $(DOING_TK)\r
+LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
+BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
+DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
+!if $(DOING_TCL)\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
+!else # DOING_TK\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!endif\r
+DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
+\r
+!else # extension other than Tk\r
+\r
+PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
+!if $(MULTIPLATFORM_INSTALL)\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+!else\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+!endif\r
+DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
+DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
+\r
+!endif\r
+\r
+###################################################################\r
+# 12. Set up actual options to be passed to the compiler and linker\r
+# Now we have all the information we need, set up the actual flags and\r
+# options that we will pass to the compiler and linker. The main\r
+# makefile should use these in combination with whatever other flags\r
+# and switches are specific to it.\r
+# The following macros are defined, names are for historical compatibility:\r
+# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
+# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
+# crt - Compiler switch that selects the appropriate C runtime\r
+# cdebug - Compiler switches related to debug AND optimizations\r
+# cwarn - Compiler switches that set warning levels\r
+# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
+# ldebug - Linker switches controlling debug information and optimization\r
+# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
+# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
+# conlflags - complete linker switches for console program (subsumes lflags)\r
+# guilflags - complete linker switches for GUI program (subsumes lflags)\r
+# baselibs - minimum Windows libraries required. Parent makefile can\r
+#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
+\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
+\r
+!if $(TCL_MEM_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
+!endif\r
+!if $(TCL_COMPILE_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_COMPILE_DEBUG /DTCL_COMPILE_STATS\r
+!endif\r
+!if $(TCL_THREADS) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_THREADS=1\r
+!if $(USE_THREAD_ALLOC) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1\r
+!endif\r
+!endif\r
+!if $(STATIC_BUILD)\r
+OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
+!endif\r
+!if $(TCL_NO_DEPRECATED)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
+!endif\r
+\r
+!if $(USE_STUBS)\r
+# Note we do not define USE_TCL_STUBS even when building tk since some\r
+# test targets in tk do not use stubs\r
+!if !$(DOING_TCL)\r
+USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
+!if $(NEED_TK)\r
+USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
+!endif\r
+!endif\r
+!endif # USE_STUBS\r
+\r
+!if !$(DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DNDEBUG\r
+!if $(OPTIMIZING)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_OPTIMIZED\r
+!endif\r
+!endif\r
+!if $(PROFILE)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_PROFILED\r
+!endif\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
+!endif\r
+!if $(VCVERSION) < 1300\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
+!endif\r
+\r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
+!if "$(_USE_64BIT_TIME_T)" == "1"\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
+!endif\r
+\r
+# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
+COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
+\r
+# Like the TEA system only set this non empty for non-Tk extensions\r
+# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
+# so we pass both\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+PKGNAMEFLAGS = /DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
+               /DMODULE_SCOPE=extern\r
+!endif\r
+\r
+# crt picks the C run time based on selected OPTS\r
+!if $(MSVCRT)\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MDd\r
+!else\r
+crt = -MD\r
+!endif\r
+!else\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MTd\r
+!else\r
+crt = -MT\r
+!endif\r
+!endif\r
+\r
+# cdebug includes compiler options for debugging as well as optimization.\r
+!if $(DEBUG)\r
+\r
+# In debugging mode, optimizations need to be disabled\r
+cdebug = -Zi -Od $(DEBUGFLAGS)\r
+\r
+!else\r
+\r
+cdebug = $(OPTIMIZATIONS)\r
+!if $(SYMBOLS)\r
+cdebug = $(cdebug) -Zi\r
+!endif\r
+\r
+!endif # $(DEBUG)\r
+\r
+# cwarn includes default warning levels.\r
+cwarn = $(WARNINGS)\r
+\r
+!if "$(MACHINE)" == "AMD64"\r
+# Disable pointer<->int warnings related to cast between different sizes\r
+# There are a gadzillion of these due to use of ClientData and\r
+# clutter up compiler\r
+# output increasing chance of a real warning getting lost. So disable them.\r
+# Eventually some day, Tcl will be 64-bit clean.\r
+cwarn = $(cwarn) -wd4311 -wd4312\r
+!endif\r
+\r
+### Common compiler options that are architecture specific\r
+!if "$(MACHINE)" == "ARM"\r
+carch = /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
+!else\r
+carch =\r
+!endif\r
+\r
+!if $(DEBUG)\r
+# Turn warnings into errors\r
+cwarn = $(cwarn) -WX\r
+!endif\r
+\r
+INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WIN_DIR)" -I"$(COMPATDIR)"\r
+!endif\r
+\r
+# These flags are defined roughly in the order of the pre-reform\r
+# rules.vc/makefile.vc to help visually compare that the pre- and\r
+# post-reform build logs\r
+\r
+# cflags contains generic flags used for building practically all object files\r
+cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
+\r
+# appcflags contains $(cflags) and flags for building the application\r
+# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
+# flags used for building shared object files The two differ in the\r
+# BUILD_$(PROJECT) macro which should be defined only for the shared\r
+# library *implementation* and not for its caller interface\r
+\r
+appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
+appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
+pkgcflags = $(appcflags) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+\r
+# stubscflags contains $(cflags) plus flags used for building a stubs\r
+# library for the package.  Note: /DSTATIC_BUILD is defined in\r
+# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
+# library. However the stubs library is ALWAYS static hence included\r
+# here irrespective of the OPTS setting.\r
+#\r
+# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
+# without stating why. Tcl itself compiled stubs libs with this flag.\r
+# so we do not remove it from cflags. -GL may prevent extensions\r
+# compiled with one VC version to fail to link against stubs library\r
+# compiled with another VC version. Check for this and fix accordingly.\r
+stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl /DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
+\r
+# Link flags\r
+\r
+!if $(DEBUG)\r
+ldebug = -debug -debugtype:cv\r
+!else\r
+ldebug = -release -opt:ref -opt:icf,3\r
+!if $(SYMBOLS)\r
+ldebug = $(ldebug) -debug -debugtype:cv\r
+!endif\r
+!endif\r
+\r
+# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
+!if $(PROFILE)\r
+ldebug= $(ldebug) -profile\r
+!endif\r
+\r
+### Declarations common to all linker versions\r
+lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+lflags = $(lflags) -nodefaultlib:libucrt.lib\r
+!endif\r
+\r
+dlllflags = $(lflags) -dll\r
+conlflags = $(lflags) -subsystem:console\r
+guilflags = $(lflags) -subsystem:windows\r
+\r
+# Libraries that are required for every image.\r
+# Extensions should define any additional libraries with $(PRJ_LIBS)\r
+winlibs   = kernel32.lib advapi32.lib\r
+\r
+!if $(NEED_TK)\r
+winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
+!endif\r
+\r
+# Avoid 'unresolved external symbol __security_cookie' errors.\r
+# c.f. http://support.microsoft.com/?id=894573\r
+!if "$(MACHINE)" == "AMD64"\r
+!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
+winlibs   = $(winlibs) bufferoverflowU.lib\r
+!endif\r
+!endif\r
+\r
+baselibs = $(winlibs) $(PRJ_LIBS)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+baselibs   = $(baselibs) ucrt.lib\r
+!endif\r
+\r
+################################################################\r
+# 13. Define standard commands, common make targets and implicit rules\r
+\r
+CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
+CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
+CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
+\r
+LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
+DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+\r
+CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
+           $(TCL_INCLUDES) \\r
+           /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
+           /DDOTVERSION=\"$(DOTVERSION)\" \\r
+           /DVERSION=\"$(VERSION)\" \\r
+           /DSUFX=\"$(SUFX)\" \\r
+           /DPROJECT=\"$(PROJECT)\" \\r
+           /DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
+\r
+!ifndef DEFAULT_BUILD_TARGET\r
+DEFAULT_BUILD_TARGET = $(PROJECT)\r
+!endif\r
+\r
+default-target: $(DEFAULT_BUILD_TARGET)\r
+\r
+!if $(MULTIPLATFORM_INSTALL)\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!else\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!endif\r
+\r
+default-pkgindex-tea:\r
+       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
+@PACKAGE_VERSION@    $(DOTVERSION)\r
+@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
+@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
+@PKG_LIB_FILE@       $(PRJLIBNAME)\r
+<<\r
+\r
+default-install: default-install-binaries default-install-libraries\r
+!if $(SYMBOLS)\r
+default-install: default-install-pdbs\r
+!endif\r
+\r
+# Again to deal with historical brokenness, there is some confusion\r
+# in terminlogy. For extensions, the "install-binaries" was used to\r
+# locate target directory for *binary shared libraries* and thus\r
+# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
+# for executables (exes). On the other hand the "install-libraries"\r
+# target is for *scripts* and should have been called "install-scripts".\r
+default-install-binaries: $(PRJLIB)\r
+       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
+\r
+# Alias for default-install-scripts\r
+default-install-libraries: default-install-scripts\r
+\r
+default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
+       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
+       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
+       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
+       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
+\r
+default-install-stubs:\r
+       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
+       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
+       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
+\r
+default-install-pdbs:\r
+       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
+\r
+# "emacs font-lock highlighting fix\r
+\r
+default-install-docs-html:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-docs-n:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-demos:\r
+       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
+       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
+       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
+\r
+default-clean:\r
+       @echo Cleaning $(TMP_DIR)\* ...\r
+       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
+       @echo Cleaning $(WIN_DIR)\nmakehlp.obj, nmakehlp.exe ...\r
+       @if exist $(WIN_DIR)\nmakehlp.obj del $(WIN_DIR)\nmakehlp.obj\r
+       @if exist $(WIN_DIR)\nmakehlp.exe del $(WIN_DIR)\nmakehlp.exe\r
+       @if exist $(WIN_DIR)\nmakehlp.out del $(WIN_DIR)\nmakehlp.out\r
+       @echo Cleaning $(WIN_DIR)\nmhlp-out.txt ...\r
+       @if exist $(WIN_DIR)\nmhlp-out.txt del $(WIN_DIR)\nmhlp-out.txt\r
+       @echo Cleaning $(WIN_DIR)\_junk.pch ...\r
+       @if exist $(WIN_DIR)\_junk.pch del $(WIN_DIR)\_junk.pch\r
+       @echo Cleaning $(WIN_DIR)\vercl.x, vercl.i ...\r
+       @if exist $(WIN_DIR)\vercl.x del $(WIN_DIR)\vercl.x\r
+       @if exist $(WIN_DIR)\vercl.i del $(WIN_DIR)\vercl.i\r
+       @echo Cleaning $(WIN_DIR)\versions.vc, version.vc ...\r
+       @if exist $(WIN_DIR)\versions.vc del $(WIN_DIR)\versions.vc\r
+       @if exist $(WIN_DIR)\version.vc del $(WIN_DIR)\version.vc\r
+\r
+default-hose: default-clean\r
+       @echo Hosing $(OUT_DIR)\* ...\r
+       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
+\r
+# Only for backward compatibility\r
+default-distclean: default-hose\r
+\r
+default-setup:\r
+       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
+       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
+\r
+!if "$(TESTPAT)" != ""\r
+TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
+!endif\r
+\r
+default-test: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
+\r
+default-shell: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       $(DEBUGGER) $(TCLSH)\r
+\r
+# Generation of Windows version resource\r
+!ifdef RCFILE\r
+\r
+# Note: don't use $** in below rule because there may be other dependencies\r
+# and only the "main" rc must be passed to the resource compiler\r
+$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
+       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
+\r
+!else\r
+\r
+# If parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
+\r
+$(TMP_DIR)\$(PROJECT).rc:\r
+       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
+#include <winver.h>\r
+\r
+VS_VERSION_INFO VERSIONINFO\r
+ FILEVERSION   COMMAVERSION\r
+ PRODUCTVERSION        COMMAVERSION\r
+ FILEFLAGSMASK 0x3fL\r
+#ifdef DEBUG\r
+ FILEFLAGS     VS_FF_DEBUG\r
+#else\r
+ FILEFLAGS     0x0L\r
+#endif\r
+ FILEOS                VOS_NT_WINDOWS32\r
+ FILETYPE      VFT_DLL\r
+ FILESUBTYPE   0x0L\r
+BEGIN\r
+    BLOCK "StringFileInfo"\r
+    BEGIN\r
+        BLOCK "040904b0"\r
+        BEGIN\r
+            VALUE "FileDescription",  "Tcl extension " PROJECT\r
+            VALUE "OriginalFilename", PRJLIBNAME\r
+            VALUE "FileVersion",      DOTVERSION\r
+            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
+            VALUE "ProductVersion",   DOTVERSION\r
+        END\r
+    END\r
+    BLOCK "VarFileInfo"\r
+    BEGIN\r
+        VALUE "Translation", 0x409, 1200\r
+    END\r
+END\r
+\r
+<<\r
+\r
+!endif # ifdef RCFILE\r
+\r
+!ifndef DISABLE_IMPLICIT_RULES\r
+DISABLE_IMPLICIT_RULES = 0\r
+!endif\r
+\r
+!if !$(DISABLE_IMPLICIT_RULES)\r
+# Implicit rule definitions - only for building library objects. For stubs and\r
+# main application, the makefile should define explicit rules.\r
+\r
+{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(WIN_DIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(WIN_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+.SUFFIXES:\r
+.SUFFIXES:.c .rc\r
+\r
+!endif\r
+\r
+################################################################\r
+# 14. Sanity check selected options against Tcl build options\r
+# When building an extension, certain configuration options should\r
+# match the ones used when Tcl was built. Here we check and\r
+# warn on a mismatch.\r
+!if !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
+!endif\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
+!endif\r
+!endif # TCLINSTALL\r
+\r
+!if $(CONFIG_CHECK)\r
+!ifdef TCLNMAKECONFIG\r
+!include $(TCLNMAKECONFIG)\r
+\r
+!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
+!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
+!endif\r
+!if $(TCL_VERSION) < 87 && defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
+!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
+!endif\r
+!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
+!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
+!endif\r
+!endif\r
+\r
+!endif # TCLNMAKECONFIG\r
+\r
+!endif # !$(DOING_TCL)\r
+\r
+\r
+#----------------------------------------------------------\r
+# Display stats being used.\r
+#----------------------------------------------------------\r
+\r
+!if !$(DOING_TCL)\r
+!message *** Building against Tcl at '$(_TCLDIR)'\r
+!endif\r
+!if !$(DOING_TK) && $(NEED_TK)\r
+!message *** Building against Tk at '$(_TKDIR)'\r
+!endif\r
+!message *** Intermediate directory will be '$(TMP_DIR)'\r
+!message *** Output directory will be '$(OUT_DIR)'\r
+!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
+!message *** Suffix for binaries will be '$(SUFX)'\r
+!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
+\r
+!endif # ifdef _RULES_VC\r
similarity index 93%
rename from pkgs/itcl4.2.0/win/targets.vc
rename to pkgs/tdbcodbc1.1.2/win/targets.vc
index 7f1d388..077e8f7 100644 (file)
@@ -4,7 +4,7 @@
 # Part of the nmake based build system for Tcl and its extensions.\r
 # This file defines some standard targets for the convenience of extensions\r
 # and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
 \r
 $(PROJECT): setup pkgindex $(PRJLIB)\r
 \r
diff --git a/pkgs/tdbcpostgres1.1.1/tclconfig/README.txt b/pkgs/tdbcpostgres1.1.1/tclconfig/README.txt
deleted file mode 100644 (file)
index 59b5a3e..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-These files comprise the basic building blocks for a Tcl Extension
-Architecture (TEA) extension.  For more information on TEA see:
-
-       http://www.tcl.tk/doc/tea/
-
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
-
-       http://tcl.sourceforge.net/
-
-This package is a freely available open source package.  You can do
-virtually anything you like with it, such as modifying it, redistributing
-it, and selling it either in whole or in part.
-
-CONTENTS
-========
-The following is a short description of the files you will find in
-the sample extension.
-
-README.txt     This file
-
-install-sh     Program used for copying binaries and script files
-               to their install locations.
-
-tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
-               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/tdbcpostgres1.1.1/tclconfig/install-sh b/pkgs/tdbcpostgres1.1.1/tclconfig/install-sh
deleted file mode 100644 (file)
index 7c34c3f..0000000
+++ /dev/null
@@ -1,528 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2011-04-20.01; # UTC
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# 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.
-
-nl='
-'
-IFS=" ""       $nl"
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
-
-# Put in absolute file names if you don't have them in your path;
-# or use environment vars.
-
-chgrpprog=${CHGRPPROG-chgrp}
-chmodprog=${CHMODPROG-chmod}
-chownprog=${CHOWNPROG-chown}
-cmpprog=${CMPPROG-cmp}
-cpprog=${CPPROG-cp}
-mkdirprog=${MKDIRPROG-mkdir}
-mvprog=${MVPROG-mv}
-rmprog=${RMPROG-rm}
-stripprog=${STRIPPROG-strip}
-
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
-posix_mkdir=
-
-# Desired mode of installed file.
-mode=0755
-
-chgrpcmd=
-chmodcmd=$chmodprog
-chowncmd=
-mvcmd=$mvprog
-rmcmd="$rmprog -f"
-stripcmd=
-
-src=
-dst=
-dir_arg=
-dst_arg=
-
-copy_on_change=false
-no_target_directory=
-
-usage="\
-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
-   or: $0 [OPTION]... SRCFILES... DIRECTORY
-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
-   or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
-     --help     display this help and exit.
-     --version  display version info and exit.
-
-  -c            (ignored)
-  -C            install only if different (preserve the last data modification time)
-  -d            create directories instead of installing files.
-  -g GROUP      $chgrpprog installed files to GROUP.
-  -m MODE       $chmodprog installed files to MODE.
-  -o USER       $chownprog installed files to USER.
-  -s            $stripprog installed files.
-  -S            $stripprog installed files.
-  -t DIRECTORY  install into DIRECTORY.
-  -T            report an error if DSTFILE is a directory.
-
-Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
-  RMPROG STRIPPROG
-"
-
-while test $# -ne 0; do
-  case $1 in
-    -c) ;;
-
-    -C) copy_on_change=true;;
-
-    -d) dir_arg=true;;
-
-    -g) chgrpcmd="$chgrpprog $2"
-       shift;;
-
-    --help) echo "$usage"; exit $?;;
-
-    -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
-
-    -o) chowncmd="$chownprog $2"
-       shift;;
-
-    -s) stripcmd=$stripprog;;
-
-    -S) stripcmd="$stripprog $2"
-       shift;;
-
-    -t) dst_arg=$2
-       shift;;
-
-    -T) no_target_directory=true;;
-
-    --version) echo "$0 $scriptversion"; exit $?;;
-
-    --)        shift
-       break;;
-
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
-
-    *)  break;;
-  esac
-  shift
-done
-
-if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
-  # When -d is used, all remaining arguments are directories to create.
-  # When -t is used, the destination is already specified.
-  # Otherwise, the last argument is the destination.  Remove it from $@.
-  for arg
-  do
-    if test -n "$dst_arg"; then
-      # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dst_arg"
-      shift # fnord
-    fi
-    shift # arg
-    dst_arg=$arg
-  done
-fi
-
-if test $# -eq 0; then
-  if test -z "$dir_arg"; then
-    echo "$0: no input file specified." >&2
-    exit 1
-  fi
-  # It's OK to call `install-sh -d' without argument.
-  # This can happen when creating conditional directories.
-  exit 0
-fi
-
-if test -z "$dir_arg"; then
-  do_exit='(exit $ret); exit $ret'
-  trap "ret=129; $do_exit" 1
-  trap "ret=130; $do_exit" 2
-  trap "ret=141; $do_exit" 13
-  trap "ret=143; $do_exit" 15
-
-  # Set umask so as not to create temps with too-generous modes.
-  # However, 'strip' requires both read and write access to temps.
-  case $mode in
-    # Optimize common cases.
-    *644) cp_umask=133;;
-    *755) cp_umask=22;;
-
-    *[0-7])
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw='% 200'
-      fi
-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
-    *)
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw=,u+rw
-      fi
-      cp_umask=$mode$u_plus_rw;;
-  esac
-fi
-
-for src
-do
-  # Protect names starting with `-'.
-  case $src in
-    -*) src=./$src;;
-  esac
-
-  if test -n "$dir_arg"; then
-    dst=$src
-    dstdir=$dst
-    test -d "$dstdir"
-    dstdir_status=$?
-  else
-
-    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
-    # might cause directories to be created, which would be especially bad
-    # if $src (and thus $dsttmp) contains '*'.
-    if test ! -f "$src" && test ! -d "$src"; then
-      echo "$0: $src does not exist." >&2
-      exit 1
-    fi
-
-    if test -z "$dst_arg"; then
-      echo "$0: no destination specified." >&2
-      exit 1
-    fi
-
-    dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
-
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
-    if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
-      fi
-      dstdir=$dst
-      dst=$dstdir/`basename "$src"`
-      dstdir_status=0
-    else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
-      test -d "$dstdir"
-      dstdir_status=$?
-    fi
-  fi
-
-  obsolete_mkdir_used=false
-
-  if test $dstdir_status != 0; then
-    case $posix_mkdir in
-      '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
-       else
-         mkdir_mode=
-       fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
-    esac
-
-    if
-      $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
-      )
-    then :
-    else
-
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
-      # or it failed possibly due to a race condition.  Create the
-      # directory the slow way, step by step, checking for races as we go.
-
-      case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
-      esac
-
-      eval "$initialize_posix_glob"
-
-      oIFS=$IFS
-      IFS=/
-      $posix_glob set -f
-      set fnord $dstdir
-      shift
-      $posix_glob set +f
-      IFS=$oIFS
-
-      prefixes=
-
-      for d
-      do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
-      done
-
-      if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
-      fi
-    fi
-  fi
-
-  if test -n "$dir_arg"; then
-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
-  else
-
-    # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
-
-    # Trap to clean up those temp files at exit.
-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
-
-    # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
-
-    # 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 $cpprog $src $dsttmp" command.
-    #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
-
-    # If -C, don't bother to copy if it wouldn't change the file.
-    if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
-       set X $old && old=:$2:$4:$5:$6 &&
-       set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
-       test "$old" = "$new" &&
-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
-    then
-      rm -f "$dsttmp"
-    else
-      # Rename the file to the real destination.
-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
-
-      # The rename failed, perhaps because mv can't rename something else
-      # to itself, or perhaps because mv is so ancient that it does not
-      # support -f.
-      {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
-      }
-    fi || exit 1
-
-    trap '' 0
-  fi
-done
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/pkgs/tdbcpostgres1.1.1/tclconfig/tcl.m4 b/pkgs/tdbcpostgres1.1.1/tclconfig/tcl.m4
deleted file mode 100644 (file)
index 7d901f9..0000000
+++ /dev/null
@@ -1,4033 +0,0 @@
-# tcl.m4 --
-#
-#      This file provides a set of autoconf macros to help TEA-enable
-#      a Tcl extension.
-#
-# Copyright (c) 1999-2000 Ajuba Solutions.
-# Copyright (c) 2002-2005 ActiveState Corporation.
-#
-# See the file "license.terms" for information on usage and redistribution
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-
-AC_PREREQ(2.57)
-
-# Possible values for key variables defined:
-#
-# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
-# TEA_PLATFORM        - windows unix
-# TEA_TK_EXTENSION    - True if this is a Tk extension
-#
-
-#------------------------------------------------------------------------
-# TEA_PATH_TCLCONFIG --
-#
-#      Locate the tclConfig.sh file and perform a sanity check on
-#      the Tcl compile flags
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tcl=...
-#
-#      Defines the following vars:
-#              TCL_BIN_DIR     Full path to the directory containing
-#                              the tclConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TCLCONFIG], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-    #
-    # Ok, lets find the tcl configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tcl
-    #
-
-    if test x"${no_tcl}" = x ; then
-       # we reset no_tcl in case something fails here
-       no_tcl=true
-       AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
-               [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
-       AC_MSG_CHECKING([for Tcl configuration])
-       AC_CACHE_VAL(ac_cv_c_tclconfig,[
-
-           # First check to see if --with-tcl was specified.
-           if test x"${with_tclconfig}" != x ; then
-               case "${with_tclconfig}" in
-                   */tclConfig.sh )
-                       if test -f "${with_tclconfig}"; then
-                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
-                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tclconfig}/tclConfig.sh" ; then
-                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tcl installation
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ../tcl \
-                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tcl \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tcl \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tcl \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tclconfig}" = x ; then
-           TCL_BIN_DIR="# no Tcl configs found"
-           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
-       else
-           no_tcl=
-           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
-           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_TKCONFIG --
-#
-#      Locate the tkConfig.sh file
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tk=...
-#
-#      Defines the following vars:
-#              TK_BIN_DIR      Full path to the directory containing
-#                              the tkConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TKCONFIG], [
-    #
-    # Ok, lets find the tk configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tk
-    #
-
-    if test x"${no_tk}" = x ; then
-       # we reset no_tk in case something fails here
-       no_tk=true
-       AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
-               [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
-       AC_MSG_CHECKING([for Tk configuration])
-       AC_CACHE_VAL(ac_cv_c_tkconfig,[
-
-           # First check to see if --with-tkconfig was specified.
-           if test x"${with_tkconfig}" != x ; then
-               case "${with_tkconfig}" in
-                   */tkConfig.sh )
-                       if test -f "${with_tkconfig}"; then
-                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
-                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tkconfig}/tkConfig.sh" ; then
-                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tk library
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ../tk \
-                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tk \
-                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tk \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tk \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tkconfig}" = x ; then
-           TK_BIN_DIR="# no Tk configs found"
-           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
-       else
-           no_tk=
-           TK_BIN_DIR="${ac_cv_c_tkconfig}"
-           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TCLCONFIG --
-#
-#      Load the tclConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TCL_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_BIN_DIR
-#              TCL_SRC_DIR
-#              TCL_LIB_FILE
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TCLCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
-
-    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TCL_BIN_DIR}/tclConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
-    # If the TCL_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TCL_LIB_SPEC will be set to the value
-    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
-    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
-        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
-        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tcl was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tcl.framework installed in an arbitrary location.
-       case ${TCL_DEFS} in
-           *TCL_FRAMEWORK*)
-               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
-                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
-                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
-                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
-                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
-                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
-    AC_SUBST(TCL_VERSION)
-    AC_SUBST(TCL_PATCH_LEVEL)
-    AC_SUBST(TCL_BIN_DIR)
-    AC_SUBST(TCL_SRC_DIR)
-
-    AC_SUBST(TCL_LIB_FILE)
-    AC_SUBST(TCL_LIB_FLAG)
-    AC_SUBST(TCL_LIB_SPEC)
-
-    AC_SUBST(TCL_STUB_LIB_FILE)
-    AC_SUBST(TCL_STUB_LIB_FLAG)
-    AC_SUBST(TCL_STUB_LIB_SPEC)
-
-    AC_MSG_CHECKING([platform])
-    hold_cc=$CC; CC="$TCL_CC"
-    AC_TRY_COMPILE(,[
-           #ifdef _WIN32
-               #error win32
-           #endif
-       ], [
-           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
-           TEA_PLATFORM="${TEA_PLATFORM-unix}"
-           CYGPATH=echo
-       ], [
-           TEA_PLATFORM="windows"
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
-    )
-    CC=$hold_cc
-    AC_MSG_RESULT($TEA_PLATFORM)
-
-    # The BUILD_$pkg is to define the correct extern storage class
-    # handling when making this package
-    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
-           [Building extension source?])
-    # Do this here as we have fully defined TEA_PLATFORM now
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       EXEEXT=".exe"
-       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
-    fi
-
-    # TEA specific:
-    AC_SUBST(CLEANFILES)
-    AC_SUBST(TCL_LIBS)
-    AC_SUBST(TCL_DEFS)
-    AC_SUBST(TCL_EXTRA_CFLAGS)
-    AC_SUBST(TCL_LD_FLAGS)
-    AC_SUBST(TCL_SHLIB_LD_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TKCONFIG --
-#
-#      Load the tkConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TK_BIN_DIR
-#
-# Results:
-#
-#      Sets the following vars that should be in tkConfig.sh:
-#              TK_BIN_DIR
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TKCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
-
-    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TK_BIN_DIR}/tkConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
-    # If the TK_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TK_LIB_SPEC will be set to the value
-    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
-    # instead of TK_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
-        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
-        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tk was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tk.framework installed in an arbitrary location.
-       case ${TK_DEFS} in
-           *TK_FRAMEWORK*)
-               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
-                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
-                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
-                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
-                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
-                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
-    # TEA specific: Ensure windowingsystem is defined
-    if test "${TEA_PLATFORM}" = "unix" ; then
-       case ${TK_DEFS} in
-           *MAC_OSX_TK*)
-               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
-               TEA_WINDOWINGSYSTEM="aqua"
-               ;;
-           *)
-               TEA_WINDOWINGSYSTEM="x11"
-               ;;
-       esac
-    elif test "${TEA_PLATFORM}" = "windows" ; then
-       TEA_WINDOWINGSYSTEM="win32"
-    fi
-
-    AC_SUBST(TK_VERSION)
-    AC_SUBST(TK_BIN_DIR)
-    AC_SUBST(TK_SRC_DIR)
-
-    AC_SUBST(TK_LIB_FILE)
-    AC_SUBST(TK_LIB_FLAG)
-    AC_SUBST(TK_LIB_SPEC)
-
-    AC_SUBST(TK_STUB_LIB_FILE)
-    AC_SUBST(TK_STUB_LIB_FLAG)
-    AC_SUBST(TK_STUB_LIB_SPEC)
-
-    # TEA specific:
-    AC_SUBST(TK_LIBS)
-    AC_SUBST(TK_XINCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_TCLSH
-#      Determine the fully qualified path name of the tclsh executable
-#      in the Tcl build directory or the tclsh installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the tclsh executable even if tclsh has not yet been
-#      built in the build directory. The tclsh found is always
-#      associated with a tclConfig.sh file. This tclsh should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCLSH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_TCLSH], [
-    AC_MSG_CHECKING([for tclsh])
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        # tclConfig.sh is in Tcl build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
-          fi
-        else
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
-        fi
-    else
-        # tclConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-        else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
-        fi
-        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${TCLSH_PROG}" ; then
-                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
-    fi
-    AC_MSG_RESULT([${TCLSH_PROG}])
-    AC_SUBST(TCLSH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_WISH
-#      Determine the fully qualified path name of the wish executable
-#      in the Tk build directory or the wish installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the wish executable even if wish has not yet been
-#      built in the build directory. The wish found is always
-#      associated with a tkConfig.sh file. This wish should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              WISH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_WISH], [
-    AC_MSG_CHECKING([for wish])
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        # tkConfig.sh is in Tk build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
-          fi
-        else
-            WISH_PROG="${TK_BIN_DIR}/wish"
-        fi
-    else
-        # tkConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-        else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
-        fi
-        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${WISH_PROG}" ; then
-                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
-    fi
-    AC_MSG_RESULT([${WISH_PROG}])
-    AC_SUBST(WISH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SHARED --
-#
-#      Allows the building of shared libraries
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-shared=yes|no
-#              --enable-stubs=yes|no
-#
-#      Defines the following vars:
-#              STATIC_BUILD    Used for building import/export libraries
-#                              on Windows.
-#
-#      Sets the following vars:
-#              SHARED_BUILD    Value of 1 or 0
-#               STUBS_BUILD     Value if 1 or 0
-#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
-#                                AND TEA_WINDOWING_SYSTEM != ""
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ENABLE_SHARED], [
-    AC_MSG_CHECKING([how to build libraries])
-    AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
-           [build and link with shared libraries (default: on)]),
-       [shared_ok=$enableval], [shared_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       shared_ok=$enableval
-    else
-       shared_ok=yes
-    fi
-
-    AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
-           [build and link with stub libraries. Always true for shared builds (default: on)]),
-       [stubs_ok=$enableval], [stubs_ok=yes])
-
-    if test "${enable_stubs+set}" = set; then
-       enableval="$enable_stubs"
-       stubs_ok=$enableval
-    else
-       stubs_ok=yes
-    fi
-
-    # Stubs are always enabled for shared builds
-    if test "$shared_ok" = "yes" ; then
-       AC_MSG_RESULT([shared])
-       SHARED_BUILD=1
-        STUBS_BUILD=1
-    else
-       AC_MSG_RESULT([static])
-       SHARED_BUILD=0
-       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
-        if test "$stubs_ok" = "yes" ; then
-          STUBS_BUILD=1
-        else
-          STUBS_BUILD=0
-        fi
-    fi
-    if test "${STUBS_BUILD}" = "1" ; then
-      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
-      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
-      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
-        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
-      fi
-    fi
-
-    AC_SUBST(SHARED_BUILD)
-    AC_SUBST(STUBS_BUILD)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_THREADS --
-#
-#      Specify if thread support should be enabled.  If "yes" is specified
-#      as an arg (optional), threads are enabled by default, "no" means
-#      threads are disabled.  "yes" is the default.
-#
-#      TCL_THREADS is checked so that if you are compiling an extension
-#      against a threaded core, your extension must be compiled threaded
-#      as well.
-#
-#      Note that it is legal to have a thread enabled extension run in a
-#      threaded or non-threaded Tcl core, but a non-threaded extension may
-#      only run in a non-threaded Tcl core.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-threads
-#
-#      Sets the following vars:
-#              THREADS_LIBS    Thread library(s)
-#
-#      Defines the following vars:
-#              TCL_THREADS
-#              _REENTRANT
-#              _THREAD_SAFE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_THREADS], [
-    AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
-           [build with threads (default: on)]),
-       [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_threads+set}" = set; then
-       enableval="$enable_threads"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
-    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
-       TCL_THREADS=1
-
-       if test "${TEA_PLATFORM}" != "windows" ; then
-           # We are always OK on Windows, so check what this platform wants:
-
-           # USE_THREAD_ALLOC tells us to try the special thread-based
-           # allocator that significantly reduces lock contention
-           AC_DEFINE(USE_THREAD_ALLOC, 1,
-               [Do we want to use the threaded memory allocator?])
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           if test "`uname -s`" = "SunOS" ; then
-               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-                       [Do we really want to follow the standard? Yes we do!])
-           fi
-           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
-           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
-           if test "$tcl_ok" = "no"; then
-               # Check a little harder for __pthread_mutex_init in the same
-               # library, as some systems hide it there until pthread.h is
-               # defined.  We could alternatively do an AC_TRY_COMPILE with
-               # pthread.h, but that will work with libpthread really doesn't
-               # exist, like AIX 4.2.  [Bug: 4359]
-               AC_CHECK_LIB(pthread, __pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-           fi
-
-           if test "$tcl_ok" = "yes"; then
-               # The space is needed
-               THREADS_LIBS=" -lpthread"
-           else
-               AC_CHECK_LIB(pthreads, pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-               if test "$tcl_ok" = "yes"; then
-                   # The space is needed
-                   THREADS_LIBS=" -lpthreads"
-               else
-                   AC_CHECK_LIB(c, pthread_mutex_init,
-                       tcl_ok=yes, tcl_ok=no)
-                   if test "$tcl_ok" = "no"; then
-                       AC_CHECK_LIB(c_r, pthread_mutex_init,
-                           tcl_ok=yes, tcl_ok=no)
-                       if test "$tcl_ok" = "yes"; then
-                           # The space is needed
-                           THREADS_LIBS=" -pthread"
-                       else
-                           TCL_THREADS=0
-                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
-                       fi
-                   fi
-               fi
-           fi
-       fi
-    else
-       TCL_THREADS=0
-    fi
-    # Do checking message here to not mess up interleaved configure output
-    AC_MSG_CHECKING([for building with threads])
-    if test "${TCL_THREADS}" = 1; then
-       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
-       AC_MSG_RESULT([yes (default)])
-    else
-       AC_MSG_RESULT([no])
-    fi
-    # TCL_THREADS sanity checking.  See if our request for building with
-    # threads is the same as the way Tcl was built.  If not, warn the user.
-    case ${TCL_DEFS} in
-       *THREADS=1*)
-           if test "${TCL_THREADS}" = "0"; then
-               AC_MSG_WARN([
-    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
-    that IS thread-enabled.  It is recommended to use --enable-threads.])
-           fi
-           ;;
-    esac
-    AC_SUBST(TCL_THREADS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SYMBOLS --
-#
-#      Specify if debugging symbols should be used.
-#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
-#
-# Arguments:
-#      none
-#
-#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
-#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
-#      Requires the following vars to be set in the Makefile:
-#              CFLAGS_DEFAULT
-#              LDFLAGS_DEFAULT
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-symbols
-#
-#      Defines the following vars:
-#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
-#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
-#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
-#                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_SYMBOLS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_CONFIG_CFLAGS])
-    AC_MSG_CHECKING([for build with symbols])
-    AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
-           [build with debugging symbols (default: off)]),
-       [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
-    if test "$tcl_ok" = "no"; then
-       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
-       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
-       AC_MSG_RESULT([no])
-    else
-       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
-       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
-       if test "$tcl_ok" = "yes"; then
-           AC_MSG_RESULT([yes (standard debugging)])
-       fi
-    fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-    AC_SUBST(CFLAGS_DEFAULT)
-    AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
-
-    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
-       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
-    fi
-
-    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
-       if test "$tcl_ok" = "all"; then
-           AC_MSG_RESULT([enabled symbols mem debugging])
-       else
-           AC_MSG_RESULT([enabled $tcl_ok debugging])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_LANGINFO --
-#
-#      Allows use of modern nl_langinfo check for better l10n.
-#      This is only relevant for Unix.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-langinfo=yes|no (default is yes)
-#
-#      Defines the following vars:
-#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_LANGINFO], [
-    AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
-           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
-       [langinfo_ok=$enableval], [langinfo_ok=yes])
-
-    HAVE_LANGINFO=0
-    if test "$langinfo_ok" = "yes"; then
-       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
-    fi
-    AC_MSG_CHECKING([whether to use nl_langinfo])
-    if test "$langinfo_ok" = "yes"; then
-       AC_CACHE_VAL(tcl_cv_langinfo_h, [
-           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
-                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
-       AC_MSG_RESULT([$tcl_cv_langinfo_h])
-       if test $tcl_cv_langinfo_h = yes; then
-           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
-       fi
-    else
-       AC_MSG_RESULT([$langinfo_ok])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_SYSTEM
-#
-#      Determine what the system is (some things cannot be easily checked
-#      on a feature-driven basis, alas). This can usually be done via the
-#      "uname" command.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Defines the following var:
-#
-#      system -        System/platform/version identification code.
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_SYSTEM], [
-    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
-       # TEA specific:
-       if test "${TEA_PLATFORM}" = "windows" ; then
-           tcl_cv_sys_version=windows
-       else
-           tcl_cv_sys_version=`uname -s`-`uname -r`
-           if test "$?" -ne 0 ; then
-               AC_MSG_WARN([can't find uname command])
-               tcl_cv_sys_version=unknown
-           else
-               if test "`uname -s`" = "AIX" ; then
-                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
-               fi
-               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
-                   tcl_cv_sys_version=NetBSD-Debian
-               fi
-           fi
-       fi
-    ])
-    system=$tcl_cv_sys_version
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_CFLAGS
-#
-#      Try to determine the proper flags to pass to the compiler
-#      for building shared libraries and other such nonsense.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substitutes the following vars:
-#
-#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
-#       LDFLAGS -      Flags to pass to the compiler when linking object
-#                       files into an executable application binary such
-#                       as tclsh.
-#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
-#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
-#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile.
-#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
-#                       of a shared library (may request position-independent
-#                       code, among other things).
-#       SHLIB_LD -      Base command to use for combining object files
-#                       into a shared library.
-#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
-#                       creating shared libraries.  This symbol typically
-#                       goes at the end of the "ld" commands that build
-#                       shared libraries. The value of the symbol defaults to
-#                       "${LIBS}" if all of the dependent libraries should
-#                       be specified when creating a shared library.  If
-#                       dependent libraries should not be specified (as on
-#                       SunOS 4.x, where they cause the link to fail, or in
-#                       general if Tcl and Tk aren't themselves shared
-#                       libraries), then this symbol has an empty string
-#                       as its value.
-#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
-#                       extensions.  An empty string means we don't know how
-#                       to use shared libraries on this platform.
-#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
-#                       in a static or shared library name, using the $PACKAGE_VERSION variable
-#                       to put the version in the right place.  This is used
-#                       by platforms that need non-standard library names.
-#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
-#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
-#                       on AIX, since a shared library needs to have
-#                       a .a extension whereas shared objects for loadable
-#                       extensions have a .so extension.  Defaults to
-#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
-#      CFLAGS_DEBUG -
-#                      Flags used when running the compiler in debug mode
-#      CFLAGS_OPTIMIZE -
-#                      Flags used when running the compiler in optimize mode
-#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_CFLAGS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-
-    # Step 0.a: Enable 64 bit support?
-
-    AC_MSG_CHECKING([if 64bit support is requested])
-    AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
-           [enable 64bit support (default: off)]),
-       [do64bit=$enableval], [do64bit=no])
-    AC_MSG_RESULT([$do64bit])
-
-    # Step 0.b: Enable Solaris 64 bit VIS support?
-
-    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
-    AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
-           [enable 64bit Sparc VIS support (default: off)]),
-       [do64bitVIS=$enableval], [do64bitVIS=no])
-    AC_MSG_RESULT([$do64bitVIS])
-    # Force 64bit on with VIS
-    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
-
-    # Step 0.c: Check if visibility support is available. Do this here so
-    # that platform specific alternatives can be used below if this fails.
-
-    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
-       tcl_cv_cc_visibility_hidden, [
-       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
-       AC_TRY_LINK([
-           extern __attribute__((__visibility__("hidden"))) void f(void);
-           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
-           tcl_cv_cc_visibility_hidden=no)
-       CFLAGS=$hold_cflags])
-    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
-       AC_DEFINE(MODULE_SCOPE,
-           [extern __attribute__((__visibility__("hidden")))],
-           [Compiler support for module scope symbols])
-       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
-    ])
-
-    # Step 0.d: Disable -rpath support?
-
-    AC_MSG_CHECKING([if rpath support is requested])
-    AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
-           [disable rpath support (default: on)]),
-       [doRpath=$enableval], [doRpath=yes])
-    AC_MSG_RESULT([$doRpath])
-
-    # Set the variable "system" to hold the name and version number
-    # for the system.
-
-    TEA_CONFIG_SYSTEM
-
-    # Require ranlib early so we can override it in special cases below.
-
-    AC_REQUIRE([AC_PROG_RANLIB])
-
-    # Set configuration options based on system name and version.
-    # This is similar to Tcl's unix/tcl.m4 except that we've added a
-    # "windows" case and removed some core-only vars.
-
-    do64bit_ok=no
-    # default to '{$LIBS}' and set to "" on per-platform necessary basis
-    SHLIB_LD_LIBS='${LIBS}'
-    # When ld needs options to work in 64-bit mode, put them in
-    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
-    # is disabled by the user. [Bug 1016796]
-    LDFLAGS_ARCH=""
-    UNSHARED_LIB_SUFFIX=""
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
-    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
-    TCL_LIB_VERSIONS_OK=ok
-    CFLAGS_DEBUG=-g
-    AS_IF([test "$GCC" = yes], [
-       CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
-    ], [
-       CFLAGS_OPTIMIZE=-O
-       CFLAGS_WARNING=""
-    ])
-    AC_CHECK_TOOL(AR, ar)
-    STLIB_LD='${AR} cr'
-    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
-    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
-    case $system in
-       # TEA specific:
-       windows)
-           MACHINE="X86"
-           if test "$do64bit" != "no" ; then
-               case "$do64bit" in
-                   amd64|x64|yes)
-                       MACHINE="AMD64" ; # default to AMD64 64-bit build
-                       ;;
-                   ia64)
-                       MACHINE="IA64"
-                       ;;
-               esac
-           fi
-
-           if test "$GCC" != "yes" ; then
-               if test "${SHARED_BUILD}" = "0" ; then
-                   runtime=-MT
-               else
-                   runtime=-MD
-               fi
-               case "x`echo \${VisualStudioVersion}`" in
-                   x1[[4-9]]*)
-                       lflags="${lflags} -nodefaultlib:libucrt.lib"
-                       TEA_ADD_LIBS([ucrt.lib])
-                   ;;
-                   *)
-                   ;;
-               esac
-
-                if test "$do64bit" != "no" ; then
-                   CC="cl.exe"
-                   RC="rc.exe"
-                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
-                   LINKBIN="link.exe"
-                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-                   # Avoid 'unresolved external symbol __security_cookie'
-                   # errors, c.f. http://support.microsoft.com/?id=894573
-                   TEA_ADD_LIBS([bufferoverflowU.lib])
-               else
-                   RC="rc"
-                   lflags="${lflags} -nologo"
-                   LINKBIN="link"
-                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-               fi
-           fi
-
-           if test "$GCC" = "yes"; then
-               # mingw gcc mode
-               AC_CHECK_TOOL(RC, windres)
-               CFLAGS_DEBUG="-g"
-               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-               SHLIB_LD='${CC} -shared'
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
-               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
-
-               AC_CACHE_CHECK(for cross-compile version of gcc,
-                       ac_cv_cross,
-                       AC_TRY_COMPILE([
-                           #ifdef _WIN32
-                               #error cross-compiler
-                           #endif
-                       ], [],
-                       ac_cv_cross=yes,
-                       ac_cv_cross=no)
-                     )
-                     if test "$ac_cv_cross" = "yes"; then
-                       case "$do64bit" in
-                           amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
-                               LD="x86_64-w64-mingw32-ld"
-                               AR="x86_64-w64-mingw32-ar"
-                               RANLIB="x86_64-w64-mingw32-ranlib"
-                               RC="x86_64-w64-mingw32-windres"
-                           ;;
-                           *)
-                               CC="i686-w64-mingw32-gcc"
-                               LD="i686-w64-mingw32-ld"
-                               AR="i686-w64-mingw32-ar"
-                               RANLIB="i686-w64-mingw32-ranlib"
-                               RC="i686-w64-mingw32-windres"
-                           ;;
-                       esac
-               fi
-
-           else
-               SHLIB_LD="${LINKBIN} -dll ${lflags}"
-               # link -lib only works when -lib is the first arg
-               STLIB_LD="${LINKBIN} -lib ${lflags}"
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
-               PATHTYPE=-w
-               # For information on what debugtype is most useful, see:
-               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
-               # and also
-               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
-               # This essentially turns it all on.
-               LDFLAGS_DEBUG="-debug -debugtype:cv"
-               LDFLAGS_OPTIMIZE="-release"
-               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
-               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
-           fi
-
-           SHLIB_SUFFIX=".dll"
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
-
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       AIX-*)
-           AS_IF([test "$GCC" != "yes"], [
-               # AIX requires the _r compiler when gcc isn't being used
-               case "${CC}" in
-                   *_r|*_r\ *)
-                       # ok ...
-                       ;;
-                   *)
-                       # Make sure only first arg gets _r
-                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
-                       ;;
-               esac
-               AC_MSG_RESULT([Using $CC for compiling with threads])
-           ])
-           LIBS="$LIBS -lc"
-           SHLIB_CFLAGS=""
-           SHLIB_SUFFIX=".so"
-
-           LD_LIBRARY_PATH_VAR="LIBPATH"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS -q64"
-                   LDFLAGS_ARCH="-q64"
-                   RANLIB="${RANLIB} -X64"
-                   AR="${AR} -X64"
-                   SHLIB_LD_FLAGS="-b64"
-               ])
-           ])
-
-           AS_IF([test "`uname -m`" = ia64], [
-               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
-               ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ], [
-               AS_IF([test "$GCC" = yes], [
-                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
-               ], [
-                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
-                   LDFLAGS="$LDFLAGS -brtl"
-               ])
-               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       BeOS*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} -nostart'
-           SHLIB_SUFFIX=".so"
-
-           #-----------------------------------------------------------
-           # Check for inet_ntoa in -lbind, for BeOS (which also needs
-           # -lsocket, even if the network functions are in -lnet which
-           # is always linked to, for compatibility.
-           #-----------------------------------------------------------
-           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
-           ;;
-       BSD/OS-2.1*|BSD/OS-3*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="shlicc -r"
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       BSD/OS-4.*)
-           SHLIB_CFLAGS="-export-dynamic -fPIC"
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       CYGWIN_*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".dll"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
-           EXEEXT=".exe"
-           do64bit_ok=yes
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       dgux*)
-           SHLIB_CFLAGS="-K PIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       Haiku*)
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
-           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
-           ;;
-       HP-UX-*.11.*)
-           # Use updated header definitions where possible
-           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
-           # TEA specific: Needed by Tcl, but not most extensions
-           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
-           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
-
-           AS_IF([test "`uname -m`" = ia64], [
-               SHLIB_SUFFIX=".so"
-           ], [
-               SHLIB_SUFFIX=".sl"
-           ])
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ])
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               CFLAGS="$CFLAGS -z"
-           ])
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = "yes"], [
-               AS_IF([test "$GCC" = yes], [
-                   case `${CC} -dumpmachine` in
-                       hppa64*)
-                           # 64-bit gcc in use.  Fix flags for GNU ld.
-                           do64bit_ok=yes
-                           SHLIB_LD='${CC} -shared'
-                           AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-                           ;;
-                       *)
-                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
-                           ;;
-                   esac
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS +DD64"
-                   LDFLAGS_ARCH="+DD64"
-               ])
-           ]) ;;
-       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
-           SHLIB_SUFFIX=".sl"
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               SHLIB_LD_LIBS=""
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ]) ;;
-       IRIX-5.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AC_LIBOBJ(mkstemp)
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           ;;
-       IRIX-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [
-               CFLAGS="$CFLAGS -mabi=n32"
-               LDFLAGS="$LDFLAGS -mabi=n32"
-           ], [
-               case $system in
-                   IRIX-6.3)
-                       # Use to build 6.2 compatible binaries on 6.3.
-                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
-                       ;;
-                   *)
-                       CFLAGS="$CFLAGS -n32"
-                       ;;
-               esac
-               LDFLAGS="$LDFLAGS -n32"
-           ])
-           ;;
-       IRIX64-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-
-           # Check to enable 64-bit flags for compiler/linker
-
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported by gcc])
-               ], [
-                   do64bit_ok=yes
-                   SHLIB_LD="ld -64 -shared -rdata_shared"
-                   CFLAGS="$CFLAGS -64"
-                   LDFLAGS_ARCH="-64"
-               ])
-           ])
-           ;;
-       Linux*|GNU*|NetBSD-Debian)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-
-           # TEA specific:
-           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
-           AS_IF([test $do64bit = yes], [
-               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
-                   hold_cflags=$CFLAGS
-                   CFLAGS="$CFLAGS -m64"
-                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
-                   CFLAGS=$hold_cflags])
-               AS_IF([test $tcl_cv_cc_m64 = yes], [
-                   CFLAGS="$CFLAGS -m64"
-                   do64bit_ok=yes
-               ])
-          ])
-
-           # The combo of gcc + glibc has a bug related to inlining of
-           # functions like strtod(). The -fno-builtin flag should address
-           # this problem but it does not work. The -fno-inline flag is kind
-           # of overkill but it works. Disable inlining only when one of the
-           # files in compat/*.c is being linked in.
-
-           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
-           ;;
-       Lynx*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           CFLAGS_OPTIMIZE=-02
-           SHLIB_LD='${CC} -shared'
-           LD_FLAGS="-Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           ;;
-       OpenBSD-*)
-           arch=`arch -s`
-           case "$arch" in
-           alpha|sparc64)
-               SHLIB_CFLAGS="-fPIC"
-               ;;
-           *)
-               SHLIB_CFLAGS="-fpic"
-               ;;
-           esac
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
-           CFLAGS_OPTIMIZE="-O2"
-           # On OpenBSD:       Compile with -pthread
-           #           Don't link with -lpthread
-           LIBS=`echo $LIBS | sed s/-lpthread//`
-           CFLAGS="$CFLAGS -pthread"
-           # OpenBSD doesn't do version numbers with dots.
-           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       NetBSD-*)
-           # NetBSD has ELF and can use 'cc -shared' to build shared libs
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           # The -pthread needs to go in the CFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS -pthread"
-           LDFLAGS="$LDFLAGS -pthread"
-           ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
-       Darwin-*)
-           CFLAGS_OPTIMIZE="-Os"
-           SHLIB_CFLAGS="-fno-common"
-           # To avoid discrepancies between what headers configure sees during
-           # preprocessing tests and compiling tests, move any -isysroot and
-           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
-           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
-           CFLAGS="`echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
-           AS_IF([test $do64bit = yes], [
-               case `arch` in
-                   ppc)
-                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
-                               tcl_cv_cc_arch_ppc64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
-                                   tcl_cv_cc_arch_ppc64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           do64bit_ok=yes
-                       ]);;
-                   i386)
-                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
-                               tcl_cv_cc_arch_x86_64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
-                                   tcl_cv_cc_arch_x86_64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           do64bit_ok=yes
-                       ]);;
-                   *)
-                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
-               esac
-           ], [
-               # Check for combined 32-bit and 64-bit fat build
-               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
-                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
-                   fat_32_64=yes])
-           ])
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
-           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_single_module = yes], [
-               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
-           ])
-           # TEA specific: link shlib with current and compatibility version flags
-           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
-           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
-           SHLIB_SUFFIX=".dylib"
-           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
-           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
-                   tcl_cv_ld_search_paths_first, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
-                       tcl_cv_ld_search_paths_first=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-           ])
-           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
-                   [Compiler support for module scope symbols])
-               tcl_cv_cc_visibility_hidden=yes
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
-           # TEA specific: for combined 32 & 64 bit fat builds of Tk
-           # extensions, verify that 64-bit build is possible.
-           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
-                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
-                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
-                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
-                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
-                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
-                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
-                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
-                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               # remove 64-bit arch flags from CFLAGS et al. if configuration
-               # does not support 64-bit.
-               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
-                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
-                   for v in CFLAGS CPPFLAGS LDFLAGS; do
-                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
-                   done])
-           ])
-           ;;
-       OS/390-*)
-           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
-           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
-               [Should OS/390 do the right thing with sockets?])
-           ;;
-       OSF1-V*)
-           # Digital OSF/1
-           SHLIB_CFLAGS=""
-           AS_IF([test "$SHARED_BUILD" = 1], [
-               SHLIB_LD='ld -shared -expect_unresolved "*"'
-           ], [
-               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
-           ])
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
-               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
-           # see pthread_intro(3) for pthread support on osf1, k.furukawa
-           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
-           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
-           LIBS=`echo $LIBS | sed s/-lpthreads//`
-           AS_IF([test "$GCC" = yes], [
-               LIBS="$LIBS -lpthread -lmach -lexc"
-           ], [
-               CFLAGS="$CFLAGS -pthread"
-               LDFLAGS="$LDFLAGS -pthread"
-           ])
-           ;;
-       QNX-6*)
-           # QNX RTP
-           # This may work for all QNX, but it was only reported for v6.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="ld -Bshareable -x"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SCO_SV-3.2*)
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_CFLAGS="-fPIC -melf"
-               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
-           ], [
-               SHLIB_CFLAGS="-Kpic -belf"
-               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
-           ])
-           SHLIB_LD="ld -G"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SunOS-5.[[0-6]])
-           # Careful to not let 5.10+ fall into this case
-
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       SunOS-5*)
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               arch=`isainfo`
-               AS_IF([test "$arch" = "sparcv9 sparc"], [
-                   AS_IF([test "$GCC" = yes], [
-                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
-                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
-                       ], [
-                           do64bit_ok=yes
-                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
-                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
-                           SHLIB_CFLAGS="-fPIC"
-                       ])
-                   ], [
-                       do64bit_ok=yes
-                       AS_IF([test "$do64bitVIS" = yes], [
-                           CFLAGS="$CFLAGS -xarch=v9a"
-                           LDFLAGS_ARCH="-xarch=v9a"
-                       ], [
-                           CFLAGS="$CFLAGS -xarch=v9"
-                           LDFLAGS_ARCH="-xarch=v9"
-                       ])
-                       # Solaris 64 uses this as well
-                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
-                   ])
-               ], [AS_IF([test "$arch" = "amd64 i386"], [
-                   AS_IF([test "$GCC" = yes], [
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               do64bit_ok=yes
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
-                       esac
-                   ], [
-                       do64bit_ok=yes
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               CFLAGS="$CFLAGS -xarch=amd64"
-                               LDFLAGS="$LDFLAGS -xarch=amd64";;
-                       esac
-                   ])
-               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
-           ])
-
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-               AS_IF([test "$do64bit_ok" = yes], [
-                   AS_IF([test "$arch" = "sparcv9 sparc"], [
-                       # We need to specify -static-libgcc or we need to
-                       # add the path to the sparv9 libgcc.
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
-                       # for finding sparcv9 libgcc, get the regular libgcc
-                       # path, remove so name and append 'sparcv9'
-                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
-                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
-                   ], [AS_IF([test "$arch" = "amd64 i386"], [
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
-                   ])])
-               ])
-           ], [
-               case $system in
-                   SunOS-5.[[1-9]][[0-9]]*)
-                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
-                   *)
-                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
-               esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ])
-           ;;
-       UNIX_SV* | UnixWare-5*)
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
-           # that don't grok the -Bexport option.  Test that it does.
-           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_Bexport = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-    esac
-
-    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
-       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
-    ])
-
-dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
-dnl # until the end of configure, as configure's compile and link tests use
-dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
-dnl # preprocessing tests use only CPPFLAGS.
-    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
-
-    # Add in the arch flags late to ensure it wasn't removed.
-    # Not necessary in TEA, but this is aligned with core
-    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
-
-    # If we're running gcc, then change the C flags for compiling shared
-    # libraries to the right flags for gcc, instead of those for the
-    # standard manufacturer compiler.
-
-    AS_IF([test "$GCC" = yes], [
-       case $system in
-           AIX-*) ;;
-           BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
-           IRIX*) ;;
-           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
-           Darwin-*) ;;
-           SCO_SV-3.2*) ;;
-           windows) ;;
-           *) SHLIB_CFLAGS="-fPIC" ;;
-       esac])
-
-    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-       AC_DEFINE(MODULE_SCOPE, [extern],
-           [No Compiler support for module scope symbols])
-    ])
-
-    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
-    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
-
-    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
-       AC_CACHE_CHECK(for SEH support in compiler,
-           tcl_cv_seh,
-       AC_TRY_RUN([
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-
-           int main(int argc, char** argv) {
-               int a, b = 0;
-               __try {
-                   a = 666 / b;
-               }
-               __except (EXCEPTION_EXECUTE_HANDLER) {
-                   return 0;
-               }
-               return 1;
-           }
-       ],
-           tcl_cv_seh=yes,
-           tcl_cv_seh=no,
-           tcl_cv_seh=no)
-       )
-       if test "$tcl_cv_seh" = "no" ; then
-           AC_DEFINE(HAVE_NO_SEH, 1,
-                   [Defined when mingw does not support SEH])
-       fi
-
-       #
-       # Check to see if the excpt.h include file provided contains the
-       # definition for EXCEPTION_DISPOSITION; if not, which is the case
-       # with Cygwin's version as of 2002-04-10, define it to be int,
-       # sufficient for getting the current code to work.
-       #
-       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
-           tcl_cv_eh_disposition,
-           AC_TRY_COMPILE([
-#          define WIN32_LEAN_AND_MEAN
-#          include <windows.h>
-#          undef WIN32_LEAN_AND_MEAN
-           ],[
-               EXCEPTION_DISPOSITION x;
-           ],
-               tcl_cv_eh_disposition=yes,
-               tcl_cv_eh_disposition=no)
-       )
-       if test "$tcl_cv_eh_disposition" = "no" ; then
-       AC_DEFINE(EXCEPTION_DISPOSITION, int,
-               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
-       fi
-
-       # Check to see if winnt.h defines CHAR, SHORT, and LONG
-       # even if VOID has already been #defined. The win32api
-       # used by mingw and cygwin is known to do this.
-
-       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
-           tcl_cv_winnt_ignore_void,
-           AC_TRY_COMPILE([
-#define VOID void
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-           ], [
-               CHAR c;
-               SHORT s;
-               LONG l;
-           ],
-        tcl_cv_winnt_ignore_void=yes,
-        tcl_cv_winnt_ignore_void=no)
-       )
-       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
-           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
-                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
-       fi
-    fi
-
-       # See if the compiler supports casting to a union type.
-       # This is used to stop gcc from printing a compiler
-       # warning when initializing a union member.
-
-       AC_CACHE_CHECK(for cast to union support,
-           tcl_cv_cast_to_union,
-           AC_TRY_COMPILE([],
-           [
-                 union foo { int i; double d; };
-                 union foo f = (union foo) (int) 0;
-           ],
-           tcl_cv_cast_to_union=yes,
-           tcl_cv_cast_to_union=no)
-       )
-       if test "$tcl_cv_cast_to_union" = "yes"; then
-           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
-                   [Defined when compiler supports casting to union type.])
-       fi
-
-       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
-
-    AC_SUBST(CFLAGS_DEBUG)
-    AC_SUBST(CFLAGS_OPTIMIZE)
-    AC_SUBST(CFLAGS_WARNING)
-
-    AC_SUBST(STLIB_LD)
-    AC_SUBST(SHLIB_LD)
-
-    AC_SUBST(SHLIB_LD_LIBS)
-    AC_SUBST(SHLIB_CFLAGS)
-
-    AC_SUBST(LD_LIBRARY_PATH_VAR)
-
-    # These must be called after we do the basic CFLAGS checks and
-    # verify any possible 64-bit or similar switches are necessary
-    TEA_TCL_EARLY_FLAGS
-    TEA_TCL_64BIT_FLAGS
-])
-
-#--------------------------------------------------------------------
-# TEA_SERIAL_PORT
-#
-#      Determine which interface to use to talk to the serial port.
-#      Note that #include lines must begin in leftmost column for
-#      some compilers to recognize them as preprocessor directives,
-#      and some build environments have stdin not pointing at a
-#      pseudo-terminal (usually /dev/null instead.)
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines only one of the following vars:
-#              HAVE_SYS_MODEM_H
-#              USE_TERMIOS
-#              USE_TERMIO
-#              USE_SGTTY
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_SERIAL_PORT], [
-    AC_CHECK_HEADERS(sys/modem.h)
-    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
-    AC_TRY_RUN([
-#include <termios.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termio.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termios.h>
-#include <errno.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <termio.h>
-#include <errno.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-#include <errno.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
-    fi])
-    case $tcl_cv_api_serial in
-       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
-       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
-       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_PATH_X
-#
-#      Locate the X11 header files and the X11 library archive.  Try
-#      the ac_path_x macro first, but if it doesn't find the X stuff
-#      (e.g. because there's no xmkmf program) then check through
-#      a list of possible directories.  Under some conditions the
-#      autoconf macro will return an include directory that contains
-#      no include files, so double-check its result just to be safe.
-#
-#      This should be called after TEA_CONFIG_CFLAGS as setting the
-#      LIBS line can confuse some configure macro magic.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets the following vars:
-#              XINCLUDES
-#              XLIBSW
-#              PKG_LIBS (appends to)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_X], [
-    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
-       TEA_PATH_UNIX_X
-    fi
-])
-
-AC_DEFUN([TEA_PATH_UNIX_X], [
-    AC_PATH_X
-    not_really_there=""
-    if test "$no_x" = ""; then
-       if test "$x_includes" = ""; then
-           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
-       else
-           if test ! -r $x_includes/X11/Xlib.h; then
-               not_really_there="yes"
-           fi
-       fi
-    fi
-    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
-       AC_MSG_CHECKING([for X11 header files])
-       found_xincludes="no"
-       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
-       if test "$found_xincludes" = "no"; then
-           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
-           for i in $dirs ; do
-               if test -r $i/X11/Xlib.h; then
-                   AC_MSG_RESULT([$i])
-                   XINCLUDES=" -I$i"
-                   found_xincludes="yes"
-                   break
-               fi
-           done
-       fi
-    else
-       if test "$x_includes" != ""; then
-           XINCLUDES="-I$x_includes"
-           found_xincludes="yes"
-       fi
-    fi
-    if test "$found_xincludes" = "no"; then
-       AC_MSG_RESULT([couldn't find any!])
-    fi
-
-    if test "$no_x" = yes; then
-       AC_MSG_CHECKING([for X11 libraries])
-       XLIBSW=nope
-       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
-       for i in $dirs ; do
-           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
-               AC_MSG_RESULT([$i])
-               XLIBSW="-L$i -lX11"
-               x_libraries="$i"
-               break
-           fi
-       done
-    else
-       if test "$x_libraries" = ""; then
-           XLIBSW=-lX11
-       else
-           XLIBSW="-L$x_libraries -lX11"
-       fi
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_MSG_RESULT([could not find any!  Using -lX11.])
-       XLIBSW=-lX11
-    fi
-    # TEA specific:
-    if test x"${XLIBSW}" != x ; then
-       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BLOCKING_STYLE
-#
-#      The statements below check for systems where POSIX-style
-#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
-#      On these systems (mostly older ones), use the old BSD-style
-#      FIONBIO approach instead.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              HAVE_SYS_IOCTL_H
-#              HAVE_SYS_FILIO_H
-#              USE_FIONBIO
-#              O_NONBLOCK
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BLOCKING_STYLE], [
-    AC_CHECK_HEADERS(sys/ioctl.h)
-    AC_CHECK_HEADERS(sys/filio.h)
-    TEA_CONFIG_SYSTEM
-    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
-    case $system in
-       OSF*)
-           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
-           AC_MSG_RESULT([FIONBIO])
-           ;;
-       *)
-           AC_MSG_RESULT([O_NONBLOCK])
-           ;;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_TIME_HANDLER
-#
-#      Checks how the system deals with time.h, what time structures
-#      are used on the system, and what fields the structures have.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              USE_DELTA_FOR_TZ
-#              HAVE_TM_GMTOFF
-#              HAVE_TM_TZADJ
-#              HAVE_TIMEZONE_VAR
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TIME_HANDLER], [
-    AC_CHECK_HEADERS(sys/time.h)
-    AC_HEADER_TIME
-    AC_STRUCT_TIMEZONE
-
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
-
-    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
-           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
-    if test $tcl_cv_member_tm_tzadj = yes ; then
-       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
-    fi
-
-    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
-           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
-    if test $tcl_cv_member_tm_gmtoff = yes ; then
-       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
-    fi
-
-    #
-    # Its important to include time.h in this check, as some systems
-    # (like convex) have timezone functions, etc.
-    #
-    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
-       AC_TRY_COMPILE([#include <time.h>],
-           [extern long timezone;
-           timezone += 1;
-           exit (0);],
-           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
-    if test $tcl_cv_timezone_long = yes ; then
-       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-    else
-       #
-       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
-       #
-       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
-           AC_TRY_COMPILE([#include <time.h>],
-               [extern time_t timezone;
-               timezone += 1;
-               exit (0);],
-               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
-       if test $tcl_cv_timezone_time = yes ; then
-           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BUGGY_STRTOD
-#
-#      Under Solaris 2.4, strtod returns the wrong value for the
-#      terminating character under some conditions.  Check for this
-#      and if the problem exists use a substitute procedure
-#      "fixstrtod" (provided by Tcl) that corrects the error.
-#      Also, on Compaq's Tru64 Unix 5.0,
-#      strtod(" ") returns 0.0 instead of a failure to convert.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Might defines some of the following vars:
-#              strtod (=fixstrtod)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BUGGY_STRTOD], [
-    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
-    if test "$tcl_strtod" = 1; then
-       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
-           AC_TRY_RUN([
-               extern double strtod();
-               int main() {
-                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
-                   char *term;
-                   double value;
-                   value = strtod(infString, &term);
-                   if ((term != infString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(nanString, &term);
-                   if ((term != nanString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(spaceString, &term);
-                   if (term == (spaceString+1)) {
-                       exit(1);
-                   }
-                   exit(0);
-               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
-                   tcl_cv_strtod_buggy=buggy)])
-       if test "$tcl_cv_strtod_buggy" = buggy; then
-           AC_LIBOBJ([fixstrtod])
-           USE_COMPAT=1
-           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_EARLY_FLAGS
-#
-#      Check for what flags are needed to be passed so the correct OS
-#      features are available.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              _ISOC99_SOURCE
-#              _LARGEFILE64_SOURCE
-#              _LARGEFILE_SOURCE64
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_EARLY_FLAG],[
-    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
-       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
-           AC_TRY_COMPILE([[#define ]$1[ 1
-]$2], $3,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
-    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
-       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
-       tcl_flags="$tcl_flags $1"
-    fi
-])
-
-AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
-    AC_MSG_CHECKING([for required early compiler flags])
-    tcl_flags=""
-    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
-       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
-       [struct stat64 buf; int i = stat64("/", &buf);])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
-       [char *p = (char *)open64;])
-    if test "x${tcl_flags}" = "x" ; then
-       AC_MSG_RESULT([none])
-    else
-       AC_MSG_RESULT([${tcl_flags}])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_64BIT_FLAGS
-#
-#      Check for what is defined in the way of 64-bit features.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              TCL_WIDE_INT_IS_LONG
-#              TCL_WIDE_INT_TYPE
-#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
-#              HAVE_STRUCT_STAT64
-#              HAVE_TYPE_OFF64_T
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
-    AC_MSG_CHECKING([for 64-bit integer type])
-    AC_CACHE_VAL(tcl_cv_type_64bit,[
-       tcl_cv_type_64bit=none
-       # See if the compiler knows natively about __int64
-       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
-           tcl_type_64bit=__int64, tcl_type_64bit="long long")
-       # See if we could use long anyway  Note that we substitute in the
-       # type that is our current guess for a 64-bit type inside this check
-       # program, so it should be modified only carefully...
-        AC_TRY_COMPILE(,[switch (0) {
-            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
-        }],tcl_cv_type_64bit=${tcl_type_64bit})])
-    if test "${tcl_cv_type_64bit}" = none ; then
-       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
-       AC_MSG_RESULT([yes])
-    elif test "${tcl_cv_type_64bit}" = "__int64" \
-               -a "${TEA_PLATFORM}" = "windows" ; then
-       # TEA specific: We actually want to use the default tcl.h checks in
-       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
-       AC_MSG_RESULT([using Tcl header defaults])
-    else
-       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
-           [What type should be used to define wide integers?])
-       AC_MSG_RESULT([${tcl_cv_type_64bit}])
-
-       # Now check for auxiliary declarations
-       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 p;],
-               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
-       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
-            p = readdir64(d); rewinddir64(d); closedir64(d);],
-               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
-       if test "x${tcl_cv_DIR64}" = "xyes" ; then
-           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
-           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
-],
-               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
-       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
-       fi
-
-       AC_CHECK_FUNCS(open64 lseek64)
-       AC_MSG_CHECKING([for off64_t])
-       AC_CACHE_VAL(tcl_cv_type_off64_t,[
-           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
-],
-               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
-       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
-       dnl functions lseek64 and open64 are defined.
-       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
-               test "x${ac_cv_func_lseek64}" = "xyes" && \
-               test "x${ac_cv_func_open64}" = "xyes" ; then
-           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
-           AC_MSG_RESULT([yes])
-       else
-           AC_MSG_RESULT([no])
-       fi
-    fi
-])
-
-##
-## Here ends the standard Tcl configuration bits and starts the
-## TEA specific functions
-##
-
-#------------------------------------------------------------------------
-# TEA_INIT --
-#
-#      Init various Tcl Extension Architecture (TEA) variables.
-#      This should be the first called TEA_* macro.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              CYGPATH
-#              EXEEXT
-#      Defines only:
-#              TEA_VERSION
-#              TEA_INITED
-#              TEA_PLATFORM (windows or unix)
-#
-# "cygpath" is used on windows to generate native path names for include
-# files. These variables should only be used with the compiler and linker
-# since they generate native path names.
-#
-# EXEEXT
-#      Select the executable extension based on the host type.  This
-#      is a lightweight replacement for AC_EXEEXT that doesn't require
-#      a compiler.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INIT], [
-    TEA_VERSION="3.13"
-
-    AC_MSG_CHECKING([TEA configuration])
-    if test x"${PACKAGE_NAME}" = x ; then
-       AC_MSG_ERROR([
-The PACKAGE_NAME variable must be defined by your TEA configure.ac])
-    fi
-    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
-
-    # If the user did not set CFLAGS, set it now to keep macros
-    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
-    if test "${CFLAGS+set}" != "set" ; then
-       CFLAGS=""
-    fi
-
-    case "`uname -s`" in
-       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
-           EXEEXT=".exe"
-           TEA_PLATFORM="windows"
-           ;;
-       *CYGWIN_*)
-           EXEEXT=".exe"
-           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
-           ;;
-       *)
-           CYGPATH=echo
-           # Maybe we are cross-compiling....
-           case ${host_alias} in
-               *mingw32*)
-               EXEEXT=".exe"
-               TEA_PLATFORM="windows"
-               ;;
-           *)
-               EXEEXT=""
-               TEA_PLATFORM="unix"
-               ;;
-           esac
-           ;;
-    esac
-
-    # Check if exec_prefix is set. If not use fall back to prefix.
-    # Note when adjusted, so that TEA_PREFIX can correct for this.
-    # This is needed for recursive configures, since autoconf propagates
-    # $prefix, but not $exec_prefix (doh!).
-    if test x$exec_prefix = xNONE ; then
-       exec_prefix_default=yes
-       exec_prefix=$prefix
-    fi
-
-    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
-
-    AC_SUBST(EXEEXT)
-    AC_SUBST(CYGPATH)
-
-    # This package name must be replaced statically for AC_SUBST to work
-    AC_SUBST(PKG_LIB_FILE)
-    # Substitute STUB_LIB_FILE in case package creates a stub library too.
-    AC_SUBST(PKG_STUB_LIB_FILE)
-
-    # We AC_SUBST these here to ensure they are subst'ed,
-    # in case the user doesn't call TEA_ADD_...
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-    AC_SUBST(PKG_TCL_SOURCES)
-    AC_SUBST(PKG_HEADERS)
-    AC_SUBST(PKG_INCLUDES)
-    AC_SUBST(PKG_LIBS)
-    AC_SUBST(PKG_CFLAGS)
-
-    # Configure the installer.
-    TEA_INSTALLER
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_SOURCES
-#              PKG_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       case $i in
-           [\$]*)
-               # allow $-var names
-               PKG_SOURCES="$PKG_SOURCES $i"
-               PKG_OBJECTS="$PKG_OBJECTS $i"
-               ;;
-           *)
-               # check for existence - allows for generic/win/unix VPATH
-               # To add more dirs here (like 'src'), you have to update VPATH
-               # in Makefile.in as well
-               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-                   -a ! -f "${srcdir}/macosx/$i" \
-                   ; then
-                   AC_MSG_ERROR([could not find source file '$i'])
-               fi
-               PKG_SOURCES="$PKG_SOURCES $i"
-               # this assumes it is in a VPATH dir
-               i=`basename $i`
-               # handle user calling this before or after TEA_SETUP_COMPILER
-               if test x"${OBJEXT}" != x ; then
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-               else
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-               fi
-               PKG_OBJECTS="$PKG_OBJECTS $j"
-               ;;
-       esac
-    done
-    AC_SUBST(PKG_SOURCES)
-    AC_SUBST(PKG_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_STUB_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_STUB_SOURCES
-#              PKG_STUB_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_STUB_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence - allows for generic/win/unix VPATH
-       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-           -a ! -f "${srcdir}/macosx/$i" \
-           ; then
-           AC_MSG_ERROR([could not find stub source file '$i'])
-       fi
-       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
-       # this assumes it is in a VPATH dir
-       i=`basename $i`
-       # handle user calling this before or after TEA_SETUP_COMPILER
-       if test x"${OBJEXT}" != x ; then
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-       else
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-       fi
-       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
-    done
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_TCL_SOURCES --
-#
-#      Specify one or more Tcl source files.  These should be platform
-#      independent runtime files.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_TCL_SOURCES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_TCL_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
-       fi
-       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
-    done
-    AC_SUBST(PKG_TCL_SOURCES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_HEADERS --
-#
-#      Specify one or more source headers.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_HEADERS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_HEADERS], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
-       fi
-       PKG_HEADERS="$PKG_HEADERS $i"
-    done
-    AC_SUBST(PKG_HEADERS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_INCLUDES --
-#
-#      Specify one or more include dirs.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_INCLUDES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_INCLUDES], [
-    vars="$@"
-    for i in $vars; do
-       PKG_INCLUDES="$PKG_INCLUDES $i"
-    done
-    AC_SUBST(PKG_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_LIBS --
-#
-#      Specify one or more libraries.  Users should check for
-#      the right platform before adding to their list.  For Windows,
-#      libraries provided in "foo.lib" format will be converted to
-#      "-lfoo" when using GCC (mingw).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_LIBS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_LIBS], [
-    vars="$@"
-    for i in $vars; do
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
-           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
-       fi
-       PKG_LIBS="$PKG_LIBS $i"
-    done
-    AC_SUBST(PKG_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CFLAGS --
-#
-#      Specify one or more CFLAGS.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_CFLAGS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CFLAGS], [
-    PKG_CFLAGS="$PKG_CFLAGS $@"
-    AC_SUBST(PKG_CFLAGS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CLEANFILES --
-#
-#      Specify one or more CLEANFILES.
-#
-# Arguments:
-#      one or more file names to clean target
-#
-# Results:
-#
-#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CLEANFILES], [
-    CLEANFILES="$CLEANFILES $@"
-])
-
-#------------------------------------------------------------------------
-# TEA_PREFIX --
-#
-#      Handle the --prefix=... option by defaulting to what Tcl gave
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      If --prefix or --exec-prefix was not specified, $prefix and
-#      $exec_prefix will be set to the values given to Tcl when it was
-#      configured.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_PREFIX], [
-    if test "${prefix}" = "NONE"; then
-       prefix_default=yes
-       if test x"${TCL_PREFIX}" != x; then
-           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
-           prefix=${TCL_PREFIX}
-       else
-           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
-           prefix=/usr/local
-       fi
-    fi
-    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
-       -o x"${exec_prefix_default}" = x"yes" ; then
-       if test x"${TCL_EXEC_PREFIX}" != x; then
-           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
-           exec_prefix=${TCL_EXEC_PREFIX}
-       else
-           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
-           exec_prefix=$prefix
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER_CC --
-#
-#      Do compiler checks the way we want.  This is just a replacement
-#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER_CC], [
-    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
-    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
-
-    AC_PROG_CC
-    AC_PROG_CPP
-
-    #--------------------------------------------------------------------
-    # Checks to see if the make program sets the $MAKE variable.
-    #--------------------------------------------------------------------
-
-    AC_PROG_MAKE_SET
-
-    #--------------------------------------------------------------------
-    # Find ranlib
-    #--------------------------------------------------------------------
-
-    AC_CHECK_TOOL(RANLIB, ranlib)
-
-    #--------------------------------------------------------------------
-    # Determines the correct binary file extension (.o, .obj, .exe etc.)
-    #--------------------------------------------------------------------
-
-    AC_OBJEXT
-    AC_EXEEXT
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER --
-#
-#      Do compiler checks that use the compiler.  This must go after
-#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER], [
-    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
-    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
-
-    #------------------------------------------------------------------------
-    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
-    # It makes compiling go faster.  (This is only a performance feature.)
-    #------------------------------------------------------------------------
-
-    if test -z "$no_pipe" -a -n "$GCC"; then
-       AC_CACHE_CHECK([if the compiler understands -pipe],
-           tcl_cv_cc_pipe, [
-           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
-           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
-           CFLAGS=$hold_cflags])
-       if test $tcl_cv_cc_pipe = yes; then
-           CFLAGS="$CFLAGS -pipe"
-       fi
-    fi
-
-    #--------------------------------------------------------------------
-    # Common compiler flag setup
-    #--------------------------------------------------------------------
-
-    AC_C_BIGENDIAN
-])
-
-#------------------------------------------------------------------------
-# TEA_MAKE_LIB --
-#
-#      Generate a line that can be used to build a shared/unshared library
-#      in a platform independent manner.
-#
-# Arguments:
-#      none
-#
-#      Requires:
-#
-# Results:
-#
-#      Defines the following vars:
-#      CFLAGS -        Done late here to note disturb other AC macros
-#       MAKE_LIB -      Command to execute to build the Tcl library;
-#                       differs depending on whether or not Tcl is being
-#                       compiled as a shared library.
-#      MAKE_SHARED_LIB Makefile rule for building a shared library
-#      MAKE_STATIC_LIB Makefile rule for building a static library
-#      MAKE_STUB_LIB   Makefile rule for building a stub library
-#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
-#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_MAKE_LIB], [
-    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
-       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
-       AC_EGREP_CPP([manifest needed], [
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-print("manifest needed")
-#endif
-       ], [
-       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
-       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
-       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
-       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
-       TEA_ADD_CLEANFILES([*.manifest])
-       ])
-       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
-    else
-       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
-       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
-    fi
-
-    if test "${SHARED_BUILD}" = "1" ; then
-       MAKE_LIB="${MAKE_SHARED_LIB} "
-    else
-       MAKE_LIB="${MAKE_STATIC_LIB} "
-    fi
-
-    #--------------------------------------------------------------------
-    # Shared libraries and static libraries have different names.
-    # Use the double eval to make sure any variables in the suffix is
-    # substituted. (@@@ Might not be necessary anymore)
-    #--------------------------------------------------------------------
-
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       if test "${SHARED_BUILD}" = "1" ; then
-           # We force the unresolved linking of symbols that are really in
-           # the private libraries of Tcl and Tk.
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
-           fi
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
-           if test "$GCC" = "yes"; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
-           fi
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-       else
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-           if test "$GCC" = "yes"; then
-               PKG_LIB_FILE=lib${PKG_LIB_FILE}
-           fi
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-       if test "$GCC" = "yes"; then
-           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
-       fi
-       # These aren't needed on Windows (either MSVC or gcc)
-       RANLIB=:
-       RANLIB_STUB=:
-    else
-       RANLIB_STUB="${RANLIB}"
-       if test "${SHARED_BUILD}" = "1" ; then
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
-           fi
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-           RANLIB=:
-       else
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-    fi
-
-    # These are escaped so that only CFLAGS is picked up at configure time.
-    # The other values will be substituted at make time.
-    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
-    if test "${SHARED_BUILD}" = "1" ; then
-       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
-    fi
-
-    AC_SUBST(MAKE_LIB)
-    AC_SUBST(MAKE_SHARED_LIB)
-    AC_SUBST(MAKE_STATIC_LIB)
-    AC_SUBST(MAKE_STUB_LIB)
-    AC_SUBST(RANLIB_STUB)
-    AC_SUBST(VC_MANIFEST_EMBED_DLL)
-    AC_SUBST(VC_MANIFEST_EMBED_EXE)
-])
-
-#------------------------------------------------------------------------
-# TEA_LIB_SPEC --
-#
-#      Compute the name of an existing object library located in libdir
-#      from the given base name and produce the appropriate linker flags.
-#
-# Arguments:
-#      basename        The base name of the library without version
-#                      numbers, extensions, or "lib" prefixes.
-#      extra_dir       Extra directory in which to search for the
-#                      library.  This location is used first, then
-#                      $prefix/$exec-prefix, then some defaults.
-#
-# Requires:
-#      TEA_INIT and TEA_PREFIX must be called first.
-#
-# Results:
-#
-#      Defines the following vars:
-#              ${basename}_LIB_NAME    The computed library name.
-#              ${basename}_LIB_SPEC    The computed linker flags.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LIB_SPEC], [
-    AC_MSG_CHECKING([for $1 library])
-
-    # Look in exec-prefix for the library (defined by TEA_PREFIX).
-
-    tea_lib_name_dir="${exec_prefix}/lib"
-
-    # Or in a user-specified location.
-
-    if test x"$2" != x ; then
-       tea_extra_lib_dir=$2
-    else
-       tea_extra_lib_dir=NONE
-    fi
-
-    for i in \
-           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
-       if test -f "$i" ; then
-           tea_lib_name_dir=`dirname $i`
-           $1_LIB_NAME=`basename $i`
-           $1_LIB_PATH_NAME=$i
-           break
-       fi
-    done
-
-    if test "${TEA_PLATFORM}" = "windows"; then
-       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
-    else
-       # Strip off the leading "lib" and trailing ".a" or ".so"
-
-       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
-       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
-    fi
-
-    if test "x${$1_LIB_NAME}" = x ; then
-       AC_MSG_ERROR([not found])
-    else
-       AC_MSG_RESULT([${$1_LIB_SPEC}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TCL_HEADERS --
-#
-#      Locate the private Tcl include files
-#
-# Arguments:
-#
-#      Requires:
-#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
-#                              already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_TOP_DIR_NATIVE
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
-    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
-    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
-    AC_MSG_CHECKING([for Tcl private include files])
-
-    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
-    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
-
-    # Check to see if tcl<Plat>Port.h isn't already with the public headers
-    # Don't look for tclInt.h because that resides with tcl.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
-       else
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TCL_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
-       if test "`uname -s`" = "Darwin"; then
-            # If Tcl was built as a framework, attempt to use
-            # the framework's Headers and PrivateHeaders directories
-            case ${TCL_DEFS} in
-               *TCL_FRAMEWORK*)
-                   if test -d "${TCL_BIN_DIR}/Headers" -a \
-                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
-                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
-                   else
-                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                   fi
-                   ;;
-           esac
-           result="Using ${TCL_INCLUDES}"
-       else
-           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
-               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
-           fi
-           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TCL_TOP_DIR_NATIVE)
-
-    AC_SUBST(TCL_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TCL_HEADERS --
-#
-#      Locate the installed public Tcl header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tclinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
-    AC_MSG_CHECKING([for Tcl public headers])
-
-    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tclh, [
-       # Use the value from --with-tclinclude, if it was given
-
-       if test x"${with_tclinclude}" != x ; then
-           if test -f "${with_tclinclude}/tcl.h" ; then
-               ac_cv_c_tclh=${with_tclinclude}
-           else
-               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tcl was built as a framework, attempt to use
-               # the framework's Headers directory
-               case ${TCL_DEFS} in
-                   *TCL_FRAMEWORK*)
-                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tcl is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TCL_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TCL_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tcl.h" ; then
-                   ac_cv_c_tclh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tclh}" = x ; then
-       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tclh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
-
-    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TCL_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TK_HEADERS --
-#
-#      Locate the private Tk include files
-#
-# Arguments:
-#
-#      Requires:
-#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
-#                               already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
-    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
-    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
-    AC_MSG_CHECKING([for Tk private include files])
-
-    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
-    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
-
-    # Check to see if tk<Plat>Port.h isn't already with the public headers
-    # Don't look for tkInt.h because that resides with tk.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
-       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
-       else
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TK_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
-       # Detect and add ttk subdir
-       if test -d "${TK_SRC_DIR}/generic/ttk"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
-       fi
-       if test "`uname -s`" = "Darwin"; then
-           # If Tk was built as a framework, attempt to use
-           # the framework's Headers and PrivateHeaders directories
-           case ${TK_DEFS} in
-               *TK_FRAMEWORK*)
-                       if test -d "${TK_BIN_DIR}/Headers" -a \
-                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
-                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
-                       else
-                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                       fi
-                       ;;
-           esac
-           result="Using ${TK_INCLUDES}"
-       else
-           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
-              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
-           fi
-           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TK_TOP_DIR_NATIVE)
-    AC_SUBST(TK_XLIB_DIR_NATIVE)
-
-    AC_SUBST(TK_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TK_HEADERS --
-#
-#      Locate the installed public Tk header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tkinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
-    AC_MSG_CHECKING([for Tk public headers])
-
-    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tkh, [
-       # Use the value from --with-tkinclude, if it was given
-
-       if test x"${with_tkinclude}" != x ; then
-           if test -f "${with_tkinclude}/tk.h" ; then
-               ac_cv_c_tkh=${with_tkinclude}
-           else
-               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tk was built as a framework, attempt to use
-               # the framework's Headers directory.
-               case ${TK_DEFS} in
-                   *TK_FRAMEWORK*)
-                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tk is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TK_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tk's --prefix location,
-           # relative to directory of tkConfig.sh, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
-               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TK_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tk.h" ; then
-                   ac_cv_c_tkh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tkh}" = x ; then
-       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tkh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
-
-    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TK_INCLUDES)
-
-    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-       # On Windows and Aqua, we need the X compat headers
-       AC_MSG_CHECKING([for X11 header files])
-       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
-           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
-           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-           AC_SUBST(TK_XINCLUDES)
-       fi
-       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_CONFIG --
-#
-#      Locate the ${1}Config.sh file and perform a sanity check on
-#      the ${1} compile flags.  These are used by packages like
-#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-$1=...
-#
-#      Defines the following vars:
-#              $1_BIN_DIR      Full path to the directory containing
-#                              the $1Config.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_CONFIG], [
-    #
-    # Ok, lets find the $1 configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-$1
-    #
-
-    if test x"${no_$1}" = x ; then
-       # we reset no_$1 in case something fails here
-       no_$1=true
-       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
-       AC_MSG_CHECKING([for $1 configuration])
-       AC_CACHE_VAL(ac_cv_c_$1config,[
-
-           # First check to see if --with-$1 was specified.
-           if test x"${with_$1config}" != x ; then
-               case ${with_$1config} in
-                   */$1Config.sh )
-                       if test -f ${with_$1config}; then
-                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
-                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
-                       fi;;
-               esac
-               if test -f "${with_$1config}/$1Config.sh" ; then
-                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
-               else
-                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
-               fi
-           fi
-
-           # then check for a private $1 installation
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in \
-                       ../$1 \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../$1 \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../$1 \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ${srcdir}/../$1 \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-                   if test -f "$i/unix/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_$1config}" = x ; then
-           $1_BIN_DIR="# no $1 configs found"
-           AC_MSG_WARN([Cannot find $1 configuration definitions])
-           exit 0
-       else
-           no_$1=
-           $1_BIN_DIR=${ac_cv_c_$1config}
-           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG --
-#
-#      Load the $1Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              $1_SRC_DIR
-#              $1_LIB_FILE
-#              $1_LIB_SPEC
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_CONFIG], [
-    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
-
-    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${$1_BIN_DIR}/$1Config.sh"
-    else
-        AC_MSG_RESULT([file not found])
-    fi
-
-    #
-    # If the $1_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable $1_LIB_SPEC will be set to the value
-    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
-    # instead of $1_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    #
-
-    if test -f "${$1_BIN_DIR}/Makefile" ; then
-       AC_MSG_WARN([Found Makefile - using build library specs for $1])
-        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
-        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
-        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
-        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
-        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
-    fi
-
-    AC_SUBST($1_VERSION)
-    AC_SUBST($1_BIN_DIR)
-    AC_SUBST($1_SRC_DIR)
-
-    AC_SUBST($1_LIB_FILE)
-    AC_SUBST($1_LIB_SPEC)
-
-    AC_SUBST($1_STUB_LIB_FILE)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    # Allow the caller to prevent this auto-check by specifying any 2nd arg
-    AS_IF([test "x$2" = x], [
-       # Check both upper and lower-case variants
-       # If a dev wanted non-stubs libs, this function could take an option
-       # to not use _STUB in the paths below
-       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
-           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
-           [TEA_LOAD_CONFIG_LIB($1_STUB)])
-    ])
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG_LIB --
-#
-#      Helper function to load correct library from another extension's
-#      ${PACKAGE}Config.sh.
-#
-# Results:
-#      Adds to LIBS the appropriate extension library
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
-    AC_MSG_CHECKING([For $1 library for LIBS])
-    # This simplifies the use of stub libraries by automatically adding
-    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
-    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
-    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
-    if test "x${$1_LIB_SPEC}" != "x" ; then
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
-           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
-           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
-       else
-           TEA_ADD_LIBS([${$1_LIB_SPEC}])
-           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
-       fi
-    else
-       AC_MSG_RESULT([file not found])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_EXPORT_CONFIG --
-#
-#      Define the data to insert into the ${PACKAGE}Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1
-#
-# Results:
-#      Substitutes the following vars:
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_EXPORT_CONFIG], [
-    #--------------------------------------------------------------------
-    # These are for $1Config.sh
-    #--------------------------------------------------------------------
-
-    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
-    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
-    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
-    else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-    fi
-    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
-    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
-    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
-    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
-
-    AC_SUBST($1_BUILD_LIB_SPEC)
-    AC_SUBST($1_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_PATH)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    AC_SUBST(MAJOR_VERSION)
-    AC_SUBST(MINOR_VERSION)
-    AC_SUBST(PATCHLEVEL)
-])
-
-
-#------------------------------------------------------------------------
-# TEA_INSTALLER --
-#
-#      Configure the installer.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              INSTALL
-#              INSTALL_DATA_DIR
-#              INSTALL_DATA
-#              INSTALL_PROGRAM
-#              INSTALL_SCRIPT
-#              INSTALL_LIBRARY
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INSTALLER], [
-    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
-    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
-    INSTALL_DATA='${INSTALL} -m 644'
-    INSTALL_PROGRAM='${INSTALL} -m 755'
-    INSTALL_SCRIPT='${INSTALL} -m 755'
-
-    TEA_CONFIG_SYSTEM
-    case $system in
-       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
-             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
-    esac
-
-    AC_SUBST(INSTALL)
-    AC_SUBST(INSTALL_DATA_DIR)
-    AC_SUBST(INSTALL_DATA)
-    AC_SUBST(INSTALL_PROGRAM)
-    AC_SUBST(INSTALL_SCRIPT)
-    AC_SUBST(INSTALL_LIBRARY)
-])
-
-###
-# Tip 430 - ZipFS Modifications
-###
-#------------------------------------------------------------------------
-# SC_ZIPFS_SUPPORT
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#              TCL_ZIPFS_FLAG
-#              ZIP_PROG
-#------------------------------------------------------------------------
-
-#------------------------------------------------------------------------
-# SC_PROG_ZIP
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              ZIP_PROG
-#       ZIP_PROG_OPTIONS
-#       ZIP_PROG_VFSSEARCH
-#       ZIP_INSTALL_OBJS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ZIPFS_SUPPORT], [
-    AC_MSG_CHECKING([for zipfs support])
-    ZIP_PROG=""
-    ZIP_PROG_OPTIONS=""
-    ZIP_PROG_VFSSEARCH=""
-    INSTALL_MSGS=""
-    # If our native tclsh processes the "install" command line option
-    # we can use it to mint zip files
-    AS_IF([$TCLSH_PROG install],[
-      ZIP_PROG=${TCLSH_PROG}
-      ZIP_PROG_OPTIONS="install mkzip"
-      ZIP_PROG_VFSSEARCH="."
-      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
-    ])
-    if test "x$ZIP_PROG" = "x" ; then
-        AC_CACHE_VAL(ac_cv_path_zip, [
-        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
-        for dir in $search_path ; do
-            for j in `ls -r $dir/zip 2> /dev/null` \
-                `ls -r $dir/zip 2> /dev/null` ; do
-            if test x"$ac_cv_path_zip" = x ; then
-                if test -f "$j" ; then
-                ac_cv_path_zip=$j
-                break
-                fi
-            fi
-            done
-        done
-        ])
-        if test -f "$ac_cv_path_zip" ; then
-            ZIP_PROG="$ac_cv_path_zip "
-            AC_MSG_RESULT([$ZIP_PROG])
-            ZIP_PROG_OPTIONS="-rq"
-            ZIP_PROG_VFSSEARCH="."
-            AC_MSG_RESULT([Found INFO Zip in environment])
-            # Use standard arguments for zip
-        fi
-    fi
-    if test "x$ZIP_PROG" = "x" ; then
-           # It is not an error if an installed version of Zip can't be located.
-        ZIP_PROG=""
-        ZIP_PROG_OPTIONS=""
-        ZIP_PROG_VFSSEARCH=""
-        TCL_ZIPFS_SUPPORT=0
-        TCL_ZIPFS_FLAG=
-    else
-        # ZIPFS Support
-       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
-       if test ${TCL_ZIP_FILE} = "" ; then
-          TCL_ZIPFS_SUPPORT=0
-          TCL_ZIPFS_FLAG=
-          INSTALL_LIBRARIES=install-libraries
-          INSTALL_MSGS=install-msgs
-       else
-           if test ${SHARED_BUILD} = 1 ; then
-              TCL_ZIPFS_SUPPORT=1
-              INSTALL_LIBRARIES=install-libraries-zipfs-shared
-           else
-              TCL_ZIPFS_SUPPORT=2
-              INSTALL_LIBRARIES=install-libraries-zipfs-static
-           fi
-          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
-       fi
-    fi
-
-    AC_SUBST(TCL_ZIP_FILE)
-    AC_SUBST(TCL_ZIPFS_SUPPORT)
-    AC_SUBST(TCL_ZIPFS_FLAG)
-    AC_SUBST(ZIP_PROG)
-    AC_SUBST(ZIP_PROG_OPTIONS)
-    AC_SUBST(ZIP_PROG_VFSSEARCH)
-    AC_SUBST(INSTALL_LIBRARIES)
-    AC_SUBST(INSTALL_MSGS)
-])
-
-# Local Variables:
-# mode: autoconf
-# End:
diff --git a/pkgs/tdbcpostgres1.1.1/win/nmakehlp.c b/pkgs/tdbcpostgres1.1.1/win/nmakehlp.c
deleted file mode 100644 (file)
index c21de63..0000000
+++ /dev/null
@@ -1,815 +0,0 @@
-/*
- * ----------------------------------------------------------------------------
- * nmakehlp.c --
- *
- *     This is used to fix limitations within nmake and the environment.
- *
- * Copyright (c) 2002 by David Gravereaux.
- * Copyright (c) 2006 by Pat Thoyts
- *
- * See the file "license.terms" for information on usage and redistribution of
- * this file, and for a DISCLAIMER OF ALL WARRANTIES.
- * ----------------------------------------------------------------------------
- */
-
-#define _CRT_SECURE_NO_DEPRECATE
-#include <windows.h>
-#pragma comment (lib, "user32.lib")
-#pragma comment (lib, "kernel32.lib")
-#include <stdio.h>
-#include <math.h>
-
-/*
- * This library is required for x64 builds with _some_ versions of MSVC
- */
-#if defined(_M_IA64) || defined(_M_AMD64)
-#if _MSC_VER >= 1400 && _MSC_VER < 1500
-#pragma comment(lib, "bufferoverflowU")
-#endif
-#endif
-
-/* ISO hack for dumb VC++ */
-#ifdef _MSC_VER
-#define   snprintf     _snprintf
-#endif
-
-
-/* protos */
-
-static int CheckForCompilerFeature(const char *option);
-static int CheckForLinkerFeature(const char **options, int count);
-static int IsIn(const char *string, const char *substring);
-static int SubstituteFile(const char *substs, const char *filename);
-static int QualifyPath(const char *path);
-static int LocateDependency(const char *keyfile);
-static const char *GetVersionFromFile(const char *filename, const char *match, int numdots);
-static DWORD WINAPI ReadFromPipe(LPVOID args);
-
-/* globals */
-
-#define CHUNK  25
-#define STATICBUFFERSIZE    1000
-typedef struct {
-    HANDLE pipe;
-    char buffer[STATICBUFFERSIZE];
-} pipeinfo;
-
-pipeinfo Out = {INVALID_HANDLE_VALUE, '\0'};
-pipeinfo Err = {INVALID_HANDLE_VALUE, '\0'};
-\f
-/*
- * exitcodes: 0 == no, 1 == yes, 2 == error
- */
-
-int
-main(
-    int argc,
-    char *argv[])
-{
-    char msg[300];
-    DWORD dwWritten;
-    int chars;
-    const char *s;
-
-    /*
-     * Make sure children (cl.exe and link.exe) are kept quiet.
-     */
-
-    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
-
-    /*
-     * Make sure the compiler and linker aren't effected by the outside world.
-     */
-
-    SetEnvironmentVariable("CL", "");
-    SetEnvironmentVariable("LINK", "");
-
-    if (argc > 1 && *argv[1] == '-') {
-       switch (*(argv[1]+1)) {
-       case 'c':
-           if (argc != 3) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                       "usage: %s -c <compiler option>\n"
-                       "Tests for whether cl.exe supports an option\n"
-                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                       &dwWritten, NULL);
-               return 2;
-           }
-           return CheckForCompilerFeature(argv[2]);
-       case 'l':
-           if (argc < 3) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                       "usage: %s -l <linker option> ?<mandatory option> ...?\n"
-                       "Tests for whether link.exe supports an option\n"
-                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                       &dwWritten, NULL);
-               return 2;
-           }
-           return CheckForLinkerFeature(&argv[2], argc-2);
-       case 'f':
-           if (argc == 2) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                       "usage: %s -f <string> <substring>\n"
-                       "Find a substring within another\n"
-                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                       &dwWritten, NULL);
-               return 2;
-           } else if (argc == 3) {
-               /*
-                * If the string is blank, there is no match.
-                */
-
-               return 0;
-           } else {
-               return IsIn(argv[2], argv[3]);
-           }
-       case 's':
-           if (argc == 2) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                       "usage: %s -s <substitutions file> <file>\n"
-                       "Perform a set of string map type substutitions on a file\n"
-                       "exitcodes: 0\n",
-                       argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                       &dwWritten, NULL);
-               return 2;
-           }
-           return SubstituteFile(argv[2], argv[3]);
-       case 'V':
-           if (argc != 4) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                   "usage: %s -V filename matchstring\n"
-                   "Extract a version from a file:\n"
-                   "eg: pkgIndex.tcl \"package ifneeded http\"",
-                   argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                   &dwWritten, NULL);
-               return 0;
-           }
-           s = GetVersionFromFile(argv[2], argv[3], *(argv[1]+2) - '0');
-           if (s && *s) {
-               printf("%s\n", s);
-               return 0;
-           } else
-               return 1; /* Version not found. Return non-0 exit code */
-
-       case 'Q':
-           if (argc != 3) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                   "usage: %s -Q path\n"
-                   "Emit the fully qualified path\n"
-                   "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                   &dwWritten, NULL);
-               return 2;
-           }
-           return QualifyPath(argv[2]);
-
-       case 'L':
-           if (argc != 3) {
-               chars = snprintf(msg, sizeof(msg) - 1,
-                   "usage: %s -L keypath\n"
-                   "Emit the fully qualified path of directory containing keypath\n"
-                   "exitcodes: 0 == success, 1 == not found, 2 == error\n", argv[0]);
-               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
-                   &dwWritten, NULL);
-               return 2;
-           }
-           return LocateDependency(argv[2]);
-       }
-    }
-    chars = snprintf(msg, sizeof(msg) - 1,
-           "usage: %s -c|-f|-l|-Q|-s|-V ...\n"
-           "This is a little helper app to equalize shell differences between WinNT and\n"
-           "Win9x and get nmake.exe to accomplish its job.\n",
-           argv[0]);
-    WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, &dwWritten, NULL);
-    return 2;
-}
-\f
-static int
-CheckForCompilerFeature(
-    const char *option)
-{
-    STARTUPINFO si;
-    PROCESS_INFORMATION pi;
-    SECURITY_ATTRIBUTES sa;
-    DWORD threadID;
-    char msg[300];
-    BOOL ok;
-    HANDLE hProcess, h, pipeThreads[2];
-    char cmdline[100];
-
-    hProcess = GetCurrentProcess();
-
-    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
-    ZeroMemory(&si, sizeof(STARTUPINFO));
-    si.cb = sizeof(STARTUPINFO);
-    si.dwFlags   = STARTF_USESTDHANDLES;
-    si.hStdInput = INVALID_HANDLE_VALUE;
-
-    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
-    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
-    sa.lpSecurityDescriptor = NULL;
-    sa.bInheritHandle = FALSE;
-
-    /*
-     * Create a non-inheritible pipe.
-     */
-
-    CreatePipe(&Out.pipe, &h, &sa, 0);
-
-    /*
-     * Dupe the write side, make it inheritible, and close the original.
-     */
-
-    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
-           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
-
-    /*
-     * Same as above, but for the error side.
-     */
-
-    CreatePipe(&Err.pipe, &h, &sa, 0);
-    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
-           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
-
-    /*
-     * Base command line.
-     */
-
-    lstrcpy(cmdline, "cl.exe -nologo -c -TC -Zs -X -Fp.\\_junk.pch ");
-
-    /*
-     * Append our option for testing
-     */
-
-    lstrcat(cmdline, option);
-
-    /*
-     * Filename to compile, which exists, but is nothing and empty.
-     */
-
-    lstrcat(cmdline, " .\\nul");
-
-    ok = CreateProcess(
-           NULL,           /* Module name. */
-           cmdline,        /* Command line. */
-           NULL,           /* Process handle not inheritable. */
-           NULL,           /* Thread handle not inheritable. */
-           TRUE,           /* yes, inherit handles. */
-           DETACHED_PROCESS, /* No console for you. */
-           NULL,           /* Use parent's environment block. */
-           NULL,           /* Use parent's starting directory. */
-           &si,            /* Pointer to STARTUPINFO structure. */
-           &pi);           /* Pointer to PROCESS_INFORMATION structure. */
-
-    if (!ok) {
-       DWORD err = GetLastError();
-       int chars = snprintf(msg, sizeof(msg) - 1,
-               "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);
-
-       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
-               FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
-               (300-chars), 0);
-       WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL);
-       return 2;
-    }
-
-    /*
-     * Close our references to the write handles that have now been inherited.
-     */
-
-    CloseHandle(si.hStdOutput);
-    CloseHandle(si.hStdError);
-
-    WaitForInputIdle(pi.hProcess, 5000);
-    CloseHandle(pi.hThread);
-
-    /*
-     * Start the pipe reader threads.
-     */
-
-    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
-    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);
-
-    /*
-     * Block waiting for the process to end.
-     */
-
-    WaitForSingleObject(pi.hProcess, INFINITE);
-    CloseHandle(pi.hProcess);
-
-    /*
-     * Wait for our pipe to get done reading, should it be a little slow.
-     */
-
-    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
-    CloseHandle(pipeThreads[0]);
-    CloseHandle(pipeThreads[1]);
-
-    /*
-     * Look for the commandline warning code in both streams.
-     *  - in MSVC 6 & 7 we get D4002, in MSVC 8 we get D9002.
-     */
-
-    return !(strstr(Out.buffer, "D4002") != NULL
-             || strstr(Err.buffer, "D4002") != NULL
-             || strstr(Out.buffer, "D9002") != NULL
-             || strstr(Err.buffer, "D9002") != NULL
-             || strstr(Out.buffer, "D2021") != NULL
-             || strstr(Err.buffer, "D2021") != NULL);
-}
-\f
-static int
-CheckForLinkerFeature(
-    const char **options,
-    int count)
-{
-    STARTUPINFO si;
-    PROCESS_INFORMATION pi;
-    SECURITY_ATTRIBUTES sa;
-    DWORD threadID;
-    char msg[300];
-    BOOL ok;
-    HANDLE hProcess, h, pipeThreads[2];
-    int i;
-    char cmdline[255];
-
-    hProcess = GetCurrentProcess();
-
-    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
-    ZeroMemory(&si, sizeof(STARTUPINFO));
-    si.cb = sizeof(STARTUPINFO);
-    si.dwFlags   = STARTF_USESTDHANDLES;
-    si.hStdInput = INVALID_HANDLE_VALUE;
-
-    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
-    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
-    sa.lpSecurityDescriptor = NULL;
-    sa.bInheritHandle = TRUE;
-
-    /*
-     * Create a non-inheritible pipe.
-     */
-
-    CreatePipe(&Out.pipe, &h, &sa, 0);
-
-    /*
-     * Dupe the write side, make it inheritible, and close the original.
-     */
-
-    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
-           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
-
-    /*
-     * Same as above, but for the error side.
-     */
-
-    CreatePipe(&Err.pipe, &h, &sa, 0);
-    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
-           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
-
-    /*
-     * Base command line.
-     */
-
-    lstrcpy(cmdline, "link.exe -nologo ");
-
-    /*
-     * Append our option for testing.
-     */
-
-    for (i = 0; i < count; i++) {
-       lstrcat(cmdline, " \"");
-       lstrcat(cmdline, options[i]);
-       lstrcat(cmdline, "\"");
-    }
-
-    ok = CreateProcess(
-           NULL,           /* Module name. */
-           cmdline,        /* Command line. */
-           NULL,           /* Process handle not inheritable. */
-           NULL,           /* Thread handle not inheritable. */
-           TRUE,           /* yes, inherit handles. */
-           DETACHED_PROCESS, /* No console for you. */
-           NULL,           /* Use parent's environment block. */
-           NULL,           /* Use parent's starting directory. */
-           &si,            /* Pointer to STARTUPINFO structure. */
-           &pi);           /* Pointer to PROCESS_INFORMATION structure. */
-
-    if (!ok) {
-       DWORD err = GetLastError();
-       int chars = snprintf(msg, sizeof(msg) - 1,
-               "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);
-
-       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
-               FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
-               (300-chars), 0);
-       WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL);
-       return 2;
-    }
-
-    /*
-     * Close our references to the write handles that have now been inherited.
-     */
-
-    CloseHandle(si.hStdOutput);
-    CloseHandle(si.hStdError);
-
-    WaitForInputIdle(pi.hProcess, 5000);
-    CloseHandle(pi.hThread);
-
-    /*
-     * Start the pipe reader threads.
-     */
-
-    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
-    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);
-
-    /*
-     * Block waiting for the process to end.
-     */
-
-    WaitForSingleObject(pi.hProcess, INFINITE);
-    CloseHandle(pi.hProcess);
-
-    /*
-     * Wait for our pipe to get done reading, should it be a little slow.
-     */
-
-    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
-    CloseHandle(pipeThreads[0]);
-    CloseHandle(pipeThreads[1]);
-
-    /*
-     * Look for the commandline warning code in the stderr stream.
-     */
-
-    return !(strstr(Out.buffer, "LNK1117") != NULL ||
-           strstr(Err.buffer, "LNK1117") != NULL ||
-           strstr(Out.buffer, "LNK4044") != NULL ||
-           strstr(Err.buffer, "LNK4044") != NULL ||
-           strstr(Out.buffer, "LNK4224") != NULL ||
-           strstr(Err.buffer, "LNK4224") != NULL);
-}
-\f
-static DWORD WINAPI
-ReadFromPipe(
-    LPVOID args)
-{
-    pipeinfo *pi = (pipeinfo *) args;
-    char *lastBuf = pi->buffer;
-    DWORD dwRead;
-    BOOL ok;
-
-  again:
-    if (lastBuf - pi->buffer + CHUNK > STATICBUFFERSIZE) {
-       CloseHandle(pi->pipe);
-       return (DWORD)-1;
-    }
-    ok = ReadFile(pi->pipe, lastBuf, CHUNK, &dwRead, 0L);
-    if (!ok || dwRead == 0) {
-       CloseHandle(pi->pipe);
-       return 0;
-    }
-    lastBuf += dwRead;
-    goto again;
-
-    return 0;  /* makes the compiler happy */
-}
-\f
-static int
-IsIn(
-    const char *string,
-    const char *substring)
-{
-    return (strstr(string, substring) != NULL);
-}
-\f
-/*
- * GetVersionFromFile --
- *     Looks for a match string in a file and then returns the version
- *     following the match where a version is anything acceptable to
- *     package provide or package ifneeded.
- */
-
-static const char *
-GetVersionFromFile(
-    const char *filename,
-    const char *match,
-    int numdots)
-{
-    size_t cbBuffer = 100;
-    static char szBuffer[100];
-    char *szResult = NULL;
-    FILE *fp = fopen(filename, "rt");
-
-    if (fp != NULL) {
-       /*
-        * Read data until we see our match string.
-        */
-
-       while (fgets(szBuffer, cbBuffer, fp) != NULL) {
-           LPSTR p, q;
-
-           p = strstr(szBuffer, match);
-           if (p != NULL) {
-               /*
-                * Skip to first digit after the match.
-                */
-
-               p += strlen(match);
-               while (*p && !isdigit(*p)) {
-                   ++p;
-               }
-
-               /*
-                * Find ending whitespace.
-                */
-
-               q = p;
-               while (*q && (strchr("0123456789.ab", *q)) && ((!strchr(".ab", *q)
-                           && (!strchr("ab", q[-1])) || --numdots))) {
-                   ++q;
-               }
-
-               memcpy(szBuffer, p, q - p);
-               szBuffer[q-p] = 0;
-               szResult = szBuffer;
-               break;
-           }
-       }
-       fclose(fp);
-    }
-    return szResult;
-}
-\f
-/*
- * List helpers for the SubstituteFile function
- */
-
-typedef struct list_item_t {
-    struct list_item_t *nextPtr;
-    char * key;
-    char * value;
-} list_item_t;
-
-/* insert a list item into the list (list may be null) */
-static list_item_t *
-list_insert(list_item_t **listPtrPtr, const char *key, const char *value)
-{
-    list_item_t *itemPtr = malloc(sizeof(list_item_t));
-    if (itemPtr) {
-       itemPtr->key = strdup(key);
-       itemPtr->value = strdup(value);
-       itemPtr->nextPtr = NULL;
-
-       while(*listPtrPtr) {
-           listPtrPtr = &(*listPtrPtr)->nextPtr;
-       }
-       *listPtrPtr = itemPtr;
-    }
-    return itemPtr;
-}
-
-static void
-list_free(list_item_t **listPtrPtr)
-{
-    list_item_t *tmpPtr, *listPtr = *listPtrPtr;
-    while (listPtr) {
-       tmpPtr = listPtr;
-       listPtr = listPtr->nextPtr;
-       free(tmpPtr->key);
-       free(tmpPtr->value);
-       free(tmpPtr);
-    }
-}
-\f
-/*
- * SubstituteFile --
- *     As windows doesn't provide anything useful like sed and it's unreliable
- *     to use the tclsh you are building against (consider x-platform builds -
- *     eg compiling AMD64 target from IX86) we provide a simple substitution
- *     option here to handle autoconf style substitutions.
- *     The substitution file is whitespace and line delimited. The file should
- *     consist of lines matching the regular expression:
- *       \s*\S+\s+\S*$
- *
- *     Usage is something like:
- *       nmakehlp -S << $** > $@
- *        @PACKAGE_NAME@ $(PACKAGE_NAME)
- *        @PACKAGE_VERSION@ $(PACKAGE_VERSION)
- *        <<
- */
-
-static int
-SubstituteFile(
-    const char *substitutions,
-    const char *filename)
-{
-    size_t cbBuffer = 1024;
-    static char szBuffer[1024], szCopy[1024];
-    char *szResult = NULL;
-    list_item_t *substPtr = NULL;
-    FILE *fp, *sp;
-
-    fp = fopen(filename, "rt");
-    if (fp != NULL) {
-
-       /*
-        * Build a list of substutitions from the first filename
-        */
-
-       sp = fopen(substitutions, "rt");
-       if (sp != NULL) {
-           while (fgets(szBuffer, cbBuffer, sp) != NULL) {
-               unsigned char *ks, *ke, *vs, *ve;
-               ks = (unsigned char*)szBuffer;
-               while (ks && *ks && isspace(*ks)) ++ks;
-               ke = ks;
-               while (ke && *ke && !isspace(*ke)) ++ke;
-               vs = ke;
-               while (vs && *vs && isspace(*vs)) ++vs;
-               ve = vs;
-               while (ve && *ve && !(*ve == '\r' || *ve == '\n')) ++ve;
-               *ke = 0, *ve = 0;
-               list_insert(&substPtr, (char*)ks, (char*)vs);
-           }
-           fclose(sp);
-       }
-
-       /* debug: dump the list */
-#ifdef _DEBUG
-       {
-           int n = 0;
-           list_item_t *p = NULL;
-           for (p = substPtr; p != NULL; p = p->nextPtr, ++n) {
-               fprintf(stderr, "% 3d '%s' => '%s'\n", n, p->key, p->value);
-           }
-       }
-#endif
-
-       /*
-        * Run the substitutions over each line of the input
-        */
-
-       while (fgets(szBuffer, cbBuffer, fp) != NULL) {
-           list_item_t *p = NULL;
-           for (p = substPtr; p != NULL; p = p->nextPtr) {
-               char *m = strstr(szBuffer, p->key);
-               if (m) {
-                   char *cp, *op, *sp;
-                   cp = szCopy;
-                   op = szBuffer;
-                   while (op != m) *cp++ = *op++;
-                   sp = p->value;
-                   while (sp && *sp) *cp++ = *sp++;
-                   op += strlen(p->key);
-                   while (*op) *cp++ = *op++;
-                   *cp = 0;
-                   memcpy(szBuffer, szCopy, sizeof(szCopy));
-               }
-           }
-           printf(szBuffer);
-       }
-
-       list_free(&substPtr);
-    }
-    fclose(fp);
-    return 0;
-}
-\f
-BOOL FileExists(LPCTSTR szPath)
-{
-#ifndef INVALID_FILE_ATTRIBUTES
-    #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
-#endif
-    DWORD pathAttr = GetFileAttributes(szPath);
-    return (pathAttr != INVALID_FILE_ATTRIBUTES &&
-           !(pathAttr & FILE_ATTRIBUTE_DIRECTORY));
-}
-\f
-
-/*
- * QualifyPath --
- *
- *     This composes the current working directory with a provided path
- *     and returns the fully qualified and normalized path.
- *     Mostly needed to setup paths for testing.
- */
-
-static int
-QualifyPath(
-    const char *szPath)
-{
-    char szCwd[MAX_PATH + 1];
-
-       GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
-    printf("%s\n", szCwd);
-    return 0;
-}
-
-/*
- * Implements LocateDependency for a single directory. See that command
- * for an explanation.
- * Returns 0 if found after printing the directory.
- * Returns 1 if not found but no errors.
- * Returns 2 on any kind of error
- * Basically, these are used as exit codes for the process.
- */
-static int LocateDependencyHelper(const char *dir, const char *keypath)
-{
-    HANDLE hSearch;
-    char path[MAX_PATH+1];
-    int dirlen, keylen, ret;
-    WIN32_FIND_DATA finfo;
-
-    if (dir == NULL || keypath == NULL)
-       return 2; /* Have no real error reporting mechanism into nmake */
-    dirlen = strlen(dir);
-    if ((dirlen + 3) > sizeof(path))
-       return 2;
-    strncpy(path, dir, dirlen);
-    strncpy(path+dirlen, "\\*", 3);    /* Including terminating \0 */
-    keylen = strlen(keypath);
-
-#if 0 /* This function is not available in Visual C++ 6 */
-    /*
-     * Use numerics 0 -> FindExInfoStandard,
-     * 1 -> FindExSearchLimitToDirectories,
-     * as these are not defined in Visual C++ 6
-     */
-    hSearch = FindFirstFileEx(path, 0, &finfo, 1, NULL, 0);
-#else
-    hSearch = FindFirstFile(path, &finfo);
-#endif
-    if (hSearch == INVALID_HANDLE_VALUE)
-       return 1; /* Not found */
-
-    /* Loop through all subdirs checking if the keypath is under there */
-    ret = 1; /* Assume not found */
-    do {
-       int sublen;
-       /*
-        * We need to check it is a directory despite the
-        * FindExSearchLimitToDirectories in the above call. See SDK docs
-        */
-       if ((finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
-           continue;
-       sublen = strlen(finfo.cFileName);
-       if ((dirlen+1+sublen+1+keylen+1) > sizeof(path))
-           continue;           /* Path does not fit, assume not matched */
-       strncpy(path+dirlen+1, finfo.cFileName, sublen);
-       path[dirlen+1+sublen] = '\\';
-       strncpy(path+dirlen+1+sublen+1, keypath, keylen+1);
-       if (FileExists(path)) {
-           /* Found a match, print to stdout */
-           path[dirlen+1+sublen] = '\0';
-           QualifyPath(path);
-           ret = 0;
-           break;
-       }
-    } while (FindNextFile(hSearch, &finfo));
-    FindClose(hSearch);
-    return ret;
-}
-
-/*
- * LocateDependency --
- *
- *     Locates a dependency for a package.
- *        keypath - a relative path within the package directory
- *          that is used to confirm it is the correct directory.
- *     The search path for the package directory is currently only
- *      the parent and grandparent of the current working directory.
- *      If found, the command prints
- *         name_DIRPATH=<full path of located directory>
- *      and returns 0. If not found, does not print anything and returns 1.
- */
-static int LocateDependency(const char *keypath)
-{
-    int i, ret;
-    static const char *paths[] = {"..", "..\\..", "..\\..\\.."};
-
-    for (i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i) {
-       ret = LocateDependencyHelper(paths[i], keypath);
-       if (ret == 0)
-           return ret;
-    }
-    return ret;
-}
-
-
-/*
- * Local variables:
- *   mode: c
- *   c-basic-offset: 4
- *   fill-column: 78
- *   indent-tabs-mode: t
- *   tab-width: 8
- * End:
- */
diff --git a/pkgs/tdbcpostgres1.1.1/win/rules-ext.vc b/pkgs/tdbcpostgres1.1.1/win/rules-ext.vc
deleted file mode 100644 (file)
index 531e070..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-# This file should only be included in makefiles for Tcl extensions,\r
-# NOT in the makefile for Tcl itself.\r
-\r
-!ifndef _RULES_EXT_VC\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-!if "$(PROJECT)" == "tcl"\r
-!error The rules-ext.vc file is not intended for Tcl itself.\r
-!endif\r
-\r
-# We extract version numbers using the nmakehlp program. For now use\r
-# the local copy of nmakehlp. Once we locate Tcl, we will use that\r
-# one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
-!endif\r
-\r
-# First locate the Tcl directory that we are working with.\r
-!if "$(TCLDIR)" != ""\r
-\r
-_RULESDIR = $(TCLDIR:/=\)\r
-\r
-!else\r
-\r
-# If an installation path is specified, that is also the Tcl directory.\r
-# Also Tk never builds against an installed Tcl, it needs Tcl sources\r
-!if defined(INSTALLDIR) && "$(PROJECT)" != "tk"\r
-_RULESDIR=$(INSTALLDIR:/=\)\r
-!else\r
-# Locate Tcl sources\r
-!if [echo _RULESDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-_RULESDIR = ..\..\tcl\r
-!else\r
-!include nmakehlp.out\r
-!endif\r
-\r
-!endif # defined(INSTALLDIR)....\r
-\r
-!endif # ifndef TCLDIR\r
-\r
-# Now look for the targets.vc file under the Tcl root. Note we check this\r
-# file and not rules.vc because the latter also exists on older systems.\r
-!if exist("$(_RULESDIR)\lib\nmake\targets.vc") # Building against installed Tcl\r
-_RULESDIR = $(_RULESDIR)\lib\nmake\r
-!elseif exist("$(_RULESDIR)\win\targets.vc")   # Building against Tcl sources\r
-_RULESDIR = $(_RULESDIR)\win\r
-!else\r
-# If we have not located Tcl's targets file, most likely we are compiling\r
-# against an older version of Tcl and so must use our own support files.\r
-_RULESDIR = .\r
-!endif\r
-\r
-!if "$(_RULESDIR)" != "."\r
-# Potentially using Tcl's support files. If this extension has its own\r
-# nmake support files, need to compare the versions and pick newer.\r
-\r
-!if exist("rules.vc") # The extension has its own copy\r
-\r
-!if [echo TCL_RULES_MAJOR = \> versions.vc] \\r
-   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
-!endif\r
-!if [echo TCL_RULES_MINOR = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
-!endif\r
-\r
-!if [echo OUR_RULES_MAJOR = \>> versions.vc] \\r
-   && [nmakehlp -V "rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
-!endif\r
-!if [echo OUR_RULES_MINOR = \>> versions.vc] \\r
-   && [nmakehlp -V "rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
-!endif\r
-!include versions.vc\r
-# We have a newer version of the support files, use them\r
-!if ($(TCL_RULES_MAJOR) != $(OUR_RULES_MAJOR)) || ($(TCL_RULES_MINOR) < $(OUR_RULES_MINOR))\r
-_RULESDIR = .\r
-!endif\r
-\r
-!endif # if exist("rules.vc")\r
-\r
-!endif # if $(_RULESDIR) != "."\r
-\r
-# Let rules.vc know what copy of nmakehlp.c to use.\r
-NMAKEHLPC = $(_RULESDIR)\nmakehlp.c\r
-\r
-# Get rid of our internal defines before calling rules.vc\r
-!undef TCL_RULES_MAJOR\r
-!undef TCL_RULES_MINOR\r
-!undef OUR_RULES_MAJOR\r
-!undef OUR_RULES_MINOR\r
-\r
-!if exist("$(_RULESDIR)\rules.vc")\r
-!message *** Using $(_RULESDIR)\rules.vc\r
-!include "$(_RULESDIR)\rules.vc"\r
-!else\r
-!error *** Could not locate rules.vc in $(_RULESDIR)\r
-!endif\r
-\r
-!endif # _RULES_EXT_VC
\ No newline at end of file
diff --git a/pkgs/tdbcpostgres1.1.1/win/rules.vc b/pkgs/tdbcpostgres1.1.1/win/rules.vc
deleted file mode 100644 (file)
index b1a0346..0000000
+++ /dev/null
@@ -1,1807 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# rules.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file does all the hard work in terms of parsing build options,\r
-# compiler switches, defining common targets and macros. The Tcl makefile\r
-# directly includes this. Extensions include it via "rules-ext.vc".\r
-#\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
-# detailed documentation.\r
-#\r
-# See the file "license.terms" for information on usage and redistribution\r
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
-#\r
-# Copyright (c) 2001-2003 David Gravereaux.\r
-# Copyright (c) 2003-2008 Patrick Thoyts\r
-# Copyright (c) 2017      Ashok P. Nadkarni\r
-#------------------------------------------------------------------------------\r
-\r
-!ifndef _RULES_VC\r
-_RULES_VC = 1\r
-\r
-# The following macros define the version of the rules.vc nmake build system\r
-# For modifications that are not backward-compatible, you *must* change\r
-# the major version.\r
-RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
-\r
-# The PROJECT macro must be defined by parent makefile.\r
-!if "$(PROJECT)" == ""\r
-!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
-!endif\r
-\r
-!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
-PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
-!endif\r
-\r
-# Also special case Tcl and Tk to save some typing later\r
-DOING_TCL = 0\r
-DOING_TK  = 0\r
-!if "$(PROJECT)" == "tcl"\r
-DOING_TCL = 1\r
-!elseif "$(PROJECT)" == "tk"\r
-DOING_TK = 1\r
-!endif\r
-\r
-!ifndef NEED_TK\r
-# Backwards compatibility\r
-!ifdef PROJECT_REQUIRES_TK\r
-NEED_TK = $(PROJECT_REQUIRES_TK)\r
-!else\r
-NEED_TK = 0\r
-!endif\r
-!endif\r
-\r
-!ifndef NEED_TCL_SOURCE\r
-NEED_TCL_SOURCE = 0\r
-!endif\r
-\r
-!ifdef NEED_TK_SOURCE\r
-!if $(NEED_TK_SOURCE)\r
-NEED_TK = 1\r
-!endif\r
-!else\r
-NEED_TK_SOURCE = 0\r
-!endif\r
-\r
-################################################################\r
-# Nmake is a pretty weak environment in syntax and capabilities\r
-# so this file is necessarily verbose. It's broken down into\r
-# the following parts.\r
-#\r
-# 0. Sanity check that compiler environment is set up and initialize\r
-#    any built-in settings from the parent makefile\r
-# 1. First define the external tools used for compiling, copying etc.\r
-#    as this is independent of everything else.\r
-# 2. Figure out our build structure in terms of the directory, whether\r
-#    we are building Tcl or an extension, etc.\r
-# 3. Determine the compiler and linker versions\r
-# 4. Build the nmakehlp helper application\r
-# 5. Determine the supported compiler options and features\r
-# 6. Parse the OPTS macro value for user-specified build configuration\r
-# 7. Parse the STATS macro value for statistics instrumentation\r
-# 8. Parse the CHECKS macro for additional compilation checks\r
-# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
-# 10. Based on this selected configuration, construct the output\r
-#     directory and file paths\r
-# 11. Construct the paths where the package is to be installed\r
-# 12. Set up the actual options passed to compiler and linker based\r
-#     on the information gathered above.\r
-# 13. Define some standard build targets and implicit rules. These may\r
-#     be optionally disabled by the parent makefile.\r
-# 14. (For extensions only.) Compare the configuration of the target\r
-#     Tcl and the extensions and warn against discrepancies.\r
-#\r
-# One final note about the macro names used. They are as they are\r
-# for historical reasons. We would like legacy extensions to\r
-# continue to work with this make include file so be wary of\r
-# changing them for consistency or clarity.\r
-\r
-# 0. Sanity check compiler environment\r
-\r
-# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
-# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
-\r
-!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
-MSG = ^\r
-Visual C++ compiler environment not initialized.\r
-!error $(MSG)\r
-!endif\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-\r
-################################################################\r
-# 1. Define external programs being used\r
-\r
-#----------------------------------------------------------\r
-# Set the proper copy method to avoid overwrite questions\r
-# to the user when copying files and selecting the right\r
-# "delete all" method.\r
-#----------------------------------------------------------\r
-\r
-RMDIR  = rmdir /S /Q\r
-CPY    = xcopy /i /y >NUL\r
-CPYDIR  = xcopy /e /i /y >NUL\r
-COPY   = copy /y >NUL\r
-MKDIR   = mkdir\r
-\r
-######################################################################\r
-# 2. Figure out our build environment in terms of what we're building.\r
-#\r
-# (a) Tcl itself\r
-# (b) Tk\r
-# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
-# (d) a Tcl extension using libraries/includes from Tcl source directory\r
-#\r
-# This last is needed because some extensions still need\r
-# some Tcl interfaces that are not publicly exposed.\r
-#\r
-# The fragment will set the following macros:\r
-# ROOT - root of this module sources\r
-# COMPATDIR - source directory that holds compatibility sources\r
-# DOCDIR - source directory containing documentation files\r
-# GENERICDIR - platform-independent source directory\r
-# WINDIR - Windows-specific source directory\r
-# TESTDIR - directory containing test files\r
-# TOOLSDIR - directory containing build tools\r
-# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
-#    when building Tcl itself.\r
-# _INSTALLDIR - native form of the installation path. For Tcl\r
-#    this will be the root of the Tcl installation. For extensions\r
-#    this will be the lib directory under the root.\r
-# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
-#    headers and libraries from an installed Tcl, and 0 if built against\r
-#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
-#    named.\r
-# _TCL_H - native path to the tcl.h file\r
-#\r
-# If Tk is involved, also sets the following\r
-# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
-#    Tk itself.\r
-# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
-# _TK_H - native path to the tk.h file\r
-\r
-# Root directory for sources and assumed subdirectories\r
-ROOT = $(MAKEDIR)\..\r
-# The following paths CANNOT have spaces in them as they appear on the\r
-# left side of implicit rules.\r
-!ifndef COMPATDIR\r
-COMPATDIR      = $(ROOT)\compat\r
-!endif\r
-!ifndef DOCDIR\r
-DOCDIR         = $(ROOT)\doc\r
-!endif\r
-!ifndef GENERICDIR\r
-GENERICDIR     = $(ROOT)\generic\r
-!endif\r
-!ifndef TOOLSDIR\r
-TOOLSDIR       = $(ROOT)\tools\r
-!endif\r
-!ifndef TESTDIR\r
-TESTDIR        = $(ROOT)\tests\r
-!endif\r
-!ifndef LIBDIR\r
-!if exist("$(ROOT)\library")\r
-LIBDIR          = $(ROOT)\library\r
-!else\r
-LIBDIR          = $(ROOT)\lib\r
-!endif\r
-!endif\r
-!ifndef DEMODIR\r
-!if exist("$(LIBDIR)\demos")\r
-DEMODIR                = $(LIBDIR)\demos\r
-!else\r
-DEMODIR                = $(ROOT)\demos\r
-!endif\r
-!endif # ifndef DEMODIR\r
-# Do NOT enclose WINDIR in a !ifndef because Windows always defines\r
-# WINDIR env var to point to c:\windows!\r
-# TBD - This is a potentially dangerous conflict, rename WINDIR to\r
-# something else\r
-WINDIR         = $(ROOT)\win\r
-\r
-!ifndef RCDIR\r
-!if exist("$(WINDIR)\rc")\r
-RCDIR           = $(WINDIR)\rc\r
-!else\r
-RCDIR           = $(WINDIR)\r
-!endif\r
-!endif\r
-RCDIR = $(RCDIR:/=\)\r
-\r
-# The target directory where the built packages and binaries will be installed.\r
-# INSTALLDIR is the (optional) path specified by the user.\r
-# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
-!ifdef INSTALLDIR\r
-### Fix the path separators.\r
-_INSTALLDIR    = $(INSTALLDIR:/=\)\r
-!else\r
-### Assume the normal default.\r
-_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
-!endif\r
-\r
-!if $(DOING_TCL)\r
-\r
-# BEGIN Case 2(a) - Building Tcl itself\r
-\r
-# Only need to define _TCL_H\r
-_TCL_H = ..\generic\tcl.h\r
-\r
-# END Case 2(a) - Building Tcl itself\r
-\r
-!elseif $(DOING_TK)\r
-\r
-# BEGIN Case 2(b) - Building Tk\r
-\r
-TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
-!if "$(TCLDIR)" == ""\r
-!if [echo TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-!endif # TCLDIR == ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
-!if !exist("$(_TCL_H)")\r
-!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
-!endif\r
-\r
-_TK_H = ..\generic\tk.h\r
-\r
-# END Case 2(b) - Building Tk\r
-\r
-!else\r
-\r
-# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
-\r
-# If command line has specified Tcl location through TCLDIR, use it\r
-# else default to the INSTALLDIR setting\r
-!if "$(TCLDIR)" != ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
-TCLINSTALL     = 1\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
-TCLINSTALL     = 0\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-!endif\r
-\r
-!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
-\r
-TCLINSTALL     = 1\r
-TCLDIR          = $(_INSTALLDIR)\..\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TCLDIR                = $(_INSTALLDIR)\..\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-\r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!if [echo _TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TCLINSTALL      = 0\r
-TCLDIR         = $(_TCLDIR)\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-\r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!endif # TCLDIR\r
-\r
-!ifndef _TCL_H\r
-MSG =^\r
-Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-# Now do the same to locate Tk headers and libs if project requires Tk\r
-!if $(NEED_TK)\r
-\r
-!if "$(TKDIR)" != ""\r
-\r
-_TKDIR = $(TKDIR:/=\)\r
-!if exist("$(_TKDIR)\include\tk.h")\r
-TKINSTALL      = 1\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-!elseif exist("$(_TKDIR)\generic\tk.h")\r
-TKINSTALL      = 0\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-!endif\r
-\r
-!else # TKDIR not defined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-TKINSTALL      = 1\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TKDIR         = $(_INSTALLDIR)\..\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-TKDIR          = $(_TKDIR)\r
-\r
-!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!if [echo _TKDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
-!error *** Could not locate Tk source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TKINSTALL      = 0\r
-TKDIR          = $(_TKDIR)\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-\r
-!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!endif # TKDIR\r
-\r
-!ifndef _TK_H\r
-MSG =^\r
-Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-!endif # NEED_TK\r
-\r
-!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tcl.^\r
-*** Please set the TCLDIR macro to point to the Tcl sources.\r
-!error $(MSG)\r
-!endif\r
-\r
-!if $(NEED_TK_SOURCE)\r
-!if $(TKINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tk.^\r
-*** Please set the TKDIR macro to point to the Tk sources.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-\r
-# If INSTALLDIR set to Tcl installation root dir then reset to the\r
-# lib dir for installing extensions\r
-!if exist("$(_INSTALLDIR)\include\tcl.h")\r
-_INSTALLDIR=$(_INSTALLDIR)\lib\r
-!endif\r
-\r
-# END Case 2(c) or (d) - Building an extension\r
-!endif # if $(DOING_TCL)\r
-\r
-################################################################\r
-# 3. Determine compiler version and architecture\r
-# In this section, we figure out the compiler version and the\r
-# architecture for which we are building. This sets the\r
-# following macros:\r
-# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
-#     This is also printed by the compiler in dotted form 19.10 etc.\r
-# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
-#     compiler version 1200. This is kept only for legacy reasons as it\r
-#     does not make sense for recent Microsoft compilers. Only used for\r
-#     output directory names.\r
-# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
-# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
-# MACHINE - same as $(ARCH) - legacy\r
-# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
-\r
-cc32           = $(CC)   # built-in default.\r
-link32         = link\r
-lib32          = lib\r
-rc32           = $(RC)   # built-in default.\r
-\r
-#----------------------------------------------------------------\r
-# Figure out the compiler architecture and version by writing\r
-# the C macros to a file, preprocessing them with the C\r
-# preprocessor and reading back the created file\r
-\r
-_HASH=^#\r
-_VC_MANIFEST_EMBED_EXE=\r
-_VC_MANIFEST_EMBED_DLL=\r
-VCVER=0\r
-!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
-    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
-    && ![echo ARCH=IX86 >> vercl.x] \\r
-    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
-    && ![echo ARCH=AMD64 >> vercl.x] \\r
-    && ![echo $(_HASH)endif >> vercl.x] \\r
-    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
-!include vercl.i\r
-!if $(VCVERSION) < 1900\r
-!if ![echo VCVER= ^\> vercl.vc] \\r
-    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
-!include vercl.vc\r
-!endif\r
-!else\r
-# The simple calculation above does not apply to new Visual Studio releases\r
-# Keep the compiler version in its native form.\r
-VCVER = $(VCVERSION)\r
-!endif\r
-!endif\r
-\r
-!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# The MACHINE macro is used by legacy makefiles so set it as well\r
-!ifdef MACHINE\r
-!if "$(MACHINE)" == "x86"\r
-!undef MACHINE\r
-MACHINE = IX86\r
-!elseif "$(MACHINE)" == "x64"\r
-!undef MACHINE\r
-MACHINE = AMD64\r
-!endif\r
-!if "$(MACHINE)" != "$(ARCH)"\r
-!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
-!endif\r
-!else\r
-MACHINE=$(ARCH)\r
-!endif\r
-\r
-#---------------------------------------------------------------\r
-# The PLATFORM_IDENTIFY macro matches the values returned by\r
-# the Tcl platform::identify command\r
-!if "$(MACHINE)" == "AMD64"\r
-PLATFORM_IDENTIFY = win32-x86_64\r
-!else\r
-PLATFORM_IDENTIFY = win32-ix86\r
-!endif\r
-\r
-# The MULTIPLATFORM macro controls whether binary extensions are installed\r
-# in platform-specific directories. Intended to be set/used by extensions.\r
-!ifndef MULTIPLATFORM_INSTALL\r
-MULTIPLATFORM_INSTALL = 0\r
-!endif\r
-\r
-#------------------------------------------------------------\r
-# Figure out the *host* architecture by reading the registry\r
-\r
-!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
-NATIVE_ARCH=IX86\r
-!else\r
-NATIVE_ARCH=AMD64\r
-!endif\r
-\r
-# Since MSVC8 we must deal with manifest resources.\r
-!if $(VCVERSION) >= 1400\r
-_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
-_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
-!endif\r
-\r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
-################################################################\r
-# 4. Build the nmakehlp program\r
-# This is a helper app we need to overcome nmake's limiting\r
-# environment. We will call out to it to get various bits of\r
-# information about supported compiler options etc.\r
-#\r
-# Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
-#\r
-# Extensions built against an installed Tcl will use the installed\r
-# copy of Tcl's nmakehlp.c if there is one and their own version\r
-# otherwise. In the latter case, they would also be using their own\r
-# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
-# or rules.vc.\r
-#\r
-# Extensions built against Tcl sources will use the one from the Tcl source.\r
-#\r
-# When building an extension using a sufficiently new version of Tcl,\r
-# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
-# copy of nmakehlp.c to be used.\r
-\r
-!ifndef NMAKEHLPC\r
-# Default to the one in the current directory (the extension's own nmakehlp.c)\r
-NMAKEHLPC = nmakehlp.c\r
-\r
-!if !$(DOING_TCL)\r
-!if $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
-!endif\r
-!else # ! $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
-!endif\r
-!endif # $(TCLINSTALL)\r
-!endif # !$(DOING_TCL)\r
-\r
-!endif # NMAKEHLPC\r
-\r
-# We always build nmakehlp even if it exists since we do not know\r
-# what source it was built from.\r
-!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
-!endif\r
-\r
-################################################################\r
-# 5. Test for compiler features\r
-# Visual C++ compiler options have changed over the years. Check\r
-# which options are supported by the compiler in use.\r
-#\r
-# The following macros are set:\r
-# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
-# DEBUGFLAGS - the compiler flags to be used for debug builds\r
-# LINKERFLAGS - Flags passed to the linker\r
-#\r
-# Note that these are the compiler settings *available*, not those\r
-# that will be *used*. The latter depends on the OPTS macro settings\r
-# which we have not yet parsed.\r
-#\r
-# Also note that some of the flags in OPTIMIZATIONS are not really\r
-# related to optimization. They are placed there only for legacy reasons\r
-# as some extensions expect them to be included in that macro.\r
-\r
-# -Op improves float consistency. Note only needed for older compilers\r
-# Newer compilers do not need or support this option.\r
-!if [nmakehlp -c -Op]\r
-FPOPTS  = -Op\r
-!endif\r
-\r
-# Strict floating point semantics - present in newer compilers in lieu of -Op\r
-!if [nmakehlp -c -fp:strict]\r
-FPOPTS  = $(FPOPTS) -fp:strict\r
-!endif\r
-\r
-!if "$(MACHINE)" == "IX86"\r
-### test for pentium errata\r
-!if [nmakehlp -c -QI0f]\r
-!message *** Compiler has 'Pentium 0x0f fix'\r
-FPOPTS  = $(FPOPTS) -QI0f\r
-!else\r
-!message *** Compiler does not have 'Pentium 0x0f fix'\r
-!endif\r
-!endif\r
-\r
-### test for optimizations\r
-# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
-# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
-# stack probe at *every* function entry, not just those with more than\r
-# a page of stack allocation resulting in a performance hit.  However,\r
-# /O2 documentation is misleading as its stack probes are simply the\r
-# default page size locals allocation probes and not what is implied\r
-# by an explicit /Gs option.\r
-\r
-OPTIMIZATIONS = $(FPOPTS)\r
-\r
-!if [nmakehlp -c -O2]\r
-OPTIMIZING = 1\r
-OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
-!else\r
-# Legacy, really. All modern compilers support this\r
-!message *** Compiler does not have 'Optimizations'\r
-OPTIMIZING = 0\r
-!endif\r
-\r
-# Checks for buffer overflows in local arrays\r
-!if [nmakehlp -c -GS]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
-!endif\r
-\r
-# Link time optimization. Note that this option (potentially) makes\r
-# generated libraries only usable by the specific VC++ version that\r
-# created it. Requires /LTCG linker option\r
-!if [nmakehlp -c -GL]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
-CC_GL_OPT_ENABLED = 1\r
-!else\r
-# In newer compilers -GL and -YX are incompatible.\r
-!if [nmakehlp -c -YX]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
-!endif\r
-!endif # [nmakehlp -c -GL]\r
-\r
-DEBUGFLAGS     = $(FPOPTS)\r
-\r
-# Run time error checks. Not available or valid in a release, non-debug build\r
-# RTC is for modern compilers, -GZ is legacy\r
-!if [nmakehlp -c -RTC1]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
-!elseif [nmakehlp -c -GZ]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# Linker flags\r
-\r
-# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
-# if the linker supports a specific option. Without these flags link will\r
-# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
-# They are not passed through to the actual application / extension\r
-# link rules.\r
-!ifndef LINKER_TESTFLAGS\r
-LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
-!endif\r
-\r
-LINKERFLAGS     =\r
-\r
-# If compiler has enabled link time optimization, linker must too with -ltcg\r
-!ifdef CC_GL_OPT_ENABLED\r
-!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
-!endif\r
-!endif\r
-\r
-########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
-# Based on this, we will construct the actual switches to be passed to the\r
-# compiler and linker using the macros defined in the previous section.\r
-# The following macros are defined by this section based on OPTS\r
-# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
-#                1 -> build as a static library and shell\r
-# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
-# DEBUG - 1 -> debug build, 0 -> release builds\r
-# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
-# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
-# PGO     - 1 -> profile based optimization, 0 -> no\r
-# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
-#           0 -> link to static C runtime for static Tcl build.\r
-#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
-# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
-# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
-#           0 -> Use the non-thread allocator.\r
-# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
-#           C runtime, 0 -> use the debug C runtime.\r
-# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
-# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
-#           configuration (ignored for Tcl itself)\r
-# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
-# Further, LINKERFLAGS are modified based on above.\r
-\r
-# Default values for all the above\r
-STATIC_BUILD   = 0\r
-TCL_THREADS    = 1\r
-DEBUG          = 0\r
-SYMBOLS                = 0\r
-PROFILE                = 0\r
-PGO            = 0\r
-MSVCRT         = 1\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-USE_THREAD_ALLOC = 1\r
-UNCHECKED      = 0\r
-CONFIG_CHECK    = 1\r
-!if $(DOING_TCL)\r
-USE_STUBS       = 0\r
-!else\r
-USE_STUBS       = 1\r
-!endif\r
-\r
-# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
-# set the above macros based on OPTS content\r
-!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
-\r
-# OPTS are specified, parse them\r
-\r
-!if [nmakehlp -f $(OPTS) "static"]\r
-!message *** Doing static\r
-STATIC_BUILD   = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nostubs"]\r
-!message *** Not using stubs\r
-USE_STUBS      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-!message *** Doing nomsvcrt\r
-MSVCRT         = 0\r
-!else\r
-!if [nmakehlp -f $(OPTS) "msvcrt"]\r
-!message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
-!else\r
-MSVCRT         = 0\r
-!endif\r
-!endif\r
-!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-\r
-!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
-!message *** Doing staticpkg\r
-TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nothreads"]\r
-!message *** Compile explicitly for non-threaded tcl\r
-TCL_THREADS = 0\r
-USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "time64bit"]\r
-!message *** Force 64-bit time_t\r
-_USE_64BIT_TIME_T = 1\r
-!endif\r
-\r
-# Yes, it's weird that the "symbols" option controls DEBUG and\r
-# the "pdbs" option controls SYMBOLS. That's historical.\r
-!if [nmakehlp -f $(OPTS) "symbols"]\r
-!message *** Doing symbols\r
-DEBUG          = 1\r
-!else\r
-DEBUG          = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pdbs"]\r
-!message *** Doing pdbs\r
-SYMBOLS                = 1\r
-!else\r
-SYMBOLS                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "profile"]\r
-!message *** Doing profile\r
-PROFILE                = 1\r
-!else\r
-PROFILE                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pgi"]\r
-!message *** Doing profile guided optimization instrumentation\r
-PGO            = 1\r
-!elseif [nmakehlp -f $(OPTS) "pgo"]\r
-!message *** Doing profile guided optimization\r
-PGO            = 2\r
-!else\r
-PGO            = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "loimpact"]\r
-!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
-!endif\r
-\r
-# TBD - should get rid of this option\r
-!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
-!message *** Doing thrdalloc\r
-USE_THREAD_ALLOC = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "tclalloc"]\r
-USE_THREAD_ALLOC = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "unchecked"]\r
-!message *** Doing unchecked\r
-UNCHECKED = 1\r
-!else\r
-UNCHECKED = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
-CONFIG_CHECK = 1\r
-!else\r
-CONFIG_CHECK = 0\r
-!endif\r
-\r
-!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
-\r
-# Set linker flags based on above\r
-\r
-!if $(PGO) > 1\r
-!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!elseif $(PGO) > 0\r
-!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
-# The following macros are set by this section:\r
-# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
-#                 0 -> disables\r
-# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
-#                     0 -> disables\r
-\r
-# Default both are off\r
-TCL_MEM_DEBUG      = 0\r
-TCL_COMPILE_DEBUG   = 0\r
-\r
-!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
-\r
-!if [nmakehlp -f $(STATS) "memdbg"]\r
-!message *** Doing memdbg\r
-TCL_MEM_DEBUG      = 1\r
-!else\r
-TCL_MEM_DEBUG      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(STATS) "compdbg"]\r
-!message *** Doing compdbg\r
-TCL_COMPILE_DEBUG   = 1\r
-!else\r
-TCL_COMPILE_DEBUG   = 0\r
-!endif\r
-\r
-!endif\r
-\r
-####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
-# The following macros are set by this section:\r
-# WARNINGS - compiler switches that control the warnings level\r
-# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
-#                     0 -> enable deprecated functions\r
-\r
-# Defaults - Permit deprecated functions and warning level 3\r
-TCL_NO_DEPRECATED          = 0\r
-WARNINGS                   = -W3\r
-\r
-!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
-\r
-!if [nmakehlp -f $(CHECKS) "nodep"]\r
-!message *** Doing nodep check\r
-TCL_NO_DEPRECATED          = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
-!message *** Doing full warnings check\r
-WARNINGS                   = -W4\r
-!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
-!endif\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
-!message *** Doing 64bit portability warnings\r
-WARNINGS                   = $(WARNINGS) -Wp64\r
-!endif\r
-\r
-!endif\r
-\r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
-\r
-################################################################\r
-# 10. Construct output directory and file paths\r
-# Figure-out how to name our intermediate and output directories.\r
-# In order to avoid inadvertent mixing of object files built using\r
-# different compilers, build configurations etc.,\r
-#\r
-# Naming convention (suffixes):\r
-#   t = full thread support. (Not used for Tcl >= 8.7)\r
-#   s = static library (as opposed to an import library)\r
-#   g = linked to the debug enabled C run-time.\r
-#   x = special static build when it links to the dynamic C run-time.\r
-#\r
-# The following macros are set in this section:\r
-# SUFX - the suffix to use for binaries based on above naming convention\r
-# BUILDDIRTOP - the toplevel default output directory\r
-#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
-# TMP_DIR - directory where object files are created\r
-# OUT_DIR - directory where output executables are created\r
-# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
-# parent makefile (or command line). The default values are\r
-# based on BUILDDIRTOP.\r
-# STUBPREFIX - name of the stubs library for this project\r
-# PRJIMPLIB - output path of the generated project import library\r
-# PRJLIBNAME - name of generated project library\r
-# PRJLIB     - output path of generated project library\r
-# PRJSTUBLIBNAME - name of the generated project stubs library\r
-# PRJSTUBLIB - output path of the generated project stubs library\r
-# RESFILE - output resource file (only if not static build)\r
-\r
-SUFX       = tsgx\r
-\r
-!if $(DEBUG)\r
-BUILDDIRTOP = Debug\r
-!else\r
-BUILDDIRTOP = Release\r
-!endif\r
-\r
-!if "$(MACHINE)" != "IX86"\r
-BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
-!endif\r
-!if $(VCVER) > 6\r
-BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
-!endif\r
-\r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
-SUFX       = $(SUFX:g=)\r
-!endif\r
-\r
-TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
-\r
-!if !$(STATIC_BUILD)\r
-TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
-SUFX       = $(SUFX:s=)\r
-EXT        = dll\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!else\r
-TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
-EXT        = lib\r
-!if !$(MSVCRT)\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!endif\r
-!endif\r
-\r
-!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
-TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
-SUFX       = $(SUFX:t=)\r
-!endif\r
-\r
-!ifndef TMP_DIR\r
-TMP_DIR            = $(TMP_DIRFULL)\r
-!ifndef OUT_DIR\r
-OUT_DIR            = .\$(BUILDDIRTOP)\r
-!endif\r
-!else\r
-!ifndef OUT_DIR\r
-OUT_DIR            = $(TMP_DIR)\r
-!endif\r
-!endif\r
-\r
-# Relative paths -> absolute\r
-!if [echo OUT_DIR = \> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
-!endif\r
-!if [echo TMP_DIR = \>> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
-!endif\r
-!include nmakehlp.out\r
-\r
-# The name of the stubs library for the project being built\r
-STUBPREFIX      = $(PROJECT)stub\r
-\r
-# Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
-\r
-TCLSHNAME       = $(PROJECT)sh$(TCL_VERSION)$(SUFX).exe\r
-TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
-TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
-\r
-TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
-TCL_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-\r
-# When building extensions, we need to locate tclsh. Depending on version\r
-# of Tcl we are building against, this may or may not have a "t" suffix.\r
-# Try various possibilities in turn.\r
-TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist("$(TCLSH)") && $(TCL_THREADS)\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist("$(TCLSH)")\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-\r
-TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\lib\r
-TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
-TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
-\r
-!else # Building against Tcl sources\r
-\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist($(TCLSH)) && $(TCL_THREADS)\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist($(TCLSH))\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\library\r
-TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = $(_TCLDIR)\tools\r
-TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
-\r
-!endif # TCLINSTALL\r
-\r
-tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
-\r
-!endif # $(DOING_TCL)\r
-\r
-# We need a tclsh that will run on the host machine as part of the build.\r
-# IX86 runs on all architectures.\r
-!ifndef TCLSH_NATIVE\r
-!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
-TCLSH_NATIVE   = $(TCLSH)\r
-!else\r
-!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
-!endif\r
-!endif\r
-\r
-# Do the same for Tk and Tk extensions that require the Tk libraries\r
-!if $(DOING_TK) || $(NEED_TK)\r
-WISHNAMEPREFIX = wish\r
-WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
-TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
-TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
-\r
-!if $(DOING_TK)\r
-WISH           = $(OUT_DIR)\$(WISHNAME)\r
-TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
-TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # effectively NEED_TK\r
-\r
-!if $(TKINSTALL) # Building against installed Tk\r
-WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\include"\r
-!else # Building against Tk sources\r
-WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
-!endif # TKINSTALL\r
-tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
-\r
-!endif # $(DOING_TK)\r
-!endif # $(DOING_TK) || $(NEED_TK)\r
-\r
-# Various output paths\r
-PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
-\r
-PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
-\r
-# If extension parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
-!ifdef RCFILE\r
-RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
-!else\r
-RESFILE = $(TMP_DIR)\$(PROJECT).res\r
-!endif\r
-!endif\r
-\r
-###################################################################\r
-# 11. Construct the paths for the installation directories\r
-# The following macros get defined in this section:\r
-# LIB_INSTALL_DIR - where libraries should be installed\r
-# BIN_INSTALL_DIR - where the executables should be installed\r
-# DOC_INSTALL_DIR - where documentation should be installed\r
-# SCRIPT_INSTALL_DIR - where scripts should be installed\r
-# INCLUDE_INSTALL_DIR - where C include files should be installed\r
-# DEMO_INSTALL_DIR - where demos should be installed\r
-# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
-\r
-!if $(DOING_TCL) || $(DOING_TK)\r
-LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
-BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
-DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
-!if $(DOING_TCL)\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!else # DOING_TK\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
-\r
-!else # extension other than Tk\r
-\r
-PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
-!if $(MULTIPLATFORM_INSTALL)\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-!else\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-!endif\r
-DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
-DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
-\r
-!endif\r
-\r
-###################################################################\r
-# 12. Set up actual options to be passed to the compiler and linker\r
-# Now we have all the information we need, set up the actual flags and\r
-# options that we will pass to the compiler and linker. The main\r
-# makefile should use these in combination with whatever other flags\r
-# and switches are specific to it.\r
-# The following macros are defined, names are for historical compatibility:\r
-# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
-# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
-# crt - Compiler switch that selects the appropriate C runtime\r
-# cdebug - Compiler switches related to debug AND optimizations\r
-# cwarn - Compiler switches that set warning levels\r
-# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
-# ldebug - Linker switches controlling debug information and optimization\r
-# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
-# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
-# conlflags - complete linker switches for console program (subsumes lflags)\r
-# guilflags - complete linker switches for GUI program (subsumes lflags)\r
-# baselibs - minimum Windows libraries required. Parent makefile can\r
-#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
-\r
-OPTDEFINES     = -DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) -DSTDC_HEADERS\r
-\r
-!if $(TCL_MEM_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_MEM_DEBUG\r
-!endif\r
-!if $(TCL_COMPILE_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS\r
-!endif\r
-!if $(TCL_THREADS) && $(TCL_VERSION) <= 86\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_THREADS=1\r
-!if $(USE_THREAD_ALLOC)\r
-OPTDEFINES     = $(OPTDEFINES) -DUSE_THREAD_ALLOC=1\r
-!endif\r
-!endif\r
-!if $(STATIC_BUILD)\r
-OPTDEFINES     = $(OPTDEFINES) -DSTATIC_BUILD\r
-!endif\r
-!if $(TCL_NO_DEPRECATED)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_NO_DEPRECATED\r
-!endif\r
-\r
-!if $(USE_STUBS)\r
-# Note we do not define USE_TCL_STUBS even when building tk since some\r
-# test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
-USE_STUBS_DEFS  = -DUSE_TCL_STUBS -DUSE_TCLOO_STUBS\r
-!if $(NEED_TK)\r
-USE_STUBS_DEFS  = $(USE_STUBS_DEFS) -DUSE_TK_STUBS\r
-!endif\r
-!endif\r
-!endif # USE_STUBS\r
-\r
-!if !$(DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DNDEBUG\r
-!if $(OPTIMIZING)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_OPTIMIZED\r
-!endif\r
-!endif\r
-!if $(PROFILE)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_PROFILED\r
-!endif\r
-!if "$(MACHINE)" == "AMD64"\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_DO64BIT\r
-!endif\r
-!if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) -DNO_STRTOI64\r
-!endif\r
-\r
-!if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) -D_USE_64BIT_TIME_T\r
-!endif\r
-\r
-# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
-COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
-\r
-# Following is primarily for the benefit of extensions. Tcl 8.5 builds\r
-# Tcl without /DUNICODE, while 8.6 builds with it defined. When building\r
-# an extension, it is advisable (but not mandated) to use the same Windows\r
-# API as the Tcl build. This is accordingly defaulted below. A particular\r
-# extension can override this by pre-definining USE_WIDECHAR_API.\r
-!ifndef USE_WIDECHAR_API\r
-!if $(TCL_VERSION) > 85\r
-USE_WIDECHAR_API = 1\r
-!else\r
-USE_WIDECHAR_API = 0\r
-!endif\r
-!endif\r
-\r
-!if $(USE_WIDECHAR_API)\r
-COMPILERFLAGS = $(COMPILERFLAGS) /DUNICODE /D_UNICODE\r
-!endif\r
-\r
-# Like the TEA system only set this non empty for non-Tk extensions\r
-# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
-# so we pass both\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-PKGNAMEFLAGS = -DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
-               -DMODULE_SCOPE=extern\r
-!endif\r
-\r
-# crt picks the C run time based on selected OPTS\r
-!if $(MSVCRT)\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MDd\r
-!else\r
-crt = -MD\r
-!endif\r
-!else\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MTd\r
-!else\r
-crt = -MT\r
-!endif\r
-!endif\r
-\r
-# cdebug includes compiler options for debugging as well as optimization.\r
-!if $(DEBUG)\r
-\r
-# In debugging mode, optimizations need to be disabled\r
-cdebug = -Zi -Od $(DEBUGFLAGS)\r
-\r
-!else\r
-\r
-cdebug = $(OPTIMIZATIONS)\r
-!if $(SYMBOLS)\r
-cdebug = $(cdebug) -Zi\r
-!endif\r
-\r
-!endif # $(DEBUG)\r
-\r
-# cwarn includes default warning levels.\r
-cwarn = $(WARNINGS)\r
-\r
-!if "$(MACHINE)" == "AMD64"\r
-# Disable pointer<->int warnings related to cast between different sizes\r
-# There are a gadzillion of these due to use of ClientData and\r
-# clutter up compiler\r
-# output increasing chance of a real warning getting lost. So disable them.\r
-# Eventually some day, Tcl will be 64-bit clean.\r
-cwarn = $(cwarn) -wd4311 -wd4312\r
-!endif\r
-\r
-### Common compiler options that are architecture specific\r
-!if "$(MACHINE)" == "ARM"\r
-carch = -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
-!else\r
-carch =\r
-!endif\r
-\r
-!if $(DEBUG)\r
-# Turn warnings into errors\r
-cwarn = $(cwarn) -WX\r
-!endif\r
-\r
-INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WINDIR)" -I"$(COMPATDIR)"\r
-!endif\r
-\r
-# These flags are defined roughly in the order of the pre-reform\r
-# rules.vc/makefile.vc to help visually compare that the pre- and\r
-# post-reform build logs\r
-\r
-# cflags contains generic flags used for building practically all object files\r
-cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
-\r
-# appcflags contains $(cflags) and flags for building the application\r
-# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
-# flags used for building shared object files The two differ in the\r
-# BUILD_$(PROJECT) macro which should be defined only for the shared\r
-# library *implementation* and not for its caller interface\r
-\r
-appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
-appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
-pkgcflags = $(appcflags) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-\r
-# stubscflags contains $(cflags) plus flags used for building a stubs\r
-# library for the package.  Note: -DSTATIC_BUILD is defined in\r
-# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
-# library. However the stubs library is ALWAYS static hence included\r
-# here irrespective of the OPTS setting.\r
-#\r
-# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
-# without stating why. Tcl itself compiled stubs libs with this flag.\r
-# so we do not remove it from cflags. -GL may prevent extensions\r
-# compiled with one VC version to fail to link against stubs library\r
-# compiled with another VC version. Check for this and fix accordingly.\r
-stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl -DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
-\r
-# Link flags\r
-\r
-!if $(DEBUG)\r
-ldebug = -debug -debugtype:cv\r
-!else\r
-ldebug = -release -opt:ref -opt:icf,3\r
-!if $(SYMBOLS)\r
-ldebug = $(ldebug) -debug -debugtype:cv\r
-!endif\r
-!endif\r
-\r
-# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
-!if $(PROFILE)\r
-ldebug= $(ldebug) -profile\r
-!endif\r
-\r
-### Declarations common to all linker versions\r
-lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-lflags = $(lflags) -nodefaultlib:libucrt.lib\r
-!endif\r
-\r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
-dlllflags = $(lflags) -dll\r
-conlflags = $(lflags) -subsystem:console\r
-guilflags = $(lflags) -subsystem:windows\r
-\r
-# Libraries that are required for every image.\r
-# Extensions should define any additional libraries with $(PRJ_LIBS)\r
-winlibs   = kernel32.lib advapi32.lib\r
-\r
-!if $(NEED_TK)\r
-winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
-!endif\r
-\r
-# Avoid 'unresolved external symbol __security_cookie' errors.\r
-# c.f. http://support.microsoft.com/?id=894573\r
-!if "$(MACHINE)" == "AMD64"\r
-!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
-winlibs   = $(winlibs) bufferoverflowU.lib\r
-!endif\r
-!endif\r
-\r
-baselibs = $(winlibs) $(PRJ_LIBS)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-baselibs   = $(baselibs) ucrt.lib\r
-!endif\r
-\r
-################################################################\r
-# 13. Define standard commands, common make targets and implicit rules\r
-\r
-CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
-CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
-CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
-\r
-LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
-DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-\r
-CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
-           $(TCL_INCLUDES) \\r
-           -DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           -DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
-           -DDOTVERSION=\"$(DOTVERSION)\" \\r
-           -DVERSION=\"$(VERSION)\" \\r
-           -DSUFX=\"$(SUFX)\" \\r
-           -DPROJECT=\"$(PROJECT)\" \\r
-           -DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
-\r
-!ifndef DEFAULT_BUILD_TARGET\r
-DEFAULT_BUILD_TARGET = $(PROJECT)\r
-!endif\r
-\r
-default-target: $(DEFAULT_BUILD_TARGET)\r
-\r
-!if $(MULTIPLATFORM_INSTALL)\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!else\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!endif\r
-\r
-default-pkgindex-tea:\r
-       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
-@PACKAGE_VERSION@    $(DOTVERSION)\r
-@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
-@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
-@PKG_LIB_FILE@       $(PRJLIBNAME)\r
-<<\r
-\r
-default-install: default-install-binaries default-install-libraries\r
-!if $(SYMBOLS)\r
-default-install: default-install-pdbs\r
-!endif\r
-\r
-# Again to deal with historical brokenness, there is some confusion\r
-# in terminlogy. For extensions, the "install-binaries" was used to\r
-# locate target directory for *binary shared libraries* and thus\r
-# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
-# for executables (exes). On the other hand the "install-libraries"\r
-# target is for *scripts* and should have been called "install-scripts".\r
-default-install-binaries: $(PRJLIB)\r
-       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
-\r
-# Alias for default-install-scripts\r
-default-install-libraries: default-install-scripts\r
-\r
-default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
-       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
-       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
-       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
-       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
-\r
-default-install-stubs:\r
-       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
-       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
-\r
-default-install-pdbs:\r
-       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
-\r
-default-install-docs-html:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-docs-n:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-demos:\r
-       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
-       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
-       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
-\r
-default-clean:\r
-       @echo Cleaning $(TMP_DIR)\* ...\r
-       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
-       @echo Cleaning $(WINDIR)\nmakehlp.obj, nmakehlp.exe ...\r
-       @if exist $(WINDIR)\nmakehlp.obj del $(WINDIR)\nmakehlp.obj\r
-       @if exist $(WINDIR)\nmakehlp.exe del $(WINDIR)\nmakehlp.exe\r
-       @if exist $(WINDIR)\nmakehlp.out del $(WINDIR)\nmakehlp.out\r
-       @echo Cleaning $(WINDIR)\nmhlp-out.txt ...\r
-       @if exist $(WINDIR)\nmhlp-out.txt del $(WINDIR)\nmhlp-out.txt\r
-       @echo Cleaning $(WINDIR)\_junk.pch ...\r
-       @if exist $(WINDIR)\_junk.pch del $(WINDIR)\_junk.pch\r
-       @echo Cleaning $(WINDIR)\vercl.x, vercl.i ...\r
-       @if exist $(WINDIR)\vercl.x del $(WINDIR)\vercl.x\r
-       @if exist $(WINDIR)\vercl.i del $(WINDIR)\vercl.i\r
-       @echo Cleaning $(WINDIR)\versions.vc, version.vc ...\r
-       @if exist $(WINDIR)\versions.vc del $(WINDIR)\versions.vc\r
-       @if exist $(WINDIR)\version.vc del $(WINDIR)\version.vc\r
-\r
-default-hose: default-clean\r
-       @echo Hosing $(OUT_DIR)\* ...\r
-       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
-\r
-# Only for backward compatibility\r
-default-distclean: default-hose\r
-\r
-default-setup:\r
-       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
-       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
-\r
-!if "$(TESTPAT)" != ""\r
-TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
-!endif\r
-\r
-default-test: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
-\r
-default-shell: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       $(DEBUGGER) $(TCLSH)\r
-\r
-# Generation of Windows version resource\r
-!ifdef RCFILE\r
-\r
-# Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
-$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
-       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
-\r
-!else\r
-\r
-# If parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
-\r
-$(TMP_DIR)\$(PROJECT).rc:\r
-       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
-#include <winver.h>\r
-\r
-VS_VERSION_INFO VERSIONINFO\r
- FILEVERSION   COMMAVERSION\r
- PRODUCTVERSION        COMMAVERSION\r
- FILEFLAGSMASK 0x3fL\r
-#ifdef DEBUG\r
- FILEFLAGS     VS_FF_DEBUG\r
-#else\r
- FILEFLAGS     0x0L\r
-#endif\r
- FILEOS                VOS_NT_WINDOWS32\r
- FILETYPE      VFT_DLL\r
- FILESUBTYPE   0x0L\r
-BEGIN\r
-    BLOCK "StringFileInfo"\r
-    BEGIN\r
-        BLOCK "040904b0"\r
-        BEGIN\r
-            VALUE "FileDescription",  "Tcl extension " PROJECT\r
-            VALUE "OriginalFilename", PRJLIBNAME\r
-            VALUE "FileVersion",      DOTVERSION\r
-            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
-            VALUE "ProductVersion",   DOTVERSION\r
-        END\r
-    END\r
-    BLOCK "VarFileInfo"\r
-    BEGIN\r
-        VALUE "Translation", 0x409, 1200\r
-    END\r
-END\r
-\r
-<<\r
-\r
-!endif # ifdef RCFILE\r
-\r
-!ifndef DISABLE_IMPLICIT_RULES\r
-DISABLE_IMPLICIT_RULES = 0\r
-!endif\r
-\r
-!if !$(DISABLE_IMPLICIT_RULES)\r
-# Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
-\r
-{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(WINDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(WINDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-.SUFFIXES:\r
-.SUFFIXES:.c .rc\r
-\r
-!endif\r
-\r
-################################################################\r
-# 14. Sanity check selected options against Tcl build options\r
-# When building an extension, certain configuration options should\r
-# match the ones used when Tcl was built. Here we check and\r
-# warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
-TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
-!endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
-!endif\r
-!endif # TCLINSTALL\r
-\r
-!if $(CONFIG_CHECK)\r
-!ifdef TCLNMAKECONFIG\r
-!include $(TCLNMAKECONFIG)\r
-\r
-!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
-!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
-!endif\r
-!if defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
-!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
-!endif\r
-!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
-!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
-!endif\r
-!endif\r
-\r
-!endif # TCLNMAKECONFIG\r
-\r
-!endif # ! $(DOING_TCL)\r
-\r
-\r
-#----------------------------------------------------------\r
-# Display stats being used.\r
-#----------------------------------------------------------\r
-\r
-!if !$(DOING_TCL)\r
-!message *** Building against Tcl at '$(_TCLDIR)'\r
-!endif\r
-!if !$(DOING_TK) && $(NEED_TK)\r
-!message *** Building against Tk at '$(_TKDIR)'\r
-!endif\r
-!message *** Intermediate directory will be '$(TMP_DIR)'\r
-!message *** Output directory will be '$(OUT_DIR)'\r
-!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
-!message *** Suffix for binaries will be '$(SUFX)'\r
-!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
-\r
-!endif # ifdef _RULES_VC\r
diff --git a/pkgs/tdbcpostgres1.1.1/win/targets.vc b/pkgs/tdbcpostgres1.1.1/win/targets.vc
deleted file mode 100644 (file)
index 7f1d388..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# targets.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file defines some standard targets for the convenience of extensions\r
-# and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
-\r
-$(PROJECT): setup pkgindex $(PRJLIB)\r
-\r
-!ifdef PRJ_STUBOBJS\r
-$(PROJECT): $(PRJSTUBLIB)\r
-$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
-       $(LIBCMD) $**\r
-\r
-$(PRJ_STUBOBJS):\r
-       $(CCSTUBSCMD) %s\r
-!endif # PRJ_STUBOBJS\r
-\r
-!ifdef PRJ_MANIFEST\r
-$(PROJECT): $(PRJLIB).manifest\r
-$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
-       @nmakehlp -s << $** >$@\r
-@MACHINE@        $(MACHINE:IX86=X86)\r
-<<\r
-!endif\r
-\r
-!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
-$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
-!if $(STATIC_BUILD)\r
-       $(LIBCMD) $**\r
-!else\r
-       $(DLLCMD) $**\r
-       $(_VC_MANIFEST_EMBED_DLL)\r
-!endif\r
-       -@del $*.exp\r
-!endif\r
-\r
-!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
-$(PRJ_OBJS): $(PRJ_HEADERS)\r
-!endif\r
-\r
-# If parent makefile has defined stub objects, add their installation\r
-# to the default install\r
-!if "$(PRJ_STUBOBJS)" != ""\r
-default-install: default-install-stubs\r
-!endif\r
-\r
-# Unlike the other default targets, these cannot be in rules.vc because\r
-# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
-# that the parent makefile will not define until after including rules-ext.vc\r
-!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
-default-install: default-install-headers\r
-default-install-headers:\r
-       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
-       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
-!endif\r
-\r
-!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
-DISABLE_STANDARD_TARGETS = 0\r
-!endif\r
-\r
-!if "$(DISABLE_TARGET_setup)" == ""\r
-DISABLE_TARGET_setup = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_install)" == ""\r
-DISABLE_TARGET_install = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_clean)" == ""\r
-DISABLE_TARGET_clean = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_test)" == ""\r
-DISABLE_TARGET_test = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_shell)" == ""\r
-DISABLE_TARGET_shell = 0\r
-!endif\r
-\r
-!if !$(DISABLE_STANDARD_TARGETS)\r
-!if !$(DISABLE_TARGET_setup)\r
-setup: default-setup\r
-!endif\r
-!if !$(DISABLE_TARGET_install)\r
-install: default-install\r
-!endif\r
-!if !$(DISABLE_TARGET_clean)\r
-clean: default-clean\r
-realclean: hose\r
-hose: default-hose\r
-distclean: realclean default-distclean\r
-!endif\r
-!if !$(DISABLE_TARGET_test)\r
-test: default-test\r
-!endif\r
-!if !$(DISABLE_TARGET_shell)\r
-shell: default-shell\r
-!endif\r
-!endif # DISABLE_STANDARD_TARGETS\r
similarity index 99%
rename from pkgs/tdbcpostgres1.1.1/ChangeLog
rename to pkgs/tdbcpostgres1.1.2/ChangeLog
index 7f46e07..414be97 100644 (file)
@@ -1,6 +1,6 @@
 *** Now that tdbcpostgres is under Fossil control, the ChangeLog is
     no longer being maintained. Please refer to the change history at
-    http://core.tcl.tk/tdbcpostgres/timeline/
+    https://core.tcl-lang.org/tdbcpostgres/timeline/
 
 2014-10-23  Don Porter  <dgp@users.sourceforge.net>
 
similarity index 98%
rename from pkgs/tdbcpostgres1.1.1/Makefile.in
rename to pkgs/tdbcpostgres1.1.2/Makefile.in
index 72b7996..7ae8aa4 100644 (file)
@@ -101,8 +101,6 @@ CFLAGS_WARNING      = @CFLAGS_WARNING@
 EXEEXT         = @EXEEXT@
 LDFLAGS_DEFAULT        = @LDFLAGS_DEFAULT@
 MAKE_LIB       = @MAKE_LIB@
-MAKE_SHARED_LIB        = @MAKE_SHARED_LIB@
-MAKE_STATIC_LIB        = @MAKE_STATIC_LIB@
 MAKE_STUB_LIB  = @MAKE_STUB_LIB@
 OBJEXT         = @OBJEXT@
 RANLIB         = @RANLIB@
@@ -162,7 +160,7 @@ PKG_CFLAGS  = @PKG_CFLAGS@
 # you do not compile with a similar machine setup as the Tcl core was
 # compiled with.
 #DEFS          = $(TCL_DEFS) @DEFS@ $(PKG_CFLAGS)
-DEFS           = @DEFS@ $(PKG_CFLAGS)
+DEFS           = @DEFS@ $(PKG_CFLAGS) -DTCL_NO_DEPRECATED=1
 
 # Move pkgIndex.tcl to 'BINARIES' var if it is generated in the Makefile
 CONFIG_CLEAN_FILES = Makefile pkgIndex.tcl
@@ -172,7 +170,10 @@ CPPFLAGS   = @CPPFLAGS@
 LIBS           = @PKG_LIBS@ @LIBS@
 AR             = @AR@
 CFLAGS         = @CFLAGS@
-COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LDFLAGS                = @LDFLAGS@
+LDFLAGS_DEFAULT                        = @LDFLAGS_DEFAULT@
+COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
+                         $(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
 
 GDB            = gdb
 VALGRIND       = valgrind
similarity index 96%
rename from pkgs/tdbcpostgres1.1.1/README
rename to pkgs/tdbcpostgres1.1.2/README
index c31f924..8935dfb 100644 (file)
@@ -1,6 +1,6 @@
 README: tdbcpostgres
 
-    This is the 1.1.1 source distribution of the driver for Tcl
+    This is the 1.1.2 source distribution of the driver for Tcl
     Database Connectivity (TDBC) to access Postgres databases. TDBC and
     its drivers are available from a Fossil version control repository
     at http://tdbc.tcl.tk/
similarity index 98%
rename from pkgs/tdbcpostgres1.1.1/configure
rename to pkgs/tdbcpostgres1.1.2/configure
index 4f5024e..22e30b3 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for tdbcpostgres 1.1.1.
+# Generated by GNU Autoconf 2.69 for tdbcpostgres 1.1.2.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='tdbcpostgres'
 PACKAGE_TARNAME='tdbcpostgres'
-PACKAGE_VERSION='1.1.1'
-PACKAGE_STRING='tdbcpostgres 1.1.1'
+PACKAGE_VERSION='1.1.2'
+PACKAGE_STRING='tdbcpostgres 1.1.2'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -627,7 +627,6 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -635,6 +634,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1304,7 +1305,7 @@ 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 tdbcpostgres 1.1.1 to adapt to many kinds of systems.
+\`configure' configures tdbcpostgres 1.1.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1365,7 +1366,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of tdbcpostgres 1.1.1:";;
+     short | recursive ) echo "Configuration of tdbcpostgres 1.1.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1466,7 +1467,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-tdbcpostgres configure 1.1.1
+tdbcpostgres configure 1.1.2
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2068,7 +2069,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by tdbcpostgres $as_me 1.1.1, which was
+It was created by tdbcpostgres $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3578,10 +3579,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3615,12 +3612,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3926,7 +3917,7 @@ $as_echo_n "checking For TDBC_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3940,7 +3931,7 @@ $as_echo "using TDBC_STUB_LIB_PATH ${TDBC_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3969,7 +3960,7 @@ $as_echo_n "checking For tdbc_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3983,7 +3974,7 @@ $as_echo "using tdbc_STUB_LIB_PATH ${tdbc_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5600,7 +5591,7 @@ if test "${TCL_MAJOR_VERSION}" -eq 8 ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5625,7 +5616,7 @@ if test "x${TEA_PLATFORM}" = "xwindows" -a "x${GCC}" != "xyes" ; then
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5637,7 +5628,7 @@ else
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6585,7 +6576,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6610,7 +6601,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6759,14 +6750,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6847,14 +6838,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -6869,7 +6860,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6945,39 +6936,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -7102,8 +7060,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -7130,7 +7088,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -7199,8 +7157,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -7216,8 +7174,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -7226,8 +7184,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -7255,8 +7213,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -7279,7 +7237,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -7289,9 +7247,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -7356,8 +7327,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -7374,11 +7345,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -7396,7 +7367,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -7404,32 +7375,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -7738,7 +7683,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -7808,13 +7753,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7914,7 +7859,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -7951,8 +7896,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -8251,6 +8196,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -8645,7 +8592,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -8659,11 +8605,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -8802,7 +8743,7 @@ if test "x$ac_cv_lib_ws2_32_main" = xyes; then :
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lLiIbB$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -8846,7 +8787,7 @@ if test "x$ac_cv_lib_winsock_main" = xyes; then :
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\(^-.*\)\.lLiIbB$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -8867,7 +8808,7 @@ fi
 
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8893,7 +8834,7 @@ rm -f conftest*
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8981,14 +8922,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8996,9 +8937,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -9569,7 +9510,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by tdbcpostgres $as_me 1.1.1, which was
+This file was extended by tdbcpostgres $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -9622,7 +9563,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-tdbcpostgres config.status 1.1.1
+tdbcpostgres config.status 1.1.2
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/tdbcpostgres1.1.1/configure.ac
rename to pkgs/tdbcpostgres1.1.2/configure.ac
index ae14c08..c8583ac 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([tdbcpostgres], [1.1.1])
+AC_INIT([tdbcpostgres], [1.1.2])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
@@ -366,7 +366,7 @@ typedef struct ResultSetData {
 #define DecrResultSetRefCount(x)               \
     do {                                       \
        ResultSetData* rs = (x);                \
-       if (--(rs->refCount) <= 0) {            \
+       if (rs->refCount-- <= 1) {              \
            DeleteResultSet(rs);                \
        }                                       \
     } while(0)
@@ -698,6 +698,8 @@ static void
 DummyNoticeProcessor(void* clientData,
                     const PGresult* message)
 {
+    (void)clientData;
+    (void)message;
 }
 \f
 /*
@@ -1337,7 +1339,7 @@ ConnectionConstructor(
 
 static int
 ConnectionBegintransactionMethod(
-    ClientData clientData,     /* Unused */
+    ClientData dummy,  /* Unused */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1347,6 +1349,7 @@ ConnectionBegintransactionMethod(
                                /* The current connection object */
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1394,7 +1397,7 @@ ConnectionBegintransactionMethod(
 
 static int
 ConnectionCommitMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1405,6 +1408,7 @@ ConnectionCommitMethod(
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1451,7 +1455,7 @@ ConnectionCommitMethod(
 
 static int
 ConnectionColumnsMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1474,6 +1478,7 @@ ConnectionColumnsMethod(
     Tcl_Obj* name;             /* Name of a column */
     Tcl_Obj* sqlQuery = Tcl_NewStringObj("SELECT * FROM ", -1);
                                /* Query used */
+    (void)dummy;
 
     Tcl_IncrRefCount(sqlQuery);
 
@@ -1627,7 +1632,7 @@ ConnectionColumnsMethod(
  */
 
 static int ConnectionConfigureMethod(
-     ClientData clientData,
+     ClientData dummy,
      Tcl_Interp* interp,
      Tcl_ObjectContext objectContext,
      int objc,
@@ -1640,6 +1645,8 @@ static int ConnectionConfigureMethod(
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
+    (void)dummy;
+
     return ConfigureConnection(cdata, interp, objc, objv, skip);
 }
 \f
@@ -1666,7 +1673,7 @@ static int ConnectionConfigureMethod(
 
 static int
 ConnectionRollbackMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1677,6 +1684,7 @@ ConnectionRollbackMethod(
     ConnectionData* cdata = (ConnectionData*)
        Tcl_ObjectGetMetadata(thisObject, &connectionDataType);
                                /* Instance data */
+    (void)dummy;
 
     /* Check parameters */
 
@@ -1723,7 +1731,7 @@ ConnectionRollbackMethod(
 
 static int
 ConnectionTablesMethod(
-    ClientData clientData,     /* Completion type */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext objectContext, /* Object context */
     int objc,                  /* Parameter count */
@@ -1745,6 +1753,8 @@ ConnectionTablesMethod(
                                         -1);
                                /* SQL query for table list */
     int i;
+    (void)dummy;
+
     Tcl_IncrRefCount(sqlQuery);
 
     /* Check parameters */
@@ -1851,6 +1861,9 @@ CloneConnection(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("Postgres connections are not clonable",
                                      -1));
@@ -1899,10 +1912,12 @@ DeleteCmd (
 
 static int
 CloneCmd(
-    Tcl_Interp* interp,                /* Tcl interpreter */
+    Tcl_Interp* dummy,         /* Tcl interpreter */
     ClientData oldClientData,  /* Environment handle to be discarded */
     ClientData* newClientData  /* New environment handle to be used */
 ) {
+    (void)dummy;
+
     *newClientData = oldClientData;
     return TCL_OK;
 }
@@ -2092,6 +2107,8 @@ ResultDescToTcl(
        unsigned int fieldCount = PQnfields(result);
        unsigned int i;
        char numbuf[16];
+       (void)flags;
+
        for (i = 0; i < fieldCount; ++i) {
            int isNew;
            int count = 1;
@@ -2148,7 +2165,7 @@ ResultDescToTcl(
 
 static int
 StatementConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2171,7 +2188,8 @@ StatementConstructor(
     int tokenLen;              /* Length of a token */
     PGresult* res;             /* Temporary result of libpq calls */
     char tmpstr[30];           /* Temporary array for strings */
-    int i,j;
+    int i, j;
+    (void)dummy;
 
 
     /* Find the connection object, and get its data. */
@@ -2322,7 +2340,7 @@ StatementConstructor(
 
 static int
 StatementParamsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2342,6 +2360,7 @@ StatementParamsMethod(
     Tcl_Obj* retVal;           /* Return value from this command */
     Tcl_HashEntry* typeHashEntry;
     int i;
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
@@ -2408,7 +2427,7 @@ StatementParamsMethod(
 
 static int
 StatementParamtypeMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2441,6 +2460,7 @@ StatementParamtypeMethod(
     Tcl_Obj* errorObj;         /* Error message */
 
     int i;
+    (void)dummy;
 
     /* Check parameters */
 
@@ -2593,6 +2613,9 @@ CloneStatement(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("Postgres statements are not clonable",
                                      -1));
@@ -2624,7 +2647,7 @@ CloneStatement(
 
 static int
 ResultSetConstructor(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2655,6 +2678,7 @@ ResultSetConstructor(
     PGresult* res;             /* Temporary result */
     int i;
     int status = TCL_ERROR;    /* Return status */
+    (void)dummy;
 
     /* Check parameter count */
 
@@ -2921,7 +2945,7 @@ ResultSetConstructor(
 
 static int
 ResultSetColumnsMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -2932,6 +2956,7 @@ ResultSetColumnsMethod(
     ResultSetData* rdata = (ResultSetData*)
        Tcl_ObjectGetMetadata(thisObject, &resultSetDataType);
     StatementData* sdata = (StatementData*) rdata->sdata;
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "?pattern?");
@@ -3141,6 +3166,9 @@ CloneResultSet(
     ClientData metadata,       /* Metadata to be cloned */
     ClientData* newMetaData    /* Where to put the cloned metadata */
 ) {
+    (void)metadata;
+    (void)newMetaData;
+
     Tcl_SetObjResult(interp,
                     Tcl_NewStringObj("Postgres result sets are not clonable",
                                      -1));
@@ -3165,7 +3193,7 @@ CloneResultSet(
 
 static int
 ResultSetRowcountMethod(
-    ClientData clientData,     /* Not used */
+    ClientData dummy,  /* Not used */
     Tcl_Interp* interp,                /* Tcl interpreter */
     Tcl_ObjectContext context, /* Object context  */
     int objc,                  /* Parameter count */
@@ -3182,6 +3210,7 @@ ResultSetRowcountMethod(
     ConnectionData* cdata = sdata->cdata;
     PerInterpData* pidata = cdata->pidata; /* Per-interp data */
     Tcl_Obj** literals = pidata->literals; /* Literal pool */
+    (void)dummy;
 
     if (objc != 2) {
        Tcl_WrongNumArgs(interp, 2, objv, "");
diff --git a/pkgs/tdbcpostgres1.1.2/tclconfig/README.txt b/pkgs/tdbcpostgres1.1.2/tclconfig/README.txt
new file mode 100644 (file)
index 0000000..715cb9d
--- /dev/null
@@ -0,0 +1,26 @@
+These files comprise the basic building blocks for a Tcl Extension
+Architecture (TEA) extension.  For more information on TEA see:
+
+       http://www.tcl.tk/doc/tea/
+
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
+
+       https://core.tcl-lang.org/tclconfig
+
+This package is a freely available open source package.  You can do
+virtually anything you like with it, such as modifying it, redistributing
+it, and selling it either in whole or in part.
+
+CONTENTS
+========
+The following is a short description of the files you will find in
+the sample extension.
+
+README.txt     This file
+
+install-sh     Program used for copying binaries and script files
+               to their install locations.
+
+tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
+               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/tdbcpostgres1.1.2/tclconfig/install-sh b/pkgs/tdbcpostgres1.1.2/tclconfig/install-sh
new file mode 100644 (file)
index 0000000..21b733a
--- /dev/null
@@ -0,0 +1,518 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2020-07-26.22; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# 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.
+
+tab='  '
+nl='
+'
+IFS=" $tab$nl"
+
+# Set DOITPROG to "echo" to test this script.
+
+doit=${DOITPROG-}
+doit_exec=${doit:-exec}
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+is_target_a_directory=possibly
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+        shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
+
+    -o) chowncmd="$chownprog $2"
+        shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -S) stripcmd="$stripprog $2"
+        shift;;
+
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
+
+    -T) is_target_a_directory=never;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --) shift
+        break;;
+
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename.
+    if test -d "$dst"; then
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
+      fi
+      dstdir=$dst
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
+      dstdir_status=0
+    else
+      dstdir=`dirname "$dst"`
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
+       else
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
+       fi
+       trap '' 0;;
+    esac
+
+    if
+      $posix_mkdir && (
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
+      esac
+
+      oIFS=$IFS
+      IFS=/
+      set -f
+      set fnord $dstdir
+      shift
+      set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # 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 $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       set +f &&
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC0"
+# time-stamp-end: "; # UTC"
+# End:
\ No newline at end of file
diff --git a/pkgs/tdbcpostgres1.1.2/tclconfig/tcl.m4 b/pkgs/tdbcpostgres1.1.2/tclconfig/tcl.m4
new file mode 100644 (file)
index 0000000..8d24e7f
--- /dev/null
@@ -0,0 +1,4056 @@
+# tcl.m4 --
+#
+#      This file provides a set of autoconf macros to help TEA-enable
+#      a Tcl extension.
+#
+# Copyright (c) 1999-2000 Ajuba Solutions.
+# Copyright (c) 2002-2005 ActiveState Corporation.
+#
+# See the file "license.terms" for information on usage and redistribution
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+AC_PREREQ(2.57)
+
+# Possible values for key variables defined:
+#
+# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
+# TEA_PLATFORM        - windows unix
+# TEA_TK_EXTENSION    - True if this is a Tk extension
+#
+
+#------------------------------------------------------------------------
+# TEA_PATH_TCLCONFIG --
+#
+#      Locate the tclConfig.sh file and perform a sanity check on
+#      the Tcl compile flags
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tcl=...
+#
+#      Defines the following vars:
+#              TCL_BIN_DIR     Full path to the directory containing
+#                              the tclConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TCLCONFIG], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+    #
+    # Ok, lets find the tcl configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tcl
+    #
+
+    if test x"${no_tcl}" = x ; then
+       # we reset no_tcl in case something fails here
+       no_tcl=true
+       AC_ARG_WITH(tcl,
+           AS_HELP_STRING([--with-tcl],
+               [directory containing tcl configuration (tclConfig.sh)]),
+           [with_tclconfig="${withval}"])
+       AC_MSG_CHECKING([for Tcl configuration])
+       AC_CACHE_VAL(ac_cv_c_tclconfig,[
+
+           # First check to see if --with-tcl was specified.
+           if test x"${with_tclconfig}" != x ; then
+               case "${with_tclconfig}" in
+                   */tclConfig.sh )
+                       if test -f "${with_tclconfig}"; then
+                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
+                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tclconfig}/tclConfig.sh" ; then
+                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tcl installation
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ../tcl \
+                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tcl \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tcl \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tcl \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tclconfig}" = x ; then
+           TCL_BIN_DIR="# no Tcl configs found"
+           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
+       else
+           no_tcl=
+           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
+           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_TKCONFIG --
+#
+#      Locate the tkConfig.sh file
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tk=...
+#
+#      Defines the following vars:
+#              TK_BIN_DIR      Full path to the directory containing
+#                              the tkConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TKCONFIG], [
+    #
+    # Ok, lets find the tk configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tk
+    #
+
+    if test x"${no_tk}" = x ; then
+       # we reset no_tk in case something fails here
+       no_tk=true
+       AC_ARG_WITH(tk,
+           AS_HELP_STRING([--with-tk],
+               [directory containing tk configuration (tkConfig.sh)]),
+           [with_tkconfig="${withval}"])
+       AC_MSG_CHECKING([for Tk configuration])
+       AC_CACHE_VAL(ac_cv_c_tkconfig,[
+
+           # First check to see if --with-tkconfig was specified.
+           if test x"${with_tkconfig}" != x ; then
+               case "${with_tkconfig}" in
+                   */tkConfig.sh )
+                       if test -f "${with_tkconfig}"; then
+                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
+                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tkconfig}/tkConfig.sh" ; then
+                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tk library
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ../tk \
+                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tk \
+                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tk \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tk \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tkconfig}" = x ; then
+           TK_BIN_DIR="# no Tk configs found"
+           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
+       else
+           no_tk=
+           TK_BIN_DIR="${ac_cv_c_tkconfig}"
+           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TCLCONFIG --
+#
+#      Load the tclConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TCL_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_BIN_DIR
+#              TCL_SRC_DIR
+#              TCL_LIB_FILE
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TCLCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
+
+    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TCL_BIN_DIR}/tclConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
+    fi
+
+    # If the TCL_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TCL_LIB_SPEC will be set to the value
+    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
+    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
+        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
+        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tcl was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tcl.framework installed in an arbitrary location.
+       case ${TCL_DEFS} in
+           *TCL_FRAMEWORK*)
+               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
+                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
+                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
+                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
+                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
+                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    AC_SUBST(TCL_VERSION)
+    AC_SUBST(TCL_PATCH_LEVEL)
+    AC_SUBST(TCL_BIN_DIR)
+    AC_SUBST(TCL_SRC_DIR)
+
+    AC_SUBST(TCL_LIB_FILE)
+    AC_SUBST(TCL_LIB_FLAG)
+    AC_SUBST(TCL_LIB_SPEC)
+
+    AC_SUBST(TCL_STUB_LIB_FILE)
+    AC_SUBST(TCL_STUB_LIB_FLAG)
+    AC_SUBST(TCL_STUB_LIB_SPEC)
+
+    AC_MSG_CHECKING([platform])
+    hold_cc=$CC; CC="$TCL_CC"
+    AC_TRY_COMPILE(,[
+           #ifdef _WIN32
+               #error win32
+           #endif
+       ], [
+           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
+           TEA_PLATFORM="${TEA_PLATFORM-unix}"
+           CYGPATH=echo
+       ], [
+           TEA_PLATFORM="windows"
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
+    )
+    CC=$hold_cc
+    AC_MSG_RESULT($TEA_PLATFORM)
+
+    # The BUILD_$pkg is to define the correct extern storage class
+    # handling when making this package
+    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
+           [Building extension source?])
+    # Do this here as we have fully defined TEA_PLATFORM now
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       EXEEXT=".exe"
+       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
+    fi
+
+    # TEA specific:
+    AC_SUBST(CLEANFILES)
+    AC_SUBST(TCL_LIBS)
+    AC_SUBST(TCL_DEFS)
+    AC_SUBST(TCL_EXTRA_CFLAGS)
+    AC_SUBST(TCL_LD_FLAGS)
+    AC_SUBST(TCL_SHLIB_LD_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TKCONFIG --
+#
+#      Load the tkConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TK_BIN_DIR
+#
+# Results:
+#
+#      Sets the following vars that should be in tkConfig.sh:
+#              TK_BIN_DIR
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TKCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
+
+    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TK_BIN_DIR}/tkConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
+    fi
+
+    # If the TK_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TK_LIB_SPEC will be set to the value
+    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
+    # instead of TK_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
+        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
+        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tk was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tk.framework installed in an arbitrary location.
+       case ${TK_DEFS} in
+           *TK_FRAMEWORK*)
+               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
+                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
+                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
+                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
+                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
+                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    # TEA specific: Ensure windowingsystem is defined
+    if test "${TEA_PLATFORM}" = "unix" ; then
+       case ${TK_DEFS} in
+           *MAC_OSX_TK*)
+               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
+               TEA_WINDOWINGSYSTEM="aqua"
+               ;;
+           *)
+               TEA_WINDOWINGSYSTEM="x11"
+               ;;
+       esac
+    elif test "${TEA_PLATFORM}" = "windows" ; then
+       TEA_WINDOWINGSYSTEM="win32"
+    fi
+
+    AC_SUBST(TK_VERSION)
+    AC_SUBST(TK_BIN_DIR)
+    AC_SUBST(TK_SRC_DIR)
+
+    AC_SUBST(TK_LIB_FILE)
+    AC_SUBST(TK_LIB_FLAG)
+    AC_SUBST(TK_LIB_SPEC)
+
+    AC_SUBST(TK_STUB_LIB_FILE)
+    AC_SUBST(TK_STUB_LIB_FLAG)
+    AC_SUBST(TK_STUB_LIB_SPEC)
+
+    # TEA specific:
+    AC_SUBST(TK_LIBS)
+    AC_SUBST(TK_XINCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_TCLSH
+#      Determine the fully qualified path name of the tclsh executable
+#      in the Tcl build directory or the tclsh installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the tclsh executable even if tclsh has not yet been
+#      built in the build directory. The tclsh found is always
+#      associated with a tclConfig.sh file. This tclsh should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCLSH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_TCLSH], [
+    AC_MSG_CHECKING([for tclsh])
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        # tclConfig.sh is in Tcl build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
+        fi
+    else
+        # tclConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+        else
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${TCLSH_PROG}" ; then
+                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
+    fi
+    AC_MSG_RESULT([${TCLSH_PROG}])
+    AC_SUBST(TCLSH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_WISH
+#      Determine the fully qualified path name of the wish executable
+#      in the Tk build directory or the wish installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the wish executable even if wish has not yet been
+#      built in the build directory. The wish found is always
+#      associated with a tkConfig.sh file. This wish should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              WISH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_WISH], [
+    AC_MSG_CHECKING([for wish])
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        # tkConfig.sh is in Tk build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            WISH_PROG="${TK_BIN_DIR}/wish"
+        fi
+    else
+        # tkConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+        else
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${WISH_PROG}" ; then
+                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
+    fi
+    AC_MSG_RESULT([${WISH_PROG}])
+    AC_SUBST(WISH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SHARED --
+#
+#      Allows the building of shared libraries
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-shared=yes|no
+#              --enable-stubs=yes|no
+#
+#      Defines the following vars:
+#              STATIC_BUILD    Used for building import/export libraries
+#                              on Windows.
+#
+#      Sets the following vars:
+#              SHARED_BUILD    Value of 1 or 0
+#               STUBS_BUILD     Value if 1 or 0
+#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
+#                                AND TEA_WINDOWING_SYSTEM != ""
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ENABLE_SHARED], [
+    AC_MSG_CHECKING([how to build libraries])
+    AC_ARG_ENABLE(shared,
+       AS_HELP_STRING([--enable-shared],
+           [build and link with shared libraries (default: on)]),
+       [shared_ok=$enableval], [shared_ok=yes])
+
+    if test "${enable_shared+set}" = set; then
+       enableval="$enable_shared"
+       shared_ok=$enableval
+    else
+       shared_ok=yes
+    fi
+
+    AC_ARG_ENABLE(stubs,
+       AS_HELP_STRING([--enable-stubs],
+           [build and link with stub libraries. Always true for shared builds (default: on)]),
+       [stubs_ok=$enableval], [stubs_ok=yes])
+
+    if test "${enable_stubs+set}" = set; then
+       enableval="$enable_stubs"
+       stubs_ok=$enableval
+    else
+       stubs_ok=yes
+    fi
+
+    # Stubs are always enabled for shared builds
+    if test "$shared_ok" = "yes" ; then
+       AC_MSG_RESULT([shared])
+       SHARED_BUILD=1
+        STUBS_BUILD=1
+    else
+       AC_MSG_RESULT([static])
+       SHARED_BUILD=0
+       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
+        if test "$stubs_ok" = "yes" ; then
+          STUBS_BUILD=1
+        else
+          STUBS_BUILD=0
+        fi
+    fi
+    if test "${STUBS_BUILD}" = "1" ; then
+      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
+      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
+      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
+        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
+      fi
+    fi
+
+    AC_SUBST(SHARED_BUILD)
+    AC_SUBST(STUBS_BUILD)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_THREADS --
+#
+#      Specify if thread support should be enabled.  If "yes" is specified
+#      as an arg (optional), threads are enabled by default, "no" means
+#      threads are disabled.  "yes" is the default.
+#
+#      TCL_THREADS is checked so that if you are compiling an extension
+#      against a threaded core, your extension must be compiled threaded
+#      as well.
+#
+#      Note that it is legal to have a thread enabled extension run in a
+#      threaded or non-threaded Tcl core, but a non-threaded extension may
+#      only run in a non-threaded Tcl core.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-threads
+#
+#      Sets the following vars:
+#              THREADS_LIBS    Thread library(s)
+#
+#      Defines the following vars:
+#              TCL_THREADS
+#              _REENTRANT
+#              _THREAD_SAFE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_THREADS], [
+    AC_ARG_ENABLE(threads,
+       AS_HELP_STRING([--enable-threads],
+           [build with threads (default: on)]),
+       [tcl_ok=$enableval], [tcl_ok=yes])
+
+    if test "${enable_threads+set}" = set; then
+       enableval="$enable_threads"
+       tcl_ok=$enableval
+    else
+       tcl_ok=yes
+    fi
+
+    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
+       TCL_THREADS=1
+
+       if test "${TEA_PLATFORM}" != "windows" ; then
+           # We are always OK on Windows, so check what this platform wants:
+
+           # USE_THREAD_ALLOC tells us to try the special thread-based
+           # allocator that significantly reduces lock contention
+           AC_DEFINE(USE_THREAD_ALLOC, 1,
+               [Do we want to use the threaded memory allocator?])
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           if test "`uname -s`" = "SunOS" ; then
+               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+                       [Do we really want to follow the standard? Yes we do!])
+           fi
+           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
+           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
+           if test "$tcl_ok" = "no"; then
+               # Check a little harder for __pthread_mutex_init in the same
+               # library, as some systems hide it there until pthread.h is
+               # defined.  We could alternatively do an AC_TRY_COMPILE with
+               # pthread.h, but that will work with libpthread really doesn't
+               # exist, like AIX 4.2.  [Bug: 4359]
+               AC_CHECK_LIB(pthread, __pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+           fi
+
+           if test "$tcl_ok" = "yes"; then
+               # The space is needed
+               THREADS_LIBS=" -lpthread"
+           else
+               AC_CHECK_LIB(pthreads, pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+               if test "$tcl_ok" = "yes"; then
+                   # The space is needed
+                   THREADS_LIBS=" -lpthreads"
+               else
+                   AC_CHECK_LIB(c, pthread_mutex_init,
+                       tcl_ok=yes, tcl_ok=no)
+                   if test "$tcl_ok" = "no"; then
+                       AC_CHECK_LIB(c_r, pthread_mutex_init,
+                           tcl_ok=yes, tcl_ok=no)
+                       if test "$tcl_ok" = "yes"; then
+                           # The space is needed
+                           THREADS_LIBS=" -pthread"
+                       else
+                           TCL_THREADS=0
+                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
+                       fi
+                   fi
+               fi
+           fi
+       fi
+    else
+       TCL_THREADS=0
+    fi
+    # Do checking message here to not mess up interleaved configure output
+    AC_MSG_CHECKING([for building with threads])
+    if test "${TCL_THREADS}" = 1; then
+       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
+       AC_MSG_RESULT([yes (default)])
+    else
+       AC_MSG_RESULT([no])
+    fi
+    # TCL_THREADS sanity checking.  See if our request for building with
+    # threads is the same as the way Tcl was built.  If not, warn the user.
+    case ${TCL_DEFS} in
+       *THREADS=1*)
+           if test "${TCL_THREADS}" = "0"; then
+               AC_MSG_WARN([
+    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
+    that IS thread-enabled.  It is recommended to use --enable-threads.])
+           fi
+           ;;
+    esac
+    AC_SUBST(TCL_THREADS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SYMBOLS --
+#
+#      Specify if debugging symbols should be used.
+#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
+#
+# Arguments:
+#      none
+#
+#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
+#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
+#      Requires the following vars to be set in the Makefile:
+#              CFLAGS_DEFAULT
+#              LDFLAGS_DEFAULT
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-symbols
+#
+#      Defines the following vars:
+#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
+#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
+#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
+#                              Sets to $(LDFLAGS_OPTIMIZE) if false
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_SYMBOLS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_CONFIG_CFLAGS])
+    AC_MSG_CHECKING([for build with symbols])
+    AC_ARG_ENABLE(symbols,
+       AS_HELP_STRING([--enable-symbols],
+           [build with debugging symbols (default: off)]),
+       [tcl_ok=$enableval], [tcl_ok=no])
+    if test "$tcl_ok" = "no"; then
+       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
+       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
+       AC_MSG_RESULT([no])
+    else
+       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
+       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
+       if test "$tcl_ok" = "yes"; then
+           AC_MSG_RESULT([yes (standard debugging)])
+       fi
+    fi
+    AC_SUBST(CFLAGS_DEFAULT)
+    AC_SUBST(LDFLAGS_DEFAULT)
+
+    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
+       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
+    fi
+
+    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
+       if test "$tcl_ok" = "all"; then
+           AC_MSG_RESULT([enabled symbols mem debugging])
+       else
+           AC_MSG_RESULT([enabled $tcl_ok debugging])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_LANGINFO --
+#
+#      Allows use of modern nl_langinfo check for better l10n.
+#      This is only relevant for Unix.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-langinfo=yes|no (default is yes)
+#
+#      Defines the following vars:
+#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_LANGINFO], [
+    AC_ARG_ENABLE(langinfo,
+       AS_HELP_STRING([--enable-langinfo],
+           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
+       [langinfo_ok=$enableval], [langinfo_ok=yes])
+
+    HAVE_LANGINFO=0
+    if test "$langinfo_ok" = "yes"; then
+       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
+    fi
+    AC_MSG_CHECKING([whether to use nl_langinfo])
+    if test "$langinfo_ok" = "yes"; then
+       AC_CACHE_VAL(tcl_cv_langinfo_h, [
+           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
+                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
+       AC_MSG_RESULT([$tcl_cv_langinfo_h])
+       if test $tcl_cv_langinfo_h = yes; then
+           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
+       fi
+    else
+       AC_MSG_RESULT([$langinfo_ok])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_SYSTEM
+#
+#      Determine what the system is (some things cannot be easily checked
+#      on a feature-driven basis, alas). This can usually be done via the
+#      "uname" command.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Defines the following var:
+#
+#      system -        System/platform/version identification code.
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_SYSTEM], [
+    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
+       # TEA specific:
+       if test "${TEA_PLATFORM}" = "windows" ; then
+           tcl_cv_sys_version=windows
+       else
+           tcl_cv_sys_version=`uname -s`-`uname -r`
+           if test "$?" -ne 0 ; then
+               AC_MSG_WARN([can't find uname command])
+               tcl_cv_sys_version=unknown
+           else
+               if test "`uname -s`" = "AIX" ; then
+                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
+               fi
+               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
+                   tcl_cv_sys_version=NetBSD-Debian
+               fi
+           fi
+       fi
+    ])
+    system=$tcl_cv_sys_version
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_CFLAGS
+#
+#      Try to determine the proper flags to pass to the compiler
+#      for building shared libraries and other such nonsense.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substitutes the following vars:
+#
+#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
+#       LDFLAGS -      Flags to pass to the compiler when linking object
+#                       files into an executable application binary such
+#                       as tclsh.
+#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
+#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
+#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile.
+#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
+#                       of a shared library (may request position-independent
+#                       code, among other things).
+#       SHLIB_LD -      Base command to use for combining object files
+#                       into a shared library.
+#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
+#                       creating shared libraries.  This symbol typically
+#                       goes at the end of the "ld" commands that build
+#                       shared libraries. The value of the symbol defaults to
+#                       "${LIBS}" if all of the dependent libraries should
+#                       be specified when creating a shared library.  If
+#                       dependent libraries should not be specified (as on
+#                       SunOS 4.x, where they cause the link to fail, or in
+#                       general if Tcl and Tk aren't themselves shared
+#                       libraries), then this symbol has an empty string
+#                       as its value.
+#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
+#                       extensions.  An empty string means we don't know how
+#                       to use shared libraries on this platform.
+#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
+#                       in a static or shared library name, using the $PACKAGE_VERSION variable
+#                       to put the version in the right place.  This is used
+#                       by platforms that need non-standard library names.
+#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
+#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
+#                       on AIX, since a shared library needs to have
+#                       a .a extension whereas shared objects for loadable
+#                       extensions have a .so extension.  Defaults to
+#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
+#      CFLAGS_DEBUG -
+#                      Flags used when running the compiler in debug mode
+#      CFLAGS_OPTIMIZE -
+#                      Flags used when running the compiler in optimize mode
+#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_CFLAGS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+
+    # Step 0.a: Enable 64 bit support?
+
+    AC_MSG_CHECKING([if 64bit support is requested])
+    AC_ARG_ENABLE(64bit,
+       AS_HELP_STRING([--enable-64bit],
+           [enable 64bit support (default: off)]),
+       [do64bit=$enableval], [do64bit=no])
+    AC_MSG_RESULT([$do64bit])
+
+    # Step 0.b: Enable Solaris 64 bit VIS support?
+
+    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
+    AC_ARG_ENABLE(64bit-vis,
+       AS_HELP_STRING([--enable-64bit-vis],
+           [enable 64bit Sparc VIS support (default: off)]),
+       [do64bitVIS=$enableval], [do64bitVIS=no])
+    AC_MSG_RESULT([$do64bitVIS])
+    # Force 64bit on with VIS
+    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
+
+    # Step 0.c: Check if visibility support is available. Do this here so
+    # that platform specific alternatives can be used below if this fails.
+
+    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
+       tcl_cv_cc_visibility_hidden, [
+       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
+       AC_TRY_LINK([
+           extern __attribute__((__visibility__("hidden"))) void f(void);
+           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
+           tcl_cv_cc_visibility_hidden=no)
+       CFLAGS=$hold_cflags])
+    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
+       AC_DEFINE(MODULE_SCOPE,
+           [extern __attribute__((__visibility__("hidden")))],
+           [Compiler support for module scope symbols])
+       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
+    ])
+
+    # Step 0.d: Disable -rpath support?
+
+    AC_MSG_CHECKING([if rpath support is requested])
+    AC_ARG_ENABLE(rpath,
+       AS_HELP_STRING([--disable-rpath],
+           [disable rpath support (default: on)]),
+       [doRpath=$enableval], [doRpath=yes])
+    AC_MSG_RESULT([$doRpath])
+
+    # Set the variable "system" to hold the name and version number
+    # for the system.
+
+    TEA_CONFIG_SYSTEM
+
+    # Require ranlib early so we can override it in special cases below.
+
+    AC_REQUIRE([AC_PROG_RANLIB])
+
+    # Set configuration options based on system name and version.
+    # This is similar to Tcl's unix/tcl.m4 except that we've added a
+    # "windows" case and removed some core-only vars.
+
+    do64bit_ok=no
+    # default to '{$LIBS}' and set to "" on per-platform necessary basis
+    SHLIB_LD_LIBS='${LIBS}'
+    # When ld needs options to work in 64-bit mode, put them in
+    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
+    # is disabled by the user. [Bug 1016796]
+    LDFLAGS_ARCH=""
+    UNSHARED_LIB_SUFFIX=""
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
+    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
+    TCL_LIB_VERSIONS_OK=ok
+    CFLAGS_DEBUG=-g
+    AS_IF([test "$GCC" = yes], [
+       CFLAGS_OPTIMIZE=-O2
+       CFLAGS_WARNING="-Wall"
+    ], [
+       CFLAGS_OPTIMIZE=-O
+       CFLAGS_WARNING=""
+    ])
+    AC_CHECK_TOOL(AR, ar)
+    STLIB_LD='${AR} cr'
+    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
+    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
+    case $system in
+       # TEA specific:
+       windows)
+           MACHINE="X86"
+           if test "$do64bit" != "no" ; then
+               case "$do64bit" in
+                   amd64|x64|yes)
+                       MACHINE="AMD64" ; # default to AMD64 64-bit build
+                       ;;
+                   ia64)
+                       MACHINE="IA64"
+                       ;;
+               esac
+           fi
+
+           if test "$GCC" != "yes" ; then
+               if test "${SHARED_BUILD}" = "0" ; then
+                   runtime=-MT
+               else
+                   runtime=-MD
+               fi
+               case "x`echo \${VisualStudioVersion}`" in
+                   x1[[4-9]]*)
+                       lflags="${lflags} -nodefaultlib:libucrt.lib"
+                       TEA_ADD_LIBS([ucrt.lib])
+                   ;;
+                   *)
+                   ;;
+               esac
+
+                if test "$do64bit" != "no" ; then
+                   CC="cl.exe"
+                   RC="rc.exe"
+                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
+                   LINKBIN="link.exe"
+                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+                   # Avoid 'unresolved external symbol __security_cookie'
+                   # errors, c.f. http://support.microsoft.com/?id=894573
+                   TEA_ADD_LIBS([bufferoverflowU.lib])
+               else
+                   RC="rc"
+                   lflags="${lflags} -nologo"
+                   LINKBIN="link"
+                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+               fi
+           fi
+
+           if test "$GCC" = "yes"; then
+               # mingw gcc mode
+               AC_CHECK_TOOL(RC, windres)
+               CFLAGS_DEBUG="-g"
+               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+               SHLIB_LD='${CC} -shared'
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
+               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
+
+               AC_CACHE_CHECK(for cross-compile version of gcc,
+                       ac_cv_cross,
+                       AC_TRY_COMPILE([
+                           #ifdef _WIN32
+                               #error cross-compiler
+                           #endif
+                       ], [],
+                       ac_cv_cross=yes,
+                       ac_cv_cross=no)
+                     )
+                     if test "$ac_cv_cross" = "yes"; then
+                       case "$do64bit" in
+                           amd64|x64|yes)
+                               CC="x86_64-w64-mingw32-${CC}"
+                               LD="x86_64-w64-mingw32-ld"
+                               AR="x86_64-w64-mingw32-ar"
+                               RANLIB="x86_64-w64-mingw32-ranlib"
+                               RC="x86_64-w64-mingw32-windres"
+                           ;;
+                           *)
+                               CC="i686-w64-mingw32-${CC}"
+                               LD="i686-w64-mingw32-ld"
+                               AR="i686-w64-mingw32-ar"
+                               RANLIB="i686-w64-mingw32-ranlib"
+                               RC="i686-w64-mingw32-windres"
+                           ;;
+                       esac
+               fi
+
+           else
+               SHLIB_LD="${LINKBIN} -dll ${lflags}"
+               # link -lib only works when -lib is the first arg
+               STLIB_LD="${LINKBIN} -lib ${lflags}"
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
+               PATHTYPE=-w
+               # For information on what debugtype is most useful, see:
+               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
+               # and also
+               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
+               # This essentially turns it all on.
+               LDFLAGS_DEBUG="-debug -debugtype:cv"
+               LDFLAGS_OPTIMIZE="-release"
+               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
+               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
+           fi
+
+           SHLIB_SUFFIX=".dll"
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
+
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       AIX-*)
+           AS_IF([test "$GCC" != "yes"], [
+               # AIX requires the _r compiler when gcc isn't being used
+               case "${CC}" in
+                   *_r|*_r\ *)
+                       # ok ...
+                       ;;
+                   *)
+                       # Make sure only first arg gets _r
+                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
+                       ;;
+               esac
+               AC_MSG_RESULT([Using $CC for compiling with threads])
+           ])
+           LIBS="$LIBS -lc"
+           SHLIB_CFLAGS=""
+           SHLIB_SUFFIX=".so"
+
+           LD_LIBRARY_PATH_VAR="LIBPATH"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS -q64"
+                   LDFLAGS_ARCH="-q64"
+                   RANLIB="${RANLIB} -X64"
+                   AR="${AR} -X64"
+                   SHLIB_LD_FLAGS="-b64"
+               ])
+           ])
+
+           AS_IF([test "`uname -m`" = ia64], [
+               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               AS_IF([test "$GCC" = yes], [
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               ], [
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
+               ])
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ], [
+               AS_IF([test "$GCC" = yes], [
+                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
+               ], [
+                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
+                   LDFLAGS="$LDFLAGS -brtl"
+               ])
+               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       BeOS*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} -nostart'
+           SHLIB_SUFFIX=".so"
+
+           #-----------------------------------------------------------
+           # Check for inet_ntoa in -lbind, for BeOS (which also needs
+           # -lsocket, even if the network functions are in -lnet which
+           # is always linked to, for compatibility.
+           #-----------------------------------------------------------
+           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
+           ;;
+       BSD/OS-2.1*|BSD/OS-3*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="shlicc -r"
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       BSD/OS-4.*)
+           SHLIB_CFLAGS="-export-dynamic -fPIC"
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       CYGWIN_*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".dll"
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
+           EXEEXT=".exe"
+           do64bit_ok=yes
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       dgux*)
+           SHLIB_CFLAGS="-K PIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       Haiku*)
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
+           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
+           ;;
+       HP-UX-*.11.*)
+           # Use updated header definitions where possible
+           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
+           # TEA specific: Needed by Tcl, but not most extensions
+           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
+           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
+
+           AS_IF([test "`uname -m`" = ia64], [
+               SHLIB_SUFFIX=".so"
+           ], [
+               SHLIB_SUFFIX=".sl"
+           ])
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ])
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               CFLAGS="$CFLAGS -z"
+           ])
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = "yes"], [
+               AS_IF([test "$GCC" = yes], [
+                   case `${CC} -dumpmachine` in
+                       hppa64*)
+                           # 64-bit gcc in use.  Fix flags for GNU ld.
+                           do64bit_ok=yes
+                           SHLIB_LD='${CC} -shared'
+                           AS_IF([test $doRpath = yes], [
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+                           ;;
+                       *)
+                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
+                           ;;
+                   esac
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS +DD64"
+                   LDFLAGS_ARCH="+DD64"
+               ])
+           ]) ;;
+       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
+           SHLIB_SUFFIX=".sl"
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               SHLIB_LD_LIBS=""
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ]) ;;
+       IRIX-5.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AC_LIBOBJ(mkstemp)
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           ;;
+       IRIX-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           AS_IF([test "$GCC" = yes], [
+               CFLAGS="$CFLAGS -mabi=n32"
+               LDFLAGS="$LDFLAGS -mabi=n32"
+           ], [
+               case $system in
+                   IRIX-6.3)
+                       # Use to build 6.2 compatible binaries on 6.3.
+                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
+                       ;;
+                   *)
+                       CFLAGS="$CFLAGS -n32"
+                       ;;
+               esac
+               LDFLAGS="$LDFLAGS -n32"
+           ])
+           ;;
+       IRIX64-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+
+           # Check to enable 64-bit flags for compiler/linker
+
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported by gcc])
+               ], [
+                   do64bit_ok=yes
+                   SHLIB_LD="ld -64 -shared -rdata_shared"
+                   CFLAGS="$CFLAGS -64"
+                   LDFLAGS_ARCH="-64"
+               ])
+           ])
+           ;;
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+
+           # TEA specific:
+           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
+           AS_IF([test $do64bit = yes], [
+               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
+                   hold_cflags=$CFLAGS
+                   CFLAGS="$CFLAGS -m64"
+                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
+                   CFLAGS=$hold_cflags])
+               AS_IF([test $tcl_cv_cc_m64 = yes], [
+                   CFLAGS="$CFLAGS -m64"
+                   do64bit_ok=yes
+               ])
+          ])
+
+           # The combo of gcc + glibc has a bug related to inlining of
+           # functions like strtod(). The -fno-builtin flag should address
+           # this problem but it does not work. The -fno-inline flag is kind
+           # of overkill but it works. Disable inlining only when one of the
+           # files in compat/*.c is being linked in.
+
+           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
+           ;;
+       Lynx*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           CFLAGS_OPTIMIZE=-02
+           SHLIB_LD='${CC} -shared'
+           LD_FLAGS="-Wl,--export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           ;;
+       OpenBSD-*)
+           arch=`arch -s`
+           case "$arch" in
+           alpha|sparc64)
+               SHLIB_CFLAGS="-fPIC"
+               ;;
+           *)
+               SHLIB_CFLAGS="-fpic"
+               ;;
+           esac
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
+           CFLAGS_OPTIMIZE="-O2"
+           # On OpenBSD:       Compile with -pthread
+           #           Don't link with -lpthread
+           LIBS=`echo $LIBS | sed s/-lpthread//`
+           CFLAGS="$CFLAGS -pthread"
+           # OpenBSD doesn't do version numbers with dots.
+           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       NetBSD-*)
+           # NetBSD has ELF and can use 'cc -shared' to build shared libs
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           # The -pthread needs to go in the CFLAGS, not LIBS
+           LIBS=`echo $LIBS | sed s/-pthread//`
+           CFLAGS="$CFLAGS -pthread"
+           LDFLAGS="$LDFLAGS -pthread"
+           ;;
+       Darwin-*)
+           CFLAGS_OPTIMIZE="-Os"
+           SHLIB_CFLAGS="-fno-common"
+           # To avoid discrepancies between what headers configure sees during
+           # preprocessing tests and compiling tests, move any -isysroot and
+           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
+           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
+           CFLAGS="`echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
+           AS_IF([test $do64bit = yes], [
+               case `arch` in
+                   ppc)
+                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
+                               tcl_cv_cc_arch_ppc64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
+                                   tcl_cv_cc_arch_ppc64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           do64bit_ok=yes
+                       ]);;
+                   i386)
+                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
+                               tcl_cv_cc_arch_x86_64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
+                                   tcl_cv_cc_arch_x86_64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           do64bit_ok=yes
+                       ]);;
+                   *)
+                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
+               esac
+           ], [
+               # Check for combined 32-bit and 64-bit fat build
+               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
+                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
+                   fat_32_64=yes])
+           ])
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
+           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_single_module = yes], [
+               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
+           ])
+           # TEA specific: link shlib with current and compatibility version flags
+           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
+           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
+           SHLIB_SUFFIX=".dylib"
+           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
+           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
+                   tcl_cv_ld_search_paths_first, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
+                       tcl_cv_ld_search_paths_first=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+           ])
+           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
+                   [Compiler support for module scope symbols])
+               tcl_cv_cc_visibility_hidden=yes
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
+           # TEA specific: for combined 32 & 64 bit fat builds of Tk
+           # extensions, verify that 64-bit build is possible.
+           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
+                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
+                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
+                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
+                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
+                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
+                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
+                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
+                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               # remove 64-bit arch flags from CFLAGS et al. if configuration
+               # does not support 64-bit.
+               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
+                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
+                   for v in CFLAGS CPPFLAGS LDFLAGS; do
+                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
+                   done])
+           ])
+           ;;
+       OS/390-*)
+           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
+           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
+               [Should OS/390 do the right thing with sockets?])
+           ;;
+       OSF1-V*)
+           # Digital OSF/1
+           SHLIB_CFLAGS=""
+           AS_IF([test "$SHARED_BUILD" = 1], [
+               SHLIB_LD='ld -shared -expect_unresolved "*"'
+           ], [
+               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
+           ])
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
+               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
+           # see pthread_intro(3) for pthread support on osf1, k.furukawa
+           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
+           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
+           LIBS=`echo $LIBS | sed s/-lpthreads//`
+           AS_IF([test "$GCC" = yes], [
+               LIBS="$LIBS -lpthread -lmach -lexc"
+           ], [
+               CFLAGS="$CFLAGS -pthread"
+               LDFLAGS="$LDFLAGS -pthread"
+           ])
+           ;;
+       QNX-6*)
+           # QNX RTP
+           # This may work for all QNX, but it was only reported for v6.
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD="ld -Bshareable -x"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SCO_SV-3.2*)
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_CFLAGS="-fPIC -melf"
+               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
+           ], [
+               SHLIB_CFLAGS="-Kpic -belf"
+               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
+           ])
+           SHLIB_LD="ld -G"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SunOS-5.[[0-6]])
+           # Careful to not let 5.10+ fall into this case
+
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       SunOS-5*)
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               arch=`isainfo`
+               AS_IF([test "$arch" = "sparcv9 sparc"], [
+                   AS_IF([test "$GCC" = yes], [
+                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
+                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
+                       ], [
+                           do64bit_ok=yes
+                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
+                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
+                           SHLIB_CFLAGS="-fPIC"
+                       ])
+                   ], [
+                       do64bit_ok=yes
+                       AS_IF([test "$do64bitVIS" = yes], [
+                           CFLAGS="$CFLAGS -xarch=v9a"
+                           LDFLAGS_ARCH="-xarch=v9a"
+                       ], [
+                           CFLAGS="$CFLAGS -xarch=v9"
+                           LDFLAGS_ARCH="-xarch=v9"
+                       ])
+                       # Solaris 64 uses this as well
+                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
+                   ])
+               ], [AS_IF([test "$arch" = "amd64 i386"], [
+                   AS_IF([test "$GCC" = yes], [
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               do64bit_ok=yes
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
+                       esac
+                   ], [
+                       do64bit_ok=yes
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               CFLAGS="$CFLAGS -xarch=amd64"
+                               LDFLAGS="$LDFLAGS -xarch=amd64";;
+                       esac
+                   ])
+               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
+           ])
+
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+               AS_IF([test "$do64bit_ok" = yes], [
+                   AS_IF([test "$arch" = "sparcv9 sparc"], [
+                       # We need to specify -static-libgcc or we need to
+                       # add the path to the sparv9 libgcc.
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
+                       # for finding sparcv9 libgcc, get the regular libgcc
+                       # path, remove so name and append 'sparcv9'
+                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
+                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
+                   ], [AS_IF([test "$arch" = "amd64 i386"], [
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
+                   ])])
+               ])
+           ], [
+               case $system in
+                   SunOS-5.[[1-9]][[0-9]]*)
+                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
+                   *)
+                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
+               esac
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ])
+           ;;
+       UNIX_SV* | UnixWare-5*)
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
+           # that don't grok the -Bexport option.  Test that it does.
+           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_Bexport = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+    esac
+
+    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
+       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
+    ])
+
+dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
+dnl # until the end of configure, as configure's compile and link tests use
+dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
+dnl # preprocessing tests use only CPPFLAGS.
+    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
+
+    # Add in the arch flags late to ensure it wasn't removed.
+    # Not necessary in TEA, but this is aligned with core
+    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
+
+    # If we're running gcc, then change the C flags for compiling shared
+    # libraries to the right flags for gcc, instead of those for the
+    # standard manufacturer compiler.
+
+    AS_IF([test "$GCC" = yes], [
+       case $system in
+           AIX-*) ;;
+           BSD/OS*) ;;
+           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
+           IRIX*) ;;
+           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
+           Darwin-*) ;;
+           SCO_SV-3.2*) ;;
+           windows) ;;
+           *) SHLIB_CFLAGS="-fPIC" ;;
+       esac])
+
+    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+       AC_DEFINE(MODULE_SCOPE, [extern],
+           [No Compiler support for module scope symbols])
+    ])
+
+    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
+    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
+
+    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
+       AC_CACHE_CHECK(for SEH support in compiler,
+           tcl_cv_seh,
+       AC_TRY_RUN([
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+
+           int main(int argc, char** argv) {
+               int a, b = 0;
+               __try {
+                   a = 666 / b;
+               }
+               __except (EXCEPTION_EXECUTE_HANDLER) {
+                   return 0;
+               }
+               return 1;
+           }
+       ],
+           tcl_cv_seh=yes,
+           tcl_cv_seh=no,
+           tcl_cv_seh=no)
+       )
+       if test "$tcl_cv_seh" = "no" ; then
+           AC_DEFINE(HAVE_NO_SEH, 1,
+                   [Defined when mingw does not support SEH])
+       fi
+
+       #
+       # Check to see if the excpt.h include file provided contains the
+       # definition for EXCEPTION_DISPOSITION; if not, which is the case
+       # with Cygwin's version as of 2002-04-10, define it to be int,
+       # sufficient for getting the current code to work.
+       #
+       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
+           tcl_cv_eh_disposition,
+           AC_TRY_COMPILE([
+#          define WIN32_LEAN_AND_MEAN
+#          include <windows.h>
+#          undef WIN32_LEAN_AND_MEAN
+           ],[
+               EXCEPTION_DISPOSITION x;
+           ],
+               tcl_cv_eh_disposition=yes,
+               tcl_cv_eh_disposition=no)
+       )
+       if test "$tcl_cv_eh_disposition" = "no" ; then
+       AC_DEFINE(EXCEPTION_DISPOSITION, int,
+               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
+       fi
+
+       # Check to see if winnt.h defines CHAR, SHORT, and LONG
+       # even if VOID has already been #defined. The win32api
+       # used by mingw and cygwin is known to do this.
+
+       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
+           tcl_cv_winnt_ignore_void,
+           AC_TRY_COMPILE([
+#define VOID void
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+           ], [
+               CHAR c;
+               SHORT s;
+               LONG l;
+           ],
+        tcl_cv_winnt_ignore_void=yes,
+        tcl_cv_winnt_ignore_void=no)
+       )
+       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
+           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
+                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
+       fi
+    fi
+
+       # See if the compiler supports casting to a union type.
+       # This is used to stop gcc from printing a compiler
+       # warning when initializing a union member.
+
+       AC_CACHE_CHECK(for cast to union support,
+           tcl_cv_cast_to_union,
+           AC_TRY_COMPILE([],
+           [
+                 union foo { int i; double d; };
+                 union foo f = (union foo) (int) 0;
+           ],
+           tcl_cv_cast_to_union=yes,
+           tcl_cv_cast_to_union=no)
+       )
+       if test "$tcl_cv_cast_to_union" = "yes"; then
+           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
+                   [Defined when compiler supports casting to union type.])
+       fi
+
+       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
+
+    AC_SUBST(CFLAGS_DEBUG)
+    AC_SUBST(CFLAGS_OPTIMIZE)
+    AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
+
+    AC_SUBST(STLIB_LD)
+    AC_SUBST(SHLIB_LD)
+
+    AC_SUBST(SHLIB_LD_LIBS)
+    AC_SUBST(SHLIB_CFLAGS)
+
+    AC_SUBST(LD_LIBRARY_PATH_VAR)
+
+    # These must be called after we do the basic CFLAGS checks and
+    # verify any possible 64-bit or similar switches are necessary
+    TEA_TCL_EARLY_FLAGS
+    TEA_TCL_64BIT_FLAGS
+])
+
+#--------------------------------------------------------------------
+# TEA_SERIAL_PORT
+#
+#      Determine which interface to use to talk to the serial port.
+#      Note that #include lines must begin in leftmost column for
+#      some compilers to recognize them as preprocessor directives,
+#      and some build environments have stdin not pointing at a
+#      pseudo-terminal (usually /dev/null instead.)
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines only one of the following vars:
+#              HAVE_SYS_MODEM_H
+#              USE_TERMIOS
+#              USE_TERMIO
+#              USE_SGTTY
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_SERIAL_PORT], [
+    AC_CHECK_HEADERS(sys/modem.h)
+    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
+    AC_TRY_RUN([
+#include <termios.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termio.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termios.h>
+#include <errno.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <termio.h>
+#include <errno.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+#include <errno.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
+    fi])
+    case $tcl_cv_api_serial in
+       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
+       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
+       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_PATH_X
+#
+#      Locate the X11 header files and the X11 library archive.  Try
+#      the ac_path_x macro first, but if it doesn't find the X stuff
+#      (e.g. because there's no xmkmf program) then check through
+#      a list of possible directories.  Under some conditions the
+#      autoconf macro will return an include directory that contains
+#      no include files, so double-check its result just to be safe.
+#
+#      This should be called after TEA_CONFIG_CFLAGS as setting the
+#      LIBS line can confuse some configure macro magic.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets the following vars:
+#              XINCLUDES
+#              XLIBSW
+#              PKG_LIBS (appends to)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_X], [
+    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
+       TEA_PATH_UNIX_X
+    fi
+])
+
+AC_DEFUN([TEA_PATH_UNIX_X], [
+    AC_PATH_X
+    not_really_there=""
+    if test "$no_x" = ""; then
+       if test "$x_includes" = ""; then
+           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
+       else
+           if test ! -r $x_includes/X11/Xlib.h; then
+               not_really_there="yes"
+           fi
+       fi
+    fi
+    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
+       AC_MSG_CHECKING([for X11 header files])
+       found_xincludes="no"
+       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
+       if test "$found_xincludes" = "no"; then
+           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
+           for i in $dirs ; do
+               if test -r $i/X11/Xlib.h; then
+                   AC_MSG_RESULT([$i])
+                   XINCLUDES=" -I$i"
+                   found_xincludes="yes"
+                   break
+               fi
+           done
+       fi
+    else
+       if test "$x_includes" != ""; then
+           XINCLUDES="-I$x_includes"
+           found_xincludes="yes"
+       fi
+    fi
+    if test "$found_xincludes" = "no"; then
+       AC_MSG_RESULT([couldn't find any!])
+    fi
+
+    if test "$no_x" = yes; then
+       AC_MSG_CHECKING([for X11 libraries])
+       XLIBSW=nope
+       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
+       for i in $dirs ; do
+           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
+               AC_MSG_RESULT([$i])
+               XLIBSW="-L$i -lX11"
+               x_libraries="$i"
+               break
+           fi
+       done
+    else
+       if test "$x_libraries" = ""; then
+           XLIBSW=-lX11
+       else
+           XLIBSW="-L$x_libraries -lX11"
+       fi
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_MSG_RESULT([could not find any!  Using -lX11.])
+       XLIBSW=-lX11
+    fi
+    # TEA specific:
+    if test x"${XLIBSW}" != x ; then
+       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BLOCKING_STYLE
+#
+#      The statements below check for systems where POSIX-style
+#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
+#      On these systems (mostly older ones), use the old BSD-style
+#      FIONBIO approach instead.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              HAVE_SYS_IOCTL_H
+#              HAVE_SYS_FILIO_H
+#              USE_FIONBIO
+#              O_NONBLOCK
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BLOCKING_STYLE], [
+    AC_CHECK_HEADERS(sys/ioctl.h)
+    AC_CHECK_HEADERS(sys/filio.h)
+    TEA_CONFIG_SYSTEM
+    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
+    case $system in
+       OSF*)
+           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
+           AC_MSG_RESULT([FIONBIO])
+           ;;
+       *)
+           AC_MSG_RESULT([O_NONBLOCK])
+           ;;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_TIME_HANDLER
+#
+#      Checks how the system deals with time.h, what time structures
+#      are used on the system, and what fields the structures have.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              USE_DELTA_FOR_TZ
+#              HAVE_TM_GMTOFF
+#              HAVE_TM_TZADJ
+#              HAVE_TIMEZONE_VAR
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TIME_HANDLER], [
+    AC_CHECK_HEADERS(sys/time.h)
+    AC_HEADER_TIME
+    AC_STRUCT_TIMEZONE
+
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
+
+    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
+           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
+    if test $tcl_cv_member_tm_tzadj = yes ; then
+       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
+    fi
+
+    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
+           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
+    if test $tcl_cv_member_tm_gmtoff = yes ; then
+       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
+    fi
+
+    #
+    # Its important to include time.h in this check, as some systems
+    # (like convex) have timezone functions, etc.
+    #
+    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
+       AC_TRY_COMPILE([#include <time.h>],
+           [extern long timezone;
+           timezone += 1;
+           exit (0);],
+           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
+    if test $tcl_cv_timezone_long = yes ; then
+       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+    else
+       #
+       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
+       #
+       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
+           AC_TRY_COMPILE([#include <time.h>],
+               [extern time_t timezone;
+               timezone += 1;
+               exit (0);],
+               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
+       if test $tcl_cv_timezone_time = yes ; then
+           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BUGGY_STRTOD
+#
+#      Under Solaris 2.4, strtod returns the wrong value for the
+#      terminating character under some conditions.  Check for this
+#      and if the problem exists use a substitute procedure
+#      "fixstrtod" (provided by Tcl) that corrects the error.
+#      Also, on Compaq's Tru64 Unix 5.0,
+#      strtod(" ") returns 0.0 instead of a failure to convert.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Might defines some of the following vars:
+#              strtod (=fixstrtod)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BUGGY_STRTOD], [
+    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
+    if test "$tcl_strtod" = 1; then
+       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
+           AC_TRY_RUN([
+               #include <stdlib.h>
+               extern double strtod();
+               int main() {
+                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
+                   char *term;
+                   double value;
+                   value = strtod(infString, &term);
+                   if ((term != infString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(nanString, &term);
+                   if ((term != nanString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(spaceString, &term);
+                   if (term == (spaceString+1)) {
+                       exit(1);
+                   }
+                   exit(0);
+               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
+                   tcl_cv_strtod_buggy=buggy)])
+       if test "$tcl_cv_strtod_buggy" = buggy; then
+           AC_LIBOBJ([fixstrtod])
+           USE_COMPAT=1
+           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_EARLY_FLAGS
+#
+#      Check for what flags are needed to be passed so the correct OS
+#      features are available.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              _ISOC99_SOURCE
+#              _LARGEFILE64_SOURCE
+#              _LARGEFILE_SOURCE64
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_EARLY_FLAG],[
+    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
+       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
+           AC_TRY_COMPILE([[#define ]$1[ 1
+]$2], $3,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
+    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
+       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
+       tcl_flags="$tcl_flags $1"
+    fi
+])
+
+AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
+    AC_MSG_CHECKING([for required early compiler flags])
+    tcl_flags=""
+    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
+       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
+       [struct stat64 buf; int i = stat64("/", &buf);])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
+       [char *p = (char *)open64;])
+    if test "x${tcl_flags}" = "x" ; then
+       AC_MSG_RESULT([none])
+    else
+       AC_MSG_RESULT([${tcl_flags}])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_64BIT_FLAGS
+#
+#      Check for what is defined in the way of 64-bit features.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              TCL_WIDE_INT_IS_LONG
+#              TCL_WIDE_INT_TYPE
+#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
+#              HAVE_STRUCT_STAT64
+#              HAVE_TYPE_OFF64_T
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
+    AC_MSG_CHECKING([for 64-bit integer type])
+    AC_CACHE_VAL(tcl_cv_type_64bit,[
+       tcl_cv_type_64bit=none
+       # See if the compiler knows natively about __int64
+       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
+           tcl_type_64bit=__int64, tcl_type_64bit="long long")
+       # See if we could use long anyway  Note that we substitute in the
+       # type that is our current guess for a 64-bit type inside this check
+       # program, so it should be modified only carefully...
+        AC_TRY_COMPILE(,[switch (0) {
+            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
+        }],tcl_cv_type_64bit=${tcl_type_64bit})])
+    if test "${tcl_cv_type_64bit}" = none ; then
+       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
+       AC_MSG_RESULT([yes])
+    elif test "${tcl_cv_type_64bit}" = "__int64" \
+               -a "${TEA_PLATFORM}" = "windows" ; then
+       # TEA specific: We actually want to use the default tcl.h checks in
+       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
+       AC_MSG_RESULT([using Tcl header defaults])
+    else
+       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
+           [What type should be used to define wide integers?])
+       AC_MSG_RESULT([${tcl_cv_type_64bit}])
+
+       # Now check for auxiliary declarations
+       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 p;],
+               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
+       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
+            p = readdir64(d); rewinddir64(d); closedir64(d);],
+               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
+       if test "x${tcl_cv_DIR64}" = "xyes" ; then
+           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
+           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
+],
+               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
+       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
+       fi
+
+       AC_CHECK_FUNCS(open64 lseek64)
+       AC_MSG_CHECKING([for off64_t])
+       AC_CACHE_VAL(tcl_cv_type_off64_t,[
+           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
+],
+               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
+       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
+       dnl functions lseek64 and open64 are defined.
+       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
+               test "x${ac_cv_func_lseek64}" = "xyes" && \
+               test "x${ac_cv_func_open64}" = "xyes" ; then
+           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
+           AC_MSG_RESULT([yes])
+       else
+           AC_MSG_RESULT([no])
+       fi
+    fi
+])
+
+##
+## Here ends the standard Tcl configuration bits and starts the
+## TEA specific functions
+##
+
+#------------------------------------------------------------------------
+# TEA_INIT --
+#
+#      Init various Tcl Extension Architecture (TEA) variables.
+#      This should be the first called TEA_* macro.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              CYGPATH
+#              EXEEXT
+#      Defines only:
+#              TEA_VERSION
+#              TEA_INITED
+#              TEA_PLATFORM (windows or unix)
+#
+# "cygpath" is used on windows to generate native path names for include
+# files. These variables should only be used with the compiler and linker
+# since they generate native path names.
+#
+# EXEEXT
+#      Select the executable extension based on the host type.  This
+#      is a lightweight replacement for AC_EXEEXT that doesn't require
+#      a compiler.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INIT], [
+    TEA_VERSION="3.13"
+
+    AC_MSG_CHECKING([TEA configuration])
+    if test x"${PACKAGE_NAME}" = x ; then
+       AC_MSG_ERROR([
+The PACKAGE_NAME variable must be defined by your TEA configure.ac])
+    fi
+    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
+
+    # If the user did not set CFLAGS, set it now to keep macros
+    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
+    if test "${CFLAGS+set}" != "set" ; then
+       CFLAGS=""
+    fi
+
+    case "`uname -s`" in
+       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
+           EXEEXT=".exe"
+           TEA_PLATFORM="windows"
+           ;;
+       *CYGWIN_*)
+           EXEEXT=".exe"
+           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
+           ;;
+       *)
+           CYGPATH=echo
+           # Maybe we are cross-compiling....
+           case ${host_alias} in
+               *mingw32*)
+               EXEEXT=".exe"
+               TEA_PLATFORM="windows"
+               ;;
+           *)
+               EXEEXT=""
+               TEA_PLATFORM="unix"
+               ;;
+           esac
+           ;;
+    esac
+
+    # Check if exec_prefix is set. If not use fall back to prefix.
+    # Note when adjusted, so that TEA_PREFIX can correct for this.
+    # This is needed for recursive configures, since autoconf propagates
+    # $prefix, but not $exec_prefix (doh!).
+    if test x$exec_prefix = xNONE ; then
+       exec_prefix_default=yes
+       exec_prefix=$prefix
+    fi
+
+    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
+
+    AC_SUBST(EXEEXT)
+    AC_SUBST(CYGPATH)
+
+    # This package name must be replaced statically for AC_SUBST to work
+    AC_SUBST(PKG_LIB_FILE)
+    # Substitute STUB_LIB_FILE in case package creates a stub library too.
+    AC_SUBST(PKG_STUB_LIB_FILE)
+
+    # We AC_SUBST these here to ensure they are subst'ed,
+    # in case the user doesn't call TEA_ADD_...
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+    AC_SUBST(PKG_TCL_SOURCES)
+    AC_SUBST(PKG_HEADERS)
+    AC_SUBST(PKG_INCLUDES)
+    AC_SUBST(PKG_LIBS)
+    AC_SUBST(PKG_CFLAGS)
+
+    # Configure the installer.
+    TEA_INSTALLER
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_SOURCES
+#              PKG_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       case $i in
+           [\$]*)
+               # allow $-var names
+               PKG_SOURCES="$PKG_SOURCES $i"
+               PKG_OBJECTS="$PKG_OBJECTS $i"
+               ;;
+           *)
+               # check for existence - allows for generic/win/unix VPATH
+               # To add more dirs here (like 'src'), you have to update VPATH
+               # in Makefile.in as well
+               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+                   -a ! -f "${srcdir}/macosx/$i" \
+                   ; then
+                   AC_MSG_ERROR([could not find source file '$i'])
+               fi
+               PKG_SOURCES="$PKG_SOURCES $i"
+               # this assumes it is in a VPATH dir
+               i=`basename $i`
+               # handle user calling this before or after TEA_SETUP_COMPILER
+               if test x"${OBJEXT}" != x ; then
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+               else
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+               fi
+               PKG_OBJECTS="$PKG_OBJECTS $j"
+               ;;
+       esac
+    done
+    AC_SUBST(PKG_SOURCES)
+    AC_SUBST(PKG_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_STUB_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_STUB_SOURCES
+#              PKG_STUB_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_STUB_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence - allows for generic/win/unix VPATH
+       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+           -a ! -f "${srcdir}/macosx/$i" \
+           ; then
+           AC_MSG_ERROR([could not find stub source file '$i'])
+       fi
+       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
+       # this assumes it is in a VPATH dir
+       i=`basename $i`
+       # handle user calling this before or after TEA_SETUP_COMPILER
+       if test x"${OBJEXT}" != x ; then
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+       else
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+       fi
+       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
+    done
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_TCL_SOURCES --
+#
+#      Specify one or more Tcl source files.  These should be platform
+#      independent runtime files.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_TCL_SOURCES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_TCL_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
+       fi
+       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
+    done
+    AC_SUBST(PKG_TCL_SOURCES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_HEADERS --
+#
+#      Specify one or more source headers.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_HEADERS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_HEADERS], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
+       fi
+       PKG_HEADERS="$PKG_HEADERS $i"
+    done
+    AC_SUBST(PKG_HEADERS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_INCLUDES --
+#
+#      Specify one or more include dirs.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_INCLUDES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_INCLUDES], [
+    vars="$@"
+    for i in $vars; do
+       PKG_INCLUDES="$PKG_INCLUDES $i"
+    done
+    AC_SUBST(PKG_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_LIBS --
+#
+#      Specify one or more libraries.  Users should check for
+#      the right platform before adding to their list.  For Windows,
+#      libraries provided in "foo.lib" format will be converted to
+#      "-lfoo" when using GCC (mingw).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_LIBS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_LIBS], [
+    vars="$@"
+    for i in $vars; do
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
+           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
+       fi
+       PKG_LIBS="$PKG_LIBS $i"
+    done
+    AC_SUBST(PKG_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CFLAGS --
+#
+#      Specify one or more CFLAGS.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_CFLAGS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CFLAGS], [
+    PKG_CFLAGS="$PKG_CFLAGS $@"
+    AC_SUBST(PKG_CFLAGS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CLEANFILES --
+#
+#      Specify one or more CLEANFILES.
+#
+# Arguments:
+#      one or more file names to clean target
+#
+# Results:
+#
+#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CLEANFILES], [
+    CLEANFILES="$CLEANFILES $@"
+])
+
+#------------------------------------------------------------------------
+# TEA_PREFIX --
+#
+#      Handle the --prefix=... option by defaulting to what Tcl gave
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      If --prefix or --exec-prefix was not specified, $prefix and
+#      $exec_prefix will be set to the values given to Tcl when it was
+#      configured.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_PREFIX], [
+    if test "${prefix}" = "NONE"; then
+       prefix_default=yes
+       if test x"${TCL_PREFIX}" != x; then
+           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
+           prefix=${TCL_PREFIX}
+       else
+           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
+           prefix=/usr/local
+       fi
+    fi
+    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
+       -o x"${exec_prefix_default}" = x"yes" ; then
+       if test x"${TCL_EXEC_PREFIX}" != x; then
+           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
+           exec_prefix=${TCL_EXEC_PREFIX}
+       else
+           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
+           exec_prefix=$prefix
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER_CC --
+#
+#      Do compiler checks the way we want.  This is just a replacement
+#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER_CC], [
+    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
+    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
+
+    AC_PROG_CC
+    AC_PROG_CPP
+
+    #--------------------------------------------------------------------
+    # Checks to see if the make program sets the $MAKE variable.
+    #--------------------------------------------------------------------
+
+    AC_PROG_MAKE_SET
+
+    #--------------------------------------------------------------------
+    # Find ranlib
+    #--------------------------------------------------------------------
+
+    AC_CHECK_TOOL(RANLIB, ranlib)
+
+    #--------------------------------------------------------------------
+    # Determines the correct binary file extension (.o, .obj, .exe etc.)
+    #--------------------------------------------------------------------
+
+    AC_OBJEXT
+    AC_EXEEXT
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER --
+#
+#      Do compiler checks that use the compiler.  This must go after
+#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER], [
+    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
+    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
+
+    #------------------------------------------------------------------------
+    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
+    # It makes compiling go faster.  (This is only a performance feature.)
+    #------------------------------------------------------------------------
+
+    if test -z "$no_pipe" -a -n "$GCC"; then
+       AC_CACHE_CHECK([if the compiler understands -pipe],
+           tcl_cv_cc_pipe, [
+           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
+           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
+           CFLAGS=$hold_cflags])
+       if test $tcl_cv_cc_pipe = yes; then
+           CFLAGS="$CFLAGS -pipe"
+       fi
+    fi
+
+    #--------------------------------------------------------------------
+    # Common compiler flag setup
+    #--------------------------------------------------------------------
+
+    AC_C_BIGENDIAN
+])
+
+#------------------------------------------------------------------------
+# TEA_MAKE_LIB --
+#
+#      Generate a line that can be used to build a shared/unshared library
+#      in a platform independent manner.
+#
+# Arguments:
+#      none
+#
+#      Requires:
+#
+# Results:
+#
+#      Defines the following vars:
+#      CFLAGS -        Done late here to note disturb other AC macros
+#       MAKE_LIB -      Command to execute to build the Tcl library;
+#                       differs depending on whether or not Tcl is being
+#                       compiled as a shared library.
+#      MAKE_SHARED_LIB Makefile rule for building a shared library
+#      MAKE_STATIC_LIB Makefile rule for building a static library
+#      MAKE_STUB_LIB   Makefile rule for building a stub library
+#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
+#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_MAKE_LIB], [
+    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
+       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       AC_EGREP_CPP([manifest needed], [
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+print("manifest needed")
+#endif
+       ], [
+       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
+       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
+       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
+       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
+       TEA_ADD_CLEANFILES([*.manifest])
+       ])
+       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
+    else
+       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
+    fi
+
+    if test "${SHARED_BUILD}" = "1" ; then
+       MAKE_LIB="${MAKE_SHARED_LIB} "
+    else
+       MAKE_LIB="${MAKE_STATIC_LIB} "
+    fi
+
+    #--------------------------------------------------------------------
+    # Shared libraries and static libraries have different names.
+    # Use the double eval to make sure any variables in the suffix is
+    # substituted. (@@@ Might not be necessary anymore)
+    #--------------------------------------------------------------------
+
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       if test "${SHARED_BUILD}" = "1" ; then
+           # We force the unresolved linking of symbols that are really in
+           # the private libraries of Tcl and Tk.
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
+           fi
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
+           if test "$GCC" = "yes"; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
+           fi
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+       else
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+           if test "$GCC" = "yes"; then
+               PKG_LIB_FILE=lib${PKG_LIB_FILE}
+           fi
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+       if test "$GCC" = "yes"; then
+           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
+       fi
+       # These aren't needed on Windows (either MSVC or gcc)
+       RANLIB=:
+       RANLIB_STUB=:
+    else
+       RANLIB_STUB="${RANLIB}"
+       if test "${SHARED_BUILD}" = "1" ; then
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
+           fi
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+           RANLIB=:
+       else
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+    fi
+
+    # These are escaped so that only CFLAGS is picked up at configure time.
+    # The other values will be substituted at make time.
+    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
+    if test "${SHARED_BUILD}" = "1" ; then
+       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
+    fi
+
+    AC_SUBST(MAKE_LIB)
+    AC_SUBST(MAKE_SHARED_LIB)
+    AC_SUBST(MAKE_STATIC_LIB)
+    AC_SUBST(MAKE_STUB_LIB)
+    AC_SUBST(RANLIB_STUB)
+    AC_SUBST(VC_MANIFEST_EMBED_DLL)
+    AC_SUBST(VC_MANIFEST_EMBED_EXE)
+])
+
+#------------------------------------------------------------------------
+# TEA_LIB_SPEC --
+#
+#      Compute the name of an existing object library located in libdir
+#      from the given base name and produce the appropriate linker flags.
+#
+# Arguments:
+#      basename        The base name of the library without version
+#                      numbers, extensions, or "lib" prefixes.
+#      extra_dir       Extra directory in which to search for the
+#                      library.  This location is used first, then
+#                      $prefix/$exec-prefix, then some defaults.
+#
+# Requires:
+#      TEA_INIT and TEA_PREFIX must be called first.
+#
+# Results:
+#
+#      Defines the following vars:
+#              ${basename}_LIB_NAME    The computed library name.
+#              ${basename}_LIB_SPEC    The computed linker flags.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LIB_SPEC], [
+    AC_MSG_CHECKING([for $1 library])
+
+    # Look in exec-prefix for the library (defined by TEA_PREFIX).
+
+    tea_lib_name_dir="${exec_prefix}/lib"
+
+    # Or in a user-specified location.
+
+    if test x"$2" != x ; then
+       tea_extra_lib_dir=$2
+    else
+       tea_extra_lib_dir=NONE
+    fi
+
+    for i in \
+           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
+       if test -f "$i" ; then
+           tea_lib_name_dir=`dirname $i`
+           $1_LIB_NAME=`basename $i`
+           $1_LIB_PATH_NAME=$i
+           break
+       fi
+    done
+
+    if test "${TEA_PLATFORM}" = "windows"; then
+       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
+    else
+       # Strip off the leading "lib" and trailing ".a" or ".so"
+
+       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
+       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
+    fi
+
+    if test "x${$1_LIB_NAME}" = x ; then
+       AC_MSG_ERROR([not found])
+    else
+       AC_MSG_RESULT([${$1_LIB_SPEC}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TCL_HEADERS --
+#
+#      Locate the private Tcl include files
+#
+# Arguments:
+#
+#      Requires:
+#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
+#                              already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_TOP_DIR_NATIVE
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
+    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
+    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
+    AC_MSG_CHECKING([for Tcl private include files])
+
+    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
+    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
+
+    # Check to see if tcl<Plat>Port.h isn't already with the public headers
+    # Don't look for tclInt.h because that resides with tcl.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
+       else
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TCL_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
+       if test "`uname -s`" = "Darwin"; then
+            # If Tcl was built as a framework, attempt to use
+            # the framework's Headers and PrivateHeaders directories
+            case ${TCL_DEFS} in
+               *TCL_FRAMEWORK*)
+                   if test -d "${TCL_BIN_DIR}/Headers" -a \
+                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
+                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
+                   else
+                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                   fi
+                   ;;
+           esac
+           result="Using ${TCL_INCLUDES}"
+       else
+           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
+               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
+           fi
+           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TCL_TOP_DIR_NATIVE)
+
+    AC_SUBST(TCL_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TCL_HEADERS --
+#
+#      Locate the installed public Tcl header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tclinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
+    AC_MSG_CHECKING([for Tcl public headers])
+
+    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tclh, [
+       # Use the value from --with-tclinclude, if it was given
+
+       if test x"${with_tclinclude}" != x ; then
+           if test -f "${with_tclinclude}/tcl.h" ; then
+               ac_cv_c_tclh=${with_tclinclude}
+           else
+               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tcl was built as a framework, attempt to use
+               # the framework's Headers directory
+               case ${TCL_DEFS} in
+                   *TCL_FRAMEWORK*)
+                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tcl is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TCL_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TCL_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tcl.h" ; then
+                   ac_cv_c_tclh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tclh}" = x ; then
+       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tclh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
+
+    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TCL_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TK_HEADERS --
+#
+#      Locate the private Tk include files
+#
+# Arguments:
+#
+#      Requires:
+#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
+#                               already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
+    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
+    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
+    AC_MSG_CHECKING([for Tk private include files])
+
+    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
+    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
+
+    # Check to see if tk<Plat>Port.h isn't already with the public headers
+    # Don't look for tkInt.h because that resides with tk.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
+       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
+       else
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TK_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
+       # Detect and add ttk subdir
+       if test -d "${TK_SRC_DIR}/generic/ttk"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
+       fi
+       if test "`uname -s`" = "Darwin"; then
+           # If Tk was built as a framework, attempt to use
+           # the framework's Headers and PrivateHeaders directories
+           case ${TK_DEFS} in
+               *TK_FRAMEWORK*)
+                       if test -d "${TK_BIN_DIR}/Headers" -a \
+                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
+                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
+                       else
+                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                       fi
+                       ;;
+           esac
+           result="Using ${TK_INCLUDES}"
+       else
+           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
+              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
+           fi
+           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TK_TOP_DIR_NATIVE)
+    AC_SUBST(TK_XLIB_DIR_NATIVE)
+
+    AC_SUBST(TK_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TK_HEADERS --
+#
+#      Locate the installed public Tk header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tkinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
+    AC_MSG_CHECKING([for Tk public headers])
+
+    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tkh, [
+       # Use the value from --with-tkinclude, if it was given
+
+       if test x"${with_tkinclude}" != x ; then
+           if test -f "${with_tkinclude}/tk.h" ; then
+               ac_cv_c_tkh=${with_tkinclude}
+           else
+               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tk was built as a framework, attempt to use
+               # the framework's Headers directory.
+               case ${TK_DEFS} in
+                   *TK_FRAMEWORK*)
+                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tk is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TK_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tk's --prefix location,
+           # relative to directory of tkConfig.sh, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
+               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TK_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tk.h" ; then
+                   ac_cv_c_tkh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tkh}" = x ; then
+       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tkh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
+
+    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TK_INCLUDES)
+
+    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+       # On Windows and Aqua, we need the X compat headers
+       AC_MSG_CHECKING([for X11 header files])
+       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
+           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
+           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+           AC_SUBST(TK_XINCLUDES)
+       fi
+       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_CONFIG --
+#
+#      Locate the ${1}Config.sh file and perform a sanity check on
+#      the ${1} compile flags.  These are used by packages like
+#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-$1=...
+#
+#      Defines the following vars:
+#              $1_BIN_DIR      Full path to the directory containing
+#                              the $1Config.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_CONFIG], [
+    #
+    # Ok, lets find the $1 configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-$1
+    #
+
+    if test x"${no_$1}" = x ; then
+       # we reset no_$1 in case something fails here
+       no_$1=true
+       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
+       AC_MSG_CHECKING([for $1 configuration])
+       AC_CACHE_VAL(ac_cv_c_$1config,[
+
+           # First check to see if --with-$1 was specified.
+           if test x"${with_$1config}" != x ; then
+               case ${with_$1config} in
+                   */$1Config.sh )
+                       if test -f ${with_$1config}; then
+                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
+                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
+                       fi;;
+               esac
+               if test -f "${with_$1config}/$1Config.sh" ; then
+                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
+               else
+                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
+               fi
+           fi
+
+           # then check for a private $1 installation
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in \
+                       ../$1 \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../$1 \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../$1 \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ${srcdir}/../$1 \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+                   if test -f "$i/unix/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_$1config}" = x ; then
+           $1_BIN_DIR="# no $1 configs found"
+           AC_MSG_WARN([Cannot find $1 configuration definitions])
+           exit 0
+       else
+           no_$1=
+           $1_BIN_DIR=${ac_cv_c_$1config}
+           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG --
+#
+#      Load the $1Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              $1_SRC_DIR
+#              $1_LIB_FILE
+#              $1_LIB_SPEC
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_CONFIG], [
+    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
+
+    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${$1_BIN_DIR}/$1Config.sh"
+    else
+        AC_MSG_RESULT([file not found])
+    fi
+
+    #
+    # If the $1_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable $1_LIB_SPEC will be set to the value
+    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
+    # instead of $1_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    #
+
+    if test -f "${$1_BIN_DIR}/Makefile" ; then
+       AC_MSG_WARN([Found Makefile - using build library specs for $1])
+        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
+        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
+        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
+        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
+        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
+    fi
+
+    AC_SUBST($1_VERSION)
+    AC_SUBST($1_BIN_DIR)
+    AC_SUBST($1_SRC_DIR)
+
+    AC_SUBST($1_LIB_FILE)
+    AC_SUBST($1_LIB_SPEC)
+
+    AC_SUBST($1_STUB_LIB_FILE)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    # Allow the caller to prevent this auto-check by specifying any 2nd arg
+    AS_IF([test "x$2" = x], [
+       # Check both upper and lower-case variants
+       # If a dev wanted non-stubs libs, this function could take an option
+       # to not use _STUB in the paths below
+       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
+           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
+           [TEA_LOAD_CONFIG_LIB($1_STUB)])
+    ])
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG_LIB --
+#
+#      Helper function to load correct library from another extension's
+#      ${PACKAGE}Config.sh.
+#
+# Results:
+#      Adds to LIBS the appropriate extension library
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
+    AC_MSG_CHECKING([For $1 library for LIBS])
+    # This simplifies the use of stub libraries by automatically adding
+    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
+    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
+    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
+    if test "x${$1_LIB_SPEC}" != "x" ; then
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
+           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
+           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
+       else
+           TEA_ADD_LIBS([${$1_LIB_SPEC}])
+           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
+       fi
+    else
+       AC_MSG_RESULT([file not found])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_EXPORT_CONFIG --
+#
+#      Define the data to insert into the ${PACKAGE}Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1
+#
+# Results:
+#      Substitutes the following vars:
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_EXPORT_CONFIG], [
+    #--------------------------------------------------------------------
+    # These are for $1Config.sh
+    #--------------------------------------------------------------------
+
+    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
+    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
+    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
+    else
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
+    fi
+    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
+    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
+    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
+    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
+
+    AC_SUBST($1_BUILD_LIB_SPEC)
+    AC_SUBST($1_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_PATH)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    AC_SUBST(MAJOR_VERSION)
+    AC_SUBST(MINOR_VERSION)
+    AC_SUBST(PATCHLEVEL)
+])
+
+
+#------------------------------------------------------------------------
+# TEA_INSTALLER --
+#
+#      Configure the installer.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              INSTALL
+#              INSTALL_DATA_DIR
+#              INSTALL_DATA
+#              INSTALL_PROGRAM
+#              INSTALL_SCRIPT
+#              INSTALL_LIBRARY
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INSTALLER], [
+    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
+    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
+    INSTALL_DATA='${INSTALL} -m 644'
+    INSTALL_PROGRAM='${INSTALL} -m 755'
+    INSTALL_SCRIPT='${INSTALL} -m 755'
+
+    TEA_CONFIG_SYSTEM
+    case $system in
+       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
+             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
+    esac
+
+    AC_SUBST(INSTALL)
+    AC_SUBST(INSTALL_DATA_DIR)
+    AC_SUBST(INSTALL_DATA)
+    AC_SUBST(INSTALL_PROGRAM)
+    AC_SUBST(INSTALL_SCRIPT)
+    AC_SUBST(INSTALL_LIBRARY)
+])
+
+###
+# Tip 430 - ZipFS Modifications
+###
+#------------------------------------------------------------------------
+# SC_ZIPFS_SUPPORT
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#              TCL_ZIPFS_FLAG
+#              ZIP_PROG
+#------------------------------------------------------------------------
+
+#------------------------------------------------------------------------
+# SC_PROG_ZIP
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              ZIP_PROG
+#       ZIP_PROG_OPTIONS
+#       ZIP_PROG_VFSSEARCH
+#       ZIP_INSTALL_OBJS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ZIPFS_SUPPORT], [
+    AC_MSG_CHECKING([for zipfs support])
+    ZIP_PROG=""
+    ZIP_PROG_OPTIONS=""
+    ZIP_PROG_VFSSEARCH=""
+    INSTALL_MSGS=""
+    # If our native tclsh processes the "install" command line option
+    # we can use it to mint zip files
+    AS_IF([$TCLSH_PROG install],[
+      ZIP_PROG=${TCLSH_PROG}
+      ZIP_PROG_OPTIONS="install mkzip"
+      ZIP_PROG_VFSSEARCH="."
+      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
+    ])
+    if test "x$ZIP_PROG" = "x" ; then
+        AC_CACHE_VAL(ac_cv_path_zip, [
+        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
+        for dir in $search_path ; do
+            for j in `ls -r $dir/zip 2> /dev/null` \
+                `ls -r $dir/zip 2> /dev/null` ; do
+            if test x"$ac_cv_path_zip" = x ; then
+                if test -f "$j" ; then
+                ac_cv_path_zip=$j
+                break
+                fi
+            fi
+            done
+        done
+        ])
+        if test -f "$ac_cv_path_zip" ; then
+            ZIP_PROG="$ac_cv_path_zip "
+            AC_MSG_RESULT([$ZIP_PROG])
+            ZIP_PROG_OPTIONS="-rq"
+            ZIP_PROG_VFSSEARCH="."
+            AC_MSG_RESULT([Found INFO Zip in environment])
+            # Use standard arguments for zip
+        fi
+    fi
+    if test "x$ZIP_PROG" = "x" ; then
+           # It is not an error if an installed version of Zip can't be located.
+        ZIP_PROG=""
+        ZIP_PROG_OPTIONS=""
+        ZIP_PROG_VFSSEARCH=""
+        TCL_ZIPFS_SUPPORT=0
+        TCL_ZIPFS_FLAG=
+    else
+        # ZIPFS Support
+       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
+       if test ${TCL_ZIP_FILE} = "" ; then
+          TCL_ZIPFS_SUPPORT=0
+          TCL_ZIPFS_FLAG=
+          INSTALL_LIBRARIES=install-libraries
+          INSTALL_MSGS=install-msgs
+       else
+           if test ${SHARED_BUILD} = 1 ; then
+              TCL_ZIPFS_SUPPORT=1
+              INSTALL_LIBRARIES=install-libraries-zipfs-shared
+           else
+              TCL_ZIPFS_SUPPORT=2
+              INSTALL_LIBRARIES=install-libraries-zipfs-static
+           fi
+          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
+       fi
+    fi
+
+    AC_SUBST(TCL_ZIP_FILE)
+    AC_SUBST(TCL_ZIPFS_SUPPORT)
+    AC_SUBST(TCL_ZIPFS_FLAG)
+    AC_SUBST(ZIP_PROG)
+    AC_SUBST(ZIP_PROG_OPTIONS)
+    AC_SUBST(ZIP_PROG_VFSSEARCH)
+    AC_SUBST(INSTALL_LIBRARIES)
+    AC_SUBST(INSTALL_MSGS)
+])
+
+# Local Variables:
+# mode: autoconf
+# End:
similarity index 95%
rename from pkgs/tdbcpostgres1.1.1/win/makefile.vc
rename to pkgs/tdbcpostgres1.1.2/win/makefile.vc
index 11d7839..906e1fc 100644 (file)
@@ -8,7 +8,7 @@
 #   nmake /s /nologo /f makefile.vc INSTALLDIR=c:\path\to\installdir TCLDIR=c:\path\to\tcl\source install\r
 #\r
 # For other build options (debug, static etc.)\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
similarity index 99%
rename from pkgs/tdbcodbc1.1.1/win/nmakehlp.c
rename to pkgs/tdbcpostgres1.1.2/win/nmakehlp.c
index c21de63..7536ede 100644 (file)
@@ -643,7 +643,7 @@ SubstituteFile(
        }
 
        /* debug: dump the list */
-#ifdef _DEBUG
+#ifndef NDEBUG
        {
            int n = 0;
            list_item_t *p = NULL;
@@ -708,7 +708,7 @@ QualifyPath(
 {
     char szCwd[MAX_PATH + 1];
 
-       GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
+    GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
     printf("%s\n", szCwd);
     return 0;
 }
diff --git a/pkgs/tdbcpostgres1.1.2/win/rules-ext.vc b/pkgs/tdbcpostgres1.1.2/win/rules-ext.vc
new file mode 100644 (file)
index 0000000..6da5689
--- /dev/null
@@ -0,0 +1,118 @@
+# This file should only be included in makefiles for Tcl extensions,\r
+# NOT in the makefile for Tcl itself.\r
+\r
+!ifndef _RULES_EXT_VC\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+!if "$(PROJECT)" == "tcl"\r
+!error The rules-ext.vc file is not intended for Tcl itself.\r
+!endif\r
+\r
+# We extract version numbers using the nmakehlp program. For now use\r
+# the local copy of nmakehlp. Once we locate Tcl, we will use that\r
+# one if it is newer.\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
+!endif\r
+\r
+# First locate the Tcl directory that we are working with.\r
+!if "$(TCLDIR)" != ""\r
+\r
+_RULESDIR = $(TCLDIR:/=\)\r
+\r
+!else\r
+\r
+# If an installation path is specified, that is also the Tcl directory.\r
+# Also Tk never builds against an installed Tcl, it needs Tcl sources\r
+!if defined(INSTALLDIR) && "$(PROJECT)" != "tk"\r
+_RULESDIR=$(INSTALLDIR:/=\)\r
+!else\r
+# Locate Tcl sources\r
+!if [echo _RULESDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+_RULESDIR = ..\..\tcl\r
+!else\r
+!include nmakehlp.out\r
+!endif\r
+\r
+!endif # defined(INSTALLDIR)....\r
+\r
+!endif # ifndef TCLDIR\r
+\r
+# Now look for the targets.vc file under the Tcl root. Note we check this\r
+# file and not rules.vc because the latter also exists on older systems.\r
+!if exist("$(_RULESDIR)\lib\nmake\targets.vc") # Building against installed Tcl\r
+_RULESDIR = $(_RULESDIR)\lib\nmake\r
+!elseif exist("$(_RULESDIR)\win\targets.vc")   # Building against Tcl sources\r
+_RULESDIR = $(_RULESDIR)\win\r
+!else\r
+# If we have not located Tcl's targets file, most likely we are compiling\r
+# against an older version of Tcl and so must use our own support files.\r
+_RULESDIR = .\r
+!endif\r
+\r
+!if "$(_RULESDIR)" != "."\r
+# Potentially using Tcl's support files. If this extension has its own\r
+# nmake support files, need to compare the versions and pick newer.\r
+\r
+!if exist("rules.vc") # The extension has its own copy\r
+\r
+!if [echo TCL_RULES_MAJOR = \> versions.vc] \\r
+   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
+!endif\r
+!if [echo TCL_RULES_MINOR = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
+!endif\r
+\r
+!if [echo OUR_RULES_MAJOR = \>> versions.vc] \\r
+   && [nmakehlp -V "rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
+!endif\r
+!if [echo OUR_RULES_MINOR = \>> versions.vc] \\r
+   && [nmakehlp -V "rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
+!endif\r
+!include versions.vc\r
+# We have a newer version of the support files, use them\r
+!if ($(TCL_RULES_MAJOR) != $(OUR_RULES_MAJOR)) || ($(TCL_RULES_MINOR) < $(OUR_RULES_MINOR))\r
+_RULESDIR = .\r
+!endif\r
+\r
+!endif # if exist("rules.vc")\r
+\r
+!endif # if $(_RULESDIR) != "."\r
+\r
+# Let rules.vc know what copy of nmakehlp.c to use.\r
+NMAKEHLPC = $(_RULESDIR)\nmakehlp.c\r
+\r
+# Get rid of our internal defines before calling rules.vc\r
+!undef TCL_RULES_MAJOR\r
+!undef TCL_RULES_MINOR\r
+!undef OUR_RULES_MAJOR\r
+!undef OUR_RULES_MINOR\r
+\r
+!if exist("$(_RULESDIR)\rules.vc")\r
+!message *** Using $(_RULESDIR)\rules.vc\r
+!include "$(_RULESDIR)\rules.vc"\r
+!else\r
+!error *** Could not locate rules.vc in $(_RULESDIR)\r
+!endif\r
+\r
+!endif # _RULES_EXT_VC
\ No newline at end of file
diff --git a/pkgs/tdbcpostgres1.1.2/win/rules.vc b/pkgs/tdbcpostgres1.1.2/win/rules.vc
new file mode 100644 (file)
index 0000000..13e3879
--- /dev/null
@@ -0,0 +1,1852 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# rules.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file does all the hard work in terms of parsing build options,\r
+# compiler switches, defining common targets and macros. The Tcl makefile\r
+# directly includes this. Extensions include it via "rules-ext.vc".\r
+#\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
+# detailed documentation.\r
+#\r
+# See the file "license.terms" for information on usage and redistribution\r
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
+#\r
+# Copyright (c) 2001-2003 David Gravereaux.\r
+# Copyright (c) 2003-2008 Patrick Thoyts\r
+# Copyright (c) 2017      Ashok P. Nadkarni\r
+#------------------------------------------------------------------------------\r
+\r
+!ifndef _RULES_VC\r
+_RULES_VC = 1\r
+\r
+# The following macros define the version of the rules.vc nmake build system\r
+# For modifications that are not backward-compatible, you *must* change\r
+# the major version.\r
+RULES_VERSION_MAJOR = 1\r
+RULES_VERSION_MINOR = 8\r
+\r
+# The PROJECT macro must be defined by parent makefile.\r
+!if "$(PROJECT)" == ""\r
+!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
+!endif\r
+\r
+!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
+PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
+!endif\r
+\r
+# Also special case Tcl and Tk to save some typing later\r
+DOING_TCL = 0\r
+DOING_TK  = 0\r
+!if "$(PROJECT)" == "tcl"\r
+DOING_TCL = 1\r
+!elseif "$(PROJECT)" == "tk"\r
+DOING_TK = 1\r
+!endif\r
+\r
+!ifndef NEED_TK\r
+# Backwards compatibility\r
+!ifdef PROJECT_REQUIRES_TK\r
+NEED_TK = $(PROJECT_REQUIRES_TK)\r
+!else\r
+NEED_TK = 0\r
+!endif\r
+!endif\r
+\r
+!ifndef NEED_TCL_SOURCE\r
+NEED_TCL_SOURCE = 0\r
+!endif\r
+\r
+!ifdef NEED_TK_SOURCE\r
+!if $(NEED_TK_SOURCE)\r
+NEED_TK = 1\r
+!endif\r
+!else\r
+NEED_TK_SOURCE = 0\r
+!endif\r
+\r
+################################################################\r
+# Nmake is a pretty weak environment in syntax and capabilities\r
+# so this file is necessarily verbose. It's broken down into\r
+# the following parts.\r
+#\r
+# 0. Sanity check that compiler environment is set up and initialize\r
+#    any built-in settings from the parent makefile\r
+# 1. First define the external tools used for compiling, copying etc.\r
+#    as this is independent of everything else.\r
+# 2. Figure out our build structure in terms of the directory, whether\r
+#    we are building Tcl or an extension, etc.\r
+# 3. Determine the compiler and linker versions\r
+# 4. Build the nmakehlp helper application\r
+# 5. Determine the supported compiler options and features\r
+# 6. Parse the OPTS macro value for user-specified build configuration\r
+# 7. Parse the STATS macro value for statistics instrumentation\r
+# 8. Parse the CHECKS macro for additional compilation checks\r
+# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
+# 10. Based on this selected configuration, construct the output\r
+#     directory and file paths\r
+# 11. Construct the paths where the package is to be installed\r
+# 12. Set up the actual options passed to compiler and linker based\r
+#     on the information gathered above.\r
+# 13. Define some standard build targets and implicit rules. These may\r
+#     be optionally disabled by the parent makefile.\r
+# 14. (For extensions only.) Compare the configuration of the target\r
+#     Tcl and the extensions and warn against discrepancies.\r
+#\r
+# One final note about the macro names used. They are as they are\r
+# for historical reasons. We would like legacy extensions to\r
+# continue to work with this make include file so be wary of\r
+# changing them for consistency or clarity.\r
+\r
+# 0. Sanity check compiler environment\r
+\r
+# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
+# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
+\r
+!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
+MSG = ^\r
+Visual C++ compiler environment not initialized.\r
+!error $(MSG)\r
+!endif\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+\r
+################################################################\r
+# 1. Define external programs being used\r
+\r
+#----------------------------------------------------------\r
+# Set the proper copy method to avoid overwrite questions\r
+# to the user when copying files and selecting the right\r
+# "delete all" method.\r
+#----------------------------------------------------------\r
+\r
+RMDIR  = rmdir /S /Q\r
+CPY    = xcopy /i /y >NUL\r
+CPYDIR  = xcopy /e /i /y >NUL\r
+COPY   = copy /y >NUL\r
+MKDIR   = mkdir\r
+\r
+######################################################################\r
+# 2. Figure out our build environment in terms of what we're building.\r
+#\r
+# (a) Tcl itself\r
+# (b) Tk\r
+# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
+# (d) a Tcl extension using libraries/includes from Tcl source directory\r
+#\r
+# This last is needed because some extensions still need\r
+# some Tcl interfaces that are not publicly exposed.\r
+#\r
+# The fragment will set the following macros:\r
+# ROOT - root of this module sources\r
+# COMPATDIR - source directory that holds compatibility sources\r
+# DOCDIR - source directory containing documentation files\r
+# GENERICDIR - platform-independent source directory\r
+# WIN_DIR - Windows-specific source directory\r
+# TESTDIR - directory containing test files\r
+# TOOLSDIR - directory containing build tools\r
+# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
+#    when building Tcl itself.\r
+# _INSTALLDIR - native form of the installation path. For Tcl\r
+#    this will be the root of the Tcl installation. For extensions\r
+#    this will be the lib directory under the root.\r
+# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
+#    headers and libraries from an installed Tcl, and 0 if built against\r
+#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
+#    named.\r
+# _TCL_H - native path to the tcl.h file\r
+#\r
+# If Tk is involved, also sets the following\r
+# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
+#    Tk itself.\r
+# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
+# _TK_H - native path to the tk.h file\r
+\r
+# Root directory for sources and assumed subdirectories\r
+ROOT = $(MAKEDIR)\..\r
+# The following paths CANNOT have spaces in them as they appear on the\r
+# left side of implicit rules.\r
+!ifndef COMPATDIR\r
+COMPATDIR      = $(ROOT)\compat\r
+!endif\r
+!ifndef DOCDIR\r
+DOCDIR         = $(ROOT)\doc\r
+!endif\r
+!ifndef GENERICDIR\r
+GENERICDIR     = $(ROOT)\generic\r
+!endif\r
+!ifndef TOOLSDIR\r
+TOOLSDIR       = $(ROOT)\tools\r
+!endif\r
+!ifndef TESTDIR\r
+TESTDIR        = $(ROOT)\tests\r
+!endif\r
+!ifndef LIBDIR\r
+!if exist("$(ROOT)\library")\r
+LIBDIR          = $(ROOT)\library\r
+!else\r
+LIBDIR          = $(ROOT)\lib\r
+!endif\r
+!endif\r
+!ifndef DEMODIR\r
+!if exist("$(LIBDIR)\demos")\r
+DEMODIR                = $(LIBDIR)\demos\r
+!else\r
+DEMODIR                = $(ROOT)\demos\r
+!endif\r
+!endif # ifndef DEMODIR\r
+# Do NOT use WINDIR because it is Windows internal environment\r
+# variable to point to c:\windows!\r
+WIN_DIR                = $(ROOT)\win\r
+\r
+!ifndef RCDIR\r
+!if exist("$(WIN_DIR)\rc")\r
+RCDIR           = $(WIN_DIR)\rc\r
+!else\r
+RCDIR           = $(WIN_DIR)\r
+!endif\r
+!endif\r
+RCDIR = $(RCDIR:/=\)\r
+\r
+# The target directory where the built packages and binaries will be installed.\r
+# INSTALLDIR is the (optional) path specified by the user.\r
+# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
+!ifdef INSTALLDIR\r
+### Fix the path separators.\r
+_INSTALLDIR    = $(INSTALLDIR:/=\)\r
+!else\r
+### Assume the normal default.\r
+_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+\r
+# BEGIN Case 2(a) - Building Tcl itself\r
+\r
+# Only need to define _TCL_H\r
+_TCL_H = ..\generic\tcl.h\r
+\r
+# END Case 2(a) - Building Tcl itself\r
+\r
+!elseif $(DOING_TK)\r
+\r
+# BEGIN Case 2(b) - Building Tk\r
+\r
+TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
+!if "$(TCLDIR)" == ""\r
+!if [echo TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+!endif # TCLDIR == ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
+!if !exist("$(_TCL_H)")\r
+!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
+!endif\r
+\r
+_TK_H = ..\generic\tk.h\r
+\r
+# END Case 2(b) - Building Tk\r
+\r
+!else\r
+\r
+# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
+\r
+# If command line has specified Tcl location through TCLDIR, use it\r
+# else default to the INSTALLDIR setting\r
+!if "$(TCLDIR)" != ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
+TCLINSTALL     = 1\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
+TCLINSTALL     = 0\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+!endif\r
+\r
+!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
+\r
+TCLINSTALL     = 1\r
+TCLDIR          = $(_INSTALLDIR)\..\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TCLDIR                = $(_INSTALLDIR)\..\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!if [echo _TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TCLINSTALL      = 0\r
+TCLDIR         = $(_TCLDIR)\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!endif # TCLDIR\r
+\r
+!ifndef _TCL_H\r
+MSG =^\r
+Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+# Now do the same to locate Tk headers and libs if project requires Tk\r
+!if $(NEED_TK)\r
+\r
+!if "$(TKDIR)" != ""\r
+\r
+_TKDIR = $(TKDIR:/=\)\r
+!if exist("$(_TKDIR)\include\tk.h")\r
+TKINSTALL      = 1\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+!elseif exist("$(_TKDIR)\generic\tk.h")\r
+TKINSTALL      = 0\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+!endif\r
+\r
+!else # TKDIR not defined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+TKINSTALL      = 1\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TKDIR         = $(_INSTALLDIR)\..\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+TKDIR          = $(_TKDIR)\r
+\r
+!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!if [echo _TKDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
+!error *** Could not locate Tk source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TKINSTALL      = 0\r
+TKDIR          = $(_TKDIR)\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+\r
+!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!endif # TKDIR\r
+\r
+!ifndef _TK_H\r
+MSG =^\r
+Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+!endif # NEED_TK\r
+\r
+!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tcl.^\r
+*** Please set the TCLDIR macro to point to the Tcl sources.\r
+!error $(MSG)\r
+!endif\r
+\r
+!if $(NEED_TK_SOURCE)\r
+!if $(TKINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tk.^\r
+*** Please set the TKDIR macro to point to the Tk sources.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+\r
+# If INSTALLDIR set to Tcl installation root dir then reset to the\r
+# lib dir for installing extensions\r
+!if exist("$(_INSTALLDIR)\include\tcl.h")\r
+_INSTALLDIR=$(_INSTALLDIR)\lib\r
+!endif\r
+\r
+# END Case 2(c) or (d) - Building an extension\r
+!endif # if $(DOING_TCL)\r
+\r
+################################################################\r
+# 3. Determine compiler version and architecture\r
+# In this section, we figure out the compiler version and the\r
+# architecture for which we are building. This sets the\r
+# following macros:\r
+# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
+#     This is also printed by the compiler in dotted form 19.10 etc.\r
+# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
+#     compiler version 1200. This is kept only for legacy reasons as it\r
+#     does not make sense for recent Microsoft compilers. Only used for\r
+#     output directory names.\r
+# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
+# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
+# MACHINE - same as $(ARCH) - legacy\r
+# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
+\r
+cc32           = $(CC)   # built-in default.\r
+link32         = link\r
+lib32          = lib\r
+rc32           = $(RC)   # built-in default.\r
+\r
+#----------------------------------------------------------------\r
+# Figure out the compiler architecture and version by writing\r
+# the C macros to a file, preprocessing them with the C\r
+# preprocessor and reading back the created file\r
+\r
+_HASH=^#\r
+_VC_MANIFEST_EMBED_EXE=\r
+_VC_MANIFEST_EMBED_DLL=\r
+VCVER=0\r
+!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
+    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
+    && ![echo ARCH=IX86 >> vercl.x] \\r
+    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
+    && ![echo ARCH=AMD64 >> vercl.x] \\r
+    && ![echo $(_HASH)endif >> vercl.x] \\r
+    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
+!include vercl.i\r
+!if $(VCVERSION) < 1900\r
+!if ![echo VCVER= ^\> vercl.vc] \\r
+    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
+!include vercl.vc\r
+!endif\r
+!else\r
+# The simple calculation above does not apply to new Visual Studio releases\r
+# Keep the compiler version in its native form.\r
+VCVER = $(VCVERSION)\r
+!endif\r
+!endif\r
+\r
+!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# The MACHINE macro is used by legacy makefiles so set it as well\r
+!ifdef MACHINE\r
+!if "$(MACHINE)" == "x86"\r
+!undef MACHINE\r
+MACHINE = IX86\r
+!elseif "$(MACHINE)" == "x64"\r
+!undef MACHINE\r
+MACHINE = AMD64\r
+!endif\r
+!if "$(MACHINE)" != "$(ARCH)"\r
+!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
+!endif\r
+!else\r
+MACHINE=$(ARCH)\r
+!endif\r
+\r
+#---------------------------------------------------------------\r
+# The PLATFORM_IDENTIFY macro matches the values returned by\r
+# the Tcl platform::identify command\r
+!if "$(MACHINE)" == "AMD64"\r
+PLATFORM_IDENTIFY = win32-x86_64\r
+!else\r
+PLATFORM_IDENTIFY = win32-ix86\r
+!endif\r
+\r
+# The MULTIPLATFORM macro controls whether binary extensions are installed\r
+# in platform-specific directories. Intended to be set/used by extensions.\r
+!ifndef MULTIPLATFORM_INSTALL\r
+MULTIPLATFORM_INSTALL = 0\r
+!endif\r
+\r
+#------------------------------------------------------------\r
+# Figure out the *host* architecture by reading the registry\r
+\r
+!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
+NATIVE_ARCH=IX86\r
+!else\r
+NATIVE_ARCH=AMD64\r
+!endif\r
+\r
+# Since MSVC8 we must deal with manifest resources.\r
+!if $(VCVERSION) >= 1400\r
+_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
+_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
+!endif\r
+\r
+################################################################\r
+# 4. Build the nmakehlp program\r
+# This is a helper app we need to overcome nmake's limiting\r
+# environment. We will call out to it to get various bits of\r
+# information about supported compiler options etc.\r
+#\r
+# Tcl itself will always use the nmakehlp.c program which is\r
+# in its own source. It will be kept updated there.\r
+#\r
+# Extensions built against an installed Tcl will use the installed\r
+# copy of Tcl's nmakehlp.c if there is one and their own version\r
+# otherwise. In the latter case, they would also be using their own\r
+# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
+# or rules.vc.\r
+#\r
+# Extensions built against Tcl sources will use the one from the Tcl source.\r
+#\r
+# When building an extension using a sufficiently new version of Tcl,\r
+# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
+# copy of nmakehlp.c to be used.\r
+\r
+!ifndef NMAKEHLPC\r
+# Default to the one in the current directory (the extension's own nmakehlp.c)\r
+NMAKEHLPC = nmakehlp.c\r
+\r
+!if !$(DOING_TCL)\r
+!if $(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
+!endif\r
+!else # !$(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
+!endif\r
+!endif # $(TCLINSTALL)\r
+!endif # !$(DOING_TCL)\r
+\r
+!endif # NMAKEHLPC\r
+\r
+# We always build nmakehlp even if it exists since we do not know\r
+# what source it was built from.\r
+!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
+!endif\r
+\r
+################################################################\r
+# 5. Test for compiler features\r
+# Visual C++ compiler options have changed over the years. Check\r
+# which options are supported by the compiler in use.\r
+#\r
+# The following macros are set:\r
+# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
+# DEBUGFLAGS - the compiler flags to be used for debug builds\r
+# LINKERFLAGS - Flags passed to the linker\r
+#\r
+# Note that these are the compiler settings *available*, not those\r
+# that will be *used*. The latter depends on the OPTS macro settings\r
+# which we have not yet parsed.\r
+#\r
+# Also note that some of the flags in OPTIMIZATIONS are not really\r
+# related to optimization. They are placed there only for legacy reasons\r
+# as some extensions expect them to be included in that macro.\r
+\r
+# -Op improves float consistency. Note only needed for older compilers\r
+# Newer compilers do not need or support this option.\r
+!if [nmakehlp -c -Op]\r
+FPOPTS  = -Op\r
+!endif\r
+\r
+# Strict floating point semantics - present in newer compilers in lieu of -Op\r
+!if [nmakehlp -c -fp:strict]\r
+FPOPTS  = $(FPOPTS) -fp:strict\r
+!endif\r
+\r
+!if "$(MACHINE)" == "IX86"\r
+### test for pentium errata\r
+!if [nmakehlp -c -QI0f]\r
+!message *** Compiler has 'Pentium 0x0f fix'\r
+FPOPTS  = $(FPOPTS) -QI0f\r
+!else\r
+!message *** Compiler does not have 'Pentium 0x0f fix'\r
+!endif\r
+!endif\r
+\r
+### test for optimizations\r
+# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
+# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
+# stack probe at *every* function entry, not just those with more than\r
+# a page of stack allocation resulting in a performance hit.  However,\r
+# /O2 documentation is misleading as its stack probes are simply the\r
+# default page size locals allocation probes and not what is implied\r
+# by an explicit /Gs option.\r
+\r
+OPTIMIZATIONS = $(FPOPTS)\r
+\r
+!if [nmakehlp -c -O2]\r
+OPTIMIZING = 1\r
+OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
+!else\r
+# Legacy, really. All modern compilers support this\r
+!message *** Compiler does not have 'Optimizations'\r
+OPTIMIZING = 0\r
+!endif\r
+\r
+# Checks for buffer overflows in local arrays\r
+!if [nmakehlp -c -GS]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
+!endif\r
+\r
+# Link time optimization. Note that this option (potentially) makes\r
+# generated libraries only usable by the specific VC++ version that\r
+# created it. Requires /LTCG linker option\r
+!if [nmakehlp -c -GL]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
+CC_GL_OPT_ENABLED = 1\r
+!else\r
+# In newer compilers -GL and -YX are incompatible.\r
+!if [nmakehlp -c -YX]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
+!endif\r
+!endif # [nmakehlp -c -GL]\r
+\r
+DEBUGFLAGS     = $(FPOPTS)\r
+\r
+# Run time error checks. Not available or valid in a release, non-debug build\r
+# RTC is for modern compilers, -GZ is legacy\r
+!if [nmakehlp -c -RTC1]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
+!elseif [nmakehlp -c -GZ]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# Linker flags\r
+\r
+# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
+# if the linker supports a specific option. Without these flags link will\r
+# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
+# They are not passed through to the actual application / extension\r
+# link rules.\r
+!ifndef LINKER_TESTFLAGS\r
+LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
+!endif\r
+\r
+LINKERFLAGS     =\r
+\r
+# If compiler has enabled link time optimization, linker must too with -ltcg\r
+!ifdef CC_GL_OPT_ENABLED\r
+!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
+!endif\r
+!endif\r
+\r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
+########################################################################\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
+# Based on this, we will construct the actual switches to be passed to the\r
+# compiler and linker using the macros defined in the previous section.\r
+# The following macros are defined by this section based on OPTS\r
+# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
+#                1 -> build as a static library and shell\r
+# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
+# DEBUG - 1 -> debug build, 0 -> release builds\r
+# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
+# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
+# PGO     - 1 -> profile based optimization, 0 -> no\r
+# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
+#           0 -> link to static C runtime for static Tcl build.\r
+#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
+# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
+# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
+#           0 -> Use the non-thread allocator.\r
+# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
+#           C runtime, 0 -> use the debug C runtime.\r
+# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
+# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
+#           configuration (ignored for Tcl itself)\r
+# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
+# Further, LINKERFLAGS are modified based on above.\r
+\r
+# Default values for all the above\r
+STATIC_BUILD   = 0\r
+TCL_THREADS    = 1\r
+DEBUG          = 0\r
+SYMBOLS                = 0\r
+PROFILE                = 0\r
+PGO            = 0\r
+MSVCRT         = 1\r
+TCL_USE_STATIC_PACKAGES        = 0\r
+USE_THREAD_ALLOC = 1\r
+UNCHECKED      = 0\r
+CONFIG_CHECK    = 1\r
+!if $(DOING_TCL)\r
+USE_STUBS       = 0\r
+!else\r
+USE_STUBS       = 1\r
+!endif\r
+\r
+# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
+# set the above macros based on OPTS content\r
+!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
+\r
+# OPTS are specified, parse them\r
+\r
+!if [nmakehlp -f $(OPTS) "static"]\r
+!message *** Doing static\r
+STATIC_BUILD   = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nostubs"]\r
+!message *** Not using stubs\r
+USE_STUBS      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+!message *** Doing nomsvcrt\r
+MSVCRT         = 0\r
+!else\r
+!if [nmakehlp -f $(OPTS) "msvcrt"]\r
+!message *** Doing msvcrt\r
+!else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
+MSVCRT         = 0\r
+!endif\r
+!endif\r
+!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+\r
+!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
+!message *** Doing staticpkg\r
+TCL_USE_STATIC_PACKAGES        = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nothreads"]\r
+!message *** Compile explicitly for non-threaded tcl\r
+TCL_THREADS = 0\r
+USE_THREAD_ALLOC= 0\r
+!endif\r
+\r
+!if $(TCL_MAJOR_VERSION) == 8\r
+!if [nmakehlp -f $(OPTS) "time64bit"]\r
+!message *** Force 64-bit time_t\r
+_USE_64BIT_TIME_T = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
+# Yes, it's weird that the "symbols" option controls DEBUG and\r
+# the "pdbs" option controls SYMBOLS. That's historical.\r
+!if [nmakehlp -f $(OPTS) "symbols"]\r
+!message *** Doing symbols\r
+DEBUG          = 1\r
+!else\r
+DEBUG          = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pdbs"]\r
+!message *** Doing pdbs\r
+SYMBOLS                = 1\r
+!else\r
+SYMBOLS                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "profile"]\r
+!message *** Doing profile\r
+PROFILE                = 1\r
+!else\r
+PROFILE                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pgi"]\r
+!message *** Doing profile guided optimization instrumentation\r
+PGO            = 1\r
+!elseif [nmakehlp -f $(OPTS) "pgo"]\r
+!message *** Doing profile guided optimization\r
+PGO            = 2\r
+!else\r
+PGO            = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "loimpact"]\r
+!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
+!endif\r
+\r
+# TBD - should get rid of this option\r
+!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
+!message *** Doing thrdalloc\r
+USE_THREAD_ALLOC = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "tclalloc"]\r
+USE_THREAD_ALLOC = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "unchecked"]\r
+!message *** Doing unchecked\r
+UNCHECKED = 1\r
+!else\r
+UNCHECKED = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
+CONFIG_CHECK = 1\r
+!else\r
+CONFIG_CHECK = 0\r
+!endif\r
+\r
+!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
+\r
+# Set linker flags based on above\r
+\r
+!if $(PGO) > 1\r
+!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!elseif $(PGO) > 0\r
+!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+################################################################\r
+# 8. Parse the STATS macro to configure code instrumentation\r
+# The following macros are set by this section:\r
+# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
+#                 0 -> disables\r
+# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
+#                     0 -> disables\r
+\r
+# Default both are off\r
+TCL_MEM_DEBUG      = 0\r
+TCL_COMPILE_DEBUG   = 0\r
+\r
+!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
+\r
+!if [nmakehlp -f $(STATS) "memdbg"]\r
+!message *** Doing memdbg\r
+TCL_MEM_DEBUG      = 1\r
+!else\r
+TCL_MEM_DEBUG      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(STATS) "compdbg"]\r
+!message *** Doing compdbg\r
+TCL_COMPILE_DEBUG   = 1\r
+!else\r
+TCL_COMPILE_DEBUG   = 0\r
+!endif\r
+\r
+!endif\r
+\r
+####################################################################\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
+# The following macros are set by this section:\r
+# WARNINGS - compiler switches that control the warnings level\r
+# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
+#                     0 -> enable deprecated functions\r
+\r
+# Defaults - Permit deprecated functions and warning level 3\r
+TCL_NO_DEPRECATED          = 0\r
+WARNINGS                   = -W3\r
+\r
+!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
+\r
+!if [nmakehlp -f $(CHECKS) "nodep"]\r
+!message *** Doing nodep check\r
+TCL_NO_DEPRECATED          = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
+!message *** Doing full warnings check\r
+WARNINGS                   = -W4\r
+!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
+!endif\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
+!message *** Doing 64bit portability warnings\r
+WARNINGS                   = $(WARNINGS) -Wp64\r
+!endif\r
+\r
+!endif\r
+\r
+\r
+################################################################\r
+# 10. Construct output directory and file paths\r
+# Figure-out how to name our intermediate and output directories.\r
+# In order to avoid inadvertent mixing of object files built using\r
+# different compilers, build configurations etc.,\r
+#\r
+# Naming convention (suffixes):\r
+#   t = full thread support. (Not used for Tcl >= 8.7)\r
+#   s = static library (as opposed to an import library)\r
+#   g = linked to the debug enabled C run-time.\r
+#   x = special static build when it links to the dynamic C run-time.\r
+#\r
+# The following macros are set in this section:\r
+# SUFX - the suffix to use for binaries based on above naming convention\r
+# BUILDDIRTOP - the toplevel default output directory\r
+#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
+# TMP_DIR - directory where object files are created\r
+# OUT_DIR - directory where output executables are created\r
+# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
+# parent makefile (or command line). The default values are\r
+# based on BUILDDIRTOP.\r
+# STUBPREFIX - name of the stubs library for this project\r
+# PRJIMPLIB - output path of the generated project import library\r
+# PRJLIBNAME - name of generated project library\r
+# PRJLIB     - output path of generated project library\r
+# PRJSTUBLIBNAME - name of the generated project stubs library\r
+# PRJSTUBLIB - output path of the generated project stubs library\r
+# RESFILE - output resource file (only if not static build)\r
+\r
+SUFX       = tsgx\r
+\r
+!if $(DEBUG)\r
+BUILDDIRTOP = Debug\r
+!else\r
+BUILDDIRTOP = Release\r
+!endif\r
+\r
+!if "$(MACHINE)" != "IX86"\r
+BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
+!endif\r
+!if $(VCVER) > 6\r
+BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
+!endif\r
+\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
+SUFX       = $(SUFX:g=)\r
+!endif\r
+\r
+TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
+\r
+!if !$(STATIC_BUILD)\r
+TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
+SUFX       = $(SUFX:s=)\r
+EXT        = dll\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!else\r
+TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
+EXT        = lib\r
+!if !$(MSVCRT)\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!endif\r
+!endif\r
+\r
+!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
+TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
+SUFX       = $(SUFX:t=)\r
+!endif\r
+\r
+!ifndef TMP_DIR\r
+TMP_DIR            = $(TMP_DIRFULL)\r
+!ifndef OUT_DIR\r
+OUT_DIR            = .\$(BUILDDIRTOP)\r
+!endif\r
+!else\r
+!ifndef OUT_DIR\r
+OUT_DIR            = $(TMP_DIR)\r
+!endif\r
+!endif\r
+\r
+# Relative paths -> absolute\r
+!if [echo OUT_DIR = \> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
+!endif\r
+!if [echo TMP_DIR = \>> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
+!endif\r
+!include nmakehlp.out\r
+\r
+# The name of the stubs library for the project being built\r
+STUBPREFIX      = $(PROJECT)stub\r
+\r
+#\r
+# Set up paths to various Tcl executables and libraries needed by extensions\r
+#\r
+\r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
+TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
+TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
+\r
+TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
+TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+\r
+!else # !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+\r
+# When building extensions, we need to locate tclsh. Depending on version\r
+# of Tcl we are building against, this may or may not have a "t" suffix.\r
+# Try various possibilities in turn.\r
+TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist("$(TCLSH)")\r
+TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+\r
+TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\lib\r
+TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
+TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
+\r
+!else # Building against Tcl sources\r
+\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist($(TCLSH))\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\library\r
+TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = $(_TCLDIR)\tools\r
+TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
+\r
+!endif # TCLINSTALL\r
+\r
+tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
+\r
+!endif # $(DOING_TCL)\r
+\r
+# We need a tclsh that will run on the host machine as part of the build.\r
+# IX86 runs on all architectures.\r
+!ifndef TCLSH_NATIVE\r
+!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
+TCLSH_NATIVE   = $(TCLSH)\r
+!else\r
+!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
+!endif\r
+!endif\r
+\r
+# Do the same for Tk and Tk extensions that require the Tk libraries\r
+!if $(DOING_TK) || $(NEED_TK)\r
+WISHNAMEPREFIX = wish\r
+WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
+TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
+TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
+\r
+!if $(DOING_TK)\r
+WISH           = $(OUT_DIR)\$(WISHNAME)\r
+TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
+TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
+\r
+!else # effectively NEED_TK\r
+\r
+!if $(TKINSTALL) # Building against installed Tk\r
+WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
+!else # Building against Tk sources\r
+\r
+WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
+!endif # TKINSTALL\r
+\r
+tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
+\r
+!endif # $(DOING_TK)\r
+!endif # $(DOING_TK) || $(NEED_TK)\r
+\r
+# Various output paths\r
+PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
+\r
+PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
+\r
+# If extension parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
+!ifdef RCFILE\r
+RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
+!else\r
+RESFILE = $(TMP_DIR)\$(PROJECT).res\r
+!endif\r
+!endif\r
+\r
+###################################################################\r
+# 11. Construct the paths for the installation directories\r
+# The following macros get defined in this section:\r
+# LIB_INSTALL_DIR - where libraries should be installed\r
+# BIN_INSTALL_DIR - where the executables should be installed\r
+# DOC_INSTALL_DIR - where documentation should be installed\r
+# SCRIPT_INSTALL_DIR - where scripts should be installed\r
+# INCLUDE_INSTALL_DIR - where C include files should be installed\r
+# DEMO_INSTALL_DIR - where demos should be installed\r
+# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
+\r
+!if $(DOING_TCL) || $(DOING_TK)\r
+LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
+BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
+DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
+!if $(DOING_TCL)\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
+!else # DOING_TK\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!endif\r
+DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
+\r
+!else # extension other than Tk\r
+\r
+PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
+!if $(MULTIPLATFORM_INSTALL)\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+!else\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+!endif\r
+DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
+DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
+\r
+!endif\r
+\r
+###################################################################\r
+# 12. Set up actual options to be passed to the compiler and linker\r
+# Now we have all the information we need, set up the actual flags and\r
+# options that we will pass to the compiler and linker. The main\r
+# makefile should use these in combination with whatever other flags\r
+# and switches are specific to it.\r
+# The following macros are defined, names are for historical compatibility:\r
+# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
+# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
+# crt - Compiler switch that selects the appropriate C runtime\r
+# cdebug - Compiler switches related to debug AND optimizations\r
+# cwarn - Compiler switches that set warning levels\r
+# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
+# ldebug - Linker switches controlling debug information and optimization\r
+# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
+# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
+# conlflags - complete linker switches for console program (subsumes lflags)\r
+# guilflags - complete linker switches for GUI program (subsumes lflags)\r
+# baselibs - minimum Windows libraries required. Parent makefile can\r
+#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
+\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
+\r
+!if $(TCL_MEM_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
+!endif\r
+!if $(TCL_COMPILE_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_COMPILE_DEBUG /DTCL_COMPILE_STATS\r
+!endif\r
+!if $(TCL_THREADS) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_THREADS=1\r
+!if $(USE_THREAD_ALLOC) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1\r
+!endif\r
+!endif\r
+!if $(STATIC_BUILD)\r
+OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
+!endif\r
+!if $(TCL_NO_DEPRECATED)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
+!endif\r
+\r
+!if $(USE_STUBS)\r
+# Note we do not define USE_TCL_STUBS even when building tk since some\r
+# test targets in tk do not use stubs\r
+!if !$(DOING_TCL)\r
+USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
+!if $(NEED_TK)\r
+USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
+!endif\r
+!endif\r
+!endif # USE_STUBS\r
+\r
+!if !$(DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DNDEBUG\r
+!if $(OPTIMIZING)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_OPTIMIZED\r
+!endif\r
+!endif\r
+!if $(PROFILE)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_PROFILED\r
+!endif\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
+!endif\r
+!if $(VCVERSION) < 1300\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
+!endif\r
+\r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
+!if "$(_USE_64BIT_TIME_T)" == "1"\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
+!endif\r
+\r
+# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
+COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
+\r
+# Like the TEA system only set this non empty for non-Tk extensions\r
+# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
+# so we pass both\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+PKGNAMEFLAGS = /DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
+               /DMODULE_SCOPE=extern\r
+!endif\r
+\r
+# crt picks the C run time based on selected OPTS\r
+!if $(MSVCRT)\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MDd\r
+!else\r
+crt = -MD\r
+!endif\r
+!else\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MTd\r
+!else\r
+crt = -MT\r
+!endif\r
+!endif\r
+\r
+# cdebug includes compiler options for debugging as well as optimization.\r
+!if $(DEBUG)\r
+\r
+# In debugging mode, optimizations need to be disabled\r
+cdebug = -Zi -Od $(DEBUGFLAGS)\r
+\r
+!else\r
+\r
+cdebug = $(OPTIMIZATIONS)\r
+!if $(SYMBOLS)\r
+cdebug = $(cdebug) -Zi\r
+!endif\r
+\r
+!endif # $(DEBUG)\r
+\r
+# cwarn includes default warning levels.\r
+cwarn = $(WARNINGS)\r
+\r
+!if "$(MACHINE)" == "AMD64"\r
+# Disable pointer<->int warnings related to cast between different sizes\r
+# There are a gadzillion of these due to use of ClientData and\r
+# clutter up compiler\r
+# output increasing chance of a real warning getting lost. So disable them.\r
+# Eventually some day, Tcl will be 64-bit clean.\r
+cwarn = $(cwarn) -wd4311 -wd4312\r
+!endif\r
+\r
+### Common compiler options that are architecture specific\r
+!if "$(MACHINE)" == "ARM"\r
+carch = /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
+!else\r
+carch =\r
+!endif\r
+\r
+!if $(DEBUG)\r
+# Turn warnings into errors\r
+cwarn = $(cwarn) -WX\r
+!endif\r
+\r
+INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WIN_DIR)" -I"$(COMPATDIR)"\r
+!endif\r
+\r
+# These flags are defined roughly in the order of the pre-reform\r
+# rules.vc/makefile.vc to help visually compare that the pre- and\r
+# post-reform build logs\r
+\r
+# cflags contains generic flags used for building practically all object files\r
+cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
+\r
+# appcflags contains $(cflags) and flags for building the application\r
+# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
+# flags used for building shared object files The two differ in the\r
+# BUILD_$(PROJECT) macro which should be defined only for the shared\r
+# library *implementation* and not for its caller interface\r
+\r
+appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
+appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
+pkgcflags = $(appcflags) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+\r
+# stubscflags contains $(cflags) plus flags used for building a stubs\r
+# library for the package.  Note: /DSTATIC_BUILD is defined in\r
+# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
+# library. However the stubs library is ALWAYS static hence included\r
+# here irrespective of the OPTS setting.\r
+#\r
+# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
+# without stating why. Tcl itself compiled stubs libs with this flag.\r
+# so we do not remove it from cflags. -GL may prevent extensions\r
+# compiled with one VC version to fail to link against stubs library\r
+# compiled with another VC version. Check for this and fix accordingly.\r
+stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl /DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
+\r
+# Link flags\r
+\r
+!if $(DEBUG)\r
+ldebug = -debug -debugtype:cv\r
+!else\r
+ldebug = -release -opt:ref -opt:icf,3\r
+!if $(SYMBOLS)\r
+ldebug = $(ldebug) -debug -debugtype:cv\r
+!endif\r
+!endif\r
+\r
+# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
+!if $(PROFILE)\r
+ldebug= $(ldebug) -profile\r
+!endif\r
+\r
+### Declarations common to all linker versions\r
+lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+lflags = $(lflags) -nodefaultlib:libucrt.lib\r
+!endif\r
+\r
+dlllflags = $(lflags) -dll\r
+conlflags = $(lflags) -subsystem:console\r
+guilflags = $(lflags) -subsystem:windows\r
+\r
+# Libraries that are required for every image.\r
+# Extensions should define any additional libraries with $(PRJ_LIBS)\r
+winlibs   = kernel32.lib advapi32.lib\r
+\r
+!if $(NEED_TK)\r
+winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
+!endif\r
+\r
+# Avoid 'unresolved external symbol __security_cookie' errors.\r
+# c.f. http://support.microsoft.com/?id=894573\r
+!if "$(MACHINE)" == "AMD64"\r
+!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
+winlibs   = $(winlibs) bufferoverflowU.lib\r
+!endif\r
+!endif\r
+\r
+baselibs = $(winlibs) $(PRJ_LIBS)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+baselibs   = $(baselibs) ucrt.lib\r
+!endif\r
+\r
+################################################################\r
+# 13. Define standard commands, common make targets and implicit rules\r
+\r
+CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
+CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
+CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
+\r
+LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
+DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+\r
+CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
+           $(TCL_INCLUDES) \\r
+           /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
+           /DDOTVERSION=\"$(DOTVERSION)\" \\r
+           /DVERSION=\"$(VERSION)\" \\r
+           /DSUFX=\"$(SUFX)\" \\r
+           /DPROJECT=\"$(PROJECT)\" \\r
+           /DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
+\r
+!ifndef DEFAULT_BUILD_TARGET\r
+DEFAULT_BUILD_TARGET = $(PROJECT)\r
+!endif\r
+\r
+default-target: $(DEFAULT_BUILD_TARGET)\r
+\r
+!if $(MULTIPLATFORM_INSTALL)\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!else\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!endif\r
+\r
+default-pkgindex-tea:\r
+       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
+@PACKAGE_VERSION@    $(DOTVERSION)\r
+@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
+@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
+@PKG_LIB_FILE@       $(PRJLIBNAME)\r
+<<\r
+\r
+default-install: default-install-binaries default-install-libraries\r
+!if $(SYMBOLS)\r
+default-install: default-install-pdbs\r
+!endif\r
+\r
+# Again to deal with historical brokenness, there is some confusion\r
+# in terminlogy. For extensions, the "install-binaries" was used to\r
+# locate target directory for *binary shared libraries* and thus\r
+# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
+# for executables (exes). On the other hand the "install-libraries"\r
+# target is for *scripts* and should have been called "install-scripts".\r
+default-install-binaries: $(PRJLIB)\r
+       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
+\r
+# Alias for default-install-scripts\r
+default-install-libraries: default-install-scripts\r
+\r
+default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
+       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
+       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
+       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
+       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
+\r
+default-install-stubs:\r
+       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
+       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
+       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
+\r
+default-install-pdbs:\r
+       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
+\r
+# "emacs font-lock highlighting fix\r
+\r
+default-install-docs-html:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-docs-n:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-demos:\r
+       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
+       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
+       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
+\r
+default-clean:\r
+       @echo Cleaning $(TMP_DIR)\* ...\r
+       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
+       @echo Cleaning $(WIN_DIR)\nmakehlp.obj, nmakehlp.exe ...\r
+       @if exist $(WIN_DIR)\nmakehlp.obj del $(WIN_DIR)\nmakehlp.obj\r
+       @if exist $(WIN_DIR)\nmakehlp.exe del $(WIN_DIR)\nmakehlp.exe\r
+       @if exist $(WIN_DIR)\nmakehlp.out del $(WIN_DIR)\nmakehlp.out\r
+       @echo Cleaning $(WIN_DIR)\nmhlp-out.txt ...\r
+       @if exist $(WIN_DIR)\nmhlp-out.txt del $(WIN_DIR)\nmhlp-out.txt\r
+       @echo Cleaning $(WIN_DIR)\_junk.pch ...\r
+       @if exist $(WIN_DIR)\_junk.pch del $(WIN_DIR)\_junk.pch\r
+       @echo Cleaning $(WIN_DIR)\vercl.x, vercl.i ...\r
+       @if exist $(WIN_DIR)\vercl.x del $(WIN_DIR)\vercl.x\r
+       @if exist $(WIN_DIR)\vercl.i del $(WIN_DIR)\vercl.i\r
+       @echo Cleaning $(WIN_DIR)\versions.vc, version.vc ...\r
+       @if exist $(WIN_DIR)\versions.vc del $(WIN_DIR)\versions.vc\r
+       @if exist $(WIN_DIR)\version.vc del $(WIN_DIR)\version.vc\r
+\r
+default-hose: default-clean\r
+       @echo Hosing $(OUT_DIR)\* ...\r
+       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
+\r
+# Only for backward compatibility\r
+default-distclean: default-hose\r
+\r
+default-setup:\r
+       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
+       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
+\r
+!if "$(TESTPAT)" != ""\r
+TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
+!endif\r
+\r
+default-test: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
+\r
+default-shell: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       $(DEBUGGER) $(TCLSH)\r
+\r
+# Generation of Windows version resource\r
+!ifdef RCFILE\r
+\r
+# Note: don't use $** in below rule because there may be other dependencies\r
+# and only the "main" rc must be passed to the resource compiler\r
+$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
+       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
+\r
+!else\r
+\r
+# If parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
+\r
+$(TMP_DIR)\$(PROJECT).rc:\r
+       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
+#include <winver.h>\r
+\r
+VS_VERSION_INFO VERSIONINFO\r
+ FILEVERSION   COMMAVERSION\r
+ PRODUCTVERSION        COMMAVERSION\r
+ FILEFLAGSMASK 0x3fL\r
+#ifdef DEBUG\r
+ FILEFLAGS     VS_FF_DEBUG\r
+#else\r
+ FILEFLAGS     0x0L\r
+#endif\r
+ FILEOS                VOS_NT_WINDOWS32\r
+ FILETYPE      VFT_DLL\r
+ FILESUBTYPE   0x0L\r
+BEGIN\r
+    BLOCK "StringFileInfo"\r
+    BEGIN\r
+        BLOCK "040904b0"\r
+        BEGIN\r
+            VALUE "FileDescription",  "Tcl extension " PROJECT\r
+            VALUE "OriginalFilename", PRJLIBNAME\r
+            VALUE "FileVersion",      DOTVERSION\r
+            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
+            VALUE "ProductVersion",   DOTVERSION\r
+        END\r
+    END\r
+    BLOCK "VarFileInfo"\r
+    BEGIN\r
+        VALUE "Translation", 0x409, 1200\r
+    END\r
+END\r
+\r
+<<\r
+\r
+!endif # ifdef RCFILE\r
+\r
+!ifndef DISABLE_IMPLICIT_RULES\r
+DISABLE_IMPLICIT_RULES = 0\r
+!endif\r
+\r
+!if !$(DISABLE_IMPLICIT_RULES)\r
+# Implicit rule definitions - only for building library objects. For stubs and\r
+# main application, the makefile should define explicit rules.\r
+\r
+{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(WIN_DIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(WIN_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+.SUFFIXES:\r
+.SUFFIXES:.c .rc\r
+\r
+!endif\r
+\r
+################################################################\r
+# 14. Sanity check selected options against Tcl build options\r
+# When building an extension, certain configuration options should\r
+# match the ones used when Tcl was built. Here we check and\r
+# warn on a mismatch.\r
+!if !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
+!endif\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
+!endif\r
+!endif # TCLINSTALL\r
+\r
+!if $(CONFIG_CHECK)\r
+!ifdef TCLNMAKECONFIG\r
+!include $(TCLNMAKECONFIG)\r
+\r
+!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
+!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
+!endif\r
+!if $(TCL_VERSION) < 87 && defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
+!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
+!endif\r
+!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
+!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
+!endif\r
+!endif\r
+\r
+!endif # TCLNMAKECONFIG\r
+\r
+!endif # !$(DOING_TCL)\r
+\r
+\r
+#----------------------------------------------------------\r
+# Display stats being used.\r
+#----------------------------------------------------------\r
+\r
+!if !$(DOING_TCL)\r
+!message *** Building against Tcl at '$(_TCLDIR)'\r
+!endif\r
+!if !$(DOING_TK) && $(NEED_TK)\r
+!message *** Building against Tk at '$(_TKDIR)'\r
+!endif\r
+!message *** Intermediate directory will be '$(TMP_DIR)'\r
+!message *** Output directory will be '$(OUT_DIR)'\r
+!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
+!message *** Suffix for binaries will be '$(SUFX)'\r
+!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
+\r
+!endif # ifdef _RULES_VC\r
diff --git a/pkgs/tdbcpostgres1.1.2/win/targets.vc b/pkgs/tdbcpostgres1.1.2/win/targets.vc
new file mode 100644 (file)
index 0000000..077e8f7
--- /dev/null
@@ -0,0 +1,98 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# targets.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file defines some standard targets for the convenience of extensions\r
+# and can be optionally included by the extension makefile.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
+\r
+$(PROJECT): setup pkgindex $(PRJLIB)\r
+\r
+!ifdef PRJ_STUBOBJS\r
+$(PROJECT): $(PRJSTUBLIB)\r
+$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
+       $(LIBCMD) $**\r
+\r
+$(PRJ_STUBOBJS):\r
+       $(CCSTUBSCMD) %s\r
+!endif # PRJ_STUBOBJS\r
+\r
+!ifdef PRJ_MANIFEST\r
+$(PROJECT): $(PRJLIB).manifest\r
+$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
+       @nmakehlp -s << $** >$@\r
+@MACHINE@        $(MACHINE:IX86=X86)\r
+<<\r
+!endif\r
+\r
+!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
+$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
+!if $(STATIC_BUILD)\r
+       $(LIBCMD) $**\r
+!else\r
+       $(DLLCMD) $**\r
+       $(_VC_MANIFEST_EMBED_DLL)\r
+!endif\r
+       -@del $*.exp\r
+!endif\r
+\r
+!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
+$(PRJ_OBJS): $(PRJ_HEADERS)\r
+!endif\r
+\r
+# If parent makefile has defined stub objects, add their installation\r
+# to the default install\r
+!if "$(PRJ_STUBOBJS)" != ""\r
+default-install: default-install-stubs\r
+!endif\r
+\r
+# Unlike the other default targets, these cannot be in rules.vc because\r
+# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
+# that the parent makefile will not define until after including rules-ext.vc\r
+!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
+default-install: default-install-headers\r
+default-install-headers:\r
+       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
+       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
+!endif\r
+\r
+!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
+DISABLE_STANDARD_TARGETS = 0\r
+!endif\r
+\r
+!if "$(DISABLE_TARGET_setup)" == ""\r
+DISABLE_TARGET_setup = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_install)" == ""\r
+DISABLE_TARGET_install = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_clean)" == ""\r
+DISABLE_TARGET_clean = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_test)" == ""\r
+DISABLE_TARGET_test = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_shell)" == ""\r
+DISABLE_TARGET_shell = 0\r
+!endif\r
+\r
+!if !$(DISABLE_STANDARD_TARGETS)\r
+!if !$(DISABLE_TARGET_setup)\r
+setup: default-setup\r
+!endif\r
+!if !$(DISABLE_TARGET_install)\r
+install: default-install\r
+!endif\r
+!if !$(DISABLE_TARGET_clean)\r
+clean: default-clean\r
+realclean: hose\r
+hose: default-hose\r
+distclean: realclean default-distclean\r
+!endif\r
+!if !$(DISABLE_TARGET_test)\r
+test: default-test\r
+!endif\r
+!if !$(DISABLE_TARGET_shell)\r
+shell: default-shell\r
+!endif\r
+!endif # DISABLE_STANDARD_TARGETS\r
diff --git a/pkgs/tdbcsqlite3-1.1.1/tclconfig/README.txt b/pkgs/tdbcsqlite3-1.1.1/tclconfig/README.txt
deleted file mode 100644 (file)
index 59b5a3e..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-These files comprise the basic building blocks for a Tcl Extension
-Architecture (TEA) extension.  For more information on TEA see:
-
-       http://www.tcl.tk/doc/tea/
-
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
-
-       http://tcl.sourceforge.net/
-
-This package is a freely available open source package.  You can do
-virtually anything you like with it, such as modifying it, redistributing
-it, and selling it either in whole or in part.
-
-CONTENTS
-========
-The following is a short description of the files you will find in
-the sample extension.
-
-README.txt     This file
-
-install-sh     Program used for copying binaries and script files
-               to their install locations.
-
-tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
-               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/tdbcsqlite3-1.1.1/tclconfig/install-sh b/pkgs/tdbcsqlite3-1.1.1/tclconfig/install-sh
deleted file mode 100644 (file)
index 7c34c3f..0000000
+++ /dev/null
@@ -1,528 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2011-04-20.01; # UTC
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# 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.
-
-nl='
-'
-IFS=" ""       $nl"
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
-
-# Put in absolute file names if you don't have them in your path;
-# or use environment vars.
-
-chgrpprog=${CHGRPPROG-chgrp}
-chmodprog=${CHMODPROG-chmod}
-chownprog=${CHOWNPROG-chown}
-cmpprog=${CMPPROG-cmp}
-cpprog=${CPPROG-cp}
-mkdirprog=${MKDIRPROG-mkdir}
-mvprog=${MVPROG-mv}
-rmprog=${RMPROG-rm}
-stripprog=${STRIPPROG-strip}
-
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
-posix_mkdir=
-
-# Desired mode of installed file.
-mode=0755
-
-chgrpcmd=
-chmodcmd=$chmodprog
-chowncmd=
-mvcmd=$mvprog
-rmcmd="$rmprog -f"
-stripcmd=
-
-src=
-dst=
-dir_arg=
-dst_arg=
-
-copy_on_change=false
-no_target_directory=
-
-usage="\
-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
-   or: $0 [OPTION]... SRCFILES... DIRECTORY
-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
-   or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
-     --help     display this help and exit.
-     --version  display version info and exit.
-
-  -c            (ignored)
-  -C            install only if different (preserve the last data modification time)
-  -d            create directories instead of installing files.
-  -g GROUP      $chgrpprog installed files to GROUP.
-  -m MODE       $chmodprog installed files to MODE.
-  -o USER       $chownprog installed files to USER.
-  -s            $stripprog installed files.
-  -S            $stripprog installed files.
-  -t DIRECTORY  install into DIRECTORY.
-  -T            report an error if DSTFILE is a directory.
-
-Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
-  RMPROG STRIPPROG
-"
-
-while test $# -ne 0; do
-  case $1 in
-    -c) ;;
-
-    -C) copy_on_change=true;;
-
-    -d) dir_arg=true;;
-
-    -g) chgrpcmd="$chgrpprog $2"
-       shift;;
-
-    --help) echo "$usage"; exit $?;;
-
-    -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
-
-    -o) chowncmd="$chownprog $2"
-       shift;;
-
-    -s) stripcmd=$stripprog;;
-
-    -S) stripcmd="$stripprog $2"
-       shift;;
-
-    -t) dst_arg=$2
-       shift;;
-
-    -T) no_target_directory=true;;
-
-    --version) echo "$0 $scriptversion"; exit $?;;
-
-    --)        shift
-       break;;
-
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
-
-    *)  break;;
-  esac
-  shift
-done
-
-if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
-  # When -d is used, all remaining arguments are directories to create.
-  # When -t is used, the destination is already specified.
-  # Otherwise, the last argument is the destination.  Remove it from $@.
-  for arg
-  do
-    if test -n "$dst_arg"; then
-      # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dst_arg"
-      shift # fnord
-    fi
-    shift # arg
-    dst_arg=$arg
-  done
-fi
-
-if test $# -eq 0; then
-  if test -z "$dir_arg"; then
-    echo "$0: no input file specified." >&2
-    exit 1
-  fi
-  # It's OK to call `install-sh -d' without argument.
-  # This can happen when creating conditional directories.
-  exit 0
-fi
-
-if test -z "$dir_arg"; then
-  do_exit='(exit $ret); exit $ret'
-  trap "ret=129; $do_exit" 1
-  trap "ret=130; $do_exit" 2
-  trap "ret=141; $do_exit" 13
-  trap "ret=143; $do_exit" 15
-
-  # Set umask so as not to create temps with too-generous modes.
-  # However, 'strip' requires both read and write access to temps.
-  case $mode in
-    # Optimize common cases.
-    *644) cp_umask=133;;
-    *755) cp_umask=22;;
-
-    *[0-7])
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw='% 200'
-      fi
-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
-    *)
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw=,u+rw
-      fi
-      cp_umask=$mode$u_plus_rw;;
-  esac
-fi
-
-for src
-do
-  # Protect names starting with `-'.
-  case $src in
-    -*) src=./$src;;
-  esac
-
-  if test -n "$dir_arg"; then
-    dst=$src
-    dstdir=$dst
-    test -d "$dstdir"
-    dstdir_status=$?
-  else
-
-    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
-    # might cause directories to be created, which would be especially bad
-    # if $src (and thus $dsttmp) contains '*'.
-    if test ! -f "$src" && test ! -d "$src"; then
-      echo "$0: $src does not exist." >&2
-      exit 1
-    fi
-
-    if test -z "$dst_arg"; then
-      echo "$0: no destination specified." >&2
-      exit 1
-    fi
-
-    dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
-
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
-    if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
-      fi
-      dstdir=$dst
-      dst=$dstdir/`basename "$src"`
-      dstdir_status=0
-    else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
-      test -d "$dstdir"
-      dstdir_status=$?
-    fi
-  fi
-
-  obsolete_mkdir_used=false
-
-  if test $dstdir_status != 0; then
-    case $posix_mkdir in
-      '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
-       else
-         mkdir_mode=
-       fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
-    esac
-
-    if
-      $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
-      )
-    then :
-    else
-
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
-      # or it failed possibly due to a race condition.  Create the
-      # directory the slow way, step by step, checking for races as we go.
-
-      case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
-      esac
-
-      eval "$initialize_posix_glob"
-
-      oIFS=$IFS
-      IFS=/
-      $posix_glob set -f
-      set fnord $dstdir
-      shift
-      $posix_glob set +f
-      IFS=$oIFS
-
-      prefixes=
-
-      for d
-      do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
-      done
-
-      if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
-      fi
-    fi
-  fi
-
-  if test -n "$dir_arg"; then
-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
-  else
-
-    # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
-
-    # Trap to clean up those temp files at exit.
-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
-
-    # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
-
-    # 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 $cpprog $src $dsttmp" command.
-    #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
-
-    # If -C, don't bother to copy if it wouldn't change the file.
-    if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
-       set X $old && old=:$2:$4:$5:$6 &&
-       set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
-       test "$old" = "$new" &&
-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
-    then
-      rm -f "$dsttmp"
-    else
-      # Rename the file to the real destination.
-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
-
-      # The rename failed, perhaps because mv can't rename something else
-      # to itself, or perhaps because mv is so ancient that it does not
-      # support -f.
-      {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
-      }
-    fi || exit 1
-
-    trap '' 0
-  fi
-done
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/pkgs/tdbcsqlite3-1.1.1/tclconfig/tcl.m4 b/pkgs/tdbcsqlite3-1.1.1/tclconfig/tcl.m4
deleted file mode 100644 (file)
index 7d901f9..0000000
+++ /dev/null
@@ -1,4033 +0,0 @@
-# tcl.m4 --
-#
-#      This file provides a set of autoconf macros to help TEA-enable
-#      a Tcl extension.
-#
-# Copyright (c) 1999-2000 Ajuba Solutions.
-# Copyright (c) 2002-2005 ActiveState Corporation.
-#
-# See the file "license.terms" for information on usage and redistribution
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-
-AC_PREREQ(2.57)
-
-# Possible values for key variables defined:
-#
-# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
-# TEA_PLATFORM        - windows unix
-# TEA_TK_EXTENSION    - True if this is a Tk extension
-#
-
-#------------------------------------------------------------------------
-# TEA_PATH_TCLCONFIG --
-#
-#      Locate the tclConfig.sh file and perform a sanity check on
-#      the Tcl compile flags
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tcl=...
-#
-#      Defines the following vars:
-#              TCL_BIN_DIR     Full path to the directory containing
-#                              the tclConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TCLCONFIG], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-    #
-    # Ok, lets find the tcl configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tcl
-    #
-
-    if test x"${no_tcl}" = x ; then
-       # we reset no_tcl in case something fails here
-       no_tcl=true
-       AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
-               [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
-       AC_MSG_CHECKING([for Tcl configuration])
-       AC_CACHE_VAL(ac_cv_c_tclconfig,[
-
-           # First check to see if --with-tcl was specified.
-           if test x"${with_tclconfig}" != x ; then
-               case "${with_tclconfig}" in
-                   */tclConfig.sh )
-                       if test -f "${with_tclconfig}"; then
-                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
-                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tclconfig}/tclConfig.sh" ; then
-                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tcl installation
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ../tcl \
-                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tcl \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tcl \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tcl \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tclconfig}" = x ; then
-           TCL_BIN_DIR="# no Tcl configs found"
-           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
-       else
-           no_tcl=
-           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
-           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_TKCONFIG --
-#
-#      Locate the tkConfig.sh file
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tk=...
-#
-#      Defines the following vars:
-#              TK_BIN_DIR      Full path to the directory containing
-#                              the tkConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TKCONFIG], [
-    #
-    # Ok, lets find the tk configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tk
-    #
-
-    if test x"${no_tk}" = x ; then
-       # we reset no_tk in case something fails here
-       no_tk=true
-       AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
-               [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
-       AC_MSG_CHECKING([for Tk configuration])
-       AC_CACHE_VAL(ac_cv_c_tkconfig,[
-
-           # First check to see if --with-tkconfig was specified.
-           if test x"${with_tkconfig}" != x ; then
-               case "${with_tkconfig}" in
-                   */tkConfig.sh )
-                       if test -f "${with_tkconfig}"; then
-                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
-                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tkconfig}/tkConfig.sh" ; then
-                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tk library
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ../tk \
-                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tk \
-                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tk \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tk \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tkconfig}" = x ; then
-           TK_BIN_DIR="# no Tk configs found"
-           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
-       else
-           no_tk=
-           TK_BIN_DIR="${ac_cv_c_tkconfig}"
-           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TCLCONFIG --
-#
-#      Load the tclConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TCL_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_BIN_DIR
-#              TCL_SRC_DIR
-#              TCL_LIB_FILE
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TCLCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
-
-    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TCL_BIN_DIR}/tclConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
-    # If the TCL_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TCL_LIB_SPEC will be set to the value
-    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
-    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
-        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
-        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tcl was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tcl.framework installed in an arbitrary location.
-       case ${TCL_DEFS} in
-           *TCL_FRAMEWORK*)
-               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
-                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
-                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
-                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
-                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
-                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
-    AC_SUBST(TCL_VERSION)
-    AC_SUBST(TCL_PATCH_LEVEL)
-    AC_SUBST(TCL_BIN_DIR)
-    AC_SUBST(TCL_SRC_DIR)
-
-    AC_SUBST(TCL_LIB_FILE)
-    AC_SUBST(TCL_LIB_FLAG)
-    AC_SUBST(TCL_LIB_SPEC)
-
-    AC_SUBST(TCL_STUB_LIB_FILE)
-    AC_SUBST(TCL_STUB_LIB_FLAG)
-    AC_SUBST(TCL_STUB_LIB_SPEC)
-
-    AC_MSG_CHECKING([platform])
-    hold_cc=$CC; CC="$TCL_CC"
-    AC_TRY_COMPILE(,[
-           #ifdef _WIN32
-               #error win32
-           #endif
-       ], [
-           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
-           TEA_PLATFORM="${TEA_PLATFORM-unix}"
-           CYGPATH=echo
-       ], [
-           TEA_PLATFORM="windows"
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
-    )
-    CC=$hold_cc
-    AC_MSG_RESULT($TEA_PLATFORM)
-
-    # The BUILD_$pkg is to define the correct extern storage class
-    # handling when making this package
-    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
-           [Building extension source?])
-    # Do this here as we have fully defined TEA_PLATFORM now
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       EXEEXT=".exe"
-       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
-    fi
-
-    # TEA specific:
-    AC_SUBST(CLEANFILES)
-    AC_SUBST(TCL_LIBS)
-    AC_SUBST(TCL_DEFS)
-    AC_SUBST(TCL_EXTRA_CFLAGS)
-    AC_SUBST(TCL_LD_FLAGS)
-    AC_SUBST(TCL_SHLIB_LD_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TKCONFIG --
-#
-#      Load the tkConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TK_BIN_DIR
-#
-# Results:
-#
-#      Sets the following vars that should be in tkConfig.sh:
-#              TK_BIN_DIR
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TKCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
-
-    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TK_BIN_DIR}/tkConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
-    # If the TK_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TK_LIB_SPEC will be set to the value
-    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
-    # instead of TK_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
-        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
-        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tk was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tk.framework installed in an arbitrary location.
-       case ${TK_DEFS} in
-           *TK_FRAMEWORK*)
-               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
-                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
-                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
-                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
-                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
-                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
-    # TEA specific: Ensure windowingsystem is defined
-    if test "${TEA_PLATFORM}" = "unix" ; then
-       case ${TK_DEFS} in
-           *MAC_OSX_TK*)
-               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
-               TEA_WINDOWINGSYSTEM="aqua"
-               ;;
-           *)
-               TEA_WINDOWINGSYSTEM="x11"
-               ;;
-       esac
-    elif test "${TEA_PLATFORM}" = "windows" ; then
-       TEA_WINDOWINGSYSTEM="win32"
-    fi
-
-    AC_SUBST(TK_VERSION)
-    AC_SUBST(TK_BIN_DIR)
-    AC_SUBST(TK_SRC_DIR)
-
-    AC_SUBST(TK_LIB_FILE)
-    AC_SUBST(TK_LIB_FLAG)
-    AC_SUBST(TK_LIB_SPEC)
-
-    AC_SUBST(TK_STUB_LIB_FILE)
-    AC_SUBST(TK_STUB_LIB_FLAG)
-    AC_SUBST(TK_STUB_LIB_SPEC)
-
-    # TEA specific:
-    AC_SUBST(TK_LIBS)
-    AC_SUBST(TK_XINCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_TCLSH
-#      Determine the fully qualified path name of the tclsh executable
-#      in the Tcl build directory or the tclsh installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the tclsh executable even if tclsh has not yet been
-#      built in the build directory. The tclsh found is always
-#      associated with a tclConfig.sh file. This tclsh should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCLSH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_TCLSH], [
-    AC_MSG_CHECKING([for tclsh])
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        # tclConfig.sh is in Tcl build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
-          fi
-        else
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
-        fi
-    else
-        # tclConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-        else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
-        fi
-        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${TCLSH_PROG}" ; then
-                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
-    fi
-    AC_MSG_RESULT([${TCLSH_PROG}])
-    AC_SUBST(TCLSH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_WISH
-#      Determine the fully qualified path name of the wish executable
-#      in the Tk build directory or the wish installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the wish executable even if wish has not yet been
-#      built in the build directory. The wish found is always
-#      associated with a tkConfig.sh file. This wish should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              WISH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_WISH], [
-    AC_MSG_CHECKING([for wish])
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        # tkConfig.sh is in Tk build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
-          fi
-        else
-            WISH_PROG="${TK_BIN_DIR}/wish"
-        fi
-    else
-        # tkConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-        else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
-        fi
-        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${WISH_PROG}" ; then
-                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
-    fi
-    AC_MSG_RESULT([${WISH_PROG}])
-    AC_SUBST(WISH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SHARED --
-#
-#      Allows the building of shared libraries
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-shared=yes|no
-#              --enable-stubs=yes|no
-#
-#      Defines the following vars:
-#              STATIC_BUILD    Used for building import/export libraries
-#                              on Windows.
-#
-#      Sets the following vars:
-#              SHARED_BUILD    Value of 1 or 0
-#               STUBS_BUILD     Value if 1 or 0
-#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
-#                                AND TEA_WINDOWING_SYSTEM != ""
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ENABLE_SHARED], [
-    AC_MSG_CHECKING([how to build libraries])
-    AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
-           [build and link with shared libraries (default: on)]),
-       [shared_ok=$enableval], [shared_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       shared_ok=$enableval
-    else
-       shared_ok=yes
-    fi
-
-    AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
-           [build and link with stub libraries. Always true for shared builds (default: on)]),
-       [stubs_ok=$enableval], [stubs_ok=yes])
-
-    if test "${enable_stubs+set}" = set; then
-       enableval="$enable_stubs"
-       stubs_ok=$enableval
-    else
-       stubs_ok=yes
-    fi
-
-    # Stubs are always enabled for shared builds
-    if test "$shared_ok" = "yes" ; then
-       AC_MSG_RESULT([shared])
-       SHARED_BUILD=1
-        STUBS_BUILD=1
-    else
-       AC_MSG_RESULT([static])
-       SHARED_BUILD=0
-       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
-        if test "$stubs_ok" = "yes" ; then
-          STUBS_BUILD=1
-        else
-          STUBS_BUILD=0
-        fi
-    fi
-    if test "${STUBS_BUILD}" = "1" ; then
-      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
-      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
-      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
-        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
-      fi
-    fi
-
-    AC_SUBST(SHARED_BUILD)
-    AC_SUBST(STUBS_BUILD)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_THREADS --
-#
-#      Specify if thread support should be enabled.  If "yes" is specified
-#      as an arg (optional), threads are enabled by default, "no" means
-#      threads are disabled.  "yes" is the default.
-#
-#      TCL_THREADS is checked so that if you are compiling an extension
-#      against a threaded core, your extension must be compiled threaded
-#      as well.
-#
-#      Note that it is legal to have a thread enabled extension run in a
-#      threaded or non-threaded Tcl core, but a non-threaded extension may
-#      only run in a non-threaded Tcl core.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-threads
-#
-#      Sets the following vars:
-#              THREADS_LIBS    Thread library(s)
-#
-#      Defines the following vars:
-#              TCL_THREADS
-#              _REENTRANT
-#              _THREAD_SAFE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_THREADS], [
-    AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
-           [build with threads (default: on)]),
-       [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_threads+set}" = set; then
-       enableval="$enable_threads"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
-    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
-       TCL_THREADS=1
-
-       if test "${TEA_PLATFORM}" != "windows" ; then
-           # We are always OK on Windows, so check what this platform wants:
-
-           # USE_THREAD_ALLOC tells us to try the special thread-based
-           # allocator that significantly reduces lock contention
-           AC_DEFINE(USE_THREAD_ALLOC, 1,
-               [Do we want to use the threaded memory allocator?])
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           if test "`uname -s`" = "SunOS" ; then
-               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-                       [Do we really want to follow the standard? Yes we do!])
-           fi
-           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
-           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
-           if test "$tcl_ok" = "no"; then
-               # Check a little harder for __pthread_mutex_init in the same
-               # library, as some systems hide it there until pthread.h is
-               # defined.  We could alternatively do an AC_TRY_COMPILE with
-               # pthread.h, but that will work with libpthread really doesn't
-               # exist, like AIX 4.2.  [Bug: 4359]
-               AC_CHECK_LIB(pthread, __pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-           fi
-
-           if test "$tcl_ok" = "yes"; then
-               # The space is needed
-               THREADS_LIBS=" -lpthread"
-           else
-               AC_CHECK_LIB(pthreads, pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-               if test "$tcl_ok" = "yes"; then
-                   # The space is needed
-                   THREADS_LIBS=" -lpthreads"
-               else
-                   AC_CHECK_LIB(c, pthread_mutex_init,
-                       tcl_ok=yes, tcl_ok=no)
-                   if test "$tcl_ok" = "no"; then
-                       AC_CHECK_LIB(c_r, pthread_mutex_init,
-                           tcl_ok=yes, tcl_ok=no)
-                       if test "$tcl_ok" = "yes"; then
-                           # The space is needed
-                           THREADS_LIBS=" -pthread"
-                       else
-                           TCL_THREADS=0
-                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
-                       fi
-                   fi
-               fi
-           fi
-       fi
-    else
-       TCL_THREADS=0
-    fi
-    # Do checking message here to not mess up interleaved configure output
-    AC_MSG_CHECKING([for building with threads])
-    if test "${TCL_THREADS}" = 1; then
-       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
-       AC_MSG_RESULT([yes (default)])
-    else
-       AC_MSG_RESULT([no])
-    fi
-    # TCL_THREADS sanity checking.  See if our request for building with
-    # threads is the same as the way Tcl was built.  If not, warn the user.
-    case ${TCL_DEFS} in
-       *THREADS=1*)
-           if test "${TCL_THREADS}" = "0"; then
-               AC_MSG_WARN([
-    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
-    that IS thread-enabled.  It is recommended to use --enable-threads.])
-           fi
-           ;;
-    esac
-    AC_SUBST(TCL_THREADS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SYMBOLS --
-#
-#      Specify if debugging symbols should be used.
-#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
-#
-# Arguments:
-#      none
-#
-#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
-#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
-#      Requires the following vars to be set in the Makefile:
-#              CFLAGS_DEFAULT
-#              LDFLAGS_DEFAULT
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-symbols
-#
-#      Defines the following vars:
-#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
-#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
-#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
-#                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_SYMBOLS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_CONFIG_CFLAGS])
-    AC_MSG_CHECKING([for build with symbols])
-    AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
-           [build with debugging symbols (default: off)]),
-       [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
-    if test "$tcl_ok" = "no"; then
-       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
-       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
-       AC_MSG_RESULT([no])
-    else
-       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
-       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
-       if test "$tcl_ok" = "yes"; then
-           AC_MSG_RESULT([yes (standard debugging)])
-       fi
-    fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-    AC_SUBST(CFLAGS_DEFAULT)
-    AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
-
-    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
-       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
-    fi
-
-    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
-       if test "$tcl_ok" = "all"; then
-           AC_MSG_RESULT([enabled symbols mem debugging])
-       else
-           AC_MSG_RESULT([enabled $tcl_ok debugging])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_LANGINFO --
-#
-#      Allows use of modern nl_langinfo check for better l10n.
-#      This is only relevant for Unix.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-langinfo=yes|no (default is yes)
-#
-#      Defines the following vars:
-#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_LANGINFO], [
-    AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
-           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
-       [langinfo_ok=$enableval], [langinfo_ok=yes])
-
-    HAVE_LANGINFO=0
-    if test "$langinfo_ok" = "yes"; then
-       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
-    fi
-    AC_MSG_CHECKING([whether to use nl_langinfo])
-    if test "$langinfo_ok" = "yes"; then
-       AC_CACHE_VAL(tcl_cv_langinfo_h, [
-           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
-                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
-       AC_MSG_RESULT([$tcl_cv_langinfo_h])
-       if test $tcl_cv_langinfo_h = yes; then
-           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
-       fi
-    else
-       AC_MSG_RESULT([$langinfo_ok])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_SYSTEM
-#
-#      Determine what the system is (some things cannot be easily checked
-#      on a feature-driven basis, alas). This can usually be done via the
-#      "uname" command.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Defines the following var:
-#
-#      system -        System/platform/version identification code.
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_SYSTEM], [
-    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
-       # TEA specific:
-       if test "${TEA_PLATFORM}" = "windows" ; then
-           tcl_cv_sys_version=windows
-       else
-           tcl_cv_sys_version=`uname -s`-`uname -r`
-           if test "$?" -ne 0 ; then
-               AC_MSG_WARN([can't find uname command])
-               tcl_cv_sys_version=unknown
-           else
-               if test "`uname -s`" = "AIX" ; then
-                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
-               fi
-               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
-                   tcl_cv_sys_version=NetBSD-Debian
-               fi
-           fi
-       fi
-    ])
-    system=$tcl_cv_sys_version
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_CFLAGS
-#
-#      Try to determine the proper flags to pass to the compiler
-#      for building shared libraries and other such nonsense.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substitutes the following vars:
-#
-#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
-#       LDFLAGS -      Flags to pass to the compiler when linking object
-#                       files into an executable application binary such
-#                       as tclsh.
-#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
-#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
-#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile.
-#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
-#                       of a shared library (may request position-independent
-#                       code, among other things).
-#       SHLIB_LD -      Base command to use for combining object files
-#                       into a shared library.
-#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
-#                       creating shared libraries.  This symbol typically
-#                       goes at the end of the "ld" commands that build
-#                       shared libraries. The value of the symbol defaults to
-#                       "${LIBS}" if all of the dependent libraries should
-#                       be specified when creating a shared library.  If
-#                       dependent libraries should not be specified (as on
-#                       SunOS 4.x, where they cause the link to fail, or in
-#                       general if Tcl and Tk aren't themselves shared
-#                       libraries), then this symbol has an empty string
-#                       as its value.
-#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
-#                       extensions.  An empty string means we don't know how
-#                       to use shared libraries on this platform.
-#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
-#                       in a static or shared library name, using the $PACKAGE_VERSION variable
-#                       to put the version in the right place.  This is used
-#                       by platforms that need non-standard library names.
-#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
-#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
-#                       on AIX, since a shared library needs to have
-#                       a .a extension whereas shared objects for loadable
-#                       extensions have a .so extension.  Defaults to
-#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
-#      CFLAGS_DEBUG -
-#                      Flags used when running the compiler in debug mode
-#      CFLAGS_OPTIMIZE -
-#                      Flags used when running the compiler in optimize mode
-#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_CFLAGS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-
-    # Step 0.a: Enable 64 bit support?
-
-    AC_MSG_CHECKING([if 64bit support is requested])
-    AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
-           [enable 64bit support (default: off)]),
-       [do64bit=$enableval], [do64bit=no])
-    AC_MSG_RESULT([$do64bit])
-
-    # Step 0.b: Enable Solaris 64 bit VIS support?
-
-    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
-    AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
-           [enable 64bit Sparc VIS support (default: off)]),
-       [do64bitVIS=$enableval], [do64bitVIS=no])
-    AC_MSG_RESULT([$do64bitVIS])
-    # Force 64bit on with VIS
-    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
-
-    # Step 0.c: Check if visibility support is available. Do this here so
-    # that platform specific alternatives can be used below if this fails.
-
-    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
-       tcl_cv_cc_visibility_hidden, [
-       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
-       AC_TRY_LINK([
-           extern __attribute__((__visibility__("hidden"))) void f(void);
-           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
-           tcl_cv_cc_visibility_hidden=no)
-       CFLAGS=$hold_cflags])
-    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
-       AC_DEFINE(MODULE_SCOPE,
-           [extern __attribute__((__visibility__("hidden")))],
-           [Compiler support for module scope symbols])
-       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
-    ])
-
-    # Step 0.d: Disable -rpath support?
-
-    AC_MSG_CHECKING([if rpath support is requested])
-    AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
-           [disable rpath support (default: on)]),
-       [doRpath=$enableval], [doRpath=yes])
-    AC_MSG_RESULT([$doRpath])
-
-    # Set the variable "system" to hold the name and version number
-    # for the system.
-
-    TEA_CONFIG_SYSTEM
-
-    # Require ranlib early so we can override it in special cases below.
-
-    AC_REQUIRE([AC_PROG_RANLIB])
-
-    # Set configuration options based on system name and version.
-    # This is similar to Tcl's unix/tcl.m4 except that we've added a
-    # "windows" case and removed some core-only vars.
-
-    do64bit_ok=no
-    # default to '{$LIBS}' and set to "" on per-platform necessary basis
-    SHLIB_LD_LIBS='${LIBS}'
-    # When ld needs options to work in 64-bit mode, put them in
-    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
-    # is disabled by the user. [Bug 1016796]
-    LDFLAGS_ARCH=""
-    UNSHARED_LIB_SUFFIX=""
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
-    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
-    TCL_LIB_VERSIONS_OK=ok
-    CFLAGS_DEBUG=-g
-    AS_IF([test "$GCC" = yes], [
-       CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
-    ], [
-       CFLAGS_OPTIMIZE=-O
-       CFLAGS_WARNING=""
-    ])
-    AC_CHECK_TOOL(AR, ar)
-    STLIB_LD='${AR} cr'
-    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
-    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
-    case $system in
-       # TEA specific:
-       windows)
-           MACHINE="X86"
-           if test "$do64bit" != "no" ; then
-               case "$do64bit" in
-                   amd64|x64|yes)
-                       MACHINE="AMD64" ; # default to AMD64 64-bit build
-                       ;;
-                   ia64)
-                       MACHINE="IA64"
-                       ;;
-               esac
-           fi
-
-           if test "$GCC" != "yes" ; then
-               if test "${SHARED_BUILD}" = "0" ; then
-                   runtime=-MT
-               else
-                   runtime=-MD
-               fi
-               case "x`echo \${VisualStudioVersion}`" in
-                   x1[[4-9]]*)
-                       lflags="${lflags} -nodefaultlib:libucrt.lib"
-                       TEA_ADD_LIBS([ucrt.lib])
-                   ;;
-                   *)
-                   ;;
-               esac
-
-                if test "$do64bit" != "no" ; then
-                   CC="cl.exe"
-                   RC="rc.exe"
-                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
-                   LINKBIN="link.exe"
-                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-                   # Avoid 'unresolved external symbol __security_cookie'
-                   # errors, c.f. http://support.microsoft.com/?id=894573
-                   TEA_ADD_LIBS([bufferoverflowU.lib])
-               else
-                   RC="rc"
-                   lflags="${lflags} -nologo"
-                   LINKBIN="link"
-                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-               fi
-           fi
-
-           if test "$GCC" = "yes"; then
-               # mingw gcc mode
-               AC_CHECK_TOOL(RC, windres)
-               CFLAGS_DEBUG="-g"
-               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-               SHLIB_LD='${CC} -shared'
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
-               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
-
-               AC_CACHE_CHECK(for cross-compile version of gcc,
-                       ac_cv_cross,
-                       AC_TRY_COMPILE([
-                           #ifdef _WIN32
-                               #error cross-compiler
-                           #endif
-                       ], [],
-                       ac_cv_cross=yes,
-                       ac_cv_cross=no)
-                     )
-                     if test "$ac_cv_cross" = "yes"; then
-                       case "$do64bit" in
-                           amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
-                               LD="x86_64-w64-mingw32-ld"
-                               AR="x86_64-w64-mingw32-ar"
-                               RANLIB="x86_64-w64-mingw32-ranlib"
-                               RC="x86_64-w64-mingw32-windres"
-                           ;;
-                           *)
-                               CC="i686-w64-mingw32-gcc"
-                               LD="i686-w64-mingw32-ld"
-                               AR="i686-w64-mingw32-ar"
-                               RANLIB="i686-w64-mingw32-ranlib"
-                               RC="i686-w64-mingw32-windres"
-                           ;;
-                       esac
-               fi
-
-           else
-               SHLIB_LD="${LINKBIN} -dll ${lflags}"
-               # link -lib only works when -lib is the first arg
-               STLIB_LD="${LINKBIN} -lib ${lflags}"
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
-               PATHTYPE=-w
-               # For information on what debugtype is most useful, see:
-               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
-               # and also
-               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
-               # This essentially turns it all on.
-               LDFLAGS_DEBUG="-debug -debugtype:cv"
-               LDFLAGS_OPTIMIZE="-release"
-               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
-               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
-           fi
-
-           SHLIB_SUFFIX=".dll"
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
-
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       AIX-*)
-           AS_IF([test "$GCC" != "yes"], [
-               # AIX requires the _r compiler when gcc isn't being used
-               case "${CC}" in
-                   *_r|*_r\ *)
-                       # ok ...
-                       ;;
-                   *)
-                       # Make sure only first arg gets _r
-                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
-                       ;;
-               esac
-               AC_MSG_RESULT([Using $CC for compiling with threads])
-           ])
-           LIBS="$LIBS -lc"
-           SHLIB_CFLAGS=""
-           SHLIB_SUFFIX=".so"
-
-           LD_LIBRARY_PATH_VAR="LIBPATH"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS -q64"
-                   LDFLAGS_ARCH="-q64"
-                   RANLIB="${RANLIB} -X64"
-                   AR="${AR} -X64"
-                   SHLIB_LD_FLAGS="-b64"
-               ])
-           ])
-
-           AS_IF([test "`uname -m`" = ia64], [
-               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
-               ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ], [
-               AS_IF([test "$GCC" = yes], [
-                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
-               ], [
-                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
-                   LDFLAGS="$LDFLAGS -brtl"
-               ])
-               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       BeOS*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} -nostart'
-           SHLIB_SUFFIX=".so"
-
-           #-----------------------------------------------------------
-           # Check for inet_ntoa in -lbind, for BeOS (which also needs
-           # -lsocket, even if the network functions are in -lnet which
-           # is always linked to, for compatibility.
-           #-----------------------------------------------------------
-           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
-           ;;
-       BSD/OS-2.1*|BSD/OS-3*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="shlicc -r"
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       BSD/OS-4.*)
-           SHLIB_CFLAGS="-export-dynamic -fPIC"
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       CYGWIN_*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".dll"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           AC_CACHE_CHECK(for Cygwin version of gcc,
-               ac_cv_cygwin,
-               AC_TRY_COMPILE([
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-               ], [],
-               ac_cv_cygwin=no,
-               ac_cv_cygwin=yes)
-           )
-           if test "$ac_cv_cygwin" = "no"; then
-               AC_MSG_ERROR([${CC} is not a cygwin compiler.])
-           fi
-           EXEEXT=".exe"
-           do64bit_ok=yes
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       dgux*)
-           SHLIB_CFLAGS="-K PIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       Haiku*)
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
-           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
-           ;;
-       HP-UX-*.11.*)
-           # Use updated header definitions where possible
-           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
-           # TEA specific: Needed by Tcl, but not most extensions
-           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
-           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
-
-           AS_IF([test "`uname -m`" = ia64], [
-               SHLIB_SUFFIX=".so"
-           ], [
-               SHLIB_SUFFIX=".sl"
-           ])
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ])
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               CFLAGS="$CFLAGS -z"
-           ])
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = "yes"], [
-               AS_IF([test "$GCC" = yes], [
-                   case `${CC} -dumpmachine` in
-                       hppa64*)
-                           # 64-bit gcc in use.  Fix flags for GNU ld.
-                           do64bit_ok=yes
-                           SHLIB_LD='${CC} -shared'
-                           AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-                           ;;
-                       *)
-                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
-                           ;;
-                   esac
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS +DD64"
-                   LDFLAGS_ARCH="+DD64"
-               ])
-           ]) ;;
-       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
-           SHLIB_SUFFIX=".sl"
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-               SHLIB_LD_LIBS=""
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ]) ;;
-       IRIX-5.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AC_LIBOBJ(mkstemp)
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           ;;
-       IRIX-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [
-               CFLAGS="$CFLAGS -mabi=n32"
-               LDFLAGS="$LDFLAGS -mabi=n32"
-           ], [
-               case $system in
-                   IRIX-6.3)
-                       # Use to build 6.2 compatible binaries on 6.3.
-                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
-                       ;;
-                   *)
-                       CFLAGS="$CFLAGS -n32"
-                       ;;
-               esac
-               LDFLAGS="$LDFLAGS -n32"
-           ])
-           ;;
-       IRIX64-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-
-           # Check to enable 64-bit flags for compiler/linker
-
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported by gcc])
-               ], [
-                   do64bit_ok=yes
-                   SHLIB_LD="ld -64 -shared -rdata_shared"
-                   CFLAGS="$CFLAGS -64"
-                   LDFLAGS_ARCH="-64"
-               ])
-           ])
-           ;;
-       Linux*|GNU*|NetBSD-Debian)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-
-           # TEA specific:
-           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
-           AS_IF([test $do64bit = yes], [
-               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
-                   hold_cflags=$CFLAGS
-                   CFLAGS="$CFLAGS -m64"
-                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
-                   CFLAGS=$hold_cflags])
-               AS_IF([test $tcl_cv_cc_m64 = yes], [
-                   CFLAGS="$CFLAGS -m64"
-                   do64bit_ok=yes
-               ])
-          ])
-
-           # The combo of gcc + glibc has a bug related to inlining of
-           # functions like strtod(). The -fno-builtin flag should address
-           # this problem but it does not work. The -fno-inline flag is kind
-           # of overkill but it works. Disable inlining only when one of the
-           # files in compat/*.c is being linked in.
-
-           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
-           ;;
-       Lynx*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           CFLAGS_OPTIMIZE=-02
-           SHLIB_LD='${CC} -shared'
-           LD_FLAGS="-Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           ;;
-       OpenBSD-*)
-           arch=`arch -s`
-           case "$arch" in
-           alpha|sparc64)
-               SHLIB_CFLAGS="-fPIC"
-               ;;
-           *)
-               SHLIB_CFLAGS="-fpic"
-               ;;
-           esac
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
-           CFLAGS_OPTIMIZE="-O2"
-           # On OpenBSD:       Compile with -pthread
-           #           Don't link with -lpthread
-           LIBS=`echo $LIBS | sed s/-lpthread//`
-           CFLAGS="$CFLAGS -pthread"
-           # OpenBSD doesn't do version numbers with dots.
-           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       NetBSD-*)
-           # NetBSD has ELF and can use 'cc -shared' to build shared libs
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           # The -pthread needs to go in the CFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS -pthread"
-           LDFLAGS="$LDFLAGS -pthread"
-           ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
-       Darwin-*)
-           CFLAGS_OPTIMIZE="-Os"
-           SHLIB_CFLAGS="-fno-common"
-           # To avoid discrepancies between what headers configure sees during
-           # preprocessing tests and compiling tests, move any -isysroot and
-           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
-           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
-           CFLAGS="`echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
-           AS_IF([test $do64bit = yes], [
-               case `arch` in
-                   ppc)
-                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
-                               tcl_cv_cc_arch_ppc64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
-                                   tcl_cv_cc_arch_ppc64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           do64bit_ok=yes
-                       ]);;
-                   i386)
-                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
-                               tcl_cv_cc_arch_x86_64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
-                                   tcl_cv_cc_arch_x86_64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           do64bit_ok=yes
-                       ]);;
-                   *)
-                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
-               esac
-           ], [
-               # Check for combined 32-bit and 64-bit fat build
-               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
-                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
-                   fat_32_64=yes])
-           ])
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
-           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_single_module = yes], [
-               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
-           ])
-           # TEA specific: link shlib with current and compatibility version flags
-           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
-           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
-           SHLIB_SUFFIX=".dylib"
-           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
-           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
-                   tcl_cv_ld_search_paths_first, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
-                       tcl_cv_ld_search_paths_first=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-           ])
-           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
-                   [Compiler support for module scope symbols])
-               tcl_cv_cc_visibility_hidden=yes
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
-           # TEA specific: for combined 32 & 64 bit fat builds of Tk
-           # extensions, verify that 64-bit build is possible.
-           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
-                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
-                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
-                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
-                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
-                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
-                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
-                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
-                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               # remove 64-bit arch flags from CFLAGS et al. if configuration
-               # does not support 64-bit.
-               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
-                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
-                   for v in CFLAGS CPPFLAGS LDFLAGS; do
-                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
-                   done])
-           ])
-           ;;
-       OS/390-*)
-           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
-           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
-               [Should OS/390 do the right thing with sockets?])
-           ;;
-       OSF1-V*)
-           # Digital OSF/1
-           SHLIB_CFLAGS=""
-           AS_IF([test "$SHARED_BUILD" = 1], [
-               SHLIB_LD='ld -shared -expect_unresolved "*"'
-           ], [
-               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
-           ])
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
-               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
-           # see pthread_intro(3) for pthread support on osf1, k.furukawa
-           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
-           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
-           LIBS=`echo $LIBS | sed s/-lpthreads//`
-           AS_IF([test "$GCC" = yes], [
-               LIBS="$LIBS -lpthread -lmach -lexc"
-           ], [
-               CFLAGS="$CFLAGS -pthread"
-               LDFLAGS="$LDFLAGS -pthread"
-           ])
-           ;;
-       QNX-6*)
-           # QNX RTP
-           # This may work for all QNX, but it was only reported for v6.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="ld -Bshareable -x"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SCO_SV-3.2*)
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_CFLAGS="-fPIC -melf"
-               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
-           ], [
-               SHLIB_CFLAGS="-Kpic -belf"
-               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
-           ])
-           SHLIB_LD="ld -G"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SunOS-5.[[0-6]])
-           # Careful to not let 5.10+ fall into this case
-
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       SunOS-5*)
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               arch=`isainfo`
-               AS_IF([test "$arch" = "sparcv9 sparc"], [
-                   AS_IF([test "$GCC" = yes], [
-                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
-                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
-                       ], [
-                           do64bit_ok=yes
-                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
-                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
-                           SHLIB_CFLAGS="-fPIC"
-                       ])
-                   ], [
-                       do64bit_ok=yes
-                       AS_IF([test "$do64bitVIS" = yes], [
-                           CFLAGS="$CFLAGS -xarch=v9a"
-                           LDFLAGS_ARCH="-xarch=v9a"
-                       ], [
-                           CFLAGS="$CFLAGS -xarch=v9"
-                           LDFLAGS_ARCH="-xarch=v9"
-                       ])
-                       # Solaris 64 uses this as well
-                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
-                   ])
-               ], [AS_IF([test "$arch" = "amd64 i386"], [
-                   AS_IF([test "$GCC" = yes], [
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               do64bit_ok=yes
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
-                       esac
-                   ], [
-                       do64bit_ok=yes
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               CFLAGS="$CFLAGS -xarch=amd64"
-                               LDFLAGS="$LDFLAGS -xarch=amd64";;
-                       esac
-                   ])
-               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
-           ])
-
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-               AS_IF([test "$do64bit_ok" = yes], [
-                   AS_IF([test "$arch" = "sparcv9 sparc"], [
-                       # We need to specify -static-libgcc or we need to
-                       # add the path to the sparv9 libgcc.
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
-                       # for finding sparcv9 libgcc, get the regular libgcc
-                       # path, remove so name and append 'sparcv9'
-                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
-                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
-                   ], [AS_IF([test "$arch" = "amd64 i386"], [
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
-                   ])])
-               ])
-           ], [
-               case $system in
-                   SunOS-5.[[1-9]][[0-9]]*)
-                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
-                   *)
-                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
-               esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ])
-           ;;
-       UNIX_SV* | UnixWare-5*)
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
-           # that don't grok the -Bexport option.  Test that it does.
-           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_Bexport = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-    esac
-
-    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
-       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
-    ])
-
-dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
-dnl # until the end of configure, as configure's compile and link tests use
-dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
-dnl # preprocessing tests use only CPPFLAGS.
-    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
-
-    # Add in the arch flags late to ensure it wasn't removed.
-    # Not necessary in TEA, but this is aligned with core
-    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
-
-    # If we're running gcc, then change the C flags for compiling shared
-    # libraries to the right flags for gcc, instead of those for the
-    # standard manufacturer compiler.
-
-    AS_IF([test "$GCC" = yes], [
-       case $system in
-           AIX-*) ;;
-           BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
-           IRIX*) ;;
-           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
-           Darwin-*) ;;
-           SCO_SV-3.2*) ;;
-           windows) ;;
-           *) SHLIB_CFLAGS="-fPIC" ;;
-       esac])
-
-    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-       AC_DEFINE(MODULE_SCOPE, [extern],
-           [No Compiler support for module scope symbols])
-    ])
-
-    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
-    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
-
-    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
-       AC_CACHE_CHECK(for SEH support in compiler,
-           tcl_cv_seh,
-       AC_TRY_RUN([
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-
-           int main(int argc, char** argv) {
-               int a, b = 0;
-               __try {
-                   a = 666 / b;
-               }
-               __except (EXCEPTION_EXECUTE_HANDLER) {
-                   return 0;
-               }
-               return 1;
-           }
-       ],
-           tcl_cv_seh=yes,
-           tcl_cv_seh=no,
-           tcl_cv_seh=no)
-       )
-       if test "$tcl_cv_seh" = "no" ; then
-           AC_DEFINE(HAVE_NO_SEH, 1,
-                   [Defined when mingw does not support SEH])
-       fi
-
-       #
-       # Check to see if the excpt.h include file provided contains the
-       # definition for EXCEPTION_DISPOSITION; if not, which is the case
-       # with Cygwin's version as of 2002-04-10, define it to be int,
-       # sufficient for getting the current code to work.
-       #
-       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
-           tcl_cv_eh_disposition,
-           AC_TRY_COMPILE([
-#          define WIN32_LEAN_AND_MEAN
-#          include <windows.h>
-#          undef WIN32_LEAN_AND_MEAN
-           ],[
-               EXCEPTION_DISPOSITION x;
-           ],
-               tcl_cv_eh_disposition=yes,
-               tcl_cv_eh_disposition=no)
-       )
-       if test "$tcl_cv_eh_disposition" = "no" ; then
-       AC_DEFINE(EXCEPTION_DISPOSITION, int,
-               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
-       fi
-
-       # Check to see if winnt.h defines CHAR, SHORT, and LONG
-       # even if VOID has already been #defined. The win32api
-       # used by mingw and cygwin is known to do this.
-
-       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
-           tcl_cv_winnt_ignore_void,
-           AC_TRY_COMPILE([
-#define VOID void
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-           ], [
-               CHAR c;
-               SHORT s;
-               LONG l;
-           ],
-        tcl_cv_winnt_ignore_void=yes,
-        tcl_cv_winnt_ignore_void=no)
-       )
-       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
-           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
-                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
-       fi
-    fi
-
-       # See if the compiler supports casting to a union type.
-       # This is used to stop gcc from printing a compiler
-       # warning when initializing a union member.
-
-       AC_CACHE_CHECK(for cast to union support,
-           tcl_cv_cast_to_union,
-           AC_TRY_COMPILE([],
-           [
-                 union foo { int i; double d; };
-                 union foo f = (union foo) (int) 0;
-           ],
-           tcl_cv_cast_to_union=yes,
-           tcl_cv_cast_to_union=no)
-       )
-       if test "$tcl_cv_cast_to_union" = "yes"; then
-           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
-                   [Defined when compiler supports casting to union type.])
-       fi
-
-       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
-
-    AC_SUBST(CFLAGS_DEBUG)
-    AC_SUBST(CFLAGS_OPTIMIZE)
-    AC_SUBST(CFLAGS_WARNING)
-
-    AC_SUBST(STLIB_LD)
-    AC_SUBST(SHLIB_LD)
-
-    AC_SUBST(SHLIB_LD_LIBS)
-    AC_SUBST(SHLIB_CFLAGS)
-
-    AC_SUBST(LD_LIBRARY_PATH_VAR)
-
-    # These must be called after we do the basic CFLAGS checks and
-    # verify any possible 64-bit or similar switches are necessary
-    TEA_TCL_EARLY_FLAGS
-    TEA_TCL_64BIT_FLAGS
-])
-
-#--------------------------------------------------------------------
-# TEA_SERIAL_PORT
-#
-#      Determine which interface to use to talk to the serial port.
-#      Note that #include lines must begin in leftmost column for
-#      some compilers to recognize them as preprocessor directives,
-#      and some build environments have stdin not pointing at a
-#      pseudo-terminal (usually /dev/null instead.)
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines only one of the following vars:
-#              HAVE_SYS_MODEM_H
-#              USE_TERMIOS
-#              USE_TERMIO
-#              USE_SGTTY
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_SERIAL_PORT], [
-    AC_CHECK_HEADERS(sys/modem.h)
-    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
-    AC_TRY_RUN([
-#include <termios.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termio.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termios.h>
-#include <errno.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <termio.h>
-#include <errno.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-#include <errno.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
-    fi])
-    case $tcl_cv_api_serial in
-       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
-       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
-       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_PATH_X
-#
-#      Locate the X11 header files and the X11 library archive.  Try
-#      the ac_path_x macro first, but if it doesn't find the X stuff
-#      (e.g. because there's no xmkmf program) then check through
-#      a list of possible directories.  Under some conditions the
-#      autoconf macro will return an include directory that contains
-#      no include files, so double-check its result just to be safe.
-#
-#      This should be called after TEA_CONFIG_CFLAGS as setting the
-#      LIBS line can confuse some configure macro magic.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets the following vars:
-#              XINCLUDES
-#              XLIBSW
-#              PKG_LIBS (appends to)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_X], [
-    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
-       TEA_PATH_UNIX_X
-    fi
-])
-
-AC_DEFUN([TEA_PATH_UNIX_X], [
-    AC_PATH_X
-    not_really_there=""
-    if test "$no_x" = ""; then
-       if test "$x_includes" = ""; then
-           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
-       else
-           if test ! -r $x_includes/X11/Xlib.h; then
-               not_really_there="yes"
-           fi
-       fi
-    fi
-    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
-       AC_MSG_CHECKING([for X11 header files])
-       found_xincludes="no"
-       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
-       if test "$found_xincludes" = "no"; then
-           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
-           for i in $dirs ; do
-               if test -r $i/X11/Xlib.h; then
-                   AC_MSG_RESULT([$i])
-                   XINCLUDES=" -I$i"
-                   found_xincludes="yes"
-                   break
-               fi
-           done
-       fi
-    else
-       if test "$x_includes" != ""; then
-           XINCLUDES="-I$x_includes"
-           found_xincludes="yes"
-       fi
-    fi
-    if test "$found_xincludes" = "no"; then
-       AC_MSG_RESULT([couldn't find any!])
-    fi
-
-    if test "$no_x" = yes; then
-       AC_MSG_CHECKING([for X11 libraries])
-       XLIBSW=nope
-       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
-       for i in $dirs ; do
-           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
-               AC_MSG_RESULT([$i])
-               XLIBSW="-L$i -lX11"
-               x_libraries="$i"
-               break
-           fi
-       done
-    else
-       if test "$x_libraries" = ""; then
-           XLIBSW=-lX11
-       else
-           XLIBSW="-L$x_libraries -lX11"
-       fi
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_MSG_RESULT([could not find any!  Using -lX11.])
-       XLIBSW=-lX11
-    fi
-    # TEA specific:
-    if test x"${XLIBSW}" != x ; then
-       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BLOCKING_STYLE
-#
-#      The statements below check for systems where POSIX-style
-#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
-#      On these systems (mostly older ones), use the old BSD-style
-#      FIONBIO approach instead.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              HAVE_SYS_IOCTL_H
-#              HAVE_SYS_FILIO_H
-#              USE_FIONBIO
-#              O_NONBLOCK
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BLOCKING_STYLE], [
-    AC_CHECK_HEADERS(sys/ioctl.h)
-    AC_CHECK_HEADERS(sys/filio.h)
-    TEA_CONFIG_SYSTEM
-    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
-    case $system in
-       OSF*)
-           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
-           AC_MSG_RESULT([FIONBIO])
-           ;;
-       *)
-           AC_MSG_RESULT([O_NONBLOCK])
-           ;;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_TIME_HANDLER
-#
-#      Checks how the system deals with time.h, what time structures
-#      are used on the system, and what fields the structures have.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              USE_DELTA_FOR_TZ
-#              HAVE_TM_GMTOFF
-#              HAVE_TM_TZADJ
-#              HAVE_TIMEZONE_VAR
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TIME_HANDLER], [
-    AC_CHECK_HEADERS(sys/time.h)
-    AC_HEADER_TIME
-    AC_STRUCT_TIMEZONE
-
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
-
-    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
-           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
-    if test $tcl_cv_member_tm_tzadj = yes ; then
-       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
-    fi
-
-    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
-           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
-    if test $tcl_cv_member_tm_gmtoff = yes ; then
-       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
-    fi
-
-    #
-    # Its important to include time.h in this check, as some systems
-    # (like convex) have timezone functions, etc.
-    #
-    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
-       AC_TRY_COMPILE([#include <time.h>],
-           [extern long timezone;
-           timezone += 1;
-           exit (0);],
-           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
-    if test $tcl_cv_timezone_long = yes ; then
-       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-    else
-       #
-       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
-       #
-       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
-           AC_TRY_COMPILE([#include <time.h>],
-               [extern time_t timezone;
-               timezone += 1;
-               exit (0);],
-               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
-       if test $tcl_cv_timezone_time = yes ; then
-           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BUGGY_STRTOD
-#
-#      Under Solaris 2.4, strtod returns the wrong value for the
-#      terminating character under some conditions.  Check for this
-#      and if the problem exists use a substitute procedure
-#      "fixstrtod" (provided by Tcl) that corrects the error.
-#      Also, on Compaq's Tru64 Unix 5.0,
-#      strtod(" ") returns 0.0 instead of a failure to convert.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Might defines some of the following vars:
-#              strtod (=fixstrtod)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BUGGY_STRTOD], [
-    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
-    if test "$tcl_strtod" = 1; then
-       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
-           AC_TRY_RUN([
-               extern double strtod();
-               int main() {
-                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
-                   char *term;
-                   double value;
-                   value = strtod(infString, &term);
-                   if ((term != infString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(nanString, &term);
-                   if ((term != nanString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(spaceString, &term);
-                   if (term == (spaceString+1)) {
-                       exit(1);
-                   }
-                   exit(0);
-               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
-                   tcl_cv_strtod_buggy=buggy)])
-       if test "$tcl_cv_strtod_buggy" = buggy; then
-           AC_LIBOBJ([fixstrtod])
-           USE_COMPAT=1
-           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_EARLY_FLAGS
-#
-#      Check for what flags are needed to be passed so the correct OS
-#      features are available.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              _ISOC99_SOURCE
-#              _LARGEFILE64_SOURCE
-#              _LARGEFILE_SOURCE64
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_EARLY_FLAG],[
-    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
-       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
-           AC_TRY_COMPILE([[#define ]$1[ 1
-]$2], $3,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
-    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
-       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
-       tcl_flags="$tcl_flags $1"
-    fi
-])
-
-AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
-    AC_MSG_CHECKING([for required early compiler flags])
-    tcl_flags=""
-    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
-       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
-       [struct stat64 buf; int i = stat64("/", &buf);])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
-       [char *p = (char *)open64;])
-    if test "x${tcl_flags}" = "x" ; then
-       AC_MSG_RESULT([none])
-    else
-       AC_MSG_RESULT([${tcl_flags}])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_64BIT_FLAGS
-#
-#      Check for what is defined in the way of 64-bit features.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              TCL_WIDE_INT_IS_LONG
-#              TCL_WIDE_INT_TYPE
-#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
-#              HAVE_STRUCT_STAT64
-#              HAVE_TYPE_OFF64_T
-#
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
-    AC_MSG_CHECKING([for 64-bit integer type])
-    AC_CACHE_VAL(tcl_cv_type_64bit,[
-       tcl_cv_type_64bit=none
-       # See if the compiler knows natively about __int64
-       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
-           tcl_type_64bit=__int64, tcl_type_64bit="long long")
-       # See if we could use long anyway  Note that we substitute in the
-       # type that is our current guess for a 64-bit type inside this check
-       # program, so it should be modified only carefully...
-        AC_TRY_COMPILE(,[switch (0) {
-            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
-        }],tcl_cv_type_64bit=${tcl_type_64bit})])
-    if test "${tcl_cv_type_64bit}" = none ; then
-       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
-       AC_MSG_RESULT([yes])
-    elif test "${tcl_cv_type_64bit}" = "__int64" \
-               -a "${TEA_PLATFORM}" = "windows" ; then
-       # TEA specific: We actually want to use the default tcl.h checks in
-       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
-       AC_MSG_RESULT([using Tcl header defaults])
-    else
-       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
-           [What type should be used to define wide integers?])
-       AC_MSG_RESULT([${tcl_cv_type_64bit}])
-
-       # Now check for auxiliary declarations
-       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 p;],
-               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
-       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
-            p = readdir64(d); rewinddir64(d); closedir64(d);],
-               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
-       if test "x${tcl_cv_DIR64}" = "xyes" ; then
-           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
-           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
-],
-               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
-       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
-       fi
-
-       AC_CHECK_FUNCS(open64 lseek64)
-       AC_MSG_CHECKING([for off64_t])
-       AC_CACHE_VAL(tcl_cv_type_off64_t,[
-           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
-],
-               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
-       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
-       dnl functions lseek64 and open64 are defined.
-       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
-               test "x${ac_cv_func_lseek64}" = "xyes" && \
-               test "x${ac_cv_func_open64}" = "xyes" ; then
-           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
-           AC_MSG_RESULT([yes])
-       else
-           AC_MSG_RESULT([no])
-       fi
-    fi
-])
-
-##
-## Here ends the standard Tcl configuration bits and starts the
-## TEA specific functions
-##
-
-#------------------------------------------------------------------------
-# TEA_INIT --
-#
-#      Init various Tcl Extension Architecture (TEA) variables.
-#      This should be the first called TEA_* macro.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              CYGPATH
-#              EXEEXT
-#      Defines only:
-#              TEA_VERSION
-#              TEA_INITED
-#              TEA_PLATFORM (windows or unix)
-#
-# "cygpath" is used on windows to generate native path names for include
-# files. These variables should only be used with the compiler and linker
-# since they generate native path names.
-#
-# EXEEXT
-#      Select the executable extension based on the host type.  This
-#      is a lightweight replacement for AC_EXEEXT that doesn't require
-#      a compiler.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INIT], [
-    TEA_VERSION="3.13"
-
-    AC_MSG_CHECKING([TEA configuration])
-    if test x"${PACKAGE_NAME}" = x ; then
-       AC_MSG_ERROR([
-The PACKAGE_NAME variable must be defined by your TEA configure.ac])
-    fi
-    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
-
-    # If the user did not set CFLAGS, set it now to keep macros
-    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
-    if test "${CFLAGS+set}" != "set" ; then
-       CFLAGS=""
-    fi
-
-    case "`uname -s`" in
-       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
-           EXEEXT=".exe"
-           TEA_PLATFORM="windows"
-           ;;
-       *CYGWIN_*)
-           EXEEXT=".exe"
-           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
-           ;;
-       *)
-           CYGPATH=echo
-           # Maybe we are cross-compiling....
-           case ${host_alias} in
-               *mingw32*)
-               EXEEXT=".exe"
-               TEA_PLATFORM="windows"
-               ;;
-           *)
-               EXEEXT=""
-               TEA_PLATFORM="unix"
-               ;;
-           esac
-           ;;
-    esac
-
-    # Check if exec_prefix is set. If not use fall back to prefix.
-    # Note when adjusted, so that TEA_PREFIX can correct for this.
-    # This is needed for recursive configures, since autoconf propagates
-    # $prefix, but not $exec_prefix (doh!).
-    if test x$exec_prefix = xNONE ; then
-       exec_prefix_default=yes
-       exec_prefix=$prefix
-    fi
-
-    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
-
-    AC_SUBST(EXEEXT)
-    AC_SUBST(CYGPATH)
-
-    # This package name must be replaced statically for AC_SUBST to work
-    AC_SUBST(PKG_LIB_FILE)
-    # Substitute STUB_LIB_FILE in case package creates a stub library too.
-    AC_SUBST(PKG_STUB_LIB_FILE)
-
-    # We AC_SUBST these here to ensure they are subst'ed,
-    # in case the user doesn't call TEA_ADD_...
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-    AC_SUBST(PKG_TCL_SOURCES)
-    AC_SUBST(PKG_HEADERS)
-    AC_SUBST(PKG_INCLUDES)
-    AC_SUBST(PKG_LIBS)
-    AC_SUBST(PKG_CFLAGS)
-
-    # Configure the installer.
-    TEA_INSTALLER
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_SOURCES
-#              PKG_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       case $i in
-           [\$]*)
-               # allow $-var names
-               PKG_SOURCES="$PKG_SOURCES $i"
-               PKG_OBJECTS="$PKG_OBJECTS $i"
-               ;;
-           *)
-               # check for existence - allows for generic/win/unix VPATH
-               # To add more dirs here (like 'src'), you have to update VPATH
-               # in Makefile.in as well
-               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-                   -a ! -f "${srcdir}/macosx/$i" \
-                   ; then
-                   AC_MSG_ERROR([could not find source file '$i'])
-               fi
-               PKG_SOURCES="$PKG_SOURCES $i"
-               # this assumes it is in a VPATH dir
-               i=`basename $i`
-               # handle user calling this before or after TEA_SETUP_COMPILER
-               if test x"${OBJEXT}" != x ; then
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-               else
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-               fi
-               PKG_OBJECTS="$PKG_OBJECTS $j"
-               ;;
-       esac
-    done
-    AC_SUBST(PKG_SOURCES)
-    AC_SUBST(PKG_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_STUB_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_STUB_SOURCES
-#              PKG_STUB_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_STUB_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence - allows for generic/win/unix VPATH
-       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-           -a ! -f "${srcdir}/macosx/$i" \
-           ; then
-           AC_MSG_ERROR([could not find stub source file '$i'])
-       fi
-       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
-       # this assumes it is in a VPATH dir
-       i=`basename $i`
-       # handle user calling this before or after TEA_SETUP_COMPILER
-       if test x"${OBJEXT}" != x ; then
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-       else
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-       fi
-       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
-    done
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_TCL_SOURCES --
-#
-#      Specify one or more Tcl source files.  These should be platform
-#      independent runtime files.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_TCL_SOURCES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_TCL_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
-       fi
-       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
-    done
-    AC_SUBST(PKG_TCL_SOURCES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_HEADERS --
-#
-#      Specify one or more source headers.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_HEADERS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_HEADERS], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
-       fi
-       PKG_HEADERS="$PKG_HEADERS $i"
-    done
-    AC_SUBST(PKG_HEADERS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_INCLUDES --
-#
-#      Specify one or more include dirs.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_INCLUDES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_INCLUDES], [
-    vars="$@"
-    for i in $vars; do
-       PKG_INCLUDES="$PKG_INCLUDES $i"
-    done
-    AC_SUBST(PKG_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_LIBS --
-#
-#      Specify one or more libraries.  Users should check for
-#      the right platform before adding to their list.  For Windows,
-#      libraries provided in "foo.lib" format will be converted to
-#      "-lfoo" when using GCC (mingw).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_LIBS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_LIBS], [
-    vars="$@"
-    for i in $vars; do
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
-           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
-       fi
-       PKG_LIBS="$PKG_LIBS $i"
-    done
-    AC_SUBST(PKG_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CFLAGS --
-#
-#      Specify one or more CFLAGS.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_CFLAGS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CFLAGS], [
-    PKG_CFLAGS="$PKG_CFLAGS $@"
-    AC_SUBST(PKG_CFLAGS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CLEANFILES --
-#
-#      Specify one or more CLEANFILES.
-#
-# Arguments:
-#      one or more file names to clean target
-#
-# Results:
-#
-#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CLEANFILES], [
-    CLEANFILES="$CLEANFILES $@"
-])
-
-#------------------------------------------------------------------------
-# TEA_PREFIX --
-#
-#      Handle the --prefix=... option by defaulting to what Tcl gave
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      If --prefix or --exec-prefix was not specified, $prefix and
-#      $exec_prefix will be set to the values given to Tcl when it was
-#      configured.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_PREFIX], [
-    if test "${prefix}" = "NONE"; then
-       prefix_default=yes
-       if test x"${TCL_PREFIX}" != x; then
-           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
-           prefix=${TCL_PREFIX}
-       else
-           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
-           prefix=/usr/local
-       fi
-    fi
-    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
-       -o x"${exec_prefix_default}" = x"yes" ; then
-       if test x"${TCL_EXEC_PREFIX}" != x; then
-           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
-           exec_prefix=${TCL_EXEC_PREFIX}
-       else
-           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
-           exec_prefix=$prefix
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER_CC --
-#
-#      Do compiler checks the way we want.  This is just a replacement
-#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER_CC], [
-    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
-    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
-
-    AC_PROG_CC
-    AC_PROG_CPP
-
-    #--------------------------------------------------------------------
-    # Checks to see if the make program sets the $MAKE variable.
-    #--------------------------------------------------------------------
-
-    AC_PROG_MAKE_SET
-
-    #--------------------------------------------------------------------
-    # Find ranlib
-    #--------------------------------------------------------------------
-
-    AC_CHECK_TOOL(RANLIB, ranlib)
-
-    #--------------------------------------------------------------------
-    # Determines the correct binary file extension (.o, .obj, .exe etc.)
-    #--------------------------------------------------------------------
-
-    AC_OBJEXT
-    AC_EXEEXT
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER --
-#
-#      Do compiler checks that use the compiler.  This must go after
-#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER], [
-    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
-    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
-
-    #------------------------------------------------------------------------
-    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
-    # It makes compiling go faster.  (This is only a performance feature.)
-    #------------------------------------------------------------------------
-
-    if test -z "$no_pipe" -a -n "$GCC"; then
-       AC_CACHE_CHECK([if the compiler understands -pipe],
-           tcl_cv_cc_pipe, [
-           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
-           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
-           CFLAGS=$hold_cflags])
-       if test $tcl_cv_cc_pipe = yes; then
-           CFLAGS="$CFLAGS -pipe"
-       fi
-    fi
-
-    #--------------------------------------------------------------------
-    # Common compiler flag setup
-    #--------------------------------------------------------------------
-
-    AC_C_BIGENDIAN
-])
-
-#------------------------------------------------------------------------
-# TEA_MAKE_LIB --
-#
-#      Generate a line that can be used to build a shared/unshared library
-#      in a platform independent manner.
-#
-# Arguments:
-#      none
-#
-#      Requires:
-#
-# Results:
-#
-#      Defines the following vars:
-#      CFLAGS -        Done late here to note disturb other AC macros
-#       MAKE_LIB -      Command to execute to build the Tcl library;
-#                       differs depending on whether or not Tcl is being
-#                       compiled as a shared library.
-#      MAKE_SHARED_LIB Makefile rule for building a shared library
-#      MAKE_STATIC_LIB Makefile rule for building a static library
-#      MAKE_STUB_LIB   Makefile rule for building a stub library
-#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
-#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_MAKE_LIB], [
-    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
-       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
-       AC_EGREP_CPP([manifest needed], [
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-print("manifest needed")
-#endif
-       ], [
-       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
-       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
-       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
-       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
-       TEA_ADD_CLEANFILES([*.manifest])
-       ])
-       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
-    else
-       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
-       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
-    fi
-
-    if test "${SHARED_BUILD}" = "1" ; then
-       MAKE_LIB="${MAKE_SHARED_LIB} "
-    else
-       MAKE_LIB="${MAKE_STATIC_LIB} "
-    fi
-
-    #--------------------------------------------------------------------
-    # Shared libraries and static libraries have different names.
-    # Use the double eval to make sure any variables in the suffix is
-    # substituted. (@@@ Might not be necessary anymore)
-    #--------------------------------------------------------------------
-
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       if test "${SHARED_BUILD}" = "1" ; then
-           # We force the unresolved linking of symbols that are really in
-           # the private libraries of Tcl and Tk.
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
-           fi
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
-           if test "$GCC" = "yes"; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
-           fi
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-       else
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-           if test "$GCC" = "yes"; then
-               PKG_LIB_FILE=lib${PKG_LIB_FILE}
-           fi
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-       if test "$GCC" = "yes"; then
-           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
-       fi
-       # These aren't needed on Windows (either MSVC or gcc)
-       RANLIB=:
-       RANLIB_STUB=:
-    else
-       RANLIB_STUB="${RANLIB}"
-       if test "${SHARED_BUILD}" = "1" ; then
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
-           fi
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-           RANLIB=:
-       else
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-    fi
-
-    # These are escaped so that only CFLAGS is picked up at configure time.
-    # The other values will be substituted at make time.
-    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
-    if test "${SHARED_BUILD}" = "1" ; then
-       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
-    fi
-
-    AC_SUBST(MAKE_LIB)
-    AC_SUBST(MAKE_SHARED_LIB)
-    AC_SUBST(MAKE_STATIC_LIB)
-    AC_SUBST(MAKE_STUB_LIB)
-    AC_SUBST(RANLIB_STUB)
-    AC_SUBST(VC_MANIFEST_EMBED_DLL)
-    AC_SUBST(VC_MANIFEST_EMBED_EXE)
-])
-
-#------------------------------------------------------------------------
-# TEA_LIB_SPEC --
-#
-#      Compute the name of an existing object library located in libdir
-#      from the given base name and produce the appropriate linker flags.
-#
-# Arguments:
-#      basename        The base name of the library without version
-#                      numbers, extensions, or "lib" prefixes.
-#      extra_dir       Extra directory in which to search for the
-#                      library.  This location is used first, then
-#                      $prefix/$exec-prefix, then some defaults.
-#
-# Requires:
-#      TEA_INIT and TEA_PREFIX must be called first.
-#
-# Results:
-#
-#      Defines the following vars:
-#              ${basename}_LIB_NAME    The computed library name.
-#              ${basename}_LIB_SPEC    The computed linker flags.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LIB_SPEC], [
-    AC_MSG_CHECKING([for $1 library])
-
-    # Look in exec-prefix for the library (defined by TEA_PREFIX).
-
-    tea_lib_name_dir="${exec_prefix}/lib"
-
-    # Or in a user-specified location.
-
-    if test x"$2" != x ; then
-       tea_extra_lib_dir=$2
-    else
-       tea_extra_lib_dir=NONE
-    fi
-
-    for i in \
-           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
-       if test -f "$i" ; then
-           tea_lib_name_dir=`dirname $i`
-           $1_LIB_NAME=`basename $i`
-           $1_LIB_PATH_NAME=$i
-           break
-       fi
-    done
-
-    if test "${TEA_PLATFORM}" = "windows"; then
-       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
-    else
-       # Strip off the leading "lib" and trailing ".a" or ".so"
-
-       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
-       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
-    fi
-
-    if test "x${$1_LIB_NAME}" = x ; then
-       AC_MSG_ERROR([not found])
-    else
-       AC_MSG_RESULT([${$1_LIB_SPEC}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TCL_HEADERS --
-#
-#      Locate the private Tcl include files
-#
-# Arguments:
-#
-#      Requires:
-#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
-#                              already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_TOP_DIR_NATIVE
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
-    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
-    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
-    AC_MSG_CHECKING([for Tcl private include files])
-
-    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
-    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
-
-    # Check to see if tcl<Plat>Port.h isn't already with the public headers
-    # Don't look for tclInt.h because that resides with tcl.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
-       else
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TCL_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
-       if test "`uname -s`" = "Darwin"; then
-            # If Tcl was built as a framework, attempt to use
-            # the framework's Headers and PrivateHeaders directories
-            case ${TCL_DEFS} in
-               *TCL_FRAMEWORK*)
-                   if test -d "${TCL_BIN_DIR}/Headers" -a \
-                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
-                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
-                   else
-                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                   fi
-                   ;;
-           esac
-           result="Using ${TCL_INCLUDES}"
-       else
-           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
-               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
-           fi
-           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TCL_TOP_DIR_NATIVE)
-
-    AC_SUBST(TCL_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TCL_HEADERS --
-#
-#      Locate the installed public Tcl header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tclinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
-    AC_MSG_CHECKING([for Tcl public headers])
-
-    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tclh, [
-       # Use the value from --with-tclinclude, if it was given
-
-       if test x"${with_tclinclude}" != x ; then
-           if test -f "${with_tclinclude}/tcl.h" ; then
-               ac_cv_c_tclh=${with_tclinclude}
-           else
-               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tcl was built as a framework, attempt to use
-               # the framework's Headers directory
-               case ${TCL_DEFS} in
-                   *TCL_FRAMEWORK*)
-                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tcl is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TCL_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TCL_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tcl.h" ; then
-                   ac_cv_c_tclh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tclh}" = x ; then
-       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tclh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
-
-    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TCL_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TK_HEADERS --
-#
-#      Locate the private Tk include files
-#
-# Arguments:
-#
-#      Requires:
-#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
-#                               already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
-    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
-    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
-    AC_MSG_CHECKING([for Tk private include files])
-
-    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
-    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
-
-    # Check to see if tk<Plat>Port.h isn't already with the public headers
-    # Don't look for tkInt.h because that resides with tk.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
-       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
-       else
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TK_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
-       # Detect and add ttk subdir
-       if test -d "${TK_SRC_DIR}/generic/ttk"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
-       fi
-       if test "`uname -s`" = "Darwin"; then
-           # If Tk was built as a framework, attempt to use
-           # the framework's Headers and PrivateHeaders directories
-           case ${TK_DEFS} in
-               *TK_FRAMEWORK*)
-                       if test -d "${TK_BIN_DIR}/Headers" -a \
-                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
-                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
-                       else
-                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                       fi
-                       ;;
-           esac
-           result="Using ${TK_INCLUDES}"
-       else
-           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
-              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
-           fi
-           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TK_TOP_DIR_NATIVE)
-    AC_SUBST(TK_XLIB_DIR_NATIVE)
-
-    AC_SUBST(TK_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TK_HEADERS --
-#
-#      Locate the installed public Tk header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tkinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
-    AC_MSG_CHECKING([for Tk public headers])
-
-    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tkh, [
-       # Use the value from --with-tkinclude, if it was given
-
-       if test x"${with_tkinclude}" != x ; then
-           if test -f "${with_tkinclude}/tk.h" ; then
-               ac_cv_c_tkh=${with_tkinclude}
-           else
-               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tk was built as a framework, attempt to use
-               # the framework's Headers directory.
-               case ${TK_DEFS} in
-                   *TK_FRAMEWORK*)
-                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tk is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TK_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tk's --prefix location,
-           # relative to directory of tkConfig.sh, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
-               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TK_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tk.h" ; then
-                   ac_cv_c_tkh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tkh}" = x ; then
-       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tkh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
-
-    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TK_INCLUDES)
-
-    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-       # On Windows and Aqua, we need the X compat headers
-       AC_MSG_CHECKING([for X11 header files])
-       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
-           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
-           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-           AC_SUBST(TK_XINCLUDES)
-       fi
-       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_CONFIG --
-#
-#      Locate the ${1}Config.sh file and perform a sanity check on
-#      the ${1} compile flags.  These are used by packages like
-#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-$1=...
-#
-#      Defines the following vars:
-#              $1_BIN_DIR      Full path to the directory containing
-#                              the $1Config.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_CONFIG], [
-    #
-    # Ok, lets find the $1 configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-$1
-    #
-
-    if test x"${no_$1}" = x ; then
-       # we reset no_$1 in case something fails here
-       no_$1=true
-       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
-       AC_MSG_CHECKING([for $1 configuration])
-       AC_CACHE_VAL(ac_cv_c_$1config,[
-
-           # First check to see if --with-$1 was specified.
-           if test x"${with_$1config}" != x ; then
-               case ${with_$1config} in
-                   */$1Config.sh )
-                       if test -f ${with_$1config}; then
-                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
-                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
-                       fi;;
-               esac
-               if test -f "${with_$1config}/$1Config.sh" ; then
-                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
-               else
-                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
-               fi
-           fi
-
-           # then check for a private $1 installation
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in \
-                       ../$1 \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../$1 \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../$1 \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ${srcdir}/../$1 \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-                   if test -f "$i/unix/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_$1config}" = x ; then
-           $1_BIN_DIR="# no $1 configs found"
-           AC_MSG_WARN([Cannot find $1 configuration definitions])
-           exit 0
-       else
-           no_$1=
-           $1_BIN_DIR=${ac_cv_c_$1config}
-           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG --
-#
-#      Load the $1Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              $1_SRC_DIR
-#              $1_LIB_FILE
-#              $1_LIB_SPEC
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_CONFIG], [
-    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
-
-    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${$1_BIN_DIR}/$1Config.sh"
-    else
-        AC_MSG_RESULT([file not found])
-    fi
-
-    #
-    # If the $1_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable $1_LIB_SPEC will be set to the value
-    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
-    # instead of $1_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    #
-
-    if test -f "${$1_BIN_DIR}/Makefile" ; then
-       AC_MSG_WARN([Found Makefile - using build library specs for $1])
-        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
-        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
-        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
-        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
-        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
-    fi
-
-    AC_SUBST($1_VERSION)
-    AC_SUBST($1_BIN_DIR)
-    AC_SUBST($1_SRC_DIR)
-
-    AC_SUBST($1_LIB_FILE)
-    AC_SUBST($1_LIB_SPEC)
-
-    AC_SUBST($1_STUB_LIB_FILE)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    # Allow the caller to prevent this auto-check by specifying any 2nd arg
-    AS_IF([test "x$2" = x], [
-       # Check both upper and lower-case variants
-       # If a dev wanted non-stubs libs, this function could take an option
-       # to not use _STUB in the paths below
-       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
-           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
-           [TEA_LOAD_CONFIG_LIB($1_STUB)])
-    ])
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG_LIB --
-#
-#      Helper function to load correct library from another extension's
-#      ${PACKAGE}Config.sh.
-#
-# Results:
-#      Adds to LIBS the appropriate extension library
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
-    AC_MSG_CHECKING([For $1 library for LIBS])
-    # This simplifies the use of stub libraries by automatically adding
-    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
-    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
-    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
-    if test "x${$1_LIB_SPEC}" != "x" ; then
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
-           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
-           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
-       else
-           TEA_ADD_LIBS([${$1_LIB_SPEC}])
-           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
-       fi
-    else
-       AC_MSG_RESULT([file not found])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_EXPORT_CONFIG --
-#
-#      Define the data to insert into the ${PACKAGE}Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1
-#
-# Results:
-#      Substitutes the following vars:
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_EXPORT_CONFIG], [
-    #--------------------------------------------------------------------
-    # These are for $1Config.sh
-    #--------------------------------------------------------------------
-
-    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
-    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
-    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
-    else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-    fi
-    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
-    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
-    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
-    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
-
-    AC_SUBST($1_BUILD_LIB_SPEC)
-    AC_SUBST($1_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_PATH)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    AC_SUBST(MAJOR_VERSION)
-    AC_SUBST(MINOR_VERSION)
-    AC_SUBST(PATCHLEVEL)
-])
-
-
-#------------------------------------------------------------------------
-# TEA_INSTALLER --
-#
-#      Configure the installer.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              INSTALL
-#              INSTALL_DATA_DIR
-#              INSTALL_DATA
-#              INSTALL_PROGRAM
-#              INSTALL_SCRIPT
-#              INSTALL_LIBRARY
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INSTALLER], [
-    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
-    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
-    INSTALL_DATA='${INSTALL} -m 644'
-    INSTALL_PROGRAM='${INSTALL} -m 755'
-    INSTALL_SCRIPT='${INSTALL} -m 755'
-
-    TEA_CONFIG_SYSTEM
-    case $system in
-       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
-             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
-    esac
-
-    AC_SUBST(INSTALL)
-    AC_SUBST(INSTALL_DATA_DIR)
-    AC_SUBST(INSTALL_DATA)
-    AC_SUBST(INSTALL_PROGRAM)
-    AC_SUBST(INSTALL_SCRIPT)
-    AC_SUBST(INSTALL_LIBRARY)
-])
-
-###
-# Tip 430 - ZipFS Modifications
-###
-#------------------------------------------------------------------------
-# SC_ZIPFS_SUPPORT
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#              TCL_ZIPFS_FLAG
-#              ZIP_PROG
-#------------------------------------------------------------------------
-
-#------------------------------------------------------------------------
-# SC_PROG_ZIP
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              ZIP_PROG
-#       ZIP_PROG_OPTIONS
-#       ZIP_PROG_VFSSEARCH
-#       ZIP_INSTALL_OBJS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ZIPFS_SUPPORT], [
-    AC_MSG_CHECKING([for zipfs support])
-    ZIP_PROG=""
-    ZIP_PROG_OPTIONS=""
-    ZIP_PROG_VFSSEARCH=""
-    INSTALL_MSGS=""
-    # If our native tclsh processes the "install" command line option
-    # we can use it to mint zip files
-    AS_IF([$TCLSH_PROG install],[
-      ZIP_PROG=${TCLSH_PROG}
-      ZIP_PROG_OPTIONS="install mkzip"
-      ZIP_PROG_VFSSEARCH="."
-      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
-    ])
-    if test "x$ZIP_PROG" = "x" ; then
-        AC_CACHE_VAL(ac_cv_path_zip, [
-        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
-        for dir in $search_path ; do
-            for j in `ls -r $dir/zip 2> /dev/null` \
-                `ls -r $dir/zip 2> /dev/null` ; do
-            if test x"$ac_cv_path_zip" = x ; then
-                if test -f "$j" ; then
-                ac_cv_path_zip=$j
-                break
-                fi
-            fi
-            done
-        done
-        ])
-        if test -f "$ac_cv_path_zip" ; then
-            ZIP_PROG="$ac_cv_path_zip "
-            AC_MSG_RESULT([$ZIP_PROG])
-            ZIP_PROG_OPTIONS="-rq"
-            ZIP_PROG_VFSSEARCH="."
-            AC_MSG_RESULT([Found INFO Zip in environment])
-            # Use standard arguments for zip
-        fi
-    fi
-    if test "x$ZIP_PROG" = "x" ; then
-           # It is not an error if an installed version of Zip can't be located.
-        ZIP_PROG=""
-        ZIP_PROG_OPTIONS=""
-        ZIP_PROG_VFSSEARCH=""
-        TCL_ZIPFS_SUPPORT=0
-        TCL_ZIPFS_FLAG=
-    else
-        # ZIPFS Support
-       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
-       if test ${TCL_ZIP_FILE} = "" ; then
-          TCL_ZIPFS_SUPPORT=0
-          TCL_ZIPFS_FLAG=
-          INSTALL_LIBRARIES=install-libraries
-          INSTALL_MSGS=install-msgs
-       else
-           if test ${SHARED_BUILD} = 1 ; then
-              TCL_ZIPFS_SUPPORT=1
-              INSTALL_LIBRARIES=install-libraries-zipfs-shared
-           else
-              TCL_ZIPFS_SUPPORT=2
-              INSTALL_LIBRARIES=install-libraries-zipfs-static
-           fi
-          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
-       fi
-    fi
-
-    AC_SUBST(TCL_ZIP_FILE)
-    AC_SUBST(TCL_ZIPFS_SUPPORT)
-    AC_SUBST(TCL_ZIPFS_FLAG)
-    AC_SUBST(ZIP_PROG)
-    AC_SUBST(ZIP_PROG_OPTIONS)
-    AC_SUBST(ZIP_PROG_VFSSEARCH)
-    AC_SUBST(INSTALL_LIBRARIES)
-    AC_SUBST(INSTALL_MSGS)
-])
-
-# Local Variables:
-# mode: autoconf
-# End:
diff --git a/pkgs/tdbcsqlite3-1.1.1/win/rules.vc b/pkgs/tdbcsqlite3-1.1.1/win/rules.vc
deleted file mode 100644 (file)
index b1a0346..0000000
+++ /dev/null
@@ -1,1807 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# rules.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file does all the hard work in terms of parsing build options,\r
-# compiler switches, defining common targets and macros. The Tcl makefile\r
-# directly includes this. Extensions include it via "rules-ext.vc".\r
-#\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
-# detailed documentation.\r
-#\r
-# See the file "license.terms" for information on usage and redistribution\r
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
-#\r
-# Copyright (c) 2001-2003 David Gravereaux.\r
-# Copyright (c) 2003-2008 Patrick Thoyts\r
-# Copyright (c) 2017      Ashok P. Nadkarni\r
-#------------------------------------------------------------------------------\r
-\r
-!ifndef _RULES_VC\r
-_RULES_VC = 1\r
-\r
-# The following macros define the version of the rules.vc nmake build system\r
-# For modifications that are not backward-compatible, you *must* change\r
-# the major version.\r
-RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
-\r
-# The PROJECT macro must be defined by parent makefile.\r
-!if "$(PROJECT)" == ""\r
-!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
-!endif\r
-\r
-!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
-PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
-!endif\r
-\r
-# Also special case Tcl and Tk to save some typing later\r
-DOING_TCL = 0\r
-DOING_TK  = 0\r
-!if "$(PROJECT)" == "tcl"\r
-DOING_TCL = 1\r
-!elseif "$(PROJECT)" == "tk"\r
-DOING_TK = 1\r
-!endif\r
-\r
-!ifndef NEED_TK\r
-# Backwards compatibility\r
-!ifdef PROJECT_REQUIRES_TK\r
-NEED_TK = $(PROJECT_REQUIRES_TK)\r
-!else\r
-NEED_TK = 0\r
-!endif\r
-!endif\r
-\r
-!ifndef NEED_TCL_SOURCE\r
-NEED_TCL_SOURCE = 0\r
-!endif\r
-\r
-!ifdef NEED_TK_SOURCE\r
-!if $(NEED_TK_SOURCE)\r
-NEED_TK = 1\r
-!endif\r
-!else\r
-NEED_TK_SOURCE = 0\r
-!endif\r
-\r
-################################################################\r
-# Nmake is a pretty weak environment in syntax and capabilities\r
-# so this file is necessarily verbose. It's broken down into\r
-# the following parts.\r
-#\r
-# 0. Sanity check that compiler environment is set up and initialize\r
-#    any built-in settings from the parent makefile\r
-# 1. First define the external tools used for compiling, copying etc.\r
-#    as this is independent of everything else.\r
-# 2. Figure out our build structure in terms of the directory, whether\r
-#    we are building Tcl or an extension, etc.\r
-# 3. Determine the compiler and linker versions\r
-# 4. Build the nmakehlp helper application\r
-# 5. Determine the supported compiler options and features\r
-# 6. Parse the OPTS macro value for user-specified build configuration\r
-# 7. Parse the STATS macro value for statistics instrumentation\r
-# 8. Parse the CHECKS macro for additional compilation checks\r
-# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
-# 10. Based on this selected configuration, construct the output\r
-#     directory and file paths\r
-# 11. Construct the paths where the package is to be installed\r
-# 12. Set up the actual options passed to compiler and linker based\r
-#     on the information gathered above.\r
-# 13. Define some standard build targets and implicit rules. These may\r
-#     be optionally disabled by the parent makefile.\r
-# 14. (For extensions only.) Compare the configuration of the target\r
-#     Tcl and the extensions and warn against discrepancies.\r
-#\r
-# One final note about the macro names used. They are as they are\r
-# for historical reasons. We would like legacy extensions to\r
-# continue to work with this make include file so be wary of\r
-# changing them for consistency or clarity.\r
-\r
-# 0. Sanity check compiler environment\r
-\r
-# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
-# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
-\r
-!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
-MSG = ^\r
-Visual C++ compiler environment not initialized.\r
-!error $(MSG)\r
-!endif\r
-\r
-# We need to run from the directory the parent makefile is located in.\r
-# nmake does not tell us what makefile was used to invoke it so parent\r
-# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
-# warn if we think that is not the case.\r
-!if "$(MAKEFILEVC)" == ""\r
-\r
-!if exist("$(PROJECT).vc")\r
-MAKEFILEVC = $(PROJECT).vc\r
-!elseif exist("makefile.vc")\r
-MAKEFILEVC = makefile.vc\r
-!endif\r
-!endif # "$(MAKEFILEVC)" == ""\r
-\r
-!if !exist("$(MAKEFILEVC)")\r
-MSG = ^\r
-You must run nmake from the directory containing the project makefile.^\r
-If you are doing that and getting this message, set the MAKEFILEVC^\r
-macro to the name of the project makefile.\r
-!message WARNING: $(MSG)\r
-!endif\r
-\r
-\r
-################################################################\r
-# 1. Define external programs being used\r
-\r
-#----------------------------------------------------------\r
-# Set the proper copy method to avoid overwrite questions\r
-# to the user when copying files and selecting the right\r
-# "delete all" method.\r
-#----------------------------------------------------------\r
-\r
-RMDIR  = rmdir /S /Q\r
-CPY    = xcopy /i /y >NUL\r
-CPYDIR  = xcopy /e /i /y >NUL\r
-COPY   = copy /y >NUL\r
-MKDIR   = mkdir\r
-\r
-######################################################################\r
-# 2. Figure out our build environment in terms of what we're building.\r
-#\r
-# (a) Tcl itself\r
-# (b) Tk\r
-# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
-# (d) a Tcl extension using libraries/includes from Tcl source directory\r
-#\r
-# This last is needed because some extensions still need\r
-# some Tcl interfaces that are not publicly exposed.\r
-#\r
-# The fragment will set the following macros:\r
-# ROOT - root of this module sources\r
-# COMPATDIR - source directory that holds compatibility sources\r
-# DOCDIR - source directory containing documentation files\r
-# GENERICDIR - platform-independent source directory\r
-# WINDIR - Windows-specific source directory\r
-# TESTDIR - directory containing test files\r
-# TOOLSDIR - directory containing build tools\r
-# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
-#    when building Tcl itself.\r
-# _INSTALLDIR - native form of the installation path. For Tcl\r
-#    this will be the root of the Tcl installation. For extensions\r
-#    this will be the lib directory under the root.\r
-# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
-#    headers and libraries from an installed Tcl, and 0 if built against\r
-#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
-#    named.\r
-# _TCL_H - native path to the tcl.h file\r
-#\r
-# If Tk is involved, also sets the following\r
-# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
-#    Tk itself.\r
-# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
-# _TK_H - native path to the tk.h file\r
-\r
-# Root directory for sources and assumed subdirectories\r
-ROOT = $(MAKEDIR)\..\r
-# The following paths CANNOT have spaces in them as they appear on the\r
-# left side of implicit rules.\r
-!ifndef COMPATDIR\r
-COMPATDIR      = $(ROOT)\compat\r
-!endif\r
-!ifndef DOCDIR\r
-DOCDIR         = $(ROOT)\doc\r
-!endif\r
-!ifndef GENERICDIR\r
-GENERICDIR     = $(ROOT)\generic\r
-!endif\r
-!ifndef TOOLSDIR\r
-TOOLSDIR       = $(ROOT)\tools\r
-!endif\r
-!ifndef TESTDIR\r
-TESTDIR        = $(ROOT)\tests\r
-!endif\r
-!ifndef LIBDIR\r
-!if exist("$(ROOT)\library")\r
-LIBDIR          = $(ROOT)\library\r
-!else\r
-LIBDIR          = $(ROOT)\lib\r
-!endif\r
-!endif\r
-!ifndef DEMODIR\r
-!if exist("$(LIBDIR)\demos")\r
-DEMODIR                = $(LIBDIR)\demos\r
-!else\r
-DEMODIR                = $(ROOT)\demos\r
-!endif\r
-!endif # ifndef DEMODIR\r
-# Do NOT enclose WINDIR in a !ifndef because Windows always defines\r
-# WINDIR env var to point to c:\windows!\r
-# TBD - This is a potentially dangerous conflict, rename WINDIR to\r
-# something else\r
-WINDIR         = $(ROOT)\win\r
-\r
-!ifndef RCDIR\r
-!if exist("$(WINDIR)\rc")\r
-RCDIR           = $(WINDIR)\rc\r
-!else\r
-RCDIR           = $(WINDIR)\r
-!endif\r
-!endif\r
-RCDIR = $(RCDIR:/=\)\r
-\r
-# The target directory where the built packages and binaries will be installed.\r
-# INSTALLDIR is the (optional) path specified by the user.\r
-# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
-!ifdef INSTALLDIR\r
-### Fix the path separators.\r
-_INSTALLDIR    = $(INSTALLDIR:/=\)\r
-!else\r
-### Assume the normal default.\r
-_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
-!endif\r
-\r
-!if $(DOING_TCL)\r
-\r
-# BEGIN Case 2(a) - Building Tcl itself\r
-\r
-# Only need to define _TCL_H\r
-_TCL_H = ..\generic\tcl.h\r
-\r
-# END Case 2(a) - Building Tcl itself\r
-\r
-!elseif $(DOING_TK)\r
-\r
-# BEGIN Case 2(b) - Building Tk\r
-\r
-TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
-!if "$(TCLDIR)" == ""\r
-!if [echo TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-!endif # TCLDIR == ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
-!if !exist("$(_TCL_H)")\r
-!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
-!endif\r
-\r
-_TK_H = ..\generic\tk.h\r
-\r
-# END Case 2(b) - Building Tk\r
-\r
-!else\r
-\r
-# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
-\r
-# If command line has specified Tcl location through TCLDIR, use it\r
-# else default to the INSTALLDIR setting\r
-!if "$(TCLDIR)" != ""\r
-\r
-_TCLDIR        = $(TCLDIR:/=\)\r
-!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
-TCLINSTALL     = 1\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
-TCLINSTALL     = 0\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-!endif\r
-\r
-!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
-\r
-TCLINSTALL     = 1\r
-TCLDIR          = $(_INSTALLDIR)\..\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TCLDIR                = $(_INSTALLDIR)\..\r
-_TCL_H          = $(_TCLDIR)\include\tcl.h\r
-\r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!if [echo _TCLDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
-!error *** Could not locate Tcl source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TCLINSTALL      = 0\r
-TCLDIR         = $(_TCLDIR)\r
-_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
-\r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
-\r
-!endif # TCLDIR\r
-\r
-!ifndef _TCL_H\r
-MSG =^\r
-Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-# Now do the same to locate Tk headers and libs if project requires Tk\r
-!if $(NEED_TK)\r
-\r
-!if "$(TKDIR)" != ""\r
-\r
-_TKDIR = $(TKDIR:/=\)\r
-!if exist("$(_TKDIR)\include\tk.h")\r
-TKINSTALL      = 1\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-!elseif exist("$(_TKDIR)\generic\tk.h")\r
-TKINSTALL      = 0\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-!endif\r
-\r
-!else # TKDIR not defined\r
-\r
-# Need to locate Tcl depending on whether it needs Tcl source or not.\r
-# If we don't, check the INSTALLDIR for an installed Tcl first\r
-\r
-!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-TKINSTALL      = 1\r
-# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
-# later so the \.. accounts for the /lib\r
-_TKDIR         = $(_INSTALLDIR)\..\r
-_TK_H          = $(_TKDIR)\include\tk.h\r
-TKDIR          = $(_TKDIR)\r
-\r
-!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!if [echo _TKDIR = \> nmakehlp.out] \\r
-   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
-!error *** Could not locate Tk source directory.\r
-!endif\r
-!include nmakehlp.out\r
-TKINSTALL      = 0\r
-TKDIR          = $(_TKDIR)\r
-_TK_H          = $(_TKDIR)\generic\tk.h\r
-\r
-!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
-\r
-!endif # TKDIR\r
-\r
-!ifndef _TK_H\r
-MSG =^\r
-Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
-!error $(MSG)\r
-!endif\r
-\r
-!endif # NEED_TK\r
-\r
-!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tcl.^\r
-*** Please set the TCLDIR macro to point to the Tcl sources.\r
-!error $(MSG)\r
-!endif\r
-\r
-!if $(NEED_TK_SOURCE)\r
-!if $(TKINSTALL)\r
-MSG = ^\r
-*** Warning: This extension requires the source distribution of Tk.^\r
-*** Please set the TKDIR macro to point to the Tk sources.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-\r
-# If INSTALLDIR set to Tcl installation root dir then reset to the\r
-# lib dir for installing extensions\r
-!if exist("$(_INSTALLDIR)\include\tcl.h")\r
-_INSTALLDIR=$(_INSTALLDIR)\lib\r
-!endif\r
-\r
-# END Case 2(c) or (d) - Building an extension\r
-!endif # if $(DOING_TCL)\r
-\r
-################################################################\r
-# 3. Determine compiler version and architecture\r
-# In this section, we figure out the compiler version and the\r
-# architecture for which we are building. This sets the\r
-# following macros:\r
-# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
-#     This is also printed by the compiler in dotted form 19.10 etc.\r
-# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
-#     compiler version 1200. This is kept only for legacy reasons as it\r
-#     does not make sense for recent Microsoft compilers. Only used for\r
-#     output directory names.\r
-# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
-# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
-# MACHINE - same as $(ARCH) - legacy\r
-# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
-\r
-cc32           = $(CC)   # built-in default.\r
-link32         = link\r
-lib32          = lib\r
-rc32           = $(RC)   # built-in default.\r
-\r
-#----------------------------------------------------------------\r
-# Figure out the compiler architecture and version by writing\r
-# the C macros to a file, preprocessing them with the C\r
-# preprocessor and reading back the created file\r
-\r
-_HASH=^#\r
-_VC_MANIFEST_EMBED_EXE=\r
-_VC_MANIFEST_EMBED_DLL=\r
-VCVER=0\r
-!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
-    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
-    && ![echo ARCH=IX86 >> vercl.x] \\r
-    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
-    && ![echo ARCH=AMD64 >> vercl.x] \\r
-    && ![echo $(_HASH)endif >> vercl.x] \\r
-    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
-!include vercl.i\r
-!if $(VCVERSION) < 1900\r
-!if ![echo VCVER= ^\> vercl.vc] \\r
-    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
-!include vercl.vc\r
-!endif\r
-!else\r
-# The simple calculation above does not apply to new Visual Studio releases\r
-# Keep the compiler version in its native form.\r
-VCVER = $(VCVERSION)\r
-!endif\r
-!endif\r
-\r
-!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# The MACHINE macro is used by legacy makefiles so set it as well\r
-!ifdef MACHINE\r
-!if "$(MACHINE)" == "x86"\r
-!undef MACHINE\r
-MACHINE = IX86\r
-!elseif "$(MACHINE)" == "x64"\r
-!undef MACHINE\r
-MACHINE = AMD64\r
-!endif\r
-!if "$(MACHINE)" != "$(ARCH)"\r
-!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
-!endif\r
-!else\r
-MACHINE=$(ARCH)\r
-!endif\r
-\r
-#---------------------------------------------------------------\r
-# The PLATFORM_IDENTIFY macro matches the values returned by\r
-# the Tcl platform::identify command\r
-!if "$(MACHINE)" == "AMD64"\r
-PLATFORM_IDENTIFY = win32-x86_64\r
-!else\r
-PLATFORM_IDENTIFY = win32-ix86\r
-!endif\r
-\r
-# The MULTIPLATFORM macro controls whether binary extensions are installed\r
-# in platform-specific directories. Intended to be set/used by extensions.\r
-!ifndef MULTIPLATFORM_INSTALL\r
-MULTIPLATFORM_INSTALL = 0\r
-!endif\r
-\r
-#------------------------------------------------------------\r
-# Figure out the *host* architecture by reading the registry\r
-\r
-!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
-NATIVE_ARCH=IX86\r
-!else\r
-NATIVE_ARCH=AMD64\r
-!endif\r
-\r
-# Since MSVC8 we must deal with manifest resources.\r
-!if $(VCVERSION) >= 1400\r
-_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
-_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
-!endif\r
-\r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
-################################################################\r
-# 4. Build the nmakehlp program\r
-# This is a helper app we need to overcome nmake's limiting\r
-# environment. We will call out to it to get various bits of\r
-# information about supported compiler options etc.\r
-#\r
-# Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
-#\r
-# Extensions built against an installed Tcl will use the installed\r
-# copy of Tcl's nmakehlp.c if there is one and their own version\r
-# otherwise. In the latter case, they would also be using their own\r
-# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
-# or rules.vc.\r
-#\r
-# Extensions built against Tcl sources will use the one from the Tcl source.\r
-#\r
-# When building an extension using a sufficiently new version of Tcl,\r
-# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
-# copy of nmakehlp.c to be used.\r
-\r
-!ifndef NMAKEHLPC\r
-# Default to the one in the current directory (the extension's own nmakehlp.c)\r
-NMAKEHLPC = nmakehlp.c\r
-\r
-!if !$(DOING_TCL)\r
-!if $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
-!endif\r
-!else # ! $(TCLINSTALL)\r
-!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
-NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
-!endif\r
-!endif # $(TCLINSTALL)\r
-!endif # !$(DOING_TCL)\r
-\r
-!endif # NMAKEHLPC\r
-\r
-# We always build nmakehlp even if it exists since we do not know\r
-# what source it was built from.\r
-!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
-!endif\r
-\r
-################################################################\r
-# 5. Test for compiler features\r
-# Visual C++ compiler options have changed over the years. Check\r
-# which options are supported by the compiler in use.\r
-#\r
-# The following macros are set:\r
-# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
-# DEBUGFLAGS - the compiler flags to be used for debug builds\r
-# LINKERFLAGS - Flags passed to the linker\r
-#\r
-# Note that these are the compiler settings *available*, not those\r
-# that will be *used*. The latter depends on the OPTS macro settings\r
-# which we have not yet parsed.\r
-#\r
-# Also note that some of the flags in OPTIMIZATIONS are not really\r
-# related to optimization. They are placed there only for legacy reasons\r
-# as some extensions expect them to be included in that macro.\r
-\r
-# -Op improves float consistency. Note only needed for older compilers\r
-# Newer compilers do not need or support this option.\r
-!if [nmakehlp -c -Op]\r
-FPOPTS  = -Op\r
-!endif\r
-\r
-# Strict floating point semantics - present in newer compilers in lieu of -Op\r
-!if [nmakehlp -c -fp:strict]\r
-FPOPTS  = $(FPOPTS) -fp:strict\r
-!endif\r
-\r
-!if "$(MACHINE)" == "IX86"\r
-### test for pentium errata\r
-!if [nmakehlp -c -QI0f]\r
-!message *** Compiler has 'Pentium 0x0f fix'\r
-FPOPTS  = $(FPOPTS) -QI0f\r
-!else\r
-!message *** Compiler does not have 'Pentium 0x0f fix'\r
-!endif\r
-!endif\r
-\r
-### test for optimizations\r
-# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
-# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
-# stack probe at *every* function entry, not just those with more than\r
-# a page of stack allocation resulting in a performance hit.  However,\r
-# /O2 documentation is misleading as its stack probes are simply the\r
-# default page size locals allocation probes and not what is implied\r
-# by an explicit /Gs option.\r
-\r
-OPTIMIZATIONS = $(FPOPTS)\r
-\r
-!if [nmakehlp -c -O2]\r
-OPTIMIZING = 1\r
-OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
-!else\r
-# Legacy, really. All modern compilers support this\r
-!message *** Compiler does not have 'Optimizations'\r
-OPTIMIZING = 0\r
-!endif\r
-\r
-# Checks for buffer overflows in local arrays\r
-!if [nmakehlp -c -GS]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
-!endif\r
-\r
-# Link time optimization. Note that this option (potentially) makes\r
-# generated libraries only usable by the specific VC++ version that\r
-# created it. Requires /LTCG linker option\r
-!if [nmakehlp -c -GL]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
-CC_GL_OPT_ENABLED = 1\r
-!else\r
-# In newer compilers -GL and -YX are incompatible.\r
-!if [nmakehlp -c -YX]\r
-OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
-!endif\r
-!endif # [nmakehlp -c -GL]\r
-\r
-DEBUGFLAGS     = $(FPOPTS)\r
-\r
-# Run time error checks. Not available or valid in a release, non-debug build\r
-# RTC is for modern compilers, -GZ is legacy\r
-!if [nmakehlp -c -RTC1]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
-!elseif [nmakehlp -c -GZ]\r
-DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
-!endif\r
-\r
-#----------------------------------------------------------------\r
-# Linker flags\r
-\r
-# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
-# if the linker supports a specific option. Without these flags link will\r
-# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
-# They are not passed through to the actual application / extension\r
-# link rules.\r
-!ifndef LINKER_TESTFLAGS\r
-LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
-!endif\r
-\r
-LINKERFLAGS     =\r
-\r
-# If compiler has enabled link time optimization, linker must too with -ltcg\r
-!ifdef CC_GL_OPT_ENABLED\r
-!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
-!endif\r
-!endif\r
-\r
-########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
-# Based on this, we will construct the actual switches to be passed to the\r
-# compiler and linker using the macros defined in the previous section.\r
-# The following macros are defined by this section based on OPTS\r
-# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
-#                1 -> build as a static library and shell\r
-# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
-# DEBUG - 1 -> debug build, 0 -> release builds\r
-# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
-# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
-# PGO     - 1 -> profile based optimization, 0 -> no\r
-# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
-#           0 -> link to static C runtime for static Tcl build.\r
-#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
-# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
-# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
-#           0 -> Use the non-thread allocator.\r
-# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
-#           C runtime, 0 -> use the debug C runtime.\r
-# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
-# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
-#           configuration (ignored for Tcl itself)\r
-# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
-# Further, LINKERFLAGS are modified based on above.\r
-\r
-# Default values for all the above\r
-STATIC_BUILD   = 0\r
-TCL_THREADS    = 1\r
-DEBUG          = 0\r
-SYMBOLS                = 0\r
-PROFILE                = 0\r
-PGO            = 0\r
-MSVCRT         = 1\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-USE_THREAD_ALLOC = 1\r
-UNCHECKED      = 0\r
-CONFIG_CHECK    = 1\r
-!if $(DOING_TCL)\r
-USE_STUBS       = 0\r
-!else\r
-USE_STUBS       = 1\r
-!endif\r
-\r
-# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
-# set the above macros based on OPTS content\r
-!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
-\r
-# OPTS are specified, parse them\r
-\r
-!if [nmakehlp -f $(OPTS) "static"]\r
-!message *** Doing static\r
-STATIC_BUILD   = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nostubs"]\r
-!message *** Not using stubs\r
-USE_STUBS      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-!message *** Doing nomsvcrt\r
-MSVCRT         = 0\r
-!else\r
-!if [nmakehlp -f $(OPTS) "msvcrt"]\r
-!message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
-!else\r
-MSVCRT         = 0\r
-!endif\r
-!endif\r
-!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
-\r
-!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
-!message *** Doing staticpkg\r
-TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "nothreads"]\r
-!message *** Compile explicitly for non-threaded tcl\r
-TCL_THREADS = 0\r
-USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "time64bit"]\r
-!message *** Force 64-bit time_t\r
-_USE_64BIT_TIME_T = 1\r
-!endif\r
-\r
-# Yes, it's weird that the "symbols" option controls DEBUG and\r
-# the "pdbs" option controls SYMBOLS. That's historical.\r
-!if [nmakehlp -f $(OPTS) "symbols"]\r
-!message *** Doing symbols\r
-DEBUG          = 1\r
-!else\r
-DEBUG          = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pdbs"]\r
-!message *** Doing pdbs\r
-SYMBOLS                = 1\r
-!else\r
-SYMBOLS                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "profile"]\r
-!message *** Doing profile\r
-PROFILE                = 1\r
-!else\r
-PROFILE                = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "pgi"]\r
-!message *** Doing profile guided optimization instrumentation\r
-PGO            = 1\r
-!elseif [nmakehlp -f $(OPTS) "pgo"]\r
-!message *** Doing profile guided optimization\r
-PGO            = 2\r
-!else\r
-PGO            = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "loimpact"]\r
-!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
-!endif\r
-\r
-# TBD - should get rid of this option\r
-!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
-!message *** Doing thrdalloc\r
-USE_THREAD_ALLOC = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "tclalloc"]\r
-USE_THREAD_ALLOC = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "unchecked"]\r
-!message *** Doing unchecked\r
-UNCHECKED = 1\r
-!else\r
-UNCHECKED = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
-CONFIG_CHECK = 1\r
-!else\r
-CONFIG_CHECK = 0\r
-!endif\r
-\r
-!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
-\r
-# Set linker flags based on above\r
-\r
-!if $(PGO) > 1\r
-!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!elseif $(PGO) > 0\r
-!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
-!else\r
-MSG=^\r
-This compiler does not support profile guided optimization.\r
-!error $(MSG)\r
-!endif\r
-!endif\r
-\r
-################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
-# The following macros are set by this section:\r
-# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
-#                 0 -> disables\r
-# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
-#                     0 -> disables\r
-\r
-# Default both are off\r
-TCL_MEM_DEBUG      = 0\r
-TCL_COMPILE_DEBUG   = 0\r
-\r
-!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
-\r
-!if [nmakehlp -f $(STATS) "memdbg"]\r
-!message *** Doing memdbg\r
-TCL_MEM_DEBUG      = 1\r
-!else\r
-TCL_MEM_DEBUG      = 0\r
-!endif\r
-\r
-!if [nmakehlp -f $(STATS) "compdbg"]\r
-!message *** Doing compdbg\r
-TCL_COMPILE_DEBUG   = 1\r
-!else\r
-TCL_COMPILE_DEBUG   = 0\r
-!endif\r
-\r
-!endif\r
-\r
-####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
-# The following macros are set by this section:\r
-# WARNINGS - compiler switches that control the warnings level\r
-# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
-#                     0 -> enable deprecated functions\r
-\r
-# Defaults - Permit deprecated functions and warning level 3\r
-TCL_NO_DEPRECATED          = 0\r
-WARNINGS                   = -W3\r
-\r
-!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
-\r
-!if [nmakehlp -f $(CHECKS) "nodep"]\r
-!message *** Doing nodep check\r
-TCL_NO_DEPRECATED          = 1\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
-!message *** Doing full warnings check\r
-WARNINGS                   = -W4\r
-!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
-LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
-!endif\r
-!endif\r
-\r
-!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
-!message *** Doing 64bit portability warnings\r
-WARNINGS                   = $(WARNINGS) -Wp64\r
-!endif\r
-\r
-!endif\r
-\r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
-\r
-################################################################\r
-# 10. Construct output directory and file paths\r
-# Figure-out how to name our intermediate and output directories.\r
-# In order to avoid inadvertent mixing of object files built using\r
-# different compilers, build configurations etc.,\r
-#\r
-# Naming convention (suffixes):\r
-#   t = full thread support. (Not used for Tcl >= 8.7)\r
-#   s = static library (as opposed to an import library)\r
-#   g = linked to the debug enabled C run-time.\r
-#   x = special static build when it links to the dynamic C run-time.\r
-#\r
-# The following macros are set in this section:\r
-# SUFX - the suffix to use for binaries based on above naming convention\r
-# BUILDDIRTOP - the toplevel default output directory\r
-#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
-# TMP_DIR - directory where object files are created\r
-# OUT_DIR - directory where output executables are created\r
-# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
-# parent makefile (or command line). The default values are\r
-# based on BUILDDIRTOP.\r
-# STUBPREFIX - name of the stubs library for this project\r
-# PRJIMPLIB - output path of the generated project import library\r
-# PRJLIBNAME - name of generated project library\r
-# PRJLIB     - output path of generated project library\r
-# PRJSTUBLIBNAME - name of the generated project stubs library\r
-# PRJSTUBLIB - output path of the generated project stubs library\r
-# RESFILE - output resource file (only if not static build)\r
-\r
-SUFX       = tsgx\r
-\r
-!if $(DEBUG)\r
-BUILDDIRTOP = Debug\r
-!else\r
-BUILDDIRTOP = Release\r
-!endif\r
-\r
-!if "$(MACHINE)" != "IX86"\r
-BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
-!endif\r
-!if $(VCVER) > 6\r
-BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
-!endif\r
-\r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
-SUFX       = $(SUFX:g=)\r
-!endif\r
-\r
-TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
-\r
-!if !$(STATIC_BUILD)\r
-TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
-SUFX       = $(SUFX:s=)\r
-EXT        = dll\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!else\r
-TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
-EXT        = lib\r
-!if !$(MSVCRT)\r
-TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
-SUFX       = $(SUFX:x=)\r
-!endif\r
-!endif\r
-\r
-!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
-TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
-SUFX       = $(SUFX:t=)\r
-!endif\r
-\r
-!ifndef TMP_DIR\r
-TMP_DIR            = $(TMP_DIRFULL)\r
-!ifndef OUT_DIR\r
-OUT_DIR            = .\$(BUILDDIRTOP)\r
-!endif\r
-!else\r
-!ifndef OUT_DIR\r
-OUT_DIR            = $(TMP_DIR)\r
-!endif\r
-!endif\r
-\r
-# Relative paths -> absolute\r
-!if [echo OUT_DIR = \> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
-!endif\r
-!if [echo TMP_DIR = \>> nmakehlp.out] \\r
-   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
-!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
-!endif\r
-!include nmakehlp.out\r
-\r
-# The name of the stubs library for the project being built\r
-STUBPREFIX      = $(PROJECT)stub\r
-\r
-# Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
-\r
-TCLSHNAME       = $(PROJECT)sh$(TCL_VERSION)$(SUFX).exe\r
-TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
-TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
-\r
-TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
-TCL_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-\r
-# When building extensions, we need to locate tclsh. Depending on version\r
-# of Tcl we are building against, this may or may not have a "t" suffix.\r
-# Try various possibilities in turn.\r
-TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist("$(TCLSH)") && $(TCL_THREADS)\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist("$(TCLSH)")\r
-TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-\r
-TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\lib\r
-TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
-TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
-\r
-!else # Building against Tcl sources\r
-\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX).exe\r
-!if !exist($(TCLSH)) && $(TCL_THREADS)\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX).exe\r
-!endif\r
-!if !exist($(TCLSH))\r
-TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
-!endif\r
-TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX).lib\r
-# When building extensions, may be linking against Tcl that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TCLIMPLIB)")\r
-TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
-!endif\r
-TCL_LIBRARY    = $(_TCLDIR)\library\r
-TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
-TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
-TCLTOOLSDIR    = $(_TCLDIR)\tools\r
-TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
-\r
-!endif # TCLINSTALL\r
-\r
-tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
-\r
-!endif # $(DOING_TCL)\r
-\r
-# We need a tclsh that will run on the host machine as part of the build.\r
-# IX86 runs on all architectures.\r
-!ifndef TCLSH_NATIVE\r
-!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
-TCLSH_NATIVE   = $(TCLSH)\r
-!else\r
-!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
-!endif\r
-!endif\r
-\r
-# Do the same for Tk and Tk extensions that require the Tk libraries\r
-!if $(DOING_TK) || $(NEED_TK)\r
-WISHNAMEPREFIX = wish\r
-WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
-TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
-TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
-\r
-!if $(DOING_TK)\r
-WISH           = $(OUT_DIR)\$(WISHNAME)\r
-TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
-TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WINDIR)" -I"$(GENERICDIR)"\r
-\r
-!else # effectively NEED_TK\r
-\r
-!if $(TKINSTALL) # Building against installed Tk\r
-WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\include"\r
-!else # Building against Tk sources\r
-WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
-TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-# When building extensions, may be linking against Tk that does not add\r
-# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
-!if !exist("$(TKIMPLIB)")\r
-TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
-TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
-!endif\r
-TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
-!endif # TKINSTALL\r
-tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
-\r
-!endif # $(DOING_TK)\r
-!endif # $(DOING_TK) || $(NEED_TK)\r
-\r
-# Various output paths\r
-PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
-PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
-PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
-\r
-PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
-PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
-\r
-# If extension parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
-!ifdef RCFILE\r
-RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
-!else\r
-RESFILE = $(TMP_DIR)\$(PROJECT).res\r
-!endif\r
-!endif\r
-\r
-###################################################################\r
-# 11. Construct the paths for the installation directories\r
-# The following macros get defined in this section:\r
-# LIB_INSTALL_DIR - where libraries should be installed\r
-# BIN_INSTALL_DIR - where the executables should be installed\r
-# DOC_INSTALL_DIR - where documentation should be installed\r
-# SCRIPT_INSTALL_DIR - where scripts should be installed\r
-# INCLUDE_INSTALL_DIR - where C include files should be installed\r
-# DEMO_INSTALL_DIR - where demos should be installed\r
-# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
-\r
-!if $(DOING_TCL) || $(DOING_TK)\r
-LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
-BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
-DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
-!if $(DOING_TCL)\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!else # DOING_TK\r
-SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
-\r
-!else # extension other than Tk\r
-\r
-PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
-!if $(MULTIPLATFORM_INSTALL)\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
-!else\r
-LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-!endif\r
-DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
-SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
-DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
-INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
-\r
-!endif\r
-\r
-###################################################################\r
-# 12. Set up actual options to be passed to the compiler and linker\r
-# Now we have all the information we need, set up the actual flags and\r
-# options that we will pass to the compiler and linker. The main\r
-# makefile should use these in combination with whatever other flags\r
-# and switches are specific to it.\r
-# The following macros are defined, names are for historical compatibility:\r
-# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
-# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
-# crt - Compiler switch that selects the appropriate C runtime\r
-# cdebug - Compiler switches related to debug AND optimizations\r
-# cwarn - Compiler switches that set warning levels\r
-# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
-# ldebug - Linker switches controlling debug information and optimization\r
-# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
-# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
-# conlflags - complete linker switches for console program (subsumes lflags)\r
-# guilflags - complete linker switches for GUI program (subsumes lflags)\r
-# baselibs - minimum Windows libraries required. Parent makefile can\r
-#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
-\r
-OPTDEFINES     = -DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) -DSTDC_HEADERS\r
-\r
-!if $(TCL_MEM_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_MEM_DEBUG\r
-!endif\r
-!if $(TCL_COMPILE_DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_COMPILE_DEBUG -DTCL_COMPILE_STATS\r
-!endif\r
-!if $(TCL_THREADS) && $(TCL_VERSION) <= 86\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_THREADS=1\r
-!if $(USE_THREAD_ALLOC)\r
-OPTDEFINES     = $(OPTDEFINES) -DUSE_THREAD_ALLOC=1\r
-!endif\r
-!endif\r
-!if $(STATIC_BUILD)\r
-OPTDEFINES     = $(OPTDEFINES) -DSTATIC_BUILD\r
-!endif\r
-!if $(TCL_NO_DEPRECATED)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_NO_DEPRECATED\r
-!endif\r
-\r
-!if $(USE_STUBS)\r
-# Note we do not define USE_TCL_STUBS even when building tk since some\r
-# test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
-USE_STUBS_DEFS  = -DUSE_TCL_STUBS -DUSE_TCLOO_STUBS\r
-!if $(NEED_TK)\r
-USE_STUBS_DEFS  = $(USE_STUBS_DEFS) -DUSE_TK_STUBS\r
-!endif\r
-!endif\r
-!endif # USE_STUBS\r
-\r
-!if !$(DEBUG)\r
-OPTDEFINES     = $(OPTDEFINES) -DNDEBUG\r
-!if $(OPTIMIZING)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_OPTIMIZED\r
-!endif\r
-!endif\r
-!if $(PROFILE)\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_PROFILED\r
-!endif\r
-!if "$(MACHINE)" == "AMD64"\r
-OPTDEFINES     = $(OPTDEFINES) -DTCL_CFG_DO64BIT\r
-!endif\r
-!if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) -DNO_STRTOI64\r
-!endif\r
-\r
-!if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) -D_USE_64BIT_TIME_T\r
-!endif\r
-\r
-# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
-COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
-\r
-# Following is primarily for the benefit of extensions. Tcl 8.5 builds\r
-# Tcl without /DUNICODE, while 8.6 builds with it defined. When building\r
-# an extension, it is advisable (but not mandated) to use the same Windows\r
-# API as the Tcl build. This is accordingly defaulted below. A particular\r
-# extension can override this by pre-definining USE_WIDECHAR_API.\r
-!ifndef USE_WIDECHAR_API\r
-!if $(TCL_VERSION) > 85\r
-USE_WIDECHAR_API = 1\r
-!else\r
-USE_WIDECHAR_API = 0\r
-!endif\r
-!endif\r
-\r
-!if $(USE_WIDECHAR_API)\r
-COMPILERFLAGS = $(COMPILERFLAGS) /DUNICODE /D_UNICODE\r
-!endif\r
-\r
-# Like the TEA system only set this non empty for non-Tk extensions\r
-# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
-# so we pass both\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-PKGNAMEFLAGS = -DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
-               -DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
-               -DMODULE_SCOPE=extern\r
-!endif\r
-\r
-# crt picks the C run time based on selected OPTS\r
-!if $(MSVCRT)\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MDd\r
-!else\r
-crt = -MD\r
-!endif\r
-!else\r
-!if $(DEBUG) && !$(UNCHECKED)\r
-crt = -MTd\r
-!else\r
-crt = -MT\r
-!endif\r
-!endif\r
-\r
-# cdebug includes compiler options for debugging as well as optimization.\r
-!if $(DEBUG)\r
-\r
-# In debugging mode, optimizations need to be disabled\r
-cdebug = -Zi -Od $(DEBUGFLAGS)\r
-\r
-!else\r
-\r
-cdebug = $(OPTIMIZATIONS)\r
-!if $(SYMBOLS)\r
-cdebug = $(cdebug) -Zi\r
-!endif\r
-\r
-!endif # $(DEBUG)\r
-\r
-# cwarn includes default warning levels.\r
-cwarn = $(WARNINGS)\r
-\r
-!if "$(MACHINE)" == "AMD64"\r
-# Disable pointer<->int warnings related to cast between different sizes\r
-# There are a gadzillion of these due to use of ClientData and\r
-# clutter up compiler\r
-# output increasing chance of a real warning getting lost. So disable them.\r
-# Eventually some day, Tcl will be 64-bit clean.\r
-cwarn = $(cwarn) -wd4311 -wd4312\r
-!endif\r
-\r
-### Common compiler options that are architecture specific\r
-!if "$(MACHINE)" == "ARM"\r
-carch = -D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
-!else\r
-carch =\r
-!endif\r
-\r
-!if $(DEBUG)\r
-# Turn warnings into errors\r
-cwarn = $(cwarn) -WX\r
-!endif\r
-\r
-INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
-!if !$(DOING_TCL) && !$(DOING_TK)\r
-INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WINDIR)" -I"$(COMPATDIR)"\r
-!endif\r
-\r
-# These flags are defined roughly in the order of the pre-reform\r
-# rules.vc/makefile.vc to help visually compare that the pre- and\r
-# post-reform build logs\r
-\r
-# cflags contains generic flags used for building practically all object files\r
-cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
-\r
-# appcflags contains $(cflags) and flags for building the application\r
-# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
-# flags used for building shared object files The two differ in the\r
-# BUILD_$(PROJECT) macro which should be defined only for the shared\r
-# library *implementation* and not for its caller interface\r
-\r
-appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
-appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
-pkgcflags = $(appcflags) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) -DBUILD_$(PROJECT)\r
-\r
-# stubscflags contains $(cflags) plus flags used for building a stubs\r
-# library for the package.  Note: -DSTATIC_BUILD is defined in\r
-# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
-# library. However the stubs library is ALWAYS static hence included\r
-# here irrespective of the OPTS setting.\r
-#\r
-# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
-# without stating why. Tcl itself compiled stubs libs with this flag.\r
-# so we do not remove it from cflags. -GL may prevent extensions\r
-# compiled with one VC version to fail to link against stubs library\r
-# compiled with another VC version. Check for this and fix accordingly.\r
-stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl -DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
-\r
-# Link flags\r
-\r
-!if $(DEBUG)\r
-ldebug = -debug -debugtype:cv\r
-!else\r
-ldebug = -release -opt:ref -opt:icf,3\r
-!if $(SYMBOLS)\r
-ldebug = $(ldebug) -debug -debugtype:cv\r
-!endif\r
-!endif\r
-\r
-# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
-!if $(PROFILE)\r
-ldebug= $(ldebug) -profile\r
-!endif\r
-\r
-### Declarations common to all linker versions\r
-lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-lflags = $(lflags) -nodefaultlib:libucrt.lib\r
-!endif\r
-\r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
-dlllflags = $(lflags) -dll\r
-conlflags = $(lflags) -subsystem:console\r
-guilflags = $(lflags) -subsystem:windows\r
-\r
-# Libraries that are required for every image.\r
-# Extensions should define any additional libraries with $(PRJ_LIBS)\r
-winlibs   = kernel32.lib advapi32.lib\r
-\r
-!if $(NEED_TK)\r
-winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
-!endif\r
-\r
-# Avoid 'unresolved external symbol __security_cookie' errors.\r
-# c.f. http://support.microsoft.com/?id=894573\r
-!if "$(MACHINE)" == "AMD64"\r
-!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
-winlibs   = $(winlibs) bufferoverflowU.lib\r
-!endif\r
-!endif\r
-\r
-baselibs = $(winlibs) $(PRJ_LIBS)\r
-\r
-!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
-baselibs   = $(baselibs) ucrt.lib\r
-!endif\r
-\r
-################################################################\r
-# 13. Define standard commands, common make targets and implicit rules\r
-\r
-CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
-CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
-CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
-\r
-LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
-DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-\r
-CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
-RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
-           $(TCL_INCLUDES) \\r
-           -DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           -DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
-           -DDOTVERSION=\"$(DOTVERSION)\" \\r
-           -DVERSION=\"$(VERSION)\" \\r
-           -DSUFX=\"$(SUFX)\" \\r
-           -DPROJECT=\"$(PROJECT)\" \\r
-           -DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
-\r
-!ifndef DEFAULT_BUILD_TARGET\r
-DEFAULT_BUILD_TARGET = $(PROJECT)\r
-!endif\r
-\r
-default-target: $(DEFAULT_BUILD_TARGET)\r
-\r
-!if $(MULTIPLATFORM_INSTALL)\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!else\r
-default-pkgindex:\r
-       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
-!endif\r
-\r
-default-pkgindex-tea:\r
-       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
-@PACKAGE_VERSION@    $(DOTVERSION)\r
-@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
-@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
-@PKG_LIB_FILE@       $(PRJLIBNAME)\r
-<<\r
-\r
-default-install: default-install-binaries default-install-libraries\r
-!if $(SYMBOLS)\r
-default-install: default-install-pdbs\r
-!endif\r
-\r
-# Again to deal with historical brokenness, there is some confusion\r
-# in terminlogy. For extensions, the "install-binaries" was used to\r
-# locate target directory for *binary shared libraries* and thus\r
-# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
-# for executables (exes). On the other hand the "install-libraries"\r
-# target is for *scripts* and should have been called "install-scripts".\r
-default-install-binaries: $(PRJLIB)\r
-       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
-\r
-# Alias for default-install-scripts\r
-default-install-libraries: default-install-scripts\r
-\r
-default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
-       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
-       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
-       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
-       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
-\r
-default-install-stubs:\r
-       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
-       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
-\r
-default-install-pdbs:\r
-       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
-       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
-       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
-\r
-default-install-docs-html:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-docs-n:\r
-       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
-       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
-       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
-\r
-default-install-demos:\r
-       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
-       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
-       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
-\r
-default-clean:\r
-       @echo Cleaning $(TMP_DIR)\* ...\r
-       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
-       @echo Cleaning $(WINDIR)\nmakehlp.obj, nmakehlp.exe ...\r
-       @if exist $(WINDIR)\nmakehlp.obj del $(WINDIR)\nmakehlp.obj\r
-       @if exist $(WINDIR)\nmakehlp.exe del $(WINDIR)\nmakehlp.exe\r
-       @if exist $(WINDIR)\nmakehlp.out del $(WINDIR)\nmakehlp.out\r
-       @echo Cleaning $(WINDIR)\nmhlp-out.txt ...\r
-       @if exist $(WINDIR)\nmhlp-out.txt del $(WINDIR)\nmhlp-out.txt\r
-       @echo Cleaning $(WINDIR)\_junk.pch ...\r
-       @if exist $(WINDIR)\_junk.pch del $(WINDIR)\_junk.pch\r
-       @echo Cleaning $(WINDIR)\vercl.x, vercl.i ...\r
-       @if exist $(WINDIR)\vercl.x del $(WINDIR)\vercl.x\r
-       @if exist $(WINDIR)\vercl.i del $(WINDIR)\vercl.i\r
-       @echo Cleaning $(WINDIR)\versions.vc, version.vc ...\r
-       @if exist $(WINDIR)\versions.vc del $(WINDIR)\versions.vc\r
-       @if exist $(WINDIR)\version.vc del $(WINDIR)\version.vc\r
-\r
-default-hose: default-clean\r
-       @echo Hosing $(OUT_DIR)\* ...\r
-       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
-\r
-# Only for backward compatibility\r
-default-distclean: default-hose\r
-\r
-default-setup:\r
-       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
-       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
-\r
-!if "$(TESTPAT)" != ""\r
-TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
-!endif\r
-\r
-default-test: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
-\r
-default-shell: default-setup $(PROJECT)\r
-       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
-       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
-       $(DEBUGGER) $(TCLSH)\r
-\r
-# Generation of Windows version resource\r
-!ifdef RCFILE\r
-\r
-# Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
-$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
-       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
-\r
-!else\r
-\r
-# If parent makefile has not defined a resource definition file,\r
-# we will generate one from standard template.\r
-$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
-\r
-$(TMP_DIR)\$(PROJECT).rc:\r
-       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
-#include <winver.h>\r
-\r
-VS_VERSION_INFO VERSIONINFO\r
- FILEVERSION   COMMAVERSION\r
- PRODUCTVERSION        COMMAVERSION\r
- FILEFLAGSMASK 0x3fL\r
-#ifdef DEBUG\r
- FILEFLAGS     VS_FF_DEBUG\r
-#else\r
- FILEFLAGS     0x0L\r
-#endif\r
- FILEOS                VOS_NT_WINDOWS32\r
- FILETYPE      VFT_DLL\r
- FILESUBTYPE   0x0L\r
-BEGIN\r
-    BLOCK "StringFileInfo"\r
-    BEGIN\r
-        BLOCK "040904b0"\r
-        BEGIN\r
-            VALUE "FileDescription",  "Tcl extension " PROJECT\r
-            VALUE "OriginalFilename", PRJLIBNAME\r
-            VALUE "FileVersion",      DOTVERSION\r
-            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
-            VALUE "ProductVersion",   DOTVERSION\r
-        END\r
-    END\r
-    BLOCK "VarFileInfo"\r
-    BEGIN\r
-        VALUE "Translation", 0x409, 1200\r
-    END\r
-END\r
-\r
-<<\r
-\r
-!endif # ifdef RCFILE\r
-\r
-!ifndef DISABLE_IMPLICIT_RULES\r
-DISABLE_IMPLICIT_RULES = 0\r
-!endif\r
-\r
-!if !$(DISABLE_IMPLICIT_RULES)\r
-# Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
-\r
-{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(WINDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
-       $(CCPKGCMD) @<<\r
-$<\r
-<<\r
-\r
-{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(WINDIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
-       $(RESCMD) $<\r
-\r
-.SUFFIXES:\r
-.SUFFIXES:.c .rc\r
-\r
-!endif\r
-\r
-################################################################\r
-# 14. Sanity check selected options against Tcl build options\r
-# When building an extension, certain configuration options should\r
-# match the ones used when Tcl was built. Here we check and\r
-# warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
-\r
-!if $(TCLINSTALL) # Building against an installed Tcl\r
-!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
-TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
-!endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
-!endif\r
-!endif # TCLINSTALL\r
-\r
-!if $(CONFIG_CHECK)\r
-!ifdef TCLNMAKECONFIG\r
-!include $(TCLNMAKECONFIG)\r
-\r
-!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
-!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
-!endif\r
-!if defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
-!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
-!endif\r
-!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
-!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
-!endif\r
-!endif\r
-\r
-!endif # TCLNMAKECONFIG\r
-\r
-!endif # ! $(DOING_TCL)\r
-\r
-\r
-#----------------------------------------------------------\r
-# Display stats being used.\r
-#----------------------------------------------------------\r
-\r
-!if !$(DOING_TCL)\r
-!message *** Building against Tcl at '$(_TCLDIR)'\r
-!endif\r
-!if !$(DOING_TK) && $(NEED_TK)\r
-!message *** Building against Tk at '$(_TKDIR)'\r
-!endif\r
-!message *** Intermediate directory will be '$(TMP_DIR)'\r
-!message *** Output directory will be '$(OUT_DIR)'\r
-!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
-!message *** Suffix for binaries will be '$(SUFX)'\r
-!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
-\r
-!endif # ifdef _RULES_VC\r
diff --git a/pkgs/tdbcsqlite3-1.1.1/win/targets.vc b/pkgs/tdbcsqlite3-1.1.1/win/targets.vc
deleted file mode 100644 (file)
index 7f1d388..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-#------------------------------------------------------------- -*- makefile -*-\r
-# targets.vc --\r
-#\r
-# Part of the nmake based build system for Tcl and its extensions.\r
-# This file defines some standard targets for the convenience of extensions\r
-# and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for docs.\r
-\r
-$(PROJECT): setup pkgindex $(PRJLIB)\r
-\r
-!ifdef PRJ_STUBOBJS\r
-$(PROJECT): $(PRJSTUBLIB)\r
-$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
-       $(LIBCMD) $**\r
-\r
-$(PRJ_STUBOBJS):\r
-       $(CCSTUBSCMD) %s\r
-!endif # PRJ_STUBOBJS\r
-\r
-!ifdef PRJ_MANIFEST\r
-$(PROJECT): $(PRJLIB).manifest\r
-$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
-       @nmakehlp -s << $** >$@\r
-@MACHINE@        $(MACHINE:IX86=X86)\r
-<<\r
-!endif\r
-\r
-!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
-$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
-!if $(STATIC_BUILD)\r
-       $(LIBCMD) $**\r
-!else\r
-       $(DLLCMD) $**\r
-       $(_VC_MANIFEST_EMBED_DLL)\r
-!endif\r
-       -@del $*.exp\r
-!endif\r
-\r
-!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
-$(PRJ_OBJS): $(PRJ_HEADERS)\r
-!endif\r
-\r
-# If parent makefile has defined stub objects, add their installation\r
-# to the default install\r
-!if "$(PRJ_STUBOBJS)" != ""\r
-default-install: default-install-stubs\r
-!endif\r
-\r
-# Unlike the other default targets, these cannot be in rules.vc because\r
-# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
-# that the parent makefile will not define until after including rules-ext.vc\r
-!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
-default-install: default-install-headers\r
-default-install-headers:\r
-       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
-       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
-!endif\r
-\r
-!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
-DISABLE_STANDARD_TARGETS = 0\r
-!endif\r
-\r
-!if "$(DISABLE_TARGET_setup)" == ""\r
-DISABLE_TARGET_setup = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_install)" == ""\r
-DISABLE_TARGET_install = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_clean)" == ""\r
-DISABLE_TARGET_clean = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_test)" == ""\r
-DISABLE_TARGET_test = 0\r
-!endif\r
-!if "$(DISABLE_TARGET_shell)" == ""\r
-DISABLE_TARGET_shell = 0\r
-!endif\r
-\r
-!if !$(DISABLE_STANDARD_TARGETS)\r
-!if !$(DISABLE_TARGET_setup)\r
-setup: default-setup\r
-!endif\r
-!if !$(DISABLE_TARGET_install)\r
-install: default-install\r
-!endif\r
-!if !$(DISABLE_TARGET_clean)\r
-clean: default-clean\r
-realclean: hose\r
-hose: default-hose\r
-distclean: realclean default-distclean\r
-!endif\r
-!if !$(DISABLE_TARGET_test)\r
-test: default-test\r
-!endif\r
-!if !$(DISABLE_TARGET_shell)\r
-shell: default-shell\r
-!endif\r
-!endif # DISABLE_STANDARD_TARGETS\r
similarity index 99%
rename from pkgs/tdbcsqlite3-1.1.1/Makefile.in
rename to pkgs/tdbcsqlite3-1.1.2/Makefile.in
index 106b1b0..a52af1e 100644 (file)
@@ -261,7 +261,7 @@ shell: binaries libraries
 gdb:
        $(TCLSH_ENV) $(PKG_ENV) $(GDB) $(TCLSH_PROG) $(SCRIPT)
 
-gdb-test: binaries libraries 
+gdb-test: binaries libraries
        $(TCLSH_ENV) $(PKG_ENV) $(GDB) \
            --args $(TCLSH_PROG) `@CYGPATH@ $(srcdir)/tests/all.tcl` \
            $(TESTFLAGS) -singleproc 1 \
similarity index 96%
rename from pkgs/tdbcsqlite3-1.1.1/README
rename to pkgs/tdbcsqlite3-1.1.2/README
index b953099..39eecc3 100644 (file)
@@ -1,6 +1,6 @@
 README: tdbcsqlite3
 
-    This is the 1.1.1 source distribution of the bridge between Tcl
+    This is the 1.1.2 source distribution of the bridge between Tcl
     Database Connectivity (TDBC) and SQLite3, an open-source SQL
     database with an in-process server.
 
similarity index 98%
rename from pkgs/tdbcsqlite3-1.1.1/configure
rename to pkgs/tdbcsqlite3-1.1.2/configure
index 2018c91..15ad261 100755 (executable)
@@ -1,6 +1,6 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for tdbcsqlite3 1.1.1.
+# Generated by GNU Autoconf 2.69 for tdbcsqlite3 1.1.2.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -577,8 +577,8 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='tdbcsqlite3'
 PACKAGE_TARNAME='tdbcsqlite3'
-PACKAGE_VERSION='1.1.1'
-PACKAGE_STRING='tdbcsqlite3 1.1.1'
+PACKAGE_VERSION='1.1.2'
+PACKAGE_STRING='tdbcsqlite3 1.1.2'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
@@ -622,7 +622,6 @@ ac_subst_vars='LTLIBOBJS
 TCL_MINOR_VERSION
 TCL_MAJOR_VERSION
 TCLSH_PROG
-TCL_DBGX
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -630,6 +629,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -1289,7 +1290,7 @@ 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 tdbcsqlite3 1.1.1 to adapt to many kinds of systems.
+\`configure' configures tdbcsqlite3 1.1.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1350,7 +1351,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of tdbcsqlite3 1.1.1:";;
+     short | recursive ) echo "Configuration of tdbcsqlite3 1.1.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1447,7 +1448,7 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-tdbcsqlite3 configure 1.1.1
+tdbcsqlite3 configure 1.1.2
 generated by GNU Autoconf 2.69
 
 Copyright (C) 2012 Free Software Foundation, Inc.
@@ -1770,7 +1771,7 @@ cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by tdbcsqlite3 $as_me 1.1.1, which was
+It was created by tdbcsqlite3 $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
@@ -3280,10 +3281,6 @@ $as_echo "loading" >&6; }
 $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3317,12 +3314,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3614,7 +3605,7 @@ $as_echo_n "checking For TDBC_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3628,7 +3619,7 @@ $as_echo "using TDBC_STUB_LIB_PATH ${TDBC_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3657,7 +3648,7 @@ $as_echo_n "checking For tdbc_STUB library for LIBS... " >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -3671,7 +3662,7 @@ $as_echo "using tdbc_STUB_LIB_PATH ${tdbc_STUB_LIB_PATH}" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -4925,7 +4916,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -4950,7 +4941,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5099,14 +5090,14 @@ $as_echo "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -5187,14 +5178,14 @@ fi
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
                if test "$GCC" = yes; then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
 else
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 else
 
@@ -5209,7 +5200,7 @@ else
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -5285,39 +5276,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -5442,8 +5400,8 @@ fi
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
@@ -5470,7 +5428,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
@@ -5539,8 +5497,8 @@ fi
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -5556,8 +5514,8 @@ esac
 
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
@@ -5566,8 +5524,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            if test "$GCC" = yes; then :
 
@@ -5595,8 +5553,8 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
@@ -5619,7 +5577,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -5629,9 +5587,22 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"; then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            if test "`uname -m`" = "alpha"; then :
@@ -5696,8 +5667,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -5714,11 +5685,11 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -5736,7 +5707,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -5744,32 +5715,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -6078,7 +6023,7 @@ fi
            SHLIB_SUFFIX=".so"
            if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
            if test "$GCC" = yes; then :
@@ -6148,13 +6093,13 @@ $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 else
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6254,7 +6199,7 @@ fi
            if test "$GCC" = yes; then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                if test "$do64bit_ok" = yes; then :
 
@@ -6291,8 +6236,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -6633,6 +6578,8 @@ fi
 
 
 
+
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
@@ -7022,7 +6969,6 @@ else
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
@@ -7036,11 +6982,6 @@ $as_echo "no" >&6; }
 $as_echo "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
@@ -7083,14 +7024,14 @@ $as_echo_n "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -7098,9 +7039,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -7678,7 +7619,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by tdbcsqlite3 $as_me 1.1.1, which was
+This file was extended by tdbcsqlite3 $as_me 1.1.2, which was
 generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -7731,7 +7672,7 @@ _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-tdbcsqlite3 config.status 1.1.1
+tdbcsqlite3 config.status 1.1.2
 configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
similarity index 99%
rename from pkgs/tdbcsqlite3-1.1.1/configure.ac
rename to pkgs/tdbcsqlite3-1.1.2/configure.ac
index b1cfed3..055fb90 100644 (file)
@@ -19,7 +19,7 @@ dnl   to configure the system for the local environment.
 # so that we create the export library with the dll.
 #-----------------------------------------------------------------------
 
-AC_INIT([tdbcsqlite3], [1.1.1])
+AC_INIT([tdbcsqlite3], [1.1.2])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
@@ -13,7 +13,7 @@
 package require tdbc
 package require sqlite3
 
-package provide tdbc::sqlite3 1.1.1
+package provide tdbc::sqlite3 1.1.2
 
 namespace eval tdbc::sqlite3 {
     namespace export connection
diff --git a/pkgs/tdbcsqlite3-1.1.2/tclconfig/README.txt b/pkgs/tdbcsqlite3-1.1.2/tclconfig/README.txt
new file mode 100644 (file)
index 0000000..715cb9d
--- /dev/null
@@ -0,0 +1,26 @@
+These files comprise the basic building blocks for a Tcl Extension
+Architecture (TEA) extension.  For more information on TEA see:
+
+       http://www.tcl.tk/doc/tea/
+
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
+
+       https://core.tcl-lang.org/tclconfig
+
+This package is a freely available open source package.  You can do
+virtually anything you like with it, such as modifying it, redistributing
+it, and selling it either in whole or in part.
+
+CONTENTS
+========
+The following is a short description of the files you will find in
+the sample extension.
+
+README.txt     This file
+
+install-sh     Program used for copying binaries and script files
+               to their install locations.
+
+tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
+               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/tdbcsqlite3-1.1.2/tclconfig/install-sh b/pkgs/tdbcsqlite3-1.1.2/tclconfig/install-sh
new file mode 100644 (file)
index 0000000..21b733a
--- /dev/null
@@ -0,0 +1,518 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2020-07-26.22; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# 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.
+
+tab='  '
+nl='
+'
+IFS=" $tab$nl"
+
+# Set DOITPROG to "echo" to test this script.
+
+doit=${DOITPROG-}
+doit_exec=${doit:-exec}
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+is_target_a_directory=possibly
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+        shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
+
+    -o) chowncmd="$chownprog $2"
+        shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -S) stripcmd="$stripprog $2"
+        shift;;
+
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
+
+    -T) is_target_a_directory=never;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --) shift
+        break;;
+
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename.
+    if test -d "$dst"; then
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
+      fi
+      dstdir=$dst
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
+      dstdir_status=0
+    else
+      dstdir=`dirname "$dst"`
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
+       else
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
+       fi
+       trap '' 0;;
+    esac
+
+    if
+      $posix_mkdir && (
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
+      esac
+
+      oIFS=$IFS
+      IFS=/
+      set -f
+      set fnord $dstdir
+      shift
+      set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # 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 $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       set +f &&
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC0"
+# time-stamp-end: "; # UTC"
+# End:
\ No newline at end of file
diff --git a/pkgs/tdbcsqlite3-1.1.2/tclconfig/tcl.m4 b/pkgs/tdbcsqlite3-1.1.2/tclconfig/tcl.m4
new file mode 100644 (file)
index 0000000..8d24e7f
--- /dev/null
@@ -0,0 +1,4056 @@
+# tcl.m4 --
+#
+#      This file provides a set of autoconf macros to help TEA-enable
+#      a Tcl extension.
+#
+# Copyright (c) 1999-2000 Ajuba Solutions.
+# Copyright (c) 2002-2005 ActiveState Corporation.
+#
+# See the file "license.terms" for information on usage and redistribution
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+AC_PREREQ(2.57)
+
+# Possible values for key variables defined:
+#
+# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
+# TEA_PLATFORM        - windows unix
+# TEA_TK_EXTENSION    - True if this is a Tk extension
+#
+
+#------------------------------------------------------------------------
+# TEA_PATH_TCLCONFIG --
+#
+#      Locate the tclConfig.sh file and perform a sanity check on
+#      the Tcl compile flags
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tcl=...
+#
+#      Defines the following vars:
+#              TCL_BIN_DIR     Full path to the directory containing
+#                              the tclConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TCLCONFIG], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+    #
+    # Ok, lets find the tcl configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tcl
+    #
+
+    if test x"${no_tcl}" = x ; then
+       # we reset no_tcl in case something fails here
+       no_tcl=true
+       AC_ARG_WITH(tcl,
+           AS_HELP_STRING([--with-tcl],
+               [directory containing tcl configuration (tclConfig.sh)]),
+           [with_tclconfig="${withval}"])
+       AC_MSG_CHECKING([for Tcl configuration])
+       AC_CACHE_VAL(ac_cv_c_tclconfig,[
+
+           # First check to see if --with-tcl was specified.
+           if test x"${with_tclconfig}" != x ; then
+               case "${with_tclconfig}" in
+                   */tclConfig.sh )
+                       if test -f "${with_tclconfig}"; then
+                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
+                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tclconfig}/tclConfig.sh" ; then
+                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tcl installation
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ../tcl \
+                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tcl \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tcl \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tcl \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tclconfig}" = x ; then
+           TCL_BIN_DIR="# no Tcl configs found"
+           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
+       else
+           no_tcl=
+           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
+           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_TKCONFIG --
+#
+#      Locate the tkConfig.sh file
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tk=...
+#
+#      Defines the following vars:
+#              TK_BIN_DIR      Full path to the directory containing
+#                              the tkConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TKCONFIG], [
+    #
+    # Ok, lets find the tk configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tk
+    #
+
+    if test x"${no_tk}" = x ; then
+       # we reset no_tk in case something fails here
+       no_tk=true
+       AC_ARG_WITH(tk,
+           AS_HELP_STRING([--with-tk],
+               [directory containing tk configuration (tkConfig.sh)]),
+           [with_tkconfig="${withval}"])
+       AC_MSG_CHECKING([for Tk configuration])
+       AC_CACHE_VAL(ac_cv_c_tkconfig,[
+
+           # First check to see if --with-tkconfig was specified.
+           if test x"${with_tkconfig}" != x ; then
+               case "${with_tkconfig}" in
+                   */tkConfig.sh )
+                       if test -f "${with_tkconfig}"; then
+                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
+                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tkconfig}/tkConfig.sh" ; then
+                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tk library
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ../tk \
+                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tk \
+                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tk \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tk \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tkconfig}" = x ; then
+           TK_BIN_DIR="# no Tk configs found"
+           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
+       else
+           no_tk=
+           TK_BIN_DIR="${ac_cv_c_tkconfig}"
+           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TCLCONFIG --
+#
+#      Load the tclConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TCL_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_BIN_DIR
+#              TCL_SRC_DIR
+#              TCL_LIB_FILE
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TCLCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
+
+    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TCL_BIN_DIR}/tclConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
+    fi
+
+    # If the TCL_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TCL_LIB_SPEC will be set to the value
+    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
+    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
+        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
+        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tcl was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tcl.framework installed in an arbitrary location.
+       case ${TCL_DEFS} in
+           *TCL_FRAMEWORK*)
+               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
+                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
+                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
+                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
+                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
+                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    AC_SUBST(TCL_VERSION)
+    AC_SUBST(TCL_PATCH_LEVEL)
+    AC_SUBST(TCL_BIN_DIR)
+    AC_SUBST(TCL_SRC_DIR)
+
+    AC_SUBST(TCL_LIB_FILE)
+    AC_SUBST(TCL_LIB_FLAG)
+    AC_SUBST(TCL_LIB_SPEC)
+
+    AC_SUBST(TCL_STUB_LIB_FILE)
+    AC_SUBST(TCL_STUB_LIB_FLAG)
+    AC_SUBST(TCL_STUB_LIB_SPEC)
+
+    AC_MSG_CHECKING([platform])
+    hold_cc=$CC; CC="$TCL_CC"
+    AC_TRY_COMPILE(,[
+           #ifdef _WIN32
+               #error win32
+           #endif
+       ], [
+           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
+           TEA_PLATFORM="${TEA_PLATFORM-unix}"
+           CYGPATH=echo
+       ], [
+           TEA_PLATFORM="windows"
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
+    )
+    CC=$hold_cc
+    AC_MSG_RESULT($TEA_PLATFORM)
+
+    # The BUILD_$pkg is to define the correct extern storage class
+    # handling when making this package
+    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
+           [Building extension source?])
+    # Do this here as we have fully defined TEA_PLATFORM now
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       EXEEXT=".exe"
+       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
+    fi
+
+    # TEA specific:
+    AC_SUBST(CLEANFILES)
+    AC_SUBST(TCL_LIBS)
+    AC_SUBST(TCL_DEFS)
+    AC_SUBST(TCL_EXTRA_CFLAGS)
+    AC_SUBST(TCL_LD_FLAGS)
+    AC_SUBST(TCL_SHLIB_LD_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TKCONFIG --
+#
+#      Load the tkConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TK_BIN_DIR
+#
+# Results:
+#
+#      Sets the following vars that should be in tkConfig.sh:
+#              TK_BIN_DIR
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TKCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
+
+    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TK_BIN_DIR}/tkConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
+    fi
+
+    # If the TK_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TK_LIB_SPEC will be set to the value
+    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
+    # instead of TK_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
+        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
+        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tk was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tk.framework installed in an arbitrary location.
+       case ${TK_DEFS} in
+           *TK_FRAMEWORK*)
+               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
+                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
+                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
+                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
+                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
+                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    # TEA specific: Ensure windowingsystem is defined
+    if test "${TEA_PLATFORM}" = "unix" ; then
+       case ${TK_DEFS} in
+           *MAC_OSX_TK*)
+               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
+               TEA_WINDOWINGSYSTEM="aqua"
+               ;;
+           *)
+               TEA_WINDOWINGSYSTEM="x11"
+               ;;
+       esac
+    elif test "${TEA_PLATFORM}" = "windows" ; then
+       TEA_WINDOWINGSYSTEM="win32"
+    fi
+
+    AC_SUBST(TK_VERSION)
+    AC_SUBST(TK_BIN_DIR)
+    AC_SUBST(TK_SRC_DIR)
+
+    AC_SUBST(TK_LIB_FILE)
+    AC_SUBST(TK_LIB_FLAG)
+    AC_SUBST(TK_LIB_SPEC)
+
+    AC_SUBST(TK_STUB_LIB_FILE)
+    AC_SUBST(TK_STUB_LIB_FLAG)
+    AC_SUBST(TK_STUB_LIB_SPEC)
+
+    # TEA specific:
+    AC_SUBST(TK_LIBS)
+    AC_SUBST(TK_XINCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_TCLSH
+#      Determine the fully qualified path name of the tclsh executable
+#      in the Tcl build directory or the tclsh installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the tclsh executable even if tclsh has not yet been
+#      built in the build directory. The tclsh found is always
+#      associated with a tclConfig.sh file. This tclsh should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCLSH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_TCLSH], [
+    AC_MSG_CHECKING([for tclsh])
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        # tclConfig.sh is in Tcl build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
+        fi
+    else
+        # tclConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+        else
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${TCLSH_PROG}" ; then
+                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
+    fi
+    AC_MSG_RESULT([${TCLSH_PROG}])
+    AC_SUBST(TCLSH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_WISH
+#      Determine the fully qualified path name of the wish executable
+#      in the Tk build directory or the wish installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the wish executable even if wish has not yet been
+#      built in the build directory. The wish found is always
+#      associated with a tkConfig.sh file. This wish should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              WISH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_WISH], [
+    AC_MSG_CHECKING([for wish])
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        # tkConfig.sh is in Tk build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            WISH_PROG="${TK_BIN_DIR}/wish"
+        fi
+    else
+        # tkConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+        else
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${WISH_PROG}" ; then
+                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
+    fi
+    AC_MSG_RESULT([${WISH_PROG}])
+    AC_SUBST(WISH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SHARED --
+#
+#      Allows the building of shared libraries
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-shared=yes|no
+#              --enable-stubs=yes|no
+#
+#      Defines the following vars:
+#              STATIC_BUILD    Used for building import/export libraries
+#                              on Windows.
+#
+#      Sets the following vars:
+#              SHARED_BUILD    Value of 1 or 0
+#               STUBS_BUILD     Value if 1 or 0
+#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
+#                                AND TEA_WINDOWING_SYSTEM != ""
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ENABLE_SHARED], [
+    AC_MSG_CHECKING([how to build libraries])
+    AC_ARG_ENABLE(shared,
+       AS_HELP_STRING([--enable-shared],
+           [build and link with shared libraries (default: on)]),
+       [shared_ok=$enableval], [shared_ok=yes])
+
+    if test "${enable_shared+set}" = set; then
+       enableval="$enable_shared"
+       shared_ok=$enableval
+    else
+       shared_ok=yes
+    fi
+
+    AC_ARG_ENABLE(stubs,
+       AS_HELP_STRING([--enable-stubs],
+           [build and link with stub libraries. Always true for shared builds (default: on)]),
+       [stubs_ok=$enableval], [stubs_ok=yes])
+
+    if test "${enable_stubs+set}" = set; then
+       enableval="$enable_stubs"
+       stubs_ok=$enableval
+    else
+       stubs_ok=yes
+    fi
+
+    # Stubs are always enabled for shared builds
+    if test "$shared_ok" = "yes" ; then
+       AC_MSG_RESULT([shared])
+       SHARED_BUILD=1
+        STUBS_BUILD=1
+    else
+       AC_MSG_RESULT([static])
+       SHARED_BUILD=0
+       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
+        if test "$stubs_ok" = "yes" ; then
+          STUBS_BUILD=1
+        else
+          STUBS_BUILD=0
+        fi
+    fi
+    if test "${STUBS_BUILD}" = "1" ; then
+      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
+      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
+      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
+        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
+      fi
+    fi
+
+    AC_SUBST(SHARED_BUILD)
+    AC_SUBST(STUBS_BUILD)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_THREADS --
+#
+#      Specify if thread support should be enabled.  If "yes" is specified
+#      as an arg (optional), threads are enabled by default, "no" means
+#      threads are disabled.  "yes" is the default.
+#
+#      TCL_THREADS is checked so that if you are compiling an extension
+#      against a threaded core, your extension must be compiled threaded
+#      as well.
+#
+#      Note that it is legal to have a thread enabled extension run in a
+#      threaded or non-threaded Tcl core, but a non-threaded extension may
+#      only run in a non-threaded Tcl core.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-threads
+#
+#      Sets the following vars:
+#              THREADS_LIBS    Thread library(s)
+#
+#      Defines the following vars:
+#              TCL_THREADS
+#              _REENTRANT
+#              _THREAD_SAFE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_THREADS], [
+    AC_ARG_ENABLE(threads,
+       AS_HELP_STRING([--enable-threads],
+           [build with threads (default: on)]),
+       [tcl_ok=$enableval], [tcl_ok=yes])
+
+    if test "${enable_threads+set}" = set; then
+       enableval="$enable_threads"
+       tcl_ok=$enableval
+    else
+       tcl_ok=yes
+    fi
+
+    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
+       TCL_THREADS=1
+
+       if test "${TEA_PLATFORM}" != "windows" ; then
+           # We are always OK on Windows, so check what this platform wants:
+
+           # USE_THREAD_ALLOC tells us to try the special thread-based
+           # allocator that significantly reduces lock contention
+           AC_DEFINE(USE_THREAD_ALLOC, 1,
+               [Do we want to use the threaded memory allocator?])
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           if test "`uname -s`" = "SunOS" ; then
+               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+                       [Do we really want to follow the standard? Yes we do!])
+           fi
+           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
+           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
+           if test "$tcl_ok" = "no"; then
+               # Check a little harder for __pthread_mutex_init in the same
+               # library, as some systems hide it there until pthread.h is
+               # defined.  We could alternatively do an AC_TRY_COMPILE with
+               # pthread.h, but that will work with libpthread really doesn't
+               # exist, like AIX 4.2.  [Bug: 4359]
+               AC_CHECK_LIB(pthread, __pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+           fi
+
+           if test "$tcl_ok" = "yes"; then
+               # The space is needed
+               THREADS_LIBS=" -lpthread"
+           else
+               AC_CHECK_LIB(pthreads, pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+               if test "$tcl_ok" = "yes"; then
+                   # The space is needed
+                   THREADS_LIBS=" -lpthreads"
+               else
+                   AC_CHECK_LIB(c, pthread_mutex_init,
+                       tcl_ok=yes, tcl_ok=no)
+                   if test "$tcl_ok" = "no"; then
+                       AC_CHECK_LIB(c_r, pthread_mutex_init,
+                           tcl_ok=yes, tcl_ok=no)
+                       if test "$tcl_ok" = "yes"; then
+                           # The space is needed
+                           THREADS_LIBS=" -pthread"
+                       else
+                           TCL_THREADS=0
+                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
+                       fi
+                   fi
+               fi
+           fi
+       fi
+    else
+       TCL_THREADS=0
+    fi
+    # Do checking message here to not mess up interleaved configure output
+    AC_MSG_CHECKING([for building with threads])
+    if test "${TCL_THREADS}" = 1; then
+       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
+       AC_MSG_RESULT([yes (default)])
+    else
+       AC_MSG_RESULT([no])
+    fi
+    # TCL_THREADS sanity checking.  See if our request for building with
+    # threads is the same as the way Tcl was built.  If not, warn the user.
+    case ${TCL_DEFS} in
+       *THREADS=1*)
+           if test "${TCL_THREADS}" = "0"; then
+               AC_MSG_WARN([
+    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
+    that IS thread-enabled.  It is recommended to use --enable-threads.])
+           fi
+           ;;
+    esac
+    AC_SUBST(TCL_THREADS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SYMBOLS --
+#
+#      Specify if debugging symbols should be used.
+#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
+#
+# Arguments:
+#      none
+#
+#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
+#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
+#      Requires the following vars to be set in the Makefile:
+#              CFLAGS_DEFAULT
+#              LDFLAGS_DEFAULT
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-symbols
+#
+#      Defines the following vars:
+#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
+#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
+#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
+#                              Sets to $(LDFLAGS_OPTIMIZE) if false
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_SYMBOLS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_CONFIG_CFLAGS])
+    AC_MSG_CHECKING([for build with symbols])
+    AC_ARG_ENABLE(symbols,
+       AS_HELP_STRING([--enable-symbols],
+           [build with debugging symbols (default: off)]),
+       [tcl_ok=$enableval], [tcl_ok=no])
+    if test "$tcl_ok" = "no"; then
+       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
+       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
+       AC_MSG_RESULT([no])
+    else
+       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
+       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
+       if test "$tcl_ok" = "yes"; then
+           AC_MSG_RESULT([yes (standard debugging)])
+       fi
+    fi
+    AC_SUBST(CFLAGS_DEFAULT)
+    AC_SUBST(LDFLAGS_DEFAULT)
+
+    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
+       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
+    fi
+
+    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
+       if test "$tcl_ok" = "all"; then
+           AC_MSG_RESULT([enabled symbols mem debugging])
+       else
+           AC_MSG_RESULT([enabled $tcl_ok debugging])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_LANGINFO --
+#
+#      Allows use of modern nl_langinfo check for better l10n.
+#      This is only relevant for Unix.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-langinfo=yes|no (default is yes)
+#
+#      Defines the following vars:
+#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_LANGINFO], [
+    AC_ARG_ENABLE(langinfo,
+       AS_HELP_STRING([--enable-langinfo],
+           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
+       [langinfo_ok=$enableval], [langinfo_ok=yes])
+
+    HAVE_LANGINFO=0
+    if test "$langinfo_ok" = "yes"; then
+       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
+    fi
+    AC_MSG_CHECKING([whether to use nl_langinfo])
+    if test "$langinfo_ok" = "yes"; then
+       AC_CACHE_VAL(tcl_cv_langinfo_h, [
+           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
+                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
+       AC_MSG_RESULT([$tcl_cv_langinfo_h])
+       if test $tcl_cv_langinfo_h = yes; then
+           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
+       fi
+    else
+       AC_MSG_RESULT([$langinfo_ok])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_SYSTEM
+#
+#      Determine what the system is (some things cannot be easily checked
+#      on a feature-driven basis, alas). This can usually be done via the
+#      "uname" command.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Defines the following var:
+#
+#      system -        System/platform/version identification code.
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_SYSTEM], [
+    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
+       # TEA specific:
+       if test "${TEA_PLATFORM}" = "windows" ; then
+           tcl_cv_sys_version=windows
+       else
+           tcl_cv_sys_version=`uname -s`-`uname -r`
+           if test "$?" -ne 0 ; then
+               AC_MSG_WARN([can't find uname command])
+               tcl_cv_sys_version=unknown
+           else
+               if test "`uname -s`" = "AIX" ; then
+                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
+               fi
+               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
+                   tcl_cv_sys_version=NetBSD-Debian
+               fi
+           fi
+       fi
+    ])
+    system=$tcl_cv_sys_version
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_CFLAGS
+#
+#      Try to determine the proper flags to pass to the compiler
+#      for building shared libraries and other such nonsense.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substitutes the following vars:
+#
+#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
+#       LDFLAGS -      Flags to pass to the compiler when linking object
+#                       files into an executable application binary such
+#                       as tclsh.
+#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
+#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
+#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile.
+#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
+#                       of a shared library (may request position-independent
+#                       code, among other things).
+#       SHLIB_LD -      Base command to use for combining object files
+#                       into a shared library.
+#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
+#                       creating shared libraries.  This symbol typically
+#                       goes at the end of the "ld" commands that build
+#                       shared libraries. The value of the symbol defaults to
+#                       "${LIBS}" if all of the dependent libraries should
+#                       be specified when creating a shared library.  If
+#                       dependent libraries should not be specified (as on
+#                       SunOS 4.x, where they cause the link to fail, or in
+#                       general if Tcl and Tk aren't themselves shared
+#                       libraries), then this symbol has an empty string
+#                       as its value.
+#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
+#                       extensions.  An empty string means we don't know how
+#                       to use shared libraries on this platform.
+#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
+#                       in a static or shared library name, using the $PACKAGE_VERSION variable
+#                       to put the version in the right place.  This is used
+#                       by platforms that need non-standard library names.
+#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
+#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
+#                       on AIX, since a shared library needs to have
+#                       a .a extension whereas shared objects for loadable
+#                       extensions have a .so extension.  Defaults to
+#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
+#      CFLAGS_DEBUG -
+#                      Flags used when running the compiler in debug mode
+#      CFLAGS_OPTIMIZE -
+#                      Flags used when running the compiler in optimize mode
+#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_CFLAGS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+
+    # Step 0.a: Enable 64 bit support?
+
+    AC_MSG_CHECKING([if 64bit support is requested])
+    AC_ARG_ENABLE(64bit,
+       AS_HELP_STRING([--enable-64bit],
+           [enable 64bit support (default: off)]),
+       [do64bit=$enableval], [do64bit=no])
+    AC_MSG_RESULT([$do64bit])
+
+    # Step 0.b: Enable Solaris 64 bit VIS support?
+
+    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
+    AC_ARG_ENABLE(64bit-vis,
+       AS_HELP_STRING([--enable-64bit-vis],
+           [enable 64bit Sparc VIS support (default: off)]),
+       [do64bitVIS=$enableval], [do64bitVIS=no])
+    AC_MSG_RESULT([$do64bitVIS])
+    # Force 64bit on with VIS
+    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
+
+    # Step 0.c: Check if visibility support is available. Do this here so
+    # that platform specific alternatives can be used below if this fails.
+
+    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
+       tcl_cv_cc_visibility_hidden, [
+       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
+       AC_TRY_LINK([
+           extern __attribute__((__visibility__("hidden"))) void f(void);
+           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
+           tcl_cv_cc_visibility_hidden=no)
+       CFLAGS=$hold_cflags])
+    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
+       AC_DEFINE(MODULE_SCOPE,
+           [extern __attribute__((__visibility__("hidden")))],
+           [Compiler support for module scope symbols])
+       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
+    ])
+
+    # Step 0.d: Disable -rpath support?
+
+    AC_MSG_CHECKING([if rpath support is requested])
+    AC_ARG_ENABLE(rpath,
+       AS_HELP_STRING([--disable-rpath],
+           [disable rpath support (default: on)]),
+       [doRpath=$enableval], [doRpath=yes])
+    AC_MSG_RESULT([$doRpath])
+
+    # Set the variable "system" to hold the name and version number
+    # for the system.
+
+    TEA_CONFIG_SYSTEM
+
+    # Require ranlib early so we can override it in special cases below.
+
+    AC_REQUIRE([AC_PROG_RANLIB])
+
+    # Set configuration options based on system name and version.
+    # This is similar to Tcl's unix/tcl.m4 except that we've added a
+    # "windows" case and removed some core-only vars.
+
+    do64bit_ok=no
+    # default to '{$LIBS}' and set to "" on per-platform necessary basis
+    SHLIB_LD_LIBS='${LIBS}'
+    # When ld needs options to work in 64-bit mode, put them in
+    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
+    # is disabled by the user. [Bug 1016796]
+    LDFLAGS_ARCH=""
+    UNSHARED_LIB_SUFFIX=""
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
+    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
+    TCL_LIB_VERSIONS_OK=ok
+    CFLAGS_DEBUG=-g
+    AS_IF([test "$GCC" = yes], [
+       CFLAGS_OPTIMIZE=-O2
+       CFLAGS_WARNING="-Wall"
+    ], [
+       CFLAGS_OPTIMIZE=-O
+       CFLAGS_WARNING=""
+    ])
+    AC_CHECK_TOOL(AR, ar)
+    STLIB_LD='${AR} cr'
+    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
+    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
+    case $system in
+       # TEA specific:
+       windows)
+           MACHINE="X86"
+           if test "$do64bit" != "no" ; then
+               case "$do64bit" in
+                   amd64|x64|yes)
+                       MACHINE="AMD64" ; # default to AMD64 64-bit build
+                       ;;
+                   ia64)
+                       MACHINE="IA64"
+                       ;;
+               esac
+           fi
+
+           if test "$GCC" != "yes" ; then
+               if test "${SHARED_BUILD}" = "0" ; then
+                   runtime=-MT
+               else
+                   runtime=-MD
+               fi
+               case "x`echo \${VisualStudioVersion}`" in
+                   x1[[4-9]]*)
+                       lflags="${lflags} -nodefaultlib:libucrt.lib"
+                       TEA_ADD_LIBS([ucrt.lib])
+                   ;;
+                   *)
+                   ;;
+               esac
+
+                if test "$do64bit" != "no" ; then
+                   CC="cl.exe"
+                   RC="rc.exe"
+                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
+                   LINKBIN="link.exe"
+                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+                   # Avoid 'unresolved external symbol __security_cookie'
+                   # errors, c.f. http://support.microsoft.com/?id=894573
+                   TEA_ADD_LIBS([bufferoverflowU.lib])
+               else
+                   RC="rc"
+                   lflags="${lflags} -nologo"
+                   LINKBIN="link"
+                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+               fi
+           fi
+
+           if test "$GCC" = "yes"; then
+               # mingw gcc mode
+               AC_CHECK_TOOL(RC, windres)
+               CFLAGS_DEBUG="-g"
+               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+               SHLIB_LD='${CC} -shared'
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
+               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
+
+               AC_CACHE_CHECK(for cross-compile version of gcc,
+                       ac_cv_cross,
+                       AC_TRY_COMPILE([
+                           #ifdef _WIN32
+                               #error cross-compiler
+                           #endif
+                       ], [],
+                       ac_cv_cross=yes,
+                       ac_cv_cross=no)
+                     )
+                     if test "$ac_cv_cross" = "yes"; then
+                       case "$do64bit" in
+                           amd64|x64|yes)
+                               CC="x86_64-w64-mingw32-${CC}"
+                               LD="x86_64-w64-mingw32-ld"
+                               AR="x86_64-w64-mingw32-ar"
+                               RANLIB="x86_64-w64-mingw32-ranlib"
+                               RC="x86_64-w64-mingw32-windres"
+                           ;;
+                           *)
+                               CC="i686-w64-mingw32-${CC}"
+                               LD="i686-w64-mingw32-ld"
+                               AR="i686-w64-mingw32-ar"
+                               RANLIB="i686-w64-mingw32-ranlib"
+                               RC="i686-w64-mingw32-windres"
+                           ;;
+                       esac
+               fi
+
+           else
+               SHLIB_LD="${LINKBIN} -dll ${lflags}"
+               # link -lib only works when -lib is the first arg
+               STLIB_LD="${LINKBIN} -lib ${lflags}"
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
+               PATHTYPE=-w
+               # For information on what debugtype is most useful, see:
+               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
+               # and also
+               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
+               # This essentially turns it all on.
+               LDFLAGS_DEBUG="-debug -debugtype:cv"
+               LDFLAGS_OPTIMIZE="-release"
+               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
+               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
+           fi
+
+           SHLIB_SUFFIX=".dll"
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
+
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       AIX-*)
+           AS_IF([test "$GCC" != "yes"], [
+               # AIX requires the _r compiler when gcc isn't being used
+               case "${CC}" in
+                   *_r|*_r\ *)
+                       # ok ...
+                       ;;
+                   *)
+                       # Make sure only first arg gets _r
+                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
+                       ;;
+               esac
+               AC_MSG_RESULT([Using $CC for compiling with threads])
+           ])
+           LIBS="$LIBS -lc"
+           SHLIB_CFLAGS=""
+           SHLIB_SUFFIX=".so"
+
+           LD_LIBRARY_PATH_VAR="LIBPATH"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS -q64"
+                   LDFLAGS_ARCH="-q64"
+                   RANLIB="${RANLIB} -X64"
+                   AR="${AR} -X64"
+                   SHLIB_LD_FLAGS="-b64"
+               ])
+           ])
+
+           AS_IF([test "`uname -m`" = ia64], [
+               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               AS_IF([test "$GCC" = yes], [
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               ], [
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
+               ])
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ], [
+               AS_IF([test "$GCC" = yes], [
+                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
+               ], [
+                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
+                   LDFLAGS="$LDFLAGS -brtl"
+               ])
+               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       BeOS*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} -nostart'
+           SHLIB_SUFFIX=".so"
+
+           #-----------------------------------------------------------
+           # Check for inet_ntoa in -lbind, for BeOS (which also needs
+           # -lsocket, even if the network functions are in -lnet which
+           # is always linked to, for compatibility.
+           #-----------------------------------------------------------
+           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
+           ;;
+       BSD/OS-2.1*|BSD/OS-3*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="shlicc -r"
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       BSD/OS-4.*)
+           SHLIB_CFLAGS="-export-dynamic -fPIC"
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       CYGWIN_*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".dll"
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
+           EXEEXT=".exe"
+           do64bit_ok=yes
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       dgux*)
+           SHLIB_CFLAGS="-K PIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       Haiku*)
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
+           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
+           ;;
+       HP-UX-*.11.*)
+           # Use updated header definitions where possible
+           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
+           # TEA specific: Needed by Tcl, but not most extensions
+           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
+           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
+
+           AS_IF([test "`uname -m`" = ia64], [
+               SHLIB_SUFFIX=".so"
+           ], [
+               SHLIB_SUFFIX=".sl"
+           ])
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ])
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               CFLAGS="$CFLAGS -z"
+           ])
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = "yes"], [
+               AS_IF([test "$GCC" = yes], [
+                   case `${CC} -dumpmachine` in
+                       hppa64*)
+                           # 64-bit gcc in use.  Fix flags for GNU ld.
+                           do64bit_ok=yes
+                           SHLIB_LD='${CC} -shared'
+                           AS_IF([test $doRpath = yes], [
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+                           ;;
+                       *)
+                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
+                           ;;
+                   esac
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS +DD64"
+                   LDFLAGS_ARCH="+DD64"
+               ])
+           ]) ;;
+       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
+           SHLIB_SUFFIX=".sl"
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               SHLIB_LD_LIBS=""
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ]) ;;
+       IRIX-5.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AC_LIBOBJ(mkstemp)
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           ;;
+       IRIX-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           AS_IF([test "$GCC" = yes], [
+               CFLAGS="$CFLAGS -mabi=n32"
+               LDFLAGS="$LDFLAGS -mabi=n32"
+           ], [
+               case $system in
+                   IRIX-6.3)
+                       # Use to build 6.2 compatible binaries on 6.3.
+                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
+                       ;;
+                   *)
+                       CFLAGS="$CFLAGS -n32"
+                       ;;
+               esac
+               LDFLAGS="$LDFLAGS -n32"
+           ])
+           ;;
+       IRIX64-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+
+           # Check to enable 64-bit flags for compiler/linker
+
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported by gcc])
+               ], [
+                   do64bit_ok=yes
+                   SHLIB_LD="ld -64 -shared -rdata_shared"
+                   CFLAGS="$CFLAGS -64"
+                   LDFLAGS_ARCH="-64"
+               ])
+           ])
+           ;;
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+
+           # TEA specific:
+           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
+           AS_IF([test $do64bit = yes], [
+               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
+                   hold_cflags=$CFLAGS
+                   CFLAGS="$CFLAGS -m64"
+                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
+                   CFLAGS=$hold_cflags])
+               AS_IF([test $tcl_cv_cc_m64 = yes], [
+                   CFLAGS="$CFLAGS -m64"
+                   do64bit_ok=yes
+               ])
+          ])
+
+           # The combo of gcc + glibc has a bug related to inlining of
+           # functions like strtod(). The -fno-builtin flag should address
+           # this problem but it does not work. The -fno-inline flag is kind
+           # of overkill but it works. Disable inlining only when one of the
+           # files in compat/*.c is being linked in.
+
+           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
+           ;;
+       Lynx*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           CFLAGS_OPTIMIZE=-02
+           SHLIB_LD='${CC} -shared'
+           LD_FLAGS="-Wl,--export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           ;;
+       OpenBSD-*)
+           arch=`arch -s`
+           case "$arch" in
+           alpha|sparc64)
+               SHLIB_CFLAGS="-fPIC"
+               ;;
+           *)
+               SHLIB_CFLAGS="-fpic"
+               ;;
+           esac
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
+           CFLAGS_OPTIMIZE="-O2"
+           # On OpenBSD:       Compile with -pthread
+           #           Don't link with -lpthread
+           LIBS=`echo $LIBS | sed s/-lpthread//`
+           CFLAGS="$CFLAGS -pthread"
+           # OpenBSD doesn't do version numbers with dots.
+           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       NetBSD-*)
+           # NetBSD has ELF and can use 'cc -shared' to build shared libs
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           # The -pthread needs to go in the CFLAGS, not LIBS
+           LIBS=`echo $LIBS | sed s/-pthread//`
+           CFLAGS="$CFLAGS -pthread"
+           LDFLAGS="$LDFLAGS -pthread"
+           ;;
+       Darwin-*)
+           CFLAGS_OPTIMIZE="-Os"
+           SHLIB_CFLAGS="-fno-common"
+           # To avoid discrepancies between what headers configure sees during
+           # preprocessing tests and compiling tests, move any -isysroot and
+           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
+           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
+           CFLAGS="`echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
+           AS_IF([test $do64bit = yes], [
+               case `arch` in
+                   ppc)
+                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
+                               tcl_cv_cc_arch_ppc64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
+                                   tcl_cv_cc_arch_ppc64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           do64bit_ok=yes
+                       ]);;
+                   i386)
+                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
+                               tcl_cv_cc_arch_x86_64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
+                                   tcl_cv_cc_arch_x86_64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           do64bit_ok=yes
+                       ]);;
+                   *)
+                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
+               esac
+           ], [
+               # Check for combined 32-bit and 64-bit fat build
+               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
+                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
+                   fat_32_64=yes])
+           ])
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
+           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_single_module = yes], [
+               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
+           ])
+           # TEA specific: link shlib with current and compatibility version flags
+           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
+           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
+           SHLIB_SUFFIX=".dylib"
+           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
+           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
+                   tcl_cv_ld_search_paths_first, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
+                       tcl_cv_ld_search_paths_first=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+           ])
+           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
+                   [Compiler support for module scope symbols])
+               tcl_cv_cc_visibility_hidden=yes
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
+           # TEA specific: for combined 32 & 64 bit fat builds of Tk
+           # extensions, verify that 64-bit build is possible.
+           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
+                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
+                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
+                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
+                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
+                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
+                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
+                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
+                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               # remove 64-bit arch flags from CFLAGS et al. if configuration
+               # does not support 64-bit.
+               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
+                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
+                   for v in CFLAGS CPPFLAGS LDFLAGS; do
+                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
+                   done])
+           ])
+           ;;
+       OS/390-*)
+           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
+           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
+               [Should OS/390 do the right thing with sockets?])
+           ;;
+       OSF1-V*)
+           # Digital OSF/1
+           SHLIB_CFLAGS=""
+           AS_IF([test "$SHARED_BUILD" = 1], [
+               SHLIB_LD='ld -shared -expect_unresolved "*"'
+           ], [
+               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
+           ])
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
+               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
+           # see pthread_intro(3) for pthread support on osf1, k.furukawa
+           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
+           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
+           LIBS=`echo $LIBS | sed s/-lpthreads//`
+           AS_IF([test "$GCC" = yes], [
+               LIBS="$LIBS -lpthread -lmach -lexc"
+           ], [
+               CFLAGS="$CFLAGS -pthread"
+               LDFLAGS="$LDFLAGS -pthread"
+           ])
+           ;;
+       QNX-6*)
+           # QNX RTP
+           # This may work for all QNX, but it was only reported for v6.
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD="ld -Bshareable -x"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SCO_SV-3.2*)
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_CFLAGS="-fPIC -melf"
+               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
+           ], [
+               SHLIB_CFLAGS="-Kpic -belf"
+               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
+           ])
+           SHLIB_LD="ld -G"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SunOS-5.[[0-6]])
+           # Careful to not let 5.10+ fall into this case
+
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       SunOS-5*)
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               arch=`isainfo`
+               AS_IF([test "$arch" = "sparcv9 sparc"], [
+                   AS_IF([test "$GCC" = yes], [
+                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
+                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
+                       ], [
+                           do64bit_ok=yes
+                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
+                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
+                           SHLIB_CFLAGS="-fPIC"
+                       ])
+                   ], [
+                       do64bit_ok=yes
+                       AS_IF([test "$do64bitVIS" = yes], [
+                           CFLAGS="$CFLAGS -xarch=v9a"
+                           LDFLAGS_ARCH="-xarch=v9a"
+                       ], [
+                           CFLAGS="$CFLAGS -xarch=v9"
+                           LDFLAGS_ARCH="-xarch=v9"
+                       ])
+                       # Solaris 64 uses this as well
+                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
+                   ])
+               ], [AS_IF([test "$arch" = "amd64 i386"], [
+                   AS_IF([test "$GCC" = yes], [
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               do64bit_ok=yes
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
+                       esac
+                   ], [
+                       do64bit_ok=yes
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               CFLAGS="$CFLAGS -xarch=amd64"
+                               LDFLAGS="$LDFLAGS -xarch=amd64";;
+                       esac
+                   ])
+               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
+           ])
+
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+               AS_IF([test "$do64bit_ok" = yes], [
+                   AS_IF([test "$arch" = "sparcv9 sparc"], [
+                       # We need to specify -static-libgcc or we need to
+                       # add the path to the sparv9 libgcc.
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
+                       # for finding sparcv9 libgcc, get the regular libgcc
+                       # path, remove so name and append 'sparcv9'
+                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
+                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
+                   ], [AS_IF([test "$arch" = "amd64 i386"], [
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
+                   ])])
+               ])
+           ], [
+               case $system in
+                   SunOS-5.[[1-9]][[0-9]]*)
+                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
+                   *)
+                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
+               esac
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ])
+           ;;
+       UNIX_SV* | UnixWare-5*)
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
+           # that don't grok the -Bexport option.  Test that it does.
+           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_Bexport = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+    esac
+
+    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
+       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
+    ])
+
+dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
+dnl # until the end of configure, as configure's compile and link tests use
+dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
+dnl # preprocessing tests use only CPPFLAGS.
+    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
+
+    # Add in the arch flags late to ensure it wasn't removed.
+    # Not necessary in TEA, but this is aligned with core
+    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
+
+    # If we're running gcc, then change the C flags for compiling shared
+    # libraries to the right flags for gcc, instead of those for the
+    # standard manufacturer compiler.
+
+    AS_IF([test "$GCC" = yes], [
+       case $system in
+           AIX-*) ;;
+           BSD/OS*) ;;
+           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
+           IRIX*) ;;
+           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
+           Darwin-*) ;;
+           SCO_SV-3.2*) ;;
+           windows) ;;
+           *) SHLIB_CFLAGS="-fPIC" ;;
+       esac])
+
+    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+       AC_DEFINE(MODULE_SCOPE, [extern],
+           [No Compiler support for module scope symbols])
+    ])
+
+    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
+    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
+
+    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
+       AC_CACHE_CHECK(for SEH support in compiler,
+           tcl_cv_seh,
+       AC_TRY_RUN([
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+
+           int main(int argc, char** argv) {
+               int a, b = 0;
+               __try {
+                   a = 666 / b;
+               }
+               __except (EXCEPTION_EXECUTE_HANDLER) {
+                   return 0;
+               }
+               return 1;
+           }
+       ],
+           tcl_cv_seh=yes,
+           tcl_cv_seh=no,
+           tcl_cv_seh=no)
+       )
+       if test "$tcl_cv_seh" = "no" ; then
+           AC_DEFINE(HAVE_NO_SEH, 1,
+                   [Defined when mingw does not support SEH])
+       fi
+
+       #
+       # Check to see if the excpt.h include file provided contains the
+       # definition for EXCEPTION_DISPOSITION; if not, which is the case
+       # with Cygwin's version as of 2002-04-10, define it to be int,
+       # sufficient for getting the current code to work.
+       #
+       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
+           tcl_cv_eh_disposition,
+           AC_TRY_COMPILE([
+#          define WIN32_LEAN_AND_MEAN
+#          include <windows.h>
+#          undef WIN32_LEAN_AND_MEAN
+           ],[
+               EXCEPTION_DISPOSITION x;
+           ],
+               tcl_cv_eh_disposition=yes,
+               tcl_cv_eh_disposition=no)
+       )
+       if test "$tcl_cv_eh_disposition" = "no" ; then
+       AC_DEFINE(EXCEPTION_DISPOSITION, int,
+               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
+       fi
+
+       # Check to see if winnt.h defines CHAR, SHORT, and LONG
+       # even if VOID has already been #defined. The win32api
+       # used by mingw and cygwin is known to do this.
+
+       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
+           tcl_cv_winnt_ignore_void,
+           AC_TRY_COMPILE([
+#define VOID void
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+           ], [
+               CHAR c;
+               SHORT s;
+               LONG l;
+           ],
+        tcl_cv_winnt_ignore_void=yes,
+        tcl_cv_winnt_ignore_void=no)
+       )
+       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
+           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
+                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
+       fi
+    fi
+
+       # See if the compiler supports casting to a union type.
+       # This is used to stop gcc from printing a compiler
+       # warning when initializing a union member.
+
+       AC_CACHE_CHECK(for cast to union support,
+           tcl_cv_cast_to_union,
+           AC_TRY_COMPILE([],
+           [
+                 union foo { int i; double d; };
+                 union foo f = (union foo) (int) 0;
+           ],
+           tcl_cv_cast_to_union=yes,
+           tcl_cv_cast_to_union=no)
+       )
+       if test "$tcl_cv_cast_to_union" = "yes"; then
+           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
+                   [Defined when compiler supports casting to union type.])
+       fi
+
+       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
+
+    AC_SUBST(CFLAGS_DEBUG)
+    AC_SUBST(CFLAGS_OPTIMIZE)
+    AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
+
+    AC_SUBST(STLIB_LD)
+    AC_SUBST(SHLIB_LD)
+
+    AC_SUBST(SHLIB_LD_LIBS)
+    AC_SUBST(SHLIB_CFLAGS)
+
+    AC_SUBST(LD_LIBRARY_PATH_VAR)
+
+    # These must be called after we do the basic CFLAGS checks and
+    # verify any possible 64-bit or similar switches are necessary
+    TEA_TCL_EARLY_FLAGS
+    TEA_TCL_64BIT_FLAGS
+])
+
+#--------------------------------------------------------------------
+# TEA_SERIAL_PORT
+#
+#      Determine which interface to use to talk to the serial port.
+#      Note that #include lines must begin in leftmost column for
+#      some compilers to recognize them as preprocessor directives,
+#      and some build environments have stdin not pointing at a
+#      pseudo-terminal (usually /dev/null instead.)
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines only one of the following vars:
+#              HAVE_SYS_MODEM_H
+#              USE_TERMIOS
+#              USE_TERMIO
+#              USE_SGTTY
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_SERIAL_PORT], [
+    AC_CHECK_HEADERS(sys/modem.h)
+    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
+    AC_TRY_RUN([
+#include <termios.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termio.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termios.h>
+#include <errno.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <termio.h>
+#include <errno.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+#include <errno.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
+    fi])
+    case $tcl_cv_api_serial in
+       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
+       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
+       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_PATH_X
+#
+#      Locate the X11 header files and the X11 library archive.  Try
+#      the ac_path_x macro first, but if it doesn't find the X stuff
+#      (e.g. because there's no xmkmf program) then check through
+#      a list of possible directories.  Under some conditions the
+#      autoconf macro will return an include directory that contains
+#      no include files, so double-check its result just to be safe.
+#
+#      This should be called after TEA_CONFIG_CFLAGS as setting the
+#      LIBS line can confuse some configure macro magic.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets the following vars:
+#              XINCLUDES
+#              XLIBSW
+#              PKG_LIBS (appends to)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_X], [
+    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
+       TEA_PATH_UNIX_X
+    fi
+])
+
+AC_DEFUN([TEA_PATH_UNIX_X], [
+    AC_PATH_X
+    not_really_there=""
+    if test "$no_x" = ""; then
+       if test "$x_includes" = ""; then
+           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
+       else
+           if test ! -r $x_includes/X11/Xlib.h; then
+               not_really_there="yes"
+           fi
+       fi
+    fi
+    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
+       AC_MSG_CHECKING([for X11 header files])
+       found_xincludes="no"
+       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
+       if test "$found_xincludes" = "no"; then
+           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
+           for i in $dirs ; do
+               if test -r $i/X11/Xlib.h; then
+                   AC_MSG_RESULT([$i])
+                   XINCLUDES=" -I$i"
+                   found_xincludes="yes"
+                   break
+               fi
+           done
+       fi
+    else
+       if test "$x_includes" != ""; then
+           XINCLUDES="-I$x_includes"
+           found_xincludes="yes"
+       fi
+    fi
+    if test "$found_xincludes" = "no"; then
+       AC_MSG_RESULT([couldn't find any!])
+    fi
+
+    if test "$no_x" = yes; then
+       AC_MSG_CHECKING([for X11 libraries])
+       XLIBSW=nope
+       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
+       for i in $dirs ; do
+           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
+               AC_MSG_RESULT([$i])
+               XLIBSW="-L$i -lX11"
+               x_libraries="$i"
+               break
+           fi
+       done
+    else
+       if test "$x_libraries" = ""; then
+           XLIBSW=-lX11
+       else
+           XLIBSW="-L$x_libraries -lX11"
+       fi
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_MSG_RESULT([could not find any!  Using -lX11.])
+       XLIBSW=-lX11
+    fi
+    # TEA specific:
+    if test x"${XLIBSW}" != x ; then
+       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BLOCKING_STYLE
+#
+#      The statements below check for systems where POSIX-style
+#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
+#      On these systems (mostly older ones), use the old BSD-style
+#      FIONBIO approach instead.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              HAVE_SYS_IOCTL_H
+#              HAVE_SYS_FILIO_H
+#              USE_FIONBIO
+#              O_NONBLOCK
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BLOCKING_STYLE], [
+    AC_CHECK_HEADERS(sys/ioctl.h)
+    AC_CHECK_HEADERS(sys/filio.h)
+    TEA_CONFIG_SYSTEM
+    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
+    case $system in
+       OSF*)
+           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
+           AC_MSG_RESULT([FIONBIO])
+           ;;
+       *)
+           AC_MSG_RESULT([O_NONBLOCK])
+           ;;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_TIME_HANDLER
+#
+#      Checks how the system deals with time.h, what time structures
+#      are used on the system, and what fields the structures have.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              USE_DELTA_FOR_TZ
+#              HAVE_TM_GMTOFF
+#              HAVE_TM_TZADJ
+#              HAVE_TIMEZONE_VAR
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TIME_HANDLER], [
+    AC_CHECK_HEADERS(sys/time.h)
+    AC_HEADER_TIME
+    AC_STRUCT_TIMEZONE
+
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
+
+    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
+           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
+    if test $tcl_cv_member_tm_tzadj = yes ; then
+       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
+    fi
+
+    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
+           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
+    if test $tcl_cv_member_tm_gmtoff = yes ; then
+       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
+    fi
+
+    #
+    # Its important to include time.h in this check, as some systems
+    # (like convex) have timezone functions, etc.
+    #
+    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
+       AC_TRY_COMPILE([#include <time.h>],
+           [extern long timezone;
+           timezone += 1;
+           exit (0);],
+           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
+    if test $tcl_cv_timezone_long = yes ; then
+       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+    else
+       #
+       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
+       #
+       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
+           AC_TRY_COMPILE([#include <time.h>],
+               [extern time_t timezone;
+               timezone += 1;
+               exit (0);],
+               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
+       if test $tcl_cv_timezone_time = yes ; then
+           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BUGGY_STRTOD
+#
+#      Under Solaris 2.4, strtod returns the wrong value for the
+#      terminating character under some conditions.  Check for this
+#      and if the problem exists use a substitute procedure
+#      "fixstrtod" (provided by Tcl) that corrects the error.
+#      Also, on Compaq's Tru64 Unix 5.0,
+#      strtod(" ") returns 0.0 instead of a failure to convert.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Might defines some of the following vars:
+#              strtod (=fixstrtod)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BUGGY_STRTOD], [
+    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
+    if test "$tcl_strtod" = 1; then
+       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
+           AC_TRY_RUN([
+               #include <stdlib.h>
+               extern double strtod();
+               int main() {
+                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
+                   char *term;
+                   double value;
+                   value = strtod(infString, &term);
+                   if ((term != infString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(nanString, &term);
+                   if ((term != nanString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(spaceString, &term);
+                   if (term == (spaceString+1)) {
+                       exit(1);
+                   }
+                   exit(0);
+               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
+                   tcl_cv_strtod_buggy=buggy)])
+       if test "$tcl_cv_strtod_buggy" = buggy; then
+           AC_LIBOBJ([fixstrtod])
+           USE_COMPAT=1
+           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_EARLY_FLAGS
+#
+#      Check for what flags are needed to be passed so the correct OS
+#      features are available.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              _ISOC99_SOURCE
+#              _LARGEFILE64_SOURCE
+#              _LARGEFILE_SOURCE64
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_EARLY_FLAG],[
+    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
+       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
+           AC_TRY_COMPILE([[#define ]$1[ 1
+]$2], $3,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
+    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
+       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
+       tcl_flags="$tcl_flags $1"
+    fi
+])
+
+AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
+    AC_MSG_CHECKING([for required early compiler flags])
+    tcl_flags=""
+    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
+       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
+       [struct stat64 buf; int i = stat64("/", &buf);])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
+       [char *p = (char *)open64;])
+    if test "x${tcl_flags}" = "x" ; then
+       AC_MSG_RESULT([none])
+    else
+       AC_MSG_RESULT([${tcl_flags}])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_64BIT_FLAGS
+#
+#      Check for what is defined in the way of 64-bit features.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              TCL_WIDE_INT_IS_LONG
+#              TCL_WIDE_INT_TYPE
+#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
+#              HAVE_STRUCT_STAT64
+#              HAVE_TYPE_OFF64_T
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
+    AC_MSG_CHECKING([for 64-bit integer type])
+    AC_CACHE_VAL(tcl_cv_type_64bit,[
+       tcl_cv_type_64bit=none
+       # See if the compiler knows natively about __int64
+       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
+           tcl_type_64bit=__int64, tcl_type_64bit="long long")
+       # See if we could use long anyway  Note that we substitute in the
+       # type that is our current guess for a 64-bit type inside this check
+       # program, so it should be modified only carefully...
+        AC_TRY_COMPILE(,[switch (0) {
+            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
+        }],tcl_cv_type_64bit=${tcl_type_64bit})])
+    if test "${tcl_cv_type_64bit}" = none ; then
+       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
+       AC_MSG_RESULT([yes])
+    elif test "${tcl_cv_type_64bit}" = "__int64" \
+               -a "${TEA_PLATFORM}" = "windows" ; then
+       # TEA specific: We actually want to use the default tcl.h checks in
+       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
+       AC_MSG_RESULT([using Tcl header defaults])
+    else
+       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
+           [What type should be used to define wide integers?])
+       AC_MSG_RESULT([${tcl_cv_type_64bit}])
+
+       # Now check for auxiliary declarations
+       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 p;],
+               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
+       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
+            p = readdir64(d); rewinddir64(d); closedir64(d);],
+               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
+       if test "x${tcl_cv_DIR64}" = "xyes" ; then
+           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
+           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
+],
+               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
+       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
+       fi
+
+       AC_CHECK_FUNCS(open64 lseek64)
+       AC_MSG_CHECKING([for off64_t])
+       AC_CACHE_VAL(tcl_cv_type_off64_t,[
+           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
+],
+               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
+       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
+       dnl functions lseek64 and open64 are defined.
+       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
+               test "x${ac_cv_func_lseek64}" = "xyes" && \
+               test "x${ac_cv_func_open64}" = "xyes" ; then
+           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
+           AC_MSG_RESULT([yes])
+       else
+           AC_MSG_RESULT([no])
+       fi
+    fi
+])
+
+##
+## Here ends the standard Tcl configuration bits and starts the
+## TEA specific functions
+##
+
+#------------------------------------------------------------------------
+# TEA_INIT --
+#
+#      Init various Tcl Extension Architecture (TEA) variables.
+#      This should be the first called TEA_* macro.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              CYGPATH
+#              EXEEXT
+#      Defines only:
+#              TEA_VERSION
+#              TEA_INITED
+#              TEA_PLATFORM (windows or unix)
+#
+# "cygpath" is used on windows to generate native path names for include
+# files. These variables should only be used with the compiler and linker
+# since they generate native path names.
+#
+# EXEEXT
+#      Select the executable extension based on the host type.  This
+#      is a lightweight replacement for AC_EXEEXT that doesn't require
+#      a compiler.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INIT], [
+    TEA_VERSION="3.13"
+
+    AC_MSG_CHECKING([TEA configuration])
+    if test x"${PACKAGE_NAME}" = x ; then
+       AC_MSG_ERROR([
+The PACKAGE_NAME variable must be defined by your TEA configure.ac])
+    fi
+    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
+
+    # If the user did not set CFLAGS, set it now to keep macros
+    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
+    if test "${CFLAGS+set}" != "set" ; then
+       CFLAGS=""
+    fi
+
+    case "`uname -s`" in
+       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
+           EXEEXT=".exe"
+           TEA_PLATFORM="windows"
+           ;;
+       *CYGWIN_*)
+           EXEEXT=".exe"
+           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
+           ;;
+       *)
+           CYGPATH=echo
+           # Maybe we are cross-compiling....
+           case ${host_alias} in
+               *mingw32*)
+               EXEEXT=".exe"
+               TEA_PLATFORM="windows"
+               ;;
+           *)
+               EXEEXT=""
+               TEA_PLATFORM="unix"
+               ;;
+           esac
+           ;;
+    esac
+
+    # Check if exec_prefix is set. If not use fall back to prefix.
+    # Note when adjusted, so that TEA_PREFIX can correct for this.
+    # This is needed for recursive configures, since autoconf propagates
+    # $prefix, but not $exec_prefix (doh!).
+    if test x$exec_prefix = xNONE ; then
+       exec_prefix_default=yes
+       exec_prefix=$prefix
+    fi
+
+    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
+
+    AC_SUBST(EXEEXT)
+    AC_SUBST(CYGPATH)
+
+    # This package name must be replaced statically for AC_SUBST to work
+    AC_SUBST(PKG_LIB_FILE)
+    # Substitute STUB_LIB_FILE in case package creates a stub library too.
+    AC_SUBST(PKG_STUB_LIB_FILE)
+
+    # We AC_SUBST these here to ensure they are subst'ed,
+    # in case the user doesn't call TEA_ADD_...
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+    AC_SUBST(PKG_TCL_SOURCES)
+    AC_SUBST(PKG_HEADERS)
+    AC_SUBST(PKG_INCLUDES)
+    AC_SUBST(PKG_LIBS)
+    AC_SUBST(PKG_CFLAGS)
+
+    # Configure the installer.
+    TEA_INSTALLER
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_SOURCES
+#              PKG_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       case $i in
+           [\$]*)
+               # allow $-var names
+               PKG_SOURCES="$PKG_SOURCES $i"
+               PKG_OBJECTS="$PKG_OBJECTS $i"
+               ;;
+           *)
+               # check for existence - allows for generic/win/unix VPATH
+               # To add more dirs here (like 'src'), you have to update VPATH
+               # in Makefile.in as well
+               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+                   -a ! -f "${srcdir}/macosx/$i" \
+                   ; then
+                   AC_MSG_ERROR([could not find source file '$i'])
+               fi
+               PKG_SOURCES="$PKG_SOURCES $i"
+               # this assumes it is in a VPATH dir
+               i=`basename $i`
+               # handle user calling this before or after TEA_SETUP_COMPILER
+               if test x"${OBJEXT}" != x ; then
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+               else
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+               fi
+               PKG_OBJECTS="$PKG_OBJECTS $j"
+               ;;
+       esac
+    done
+    AC_SUBST(PKG_SOURCES)
+    AC_SUBST(PKG_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_STUB_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_STUB_SOURCES
+#              PKG_STUB_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_STUB_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence - allows for generic/win/unix VPATH
+       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+           -a ! -f "${srcdir}/macosx/$i" \
+           ; then
+           AC_MSG_ERROR([could not find stub source file '$i'])
+       fi
+       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
+       # this assumes it is in a VPATH dir
+       i=`basename $i`
+       # handle user calling this before or after TEA_SETUP_COMPILER
+       if test x"${OBJEXT}" != x ; then
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+       else
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+       fi
+       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
+    done
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_TCL_SOURCES --
+#
+#      Specify one or more Tcl source files.  These should be platform
+#      independent runtime files.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_TCL_SOURCES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_TCL_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
+       fi
+       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
+    done
+    AC_SUBST(PKG_TCL_SOURCES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_HEADERS --
+#
+#      Specify one or more source headers.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_HEADERS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_HEADERS], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
+       fi
+       PKG_HEADERS="$PKG_HEADERS $i"
+    done
+    AC_SUBST(PKG_HEADERS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_INCLUDES --
+#
+#      Specify one or more include dirs.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_INCLUDES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_INCLUDES], [
+    vars="$@"
+    for i in $vars; do
+       PKG_INCLUDES="$PKG_INCLUDES $i"
+    done
+    AC_SUBST(PKG_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_LIBS --
+#
+#      Specify one or more libraries.  Users should check for
+#      the right platform before adding to their list.  For Windows,
+#      libraries provided in "foo.lib" format will be converted to
+#      "-lfoo" when using GCC (mingw).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_LIBS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_LIBS], [
+    vars="$@"
+    for i in $vars; do
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
+           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
+       fi
+       PKG_LIBS="$PKG_LIBS $i"
+    done
+    AC_SUBST(PKG_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CFLAGS --
+#
+#      Specify one or more CFLAGS.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_CFLAGS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CFLAGS], [
+    PKG_CFLAGS="$PKG_CFLAGS $@"
+    AC_SUBST(PKG_CFLAGS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CLEANFILES --
+#
+#      Specify one or more CLEANFILES.
+#
+# Arguments:
+#      one or more file names to clean target
+#
+# Results:
+#
+#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CLEANFILES], [
+    CLEANFILES="$CLEANFILES $@"
+])
+
+#------------------------------------------------------------------------
+# TEA_PREFIX --
+#
+#      Handle the --prefix=... option by defaulting to what Tcl gave
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      If --prefix or --exec-prefix was not specified, $prefix and
+#      $exec_prefix will be set to the values given to Tcl when it was
+#      configured.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_PREFIX], [
+    if test "${prefix}" = "NONE"; then
+       prefix_default=yes
+       if test x"${TCL_PREFIX}" != x; then
+           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
+           prefix=${TCL_PREFIX}
+       else
+           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
+           prefix=/usr/local
+       fi
+    fi
+    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
+       -o x"${exec_prefix_default}" = x"yes" ; then
+       if test x"${TCL_EXEC_PREFIX}" != x; then
+           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
+           exec_prefix=${TCL_EXEC_PREFIX}
+       else
+           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
+           exec_prefix=$prefix
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER_CC --
+#
+#      Do compiler checks the way we want.  This is just a replacement
+#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER_CC], [
+    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
+    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
+
+    AC_PROG_CC
+    AC_PROG_CPP
+
+    #--------------------------------------------------------------------
+    # Checks to see if the make program sets the $MAKE variable.
+    #--------------------------------------------------------------------
+
+    AC_PROG_MAKE_SET
+
+    #--------------------------------------------------------------------
+    # Find ranlib
+    #--------------------------------------------------------------------
+
+    AC_CHECK_TOOL(RANLIB, ranlib)
+
+    #--------------------------------------------------------------------
+    # Determines the correct binary file extension (.o, .obj, .exe etc.)
+    #--------------------------------------------------------------------
+
+    AC_OBJEXT
+    AC_EXEEXT
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER --
+#
+#      Do compiler checks that use the compiler.  This must go after
+#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER], [
+    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
+    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
+
+    #------------------------------------------------------------------------
+    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
+    # It makes compiling go faster.  (This is only a performance feature.)
+    #------------------------------------------------------------------------
+
+    if test -z "$no_pipe" -a -n "$GCC"; then
+       AC_CACHE_CHECK([if the compiler understands -pipe],
+           tcl_cv_cc_pipe, [
+           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
+           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
+           CFLAGS=$hold_cflags])
+       if test $tcl_cv_cc_pipe = yes; then
+           CFLAGS="$CFLAGS -pipe"
+       fi
+    fi
+
+    #--------------------------------------------------------------------
+    # Common compiler flag setup
+    #--------------------------------------------------------------------
+
+    AC_C_BIGENDIAN
+])
+
+#------------------------------------------------------------------------
+# TEA_MAKE_LIB --
+#
+#      Generate a line that can be used to build a shared/unshared library
+#      in a platform independent manner.
+#
+# Arguments:
+#      none
+#
+#      Requires:
+#
+# Results:
+#
+#      Defines the following vars:
+#      CFLAGS -        Done late here to note disturb other AC macros
+#       MAKE_LIB -      Command to execute to build the Tcl library;
+#                       differs depending on whether or not Tcl is being
+#                       compiled as a shared library.
+#      MAKE_SHARED_LIB Makefile rule for building a shared library
+#      MAKE_STATIC_LIB Makefile rule for building a static library
+#      MAKE_STUB_LIB   Makefile rule for building a stub library
+#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
+#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_MAKE_LIB], [
+    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
+       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       AC_EGREP_CPP([manifest needed], [
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+print("manifest needed")
+#endif
+       ], [
+       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
+       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
+       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
+       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
+       TEA_ADD_CLEANFILES([*.manifest])
+       ])
+       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
+    else
+       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
+    fi
+
+    if test "${SHARED_BUILD}" = "1" ; then
+       MAKE_LIB="${MAKE_SHARED_LIB} "
+    else
+       MAKE_LIB="${MAKE_STATIC_LIB} "
+    fi
+
+    #--------------------------------------------------------------------
+    # Shared libraries and static libraries have different names.
+    # Use the double eval to make sure any variables in the suffix is
+    # substituted. (@@@ Might not be necessary anymore)
+    #--------------------------------------------------------------------
+
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       if test "${SHARED_BUILD}" = "1" ; then
+           # We force the unresolved linking of symbols that are really in
+           # the private libraries of Tcl and Tk.
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
+           fi
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
+           if test "$GCC" = "yes"; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
+           fi
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+       else
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+           if test "$GCC" = "yes"; then
+               PKG_LIB_FILE=lib${PKG_LIB_FILE}
+           fi
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+       if test "$GCC" = "yes"; then
+           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
+       fi
+       # These aren't needed on Windows (either MSVC or gcc)
+       RANLIB=:
+       RANLIB_STUB=:
+    else
+       RANLIB_STUB="${RANLIB}"
+       if test "${SHARED_BUILD}" = "1" ; then
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
+           fi
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+           RANLIB=:
+       else
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+    fi
+
+    # These are escaped so that only CFLAGS is picked up at configure time.
+    # The other values will be substituted at make time.
+    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
+    if test "${SHARED_BUILD}" = "1" ; then
+       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
+    fi
+
+    AC_SUBST(MAKE_LIB)
+    AC_SUBST(MAKE_SHARED_LIB)
+    AC_SUBST(MAKE_STATIC_LIB)
+    AC_SUBST(MAKE_STUB_LIB)
+    AC_SUBST(RANLIB_STUB)
+    AC_SUBST(VC_MANIFEST_EMBED_DLL)
+    AC_SUBST(VC_MANIFEST_EMBED_EXE)
+])
+
+#------------------------------------------------------------------------
+# TEA_LIB_SPEC --
+#
+#      Compute the name of an existing object library located in libdir
+#      from the given base name and produce the appropriate linker flags.
+#
+# Arguments:
+#      basename        The base name of the library without version
+#                      numbers, extensions, or "lib" prefixes.
+#      extra_dir       Extra directory in which to search for the
+#                      library.  This location is used first, then
+#                      $prefix/$exec-prefix, then some defaults.
+#
+# Requires:
+#      TEA_INIT and TEA_PREFIX must be called first.
+#
+# Results:
+#
+#      Defines the following vars:
+#              ${basename}_LIB_NAME    The computed library name.
+#              ${basename}_LIB_SPEC    The computed linker flags.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LIB_SPEC], [
+    AC_MSG_CHECKING([for $1 library])
+
+    # Look in exec-prefix for the library (defined by TEA_PREFIX).
+
+    tea_lib_name_dir="${exec_prefix}/lib"
+
+    # Or in a user-specified location.
+
+    if test x"$2" != x ; then
+       tea_extra_lib_dir=$2
+    else
+       tea_extra_lib_dir=NONE
+    fi
+
+    for i in \
+           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
+       if test -f "$i" ; then
+           tea_lib_name_dir=`dirname $i`
+           $1_LIB_NAME=`basename $i`
+           $1_LIB_PATH_NAME=$i
+           break
+       fi
+    done
+
+    if test "${TEA_PLATFORM}" = "windows"; then
+       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
+    else
+       # Strip off the leading "lib" and trailing ".a" or ".so"
+
+       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
+       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
+    fi
+
+    if test "x${$1_LIB_NAME}" = x ; then
+       AC_MSG_ERROR([not found])
+    else
+       AC_MSG_RESULT([${$1_LIB_SPEC}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TCL_HEADERS --
+#
+#      Locate the private Tcl include files
+#
+# Arguments:
+#
+#      Requires:
+#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
+#                              already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_TOP_DIR_NATIVE
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
+    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
+    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
+    AC_MSG_CHECKING([for Tcl private include files])
+
+    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
+    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
+
+    # Check to see if tcl<Plat>Port.h isn't already with the public headers
+    # Don't look for tclInt.h because that resides with tcl.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
+       else
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TCL_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
+       if test "`uname -s`" = "Darwin"; then
+            # If Tcl was built as a framework, attempt to use
+            # the framework's Headers and PrivateHeaders directories
+            case ${TCL_DEFS} in
+               *TCL_FRAMEWORK*)
+                   if test -d "${TCL_BIN_DIR}/Headers" -a \
+                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
+                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
+                   else
+                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                   fi
+                   ;;
+           esac
+           result="Using ${TCL_INCLUDES}"
+       else
+           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
+               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
+           fi
+           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TCL_TOP_DIR_NATIVE)
+
+    AC_SUBST(TCL_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TCL_HEADERS --
+#
+#      Locate the installed public Tcl header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tclinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
+    AC_MSG_CHECKING([for Tcl public headers])
+
+    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tclh, [
+       # Use the value from --with-tclinclude, if it was given
+
+       if test x"${with_tclinclude}" != x ; then
+           if test -f "${with_tclinclude}/tcl.h" ; then
+               ac_cv_c_tclh=${with_tclinclude}
+           else
+               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tcl was built as a framework, attempt to use
+               # the framework's Headers directory
+               case ${TCL_DEFS} in
+                   *TCL_FRAMEWORK*)
+                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tcl is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TCL_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TCL_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tcl.h" ; then
+                   ac_cv_c_tclh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tclh}" = x ; then
+       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tclh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
+
+    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TCL_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TK_HEADERS --
+#
+#      Locate the private Tk include files
+#
+# Arguments:
+#
+#      Requires:
+#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
+#                               already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
+    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
+    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
+    AC_MSG_CHECKING([for Tk private include files])
+
+    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
+    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
+
+    # Check to see if tk<Plat>Port.h isn't already with the public headers
+    # Don't look for tkInt.h because that resides with tk.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
+       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
+       else
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TK_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
+       # Detect and add ttk subdir
+       if test -d "${TK_SRC_DIR}/generic/ttk"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
+       fi
+       if test "`uname -s`" = "Darwin"; then
+           # If Tk was built as a framework, attempt to use
+           # the framework's Headers and PrivateHeaders directories
+           case ${TK_DEFS} in
+               *TK_FRAMEWORK*)
+                       if test -d "${TK_BIN_DIR}/Headers" -a \
+                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
+                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
+                       else
+                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                       fi
+                       ;;
+           esac
+           result="Using ${TK_INCLUDES}"
+       else
+           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
+              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
+           fi
+           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TK_TOP_DIR_NATIVE)
+    AC_SUBST(TK_XLIB_DIR_NATIVE)
+
+    AC_SUBST(TK_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TK_HEADERS --
+#
+#      Locate the installed public Tk header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tkinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
+    AC_MSG_CHECKING([for Tk public headers])
+
+    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tkh, [
+       # Use the value from --with-tkinclude, if it was given
+
+       if test x"${with_tkinclude}" != x ; then
+           if test -f "${with_tkinclude}/tk.h" ; then
+               ac_cv_c_tkh=${with_tkinclude}
+           else
+               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tk was built as a framework, attempt to use
+               # the framework's Headers directory.
+               case ${TK_DEFS} in
+                   *TK_FRAMEWORK*)
+                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tk is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TK_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tk's --prefix location,
+           # relative to directory of tkConfig.sh, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
+               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TK_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tk.h" ; then
+                   ac_cv_c_tkh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tkh}" = x ; then
+       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tkh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
+
+    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TK_INCLUDES)
+
+    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+       # On Windows and Aqua, we need the X compat headers
+       AC_MSG_CHECKING([for X11 header files])
+       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
+           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
+           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+           AC_SUBST(TK_XINCLUDES)
+       fi
+       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_CONFIG --
+#
+#      Locate the ${1}Config.sh file and perform a sanity check on
+#      the ${1} compile flags.  These are used by packages like
+#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-$1=...
+#
+#      Defines the following vars:
+#              $1_BIN_DIR      Full path to the directory containing
+#                              the $1Config.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_CONFIG], [
+    #
+    # Ok, lets find the $1 configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-$1
+    #
+
+    if test x"${no_$1}" = x ; then
+       # we reset no_$1 in case something fails here
+       no_$1=true
+       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
+       AC_MSG_CHECKING([for $1 configuration])
+       AC_CACHE_VAL(ac_cv_c_$1config,[
+
+           # First check to see if --with-$1 was specified.
+           if test x"${with_$1config}" != x ; then
+               case ${with_$1config} in
+                   */$1Config.sh )
+                       if test -f ${with_$1config}; then
+                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
+                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
+                       fi;;
+               esac
+               if test -f "${with_$1config}/$1Config.sh" ; then
+                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
+               else
+                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
+               fi
+           fi
+
+           # then check for a private $1 installation
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in \
+                       ../$1 \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../$1 \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../$1 \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ${srcdir}/../$1 \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+                   if test -f "$i/unix/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_$1config}" = x ; then
+           $1_BIN_DIR="# no $1 configs found"
+           AC_MSG_WARN([Cannot find $1 configuration definitions])
+           exit 0
+       else
+           no_$1=
+           $1_BIN_DIR=${ac_cv_c_$1config}
+           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG --
+#
+#      Load the $1Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              $1_SRC_DIR
+#              $1_LIB_FILE
+#              $1_LIB_SPEC
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_CONFIG], [
+    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
+
+    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${$1_BIN_DIR}/$1Config.sh"
+    else
+        AC_MSG_RESULT([file not found])
+    fi
+
+    #
+    # If the $1_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable $1_LIB_SPEC will be set to the value
+    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
+    # instead of $1_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    #
+
+    if test -f "${$1_BIN_DIR}/Makefile" ; then
+       AC_MSG_WARN([Found Makefile - using build library specs for $1])
+        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
+        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
+        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
+        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
+        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
+    fi
+
+    AC_SUBST($1_VERSION)
+    AC_SUBST($1_BIN_DIR)
+    AC_SUBST($1_SRC_DIR)
+
+    AC_SUBST($1_LIB_FILE)
+    AC_SUBST($1_LIB_SPEC)
+
+    AC_SUBST($1_STUB_LIB_FILE)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    # Allow the caller to prevent this auto-check by specifying any 2nd arg
+    AS_IF([test "x$2" = x], [
+       # Check both upper and lower-case variants
+       # If a dev wanted non-stubs libs, this function could take an option
+       # to not use _STUB in the paths below
+       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
+           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
+           [TEA_LOAD_CONFIG_LIB($1_STUB)])
+    ])
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG_LIB --
+#
+#      Helper function to load correct library from another extension's
+#      ${PACKAGE}Config.sh.
+#
+# Results:
+#      Adds to LIBS the appropriate extension library
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
+    AC_MSG_CHECKING([For $1 library for LIBS])
+    # This simplifies the use of stub libraries by automatically adding
+    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
+    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
+    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
+    if test "x${$1_LIB_SPEC}" != "x" ; then
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
+           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
+           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
+       else
+           TEA_ADD_LIBS([${$1_LIB_SPEC}])
+           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
+       fi
+    else
+       AC_MSG_RESULT([file not found])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_EXPORT_CONFIG --
+#
+#      Define the data to insert into the ${PACKAGE}Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1
+#
+# Results:
+#      Substitutes the following vars:
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_EXPORT_CONFIG], [
+    #--------------------------------------------------------------------
+    # These are for $1Config.sh
+    #--------------------------------------------------------------------
+
+    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
+    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
+    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
+    else
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
+    fi
+    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
+    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
+    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
+    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
+
+    AC_SUBST($1_BUILD_LIB_SPEC)
+    AC_SUBST($1_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_PATH)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    AC_SUBST(MAJOR_VERSION)
+    AC_SUBST(MINOR_VERSION)
+    AC_SUBST(PATCHLEVEL)
+])
+
+
+#------------------------------------------------------------------------
+# TEA_INSTALLER --
+#
+#      Configure the installer.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              INSTALL
+#              INSTALL_DATA_DIR
+#              INSTALL_DATA
+#              INSTALL_PROGRAM
+#              INSTALL_SCRIPT
+#              INSTALL_LIBRARY
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INSTALLER], [
+    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
+    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
+    INSTALL_DATA='${INSTALL} -m 644'
+    INSTALL_PROGRAM='${INSTALL} -m 755'
+    INSTALL_SCRIPT='${INSTALL} -m 755'
+
+    TEA_CONFIG_SYSTEM
+    case $system in
+       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
+             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
+    esac
+
+    AC_SUBST(INSTALL)
+    AC_SUBST(INSTALL_DATA_DIR)
+    AC_SUBST(INSTALL_DATA)
+    AC_SUBST(INSTALL_PROGRAM)
+    AC_SUBST(INSTALL_SCRIPT)
+    AC_SUBST(INSTALL_LIBRARY)
+])
+
+###
+# Tip 430 - ZipFS Modifications
+###
+#------------------------------------------------------------------------
+# SC_ZIPFS_SUPPORT
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#              TCL_ZIPFS_FLAG
+#              ZIP_PROG
+#------------------------------------------------------------------------
+
+#------------------------------------------------------------------------
+# SC_PROG_ZIP
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              ZIP_PROG
+#       ZIP_PROG_OPTIONS
+#       ZIP_PROG_VFSSEARCH
+#       ZIP_INSTALL_OBJS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ZIPFS_SUPPORT], [
+    AC_MSG_CHECKING([for zipfs support])
+    ZIP_PROG=""
+    ZIP_PROG_OPTIONS=""
+    ZIP_PROG_VFSSEARCH=""
+    INSTALL_MSGS=""
+    # If our native tclsh processes the "install" command line option
+    # we can use it to mint zip files
+    AS_IF([$TCLSH_PROG install],[
+      ZIP_PROG=${TCLSH_PROG}
+      ZIP_PROG_OPTIONS="install mkzip"
+      ZIP_PROG_VFSSEARCH="."
+      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
+    ])
+    if test "x$ZIP_PROG" = "x" ; then
+        AC_CACHE_VAL(ac_cv_path_zip, [
+        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
+        for dir in $search_path ; do
+            for j in `ls -r $dir/zip 2> /dev/null` \
+                `ls -r $dir/zip 2> /dev/null` ; do
+            if test x"$ac_cv_path_zip" = x ; then
+                if test -f "$j" ; then
+                ac_cv_path_zip=$j
+                break
+                fi
+            fi
+            done
+        done
+        ])
+        if test -f "$ac_cv_path_zip" ; then
+            ZIP_PROG="$ac_cv_path_zip "
+            AC_MSG_RESULT([$ZIP_PROG])
+            ZIP_PROG_OPTIONS="-rq"
+            ZIP_PROG_VFSSEARCH="."
+            AC_MSG_RESULT([Found INFO Zip in environment])
+            # Use standard arguments for zip
+        fi
+    fi
+    if test "x$ZIP_PROG" = "x" ; then
+           # It is not an error if an installed version of Zip can't be located.
+        ZIP_PROG=""
+        ZIP_PROG_OPTIONS=""
+        ZIP_PROG_VFSSEARCH=""
+        TCL_ZIPFS_SUPPORT=0
+        TCL_ZIPFS_FLAG=
+    else
+        # ZIPFS Support
+       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
+       if test ${TCL_ZIP_FILE} = "" ; then
+          TCL_ZIPFS_SUPPORT=0
+          TCL_ZIPFS_FLAG=
+          INSTALL_LIBRARIES=install-libraries
+          INSTALL_MSGS=install-msgs
+       else
+           if test ${SHARED_BUILD} = 1 ; then
+              TCL_ZIPFS_SUPPORT=1
+              INSTALL_LIBRARIES=install-libraries-zipfs-shared
+           else
+              TCL_ZIPFS_SUPPORT=2
+              INSTALL_LIBRARIES=install-libraries-zipfs-static
+           fi
+          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
+       fi
+    fi
+
+    AC_SUBST(TCL_ZIP_FILE)
+    AC_SUBST(TCL_ZIPFS_SUPPORT)
+    AC_SUBST(TCL_ZIPFS_FLAG)
+    AC_SUBST(ZIP_PROG)
+    AC_SUBST(ZIP_PROG_OPTIONS)
+    AC_SUBST(ZIP_PROG_VFSSEARCH)
+    AC_SUBST(INSTALL_LIBRARIES)
+    AC_SUBST(INSTALL_MSGS)
+])
+
+# Local Variables:
+# mode: autoconf
+# End:
similarity index 91%
rename from pkgs/tdbcsqlite3-1.1.1/win/makefile.vc
rename to pkgs/tdbcsqlite3-1.1.2/win/makefile.vc
index 9db52ae..ba40e89 100644 (file)
@@ -7,9 +7,9 @@
 #   nmake /s /nologo /f makefile.vc INSTALLDIR=c:\path\to\installdir TCLDIR=c:\path\to\tcl\source install\r
 #\r
 # For other build options (debug, static etc.)\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
-# \r
+#\r
 # See the file "license.terms" for information on usage and redistribution\r
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
 #\r
@@ -19,7 +19,7 @@ PROJECT = tdbcsqlite3
 !include "rules-ext.vc"\r
 \r
 # Pure Tcl extension, no object files\r
-PRJ_OBJS = \r
+PRJ_OBJS =\r
 \r
 TM_INSTALL_DIR = $(_INSTALLDIR)\tcl$(TCL_MAJOR_VERSION)\$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
 \r
diff --git a/pkgs/tdbcsqlite3-1.1.2/win/nmakehlp.c b/pkgs/tdbcsqlite3-1.1.2/win/nmakehlp.c
new file mode 100644 (file)
index 0000000..7536ede
--- /dev/null
@@ -0,0 +1,815 @@
+/*
+ * ----------------------------------------------------------------------------
+ * nmakehlp.c --
+ *
+ *     This is used to fix limitations within nmake and the environment.
+ *
+ * Copyright (c) 2002 by David Gravereaux.
+ * Copyright (c) 2006 by Pat Thoyts
+ *
+ * See the file "license.terms" for information on usage and redistribution of
+ * this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ * ----------------------------------------------------------------------------
+ */
+
+#define _CRT_SECURE_NO_DEPRECATE
+#include <windows.h>
+#pragma comment (lib, "user32.lib")
+#pragma comment (lib, "kernel32.lib")
+#include <stdio.h>
+#include <math.h>
+
+/*
+ * This library is required for x64 builds with _some_ versions of MSVC
+ */
+#if defined(_M_IA64) || defined(_M_AMD64)
+#if _MSC_VER >= 1400 && _MSC_VER < 1500
+#pragma comment(lib, "bufferoverflowU")
+#endif
+#endif
+
+/* ISO hack for dumb VC++ */
+#ifdef _MSC_VER
+#define   snprintf     _snprintf
+#endif
+
+
+/* protos */
+
+static int CheckForCompilerFeature(const char *option);
+static int CheckForLinkerFeature(const char **options, int count);
+static int IsIn(const char *string, const char *substring);
+static int SubstituteFile(const char *substs, const char *filename);
+static int QualifyPath(const char *path);
+static int LocateDependency(const char *keyfile);
+static const char *GetVersionFromFile(const char *filename, const char *match, int numdots);
+static DWORD WINAPI ReadFromPipe(LPVOID args);
+
+/* globals */
+
+#define CHUNK  25
+#define STATICBUFFERSIZE    1000
+typedef struct {
+    HANDLE pipe;
+    char buffer[STATICBUFFERSIZE];
+} pipeinfo;
+
+pipeinfo Out = {INVALID_HANDLE_VALUE, '\0'};
+pipeinfo Err = {INVALID_HANDLE_VALUE, '\0'};
+\f
+/*
+ * exitcodes: 0 == no, 1 == yes, 2 == error
+ */
+
+int
+main(
+    int argc,
+    char *argv[])
+{
+    char msg[300];
+    DWORD dwWritten;
+    int chars;
+    const char *s;
+
+    /*
+     * Make sure children (cl.exe and link.exe) are kept quiet.
+     */
+
+    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
+
+    /*
+     * Make sure the compiler and linker aren't effected by the outside world.
+     */
+
+    SetEnvironmentVariable("CL", "");
+    SetEnvironmentVariable("LINK", "");
+
+    if (argc > 1 && *argv[1] == '-') {
+       switch (*(argv[1]+1)) {
+       case 'c':
+           if (argc != 3) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                       "usage: %s -c <compiler option>\n"
+                       "Tests for whether cl.exe supports an option\n"
+                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                       &dwWritten, NULL);
+               return 2;
+           }
+           return CheckForCompilerFeature(argv[2]);
+       case 'l':
+           if (argc < 3) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                       "usage: %s -l <linker option> ?<mandatory option> ...?\n"
+                       "Tests for whether link.exe supports an option\n"
+                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                       &dwWritten, NULL);
+               return 2;
+           }
+           return CheckForLinkerFeature(&argv[2], argc-2);
+       case 'f':
+           if (argc == 2) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                       "usage: %s -f <string> <substring>\n"
+                       "Find a substring within another\n"
+                       "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                       &dwWritten, NULL);
+               return 2;
+           } else if (argc == 3) {
+               /*
+                * If the string is blank, there is no match.
+                */
+
+               return 0;
+           } else {
+               return IsIn(argv[2], argv[3]);
+           }
+       case 's':
+           if (argc == 2) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                       "usage: %s -s <substitutions file> <file>\n"
+                       "Perform a set of string map type substutitions on a file\n"
+                       "exitcodes: 0\n",
+                       argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                       &dwWritten, NULL);
+               return 2;
+           }
+           return SubstituteFile(argv[2], argv[3]);
+       case 'V':
+           if (argc != 4) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                   "usage: %s -V filename matchstring\n"
+                   "Extract a version from a file:\n"
+                   "eg: pkgIndex.tcl \"package ifneeded http\"",
+                   argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                   &dwWritten, NULL);
+               return 0;
+           }
+           s = GetVersionFromFile(argv[2], argv[3], *(argv[1]+2) - '0');
+           if (s && *s) {
+               printf("%s\n", s);
+               return 0;
+           } else
+               return 1; /* Version not found. Return non-0 exit code */
+
+       case 'Q':
+           if (argc != 3) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                   "usage: %s -Q path\n"
+                   "Emit the fully qualified path\n"
+                   "exitcodes: 0 == no, 1 == yes, 2 == error\n", argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                   &dwWritten, NULL);
+               return 2;
+           }
+           return QualifyPath(argv[2]);
+
+       case 'L':
+           if (argc != 3) {
+               chars = snprintf(msg, sizeof(msg) - 1,
+                   "usage: %s -L keypath\n"
+                   "Emit the fully qualified path of directory containing keypath\n"
+                   "exitcodes: 0 == success, 1 == not found, 2 == error\n", argv[0]);
+               WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars,
+                   &dwWritten, NULL);
+               return 2;
+           }
+           return LocateDependency(argv[2]);
+       }
+    }
+    chars = snprintf(msg, sizeof(msg) - 1,
+           "usage: %s -c|-f|-l|-Q|-s|-V ...\n"
+           "This is a little helper app to equalize shell differences between WinNT and\n"
+           "Win9x and get nmake.exe to accomplish its job.\n",
+           argv[0]);
+    WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, chars, &dwWritten, NULL);
+    return 2;
+}
+\f
+static int
+CheckForCompilerFeature(
+    const char *option)
+{
+    STARTUPINFO si;
+    PROCESS_INFORMATION pi;
+    SECURITY_ATTRIBUTES sa;
+    DWORD threadID;
+    char msg[300];
+    BOOL ok;
+    HANDLE hProcess, h, pipeThreads[2];
+    char cmdline[100];
+
+    hProcess = GetCurrentProcess();
+
+    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
+    ZeroMemory(&si, sizeof(STARTUPINFO));
+    si.cb = sizeof(STARTUPINFO);
+    si.dwFlags   = STARTF_USESTDHANDLES;
+    si.hStdInput = INVALID_HANDLE_VALUE;
+
+    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
+    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
+    sa.lpSecurityDescriptor = NULL;
+    sa.bInheritHandle = FALSE;
+
+    /*
+     * Create a non-inheritible pipe.
+     */
+
+    CreatePipe(&Out.pipe, &h, &sa, 0);
+
+    /*
+     * Dupe the write side, make it inheritible, and close the original.
+     */
+
+    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
+           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
+
+    /*
+     * Same as above, but for the error side.
+     */
+
+    CreatePipe(&Err.pipe, &h, &sa, 0);
+    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
+           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
+
+    /*
+     * Base command line.
+     */
+
+    lstrcpy(cmdline, "cl.exe -nologo -c -TC -Zs -X -Fp.\\_junk.pch ");
+
+    /*
+     * Append our option for testing
+     */
+
+    lstrcat(cmdline, option);
+
+    /*
+     * Filename to compile, which exists, but is nothing and empty.
+     */
+
+    lstrcat(cmdline, " .\\nul");
+
+    ok = CreateProcess(
+           NULL,           /* Module name. */
+           cmdline,        /* Command line. */
+           NULL,           /* Process handle not inheritable. */
+           NULL,           /* Thread handle not inheritable. */
+           TRUE,           /* yes, inherit handles. */
+           DETACHED_PROCESS, /* No console for you. */
+           NULL,           /* Use parent's environment block. */
+           NULL,           /* Use parent's starting directory. */
+           &si,            /* Pointer to STARTUPINFO structure. */
+           &pi);           /* Pointer to PROCESS_INFORMATION structure. */
+
+    if (!ok) {
+       DWORD err = GetLastError();
+       int chars = snprintf(msg, sizeof(msg) - 1,
+               "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);
+
+       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
+               FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
+               (300-chars), 0);
+       WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL);
+       return 2;
+    }
+
+    /*
+     * Close our references to the write handles that have now been inherited.
+     */
+
+    CloseHandle(si.hStdOutput);
+    CloseHandle(si.hStdError);
+
+    WaitForInputIdle(pi.hProcess, 5000);
+    CloseHandle(pi.hThread);
+
+    /*
+     * Start the pipe reader threads.
+     */
+
+    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
+    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);
+
+    /*
+     * Block waiting for the process to end.
+     */
+
+    WaitForSingleObject(pi.hProcess, INFINITE);
+    CloseHandle(pi.hProcess);
+
+    /*
+     * Wait for our pipe to get done reading, should it be a little slow.
+     */
+
+    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
+    CloseHandle(pipeThreads[0]);
+    CloseHandle(pipeThreads[1]);
+
+    /*
+     * Look for the commandline warning code in both streams.
+     *  - in MSVC 6 & 7 we get D4002, in MSVC 8 we get D9002.
+     */
+
+    return !(strstr(Out.buffer, "D4002") != NULL
+             || strstr(Err.buffer, "D4002") != NULL
+             || strstr(Out.buffer, "D9002") != NULL
+             || strstr(Err.buffer, "D9002") != NULL
+             || strstr(Out.buffer, "D2021") != NULL
+             || strstr(Err.buffer, "D2021") != NULL);
+}
+\f
+static int
+CheckForLinkerFeature(
+    const char **options,
+    int count)
+{
+    STARTUPINFO si;
+    PROCESS_INFORMATION pi;
+    SECURITY_ATTRIBUTES sa;
+    DWORD threadID;
+    char msg[300];
+    BOOL ok;
+    HANDLE hProcess, h, pipeThreads[2];
+    int i;
+    char cmdline[255];
+
+    hProcess = GetCurrentProcess();
+
+    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
+    ZeroMemory(&si, sizeof(STARTUPINFO));
+    si.cb = sizeof(STARTUPINFO);
+    si.dwFlags   = STARTF_USESTDHANDLES;
+    si.hStdInput = INVALID_HANDLE_VALUE;
+
+    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
+    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
+    sa.lpSecurityDescriptor = NULL;
+    sa.bInheritHandle = TRUE;
+
+    /*
+     * Create a non-inheritible pipe.
+     */
+
+    CreatePipe(&Out.pipe, &h, &sa, 0);
+
+    /*
+     * Dupe the write side, make it inheritible, and close the original.
+     */
+
+    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
+           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
+
+    /*
+     * Same as above, but for the error side.
+     */
+
+    CreatePipe(&Err.pipe, &h, &sa, 0);
+    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
+           DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
+
+    /*
+     * Base command line.
+     */
+
+    lstrcpy(cmdline, "link.exe -nologo ");
+
+    /*
+     * Append our option for testing.
+     */
+
+    for (i = 0; i < count; i++) {
+       lstrcat(cmdline, " \"");
+       lstrcat(cmdline, options[i]);
+       lstrcat(cmdline, "\"");
+    }
+
+    ok = CreateProcess(
+           NULL,           /* Module name. */
+           cmdline,        /* Command line. */
+           NULL,           /* Process handle not inheritable. */
+           NULL,           /* Thread handle not inheritable. */
+           TRUE,           /* yes, inherit handles. */
+           DETACHED_PROCESS, /* No console for you. */
+           NULL,           /* Use parent's environment block. */
+           NULL,           /* Use parent's starting directory. */
+           &si,            /* Pointer to STARTUPINFO structure. */
+           &pi);           /* Pointer to PROCESS_INFORMATION structure. */
+
+    if (!ok) {
+       DWORD err = GetLastError();
+       int chars = snprintf(msg, sizeof(msg) - 1,
+               "Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);
+
+       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
+               FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
+               (300-chars), 0);
+       WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg, lstrlen(msg), &err,NULL);
+       return 2;
+    }
+
+    /*
+     * Close our references to the write handles that have now been inherited.
+     */
+
+    CloseHandle(si.hStdOutput);
+    CloseHandle(si.hStdError);
+
+    WaitForInputIdle(pi.hProcess, 5000);
+    CloseHandle(pi.hThread);
+
+    /*
+     * Start the pipe reader threads.
+     */
+
+    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
+    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);
+
+    /*
+     * Block waiting for the process to end.
+     */
+
+    WaitForSingleObject(pi.hProcess, INFINITE);
+    CloseHandle(pi.hProcess);
+
+    /*
+     * Wait for our pipe to get done reading, should it be a little slow.
+     */
+
+    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
+    CloseHandle(pipeThreads[0]);
+    CloseHandle(pipeThreads[1]);
+
+    /*
+     * Look for the commandline warning code in the stderr stream.
+     */
+
+    return !(strstr(Out.buffer, "LNK1117") != NULL ||
+           strstr(Err.buffer, "LNK1117") != NULL ||
+           strstr(Out.buffer, "LNK4044") != NULL ||
+           strstr(Err.buffer, "LNK4044") != NULL ||
+           strstr(Out.buffer, "LNK4224") != NULL ||
+           strstr(Err.buffer, "LNK4224") != NULL);
+}
+\f
+static DWORD WINAPI
+ReadFromPipe(
+    LPVOID args)
+{
+    pipeinfo *pi = (pipeinfo *) args;
+    char *lastBuf = pi->buffer;
+    DWORD dwRead;
+    BOOL ok;
+
+  again:
+    if (lastBuf - pi->buffer + CHUNK > STATICBUFFERSIZE) {
+       CloseHandle(pi->pipe);
+       return (DWORD)-1;
+    }
+    ok = ReadFile(pi->pipe, lastBuf, CHUNK, &dwRead, 0L);
+    if (!ok || dwRead == 0) {
+       CloseHandle(pi->pipe);
+       return 0;
+    }
+    lastBuf += dwRead;
+    goto again;
+
+    return 0;  /* makes the compiler happy */
+}
+\f
+static int
+IsIn(
+    const char *string,
+    const char *substring)
+{
+    return (strstr(string, substring) != NULL);
+}
+\f
+/*
+ * GetVersionFromFile --
+ *     Looks for a match string in a file and then returns the version
+ *     following the match where a version is anything acceptable to
+ *     package provide or package ifneeded.
+ */
+
+static const char *
+GetVersionFromFile(
+    const char *filename,
+    const char *match,
+    int numdots)
+{
+    size_t cbBuffer = 100;
+    static char szBuffer[100];
+    char *szResult = NULL;
+    FILE *fp = fopen(filename, "rt");
+
+    if (fp != NULL) {
+       /*
+        * Read data until we see our match string.
+        */
+
+       while (fgets(szBuffer, cbBuffer, fp) != NULL) {
+           LPSTR p, q;
+
+           p = strstr(szBuffer, match);
+           if (p != NULL) {
+               /*
+                * Skip to first digit after the match.
+                */
+
+               p += strlen(match);
+               while (*p && !isdigit(*p)) {
+                   ++p;
+               }
+
+               /*
+                * Find ending whitespace.
+                */
+
+               q = p;
+               while (*q && (strchr("0123456789.ab", *q)) && ((!strchr(".ab", *q)
+                           && (!strchr("ab", q[-1])) || --numdots))) {
+                   ++q;
+               }
+
+               memcpy(szBuffer, p, q - p);
+               szBuffer[q-p] = 0;
+               szResult = szBuffer;
+               break;
+           }
+       }
+       fclose(fp);
+    }
+    return szResult;
+}
+\f
+/*
+ * List helpers for the SubstituteFile function
+ */
+
+typedef struct list_item_t {
+    struct list_item_t *nextPtr;
+    char * key;
+    char * value;
+} list_item_t;
+
+/* insert a list item into the list (list may be null) */
+static list_item_t *
+list_insert(list_item_t **listPtrPtr, const char *key, const char *value)
+{
+    list_item_t *itemPtr = malloc(sizeof(list_item_t));
+    if (itemPtr) {
+       itemPtr->key = strdup(key);
+       itemPtr->value = strdup(value);
+       itemPtr->nextPtr = NULL;
+
+       while(*listPtrPtr) {
+           listPtrPtr = &(*listPtrPtr)->nextPtr;
+       }
+       *listPtrPtr = itemPtr;
+    }
+    return itemPtr;
+}
+
+static void
+list_free(list_item_t **listPtrPtr)
+{
+    list_item_t *tmpPtr, *listPtr = *listPtrPtr;
+    while (listPtr) {
+       tmpPtr = listPtr;
+       listPtr = listPtr->nextPtr;
+       free(tmpPtr->key);
+       free(tmpPtr->value);
+       free(tmpPtr);
+    }
+}
+\f
+/*
+ * SubstituteFile --
+ *     As windows doesn't provide anything useful like sed and it's unreliable
+ *     to use the tclsh you are building against (consider x-platform builds -
+ *     eg compiling AMD64 target from IX86) we provide a simple substitution
+ *     option here to handle autoconf style substitutions.
+ *     The substitution file is whitespace and line delimited. The file should
+ *     consist of lines matching the regular expression:
+ *       \s*\S+\s+\S*$
+ *
+ *     Usage is something like:
+ *       nmakehlp -S << $** > $@
+ *        @PACKAGE_NAME@ $(PACKAGE_NAME)
+ *        @PACKAGE_VERSION@ $(PACKAGE_VERSION)
+ *        <<
+ */
+
+static int
+SubstituteFile(
+    const char *substitutions,
+    const char *filename)
+{
+    size_t cbBuffer = 1024;
+    static char szBuffer[1024], szCopy[1024];
+    char *szResult = NULL;
+    list_item_t *substPtr = NULL;
+    FILE *fp, *sp;
+
+    fp = fopen(filename, "rt");
+    if (fp != NULL) {
+
+       /*
+        * Build a list of substutitions from the first filename
+        */
+
+       sp = fopen(substitutions, "rt");
+       if (sp != NULL) {
+           while (fgets(szBuffer, cbBuffer, sp) != NULL) {
+               unsigned char *ks, *ke, *vs, *ve;
+               ks = (unsigned char*)szBuffer;
+               while (ks && *ks && isspace(*ks)) ++ks;
+               ke = ks;
+               while (ke && *ke && !isspace(*ke)) ++ke;
+               vs = ke;
+               while (vs && *vs && isspace(*vs)) ++vs;
+               ve = vs;
+               while (ve && *ve && !(*ve == '\r' || *ve == '\n')) ++ve;
+               *ke = 0, *ve = 0;
+               list_insert(&substPtr, (char*)ks, (char*)vs);
+           }
+           fclose(sp);
+       }
+
+       /* debug: dump the list */
+#ifndef NDEBUG
+       {
+           int n = 0;
+           list_item_t *p = NULL;
+           for (p = substPtr; p != NULL; p = p->nextPtr, ++n) {
+               fprintf(stderr, "% 3d '%s' => '%s'\n", n, p->key, p->value);
+           }
+       }
+#endif
+
+       /*
+        * Run the substitutions over each line of the input
+        */
+
+       while (fgets(szBuffer, cbBuffer, fp) != NULL) {
+           list_item_t *p = NULL;
+           for (p = substPtr; p != NULL; p = p->nextPtr) {
+               char *m = strstr(szBuffer, p->key);
+               if (m) {
+                   char *cp, *op, *sp;
+                   cp = szCopy;
+                   op = szBuffer;
+                   while (op != m) *cp++ = *op++;
+                   sp = p->value;
+                   while (sp && *sp) *cp++ = *sp++;
+                   op += strlen(p->key);
+                   while (*op) *cp++ = *op++;
+                   *cp = 0;
+                   memcpy(szBuffer, szCopy, sizeof(szCopy));
+               }
+           }
+           printf(szBuffer);
+       }
+
+       list_free(&substPtr);
+    }
+    fclose(fp);
+    return 0;
+}
+\f
+BOOL FileExists(LPCTSTR szPath)
+{
+#ifndef INVALID_FILE_ATTRIBUTES
+    #define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
+#endif
+    DWORD pathAttr = GetFileAttributes(szPath);
+    return (pathAttr != INVALID_FILE_ATTRIBUTES &&
+           !(pathAttr & FILE_ATTRIBUTE_DIRECTORY));
+}
+\f
+
+/*
+ * QualifyPath --
+ *
+ *     This composes the current working directory with a provided path
+ *     and returns the fully qualified and normalized path.
+ *     Mostly needed to setup paths for testing.
+ */
+
+static int
+QualifyPath(
+    const char *szPath)
+{
+    char szCwd[MAX_PATH + 1];
+
+    GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
+    printf("%s\n", szCwd);
+    return 0;
+}
+
+/*
+ * Implements LocateDependency for a single directory. See that command
+ * for an explanation.
+ * Returns 0 if found after printing the directory.
+ * Returns 1 if not found but no errors.
+ * Returns 2 on any kind of error
+ * Basically, these are used as exit codes for the process.
+ */
+static int LocateDependencyHelper(const char *dir, const char *keypath)
+{
+    HANDLE hSearch;
+    char path[MAX_PATH+1];
+    int dirlen, keylen, ret;
+    WIN32_FIND_DATA finfo;
+
+    if (dir == NULL || keypath == NULL)
+       return 2; /* Have no real error reporting mechanism into nmake */
+    dirlen = strlen(dir);
+    if ((dirlen + 3) > sizeof(path))
+       return 2;
+    strncpy(path, dir, dirlen);
+    strncpy(path+dirlen, "\\*", 3);    /* Including terminating \0 */
+    keylen = strlen(keypath);
+
+#if 0 /* This function is not available in Visual C++ 6 */
+    /*
+     * Use numerics 0 -> FindExInfoStandard,
+     * 1 -> FindExSearchLimitToDirectories,
+     * as these are not defined in Visual C++ 6
+     */
+    hSearch = FindFirstFileEx(path, 0, &finfo, 1, NULL, 0);
+#else
+    hSearch = FindFirstFile(path, &finfo);
+#endif
+    if (hSearch == INVALID_HANDLE_VALUE)
+       return 1; /* Not found */
+
+    /* Loop through all subdirs checking if the keypath is under there */
+    ret = 1; /* Assume not found */
+    do {
+       int sublen;
+       /*
+        * We need to check it is a directory despite the
+        * FindExSearchLimitToDirectories in the above call. See SDK docs
+        */
+       if ((finfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
+           continue;
+       sublen = strlen(finfo.cFileName);
+       if ((dirlen+1+sublen+1+keylen+1) > sizeof(path))
+           continue;           /* Path does not fit, assume not matched */
+       strncpy(path+dirlen+1, finfo.cFileName, sublen);
+       path[dirlen+1+sublen] = '\\';
+       strncpy(path+dirlen+1+sublen+1, keypath, keylen+1);
+       if (FileExists(path)) {
+           /* Found a match, print to stdout */
+           path[dirlen+1+sublen] = '\0';
+           QualifyPath(path);
+           ret = 0;
+           break;
+       }
+    } while (FindNextFile(hSearch, &finfo));
+    FindClose(hSearch);
+    return ret;
+}
+
+/*
+ * LocateDependency --
+ *
+ *     Locates a dependency for a package.
+ *        keypath - a relative path within the package directory
+ *          that is used to confirm it is the correct directory.
+ *     The search path for the package directory is currently only
+ *      the parent and grandparent of the current working directory.
+ *      If found, the command prints
+ *         name_DIRPATH=<full path of located directory>
+ *      and returns 0. If not found, does not print anything and returns 1.
+ */
+static int LocateDependency(const char *keypath)
+{
+    int i, ret;
+    static const char *paths[] = {"..", "..\\..", "..\\..\\.."};
+
+    for (i = 0; i < (sizeof(paths)/sizeof(paths[0])); ++i) {
+       ret = LocateDependencyHelper(paths[i], keypath);
+       if (ret == 0)
+           return ret;
+    }
+    return ret;
+}
+
+
+/*
+ * Local variables:
+ *   mode: c
+ *   c-basic-offset: 4
+ *   fill-column: 78
+ *   indent-tabs-mode: t
+ *   tab-width: 8
+ * End:
+ */
similarity index 93%
rename from pkgs/itcl4.2.0/win/rules.vc
rename to pkgs/tdbcsqlite3-1.1.2/win/rules.vc
index 325357c..f3e5439 100644 (file)
@@ -6,7 +6,7 @@
 # compiler switches, defining common targets and macros. The Tcl makefile\r
 # directly includes this. Extensions include it via "rules-ext.vc".\r
 #\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
@@ -24,7 +24,7 @@ _RULES_VC = 1
 # For modifications that are not backward-compatible, you *must* change\r
 # the major version.\r
 RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
+RULES_VERSION_MINOR = 6\r
 \r
 # The PROJECT macro must be defined by parent makefile.\r
 !if "$(PROJECT)" == ""\r
@@ -302,7 +302,7 @@ TCLDIR          = $(_INSTALLDIR)\..
 _TCLDIR                = $(_INSTALLDIR)\..\r
 _TCL_H          = $(_TCLDIR)\include\tcl.h\r
 \r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !if [echo _TCLDIR = \> nmakehlp.out] \\r
    || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
@@ -313,7 +313,7 @@ TCLINSTALL      = 0
 TCLDIR         = $(_TCLDIR)\r
 _TCL_H          = $(_TCLDIR)\generic\tcl.h\r
 \r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !endif # TCLDIR\r
 \r
@@ -415,9 +415,6 @@ _INSTALLDIR=$(_INSTALLDIR)\lib
 # NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
 # MACHINE - same as $(ARCH) - legacy\r
 # _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
 \r
 cc32           = $(CC)   # built-in default.\r
 link32         = link\r
@@ -503,10 +500,6 @@ _VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -ou
 _VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
 !endif\r
 \r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
 ################################################################\r
 # 4. Build the nmakehlp program\r
 # This is a helper app we need to overcome nmake's limiting\r
@@ -514,7 +507,7 @@ CFG_ENCODING        = \"cp1252\"
 # information about supported compiler options etc.\r
 #\r
 # Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
+# in its own source. It will be kept updated there.\r
 #\r
 # Extensions built against an installed Tcl will use the installed\r
 # copy of Tcl's nmakehlp.c if there is one and their own version\r
@@ -537,7 +530,7 @@ NMAKEHLPC = nmakehlp.c
 !if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
 !endif\r
-!else # ! $(TCLINSTALL)\r
+!else # !$(TCLINSTALL)\r
 !if exist("$(_TCLDIR)\win\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
 !endif\r
@@ -685,7 +678,9 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
 #           configuration (ignored for Tcl itself)\r
 # _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
 # Further, LINKERFLAGS are modified based on above.\r
 \r
 # Default values for all the above\r
@@ -728,11 +723,8 @@ MSVCRT             = 0
 !else\r
 !if [nmakehlp -f $(OPTS) "msvcrt"]\r
 !message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
 !else\r
+!if $(STATIC_BUILD)\r
 MSVCRT         = 0\r
 !endif\r
 !endif\r
@@ -741,24 +733,26 @@ MSVCRT            = 0
 !if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
 !message *** Doing staticpkg\r
 TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
 !endif\r
 \r
 !if [nmakehlp -f $(OPTS) "nothreads"]\r
 !message *** Compile explicitly for non-threaded tcl\r
 TCL_THREADS = 0\r
 USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
 !endif\r
 \r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
 !if [nmakehlp -f $(OPTS) "time64bit"]\r
 !message *** Force 64-bit time_t\r
 _USE_64BIT_TIME_T = 1\r
 !endif\r
 \r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
 # Yes, it's weird that the "symbols" option controls DEBUG and\r
 # the "pdbs" option controls SYMBOLS. That's historical.\r
 !if [nmakehlp -f $(OPTS) "symbols"]\r
@@ -985,6 +979,19 @@ VERSION         = $(DOTVERSION:.=)
 \r
 !endif # $(DOING_TCL) ... etc.\r
 \r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
 ################################################################\r
 # 10. Construct output directory and file paths\r
 # Figure-out how to name our intermediate and output directories.\r
@@ -1029,7 +1036,7 @@ BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)
 BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
 !endif\r
 \r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
 SUFX       = $(SUFX:g=)\r
 !endif\r
 \r
@@ -1093,7 +1100,7 @@ TCLSTUBLIBNAME    = $(STUBPREFIX)$(VERSION).lib
 TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
 TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
 \r
-!else # ! $(DOING_TCL)\r
+!else # !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 \r
@@ -1233,6 +1240,7 @@ BIN_INSTALL_DIR           = $(_INSTALLDIR)\bin
 DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
 !if $(DOING_TCL)\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
 !else # DOING_TK\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
 !endif\r
@@ -1277,7 +1285,15 @@ INCLUDE_INSTALL_DIR      = $(_INSTALLDIR)\..\include
 # baselibs - minimum Windows libraries required. Parent makefile can\r
 #    define PRJ_LIBS before including rules.rc if additional libs are needed\r
 \r
-OPTDEFINES     = /DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) /DSTDC_HEADERS\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) >= 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
 \r
 !if $(TCL_MEM_DEBUG)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
@@ -1293,6 +1309,11 @@ OPTDEFINES       = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1
 !endif\r
 !if $(STATIC_BUILD)\r
 OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
 !endif\r
 !if $(TCL_NO_DEPRECATED)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
@@ -1301,7 +1322,7 @@ OPTDEFINES        = $(OPTDEFINES) /DTCL_NO_DEPRECATED
 !if $(USE_STUBS)\r
 # Note we do not define USE_TCL_STUBS even when building tk since some\r
 # test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
 !if $(NEED_TK)\r
 USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
@@ -1322,15 +1343,20 @@ OPTDEFINES      = $(OPTDEFINES) /DTCL_CFG_PROFILED
 OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
 !endif\r
 !if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
 !endif\r
 \r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
 !if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
 !endif\r
 \r
 # _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
 COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
 \r
 # Like the TEA system only set this non empty for non-Tk extensions\r
 # Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
@@ -1508,7 +1534,7 @@ GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)
 RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
            $(TCL_INCLUDES) \\r
            /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           /DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
            /DDOTVERSION=\"$(DOTVERSION)\" \\r
            /DVERSION=\"$(VERSION)\" \\r
            /DSUFX=\"$(SUFX)\" \\r
@@ -1636,7 +1662,7 @@ default-shell: default-setup $(PROJECT)
 !ifdef RCFILE\r
 \r
 # Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
+# and only the "main" rc must be passed to the resource compiler\r
 $(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
        $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
 \r
@@ -1690,7 +1716,7 @@ DISABLE_IMPLICIT_RULES = 0
 \r
 !if !$(DISABLE_IMPLICIT_RULES)\r
 # Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
+# main application, the makefile should define explicit rules.\r
 \r
 {$(ROOT)}.c{$(TMP_DIR)}.obj::\r
        $(CCPKGCMD) @<<\r
@@ -1731,13 +1757,13 @@ $<
 # When building an extension, certain configuration options should\r
 # match the ones used when Tcl was built. Here we check and\r
 # warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 !if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
 TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
 !endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
 !if exist("$(OUT_DIR)\tcl.nmake")\r
 TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
 !endif\r
@@ -1760,7 +1786,7 @@ TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"
 \r
 !endif # TCLNMAKECONFIG\r
 \r
-!endif # ! $(DOING_TCL)\r
+!endif # !$(DOING_TCL)\r
 \r
 \r
 #----------------------------------------------------------\r
diff --git a/pkgs/tdbcsqlite3-1.1.2/win/targets.vc b/pkgs/tdbcsqlite3-1.1.2/win/targets.vc
new file mode 100644 (file)
index 0000000..6bfebc7
--- /dev/null
@@ -0,0 +1,98 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# targets.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file defines some standard targets for the convenience of extensions\r
+# and can be optionally included by the extension makefile.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for docs.\r
+\r
+$(PROJECT): setup pkgindex $(PRJLIB)\r
+\r
+!ifdef PRJ_STUBOBJS\r
+$(PROJECT): $(PRJSTUBLIB)\r
+$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
+       $(LIBCMD) $**\r
+\r
+$(PRJ_STUBOBJS):\r
+       $(CCSTUBSCMD) %s\r
+!endif # PRJ_STUBOBJS\r
+\r
+!ifdef PRJ_MANIFEST\r
+$(PROJECT): $(PRJLIB).manifest\r
+$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
+       @nmakehlp -s << $** >$@\r
+@MACHINE@        $(MACHINE:IX86=X86)\r
+<<\r
+!endif\r
+\r
+!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
+$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
+!if $(STATIC_BUILD)\r
+       $(LIBCMD) $**\r
+!else\r
+       $(DLLCMD) $**\r
+       $(_VC_MANIFEST_EMBED_DLL)\r
+!endif\r
+       -@del $*.exp\r
+!endif\r
+\r
+!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
+$(PRJ_OBJS): $(PRJ_HEADERS)\r
+!endif\r
+\r
+# If parent makefile has defined stub objects, add their installation\r
+# to the default install\r
+!if "$(PRJ_STUBOBJS)" != ""\r
+default-install: default-install-stubs\r
+!endif\r
+\r
+# Unlike the other default targets, these cannot be in rules.vc because\r
+# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
+# that the parent makefile will not define until after including rules-ext.vc\r
+!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
+default-install: default-install-headers\r
+default-install-headers:\r
+       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
+       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
+!endif\r
+\r
+!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
+DISABLE_STANDARD_TARGETS = 0\r
+!endif\r
+\r
+!if "$(DISABLE_TARGET_setup)" == ""\r
+DISABLE_TARGET_setup = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_install)" == ""\r
+DISABLE_TARGET_install = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_clean)" == ""\r
+DISABLE_TARGET_clean = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_test)" == ""\r
+DISABLE_TARGET_test = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_shell)" == ""\r
+DISABLE_TARGET_shell = 0\r
+!endif\r
+\r
+!if !$(DISABLE_STANDARD_TARGETS)\r
+!if !$(DISABLE_TARGET_setup)\r
+setup: default-setup\r
+!endif\r
+!if !$(DISABLE_TARGET_install)\r
+install: default-install\r
+!endif\r
+!if !$(DISABLE_TARGET_clean)\r
+clean: default-clean\r
+realclean: hose\r
+hose: default-hose\r
+distclean: realclean default-distclean\r
+!endif\r
+!if !$(DISABLE_TARGET_test)\r
+test: default-test\r
+!endif\r
+!if !$(DISABLE_TARGET_shell)\r
+shell: default-shell\r
+!endif\r
+!endif # DISABLE_STANDARD_TARGETS\r
diff --git a/pkgs/thread2.8.5/tclconfig/README.txt b/pkgs/thread2.8.5/tclconfig/README.txt
deleted file mode 100644 (file)
index 59b5a3e..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-These files comprise the basic building blocks for a Tcl Extension
-Architecture (TEA) extension.  For more information on TEA see:
-
-       http://www.tcl.tk/doc/tea/
-
-This package is part of the Tcl project at SourceForge, and latest
-sources should be available there:
-
-       http://tcl.sourceforge.net/
-
-This package is a freely available open source package.  You can do
-virtually anything you like with it, such as modifying it, redistributing
-it, and selling it either in whole or in part.
-
-CONTENTS
-========
-The following is a short description of the files you will find in
-the sample extension.
-
-README.txt     This file
-
-install-sh     Program used for copying binaries and script files
-               to their install locations.
-
-tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
-               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/thread2.8.5/tclconfig/install-sh b/pkgs/thread2.8.5/tclconfig/install-sh
deleted file mode 100644 (file)
index 7c34c3f..0000000
+++ /dev/null
@@ -1,528 +0,0 @@
-#!/bin/sh
-# install - install a program, script, or datafile
-
-scriptversion=2011-04-20.01; # UTC
-
-# This originates from X11R5 (mit/util/scripts/install.sh), which was
-# later released in X11R6 (xc/config/util/install.sh) with the
-# following copyright and license.
-#
-# Copyright (C) 1994 X Consortium
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
-# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-# Except as contained in this notice, the name of the X Consortium shall not
-# be used in advertising or otherwise to promote the sale, use or other deal-
-# ings in this Software without prior written authorization from the X Consor-
-# tium.
-#
-#
-# FSF changes to this file are in the public domain.
-#
-# 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.
-
-nl='
-'
-IFS=" ""       $nl"
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
-
-# Put in absolute file names if you don't have them in your path;
-# or use environment vars.
-
-chgrpprog=${CHGRPPROG-chgrp}
-chmodprog=${CHMODPROG-chmod}
-chownprog=${CHOWNPROG-chown}
-cmpprog=${CMPPROG-cmp}
-cpprog=${CPPROG-cp}
-mkdirprog=${MKDIRPROG-mkdir}
-mvprog=${MVPROG-mv}
-rmprog=${RMPROG-rm}
-stripprog=${STRIPPROG-strip}
-
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
-posix_mkdir=
-
-# Desired mode of installed file.
-mode=0755
-
-chgrpcmd=
-chmodcmd=$chmodprog
-chowncmd=
-mvcmd=$mvprog
-rmcmd="$rmprog -f"
-stripcmd=
-
-src=
-dst=
-dir_arg=
-dst_arg=
-
-copy_on_change=false
-no_target_directory=
-
-usage="\
-Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
-   or: $0 [OPTION]... SRCFILES... DIRECTORY
-   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
-   or: $0 [OPTION]... -d DIRECTORIES...
-
-In the 1st form, copy SRCFILE to DSTFILE.
-In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
-In the 4th, create DIRECTORIES.
-
-Options:
-     --help     display this help and exit.
-     --version  display version info and exit.
-
-  -c            (ignored)
-  -C            install only if different (preserve the last data modification time)
-  -d            create directories instead of installing files.
-  -g GROUP      $chgrpprog installed files to GROUP.
-  -m MODE       $chmodprog installed files to MODE.
-  -o USER       $chownprog installed files to USER.
-  -s            $stripprog installed files.
-  -S            $stripprog installed files.
-  -t DIRECTORY  install into DIRECTORY.
-  -T            report an error if DSTFILE is a directory.
-
-Environment variables override the default commands:
-  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
-  RMPROG STRIPPROG
-"
-
-while test $# -ne 0; do
-  case $1 in
-    -c) ;;
-
-    -C) copy_on_change=true;;
-
-    -d) dir_arg=true;;
-
-    -g) chgrpcmd="$chgrpprog $2"
-       shift;;
-
-    --help) echo "$usage"; exit $?;;
-
-    -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
-
-    -o) chowncmd="$chownprog $2"
-       shift;;
-
-    -s) stripcmd=$stripprog;;
-
-    -S) stripcmd="$stripprog $2"
-       shift;;
-
-    -t) dst_arg=$2
-       shift;;
-
-    -T) no_target_directory=true;;
-
-    --version) echo "$0 $scriptversion"; exit $?;;
-
-    --)        shift
-       break;;
-
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
-
-    *)  break;;
-  esac
-  shift
-done
-
-if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
-  # When -d is used, all remaining arguments are directories to create.
-  # When -t is used, the destination is already specified.
-  # Otherwise, the last argument is the destination.  Remove it from $@.
-  for arg
-  do
-    if test -n "$dst_arg"; then
-      # $@ is not empty: it contains at least $arg.
-      set fnord "$@" "$dst_arg"
-      shift # fnord
-    fi
-    shift # arg
-    dst_arg=$arg
-  done
-fi
-
-if test $# -eq 0; then
-  if test -z "$dir_arg"; then
-    echo "$0: no input file specified." >&2
-    exit 1
-  fi
-  # It's OK to call `install-sh -d' without argument.
-  # This can happen when creating conditional directories.
-  exit 0
-fi
-
-if test -z "$dir_arg"; then
-  do_exit='(exit $ret); exit $ret'
-  trap "ret=129; $do_exit" 1
-  trap "ret=130; $do_exit" 2
-  trap "ret=141; $do_exit" 13
-  trap "ret=143; $do_exit" 15
-
-  # Set umask so as not to create temps with too-generous modes.
-  # However, 'strip' requires both read and write access to temps.
-  case $mode in
-    # Optimize common cases.
-    *644) cp_umask=133;;
-    *755) cp_umask=22;;
-
-    *[0-7])
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw='% 200'
-      fi
-      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
-    *)
-      if test -z "$stripcmd"; then
-       u_plus_rw=
-      else
-       u_plus_rw=,u+rw
-      fi
-      cp_umask=$mode$u_plus_rw;;
-  esac
-fi
-
-for src
-do
-  # Protect names starting with `-'.
-  case $src in
-    -*) src=./$src;;
-  esac
-
-  if test -n "$dir_arg"; then
-    dst=$src
-    dstdir=$dst
-    test -d "$dstdir"
-    dstdir_status=$?
-  else
-
-    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
-    # might cause directories to be created, which would be especially bad
-    # if $src (and thus $dsttmp) contains '*'.
-    if test ! -f "$src" && test ! -d "$src"; then
-      echo "$0: $src does not exist." >&2
-      exit 1
-    fi
-
-    if test -z "$dst_arg"; then
-      echo "$0: no destination specified." >&2
-      exit 1
-    fi
-
-    dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
-
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
-    if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
-      fi
-      dstdir=$dst
-      dst=$dstdir/`basename "$src"`
-      dstdir_status=0
-    else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
-      test -d "$dstdir"
-      dstdir_status=$?
-    fi
-  fi
-
-  obsolete_mkdir_used=false
-
-  if test $dstdir_status != 0; then
-    case $posix_mkdir in
-      '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
-       else
-         mkdir_mode=
-       fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
-    esac
-
-    if
-      $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
-      )
-    then :
-    else
-
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
-      # or it failed possibly due to a race condition.  Create the
-      # directory the slow way, step by step, checking for races as we go.
-
-      case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
-      esac
-
-      eval "$initialize_posix_glob"
-
-      oIFS=$IFS
-      IFS=/
-      $posix_glob set -f
-      set fnord $dstdir
-      shift
-      $posix_glob set +f
-      IFS=$oIFS
-
-      prefixes=
-
-      for d
-      do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
-      done
-
-      if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
-      fi
-    fi
-  fi
-
-  if test -n "$dir_arg"; then
-    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
-    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
-      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
-  else
-
-    # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
-
-    # Trap to clean up those temp files at exit.
-    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
-
-    # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
-
-    # 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 $cpprog $src $dsttmp" command.
-    #
-    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
-    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
-    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
-    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
-
-    # If -C, don't bother to copy if it wouldn't change the file.
-    if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
-       set X $old && old=:$2:$4:$5:$6 &&
-       set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
-       test "$old" = "$new" &&
-       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
-    then
-      rm -f "$dsttmp"
-    else
-      # Rename the file to the real destination.
-      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
-
-      # The rename failed, perhaps because mv can't rename something else
-      # to itself, or perhaps because mv is so ancient that it does not
-      # support -f.
-      {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
-      }
-    fi || exit 1
-
-    trap '' 0
-  fi
-done
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "scriptversion="
-# time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
-# time-stamp-end: "; # UTC"
-# End:
diff --git a/pkgs/thread2.8.5/tclconfig/tcl.m4 b/pkgs/thread2.8.5/tclconfig/tcl.m4
deleted file mode 100644 (file)
index fb180ab..0000000
+++ /dev/null
@@ -1,4005 +0,0 @@
-# tcl.m4 --
-#
-#      This file provides a set of autoconf macros to help TEA-enable
-#      a Tcl extension.
-#
-# Copyright (c) 1999-2000 Ajuba Solutions.
-# Copyright (c) 2002-2005 ActiveState Corporation.
-#
-# See the file "license.terms" for information on usage and redistribution
-# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
-
-AC_PREREQ(2.57)
-
-# Possible values for key variables defined:
-#
-# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
-# TEA_PLATFORM        - windows unix
-# TEA_TK_EXTENSION    - True if this is a Tk extension
-#
-
-#------------------------------------------------------------------------
-# TEA_PATH_TCLCONFIG --
-#
-#      Locate the tclConfig.sh file and perform a sanity check on
-#      the Tcl compile flags
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tcl=...
-#
-#      Defines the following vars:
-#              TCL_BIN_DIR     Full path to the directory containing
-#                              the tclConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TCLCONFIG], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-    #
-    # Ok, lets find the tcl configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tcl
-    #
-
-    if test x"${no_tcl}" = x ; then
-       # we reset no_tcl in case something fails here
-       no_tcl=true
-       AC_ARG_WITH(tcl,
-           AC_HELP_STRING([--with-tcl],
-               [directory containing tcl configuration (tclConfig.sh)]),
-           with_tclconfig="${withval}")
-       AC_MSG_CHECKING([for Tcl configuration])
-       AC_CACHE_VAL(ac_cv_c_tclconfig,[
-
-           # First check to see if --with-tcl was specified.
-           if test x"${with_tclconfig}" != x ; then
-               case "${with_tclconfig}" in
-                   */tclConfig.sh )
-                       if test -f "${with_tclconfig}"; then
-                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
-                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tclconfig}/tclConfig.sh" ; then
-                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tcl installation
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ../tcl \
-                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tcl \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tcl \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /System/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tclconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tcl \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tclConfig.sh" ; then
-                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tclconfig}" = x ; then
-           TCL_BIN_DIR="# no Tcl configs found"
-           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
-       else
-           no_tcl=
-           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
-           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_TKCONFIG --
-#
-#      Locate the tkConfig.sh file
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-tk=...
-#
-#      Defines the following vars:
-#              TK_BIN_DIR      Full path to the directory containing
-#                              the tkConfig.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_TKCONFIG], [
-    #
-    # Ok, lets find the tk configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-tk
-    #
-
-    if test x"${no_tk}" = x ; then
-       # we reset no_tk in case something fails here
-       no_tk=true
-       AC_ARG_WITH(tk,
-           AC_HELP_STRING([--with-tk],
-               [directory containing tk configuration (tkConfig.sh)]),
-           with_tkconfig="${withval}")
-       AC_MSG_CHECKING([for Tk configuration])
-       AC_CACHE_VAL(ac_cv_c_tkconfig,[
-
-           # First check to see if --with-tkconfig was specified.
-           if test x"${with_tkconfig}" != x ; then
-               case "${with_tkconfig}" in
-                   */tkConfig.sh )
-                       if test -f "${with_tkconfig}"; then
-                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
-                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
-                       fi ;;
-               esac
-               if test -f "${with_tkconfig}/tkConfig.sh" ; then
-                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
-               else
-                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
-               fi
-           fi
-
-           # then check for a private Tk library
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ../tk \
-                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../tk \
-                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../tk \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # on Darwin, check in Framework installation locations
-           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Library/Frameworks 2>/dev/null` \
-                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
-                       `ls -d /System/Library/Frameworks 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
-                       ; do
-                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
-                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # TEA specific: on Windows, check in common installation locations
-           if test "${TEA_PLATFORM}" = "windows" \
-               -a x"${ac_cv_c_tkconfig}" = x ; then
-               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
-                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
-                       ; do
-                   if test -f "$i/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few other private locations
-           if test x"${ac_cv_c_tkconfig}" = x ; then
-               for i in \
-                       ${srcdir}/../tk \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
-                   if test "${TEA_PLATFORM}" = "windows" \
-                           -a -f "$i/win/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
-                       break
-                   fi
-                   if test -f "$i/unix/tkConfig.sh" ; then
-                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_tkconfig}" = x ; then
-           TK_BIN_DIR="# no Tk configs found"
-           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
-       else
-           no_tk=
-           TK_BIN_DIR="${ac_cv_c_tkconfig}"
-           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TCLCONFIG --
-#
-#      Load the tclConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TCL_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_BIN_DIR
-#              TCL_SRC_DIR
-#              TCL_LIB_FILE
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TCLCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
-
-    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TCL_BIN_DIR}/tclConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
-    # If the TCL_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TCL_LIB_SPEC will be set to the value
-    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
-    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
-        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
-        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tcl was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tcl.framework installed in an arbitrary location.
-       case ${TCL_DEFS} in
-           *TCL_FRAMEWORK*)
-               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
-                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
-                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
-                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
-                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
-                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
-    AC_SUBST(TCL_VERSION)
-    AC_SUBST(TCL_PATCH_LEVEL)
-    AC_SUBST(TCL_BIN_DIR)
-    AC_SUBST(TCL_SRC_DIR)
-
-    AC_SUBST(TCL_LIB_FILE)
-    AC_SUBST(TCL_LIB_FLAG)
-    AC_SUBST(TCL_LIB_SPEC)
-
-    AC_SUBST(TCL_STUB_LIB_FILE)
-    AC_SUBST(TCL_STUB_LIB_FLAG)
-    AC_SUBST(TCL_STUB_LIB_SPEC)
-
-    AC_MSG_CHECKING([platform])
-    hold_cc=$CC; CC="$TCL_CC"
-    AC_TRY_COMPILE(,[
-           #ifdef _WIN32
-               #error win32
-           #endif
-       ], [
-           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
-           TEA_PLATFORM="${TEA_PLATFORM-unix}"
-           CYGPATH=echo
-       ], [
-           TEA_PLATFORM="windows"
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
-    )
-    CC=$hold_cc
-    AC_MSG_RESULT($TEA_PLATFORM)
-
-    # The BUILD_$pkg is to define the correct extern storage class
-    # handling when making this package
-    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
-           [Building extension source?])
-    # Do this here as we have fully defined TEA_PLATFORM now
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       EXEEXT=".exe"
-       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
-    fi
-
-    # TEA specific:
-    AC_SUBST(CLEANFILES)
-    AC_SUBST(TCL_LIBS)
-    AC_SUBST(TCL_DEFS)
-    AC_SUBST(TCL_EXTRA_CFLAGS)
-    AC_SUBST(TCL_LD_FLAGS)
-    AC_SUBST(TCL_SHLIB_LD_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_TKCONFIG --
-#
-#      Load the tkConfig.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              TK_BIN_DIR
-#
-# Results:
-#
-#      Sets the following vars that should be in tkConfig.sh:
-#              TK_BIN_DIR
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_TKCONFIG], [
-    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
-
-    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${TK_BIN_DIR}/tkConfig.sh"
-    else
-        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
-    # If the TK_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable TK_LIB_SPEC will be set to the value
-    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
-    # instead of TK_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
-        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
-        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
-    elif test "`uname -s`" = "Darwin"; then
-       # If Tk was built as a framework, attempt to use the libraries
-       # from the framework at the given location so that linking works
-       # against Tk.framework installed in an arbitrary location.
-       case ${TK_DEFS} in
-           *TK_FRAMEWORK*)
-               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
-                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
-                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
-                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
-                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
-                           break
-                       fi
-                   done
-               fi
-               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
-                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
-                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
-               fi
-               ;;
-       esac
-    fi
-
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
-    # TEA specific: Ensure windowingsystem is defined
-    if test "${TEA_PLATFORM}" = "unix" ; then
-       case ${TK_DEFS} in
-           *MAC_OSX_TK*)
-               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
-               TEA_WINDOWINGSYSTEM="aqua"
-               ;;
-           *)
-               TEA_WINDOWINGSYSTEM="x11"
-               ;;
-       esac
-    elif test "${TEA_PLATFORM}" = "windows" ; then
-       TEA_WINDOWINGSYSTEM="win32"
-    fi
-
-    AC_SUBST(TK_VERSION)
-    AC_SUBST(TK_BIN_DIR)
-    AC_SUBST(TK_SRC_DIR)
-
-    AC_SUBST(TK_LIB_FILE)
-    AC_SUBST(TK_LIB_FLAG)
-    AC_SUBST(TK_LIB_SPEC)
-
-    AC_SUBST(TK_STUB_LIB_FILE)
-    AC_SUBST(TK_STUB_LIB_FLAG)
-    AC_SUBST(TK_STUB_LIB_SPEC)
-
-    # TEA specific:
-    AC_SUBST(TK_LIBS)
-    AC_SUBST(TK_XINCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_TCLSH
-#      Determine the fully qualified path name of the tclsh executable
-#      in the Tcl build directory or the tclsh installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the tclsh executable even if tclsh has not yet been
-#      built in the build directory. The tclsh found is always
-#      associated with a tclConfig.sh file. This tclsh should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCLSH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_TCLSH], [
-    AC_MSG_CHECKING([for tclsh])
-    if test -f "${TCL_BIN_DIR}/Makefile" ; then
-        # tclConfig.sh is in Tcl build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
-          fi
-        else
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
-        fi
-    else
-        # tclConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-        else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
-        fi
-        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${TCLSH_PROG}" ; then
-                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
-    fi
-    AC_MSG_RESULT([${TCLSH_PROG}])
-    AC_SUBST(TCLSH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_PROG_WISH
-#      Determine the fully qualified path name of the wish executable
-#      in the Tk build directory or the wish installed in a bin
-#      directory. This macro will correctly determine the name
-#      of the wish executable even if wish has not yet been
-#      built in the build directory. The wish found is always
-#      associated with a tkConfig.sh file. This wish should be used
-#      only for running extension test cases. It should never be
-#      or generation of files (like pkgIndex.tcl) at build time.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              WISH_PROG
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PROG_WISH], [
-    AC_MSG_CHECKING([for wish])
-    if test -f "${TK_BIN_DIR}/Makefile" ; then
-        # tkConfig.sh is in Tk build directory
-        if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}s${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}$s{EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}t${EXEEXT}"
-          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}" ; then
-            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}st${EXEEXT}"
-          fi
-        else
-            WISH_PROG="${TK_BIN_DIR}/wish"
-        fi
-    else
-        # tkConfig.sh is in install location
-        if test "${TEA_PLATFORM}" = "windows"; then
-            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${TK_DBGX}${EXEEXT}"
-        else
-            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}${TK_DBGX}"
-        fi
-        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
-              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
-              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
-        for i in $list ; do
-            if test -f "$i/${WISH_PROG}" ; then
-                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
-                break
-            fi
-        done
-        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
-    fi
-    AC_MSG_RESULT([${WISH_PROG}])
-    AC_SUBST(WISH_PROG)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SHARED --
-#
-#      Allows the building of shared libraries
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-shared=yes|no
-#              --enable-stubs=yes|no
-#
-#      Defines the following vars:
-#              STATIC_BUILD    Used for building import/export libraries
-#                              on Windows.
-#
-#      Sets the following vars:
-#              SHARED_BUILD    Value of 1 or 0
-#               STUBS_BUILD     Value if 1 or 0
-#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
-#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
-#                                AND TEA_WINDOWING_SYSTEM != ""
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ENABLE_SHARED], [
-    AC_MSG_CHECKING([how to build libraries])
-    AC_ARG_ENABLE(shared,
-       AC_HELP_STRING([--enable-shared],
-           [build and link with shared libraries (default: on)]),
-       [shared_ok=$enableval], [shared_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       shared_ok=$enableval
-    else
-       shared_ok=yes
-    fi
-
-    AC_ARG_ENABLE(stubs,
-       AC_HELP_STRING([--enable-stubs],
-           [build and link with stub libraries. Always true for shared builds (default: on)]),
-       [stubs_ok=$enableval], [stubs_ok=yes])
-
-    if test "${enable_stubs+set}" = set; then
-       enableval="$enable_stubs"
-       stubs_ok=$enableval
-    else
-       stubs_ok=yes
-    fi
-
-    # Stubs are always enabled for shared builds
-    if test "$shared_ok" = "yes" ; then
-       AC_MSG_RESULT([shared])
-       SHARED_BUILD=1
-        STUBS_BUILD=1
-    else
-       AC_MSG_RESULT([static])
-       SHARED_BUILD=0
-       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
-        if test "$stubs_ok" = "yes" ; then
-          STUBS_BUILD=1
-        else
-          STUBS_BUILD=0
-        fi
-    fi
-    if test "${STUBS_BUILD}" = "1" ; then
-      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
-      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
-      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
-        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
-      fi
-    fi
-
-    AC_SUBST(SHARED_BUILD)
-    AC_SUBST(STUBS_BUILD)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_THREADS --
-#
-#      Specify if thread support should be enabled.  If "yes" is specified
-#      as an arg (optional), threads are enabled by default, "no" means
-#      threads are disabled.  "yes" is the default.
-#
-#      TCL_THREADS is checked so that if you are compiling an extension
-#      against a threaded core, your extension must be compiled threaded
-#      as well.
-#
-#      Note that it is legal to have a thread enabled extension run in a
-#      threaded or non-threaded Tcl core, but a non-threaded extension may
-#      only run in a non-threaded Tcl core.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-threads
-#
-#      Sets the following vars:
-#              THREADS_LIBS    Thread library(s)
-#
-#      Defines the following vars:
-#              TCL_THREADS
-#              _REENTRANT
-#              _THREAD_SAFE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_THREADS], [
-    AC_ARG_ENABLE(threads,
-       AC_HELP_STRING([--enable-threads],
-           [build with threads (default: on)]),
-       [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_threads+set}" = set; then
-       enableval="$enable_threads"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
-    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
-       TCL_THREADS=1
-
-       if test "${TEA_PLATFORM}" != "windows" ; then
-           # We are always OK on Windows, so check what this platform wants:
-
-           # USE_THREAD_ALLOC tells us to try the special thread-based
-           # allocator that significantly reduces lock contention
-           AC_DEFINE(USE_THREAD_ALLOC, 1,
-               [Do we want to use the threaded memory allocator?])
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           if test "`uname -s`" = "SunOS" ; then
-               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-                       [Do we really want to follow the standard? Yes we do!])
-           fi
-           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
-           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
-           if test "$tcl_ok" = "no"; then
-               # Check a little harder for __pthread_mutex_init in the same
-               # library, as some systems hide it there until pthread.h is
-               # defined.  We could alternatively do an AC_TRY_COMPILE with
-               # pthread.h, but that will work with libpthread really doesn't
-               # exist, like AIX 4.2.  [Bug: 4359]
-               AC_CHECK_LIB(pthread, __pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-           fi
-
-           if test "$tcl_ok" = "yes"; then
-               # The space is needed
-               THREADS_LIBS=" -lpthread"
-           else
-               AC_CHECK_LIB(pthreads, pthread_mutex_init,
-                   tcl_ok=yes, tcl_ok=no)
-               if test "$tcl_ok" = "yes"; then
-                   # The space is needed
-                   THREADS_LIBS=" -lpthreads"
-               else
-                   AC_CHECK_LIB(c, pthread_mutex_init,
-                       tcl_ok=yes, tcl_ok=no)
-                   if test "$tcl_ok" = "no"; then
-                       AC_CHECK_LIB(c_r, pthread_mutex_init,
-                           tcl_ok=yes, tcl_ok=no)
-                       if test "$tcl_ok" = "yes"; then
-                           # The space is needed
-                           THREADS_LIBS=" -pthread"
-                       else
-                           TCL_THREADS=0
-                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
-                       fi
-                   fi
-               fi
-           fi
-       fi
-    else
-       TCL_THREADS=0
-    fi
-    # Do checking message here to not mess up interleaved configure output
-    AC_MSG_CHECKING([for building with threads])
-    if test "${TCL_THREADS}" = 1; then
-       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
-       AC_MSG_RESULT([yes (default)])
-    else
-       AC_MSG_RESULT([no])
-    fi
-    # TCL_THREADS sanity checking.  See if our request for building with
-    # threads is the same as the way Tcl was built.  If not, warn the user.
-    case ${TCL_DEFS} in
-       *THREADS=1*)
-           if test "${TCL_THREADS}" = "0"; then
-               AC_MSG_WARN([
-    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
-    that IS thread-enabled.  It is recommended to use --enable-threads.])
-           fi
-           ;;
-    esac
-    AC_SUBST(TCL_THREADS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_SYMBOLS --
-#
-#      Specify if debugging symbols should be used.
-#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
-#
-# Arguments:
-#      none
-#
-#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
-#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
-#      Requires the following vars to be set in the Makefile:
-#              CFLAGS_DEFAULT
-#              LDFLAGS_DEFAULT
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-symbols
-#
-#      Defines the following vars:
-#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
-#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
-#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
-#                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_SYMBOLS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_CONFIG_CFLAGS])
-    AC_MSG_CHECKING([for build with symbols])
-    AC_ARG_ENABLE(symbols,
-       AC_HELP_STRING([--enable-symbols],
-           [build with debugging symbols (default: off)]),
-       [tcl_ok=$enableval], [tcl_ok=no])
-    DBGX=""
-    if test "$tcl_ok" = "no"; then
-       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
-       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
-       AC_MSG_RESULT([no])
-    else
-       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
-       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
-       if test "$tcl_ok" = "yes"; then
-           AC_MSG_RESULT([yes (standard debugging)])
-       fi
-    fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-    AC_SUBST(CFLAGS_DEFAULT)
-    AC_SUBST(LDFLAGS_DEFAULT)
-    AC_SUBST(TCL_DBGX)
-
-    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
-       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
-    fi
-
-    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
-       if test "$tcl_ok" = "all"; then
-           AC_MSG_RESULT([enabled symbols mem debugging])
-       else
-           AC_MSG_RESULT([enabled $tcl_ok debugging])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_ENABLE_LANGINFO --
-#
-#      Allows use of modern nl_langinfo check for better l10n.
-#      This is only relevant for Unix.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --enable-langinfo=yes|no (default is yes)
-#
-#      Defines the following vars:
-#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_ENABLE_LANGINFO], [
-    AC_ARG_ENABLE(langinfo,
-       AC_HELP_STRING([--enable-langinfo],
-           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
-       [langinfo_ok=$enableval], [langinfo_ok=yes])
-
-    HAVE_LANGINFO=0
-    if test "$langinfo_ok" = "yes"; then
-       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
-    fi
-    AC_MSG_CHECKING([whether to use nl_langinfo])
-    if test "$langinfo_ok" = "yes"; then
-       AC_CACHE_VAL(tcl_cv_langinfo_h, [
-           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
-                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
-       AC_MSG_RESULT([$tcl_cv_langinfo_h])
-       if test $tcl_cv_langinfo_h = yes; then
-           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
-       fi
-    else
-       AC_MSG_RESULT([$langinfo_ok])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_SYSTEM
-#
-#      Determine what the system is (some things cannot be easily checked
-#      on a feature-driven basis, alas). This can usually be done via the
-#      "uname" command.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Defines the following var:
-#
-#      system -        System/platform/version identification code.
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_SYSTEM], [
-    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
-       # TEA specific:
-       if test "${TEA_PLATFORM}" = "windows" ; then
-           tcl_cv_sys_version=windows
-       else
-           tcl_cv_sys_version=`uname -s`-`uname -r`
-           if test "$?" -ne 0 ; then
-               AC_MSG_WARN([can't find uname command])
-               tcl_cv_sys_version=unknown
-           else
-               if test "`uname -s`" = "AIX" ; then
-                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
-               fi
-           fi
-       fi
-    ])
-    system=$tcl_cv_sys_version
-])
-
-#--------------------------------------------------------------------
-# TEA_CONFIG_CFLAGS
-#
-#      Try to determine the proper flags to pass to the compiler
-#      for building shared libraries and other such nonsense.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substitutes the following vars:
-#
-#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
-#       LDFLAGS -      Flags to pass to the compiler when linking object
-#                       files into an executable application binary such
-#                       as tclsh.
-#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
-#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
-#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
-#                       that tell the run-time dynamic linker where to look
-#                       for shared libraries such as libtcl.so.  Depends on
-#                       the variable LIB_RUNTIME_DIR in the Makefile.
-#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
-#                       of a shared library (may request position-independent
-#                       code, among other things).
-#       SHLIB_LD -      Base command to use for combining object files
-#                       into a shared library.
-#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
-#                       creating shared libraries.  This symbol typically
-#                       goes at the end of the "ld" commands that build
-#                       shared libraries. The value of the symbol defaults to
-#                       "${LIBS}" if all of the dependent libraries should
-#                       be specified when creating a shared library.  If
-#                       dependent libraries should not be specified (as on
-#                       SunOS 4.x, where they cause the link to fail, or in
-#                       general if Tcl and Tk aren't themselves shared
-#                       libraries), then this symbol has an empty string
-#                       as its value.
-#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
-#                       extensions.  An empty string means we don't know how
-#                       to use shared libraries on this platform.
-#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
-#                       in a static or shared library name, using the $PACKAGE_VERSION variable
-#                       to put the version in the right place.  This is used
-#                       by platforms that need non-standard library names.
-#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
-#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
-#                       on AIX, since a shared library needs to have
-#                       a .a extension whereas shared objects for loadable
-#                       extensions have a .so extension.  Defaults to
-#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
-#      CFLAGS_DEBUG -
-#                      Flags used when running the compiler in debug mode
-#      CFLAGS_OPTIMIZE -
-#                      Flags used when running the compiler in optimize mode
-#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_CONFIG_CFLAGS], [
-    dnl TEA specific: Make sure we are initialized
-    AC_REQUIRE([TEA_INIT])
-
-    # Step 0.a: Enable 64 bit support?
-
-    AC_MSG_CHECKING([if 64bit support is requested])
-    AC_ARG_ENABLE(64bit,
-       AC_HELP_STRING([--enable-64bit],
-           [enable 64bit support (default: off)]),
-       [do64bit=$enableval], [do64bit=no])
-    AC_MSG_RESULT([$do64bit])
-
-    # Step 0.b: Enable Solaris 64 bit VIS support?
-
-    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
-    AC_ARG_ENABLE(64bit-vis,
-       AC_HELP_STRING([--enable-64bit-vis],
-           [enable 64bit Sparc VIS support (default: off)]),
-       [do64bitVIS=$enableval], [do64bitVIS=no])
-    AC_MSG_RESULT([$do64bitVIS])
-    # Force 64bit on with VIS
-    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
-
-    # Step 0.c: Check if visibility support is available. Do this here so
-    # that platform specific alternatives can be used below if this fails.
-
-    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
-       tcl_cv_cc_visibility_hidden, [
-       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
-       AC_TRY_LINK([
-           extern __attribute__((__visibility__("hidden"))) void f(void);
-           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
-           tcl_cv_cc_visibility_hidden=no)
-       CFLAGS=$hold_cflags])
-    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
-       AC_DEFINE(MODULE_SCOPE,
-           [extern __attribute__((__visibility__("hidden")))],
-           [Compiler support for module scope symbols])
-       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
-    ])
-
-    # Step 0.d: Disable -rpath support?
-
-    AC_MSG_CHECKING([if rpath support is requested])
-    AC_ARG_ENABLE(rpath,
-       AC_HELP_STRING([--disable-rpath],
-           [disable rpath support (default: on)]),
-       [doRpath=$enableval], [doRpath=yes])
-    AC_MSG_RESULT([$doRpath])
-
-    # Set the variable "system" to hold the name and version number
-    # for the system.
-
-    TEA_CONFIG_SYSTEM
-
-    # Require ranlib early so we can override it in special cases below.
-
-    AC_REQUIRE([AC_PROG_RANLIB])
-
-    # Set configuration options based on system name and version.
-    # This is similar to Tcl's unix/tcl.m4 except that we've added a
-    # "windows" case and removed some core-only vars.
-
-    do64bit_ok=no
-    # default to '{$LIBS}' and set to "" on per-platform necessary basis
-    SHLIB_LD_LIBS='${LIBS}'
-    # When ld needs options to work in 64-bit mode, put them in
-    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
-    # is disabled by the user. [Bug 1016796]
-    LDFLAGS_ARCH=""
-    UNSHARED_LIB_SUFFIX=""
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
-    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
-    TCL_LIB_VERSIONS_OK=ok
-    CFLAGS_DEBUG=-g
-    AS_IF([test "$GCC" = yes], [
-       CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
-    ], [
-       CFLAGS_OPTIMIZE=-O
-       CFLAGS_WARNING=""
-    ])
-    AC_CHECK_TOOL(AR, ar)
-    STLIB_LD='${AR} cr'
-    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
-    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
-    case $system in
-       # TEA specific:
-       windows)
-           # This is a 2-stage check to make sure we have the 64-bit SDK
-           # We have to know where the SDK is installed.
-           # This magic is based on MS Platform SDK for Win2003 SP1 - hobbs
-           # MACHINE is IX86 for LINK, but this is used by the manifest,
-           # which requires x86|amd64|ia64.
-           MACHINE="X86"
-           if test "$do64bit" != "no" ; then
-               if test "x${MSSDK}x" = "xx" ; then
-                   MSSDK="C:/Progra~1/Microsoft Platform SDK"
-               fi
-               MSSDK=`echo "$MSSDK" | sed -e  's!\\\!/!g'`
-               PATH64=""
-               case "$do64bit" in
-                   amd64|x64|yes)
-                       MACHINE="AMD64" ; # default to AMD64 64-bit build
-                       PATH64="${MSSDK}/Bin/Win64/x86/AMD64"
-                       ;;
-                   ia64)
-                       MACHINE="IA64"
-                       PATH64="${MSSDK}/Bin/Win64"
-                       ;;
-               esac
-               if test "$GCC" != "yes" -a ! -d "${PATH64}" ; then
-                   AC_MSG_WARN([Could not find 64-bit $MACHINE SDK to enable 64bit mode])
-                   AC_MSG_WARN([Ensure latest Platform SDK is installed])
-                   do64bit="no"
-               else
-                   AC_MSG_RESULT([   Using 64-bit $MACHINE mode])
-                   do64bit_ok="yes"
-               fi
-           fi
-
-           if test "$GCC" != "yes" ; then
-               if test "${SHARED_BUILD}" = "0" ; then
-                   runtime=-MT
-               else
-                   runtime=-MD
-               fi
-               case "x`echo \${VisualStudioVersion}`" in
-                   x1[[4-9]]*)
-                       lflags="${lflags} -nodefaultlib:libucrt.lib"
-                       TEA_ADD_LIBS([ucrt.lib])
-                   ;;
-                   *)
-                   ;;
-               esac
-
-                if test "$do64bit" != "no" ; then
-                   # All this magic is necessary for the Win64 SDK RC1 - hobbs
-                   CC="\"${PATH64}/cl.exe\""
-                   CFLAGS="${CFLAGS} -I\"${MSSDK}/Include\" -I\"${MSSDK}/Include/crt\" -I\"${MSSDK}/Include/crt/sys\""
-                   RC="\"${MSSDK}/bin/rc.exe\""
-                   lflags="${lflags} -nologo -MACHINE:${MACHINE} -LIBPATH:\"${MSSDK}/Lib/${MACHINE}\""
-                   LINKBIN="\"${PATH64}/link.exe\""
-                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-                   # Avoid 'unresolved external symbol __security_cookie'
-                   # errors, c.f. http://support.microsoft.com/?id=894573
-                   TEA_ADD_LIBS([bufferoverflowU.lib])
-               else
-                   RC="rc"
-                   lflags="${lflags} -nologo"
-                   LINKBIN="link"
-                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
-                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
-               fi
-           fi
-
-           if test "$GCC" = "yes"; then
-               # mingw gcc mode
-               AC_CHECK_TOOL(RC, windres)
-               CFLAGS_DEBUG="-g"
-               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-               SHLIB_LD='${CC} -shared'
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
-               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
-
-               AC_CACHE_CHECK(for cross-compile version of gcc,
-                       ac_cv_cross,
-                       AC_TRY_COMPILE([
-                           #ifdef _WIN32
-                               #error cross-compiler
-                           #endif
-                       ], [],
-                       ac_cv_cross=yes,
-                       ac_cv_cross=no)
-                     )
-                     if test "$ac_cv_cross" = "yes"; then
-                       case "$do64bit" in
-                           amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
-                               LD="x86_64-w64-mingw32-ld"
-                               AR="x86_64-w64-mingw32-ar"
-                               RANLIB="x86_64-w64-mingw32-ranlib"
-                               RC="x86_64-w64-mingw32-windres"
-                           ;;
-                           *)
-                               CC="i686-w64-mingw32-gcc"
-                               LD="i686-w64-mingw32-ld"
-                               AR="i686-w64-mingw32-ar"
-                               RANLIB="i686-w64-mingw32-ranlib"
-                               RC="i686-w64-mingw32-windres"
-                           ;;
-                       esac
-               fi
-
-           else
-               SHLIB_LD="${LINKBIN} -dll ${lflags}"
-               # link -lib only works when -lib is the first arg
-               STLIB_LD="${LINKBIN} -lib ${lflags}"
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
-               PATHTYPE=-w
-               # For information on what debugtype is most useful, see:
-               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
-               # and also
-               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
-               # This essentially turns it all on.
-               LDFLAGS_DEBUG="-debug -debugtype:cv"
-               LDFLAGS_OPTIMIZE="-release"
-               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
-               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
-           fi
-
-           SHLIB_SUFFIX=".dll"
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
-
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       AIX-*)
-           AS_IF([test "${TCL_THREADS}" = "1" -a "$GCC" != "yes"], [
-               # AIX requires the _r compiler when gcc isn't being used
-               case "${CC}" in
-                   *_r|*_r\ *)
-                       # ok ...
-                       ;;
-                   *)
-                       # Make sure only first arg gets _r
-                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
-                       ;;
-               esac
-               AC_MSG_RESULT([Using $CC for compiling with threads])
-           ])
-           LIBS="$LIBS -lc"
-           SHLIB_CFLAGS=""
-           SHLIB_SUFFIX=".so"
-
-           LD_LIBRARY_PATH_VAR="LIBPATH"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS -q64"
-                   LDFLAGS_ARCH="-q64"
-                   RANLIB="${RANLIB} -X64"
-                   AR="${AR} -X64"
-                   SHLIB_LD_FLAGS="-b64"
-               ])
-           ])
-
-           AS_IF([test "`uname -m`" = ia64], [
-               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               AS_IF([test "$GCC" = yes], [
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               ], [
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
-               ])
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ], [
-               AS_IF([test "$GCC" = yes], [
-                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
-               ], [
-                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
-                   LDFLAGS="$LDFLAGS -brtl"
-               ])
-               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       BeOS*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} -nostart'
-           SHLIB_SUFFIX=".so"
-
-           #-----------------------------------------------------------
-           # Check for inet_ntoa in -lbind, for BeOS (which also needs
-           # -lsocket, even if the network functions are in -lnet which
-           # is always linked to, for compatibility.
-           #-----------------------------------------------------------
-           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
-           ;;
-       BSD/OS-4.*)
-           SHLIB_CFLAGS="-export-dynamic -fPIC"
-           SHLIB_LD='${CC} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       CYGWIN_*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD='${CC} -shared'
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
-           SHLIB_SUFFIX=".dll"
-           EXEEXT=".exe"
-           do64bit_ok=yes
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       Haiku*)
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
-           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
-           ;;
-       HP-UX-*.11.*)
-           # Use updated header definitions where possible
-           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
-           # TEA specific: Needed by Tcl, but not most extensions
-           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
-           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
-
-           AS_IF([test "`uname -m`" = ia64], [
-               SHLIB_SUFFIX=".so"
-               # Use newer C++ library for C++ extensions
-               #if test "$GCC" != "yes" ; then
-               #   CPPFLAGS="-AA"
-               #fi
-           ], [
-               SHLIB_SUFFIX=".sl"
-           ])
-           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
-           AS_IF([test "$tcl_ok" = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
-               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
-           ])
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               CFLAGS="$CFLAGS -z"
-               # Users may want PA-RISC 1.1/2.0 portable code - needs HP cc
-               #CFLAGS="$CFLAGS +DAportable"
-               SHLIB_CFLAGS="+z"
-               SHLIB_LD="ld -b"
-           ])
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = "yes"], [
-               AS_IF([test "$GCC" = yes], [
-                   case `${CC} -dumpmachine` in
-                       hppa64*)
-                           # 64-bit gcc in use.  Fix flags for GNU ld.
-                           do64bit_ok=yes
-                           SHLIB_LD='${CC} -shared'
-                           AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-                           ;;
-                       *)
-                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
-                           ;;
-                   esac
-               ], [
-                   do64bit_ok=yes
-                   CFLAGS="$CFLAGS +DD64"
-                   LDFLAGS_ARCH="+DD64"
-               ])
-           ]) ;;
-       IRIX-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [
-               CFLAGS="$CFLAGS -mabi=n32"
-               LDFLAGS="$LDFLAGS -mabi=n32"
-           ], [
-               case $system in
-                   IRIX-6.3)
-                       # Use to build 6.2 compatible binaries on 6.3.
-                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
-                       ;;
-                   *)
-                       CFLAGS="$CFLAGS -n32"
-                       ;;
-               esac
-               LDFLAGS="$LDFLAGS -n32"
-           ])
-           ;;
-       IRIX64-6.*)
-           SHLIB_CFLAGS=""
-           SHLIB_LD="ld -n32 -shared -rdata_shared"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-
-           # Check to enable 64-bit flags for compiler/linker
-
-           AS_IF([test "$do64bit" = yes], [
-               AS_IF([test "$GCC" = yes], [
-                   AC_MSG_WARN([64bit mode not supported by gcc])
-               ], [
-                   do64bit_ok=yes
-                   SHLIB_LD="ld -64 -shared -rdata_shared"
-                   CFLAGS="$CFLAGS -64"
-                   LDFLAGS_ARCH="-64"
-               ])
-           ])
-           ;;
-       Linux*|GNU*|NetBSD-Debian)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-
-           # TEA specific:
-           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
-           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
-           AS_IF([test $do64bit = yes], [
-               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
-                   hold_cflags=$CFLAGS
-                   CFLAGS="$CFLAGS -m64"
-                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
-                   CFLAGS=$hold_cflags])
-               AS_IF([test $tcl_cv_cc_m64 = yes], [
-                   CFLAGS="$CFLAGS -m64"
-                   do64bit_ok=yes
-               ])
-          ])
-
-           # The combo of gcc + glibc has a bug related to inlining of
-           # functions like strtod(). The -fno-builtin flag should address
-           # this problem but it does not work. The -fno-inline flag is kind
-           # of overkill but it works. Disable inlining only when one of the
-           # files in compat/*.c is being linked in.
-
-           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
-           ;;
-       Lynx*)
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_SUFFIX=".so"
-           CFLAGS_OPTIMIZE=-02
-           SHLIB_LD='${CC} -shared'
-           LD_FLAGS="-Wl,--export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           ;;
-       OpenBSD-*)
-           arch=`arch -s`
-           case "$arch" in
-           alpha|sparc64)
-               SHLIB_CFLAGS="-fPIC"
-               ;;
-           *)
-               SHLIB_CFLAGS="-fpic"
-               ;;
-           esac
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
-           CFLAGS_OPTIMIZE="-O2"
-           AS_IF([test "${TCL_THREADS}" = "1"], [
-               # On OpenBSD:   Compile with -pthread
-               #               Don't link with -lpthread
-               LIBS=`echo $LIBS | sed s/-lpthread//`
-               CFLAGS="$CFLAGS -pthread"
-           ])
-           # OpenBSD doesn't do version numbers with dots.
-           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-           TCL_LIB_VERSIONS_OK=nodots
-           ;;
-       NetBSD-*)
-           # NetBSD has ELF and can use 'cc -shared' to build shared libs
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
-           SHLIB_SUFFIX=".so"
-           LDFLAGS="$LDFLAGS -export-dynamic"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           AS_IF([test "${TCL_THREADS}" = "1"], [
-               # The -pthread needs to go in the CFLAGS, not LIBS
-               LIBS=`echo $LIBS | sed s/-pthread//`
-               CFLAGS="$CFLAGS -pthread"
-               LDFLAGS="$LDFLAGS -pthread"
-           ])
-           ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$[@]"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
-           AS_IF([test "${TCL_THREADS}" = "1"], [
-               # The -pthread needs to go in the LDFLAGS, not LIBS
-               LIBS=`echo $LIBS | sed s/-pthread//`
-               CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-               LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
-       Darwin-*)
-           CFLAGS_OPTIMIZE="-Os"
-           SHLIB_CFLAGS="-fno-common"
-           # To avoid discrepancies between what headers configure sees during
-           # preprocessing tests and compiling tests, move any -isysroot and
-           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
-           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
-           CFLAGS="`echo " ${CFLAGS}" | \
-               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
-               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
-           AS_IF([test $do64bit = yes], [
-               case `arch` in
-                   ppc)
-                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
-                               tcl_cv_cc_arch_ppc64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
-                                   tcl_cv_cc_arch_ppc64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
-                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
-                           do64bit_ok=yes
-                       ]);;
-                   i386)
-                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
-                               tcl_cv_cc_arch_x86_64, [
-                           hold_cflags=$CFLAGS
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
-                                   tcl_cv_cc_arch_x86_64=no)
-                           CFLAGS=$hold_cflags])
-                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
-                           CFLAGS="$CFLAGS -arch x86_64"
-                           do64bit_ok=yes
-                       ]);;
-                   *)
-                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
-               esac
-           ], [
-               # Check for combined 32-bit and 64-bit fat build
-               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
-                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
-                   fat_32_64=yes])
-           ])
-           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
-           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_single_module = yes], [
-               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
-           ])
-           # TEA specific: link shlib with current and compatibility version flags
-           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
-           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
-           SHLIB_SUFFIX=".dylib"
-           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
-           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
-                   tcl_cv_ld_search_paths_first, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
-                       tcl_cv_ld_search_paths_first=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
-           ])
-           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
-                   [Compiler support for module scope symbols])
-               tcl_cv_cc_visibility_hidden=yes
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
-           # TEA specific: for combined 32 & 64 bit fat builds of Tk
-           # extensions, verify that 64-bit build is possible.
-           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
-                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
-                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
-                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
-                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
-                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
-                       done
-                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
-                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
-                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
-                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
-                       for v in CFLAGS CPPFLAGS LDFLAGS; do
-                           eval $v'="$hold_'$v'"'
-                       done])
-               ])
-               # remove 64-bit arch flags from CFLAGS et al. if configuration
-               # does not support 64-bit.
-               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
-                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
-                   for v in CFLAGS CPPFLAGS LDFLAGS; do
-                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
-                   done])
-           ])
-           ;;
-       OS/390-*)
-           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
-           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
-               [Should OS/390 do the right thing with sockets?])
-           ;;
-       OSF1-V*)
-           # Digital OSF/1
-           SHLIB_CFLAGS=""
-           AS_IF([test "$SHARED_BUILD" = 1], [
-               SHLIB_LD='ld -shared -expect_unresolved "*"'
-           ], [
-               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
-           ])
-           SHLIB_SUFFIX=".so"
-           AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
-           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
-               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
-           # see pthread_intro(3) for pthread support on osf1, k.furukawa
-           AS_IF([test "${TCL_THREADS}" = 1], [
-               CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
-               CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
-               LIBS=`echo $LIBS | sed s/-lpthreads//`
-               AS_IF([test "$GCC" = yes], [
-                   LIBS="$LIBS -lpthread -lmach -lexc"
-               ], [
-                   CFLAGS="$CFLAGS -pthread"
-                   LDFLAGS="$LDFLAGS -pthread"
-               ])
-           ])
-           ;;
-       QNX-6*)
-           # QNX RTP
-           # This may work for all QNX, but it was only reported for v6.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="ld -Bshareable -x"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SCO_SV-3.2*)
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_CFLAGS="-fPIC -melf"
-               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
-           ], [
-               SHLIB_CFLAGS="-Kpic -belf"
-               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
-           ])
-           SHLIB_LD="ld -G"
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-       SunOS-5.[[0-6]])
-           # Careful to not let 5.10+ fall into this case
-
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ], [
-               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           ])
-           ;;
-       SunOS-5*)
-           # Note: If _REENTRANT isn't defined, then Solaris
-           # won't define thread-safe library routines.
-
-           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
-           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
-               [Do we really want to follow the standard? Yes we do!])
-
-           SHLIB_CFLAGS="-KPIC"
-
-           # Check to enable 64-bit flags for compiler/linker
-           AS_IF([test "$do64bit" = yes], [
-               arch=`isainfo`
-               AS_IF([test "$arch" = "sparcv9 sparc"], [
-                   AS_IF([test "$GCC" = yes], [
-                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
-                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
-                       ], [
-                           do64bit_ok=yes
-                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
-                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
-                           SHLIB_CFLAGS="-fPIC"
-                       ])
-                   ], [
-                       do64bit_ok=yes
-                       AS_IF([test "$do64bitVIS" = yes], [
-                           CFLAGS="$CFLAGS -xarch=v9a"
-                           LDFLAGS_ARCH="-xarch=v9a"
-                       ], [
-                           CFLAGS="$CFLAGS -xarch=v9"
-                           LDFLAGS_ARCH="-xarch=v9"
-                       ])
-                       # Solaris 64 uses this as well
-                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
-                   ])
-               ], [AS_IF([test "$arch" = "amd64 i386"], [
-                   AS_IF([test "$GCC" = yes], [
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               do64bit_ok=yes
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
-                       esac
-                   ], [
-                       do64bit_ok=yes
-                       case $system in
-                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
-                               CFLAGS="$CFLAGS -m64"
-                               LDFLAGS="$LDFLAGS -m64";;
-                           *)
-                               CFLAGS="$CFLAGS -xarch=amd64"
-                               LDFLAGS="$LDFLAGS -xarch=amd64";;
-                       esac
-                   ])
-               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
-           ])
-
-           SHLIB_SUFFIX=".so"
-           AS_IF([test "$GCC" = yes], [
-               SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-               AS_IF([test "$do64bit_ok" = yes], [
-                   AS_IF([test "$arch" = "sparcv9 sparc"], [
-                       # We need to specify -static-libgcc or we need to
-                       # add the path to the sparv9 libgcc.
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
-                       # for finding sparcv9 libgcc, get the regular libgcc
-                       # path, remove so name and append 'sparcv9'
-                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
-                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
-                   ], [AS_IF([test "$arch" = "amd64 i386"], [
-                       # JH: static-libgcc is necessary for core Tcl, but may
-                       # not be necessary for extensions.
-                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
-                   ])])
-               ])
-           ], [
-               case $system in
-                   SunOS-5.[[1-9]][[0-9]]*)
-                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
-                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
-                   *)
-                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
-               esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
-           ])
-           ;;
-       UNIX_SV* | UnixWare-5*)
-           SHLIB_CFLAGS="-KPIC"
-           SHLIB_LD='${CC} -G'
-           SHLIB_LD_LIBS=""
-           SHLIB_SUFFIX=".so"
-           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
-           # that don't grok the -Bexport option.  Test that it does.
-           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
-               hold_ldflags=$LDFLAGS
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
-               LDFLAGS=$hold_ldflags])
-           AS_IF([test $tcl_cv_ld_Bexport = yes], [
-               LDFLAGS="$LDFLAGS -Wl,-Bexport"
-           ])
-           CC_SEARCH_FLAGS=""
-           LD_SEARCH_FLAGS=""
-           ;;
-    esac
-
-    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
-       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
-    ])
-
-dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
-dnl # until the end of configure, as configure's compile and link tests use
-dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
-dnl # preprocessing tests use only CPPFLAGS.
-    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
-
-    # Add in the arch flags late to ensure it wasn't removed.
-    # Not necessary in TEA, but this is aligned with core
-    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
-
-    # If we're running gcc, then change the C flags for compiling shared
-    # libraries to the right flags for gcc, instead of those for the
-    # standard manufacturer compiler.
-
-    AS_IF([test "$GCC" = yes], [
-       case $system in
-           AIX-*) ;;
-           BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
-           IRIX*) ;;
-           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
-           Darwin-*) ;;
-           SCO_SV-3.2*) ;;
-           windows) ;;
-           *) SHLIB_CFLAGS="-fPIC" ;;
-       esac])
-
-    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
-       AC_DEFINE(MODULE_SCOPE, [extern],
-           [No Compiler support for module scope symbols])
-    ])
-
-    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
-    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
-    # TEA specific: use PACKAGE_VERSION instead of VERSION
-    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
-
-    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
-       AC_CACHE_CHECK(for SEH support in compiler,
-           tcl_cv_seh,
-       AC_TRY_RUN([
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-
-           int main(int argc, char** argv) {
-               int a, b = 0;
-               __try {
-                   a = 666 / b;
-               }
-               __except (EXCEPTION_EXECUTE_HANDLER) {
-                   return 0;
-               }
-               return 1;
-           }
-       ],
-           tcl_cv_seh=yes,
-           tcl_cv_seh=no,
-           tcl_cv_seh=no)
-       )
-       if test "$tcl_cv_seh" = "no" ; then
-           AC_DEFINE(HAVE_NO_SEH, 1,
-                   [Defined when mingw does not support SEH])
-       fi
-
-       #
-       # Check to see if the excpt.h include file provided contains the
-       # definition for EXCEPTION_DISPOSITION; if not, which is the case
-       # with Cygwin's version as of 2002-04-10, define it to be int,
-       # sufficient for getting the current code to work.
-       #
-       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
-           tcl_cv_eh_disposition,
-           AC_TRY_COMPILE([
-#          define WIN32_LEAN_AND_MEAN
-#          include <windows.h>
-#          undef WIN32_LEAN_AND_MEAN
-           ],[
-               EXCEPTION_DISPOSITION x;
-           ],
-               tcl_cv_eh_disposition=yes,
-               tcl_cv_eh_disposition=no)
-       )
-       if test "$tcl_cv_eh_disposition" = "no" ; then
-       AC_DEFINE(EXCEPTION_DISPOSITION, int,
-               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
-       fi
-
-       # Check to see if winnt.h defines CHAR, SHORT, and LONG
-       # even if VOID has already been #defined. The win32api
-       # used by mingw and cygwin is known to do this.
-
-       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
-           tcl_cv_winnt_ignore_void,
-           AC_TRY_COMPILE([
-#define VOID void
-#define WIN32_LEAN_AND_MEAN
-#include <windows.h>
-#undef WIN32_LEAN_AND_MEAN
-           ], [
-               CHAR c;
-               SHORT s;
-               LONG l;
-           ],
-        tcl_cv_winnt_ignore_void=yes,
-        tcl_cv_winnt_ignore_void=no)
-       )
-       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
-           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
-                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
-       fi
-    fi
-
-       # See if the compiler supports casting to a union type.
-       # This is used to stop gcc from printing a compiler
-       # warning when initializing a union member.
-
-       AC_CACHE_CHECK(for cast to union support,
-           tcl_cv_cast_to_union,
-           AC_TRY_COMPILE([],
-           [
-                 union foo { int i; double d; };
-                 union foo f = (union foo) (int) 0;
-           ],
-           tcl_cv_cast_to_union=yes,
-           tcl_cv_cast_to_union=no)
-       )
-       if test "$tcl_cv_cast_to_union" = "yes"; then
-           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
-                   [Defined when compiler supports casting to union type.])
-       fi
-
-    AC_SUBST(CFLAGS_DEBUG)
-    AC_SUBST(CFLAGS_OPTIMIZE)
-    AC_SUBST(CFLAGS_WARNING)
-
-    AC_SUBST(STLIB_LD)
-    AC_SUBST(SHLIB_LD)
-
-    AC_SUBST(SHLIB_LD_LIBS)
-    AC_SUBST(SHLIB_CFLAGS)
-
-    AC_SUBST(LD_LIBRARY_PATH_VAR)
-
-    # These must be called after we do the basic CFLAGS checks and
-    # verify any possible 64-bit or similar switches are necessary
-    TEA_TCL_EARLY_FLAGS
-    TEA_TCL_64BIT_FLAGS
-])
-
-#--------------------------------------------------------------------
-# TEA_SERIAL_PORT
-#
-#      Determine which interface to use to talk to the serial port.
-#      Note that #include lines must begin in leftmost column for
-#      some compilers to recognize them as preprocessor directives,
-#      and some build environments have stdin not pointing at a
-#      pseudo-terminal (usually /dev/null instead.)
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines only one of the following vars:
-#              HAVE_SYS_MODEM_H
-#              USE_TERMIOS
-#              USE_TERMIO
-#              USE_SGTTY
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_SERIAL_PORT], [
-    AC_CHECK_HEADERS(sys/modem.h)
-    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
-    AC_TRY_RUN([
-#include <termios.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termio.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no ; then
-       AC_TRY_RUN([
-#include <termios.h>
-#include <errno.h>
-
-int main() {
-    struct termios t;
-    if (tcgetattr(0, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       cfsetospeed(&t, 0);
-       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <termio.h>
-#include <errno.h>
-
-int main() {
-    struct termio t;
-    if (ioctl(0, TCGETA, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
-       return 0;
-    }
-    return 1;
-    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
-    fi
-    if test $tcl_cv_api_serial = no; then
-       AC_TRY_RUN([
-#include <sgtty.h>
-#include <errno.h>
-
-int main() {
-    struct sgttyb t;
-    if (ioctl(0, TIOCGETP, &t) == 0
-       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
-       t.sg_ospeed = 0;
-       t.sg_flags |= ODDP | EVENP | RAW;
-       return 0;
-    }
-    return 1;
-}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
-    fi])
-    case $tcl_cv_api_serial in
-       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
-       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
-       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_PATH_X
-#
-#      Locate the X11 header files and the X11 library archive.  Try
-#      the ac_path_x macro first, but if it doesn't find the X stuff
-#      (e.g. because there's no xmkmf program) then check through
-#      a list of possible directories.  Under some conditions the
-#      autoconf macro will return an include directory that contains
-#      no include files, so double-check its result just to be safe.
-#
-#      This should be called after TEA_CONFIG_CFLAGS as setting the
-#      LIBS line can confuse some configure macro magic.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets the following vars:
-#              XINCLUDES
-#              XLIBSW
-#              PKG_LIBS (appends to)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_X], [
-    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
-       TEA_PATH_UNIX_X
-    fi
-])
-
-AC_DEFUN([TEA_PATH_UNIX_X], [
-    AC_PATH_X
-    not_really_there=""
-    if test "$no_x" = ""; then
-       if test "$x_includes" = ""; then
-           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
-       else
-           if test ! -r $x_includes/X11/Xlib.h; then
-               not_really_there="yes"
-           fi
-       fi
-    fi
-    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
-       AC_MSG_CHECKING([for X11 header files])
-       found_xincludes="no"
-       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
-       if test "$found_xincludes" = "no"; then
-           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
-           for i in $dirs ; do
-               if test -r $i/X11/Xlib.h; then
-                   AC_MSG_RESULT([$i])
-                   XINCLUDES=" -I$i"
-                   found_xincludes="yes"
-                   break
-               fi
-           done
-       fi
-    else
-       if test "$x_includes" != ""; then
-           XINCLUDES="-I$x_includes"
-           found_xincludes="yes"
-       fi
-    fi
-    if test "$found_xincludes" = "no"; then
-       AC_MSG_RESULT([couldn't find any!])
-    fi
-
-    if test "$no_x" = yes; then
-       AC_MSG_CHECKING([for X11 libraries])
-       XLIBSW=nope
-       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
-       for i in $dirs ; do
-           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
-               AC_MSG_RESULT([$i])
-               XLIBSW="-L$i -lX11"
-               x_libraries="$i"
-               break
-           fi
-       done
-    else
-       if test "$x_libraries" = ""; then
-           XLIBSW=-lX11
-       else
-           XLIBSW="-L$x_libraries -lX11"
-       fi
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
-    fi
-    if test "$XLIBSW" = nope ; then
-       AC_MSG_RESULT([could not find any!  Using -lX11.])
-       XLIBSW=-lX11
-    fi
-    # TEA specific:
-    if test x"${XLIBSW}" != x ; then
-       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BLOCKING_STYLE
-#
-#      The statements below check for systems where POSIX-style
-#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
-#      On these systems (mostly older ones), use the old BSD-style
-#      FIONBIO approach instead.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              HAVE_SYS_IOCTL_H
-#              HAVE_SYS_FILIO_H
-#              USE_FIONBIO
-#              O_NONBLOCK
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BLOCKING_STYLE], [
-    AC_CHECK_HEADERS(sys/ioctl.h)
-    AC_CHECK_HEADERS(sys/filio.h)
-    TEA_CONFIG_SYSTEM
-    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
-    case $system in
-       OSF*)
-           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
-           AC_MSG_RESULT([FIONBIO])
-           ;;
-       *)
-           AC_MSG_RESULT([O_NONBLOCK])
-           ;;
-    esac
-])
-
-#--------------------------------------------------------------------
-# TEA_TIME_HANDLER
-#
-#      Checks how the system deals with time.h, what time structures
-#      are used on the system, and what fields the structures have.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines some of the following vars:
-#              USE_DELTA_FOR_TZ
-#              HAVE_TM_GMTOFF
-#              HAVE_TM_TZADJ
-#              HAVE_TIMEZONE_VAR
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TIME_HANDLER], [
-    AC_CHECK_HEADERS(sys/time.h)
-    AC_HEADER_TIME
-    AC_STRUCT_TIMEZONE
-
-    AC_CHECK_FUNCS(gmtime_r localtime_r)
-
-    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
-           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
-    if test $tcl_cv_member_tm_tzadj = yes ; then
-       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
-    fi
-
-    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
-           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
-    if test $tcl_cv_member_tm_gmtoff = yes ; then
-       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
-    fi
-
-    #
-    # Its important to include time.h in this check, as some systems
-    # (like convex) have timezone functions, etc.
-    #
-    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
-       AC_TRY_COMPILE([#include <time.h>],
-           [extern long timezone;
-           timezone += 1;
-           exit (0);],
-           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
-    if test $tcl_cv_timezone_long = yes ; then
-       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-    else
-       #
-       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
-       #
-       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
-           AC_TRY_COMPILE([#include <time.h>],
-               [extern time_t timezone;
-               timezone += 1;
-               exit (0);],
-               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
-       if test $tcl_cv_timezone_time = yes ; then
-           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_BUGGY_STRTOD
-#
-#      Under Solaris 2.4, strtod returns the wrong value for the
-#      terminating character under some conditions.  Check for this
-#      and if the problem exists use a substitute procedure
-#      "fixstrtod" (provided by Tcl) that corrects the error.
-#      Also, on Compaq's Tru64 Unix 5.0,
-#      strtod(" ") returns 0.0 instead of a failure to convert.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Might defines some of the following vars:
-#              strtod (=fixstrtod)
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_BUGGY_STRTOD], [
-    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
-    if test "$tcl_strtod" = 1; then
-       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
-           AC_TRY_RUN([
-               extern double strtod();
-               int main() {
-                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
-                   char *term;
-                   double value;
-                   value = strtod(infString, &term);
-                   if ((term != infString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(nanString, &term);
-                   if ((term != nanString) && (term[-1] == 0)) {
-                       exit(1);
-                   }
-                   value = strtod(spaceString, &term);
-                   if (term == (spaceString+1)) {
-                       exit(1);
-                   }
-                   exit(0);
-               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
-                   tcl_cv_strtod_buggy=buggy)])
-       if test "$tcl_cv_strtod_buggy" = buggy; then
-           AC_LIBOBJ([fixstrtod])
-           USE_COMPAT=1
-           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
-       fi
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_EARLY_FLAGS
-#
-#      Check for what flags are needed to be passed so the correct OS
-#      features are available.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              _ISOC99_SOURCE
-#              _LARGEFILE64_SOURCE
-#              _LARGEFILE_SOURCE64
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_EARLY_FLAG],[
-    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
-       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
-           AC_TRY_COMPILE([[#define ]$1[ 1
-]$2], $3,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
-               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
-    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
-       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
-       tcl_flags="$tcl_flags $1"
-    fi
-])
-
-AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
-    AC_MSG_CHECKING([for required early compiler flags])
-    tcl_flags=""
-    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
-       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
-       [struct stat64 buf; int i = stat64("/", &buf);])
-    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
-       [char *p = (char *)open64;])
-    if test "x${tcl_flags}" = "x" ; then
-       AC_MSG_RESULT([none])
-    else
-       AC_MSG_RESULT([${tcl_flags}])
-    fi
-])
-
-#--------------------------------------------------------------------
-# TEA_TCL_64BIT_FLAGS
-#
-#      Check for what is defined in the way of 64-bit features.
-#
-# Arguments:
-#      None
-#
-# Results:
-#
-#      Might define the following vars:
-#              TCL_WIDE_INT_IS_LONG
-#              TCL_WIDE_INT_TYPE
-#              HAVE_STRUCT_DIRENT64
-#              HAVE_STRUCT_STAT64
-#              HAVE_TYPE_OFF64_T
-#--------------------------------------------------------------------
-
-AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
-    AC_MSG_CHECKING([for 64-bit integer type])
-    AC_CACHE_VAL(tcl_cv_type_64bit,[
-       tcl_cv_type_64bit=none
-       # See if the compiler knows natively about __int64
-       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
-           tcl_type_64bit=__int64, tcl_type_64bit="long long")
-       # See if we should use long anyway  Note that we substitute in the
-       # type that is our current guess for a 64-bit type inside this check
-       # program, so it should be modified only carefully...
-        AC_TRY_COMPILE(,[switch (0) {
-            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
-        }],tcl_cv_type_64bit=${tcl_type_64bit})])
-    if test "${tcl_cv_type_64bit}" = none ; then
-       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Are wide integers to be implemented with C 'long's?])
-       AC_MSG_RESULT([using long])
-    elif test "${tcl_cv_type_64bit}" = "__int64" \
-               -a "${TEA_PLATFORM}" = "windows" ; then
-       # TEA specific: We actually want to use the default tcl.h checks in
-       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
-       AC_MSG_RESULT([using Tcl header defaults])
-    else
-       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
-           [What type should be used to define wide integers?])
-       AC_MSG_RESULT([${tcl_cv_type_64bit}])
-
-       # Now check for auxiliary declarations
-       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
-           AC_TRY_COMPILE([#include <sys/types.h>
-#include <dirent.h>],[struct dirent64 p;],
-               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
-       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
-       fi
-
-       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
-           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
-],
-               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
-       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
-           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
-       fi
-
-       AC_CHECK_FUNCS(open64 lseek64)
-       AC_MSG_CHECKING([for off64_t])
-       AC_CACHE_VAL(tcl_cv_type_off64_t,[
-           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
-],
-               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
-       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
-       dnl functions lseek64 and open64 are defined.
-       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
-               test "x${ac_cv_func_lseek64}" = "xyes" && \
-               test "x${ac_cv_func_open64}" = "xyes" ; then
-           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
-           AC_MSG_RESULT([yes])
-       else
-           AC_MSG_RESULT([no])
-       fi
-    fi
-])
-
-##
-## Here ends the standard Tcl configuration bits and starts the
-## TEA specific functions
-##
-
-#------------------------------------------------------------------------
-# TEA_INIT --
-#
-#      Init various Tcl Extension Architecture (TEA) variables.
-#      This should be the first called TEA_* macro.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              CYGPATH
-#              EXEEXT
-#      Defines only:
-#              TEA_VERSION
-#              TEA_INITED
-#              TEA_PLATFORM (windows or unix)
-#
-# "cygpath" is used on windows to generate native path names for include
-# files. These variables should only be used with the compiler and linker
-# since they generate native path names.
-#
-# EXEEXT
-#      Select the executable extension based on the host type.  This
-#      is a lightweight replacement for AC_EXEEXT that doesn't require
-#      a compiler.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INIT], [
-    TEA_VERSION="3.13"
-
-    AC_MSG_CHECKING([TEA configuration])
-    if test x"${PACKAGE_NAME}" = x ; then
-       AC_MSG_ERROR([
-The PACKAGE_NAME variable must be defined by your TEA configure.ac])
-    fi
-    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
-
-    # If the user did not set CFLAGS, set it now to keep macros
-    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
-    if test "${CFLAGS+set}" != "set" ; then
-       CFLAGS=""
-    fi
-
-    case "`uname -s`" in
-       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
-           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
-           EXEEXT=".exe"
-           TEA_PLATFORM="windows"
-           ;;
-       *CYGWIN_*)
-           EXEEXT=".exe"
-           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
-           ;;
-       *)
-           CYGPATH=echo
-           # Maybe we are cross-compiling....
-           case ${host_alias} in
-               *mingw32*)
-               EXEEXT=".exe"
-               TEA_PLATFORM="windows"
-               ;;
-           *)
-               EXEEXT=""
-               TEA_PLATFORM="unix"
-               ;;
-           esac
-           ;;
-    esac
-
-    # Check if exec_prefix is set. If not use fall back to prefix.
-    # Note when adjusted, so that TEA_PREFIX can correct for this.
-    # This is needed for recursive configures, since autoconf propagates
-    # $prefix, but not $exec_prefix (doh!).
-    if test x$exec_prefix = xNONE ; then
-       exec_prefix_default=yes
-       exec_prefix=$prefix
-    fi
-
-    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
-
-    AC_SUBST(EXEEXT)
-    AC_SUBST(CYGPATH)
-
-    # This package name must be replaced statically for AC_SUBST to work
-    AC_SUBST(PKG_LIB_FILE)
-    # Substitute STUB_LIB_FILE in case package creates a stub library too.
-    AC_SUBST(PKG_STUB_LIB_FILE)
-
-    # We AC_SUBST these here to ensure they are subst'ed,
-    # in case the user doesn't call TEA_ADD_...
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-    AC_SUBST(PKG_TCL_SOURCES)
-    AC_SUBST(PKG_HEADERS)
-    AC_SUBST(PKG_INCLUDES)
-    AC_SUBST(PKG_LIBS)
-    AC_SUBST(PKG_CFLAGS)
-
-    # Configure the installer.
-    TEA_INSTALLER
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_SOURCES
-#              PKG_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       case $i in
-           [\$]*)
-               # allow $-var names
-               PKG_SOURCES="$PKG_SOURCES $i"
-               PKG_OBJECTS="$PKG_OBJECTS $i"
-               ;;
-           *)
-               # check for existence - allows for generic/win/unix VPATH
-               # To add more dirs here (like 'src'), you have to update VPATH
-               # in Makefile.in as well
-               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-                   -a ! -f "${srcdir}/macosx/$i" \
-                   ; then
-                   AC_MSG_ERROR([could not find source file '$i'])
-               fi
-               PKG_SOURCES="$PKG_SOURCES $i"
-               # this assumes it is in a VPATH dir
-               i=`basename $i`
-               # handle user calling this before or after TEA_SETUP_COMPILER
-               if test x"${OBJEXT}" != x ; then
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-               else
-                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-               fi
-               PKG_OBJECTS="$PKG_OBJECTS $j"
-               ;;
-       esac
-    done
-    AC_SUBST(PKG_SOURCES)
-    AC_SUBST(PKG_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_STUB_SOURCES --
-#
-#      Specify one or more source files.  Users should check for
-#      the right platform before adding to their list.
-#      It is not important to specify the directory, as long as it is
-#      in the generic, win or unix subdirectory of $(srcdir).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_STUB_SOURCES
-#              PKG_STUB_OBJECTS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_STUB_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence - allows for generic/win/unix VPATH
-       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
-           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
-           -a ! -f "${srcdir}/macosx/$i" \
-           ; then
-           AC_MSG_ERROR([could not find stub source file '$i'])
-       fi
-       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
-       # this assumes it is in a VPATH dir
-       i=`basename $i`
-       # handle user calling this before or after TEA_SETUP_COMPILER
-       if test x"${OBJEXT}" != x ; then
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
-       else
-           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
-       fi
-       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
-    done
-    AC_SUBST(PKG_STUB_SOURCES)
-    AC_SUBST(PKG_STUB_OBJECTS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_TCL_SOURCES --
-#
-#      Specify one or more Tcl source files.  These should be platform
-#      independent runtime files.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_TCL_SOURCES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_TCL_SOURCES], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
-       fi
-       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
-    done
-    AC_SUBST(PKG_TCL_SOURCES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_HEADERS --
-#
-#      Specify one or more source headers.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_HEADERS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_HEADERS], [
-    vars="$@"
-    for i in $vars; do
-       # check for existence, be strict because it is installed
-       if test ! -f "${srcdir}/$i" ; then
-           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
-       fi
-       PKG_HEADERS="$PKG_HEADERS $i"
-    done
-    AC_SUBST(PKG_HEADERS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_INCLUDES --
-#
-#      Specify one or more include dirs.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_INCLUDES
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_INCLUDES], [
-    vars="$@"
-    for i in $vars; do
-       PKG_INCLUDES="$PKG_INCLUDES $i"
-    done
-    AC_SUBST(PKG_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_LIBS --
-#
-#      Specify one or more libraries.  Users should check for
-#      the right platform before adding to their list.  For Windows,
-#      libraries provided in "foo.lib" format will be converted to
-#      "-lfoo" when using GCC (mingw).
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_LIBS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_LIBS], [
-    vars="$@"
-    for i in $vars; do
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
-           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.lib[$]/-l\1/i'`
-       fi
-       PKG_LIBS="$PKG_LIBS $i"
-    done
-    AC_SUBST(PKG_LIBS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CFLAGS --
-#
-#      Specify one or more CFLAGS.  Users should check for
-#      the right platform before adding to their list.
-#
-# Arguments:
-#      one or more file names
-#
-# Results:
-#
-#      Defines and substs the following vars:
-#              PKG_CFLAGS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CFLAGS], [
-    PKG_CFLAGS="$PKG_CFLAGS $@"
-    AC_SUBST(PKG_CFLAGS)
-])
-
-#------------------------------------------------------------------------
-# TEA_ADD_CLEANFILES --
-#
-#      Specify one or more CLEANFILES.
-#
-# Arguments:
-#      one or more file names to clean target
-#
-# Results:
-#
-#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ADD_CLEANFILES], [
-    CLEANFILES="$CLEANFILES $@"
-])
-
-#------------------------------------------------------------------------
-# TEA_PREFIX --
-#
-#      Handle the --prefix=... option by defaulting to what Tcl gave
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      If --prefix or --exec-prefix was not specified, $prefix and
-#      $exec_prefix will be set to the values given to Tcl when it was
-#      configured.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_PREFIX], [
-    if test "${prefix}" = "NONE"; then
-       prefix_default=yes
-       if test x"${TCL_PREFIX}" != x; then
-           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
-           prefix=${TCL_PREFIX}
-       else
-           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
-           prefix=/usr/local
-       fi
-    fi
-    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
-       -o x"${exec_prefix_default}" = x"yes" ; then
-       if test x"${TCL_EXEC_PREFIX}" != x; then
-           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
-           exec_prefix=${TCL_EXEC_PREFIX}
-       else
-           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
-           exec_prefix=$prefix
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER_CC --
-#
-#      Do compiler checks the way we want.  This is just a replacement
-#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER_CC], [
-    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
-    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
-
-    AC_PROG_CC
-    AC_PROG_CPP
-
-    #--------------------------------------------------------------------
-    # Checks to see if the make program sets the $MAKE variable.
-    #--------------------------------------------------------------------
-
-    AC_PROG_MAKE_SET
-
-    #--------------------------------------------------------------------
-    # Find ranlib
-    #--------------------------------------------------------------------
-
-    AC_CHECK_TOOL(RANLIB, ranlib)
-
-    #--------------------------------------------------------------------
-    # Determines the correct binary file extension (.o, .obj, .exe etc.)
-    #--------------------------------------------------------------------
-
-    AC_OBJEXT
-    AC_EXEEXT
-])
-
-#------------------------------------------------------------------------
-# TEA_SETUP_COMPILER --
-#
-#      Do compiler checks that use the compiler.  This must go after
-#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Sets up CC var and other standard bits we need to make executables.
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_SETUP_COMPILER], [
-    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
-    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
-
-    #------------------------------------------------------------------------
-    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
-    # It makes compiling go faster.  (This is only a performance feature.)
-    #------------------------------------------------------------------------
-
-    if test -z "$no_pipe" -a -n "$GCC"; then
-       AC_CACHE_CHECK([if the compiler understands -pipe],
-           tcl_cv_cc_pipe, [
-           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
-           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
-           CFLAGS=$hold_cflags])
-       if test $tcl_cv_cc_pipe = yes; then
-           CFLAGS="$CFLAGS -pipe"
-       fi
-    fi
-
-    #--------------------------------------------------------------------
-    # Common compiler flag setup
-    #--------------------------------------------------------------------
-
-    AC_C_BIGENDIAN
-])
-
-#------------------------------------------------------------------------
-# TEA_MAKE_LIB --
-#
-#      Generate a line that can be used to build a shared/unshared library
-#      in a platform independent manner.
-#
-# Arguments:
-#      none
-#
-#      Requires:
-#
-# Results:
-#
-#      Defines the following vars:
-#      CFLAGS -        Done late here to note disturb other AC macros
-#       MAKE_LIB -      Command to execute to build the Tcl library;
-#                       differs depending on whether or not Tcl is being
-#                       compiled as a shared library.
-#      MAKE_SHARED_LIB Makefile rule for building a shared library
-#      MAKE_STATIC_LIB Makefile rule for building a static library
-#      MAKE_STUB_LIB   Makefile rule for building a stub library
-#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
-#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_MAKE_LIB], [
-    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
-       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
-       AC_EGREP_CPP([manifest needed], [
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-print("manifest needed")
-#endif
-       ], [
-       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
-       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
-       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
-       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
-       TEA_ADD_CLEANFILES([*.manifest])
-       ])
-       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
-    else
-       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
-       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
-    fi
-
-    if test "${SHARED_BUILD}" = "1" ; then
-       MAKE_LIB="${MAKE_SHARED_LIB} "
-    else
-       MAKE_LIB="${MAKE_STATIC_LIB} "
-    fi
-
-    #--------------------------------------------------------------------
-    # Shared libraries and static libraries have different names.
-    # Use the double eval to make sure any variables in the suffix is
-    # substituted. (@@@ Might not be necessary anymore)
-    #--------------------------------------------------------------------
-
-    if test "${TEA_PLATFORM}" = "windows" ; then
-       if test "${SHARED_BUILD}" = "1" ; then
-           # We force the unresolved linking of symbols that are really in
-           # the private libraries of Tcl and Tk.
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
-           fi
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
-           if test "$GCC" = "yes"; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
-           fi
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-       else
-           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-           if test "$GCC" = "yes"; then
-               PKG_LIB_FILE=lib${PKG_LIB_FILE}
-           fi
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-       if test "$GCC" = "yes"; then
-           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
-       fi
-       # These aren't needed on Windows (either MSVC or gcc)
-       RANLIB=:
-       RANLIB_STUB=:
-    else
-       RANLIB_STUB="${RANLIB}"
-       if test "${SHARED_BUILD}" = "1" ; then
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
-           if test x"${TK_BIN_DIR}" != x ; then
-               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
-           fi
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
-           RANLIB=:
-       else
-           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
-       fi
-       # Some packages build their own stubs libraries
-       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
-    fi
-
-    # These are escaped so that only CFLAGS is picked up at configure time.
-    # The other values will be substituted at make time.
-    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
-    if test "${SHARED_BUILD}" = "1" ; then
-       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
-    fi
-
-    AC_SUBST(MAKE_LIB)
-    AC_SUBST(MAKE_SHARED_LIB)
-    AC_SUBST(MAKE_STATIC_LIB)
-    AC_SUBST(MAKE_STUB_LIB)
-    AC_SUBST(RANLIB_STUB)
-    AC_SUBST(VC_MANIFEST_EMBED_DLL)
-    AC_SUBST(VC_MANIFEST_EMBED_EXE)
-])
-
-#------------------------------------------------------------------------
-# TEA_LIB_SPEC --
-#
-#      Compute the name of an existing object library located in libdir
-#      from the given base name and produce the appropriate linker flags.
-#
-# Arguments:
-#      basename        The base name of the library without version
-#                      numbers, extensions, or "lib" prefixes.
-#      extra_dir       Extra directory in which to search for the
-#                      library.  This location is used first, then
-#                      $prefix/$exec-prefix, then some defaults.
-#
-# Requires:
-#      TEA_INIT and TEA_PREFIX must be called first.
-#
-# Results:
-#
-#      Defines the following vars:
-#              ${basename}_LIB_NAME    The computed library name.
-#              ${basename}_LIB_SPEC    The computed linker flags.
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LIB_SPEC], [
-    AC_MSG_CHECKING([for $1 library])
-
-    # Look in exec-prefix for the library (defined by TEA_PREFIX).
-
-    tea_lib_name_dir="${exec_prefix}/lib"
-
-    # Or in a user-specified location.
-
-    if test x"$2" != x ; then
-       tea_extra_lib_dir=$2
-    else
-       tea_extra_lib_dir=NONE
-    fi
-
-    for i in \
-           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
-           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
-           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
-       if test -f "$i" ; then
-           tea_lib_name_dir=`dirname $i`
-           $1_LIB_NAME=`basename $i`
-           $1_LIB_PATH_NAME=$i
-           break
-       fi
-    done
-
-    if test "${TEA_PLATFORM}" = "windows"; then
-       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
-    else
-       # Strip off the leading "lib" and trailing ".a" or ".so"
-
-       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
-       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
-    fi
-
-    if test "x${$1_LIB_NAME}" = x ; then
-       AC_MSG_ERROR([not found])
-    else
-       AC_MSG_RESULT([${$1_LIB_SPEC}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TCL_HEADERS --
-#
-#      Locate the private Tcl include files
-#
-# Arguments:
-#
-#      Requires:
-#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
-#                              already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TCL_TOP_DIR_NATIVE
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
-    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
-    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
-    AC_MSG_CHECKING([for Tcl private include files])
-
-    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
-    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
-
-    # Check to see if tcl<Plat>Port.h isn't already with the public headers
-    # Don't look for tclInt.h because that resides with tcl.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
-       else
-           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TCL_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
-       if test "`uname -s`" = "Darwin"; then
-            # If Tcl was built as a framework, attempt to use
-            # the framework's Headers and PrivateHeaders directories
-            case ${TCL_DEFS} in
-               *TCL_FRAMEWORK*)
-                   if test -d "${TCL_BIN_DIR}/Headers" -a \
-                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
-                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
-                   else
-                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                   fi
-                   ;;
-           esac
-           result="Using ${TCL_INCLUDES}"
-       else
-           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
-               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
-           fi
-           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TCL_TOP_DIR_NATIVE)
-
-    AC_SUBST(TCL_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TCL_HEADERS --
-#
-#      Locate the installed public Tcl header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tclinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TCL_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
-    AC_MSG_CHECKING([for Tcl public headers])
-
-    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tclh, [
-       # Use the value from --with-tclinclude, if it was given
-
-       if test x"${with_tclinclude}" != x ; then
-           if test -f "${with_tclinclude}/tcl.h" ; then
-               ac_cv_c_tclh=${with_tclinclude}
-           else
-               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tcl was built as a framework, attempt to use
-               # the framework's Headers directory
-               case ${TCL_DEFS} in
-                   *TCL_FRAMEWORK*)
-                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tcl is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TCL_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TCL_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tcl.h" ; then
-                   ac_cv_c_tclh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tclh}" = x ; then
-       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tclh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
-
-    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TCL_INCLUDES)
-])
-
-#------------------------------------------------------------------------
-# TEA_PRIVATE_TK_HEADERS --
-#
-#      Locate the private Tk include files
-#
-# Arguments:
-#
-#      Requires:
-#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
-#                               already been called.
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
-    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
-    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
-    AC_MSG_CHECKING([for Tk private include files])
-
-    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
-    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
-
-    # Check to see if tk<Plat>Port.h isn't already with the public headers
-    # Don't look for tkInt.h because that resides with tk.h in the core
-    # sources, but the <plat>Port headers are in a different directory
-    if test "${TEA_PLATFORM}" = "windows" -a \
-       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
-       result="private headers found with public headers"
-    elif test "${TEA_PLATFORM}" = "unix" -a \
-       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
-       result="private headers found with public headers"
-    else
-       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
-       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
-       if test "${TEA_PLATFORM}" = "windows"; then
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
-       else
-           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
-       fi
-       # Overwrite the previous TK_INCLUDES as this should capture both
-       # public and private headers in the same set.
-       # We want to ensure these are substituted so as not to require
-       # any *_NATIVE vars be defined in the Makefile
-       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
-       # Detect and add ttk subdir
-       if test -d "${TK_SRC_DIR}/generic/ttk"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
-       fi
-       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
-          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
-       fi
-       if test "`uname -s`" = "Darwin"; then
-           # If Tk was built as a framework, attempt to use
-           # the framework's Headers and PrivateHeaders directories
-           case ${TK_DEFS} in
-               *TK_FRAMEWORK*)
-                       if test -d "${TK_BIN_DIR}/Headers" -a \
-                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
-                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
-                       else
-                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
-                       fi
-                       ;;
-           esac
-           result="Using ${TK_INCLUDES}"
-       else
-           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
-              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
-           fi
-           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
-       fi
-    fi
-
-    AC_SUBST(TK_TOP_DIR_NATIVE)
-    AC_SUBST(TK_XLIB_DIR_NATIVE)
-
-    AC_SUBST(TK_INCLUDES)
-    AC_MSG_RESULT([${result}])
-])
-
-#------------------------------------------------------------------------
-# TEA_PUBLIC_TK_HEADERS --
-#
-#      Locate the installed public Tk header files
-#
-# Arguments:
-#      None.
-#
-# Requires:
-#      CYGPATH must be set
-#
-# Results:
-#
-#      Adds a --with-tkinclude switch to configure.
-#      Result is cached.
-#
-#      Substitutes the following vars:
-#              TK_INCLUDES
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
-    AC_MSG_CHECKING([for Tk public headers])
-
-    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
-
-    AC_CACHE_VAL(ac_cv_c_tkh, [
-       # Use the value from --with-tkinclude, if it was given
-
-       if test x"${with_tkinclude}" != x ; then
-           if test -f "${with_tkinclude}/tk.h" ; then
-               ac_cv_c_tkh=${with_tkinclude}
-           else
-               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
-           fi
-       else
-           list=""
-           if test "`uname -s`" = "Darwin"; then
-               # If Tk was built as a framework, attempt to use
-               # the framework's Headers directory.
-               case ${TK_DEFS} in
-                   *TK_FRAMEWORK*)
-                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
-                       ;;
-               esac
-           fi
-
-           # Look in the source dir only if Tk is not installed,
-           # and in that situation, look there before installed locations.
-           if test -f "${TK_BIN_DIR}/Makefile" ; then
-               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
-           fi
-
-           # Check order: pkg --prefix location, Tk's --prefix location,
-           # relative to directory of tkConfig.sh, Tcl's --prefix location,
-           # relative to directory of tclConfig.sh.
-
-           eval "temp_includedir=${includedir}"
-           list="$list \
-               `ls -d ${temp_includedir}        2>/dev/null` \
-               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
-               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
-               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
-               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
-           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
-               list="$list /usr/local/include /usr/include"
-               if test x"${TK_INCLUDE_SPEC}" != x ; then
-                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
-                   list="$list `ls -d ${d} 2>/dev/null`"
-               fi
-           fi
-           for i in $list ; do
-               if test -f "$i/tk.h" ; then
-                   ac_cv_c_tkh=$i
-                   break
-               fi
-           done
-       fi
-    ])
-
-    # Print a message based on how we determined the include path
-
-    if test x"${ac_cv_c_tkh}" = x ; then
-       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
-    else
-       AC_MSG_RESULT([${ac_cv_c_tkh}])
-    fi
-
-    # Convert to a native path and substitute into the output files.
-
-    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
-
-    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-
-    AC_SUBST(TK_INCLUDES)
-
-    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
-       # On Windows and Aqua, we need the X compat headers
-       AC_MSG_CHECKING([for X11 header files])
-       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
-           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
-           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
-           AC_SUBST(TK_XINCLUDES)
-       fi
-       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_PATH_CONFIG --
-#
-#      Locate the ${1}Config.sh file and perform a sanity check on
-#      the ${1} compile flags.  These are used by packages like
-#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
-#
-# Arguments:
-#      none
-#
-# Results:
-#
-#      Adds the following arguments to configure:
-#              --with-$1=...
-#
-#      Defines the following vars:
-#              $1_BIN_DIR      Full path to the directory containing
-#                              the $1Config.sh file
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_PATH_CONFIG], [
-    #
-    # Ok, lets find the $1 configuration
-    # First, look for one uninstalled.
-    # the alternative search directory is invoked by --with-$1
-    #
-
-    if test x"${no_$1}" = x ; then
-       # we reset no_$1 in case something fails here
-       no_$1=true
-       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
-       AC_MSG_CHECKING([for $1 configuration])
-       AC_CACHE_VAL(ac_cv_c_$1config,[
-
-           # First check to see if --with-$1 was specified.
-           if test x"${with_$1config}" != x ; then
-               case ${with_$1config} in
-                   */$1Config.sh )
-                       if test -f ${with_$1config}; then
-                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
-                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
-                       fi;;
-               esac
-               if test -f "${with_$1config}/$1Config.sh" ; then
-                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
-               else
-                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
-               fi
-           fi
-
-           # then check for a private $1 installation
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in \
-                       ../$1 \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../$1 \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ../../../$1 \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ${srcdir}/../$1 \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
-                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-                   if test -f "$i/unix/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
-                       break
-                   fi
-               done
-           fi
-
-           # check in a few common install locations
-           if test x"${ac_cv_c_$1config}" = x ; then
-               for i in `ls -d ${libdir} 2>/dev/null` \
-                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
-                       `ls -d ${prefix}/lib 2>/dev/null` \
-                       `ls -d /usr/local/lib 2>/dev/null` \
-                       `ls -d /usr/contrib/lib 2>/dev/null` \
-                       `ls -d /usr/pkg/lib 2>/dev/null` \
-                       `ls -d /usr/lib 2>/dev/null` \
-                       `ls -d /usr/lib64 2>/dev/null` \
-                       ; do
-                   if test -f "$i/$1Config.sh" ; then
-                       ac_cv_c_$1config=`(cd $i; pwd)`
-                       break
-                   fi
-               done
-           fi
-       ])
-
-       if test x"${ac_cv_c_$1config}" = x ; then
-           $1_BIN_DIR="# no $1 configs found"
-           AC_MSG_WARN([Cannot find $1 configuration definitions])
-           exit 0
-       else
-           no_$1=
-           $1_BIN_DIR=${ac_cv_c_$1config}
-           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
-       fi
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG --
-#
-#      Load the $1Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1_BIN_DIR
-#
-# Results:
-#
-#      Substitutes the following vars:
-#              $1_SRC_DIR
-#              $1_LIB_FILE
-#              $1_LIB_SPEC
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_LOAD_CONFIG], [
-    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
-
-    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
-        AC_MSG_RESULT([loading])
-       . "${$1_BIN_DIR}/$1Config.sh"
-    else
-        AC_MSG_RESULT([file not found])
-    fi
-
-    #
-    # If the $1_BIN_DIR is the build directory (not the install directory),
-    # then set the common variable name to the value of the build variables.
-    # For example, the variable $1_LIB_SPEC will be set to the value
-    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
-    # instead of $1_BUILD_LIB_SPEC since it will work with both an
-    # installed and uninstalled version of Tcl.
-    #
-
-    if test -f "${$1_BIN_DIR}/Makefile" ; then
-       AC_MSG_WARN([Found Makefile - using build library specs for $1])
-        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
-        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
-        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
-        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
-        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
-    fi
-
-    AC_SUBST($1_VERSION)
-    AC_SUBST($1_BIN_DIR)
-    AC_SUBST($1_SRC_DIR)
-
-    AC_SUBST($1_LIB_FILE)
-    AC_SUBST($1_LIB_SPEC)
-
-    AC_SUBST($1_STUB_LIB_FILE)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    # Allow the caller to prevent this auto-check by specifying any 2nd arg
-    AS_IF([test "x$2" = x], [
-       # Check both upper and lower-case variants
-       # If a dev wanted non-stubs libs, this function could take an option
-       # to not use _STUB in the paths below
-       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
-           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
-           [TEA_LOAD_CONFIG_LIB($1_STUB)])
-    ])
-])
-
-#------------------------------------------------------------------------
-# TEA_LOAD_CONFIG_LIB --
-#
-#      Helper function to load correct library from another extension's
-#      ${PACKAGE}Config.sh.
-#
-# Results:
-#      Adds to LIBS the appropriate extension library
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
-    AC_MSG_CHECKING([For $1 library for LIBS])
-    # This simplifies the use of stub libraries by automatically adding
-    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
-    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
-    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
-    if test "x${$1_LIB_SPEC}" != "x" ; then
-       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
-           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
-           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
-       else
-           TEA_ADD_LIBS([${$1_LIB_SPEC}])
-           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
-       fi
-    else
-       AC_MSG_RESULT([file not found])
-    fi
-])
-
-#------------------------------------------------------------------------
-# TEA_EXPORT_CONFIG --
-#
-#      Define the data to insert into the ${PACKAGE}Config.sh file
-#
-# Arguments:
-#
-#      Requires the following vars to be set:
-#              $1
-#
-# Results:
-#      Substitutes the following vars:
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_EXPORT_CONFIG], [
-    #--------------------------------------------------------------------
-    # These are for $1Config.sh
-    #--------------------------------------------------------------------
-
-    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
-    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
-    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
-       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}${DBGX}"
-    else
-       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`${DBGX}"
-    fi
-    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
-    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
-    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
-    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
-    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
-
-    AC_SUBST($1_BUILD_LIB_SPEC)
-    AC_SUBST($1_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
-    AC_SUBST($1_STUB_LIB_SPEC)
-    AC_SUBST($1_BUILD_STUB_LIB_PATH)
-    AC_SUBST($1_STUB_LIB_PATH)
-
-    AC_SUBST(MAJOR_VERSION)
-    AC_SUBST(MINOR_VERSION)
-    AC_SUBST(PATCHLEVEL)
-])
-
-
-#------------------------------------------------------------------------
-# TEA_INSTALLER --
-#
-#      Configure the installer.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              INSTALL
-#              INSTALL_DATA_DIR
-#              INSTALL_DATA
-#              INSTALL_PROGRAM
-#              INSTALL_SCRIPT
-#              INSTALL_LIBRARY
-#------------------------------------------------------------------------
-
-AC_DEFUN([TEA_INSTALLER], [
-    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
-    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
-    INSTALL_DATA='${INSTALL} -m 644'
-    INSTALL_PROGRAM='${INSTALL} -m 755'
-    INSTALL_SCRIPT='${INSTALL} -m 755'
-
-    TEA_CONFIG_SYSTEM
-    case $system in
-       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
-             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
-    esac
-
-    AC_SUBST(INSTALL)
-    AC_SUBST(INSTALL_DATA_DIR)
-    AC_SUBST(INSTALL_DATA)
-    AC_SUBST(INSTALL_PROGRAM)
-    AC_SUBST(INSTALL_SCRIPT)
-    AC_SUBST(INSTALL_LIBRARY)
-])
-
-###
-# Tip 430 - ZipFS Modifications
-###
-#------------------------------------------------------------------------
-# SC_ZIPFS_SUPPORT
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              TCL_ZIP_FILE
-#              TCL_ZIPFS_SUPPORT
-#              TCL_ZIPFS_FLAG
-#              ZIP_PROG
-#------------------------------------------------------------------------
-
-#------------------------------------------------------------------------
-# SC_PROG_ZIP
-#      Locate a zip encoder installed on the system path, or none.
-#
-# Arguments:
-#      none
-#
-# Results:
-#      Substitutes the following vars:
-#              ZIP_PROG
-#       ZIP_PROG_OPTIONS
-#       ZIP_PROG_VFSSEARCH
-#       ZIP_INSTALL_OBJS
-#------------------------------------------------------------------------
-AC_DEFUN([TEA_ZIPFS_SUPPORT], [
-    AC_MSG_CHECKING([for zipfs support])
-    ZIP_PROG=""
-    ZIP_PROG_OPTIONS=""
-    ZIP_PROG_VFSSEARCH=""
-    INSTALL_MSGS=""
-    # If our native tclsh processes the "install" command line option
-    # we can use it to mint zip files
-    AS_IF([$TCLSH_PROG install],[
-      ZIP_PROG=${TCLSH_PROG}
-      ZIP_PROG_OPTIONS="install mkzip"
-      ZIP_PROG_VFSSEARCH="."
-      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
-    ])
-    if test "x$ZIP_PROG" = "x" ; then
-        AC_CACHE_VAL(ac_cv_path_zip, [
-        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
-        for dir in $search_path ; do
-            for j in `ls -r $dir/zip 2> /dev/null` \
-                `ls -r $dir/zip 2> /dev/null` ; do
-            if test x"$ac_cv_path_zip" = x ; then
-                if test -f "$j" ; then
-                ac_cv_path_zip=$j
-                break
-                fi
-            fi
-            done
-        done
-        ])
-        if test -f "$ac_cv_path_zip" ; then
-            ZIP_PROG="$ac_cv_path_zip "
-            AC_MSG_RESULT([$ZIP_PROG])
-            ZIP_PROG_OPTIONS="-rq"
-            ZIP_PROG_VFSSEARCH="."
-            AC_MSG_RESULT([Found INFO Zip in environment])
-            # Use standard arguments for zip
-        fi
-    fi
-    if test "x$ZIP_PROG" = "x" ; then
-           # It is not an error if an installed version of Zip can't be located.
-        ZIP_PROG=""
-        ZIP_PROG_OPTIONS=""
-        ZIP_PROG_VFSSEARCH=""
-        TCL_ZIPFS_SUPPORT=0
-        TCL_ZIPFS_FLAG=
-    else
-        # ZIPFS Support
-       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
-       if test ${TCL_ZIP_FILE} = "" ; then
-          TCL_ZIPFS_SUPPORT=0
-          TCL_ZIPFS_FLAG=
-          INSTALL_LIBRARIES=install-libraries
-          INSTALL_MSGS=install-msgs
-       else
-           if test ${SHARED_BUILD} = 1 ; then
-              TCL_ZIPFS_SUPPORT=1
-              INSTALL_LIBRARIES=install-libraries-zipfs-shared
-           else
-              TCL_ZIPFS_SUPPORT=2
-              INSTALL_LIBRARIES=install-libraries-zipfs-static
-           fi
-          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
-       fi
-    fi
-
-    AC_SUBST(TCL_ZIP_FILE)
-    AC_SUBST(TCL_ZIPFS_SUPPORT)
-    AC_SUBST(TCL_ZIPFS_FLAG)
-    AC_SUBST(ZIP_PROG)
-    AC_SUBST(ZIP_PROG_OPTIONS)
-    AC_SUBST(ZIP_PROG_VFSSEARCH)
-    AC_SUBST(INSTALL_LIBRARIES)
-    AC_SUBST(INSTALL_MSGS)
-])
-
-# Local Variables:
-# mode: autoconf
-# End:
similarity index 87%
rename from pkgs/thread2.8.5/Makefile.in
rename to pkgs/thread2.8.6/Makefile.in
index 0a1a106..9697a81 100644 (file)
@@ -101,8 +101,6 @@ CFLAGS_WARNING      = @CFLAGS_WARNING@
 EXEEXT         = @EXEEXT@
 LDFLAGS_DEFAULT        = @LDFLAGS_DEFAULT@
 MAKE_LIB       = @MAKE_LIB@
-MAKE_SHARED_LIB        = @MAKE_SHARED_LIB@
-MAKE_STATIC_LIB        = @MAKE_STATIC_LIB@
 MAKE_STUB_LIB  = @MAKE_STUB_LIB@
 OBJEXT         = @OBJEXT@
 RANLIB         = @RANLIB@
@@ -137,11 +135,11 @@ PKG_ENV           = TCL_THREAD_LIBRARY=`@CYGPATH@ $(srcdir)/lib` \
                  TCLLIBPATH="$(TCLLIBPATH) $(top_builddir)/../lib"
 
 TCLSH_PROG     = @TCLSH_PROG@
-TCLSH          = $(PKG_ENV) $(TCLSH_ENV) $(TCLSH_PROG)
+TCLSH          = $(TCLSH_ENV) $(PKG_ENV) $(TCLSH_PROG)
 
 #WISH_ENV      = TK_LIBRARY=`@CYGPATH@ $(TK_SRC_DIR)/library`
 #WISH_PROG     = @WISH_PROG@
-#WISH          = $(PKG_ENV) $(TCLSH_ENV) $(WISH_ENV) $(WISH_PROG)
+#WISH          = $(TCLSH_ENV) $(WISH_ENV) $(PKG_ENV) $(WISH_PROG)
 
 SHARED_BUILD   = @SHARED_BUILD@
 
@@ -166,7 +164,15 @@ CPPFLAGS   = @CPPFLAGS@
 LIBS           = @PKG_LIBS@ @LIBS@
 AR             = @AR@
 CFLAGS         = @CFLAGS@
-COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
+LDFLAGS                = @LDFLAGS@
+LDFLAGS_DEFAULT                        = @LDFLAGS_DEFAULT@
+COMPILE                = $(CC) $(DEFS) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) \
+                         $(CFLAGS_DEFAULT) $(CFLAGS_WARNING) $(SHLIB_CFLAGS) $(CFLAGS)
+
+GDB            = gdb
+VALGRIND       = valgrind
+VALGRINDARGS   = --tool=memcheck --num-callers=8 --leak-resolution=high \
+                 --leak-check=yes --show-reachable=yes -v
 
 .SUFFIXES: .c .$(OBJEXT)
 
@@ -213,11 +219,11 @@ install-binaries: binaries install-lib-binaries install-bin-binaries
 #========================================================================
 
 install-libraries: libraries
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(includedir)
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(includedir)"
        @echo "Installing header files in $(DESTDIR)$(includedir)"
        @list='$(PKG_HEADERS)'; for i in $$list; do \
            echo "Installing $(srcdir)/$$i" ; \
-           $(INSTALL_DATA) $(srcdir)/$$i $(DESTDIR)$(includedir) ; \
+           $(INSTALL_DATA) $(srcdir)/$$i "$(DESTDIR)$(includedir)" ; \
        done;
 
 #========================================================================
@@ -226,33 +232,37 @@ install-libraries: libraries
 #========================================================================
 
 install-doc: doc
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(mandir)/mann
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(mandir)/mann"
        @echo "Installing documentation in $(DESTDIR)$(mandir)"
        @list='$(srcdir)/doc/man/*.n'; for i in $$list; do \
            echo "Installing $$i"; \
-           $(INSTALL_DATA) $$i $(DESTDIR)$(mandir)/mann ; \
+           $(INSTALL_DATA) $$i "$(DESTDIR)$(mandir)/mann" ; \
        done
 
 test: binaries libraries
        $(TCLSH) `@CYGPATH@ $(srcdir)/tests/all.tcl` $(TESTFLAGS) \
-               -load "package ifneeded $(PACKAGE_NAME) $(PACKAGE_VERSION) \
-                       [list load `@CYGPATH@ $(PKG_LIB_FILE)` $(PACKAGE_NAME)]"
+               -load "package ifneeded Thread $(PACKAGE_VERSION) \
+                       [list load `@CYGPATH@ $(PKG_LIB_FILE)` [string totitle $(PACKAGE_NAME)]]"
 
 shell: binaries libraries
        @$(TCLSH) $(SCRIPT)
 
 gdb:
-       $(TCLSH_ENV) gdb $(TCLSH_PROG) $(SCRIPT)
+       $(TCLSH_ENV) $(PKG_ENV) $(GDB) $(TCLSH_PROG) $(SCRIPT)
 
-VALGRINDARGS = --tool=memcheck --num-callers=8 --leak-resolution=high \
-               --leak-check=yes --show-reachable=yes -v
+gdb-test: binaries libraries
+       $(TCLSH_ENV) $(PKG_ENV) $(GDB) \
+           --args $(TCLSH_PROG) `@CYGPATH@ $(srcdir)/tests/all.tcl` \
+           $(TESTFLAGS) -singleproc 1 \
+           -load "package ifneeded $(PACKAGE_NAME) $(PACKAGE_VERSION) \
+               [list load `@CYGPATH@ $(PKG_LIB_FILE)` [string totitle $(PACKAGE_NAME)]]"
 
 valgrind: binaries libraries
-       $(TCLSH_ENV) valgrind $(VALGRINDARGS) $(TCLSH_PROG) \
-               `@CYGPATH@ $(srcdir)/tests/all.tcl` $(TESTFLAGS)
+       $(TCLSH_ENV) $(PKG_ENV) $(VALGRIND) $(VALGRINDARGS) $(TCLSH_PROG) \
+           `@CYGPATH@ $(srcdir)/tests/all.tcl` $(TESTFLAGS)
 
 valgrindshell: binaries libraries
-       $(TCLSH_ENV) valgrind $(VALGRINDARGS) $(TCLSH_PROG) $(SCRIPT)
+       $(TCLSH_ENV) $(PKG_ENV) $(VALGRIND) $(VALGRINDARGS) $(TCLSH_PROG) $(SCRIPT)
 
 depend:
 
@@ -312,9 +322,14 @@ DIST_INSTALL_SCRIPT        = CPPROG='cp -p' $(INSTALL) -m 755
 dist-clean:
        rm -rf $(DIST_DIR) $(DIST_ROOT)/$(PKG_DIR).tar.*
 
-dist: dist-clean
+$(srcdir)/manifest.uuid:
+       printf "git-" >$(srcdir)/manifest.uuid
+       git rev-parse HEAD >>$(srcdir)/manifest.uuid
+
+dist: dist-clean $(srcdir)/manifest.uuid
        $(INSTALL_DATA_DIR) $(DIST_DIR)
        $(DIST_INSTALL_DATA) $(srcdir)/license.terms \
+               $(srcdir)/manifest.uuid \
                $(srcdir)/ChangeLog $(srcdir)/README \
                $(srcdir)/aclocal.m4 $(srcdir)/configure.ac \
                $(srcdir)/Makefile.in $(srcdir)/pkgIndex.tcl.in \
@@ -386,25 +401,25 @@ distclean: clean
 #========================================================================
 
 install-lib-binaries: binaries
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(pkglibdir)
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(pkglibdir)"
        @list='$(lib_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_LIBRARY) $$p $(DESTDIR)$(pkglibdir)/$$p"; \
-           $(INSTALL_LIBRARY) $$p $(DESTDIR)$(pkglibdir)/$$p; \
+           $(INSTALL_LIBRARY) $$p "$(DESTDIR)$(pkglibdir)/$$p"; \
            stub=`echo $$p|sed -e "s/.*\(stub\).*/\1/"`; \
            if test "x$$stub" = "xstub"; then \
                echo " $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p"; \
-               $(RANLIB_STUB) $(DESTDIR)$(pkglibdir)/$$p; \
+               $(RANLIB_STUB) "$(DESTDIR)$(pkglibdir)/$$p"; \
            else \
                echo " $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p"; \
-               $(RANLIB) $(DESTDIR)$(pkglibdir)/$$p; \
+               $(RANLIB) "$(DESTDIR)$(pkglibdir)/$$p"; \
            fi; \
            ext=`echo $$p|sed -e "s/.*\.//"`; \
            if test "x$$ext" = "xdll"; then \
                lib=`basename $$p|sed -e 's/.[^.]*$$//'`.lib; \
                if test -f $$lib; then \
                    echo " $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib"; \
-                   $(INSTALL_DATA) $$lib $(DESTDIR)$(pkglibdir)/$$lib; \
+                   $(INSTALL_DATA) $$lib "$(DESTDIR)$(pkglibdir)/$$lib"; \
                fi; \
            fi; \
          fi; \
@@ -413,12 +428,12 @@ install-lib-binaries: binaries
          if test -f $(srcdir)/$$p; then \
            destp=`basename $$p`; \
            echo " Install $$destp $(DESTDIR)$(pkglibdir)/$$destp"; \
-           $(INSTALL_DATA) $(srcdir)/$$p $(DESTDIR)$(pkglibdir)/$$destp; \
+           $(INSTALL_DATA) $(srcdir)/$$p "$(DESTDIR)$(pkglibdir)/$$destp"; \
          fi; \
        done
        @if test "x$(SHARED_BUILD)" = "x1"; then \
            echo " Install pkgIndex.tcl $(DESTDIR)$(pkglibdir)"; \
-           $(INSTALL_DATA) pkgIndex.tcl $(DESTDIR)$(pkglibdir); \
+           $(INSTALL_DATA) pkgIndex.tcl "$(DESTDIR)$(pkglibdir)"; \
        fi
 
 #========================================================================
@@ -431,11 +446,11 @@ install-lib-binaries: binaries
 #========================================================================
 
 install-bin-binaries: binaries
-       @$(INSTALL_DATA_DIR) $(DESTDIR)$(bindir)
+       @$(INSTALL_DATA_DIR) "$(DESTDIR)$(bindir)"
        @list='$(bin_BINARIES)'; for p in $$list; do \
          if test -f $$p; then \
            echo " $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p"; \
-           $(INSTALL_PROGRAM) $$p $(DESTDIR)$(bindir)/$$p; \
+           $(INSTALL_PROGRAM) $$p "$(DESTDIR)$(bindir)/$$p"; \
          fi; \
        done
 
@@ -445,17 +460,18 @@ Makefile: $(srcdir)/Makefile.in  $(top_builddir)/config.status
 
 uninstall-binaries:
        list='$(lib_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(PKG_TCL_SOURCES)'; for p in $$list; do \
          p=`basename $$p`; \
-         rm -f $(DESTDIR)$(pkglibdir)/$$p; \
+         rm -f "$(DESTDIR)$(pkglibdir)/$$p"; \
        done
        list='$(bin_BINARIES)'; for p in $$list; do \
-         rm -f $(DESTDIR)$(bindir)/$$p; \
+         rm -f "$(DESTDIR)$(bindir)/$$p"; \
        done
 
 .PHONY: all binaries clean depend distclean doc install libraries test
+.PHONY: gdb gdb-test valgrind valgrindshell
 
 # 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.
similarity index 91%
rename from pkgs/thread2.8.5/README
rename to pkgs/thread2.8.6/README
index 7ec98db..7c93c99 100644 (file)
@@ -12,7 +12,7 @@ AOLserver 4.x series of the highly-scalable web server from America Online.
 You need to have your Tcl core compiled with "--enable-threads" in order
 to turn on internal directives supporting thread-specific details of the
 Tcl API. The extension will not load in an Tcl shell built w/o thread
-support.
+support. Starting with Tcl 8.6, "--enable-threads" is already the default.
 
 This extension is a freely available open source package. You can do
 virtually anything you like with it, such as modifying it, redistributing
@@ -44,9 +44,9 @@ HOW TO GET SUPPORT ?
 ====================
 
 The extension is maintained, enhanced, and distributed freely by the Tcl
-community. The home for sources and bug/patch database is on SourceForge:
+community. The home for sources and bug/patch database is on fossil:
 
-        http://tcl.sourceforge.net/
+        https://core.tcl-lang.org/thread
 
 Alternatively, you are always welcome to post your questions, problems
 and/or suggestions relating the extension (or any other Tcl issue)
similarity index 95%
rename from pkgs/thread2.8.5/aclocal.m4
rename to pkgs/thread2.8.6/aclocal.m4
index 9a825fb..995e3a2 100644 (file)
@@ -43,7 +43,8 @@ AC_DEFUN(TCLTHREAD_WITH_GDBM, [
                 `ls -d ${exec_prefix}/lib 2>/dev/null`\
                 `ls -d ${prefix}/lib 2>/dev/null`\
                 `ls -d /usr/local/lib 2>/dev/null`\
-                `ls -d /usr/lib 2>/dev/null` ; do
+                `ls -d /usr/lib 2>/dev/null`\
+                `ls -d /usr/lib/x86_64-linux-gnu 2>/dev/null` ; do
             if test x"`ls $i/libgdbm* 2>/dev/null`" != x ; then
                 glibdir=`(cd $i; pwd)`
                 break
@@ -105,7 +106,8 @@ AC_DEFUN(TCLTHREAD_WITH_LMDB, [
                     `ls -d ${exec_prefix}/lib 2>/dev/null`\
                     `ls -d ${prefix}/lib 2>/dev/null`\
                     `ls -d /usr/local/lib 2>/dev/null`\
-                    `ls -d /usr/lib 2>/dev/null` ; do
+                    `ls -d /usr/lib 2>/dev/null`\
+                    `ls -d /usr/lib/x86_64-linux-gnu 2>/dev/null` ; do
                 if test x"`ls $i/liblmdb* 2>/dev/null`" != x ; then
                     llibdir=`(cd $i; pwd)`
                     break
similarity index 65%
rename from pkgs/thread2.8.5/configure
rename to pkgs/thread2.8.6/configure
index 768486b..6e32fd8 100755 (executable)
@@ -1,9 +1,9 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for thread 2.8.5.
+# Generated by GNU Autoconf 2.70 for thread 2.8.6.
 #
 #
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
+# Copyright (C) 1992-1996, 1998-2017, 2020 Free Software Foundation, Inc.
 #
 #
 # This configure script is free software; the Free Software Foundation
 
 # Be more Bourne compatible
 DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+as_nop=:
+if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1
+then :
   emulate sh
   NULLCMD=:
   # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
   setopt NO_GLOB_SUBST
-else
+else $as_nop
   case `(set -o) 2>/dev/null` in #(
   *posix*) :
     set -o posix ;; #(
@@ -31,46 +33,46 @@ esac
 fi
 
 
+
+# Reset variables that may have inherited troublesome values from
+# the environment.
+
+# IFS needs to be set, to space, tab, and newline, in precisely that order.
+# (If _AS_PATH_WALK were called with IFS unset, it would have the
+# side effect of setting IFS to empty, thus disabling word splitting.)
+# Quoting is to prevent editors from complaining about space-tab.
 as_nl='
 '
 export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
+IFS=" ""       $as_nl"
+
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# Ensure predictable behavior from utilities with locale-dependent output.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# We cannot yet rely on "unset" to work, but we need these variables
+# to be unset--not just set to an empty or harmless value--now, to
+# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh).  This construct
+# also avoids known problems related to "unset" and subshell syntax
+# in other old shells (e.g. bash 2.01 and pdksh 5.2.14).
+for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH
+do eval test \${$as_var+y} \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+
+# Ensure that fds 0, 1, and 2 are open.
+if (exec 3>&0) 2>/dev/null; then :; else exec 0</dev/null; fi
+if (exec 3>&1) 2>/dev/null; then :; else exec 1>/dev/null; fi
+if (exec 3>&2)            ; then :; else exec 2>/dev/null; fi
 
 # The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
+if ${PATH_SEPARATOR+false} :; then
   PATH_SEPARATOR=:
   (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
     (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
@@ -79,13 +81,6 @@ if test "${PATH_SEPARATOR+set}" != set; then
 fi
 
 
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
 # Find who we are.  Look in the path if we contain no directory separator.
 as_myself=
 case $0 in #((
@@ -94,8 +89,12 @@ case $0 in #((
 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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    test -r "$as_dir$0" && as_myself=$as_dir$0 && break
   done
 IFS=$as_save_IFS
 
@@ -107,30 +106,10 @@ if test "x$as_myself" = x; then
   as_myself=$0
 fi
 if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
   exit 1
 fi
 
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
 # Use a proper internal environment variable to ensure we don't fall
   # into an infinite loop, continuously re-executing ourselves.
@@ -152,20 +131,22 @@ esac
 exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
 # Admittedly, this is quite paranoid, since all the known shells bail
 # out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
+printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2
+exit 255
   fi
   # We don't want this to propagate to other subprocesses.
           { _as_can_reexec=; unset _as_can_reexec;}
 if test "x$CONFIG_SHELL" = x; then
-  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  as_bourne_compatible="as_nop=:
+if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1
+then :
   emulate sh
   NULLCMD=:
   # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '\${1+\"\$@\"}'='\"\$@\"'
   setopt NO_GLOB_SUBST
-else
+else \$as_nop
   case \`(set -o) 2>/dev/null\` in #(
   *posix*) :
     set -o posix ;; #(
@@ -185,42 +166,53 @@ as_fn_success || { exitcode=1; echo as_fn_success failed.; }
 as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
 as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
 as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+if ( set x; as_fn_ret_success y && test x = \"\$1\" )
+then :
 
-else
+else \$as_nop
   exitcode=1; echo positional parameters were not saved.
 fi
 test x\$exitcode = x0 || exit 1
+blah=\$(echo \$(echo blah))
+test x\"\$blah\" = xblah || exit 1
 test -x / || exit 1"
   as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
   as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
   eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
   test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
 test \$(( 1 + 1 )) = 2 || exit 1"
-  if (eval "$as_required") 2>/dev/null; then :
+  if (eval "$as_required") 2>/dev/null
+then :
   as_have_required=yes
-else
+else $as_nop
   as_have_required=no
 fi
-  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null
+then :
 
-else
+else $as_nop
   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 as_found=false
 for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
   as_found=:
   case $as_dir in #(
         /*)
           for as_base in sh bash ksh sh5; do
             # Try only shells that exist, to save several forks.
-            as_shell=$as_dir/$as_base
+            as_shell=$as_dir$as_base
             if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-                   { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+                   as_run=a "$as_shell" -c "$as_bourne_compatible""$as_required" 2>/dev/null
+then :
   CONFIG_SHELL=$as_shell as_have_required=yes
-                  if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+                  if as_run=a "$as_shell" -c "$as_bourne_compatible""$as_suggested" 2>/dev/null
+then :
   break 2
 fi
 fi
@@ -228,14 +220,21 @@ fi
        esac
   as_found=false
 done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
-             { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
-  CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
 IFS=$as_save_IFS
+if $as_found
+then :
+
+else $as_nop
+  if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+             as_run=a "$SHELL" -c "$as_bourne_compatible""$as_required" 2>/dev/null
+then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi
+fi
 
 
-      if test "x$CONFIG_SHELL" != x; then :
+      if test "x$CONFIG_SHELL" != x
+then :
   export CONFIG_SHELL
              # We cannot yet assume a decent shell, so we have to provide a
 # neutralization value for shells without unset; and this also
@@ -253,18 +252,19 @@ esac
 exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
 # Admittedly, this is quite paranoid, since all the known shells bail
 # out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2
 exit 255
 fi
 
-    if test x$as_have_required = xno; then :
-  $as_echo "$0: This script requires a shell more modern than all"
-  $as_echo "$0: the shells that I found on your system."
-  if test x${ZSH_VERSION+set} = xset ; then
-    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
-    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+    if test x$as_have_required = xno
+then :
+  printf "%s\n" "$0: This script requires a shell more modern than all"
+  printf "%s\n" "$0: the shells that I found on your system."
+  if test ${ZSH_VERSION+y} ; then
+    printf "%s\n" "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    printf "%s\n" "$0: be upgraded to zsh 4.3.4 or later."
   else
-    $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
+    printf "%s\n" "$0: Please tell bug-autoconf@gnu.org about your system,
 $0: including any error possibly output before this
 $0: message. Then install a modern shell, or manually run
 $0: the script under such a shell if you do have one."
@@ -291,6 +291,7 @@ as_fn_unset ()
 }
 as_unset=as_fn_unset
 
+
 # as_fn_set_status STATUS
 # -----------------------
 # Set $? to STATUS, without forking.
@@ -308,6 +309,14 @@ as_fn_exit ()
   as_fn_set_status $1
   exit $1
 } # as_fn_exit
+# as_fn_nop
+# ---------
+# Do nothing but, unlike ":", preserve the value of $?.
+as_fn_nop ()
+{
+  return $?
+}
+as_nop=as_fn_nop
 
 # as_fn_mkdir_p
 # -------------
@@ -322,7 +331,7 @@ as_fn_mkdir_p ()
     as_dirs=
     while :; do
       case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
       *) as_qdir=$as_dir;;
       esac
       as_dirs="'$as_qdir' $as_dirs"
@@ -331,7 +340,7 @@ $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$as_dir" : 'X\(//\)[^/]' \| \
         X"$as_dir" : 'X\(//\)$' \| \
         X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
+printf "%s\n" X"$as_dir" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
            s//\1/
            q
@@ -370,12 +379,13 @@ as_fn_executable_p ()
 # advantage of any shell optimizations that allow amortized linear growth over
 # repeated appends, instead of the typical quadratic growth present in naive
 # implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null
+then :
   eval 'as_fn_append ()
   {
     eval $1+=\$2
   }'
-else
+else $as_nop
   as_fn_append ()
   {
     eval $1=\$$1\$2
@@ -387,18 +397,27 @@ fi # as_fn_append
 # Perform arithmetic evaluation on the ARGs, and store the result in the
 # global $as_val. Take advantage of shells that can avoid forks. The arguments
 # must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null
+then :
   eval 'as_fn_arith ()
   {
     as_val=$(( $* ))
   }'
-else
+else $as_nop
   as_fn_arith ()
   {
     as_val=`expr "$@" || test $? -eq 1`
   }
 fi # as_fn_arith
 
+# as_fn_nop
+# ---------
+# Do nothing but, unlike ":", preserve the value of $?.
+as_fn_nop ()
+{
+  return $?
+}
+as_nop=as_fn_nop
 
 # as_fn_error STATUS ERROR [LINENO LOG_FD]
 # ----------------------------------------
@@ -410,9 +429,9 @@ as_fn_error ()
   as_status=$1; test $as_status -eq 0 && as_status=1
   if test "$4"; then
     as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
   fi
-  $as_echo "$as_me: error: $2" >&2
+  printf "%s\n" "$as_me: error: $2" >&2
   as_fn_exit $as_status
 } # as_fn_error
 
@@ -439,7 +458,7 @@ as_me=`$as_basename -- "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
         X"$0" : 'X\(//\)$' \| \
         X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
+printf "%s\n" X/"$0" |
     sed '/^.*\/\([^/][^/]*\)\/*$/{
            s//\1/
            q
@@ -483,7 +502,7 @@ as_cr_alnum=$as_cr_Letters$as_cr_digits
       s/-\n.*//
     ' >$as_me.lineno &&
   chmod +x "$as_me.lineno" ||
-    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+    { printf "%s\n" "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
 
   # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
   # already done that, so ensure we don't try to do so again and fall
@@ -497,6 +516,10 @@ as_cr_alnum=$as_cr_Letters$as_cr_digits
   exit
 }
 
+
+# Determine whether it's possible to make 'echo' print without a newline.
+# These variables are no longer used directly by Autoconf, but are AC_SUBSTed
+# for compatibility with existing Makefiles.
 ECHO_C= ECHO_N= ECHO_T=
 case `echo -n x` in #(((((
 -n*)
@@ -510,6 +533,13 @@ case `echo -n x` in #(((((
   ECHO_N='-n';;
 esac
 
+# For backward compatibility with old third-party macros, we provide
+# the shell variables $as_echo and $as_echo_n.  New code should use
+# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively.
+as_echo='printf %s\n'
+as_echo_n='printf %s'
+
+
 rm -f conf$$ conf$$.exe conf$$.file
 if test -d conf$$.dir; then
   rm -f conf$$.dir/conf$$.file
@@ -577,47 +607,43 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='thread'
 PACKAGE_TARNAME='thread'
-PACKAGE_VERSION='2.8.5'
-PACKAGE_STRING='thread 2.8.5'
+PACKAGE_VERSION='2.8.6'
+PACKAGE_STRING='thread 2.8.6'
 PACKAGE_BUGREPORT=''
 PACKAGE_URL=''
 
 # Factoring default headers for most tests.
 ac_includes_default="\
-#include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
+#include <stddef.h>
+#ifdef HAVE_STDIO_H
+# include <stdio.h>
 #endif
-#ifdef STDC_HEADERS
+#ifdef HAVE_STDLIB_H
 # include <stdlib.h>
-# include <stddef.h>
-#else
-# ifdef HAVE_STDLIB_H
-#  include <stdlib.h>
-# endif
 #endif
 #ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
-#  include <memory.h>
-# endif
 # include <string.h>
 #endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
 #ifdef HAVE_INTTYPES_H
 # include <inttypes.h>
 #endif
 #ifdef HAVE_STDINT_H
 # include <stdint.h>
 #endif
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
 #ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #endif"
 
+ac_header_c_list=
 ac_subst_vars='LTLIBOBJS
 TCLSH_PROG
 VC_MANIFEST_EMBED_EXE
@@ -627,7 +653,8 @@ MAKE_STUB_LIB
 MAKE_STATIC_LIB
 MAKE_SHARED_LIB
 MAKE_LIB
-TCL_DBGX
+EGREP
+GREP
 LDFLAGS_DEFAULT
 CFLAGS_DEFAULT
 LD_LIBRARY_PATH_VAR
@@ -635,6 +662,8 @@ SHLIB_CFLAGS
 SHLIB_LD_LIBS
 SHLIB_LD
 STLIB_LD
+LDFLAGS_OPTIMIZE
+LDFLAGS_DEBUG
 CFLAGS_WARNING
 CFLAGS_OPTIMIZE
 CFLAGS_DEBUG
@@ -647,8 +676,6 @@ TCL_THREADS
 TCL_INCLUDES
 PKG_OBJECTS
 PKG_SOURCES
-EGREP
-GREP
 RANLIB
 SET_MAKE
 CPP
@@ -710,6 +737,7 @@ infodir
 docdir
 oldincludedir
 includedir
+runstatedir
 localstatedir
 sharedstatedir
 sysconfdir
@@ -792,6 +820,7 @@ datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
+runstatedir='${localstatedir}/run'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
 docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
@@ -821,8 +850,6 @@ do
   *)    ac_optarg=yes ;;
   esac
 
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
   case $ac_dashdash$ac_option in
   --)
     ac_dashdash=yes ;;
@@ -863,9 +890,9 @@ do
     ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
     # Reject names that are not valid shell variable names.
     expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
+      as_fn_error $? "invalid feature name: \`$ac_useropt'"
     ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'`
     case $ac_user_opts in
       *"
 "enable_$ac_useropt"
@@ -889,9 +916,9 @@ do
     ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
     expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid feature name: $ac_useropt"
+      as_fn_error $? "invalid feature name: \`$ac_useropt'"
     ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'`
     case $ac_user_opts in
       *"
 "enable_$ac_useropt"
@@ -1044,6 +1071,15 @@ do
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
 
+  -runstatedir | --runstatedir | --runstatedi | --runstated \
+  | --runstate | --runstat | --runsta | --runst | --runs \
+  | --run | --ru | --r)
+    ac_prev=runstatedir ;;
+  -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
+  | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
+  | --run=* | --ru=* | --r=*)
+    runstatedir=$ac_optarg ;;
+
   -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
@@ -1093,9 +1129,9 @@ do
     ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
     expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
+      as_fn_error $? "invalid package name: \`$ac_useropt'"
     ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'`
     case $ac_user_opts in
       *"
 "with_$ac_useropt"
@@ -1109,9 +1145,9 @@ do
     ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
     # Reject names that are not valid shell variable names.
     expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
-      as_fn_error $? "invalid package name: $ac_useropt"
+      as_fn_error $? "invalid package name: \`$ac_useropt'"
     ac_useropt_orig=$ac_useropt
-    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'`
     case $ac_user_opts in
       *"
 "with_$ac_useropt"
@@ -1155,9 +1191,9 @@ Try \`$0 --help' for more information"
 
   *)
     # FIXME: should be removed in autoconf 3.0.
-    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    printf "%s\n" "$as_me: WARNING: you should use --build, --host, --target" >&2
     expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+      printf "%s\n" "$as_me: WARNING: invalid host type: $ac_option" >&2
     : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
     ;;
 
@@ -1173,7 +1209,7 @@ if test -n "$ac_unrecognized_opts"; then
   case $enable_option_checking in
     no) ;;
     fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
-    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+    *)     printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
   esac
 fi
 
@@ -1181,7 +1217,7 @@ fi
 for ac_var in  exec_prefix prefix bindir sbindir libexecdir datarootdir \
                datadir sysconfdir sharedstatedir localstatedir includedir \
                oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-               libdir localedir mandir
+               libdir localedir mandir runstatedir
 do
   eval ac_val=\$$ac_var
   # Remove trailing slashes.
@@ -1237,7 +1273,7 @@ $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$as_myself" : 'X\(//\)[^/]' \| \
         X"$as_myself" : 'X\(//\)$' \| \
         X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
+printf "%s\n" X"$as_myself" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
            s//\1/
            q
@@ -1294,7 +1330,7 @@ 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 thread 2.8.5 to adapt to many kinds of systems.
+\`configure' configures thread 2.8.6 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1334,6 +1370,7 @@ Fine tuning of the installation directories:
   --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]
+  --runstatedir=DIR       modifiable per-process data [LOCALSTATEDIR/run]
   --libdir=DIR            object code libraries [EPREFIX/lib]
   --includedir=DIR        C header files [PREFIX/include]
   --oldincludedir=DIR     C header files for non-gcc [/usr/include]
@@ -1355,7 +1392,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of thread 2.8.5:";;
+     short | recursive ) echo "Configuration of thread 2.8.6:";;
    esac
   cat <<\_ACEOF
 
@@ -1411,9 +1448,9 @@ if test "$ac_init_help" = "recursive"; then
 case "$ac_dir" in
 .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
 *)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'`
   # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
   case $ac_top_builddir_sub in
   "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
   *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
@@ -1441,7 +1478,8 @@ esac
 ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
 
     cd "$ac_dir" || { ac_status=$?; continue; }
-    # Check for guested configure.
+    # Check for configure.gnu first; this name is used for a wrapper for
+    # Metaconfig's "Configure" on case-insensitive file systems.
     if test -f "$ac_srcdir/configure.gnu"; then
       echo &&
       $SHELL "$ac_srcdir/configure.gnu" --help=recursive
@@ -1449,7 +1487,7 @@ ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
       echo &&
       $SHELL "$ac_srcdir/configure" --help=recursive
     else
-      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+      printf "%s\n" "$as_me: WARNING: no configuration information is in $ac_dir" >&2
     fi || ac_status=$?
     cd "$ac_pwd" || { ac_status=$?; break; }
   done
@@ -1458,10 +1496,10 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-thread configure 2.8.5
-generated by GNU Autoconf 2.69
+thread configure 2.8.6
+generated by GNU Autoconf 2.70
 
-Copyright (C) 2012 Free Software Foundation, Inc.
+Copyright (C) 2020 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it.
 _ACEOF
@@ -1478,14 +1516,14 @@ fi
 ac_fn_c_try_compile ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext
+  rm -f conftest.$ac_objext conftest.beam
   if { { ac_try="$ac_compile"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_compile") 2>conftest.err
   ac_status=$?
   if test -s conftest.err; then
@@ -1493,14 +1531,15 @@ $as_echo "$ac_try_echo"; } >&5
     cat conftest.er1 >&5
     mv -f conftest.er1 conftest.err
   fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; } && {
         test -z "$ac_c_werror_flag" ||
         test ! -s conftest.err
-       } && test -s conftest.$ac_objext; then :
+       } && test -s conftest.$ac_objext
+then :
   ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
+else $as_nop
+  printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
        ac_retval=1
@@ -1522,7 +1561,7 @@ case "(($ac_try" in
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
   ac_status=$?
   if test -s conftest.err; then
@@ -1530,14 +1569,15 @@ $as_echo "$ac_try_echo"; } >&5
     cat conftest.er1 >&5
     mv -f conftest.er1 conftest.err
   fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; } > conftest.i && {
         test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
         test ! -s conftest.err
-       }; then :
+       }
+then :
   ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
+else $as_nop
+  printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
     ac_retval=1
@@ -1549,8 +1589,8 @@ fi
 
 # ac_fn_c_try_run LINENO
 # ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
+# Try to run conftest.$ac_ext, and return whether this succeeded. Assumes that
+# executables *can* be run.
 ac_fn_c_try_run ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
@@ -1560,25 +1600,26 @@ case "(($ac_try" in
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_link") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
   { { case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then :
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }
+then :
   ac_retval=0
-else
-  $as_echo "$as_me: program exited with status $ac_status" >&5
-       $as_echo "$as_me: failed program was:" >&5
+else $as_nop
+  printf "%s\n" "$as_me: program exited with status $ac_status" >&5
+       printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
        ac_retval=$ac_status
@@ -1596,26 +1637,28 @@ fi
 ac_fn_c_check_header_compile ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+printf %s "checking for $2... " >&6; }
+if eval test \${$3+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $4
 #include <$2>
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   eval "$3=yes"
-else
+else $as_nop
   eval "$3=no"
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
+              { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+printf "%s\n" "$ac_res" >&6; }
   eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_header_compile
@@ -1626,14 +1669,14 @@ $as_echo "$ac_res" >&6; }
 ac_fn_c_try_link ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  rm -f conftest.$ac_objext conftest$ac_exeext
+  rm -f conftest.$ac_objext conftest.beam conftest$ac_exeext
   if { { ac_try="$ac_link"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_link") 2>conftest.err
   ac_status=$?
   if test -s conftest.err; then
@@ -1641,17 +1684,18 @@ $as_echo "$ac_try_echo"; } >&5
     cat conftest.er1 >&5
     mv -f conftest.er1 conftest.err
   fi
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; } && {
         test -z "$ac_c_werror_flag" ||
         test ! -s conftest.err
        } && test -s conftest$ac_exeext && {
         test "$cross_compiling" = yes ||
         test -x conftest$ac_exeext
-       }; then :
+       }
+then :
   ac_retval=0
-else
-  $as_echo "$as_me: failed program was:" >&5
+else $as_nop
+  printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
        ac_retval=1
 
 } # ac_fn_c_try_link
 
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval \${$3+:} false; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
-  # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_header_compiler=yes
-else
-  ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-  ac_header_preproc=yes
-else
-  ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So?  What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
-  yes:no: )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-  no:yes:* )
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-    ;;
-esac
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
-  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
-
 # ac_fn_c_check_func LINENO FUNC VAR
 # ----------------------------------
 # Tests whether FUNC exists, setting the cache variable VAR accordingly
 ac_fn_c_check_func ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+printf %s "checking for $2... " >&6; }
+if eval test \${$3+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 /* Define $2 to an innocuous variant, in case <limits.h> declares $2.
@@ -1771,16 +1729,9 @@ else
 #define $2 innocuous_$2
 
 /* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $2 (); 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
+   which can conflict with char $2 (); below.  */
 
+#include <limits.h>
 #undef $2
 
 /* Override any GCC internal prototype to avoid an error.
@@ -1798,35 +1749,56 @@ choke me
 #endif
 
 int
-main ()
+main (void)
 {
 return $2 ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   eval "$3=yes"
-else
+else $as_nop
   eval "$3=no"
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 fi
 eval ac_res=\$$3
-              { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
+              { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+printf "%s\n" "$ac_res" >&6; }
   eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_func
+ac_configure_args_raw=
+for ac_arg
+do
+  case $ac_arg in
+  *\'*)
+    ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+  esac
+  as_fn_append ac_configure_args_raw " '$ac_arg'"
+done
+
+case $ac_configure_args_raw in
+  *$as_nl*)
+    ac_safe_unquote= ;;
+  *)
+    ac_unsafe_z='|&;<>()$`\\"*?[ ''    ' # This string ends in space, tab.
+    ac_unsafe_a="$ac_unsafe_z#~"
+    ac_safe_unquote="s/ '\\([^$ac_unsafe_a][^$ac_unsafe_z]*\\)'/ \\1/g"
+    ac_configure_args_raw=`      printf "%s\n" "$ac_configure_args_raw" | sed "$ac_safe_unquote"`;;
+esac
+
 cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by thread $as_me 2.8.5, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
+It was created by thread $as_me 2.8.6, which was
+generated by GNU Autoconf 2.70.  Invocation command line was
 
-  $ $0 $@
+  $ $0$ac_configure_args_raw
 
 _ACEOF
 exec 5>>config.log
@@ -1859,8 +1831,12 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    $as_echo "PATH: $as_dir"
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    printf "%s\n" "PATH: $as_dir"
   done
 IFS=$as_save_IFS
 
@@ -1895,7 +1871,7 @@ do
     | -silent | --silent | --silen | --sile | --sil)
       continue ;;
     *\'*)
-      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
     esac
     case $ac_pass in
     1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
@@ -1930,11 +1906,13 @@ done
 # WARNING: Use '\'' to represent an apostrophe within the trap.
 # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
 trap 'exit_status=$?
+  # Sanitize IFS.
+  IFS=" ""     $as_nl"
   # Save into config.log some information that might help in debugging.
   {
     echo
 
-    $as_echo "## ---------------- ##
+    printf "%s\n" "## ---------------- ##
 ## Cache variables. ##
 ## ---------------- ##"
     echo
@@ -1945,8 +1923,8 @@ trap 'exit_status=$?
     case $ac_val in #(
     *${as_nl}*)
       case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
       esac
       case $ac_var in #(
       _ | IFS | as_nl) ;; #(
@@ -1970,7 +1948,7 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
 )
     echo
 
-    $as_echo "## ----------------- ##
+    printf "%s\n" "## ----------------- ##
 ## Output variables. ##
 ## ----------------- ##"
     echo
@@ -1978,14 +1956,14 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
     do
       eval ac_val=\$$ac_var
       case $ac_val in
-      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
       esac
-      $as_echo "$ac_var='\''$ac_val'\''"
+      printf "%s\n" "$ac_var='\''$ac_val'\''"
     done | sort
     echo
 
     if test -n "$ac_subst_files"; then
-      $as_echo "## ------------------- ##
+      printf "%s\n" "## ------------------- ##
 ## File substitutions. ##
 ## ------------------- ##"
       echo
@@ -1993,15 +1971,15 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
       do
        eval ac_val=\$$ac_var
        case $ac_val in
-       *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+       *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
        esac
-       $as_echo "$ac_var='\''$ac_val'\''"
+       printf "%s\n" "$ac_var='\''$ac_val'\''"
       done | sort
       echo
     fi
 
     if test -s confdefs.h; then
-      $as_echo "## ----------- ##
+      printf "%s\n" "## ----------- ##
 ## confdefs.h. ##
 ## ----------- ##"
       echo
@@ -2009,8 +1987,8 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
       echo
     fi
     test "$ac_signal" != 0 &&
-      $as_echo "$as_me: caught signal $ac_signal"
-    $as_echo "$as_me: exit $exit_status"
+      printf "%s\n" "$as_me: caught signal $ac_signal"
+    printf "%s\n" "$as_me: exit $exit_status"
   } >&5
   rm -f core *.core core.conftest.* &&
     rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
@@ -2024,63 +2002,48 @@ ac_signal=0
 # confdefs.h avoids OS command line length limits that DEFS can exceed.
 rm -f -r conftest* confdefs.h
 
-$as_echo "/* confdefs.h */" > confdefs.h
+printf "%s\n" "/* confdefs.h */" > confdefs.h
 
 # Predefined preprocessor variables.
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
+printf "%s\n" "#define PACKAGE_NAME \"$PACKAGE_NAME\"" >>confdefs.h
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
+printf "%s\n" "#define PACKAGE_TARNAME \"$PACKAGE_TARNAME\"" >>confdefs.h
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
+printf "%s\n" "#define PACKAGE_VERSION \"$PACKAGE_VERSION\"" >>confdefs.h
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
+printf "%s\n" "#define PACKAGE_STRING \"$PACKAGE_STRING\"" >>confdefs.h
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
+printf "%s\n" "#define PACKAGE_BUGREPORT \"$PACKAGE_BUGREPORT\"" >>confdefs.h
 
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
+printf "%s\n" "#define PACKAGE_URL \"$PACKAGE_URL\"" >>confdefs.h
 
 
 # Let the site file select an alternate cache file if it wants to.
 # Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
 if test -n "$CONFIG_SITE"; then
-  # We do not want a PATH search for config.site.
-  case $CONFIG_SITE in #((
-    -*)  ac_site_file1=./$CONFIG_SITE;;
-    */*) ac_site_file1=$CONFIG_SITE;;
-    *)   ac_site_file1=./$CONFIG_SITE;;
-  esac
+  ac_site_files="$CONFIG_SITE"
 elif test "x$prefix" != xNONE; then
-  ac_site_file1=$prefix/share/config.site
-  ac_site_file2=$prefix/etc/config.site
+  ac_site_files="$prefix/share/config.site $prefix/etc/config.site"
 else
-  ac_site_file1=$ac_default_prefix/share/config.site
-  ac_site_file2=$ac_default_prefix/etc/config.site
+  ac_site_files="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+
+for ac_site_file in $ac_site_files
 do
-  test "x$ac_site_file" = xNONE && continue
-  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+  case $ac_site_file in #(
+  */*) :
+     ;; #(
+  *) :
+    ac_site_file=./$ac_site_file ;;
+esac
+  if test -f "$ac_site_file" && test -r "$ac_site_file"; then
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+printf "%s\n" "$as_me: loading site script $ac_site_file" >&6;}
     sed 's/^/| /' "$ac_site_file" >&5
     . "$ac_site_file" \
-      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+      || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "failed to load site script $ac_site_file
 See \`config.log' for more details" "$LINENO" 5; }
   fi
@@ -2090,19 +2053,336 @@ if test -r "$cache_file"; then
   # Some versions of bash will fail to source /dev/null (special files
   # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
   if test /dev/null != "$cache_file" && test -f "$cache_file"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+printf "%s\n" "$as_me: loading cache $cache_file" >&6;}
     case $cache_file in
       [\\/]* | ?:[\\/]* ) . "$cache_file";;
       *)                      . "./$cache_file";;
     esac
   fi
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+printf "%s\n" "$as_me: creating cache $cache_file" >&6;}
   >$cache_file
 fi
 
+# Test code for whether the C compiler supports C89 (global declarations)
+ac_c_conftest_c89_globals='
+/* Does the compiler advertise C89 conformance?
+   Do not test the value of __STDC__, because some compilers set it to 0
+   while being otherwise adequately conformant. */
+#if !defined __STDC__
+# error "Compiler does not advertise C89 conformance"
+#endif
+
+#include <stddef.h>
+#include <stdarg.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7 src/conf.sh.  */
+struct buf { int x; };
+struct buf * (*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 do not provoke an error unfortunately, instead are silently treated
+   as an "x".  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously \x00 != x always comes out true, for an
+   array size at least.  It is necessary to write \x00 == 0 to get something
+   that is true only with -std.  */
+int osf4_cc_array ['\''\x00'\'' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) '\''x'\''
+int xlc6_cc_array[FOO(a) == '\''x'\'' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, int *(*)(struct buf *, struct stat *, int),
+               int, int);'
+
+# Test code for whether the C compiler supports C89 (body of main).
+ac_c_conftest_c89_main='
+ok |= (argc == 0 || f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]);
+'
+
+# Test code for whether the C compiler supports C99 (global declarations)
+ac_c_conftest_c99_globals='
+// Does the compiler advertise C99 conformance?
+#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L
+# error "Compiler does not advertise C99 conformance"
+#endif
+
+#include <stdbool.h>
+extern int puts (const char *);
+extern int printf (const char *, ...);
+extern int dprintf (int, const char *, ...);
+extern void *malloc (size_t);
+
+// Check varargs macros.  These examples are taken from C99 6.10.3.5.
+// dprintf is used instead of fprintf to avoid needing to declare
+// FILE and stderr.
+#define debug(...) dprintf (2, __VA_ARGS__)
+#define showlist(...) puts (#__VA_ARGS__)
+#define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__))
+static void
+test_varargs_macros (void)
+{
+  int x = 1234;
+  int y = 5678;
+  debug ("Flag");
+  debug ("X = %d\n", x);
+  showlist (The first, second, and third items.);
+  report (x>y, "x is %d but y is %d", x, y);
+}
+
+// Check long long types.
+#define BIG64 18446744073709551615ull
+#define BIG32 4294967295ul
+#define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0)
+#if !BIG_OK
+  #error "your preprocessor is broken"
+#endif
+#if BIG_OK
+#else
+  #error "your preprocessor is broken"
+#endif
+static long long int bignum = -9223372036854775807LL;
+static unsigned long long int ubignum = BIG64;
+
+struct incomplete_array
+{
+  int datasize;
+  double data[];
+};
+
+struct named_init {
+  int number;
+  const wchar_t *name;
+  double average;
+};
+
+typedef const char *ccp;
+
+static inline int
+test_restrict (ccp restrict text)
+{
+  // See if C++-style comments work.
+  // Iterate through items via the restricted pointer.
+  // Also check for declarations in for loops.
+  for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i)
+    continue;
+  return 0;
+}
+
+// Check varargs and va_copy.
+static bool
+test_varargs (const char *format, ...)
+{
+  va_list args;
+  va_start (args, format);
+  va_list args_copy;
+  va_copy (args_copy, args);
+
+  const char *str = "";
+  int number = 0;
+  float fnumber = 0;
+
+  while (*format)
+    {
+      switch (*format++)
+       {
+       case '\''s'\'': // string
+         str = va_arg (args_copy, const char *);
+         break;
+       case '\''d'\'': // int
+         number = va_arg (args_copy, int);
+         break;
+       case '\''f'\'': // float
+         fnumber = va_arg (args_copy, double);
+         break;
+       default:
+         break;
+       }
+    }
+  va_end (args_copy);
+  va_end (args);
+
+  return *str && number && fnumber;
+}
+'
+
+# Test code for whether the C compiler supports C99 (body of main).
+ac_c_conftest_c99_main='
+  // Check bool.
+  _Bool success = false;
+  success |= (argc != 0);
+
+  // Check restrict.
+  if (test_restrict ("String literal") == 0)
+    success = true;
+  char *restrict newvar = "Another string";
+
+  // Check varargs.
+  success &= test_varargs ("s, d'\'' f .", "string", 65, 34.234);
+  test_varargs_macros ();
+
+  // Check flexible array members.
+  struct incomplete_array *ia =
+    malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10));
+  ia->datasize = 10;
+  for (int i = 0; i < ia->datasize; ++i)
+    ia->data[i] = i * 1.234;
+
+  // Check named initializers.
+  struct named_init ni = {
+    .number = 34,
+    .name = L"Test wide string",
+    .average = 543.34343,
+  };
+
+  ni.number = 58;
+
+  int dynamic_array[ni.number];
+  dynamic_array[0] = argv[0][0];
+  dynamic_array[ni.number - 1] = 543;
+
+  // work around unused variable warnings
+  ok |= (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == '\''x'\''
+        || dynamic_array[ni.number - 1] != 543);
+'
+
+# Test code for whether the C compiler supports C11 (global declarations)
+ac_c_conftest_c11_globals='
+// Does the compiler advertise C11 conformance?
+#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L
+# error "Compiler does not advertise C11 conformance"
+#endif
+
+// Check _Alignas.
+char _Alignas (double) aligned_as_double;
+char _Alignas (0) no_special_alignment;
+extern char aligned_as_int;
+char _Alignas (0) _Alignas (int) aligned_as_int;
+
+// Check _Alignof.
+enum
+{
+  int_alignment = _Alignof (int),
+  int_array_alignment = _Alignof (int[100]),
+  char_alignment = _Alignof (char)
+};
+_Static_assert (0 < -_Alignof (int), "_Alignof is signed");
+
+// Check _Noreturn.
+int _Noreturn does_not_return (void) { for (;;) continue; }
+
+// Check _Static_assert.
+struct test_static_assert
+{
+  int x;
+  _Static_assert (sizeof (int) <= sizeof (long int),
+                  "_Static_assert does not work in struct");
+  long int y;
+};
+
+// Check UTF-8 literals.
+#define u8 syntax error!
+char const utf8_literal[] = u8"happens to be ASCII" "another string";
+
+// Check duplicate typedefs.
+typedef long *long_ptr;
+typedef long int *long_ptr;
+typedef long_ptr long_ptr;
+
+// Anonymous structures and unions -- taken from C11 6.7.2.1 Example 1.
+struct anonymous
+{
+  union {
+    struct { int i; int j; };
+    struct { int k; long int l; } w;
+  };
+  int m;
+} v1;
+'
+
+# Test code for whether the C compiler supports C11 (body of main).
+ac_c_conftest_c11_main='
+  _Static_assert ((offsetof (struct anonymous, i)
+                  == offsetof (struct anonymous, w.k)),
+                 "Anonymous union alignment botch");
+  v1.i = 2;
+  v1.w.k = 5;
+  ok |= v1.i != 5;
+'
+
+# Test code for whether the C compiler supports C11 (complete).
+ac_c_conftest_c11_program="${ac_c_conftest_c89_globals}
+${ac_c_conftest_c99_globals}
+${ac_c_conftest_c11_globals}
+
+int
+main (int argc, char **argv)
+{
+  int ok = 0;
+  ${ac_c_conftest_c89_main}
+  ${ac_c_conftest_c99_main}
+  ${ac_c_conftest_c11_main}
+  return ok;
+}
+"
+
+# Test code for whether the C compiler supports C99 (complete).
+ac_c_conftest_c99_program="${ac_c_conftest_c89_globals}
+${ac_c_conftest_c99_globals}
+
+int
+main (int argc, char **argv)
+{
+  int ok = 0;
+  ${ac_c_conftest_c89_main}
+  ${ac_c_conftest_c99_main}
+  return ok;
+}
+"
+
+# Test code for whether the C compiler supports C89 (complete).
+ac_c_conftest_c89_program="${ac_c_conftest_c89_globals}
+
+int
+main (int argc, char **argv)
+{
+  int ok = 0;
+  ${ac_c_conftest_c89_main}
+  return ok;
+}
+"
+
+as_fn_append ac_header_c_list " stdio.h stdio_h HAVE_STDIO_H"
+as_fn_append ac_header_c_list " stdlib.h stdlib_h HAVE_STDLIB_H"
+as_fn_append ac_header_c_list " string.h string_h HAVE_STRING_H"
+as_fn_append ac_header_c_list " inttypes.h inttypes_h HAVE_INTTYPES_H"
+as_fn_append ac_header_c_list " stdint.h stdint_h HAVE_STDINT_H"
+as_fn_append ac_header_c_list " strings.h strings_h HAVE_STRINGS_H"
+as_fn_append ac_header_c_list " sys/stat.h sys_stat_h HAVE_SYS_STAT_H"
+as_fn_append ac_header_c_list " sys/types.h sys_types_h HAVE_SYS_TYPES_H"
+as_fn_append ac_header_c_list " unistd.h unistd_h HAVE_UNISTD_H"
 # Check that the precious variables saved in the cache have kept the same
 # value.
 ac_cache_corrupted=false
@@ -2113,12 +2393,12 @@ for ac_var in $ac_precious_vars; do
   eval ac_new_val=\$ac_env_${ac_var}_value
   case $ac_old_set,$ac_new_set in
     set,)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+printf "%s\n" "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
       ac_cache_corrupted=: ;;
     ,set)
-      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+printf "%s\n" "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
       ac_cache_corrupted=: ;;
     ,);;
     *)
@@ -2127,24 +2407,24 @@ $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
        ac_old_val_w=`echo x $ac_old_val`
        ac_new_val_w=`echo x $ac_new_val`
        if test "$ac_old_val_w" != "$ac_new_val_w"; then
-         { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+         { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+printf "%s\n" "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
          ac_cache_corrupted=:
        else
-         { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+         { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+printf "%s\n" "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
          eval $ac_var=\$ac_old_val
        fi
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
-$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
-       { $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
-$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+printf "%s\n" "$as_me:   former value:  \`$ac_old_val'" >&2;}
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+printf "%s\n" "$as_me:   current value: \`$ac_new_val'" >&2;}
       fi;;
   esac
   # Pass precious variables to config.status.
   if test "$ac_new_set" = set; then
     case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *\'*) ac_arg=$ac_var=`printf "%s\n" "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
     *) ac_arg=$ac_var=$ac_new_val ;;
     esac
     case " $ac_configure_args " in
@@ -2154,11 +2434,12 @@ $as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
   fi
 done
 if $ac_cache_corrupted; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+printf "%s\n" "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`${MAKE-make} distclean' and/or \`rm $cache_file'
+           and start over" "$LINENO" 5
 fi
 ## -------------------- ##
 ## Main body of script. ##
@@ -2181,14 +2462,14 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
     TEA_VERSION="3.13"
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking TEA configuration" >&5
-$as_echo_n "checking TEA configuration... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking TEA configuration" >&5
+printf %s "checking TEA configuration... " >&6; }
     if test x"${PACKAGE_NAME}" = x ; then
        as_fn_error $? "
 The PACKAGE_NAME variable must be defined by your TEA configure.ac" "$LINENO" 5
     fi
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok (TEA ${TEA_VERSION})" >&5
-$as_echo "ok (TEA ${TEA_VERSION})" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ok (TEA ${TEA_VERSION})" >&5
+printf "%s\n" "ok (TEA ${TEA_VERSION})" >&6; }
 
     # If the user did not set CFLAGS, set it now to keep macros
     # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
@@ -2200,11 +2481,12 @@ $as_echo "ok (TEA ${TEA_VERSION})" >&6; }
        *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
            # Extract the first word of "cygpath", so it can be a program name with args.
 set dummy cygpath; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CYGPATH+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CYGPATH+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CYGPATH"; then
   ac_cv_prog_CYGPATH="$CYGPATH" # Let the user override the test.
 else
@@ -2212,11 +2494,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CYGPATH="cygpath -m"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2228,11 +2514,11 @@ fi
 fi
 CYGPATH=$ac_cv_prog_CYGPATH
 if test -n "$CYGPATH"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CYGPATH" >&5
-$as_echo "$CYGPATH" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CYGPATH" >&5
+printf "%s\n" "$CYGPATH" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2268,8 +2554,8 @@ fi
        exec_prefix=$prefix
     fi
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}" >&5
-$as_echo "$as_me: configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}" >&6;}
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}" >&5
+printf "%s\n" "$as_me: configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}" >&6;}
 
 
 
@@ -2298,11 +2584,12 @@ $as_echo "$as_me: configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}" >&6;}
     INSTALL_SCRIPT='${INSTALL} -m 755'
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking system version" >&5
-$as_echo_n "checking system version... " >&6; }
-if ${tcl_cv_sys_version+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking system version" >&5
+printf %s "checking system version... " >&6; }
+if test ${tcl_cv_sys_version+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
        # TEA specific:
        if test "${TEA_PLATFORM}" = "windows" ; then
@@ -2310,8 +2597,8 @@ else
        else
            tcl_cv_sys_version=`uname -s`-`uname -r`
            if test "$?" -ne 0 ; then
-               { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: can't find uname command" >&5
-$as_echo "$as_me: WARNING: can't find uname command" >&2;}
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: can't find uname command" >&5
+printf "%s\n" "$as_me: WARNING: can't find uname command" >&2;}
                tcl_cv_sys_version=unknown
            else
                if test "`uname -s`" = "AIX" ; then
@@ -2324,8 +2611,8 @@ $as_echo "$as_me: WARNING: can't find uname command" >&2;}
        fi
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_sys_version" >&5
-$as_echo "$tcl_cv_sys_version" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_sys_version" >&5
+printf "%s\n" "$tcl_cv_sys_version" >&6; }
     system=$tcl_cv_sys_version
 
     case $system in
@@ -2342,34 +2629,6 @@ $as_echo "$tcl_cv_sys_version" >&6; }
 
 
 
-ac_aux_dir=
-for ac_dir in tclconfig "$srcdir"/tclconfig; 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
-  as_fn_error $? "cannot find install-sh, install.sh, or shtool in tclconfig \"$srcdir\"/tclconfig" "$LINENO" 5
-fi
-
-# These three variables are undocumented and unsupported,
-# and are intended to be withdrawn in a future Autoconf release.
-# They can cause serious problems if a builder's source tree is in a directory
-# whose full name contains unusual characters.
-ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
-ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
-ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
-
 
 
 #--------------------------------------------------------------------
@@ -2389,15 +2648,17 @@ ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
        no_tcl=true
 
 # Check whether --with-tcl was given.
-if test "${with_tcl+set}" = set; then :
+if test ${with_tcl+y}
+then :
   withval=$with_tcl; with_tclconfig="${withval}"
 fi
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Tcl configuration" >&5
-$as_echo_n "checking for Tcl configuration... " >&6; }
-       if ${ac_cv_c_tclconfig+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for Tcl configuration" >&5
+printf %s "checking for Tcl configuration... " >&6; }
+       if test ${ac_cv_c_tclconfig+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
 
            # First check to see if --with-tcl was specified.
@@ -2405,8 +2666,8 @@ else
                case "${with_tclconfig}" in
                    */tclConfig.sh )
                        if test -f "${with_tclconfig}"; then
-                           { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: --with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself" >&5
-$as_echo "$as_me: WARNING: --with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself" >&2;}
+                           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: --with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself" >&5
+printf "%s\n" "$as_me: WARNING: --with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself" >&2;}
                            with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
                        fi ;;
                esac
@@ -2525,11 +2786,20 @@ fi
        else
            no_tcl=
            TCL_BIN_DIR="${ac_cv_c_tclconfig}"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: found ${TCL_BIN_DIR}/tclConfig.sh" >&5
-$as_echo "found ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found ${TCL_BIN_DIR}/tclConfig.sh" >&5
+printf "%s\n" "found ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        fi
     fi
 
+
+
+
+
+
+
+
+
+
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -2538,11 +2808,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -2550,11 +2821,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2565,11 +2840,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2578,11 +2853,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
 else
@@ -2590,11 +2866,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2605,11 +2885,11 @@ fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
   if test "x$ac_ct_CC" = x; then
@@ -2617,8 +2897,8 @@ fi
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     CC=$ac_ct_CC
@@ -2631,11 +2911,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -2643,11 +2924,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2658,11 +2943,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2671,11 +2956,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -2684,15 +2970,19 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+  if as_fn_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"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2708,18 +2998,18 @@ if test $ac_prog_rejected = yes; then
     # 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+' '}$@"
+    ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@"
   fi
 fi
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2730,11 +3020,12 @@ if test -z "$CC"; then
   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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -2742,11 +3033,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2757,11 +3052,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2774,11 +3069,12 @@ if test -z "$CC"; then
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
 else
@@ -2786,11 +3082,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -2801,11 +3101,11 @@ fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -2817,8 +3117,8 @@ done
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     CC=$ac_ct_CC
@@ -2826,25 +3126,129 @@ esac
 fi
 
 fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args.
+set dummy ${ac_tool_prefix}clang; ac_word=$2
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}clang"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
+else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+fi
 
 
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "clang", so it can be a program name with args.
+set dummy clang; ac_word=$2
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="clang"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
+else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+fi
+
+
+test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "no acceptable C compiler found in \$PATH
 See \`config.log' for more details" "$LINENO" 5; }
 
 # Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
 set X $ac_compile
 ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
+for ac_option in --version -v -V -qversion -version; do
   { { ac_try="$ac_compiler $ac_option >&5"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_compiler $ac_option >&5") 2>conftest.err
   ac_status=$?
   if test -s conftest.err; then
@@ -2854,7 +3258,7 @@ $as_echo "$ac_try_echo"; } >&5
     cat conftest.er1 >&5
   fi
   rm -f conftest.er1 conftest.err
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }
 done
 
@@ -2862,7 +3266,7 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
@@ -2874,9 +3278,9 @@ ac_clean_files="$ac_clean_files a.out a.out.dSYM 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.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+printf %s "checking whether the C compiler works... " >&6; }
+ac_link_default=`printf "%s\n" "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
 
 # The possible output files:
 ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
@@ -2897,11 +3301,12 @@ case "(($ac_try" in
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_link_default") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+then :
   # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
 # So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
 # in a Makefile.  We should not override ac_cv_exeext if it was cached,
@@ -2918,7 +3323,7 @@ do
        # certainly right.
        break;;
     *.* )
-       if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+       if test ${ac_cv_exeext+y} && test "$ac_cv_exeext" != no;
        then :; else
           ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
        fi
@@ -2934,44 +3339,46 @@ do
 done
 test "$ac_cv_exeext" = no && ac_cv_exeext=
 
-else
+else $as_nop
   ac_file=''
 fi
-if test -z "$ac_file"; then :
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
+if test -z "$ac_file"
+then :
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error 77 "C compiler cannot create executables
 See \`config.log' for more details" "$LINENO" 5; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+printf "%s\n" "yes" >&6; }
+fi
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+printf %s "checking for C compiler default output file name... " >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+printf "%s\n" "$ac_file" >&6; }
 ac_exeext=$ac_cv_exeext
 
 rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
 ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+printf %s "checking for suffix of executables... " >&6; }
 if { { ac_try="$ac_link"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_link") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+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
@@ -2985,15 +3392,15 @@ for ac_file in conftest.exe conftest conftest.*; do
     * ) break;;
   esac
 done
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+else $as_nop
+  { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of executables: cannot compile and link
 See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+printf "%s\n" "$ac_cv_exeext" >&6; }
 
 rm -f conftest.$ac_ext
 EXEEXT=$ac_cv_exeext
@@ -3002,7 +3409,7 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdio.h>
 int
-main ()
+main (void)
 {
 FILE *f = fopen ("conftest.out", "w");
  return ferror (f) || fclose (f) != 0;
@@ -3014,8 +3421,8 @@ _ACEOF
 ac_clean_files="$ac_clean_files conftest.out"
 # Check that the compiler produces executables we can run.  If not, either
 # the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+printf %s "checking whether we are cross compiling... " >&6; }
 if test "$cross_compiling" != yes; then
   { { ac_try="$ac_link"
 case "(($ac_try" in
@@ -3023,10 +3430,10 @@ case "(($ac_try" in
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_link") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }
   if { ac_try='./conftest$ac_cv_exeext'
   { { case "(($ac_try" in
@@ -3034,39 +3441,40 @@ $as_echo "$ac_try_echo"; } >&5
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_try") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }; }; then
     cross_compiling=no
   else
     if test "$cross_compiling" = maybe; then
        cross_compiling=yes
     else
-       { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
+       { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "cannot run C compiled programs.
 If you meant to cross compile, use \`--host'.
 See \`config.log' for more details" "$LINENO" 5; }
     fi
   fi
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+printf "%s\n" "$cross_compiling" >&6; }
 
 rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
 ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+printf %s "checking for suffix of object files... " >&6; }
+if test ${ac_cv_objext+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
@@ -3080,11 +3488,12 @@ case "(($ac_try" in
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_compile") 2>&5
   ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; then :
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+then :
   for ac_file in conftest.o conftest.obj conftest.*; do
   test -f "$ac_file" || continue;
   case $ac_file in
@@ -3093,31 +3502,32 @@ $as_echo "$ac_try_echo"; } >&5
        break;;
   esac
 done
-else
-  $as_echo "$as_me: failed program was:" >&5
+else $as_nop
+  printf "%s\n" "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of object files: cannot compile
 See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+printf "%s\n" "$ac_cv_objext" >&6; }
 OBJEXT=$ac_cv_objext
 ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5
+printf %s "checking whether the compiler supports GNU C... " >&6; }
+if test ${ac_cv_c_compiler_gnu+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 #ifndef __GNUC__
        choke me
@@ -3127,29 +3537,33 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_compiler_gnu=yes
-else
+else $as_nop
   ac_compiler_gnu=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 ac_cv_c_compiler_gnu=$ac_compiler_gnu
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; }
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
 if test $ac_compiler_gnu = yes; then
   GCC=yes
 else
   GCC=
 fi
-ac_test_CFLAGS=${CFLAGS+set}
+ac_test_CFLAGS=${CFLAGS+y}
 ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+printf %s "checking whether $CC accepts -g... " >&6; }
+if test ${ac_cv_prog_cc_g+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_save_c_werror_flag=$ac_c_werror_flag
    ac_c_werror_flag=yes
    ac_cv_prog_cc_g=no
@@ -3158,57 +3572,60 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_g=yes
-else
+else $as_nop
   CFLAGS=""
       cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
 
-else
+else $as_nop
   ac_c_werror_flag=$ac_save_c_werror_flag
         CFLAGS="-g"
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_g=yes
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
    ac_c_werror_flag=$ac_save_c_werror_flag
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+printf "%s\n" "$ac_cv_prog_cc_g" >&6; }
+if test $ac_test_CFLAGS; then
   CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
   if test "$GCC" = yes; then
@@ -3223,73 +3640,119 @@ else
     CFLAGS=
   fi
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_prog_cc_c89=no
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5
+printf %s "checking for $CC option to enable C11 features... " >&6; }
+if test ${ac_cv_prog_cc_c11+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c11=no
 ac_save_CC=$CC
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* 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 -std 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 -std.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+$ac_c_conftest_c11_program
+_ACEOF
+for ac_arg in '' -std=gnu11
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"
+then :
+  ac_cv_prog_cc_c11=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.beam
+  test "x$ac_cv_prog_cc_c11" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
 
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
-   inside strings and character constants.  */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+fi
+# AC_CACHE_VAL
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c11" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c11"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5
+printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c11" != xno
+then :
+  ac_prog_cc_stdc=c11
+                ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5
+printf %s "checking for $CC option to enable C99 features... " >&6; }
+if test ${ac_cv_prog_cc_c99+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c99=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$ac_c_conftest_c89_program
+_ACEOF
+for ac_arg in '' -std=gnu99 -std=c99 -c99 -AC99 -D_STDC_C99= -qlanglvl=extc1x -qlanglvl=extc99
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"
+then :
+  ac_cv_prog_cc_c99=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.beam
+  test "x$ac_cv_prog_cc_c99" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
 
-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;
-}
+fi
+# AC_CACHE_VAL
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c99" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c99"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5
+printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c99" != xno
+then :
+  ac_prog_cc_stdc=c99
+                   ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5
+printf %s "checking for $CC option to enable C89 features... " >&6; }
+if test ${ac_cv_prog_cc_c89+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$ac_c_conftest_c89_program
 _ACEOF
 for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
        -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC="$ac_save_CC $ac_arg"
-  if ac_fn_c_try_compile "$LINENO"; then :
+  if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_c89=$ac_arg
 fi
-rm -f core conftest.err conftest.$ac_objext
+rm -f core conftest.err conftest.$ac_objext conftest.beam
   test "x$ac_cv_prog_cc_c89" != "xno" && break
 done
 rm -f conftest.$ac_ext
@@ -3297,19 +3760,30 @@ CC=$ac_save_CC
 
 fi
 # AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
-  xno)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
-  *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c89" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c89"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } ;;
 esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
+if test "x$ac_cv_prog_cc_c89" != xno
+then :
+  ac_prog_cc_stdc=c89
+                      ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89
+else $as_nop
+  ac_prog_cc_stdc=no
+                      ac_cv_prog_cc_stdc=no
+fi
+
+fi
 
 fi
 
@@ -3321,22 +3795,18 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for existence of ${TCL_BIN_DIR}/tclConfig.sh" >&5
-$as_echo_n "checking for existence of ${TCL_BIN_DIR}/tclConfig.sh... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for existence of ${TCL_BIN_DIR}/tclConfig.sh" >&5
+printf %s "checking for existence of ${TCL_BIN_DIR}/tclConfig.sh... " >&6; }
 
     if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: loading" >&5
-$as_echo "loading" >&6; }
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: loading" >&5
+printf "%s\n" "loading" >&6; }
        . "${TCL_BIN_DIR}/tclConfig.sh"
     else
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: could not find ${TCL_BIN_DIR}/tclConfig.sh" >&5
-$as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: could not find ${TCL_BIN_DIR}/tclConfig.sh" >&5
+printf "%s\n" "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -3370,12 +3840,6 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
 
 
 
@@ -3389,14 +3853,14 @@ $as_echo "could not find ${TCL_BIN_DIR}/tclConfig.sh" >&6; }
 
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking platform" >&5
-$as_echo_n "checking platform... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking platform" >&5
+printf %s "checking platform... " >&6; }
     hold_cc=$CC; CC="$TCL_CC"
     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
            #ifdef _WIN32
@@ -3407,22 +3871,24 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
 
            # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
            TEA_PLATFORM="${TEA_PLATFORM-unix}"
            CYGPATH=echo
 
-else
+else $as_nop
 
            TEA_PLATFORM="windows"
            # Extract the first word of "cygpath", so it can be a program name with args.
 set dummy cygpath; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CYGPATH+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CYGPATH+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CYGPATH"; then
   ac_cv_prog_CYGPATH="$CYGPATH" # Let the user override the test.
 else
@@ -3430,11 +3896,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CYGPATH="cygpath -m"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3446,27 +3916,25 @@ fi
 fi
 CYGPATH=$ac_cv_prog_CYGPATH
 if test -n "$CYGPATH"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CYGPATH" >&5
-$as_echo "$CYGPATH" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CYGPATH" >&5
+printf "%s\n" "$CYGPATH" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
 
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
     CC=$hold_cc
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TEA_PLATFORM" >&5
-$as_echo "$TEA_PLATFORM" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $TEA_PLATFORM" >&5
+printf "%s\n" "$TEA_PLATFORM" >&6; }
 
     # The BUILD_$pkg is to define the correct extern storage class
     # handling when making this package
 
-cat >>confdefs.h <<_ACEOF
-#define BUILD_${PACKAGE_NAME} /**/
-_ACEOF
+printf "%s\n" "#define BUILD_${PACKAGE_NAME} /**/" >>confdefs.h
 
     # Do this here as we have fully defined TEA_PLATFORM now
     if test "${TEA_PLATFORM}" = "windows" ; then
@@ -3508,24 +3976,24 @@ fi
     if test "${prefix}" = "NONE"; then
        prefix_default=yes
        if test x"${TCL_PREFIX}" != x; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: --prefix defaulting to TCL_PREFIX ${TCL_PREFIX}" >&5
-$as_echo "$as_me: --prefix defaulting to TCL_PREFIX ${TCL_PREFIX}" >&6;}
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --prefix defaulting to TCL_PREFIX ${TCL_PREFIX}" >&5
+printf "%s\n" "$as_me: --prefix defaulting to TCL_PREFIX ${TCL_PREFIX}" >&6;}
            prefix=${TCL_PREFIX}
        else
-           { $as_echo "$as_me:${as_lineno-$LINENO}: --prefix defaulting to /usr/local" >&5
-$as_echo "$as_me: --prefix defaulting to /usr/local" >&6;}
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --prefix defaulting to /usr/local" >&5
+printf "%s\n" "$as_me: --prefix defaulting to /usr/local" >&6;}
            prefix=/usr/local
        fi
     fi
     if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
        -o x"${exec_prefix_default}" = x"yes" ; then
        if test x"${TCL_EXEC_PREFIX}" != x; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: --exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}" >&5
-$as_echo "$as_me: --exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}" >&6;}
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}" >&5
+printf "%s\n" "$as_me: --exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}" >&6;}
            exec_prefix=${TCL_EXEC_PREFIX}
        else
-           { $as_echo "$as_me:${as_lineno-$LINENO}: --exec-prefix defaulting to ${prefix}" >&5
-$as_echo "$as_me: --exec-prefix defaulting to ${prefix}" >&6;}
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: --exec-prefix defaulting to ${prefix}" >&5
+printf "%s\n" "$as_me: --exec-prefix defaulting to ${prefix}" >&6;}
            exec_prefix=$prefix
        fi
     fi
@@ -3550,11 +4018,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -3562,11 +4031,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3577,11 +4050,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -3590,11 +4063,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
 else
@@ -3602,11 +4076,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="gcc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3617,11 +4095,11 @@ fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
   if test "x$ac_ct_CC" = x; then
@@ -3629,8 +4107,8 @@ fi
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     CC=$ac_ct_CC
@@ -3643,11 +4121,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -3655,11 +4134,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3670,11 +4153,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -3683,11 +4166,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -3696,15 +4180,19 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+  if as_fn_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"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3720,18 +4208,18 @@ if test $ac_prog_rejected = yes; then
     # 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+' '}$@"
+    ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@"
   fi
 fi
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -3742,11 +4230,12 @@ if test -z "$CC"; then
   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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$CC"; then
   ac_cv_prog_CC="$CC" # Let the user override the test.
 else
@@ -3754,11 +4243,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3769,11 +4262,11 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -3786,11 +4279,12 @@ if test -z "$CC"; then
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_CC"; then
   ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
 else
@@ -3798,11 +4292,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -3813,11 +4311,11 @@ fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -3829,34 +4327,138 @@ done
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args.
+set dummy ${ac_tool_prefix}clang; ac_word=$2
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}clang"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+printf "%s\n" "$CC" >&6; }
+else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "clang", so it can be a program name with args.
+set dummy clang; ac_word=$2
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_CC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="clang"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+printf "%s\n" "$ac_ct_CC" >&6; }
+else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     CC=$ac_ct_CC
   fi
+else
+  CC="$ac_cv_prog_CC"
 fi
 
 fi
 
 
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "no acceptable C compiler found in \$PATH
 See \`config.log' for more details" "$LINENO" 5; }
 
 # Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
 set X $ac_compile
 ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
+for ac_option in --version -v -V -qversion -version; do
   { { ac_try="$ac_compiler $ac_option >&5"
 case "(($ac_try" in
   *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
   *) ac_try_echo=$ac_try;;
 esac
 eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
+printf "%s\n" "$ac_try_echo"; } >&5
   (eval "$ac_compiler $ac_option >&5") 2>conftest.err
   ac_status=$?
   if test -s conftest.err; then
@@ -3866,20 +4468,21 @@ $as_echo "$ac_try_echo"; } >&5
     cat conftest.er1 >&5
   fi
   rm -f conftest.er1 conftest.err
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
   test $ac_status = 0; }
 done
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5
+printf %s "checking whether the compiler supports GNU C... " >&6; }
+if test ${ac_cv_c_compiler_gnu+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 #ifndef __GNUC__
        choke me
@@ -3889,29 +4492,33 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_compiler_gnu=yes
-else
+else $as_nop
   ac_compiler_gnu=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 ac_cv_c_compiler_gnu=$ac_compiler_gnu
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; }
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
 if test $ac_compiler_gnu = yes; then
   GCC=yes
 else
   GCC=
 fi
-ac_test_CFLAGS=${CFLAGS+set}
+ac_test_CFLAGS=${CFLAGS+y}
 ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+printf %s "checking whether $CC accepts -g... " >&6; }
+if test ${ac_cv_prog_cc_g+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_save_c_werror_flag=$ac_c_werror_flag
    ac_c_werror_flag=yes
    ac_cv_prog_cc_g=no
@@ -3920,57 +4527,60 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_g=yes
-else
+else $as_nop
   CFLAGS=""
       cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
 
-else
+else $as_nop
   ac_c_werror_flag=$ac_save_c_werror_flag
         CFLAGS="-g"
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_g=yes
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
    ac_c_werror_flag=$ac_save_c_werror_flag
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+printf "%s\n" "$ac_cv_prog_cc_g" >&6; }
+if test $ac_test_CFLAGS; then
   CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
   if test "$GCC" = yes; then
@@ -3985,73 +4595,119 @@ else
     CFLAGS=
   fi
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_cv_prog_cc_c89=no
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5
+printf %s "checking for $CC option to enable C11 features... " >&6; }
+if test ${ac_cv_prog_cc_c11+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c11=no
 ac_save_CC=$CC
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* 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 -std 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 -std.  */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+$ac_c_conftest_c11_program
+_ACEOF
+for ac_arg in '' -std=gnu11
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"
+then :
+  ac_cv_prog_cc_c11=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.beam
+  test "x$ac_cv_prog_cc_c11" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
 
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
-   inside strings and character constants.  */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+fi
+# AC_CACHE_VAL
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c11" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c11"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5
+printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c11" != xno
+then :
+  ac_prog_cc_stdc=c11
+                ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5
+printf %s "checking for $CC option to enable C99 features... " >&6; }
+if test ${ac_cv_prog_cc_c99+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c99=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$ac_c_conftest_c89_program
+_ACEOF
+for ac_arg in '' -std=gnu99 -std=c99 -c99 -AC99 -D_STDC_C99= -qlanglvl=extc1x -qlanglvl=extc99
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"
+then :
+  ac_cv_prog_cc_c99=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.beam
+  test "x$ac_cv_prog_cc_c99" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
 
-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;
-}
+fi
+# AC_CACHE_VAL
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c99" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c99"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5
+printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c99" != xno
+then :
+  ac_prog_cc_stdc=c99
+                   ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5
+printf %s "checking for $CC option to enable C89 features... " >&6; }
+if test ${ac_cv_prog_cc_c89+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$ac_c_conftest_c89_program
 _ACEOF
 for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
        -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC="$ac_save_CC $ac_arg"
-  if ac_fn_c_try_compile "$LINENO"; then :
+  if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_prog_cc_c89=$ac_arg
 fi
-rm -f core conftest.err conftest.$ac_objext
+rm -f core conftest.err conftest.$ac_objext conftest.beam
   test "x$ac_cv_prog_cc_c89" != "xno" && break
 done
 rm -f conftest.$ac_ext
@@ -4059,19 +4715,30 @@ CC=$ac_save_CC
 
 fi
 # AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
-  x)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
-  xno)
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
-  *)
-    CC="$CC $ac_cv_prog_cc_c89"
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+ac_prog_cc_stdc_options=
+case "x$ac_cv_prog_cc_c89" in #(
+  x) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+printf "%s\n" "none needed" >&6; } ;; #(
+  xno) :
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+printf "%s\n" "unsupported" >&6; } ;; #(
+  *) :
+    ac_prog_cc_stdc_options=" $ac_cv_prog_cc_c89"
+    CC="$CC$ac_prog_cc_stdc_options"
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } ;;
 esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
+if test "x$ac_cv_prog_cc_c89" != xno
+then :
+  ac_prog_cc_stdc=c89
+                      ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89
+else $as_nop
+  ac_prog_cc_stdc=no
+                      ac_cv_prog_cc_stdc=no
+fi
+
+fi
 
 fi
 
@@ -4086,40 +4753,36 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+printf %s "checking how to run the C preprocessor... " >&6; }
 # On Suns, sometimes $CPP names a directory.
 if test -n "$CPP" && test -d "$CPP"; then
   CPP=
 fi
 if test -z "$CPP"; then
-  if ${ac_cv_prog_CPP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-      # Double quotes because CPP needs to be expanded
-    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+  if test ${ac_cv_prog_CPP+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+      # Double quotes because $CC needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" 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 confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
+#include <limits.h>
                     Syntax error
 _ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
+if ac_fn_c_try_cpp "$LINENO"
+then :
 
-else
+else $as_nop
   # Broken: fails on valid input.
 continue
 fi
@@ -4131,10 +4794,11 @@ rm -f conftest.err conftest.i conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
+if ac_fn_c_try_cpp "$LINENO"
+then :
   # Broken: success on invalid input.
 continue
-else
+else $as_nop
   # Passes both tests.
 ac_preproc_ok=:
 break
@@ -4144,7 +4808,8 @@ rm -f conftest.err conftest.i conftest.$ac_ext
 done
 # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
 rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
+if $ac_preproc_ok
+then :
   break
 fi
 
@@ -4156,29 +4821,24 @@ fi
 else
   ac_cv_prog_CPP=$CPP
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+printf "%s\n" "$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 confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
+#include <limits.h>
                     Syntax error
 _ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
+if ac_fn_c_try_cpp "$LINENO"
+then :
 
-else
+else $as_nop
   # Broken: fails on valid input.
 continue
 fi
@@ -4190,10 +4850,11 @@ rm -f conftest.err conftest.i conftest.$ac_ext
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
+if ac_fn_c_try_cpp "$LINENO"
+then :
   # Broken: success on invalid input.
 continue
-else
+else $as_nop
   # Passes both tests.
 ac_preproc_ok=:
 break
@@ -4203,11 +4864,12 @@ rm -f conftest.err conftest.i conftest.$ac_ext
 done
 # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
 rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
+if $ac_preproc_ok
+then :
 
-else
-  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+else $as_nop
+  { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
 See \`config.log' for more details" "$LINENO" 5; }
 fi
@@ -4223,13 +4885,14 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
     # Checks to see if the make program sets the $MAKE variable.
     #--------------------------------------------------------------------
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+printf %s "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
 set x ${MAKE-make}
-ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
-if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+ac_make=`printf "%s\n" "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if eval test \${ac_cv_prog_make_${ac_make}_set+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat >conftest.make <<\_ACEOF
 SHELL = /bin/sh
 all:
@@ -4245,380 +4908,159 @@ esac
 rm -f conftest.make
 fi
 if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+printf "%s\n" "yes" >&6; }
   SET_MAKE=
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
 
-    #--------------------------------------------------------------------
-    # Find ranlib
-    #--------------------------------------------------------------------
-
-    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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&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_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&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_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_RANLIB="ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-  if test "x$ac_ct_RANLIB" = x; then
-    RANLIB=""
-  else
-    case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
-    RANLIB=$ac_ct_RANLIB
-  fi
-else
-  RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-
-    #--------------------------------------------------------------------
-    # Determines the correct binary file extension (.o, .obj, .exe etc.)
-    #--------------------------------------------------------------------
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -z "$GREP"; then
-  ac_path_GREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_prog in grep ggrep; do
-    for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_GREP" || continue
-# Check for GNU ac_path_GREP and select it if it is found.
-  # Check for GNU $ac_path_GREP
-case `"$ac_path_GREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'GREP' >> "conftest.nl"
-    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_GREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_GREP="$ac_path_GREP"
-      ac_path_GREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_GREP_found && break 3
-    done
-  done
-  done
-IFS=$as_save_IFS
-  if test -z "$ac_cv_path_GREP"; then
-    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_GREP=$GREP
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
-$as_echo "$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
+    #--------------------------------------------------------------------
+    # Find ranlib
+    #--------------------------------------------------------------------
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
-$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
-  $as_echo_n "(cached) " >&6
+    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
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_RANLIB+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  if test -n "$RANLIB"; then
+  ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
 else
-  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
-   then ac_cv_path_EGREP="$GREP -E"
-   else
-     if test -z "$EGREP"; then
-  ac_path_EGREP_found=false
-  # Loop through the user's path and test for each of PROGNAME-LIST
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+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_prog in egrep; do
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
-      as_fn_executable_p "$ac_path_EGREP" || continue
-# Check for GNU ac_path_EGREP and select it if it is found.
-  # Check for GNU $ac_path_EGREP
-case `"$ac_path_EGREP" --version 2>&1` in
-*GNU*)
-  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
-*)
-  ac_count=0
-  $as_echo_n 0123456789 >"conftest.in"
-  while :
-  do
-    cat "conftest.in" "conftest.in" >"conftest.tmp"
-    mv "conftest.tmp" "conftest.in"
-    cp "conftest.in" "conftest.nl"
-    $as_echo 'EGREP' >> "conftest.nl"
-    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
-    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
-    as_fn_arith $ac_count + 1 && ac_count=$as_val
-    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
-      # Best one so far, save it but keep looking for a better one
-      ac_cv_path_EGREP="$ac_path_EGREP"
-      ac_path_EGREP_max=$ac_count
-    fi
-    # 10*(2^10) chars as input seems more than enough
-    test $ac_count -gt 10 && break
-  done
-  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
-      $ac_path_EGREP_found && break 3
-    done
-  done
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
   done
 IFS=$as_save_IFS
-  if test -z "$ac_cv_path_EGREP"; then
-    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
-  fi
-else
-  ac_cv_path_EGREP=$EGREP
-fi
 
-   fi
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
-$as_echo "$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
+fi
+RANLIB=$ac_cv_prog_RANLIB
+if test -n "$RANLIB"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
+printf "%s\n" "$RANLIB" >&6; }
+else
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
+fi
 
 
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
-  $as_echo_n "(cached) " >&6
+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
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_RANLIB+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  if test -n "$ac_ct_RANLIB"; then
+  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
 else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_RANLIB="ranlib"
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
 
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_header_stdc=yes
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
+printf "%s\n" "$ac_ct_RANLIB" >&6; }
 else
-  ac_cv_header_stdc=no
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
-rm -f core 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 confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then :
 
+  if test "x$ac_ct_RANLIB" = x; then
+    RANLIB=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    RANLIB=$ac_ct_RANLIB
+  fi
 else
-  ac_cv_header_stdc=no
+  RANLIB="$ac_cv_prog_RANLIB"
 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 confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <stdlib.h>
+    #--------------------------------------------------------------------
+    # Determines the correct binary file extension (.o, .obj, .exe etc.)
+    #--------------------------------------------------------------------
 
-_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 confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-#include <ctype.h>
-#include <stdlib.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
+ac_header= ac_cache=
+for ac_item in $ac_header_c_list
+do
+  if test $ac_cache; then
+    ac_fn_c_check_header_compile "$LINENO" $ac_header ac_cv_header_$ac_cache "$ac_includes_default"
+    if eval test \"x\$ac_cv_header_$ac_cache\" = xyes; then
+      printf "%s\n" "#define $ac_item 1" >> confdefs.h
+    fi
+    ac_header= ac_cache=
+  elif test $ac_header; then
+    ac_cache=$ac_item
+  else
+    ac_header=$ac_item
+  fi
+done
 
-#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))
-      return 2;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
 
-else
-  ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
 
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
 
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
 
-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=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
-"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
 
-fi
 
-done
+if test $ac_cv_header_stdlib_h = yes && test $ac_cv_header_string_h = yes
+then :
 
+printf "%s\n" "#define STDC_HEADERS 1" >>confdefs.h
 
+fi
 
     # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
 
@@ -4629,34 +5071,36 @@ done
     #------------------------------------------------------------------------
 
     if test -z "$no_pipe" -a -n "$GCC"; then
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the compiler understands -pipe" >&5
-$as_echo_n "checking if the compiler understands -pipe... " >&6; }
-if ${tcl_cv_cc_pipe+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if the compiler understands -pipe" >&5
+printf %s "checking if the compiler understands -pipe... " >&6; }
+if test ${tcl_cv_cc_pipe+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
            hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_cc_pipe=yes
-else
+else $as_nop
   tcl_cv_cc_pipe=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
            CFLAGS=$hold_cflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_pipe" >&5
-$as_echo "$tcl_cv_cc_pipe" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_pipe" >&5
+printf "%s\n" "$tcl_cv_cc_pipe" >&6; }
        if test $tcl_cv_cc_pipe = yes; then
            CFLAGS="$CFLAGS -pipe"
        fi
@@ -4666,11 +5110,12 @@ $as_echo "$tcl_cv_cc_pipe" >&6; }
     # Common compiler flag setup
     #--------------------------------------------------------------------
 
-     { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
-$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+     { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
+printf %s "checking whether byte ordering is bigendian... " >&6; }
+if test ${ac_cv_c_bigendian+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_cv_c_bigendian=unknown
     # See if we're dealing with a universal compiler.
     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -4681,7 +5126,8 @@ else
             typedef int dummy;
 
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
 
        # Check for potential -arch flags.  It is not universal unless
        # there are at least two -arch flags with different values.
@@ -4705,7 +5151,7 @@ if ac_fn_c_try_compile "$LINENO"; then :
         fi
        done
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
     if test $ac_cv_c_bigendian = unknown; then
       # See if sys/param.h defines the BYTE_ORDER macro.
       cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -4714,7 +5160,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
             #include <sys/param.h>
 
 int
-main ()
+main (void)
 {
 #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \
                     && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \
@@ -4726,7 +5172,8 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   # It does; now see whether it defined to BIG_ENDIAN or not.
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
@@ -4734,7 +5181,7 @@ if ac_fn_c_try_compile "$LINENO"; then :
                #include <sys/param.h>
 
 int
-main ()
+main (void)
 {
 #if BYTE_ORDER != BIG_ENDIAN
                 not big endian
@@ -4744,14 +5191,15 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_c_bigendian=yes
-else
+else $as_nop
   ac_cv_c_bigendian=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
     fi
     if test $ac_cv_c_bigendian = unknown; then
       # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
@@ -4760,7 +5208,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 #include <limits.h>
 
 int
-main ()
+main (void)
 {
 #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
              bogus endian macros
@@ -4770,14 +5218,15 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   # It does; now see whether it defined to _BIG_ENDIAN or not.
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <limits.h>
 
 int
-main ()
+main (void)
 {
 #ifndef _BIG_ENDIAN
                 not big endian
@@ -4787,31 +5236,33 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_c_bigendian=yes
-else
+else $as_nop
   ac_cv_c_bigendian=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
     fi
     if test $ac_cv_c_bigendian = unknown; then
       # Compile a test program.
-      if test "$cross_compiling" = yes; then :
+      if test "$cross_compiling" = yes
+then :
   # Try to guess by grepping values from an object file.
         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
-short int ascii_mm[] =
+unsigned short int ascii_mm[] =
                  { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
-               short int ascii_ii[] =
+               unsigned short int ascii_ii[] =
                  { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
                int use_ascii (int i) {
                  return ascii_mm[i] + ascii_ii[i];
                }
-               short int ebcdic_ii[] =
+               unsigned short int ebcdic_ii[] =
                  { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
-               short int ebcdic_mm[] =
+               unsigned short int ebcdic_mm[] =
                  { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
                int use_ebcdic (int i) {
                  return ebcdic_mm[i] + ebcdic_ii[i];
@@ -4819,14 +5270,15 @@ short int ascii_mm[] =
                extern int foo;
 
 int
-main ()
+main (void)
 {
 return use_ascii (foo) == use_ebcdic (foo);
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then
              ac_cv_c_bigendian=yes
            fi
@@ -4839,13 +5291,13 @@ if ac_fn_c_try_compile "$LINENO"; then :
              fi
            fi
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
 int
-main ()
+main (void)
 {
 
             /* Are we little or big endian?  From Harbison&Steele.  */
@@ -4861,9 +5313,10 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
+if ac_fn_c_try_run "$LINENO"
+then :
   ac_cv_c_bigendian=no
-else
+else $as_nop
   ac_cv_c_bigendian=yes
 fi
 rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
@@ -4872,17 +5325,17 @@ fi
 
     fi
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
-$as_echo "$ac_cv_c_bigendian" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
+printf "%s\n" "$ac_cv_c_bigendian" >&6; }
  case $ac_cv_c_bigendian in #(
    yes)
-     $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h
+     printf "%s\n" "#define WORDS_BIGENDIAN 1" >>confdefs.h
 ;; #(
    no)
       ;; #(
    universal)
 
-$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
+printf "%s\n" "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
 
      ;; #(
    *)
@@ -4900,7 +5353,8 @@ $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
 
 
 # Check whether --with-gdbm was given.
-if test "${with_gdbm+set}" = set; then :
+if test ${with_gdbm+y}
+then :
   withval=$with_gdbm; \
        with_gdbm=${withval}
 fi
@@ -4908,20 +5362,21 @@ fi
 
     if test x"${with_gdbm}" != x -a "${with_gdbm}" != no; then
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU gdbm library" >&5
-$as_echo_n "checking for GNU gdbm library... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU gdbm library" >&5
+printf %s "checking for GNU gdbm library... " >&6; }
 
-    if ${ac_cv_c_gdbm+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${ac_cv_c_gdbm+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
     if test x"${with_gdbm}" != x -a "${with_gdbm}" != "yes"; then
         if test -f "${with_gdbm}/gdbm.h" -a x"`ls ${with_gdbm}/libgdbm* 2>/dev/null`" != x; then
             ac_cv_c_gdbm=`(cd ${with_gdbm}; pwd)`
             gincdir=$ac_cv_c_gdbm
             glibdir=$ac_cv_c_gdbm
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: found in $glibdir" >&5
-$as_echo "found in $glibdir" >&6; }
+            { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found in $glibdir" >&5
+printf "%s\n" "found in $glibdir" >&6; }
         else
             as_fn_error $? "${with_gdbm} directory doesn't contain gdbm library" "$LINENO" 5
         fi
@@ -4934,7 +5389,8 @@ fi
                 `ls -d ${exec_prefix}/lib 2>/dev/null`\
                 `ls -d ${prefix}/lib 2>/dev/null`\
                 `ls -d /usr/local/lib 2>/dev/null`\
-                `ls -d /usr/lib 2>/dev/null` ; do
+                `ls -d /usr/lib 2>/dev/null`\
+                `ls -d /usr/lib/x86_64-linux-gnu 2>/dev/null` ; do
             if test x"`ls $i/libgdbm* 2>/dev/null`" != x ; then
                 glibdir=`(cd $i; pwd)`
                 break
@@ -4952,9 +5408,9 @@ fi
         if test x"$glibdir" = x -o x"$gincdir" = x ; then
             as_fn_error $? "none found" "$LINENO" 5
         else
-            { $as_echo "$as_me:${as_lineno-$LINENO}: result: found in $glibdir, includes in $gincdir" >&5
-$as_echo "found in $glibdir, includes in $gincdir" >&6; }
-            $as_echo "#define HAVE_GDBM 1" >>confdefs.h
+            { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found in $glibdir, includes in $gincdir" >&5
+printf "%s\n" "found in $glibdir, includes in $gincdir" >&6; }
+            printf "%s\n" "#define HAVE_GDBM 1" >>confdefs.h
 
             GDBM_CFLAGS="-I\"$gincdir\""
             GDBM_LIBS="-L\"$glibdir\" -lgdbm"
@@ -4971,25 +5427,27 @@ $as_echo "found in $glibdir, includes in $gincdir" >&6; }
 
 
 # Check whether --with-lmdb was given.
-if test "${with_lmdb+set}" = set; then :
+if test ${with_lmdb+y}
+then :
   withval=$with_lmdb; with_lmdb=${withval}
 fi
 
 
     if test x"${with_lmdb}" != "x" -a "${with_lmdb}" != no; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for LMDB library" >&5
-$as_echo_n "checking for LMDB library... " >&6; }
-        if ${ac_cv_c_lmdb+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for LMDB library" >&5
+printf %s "checking for LMDB library... " >&6; }
+        if test ${ac_cv_c_lmdb+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
         if test x"${with_lmdb}" != x -a "${with_lmdb}" != "yes"; then
             if test -f "${with_lmdb}/lmdb.h" -a x"`ls ${with_lmdb}/liblmdb* 2>/dev/null`" != x; then
                 ac_cv_c_lmdb=`(cd ${with_lmdb}; pwd)`
                 lincdir=$ac_cv_c_lmdb
                 llibdir=$ac_cv_c_lmdb
-                { $as_echo "$as_me:${as_lineno-$LINENO}: result: found in $llibdir" >&5
-$as_echo "found in $llibdir" >&6; }
+                { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found in $llibdir" >&5
+printf "%s\n" "found in $llibdir" >&6; }
             else
                 as_fn_error $? "${with_lmdb} directory doesn't contain lmdb library" "$LINENO" 5
             fi
@@ -5002,7 +5460,8 @@ fi
                     `ls -d ${exec_prefix}/lib 2>/dev/null`\
                     `ls -d ${prefix}/lib 2>/dev/null`\
                     `ls -d /usr/local/lib 2>/dev/null`\
-                    `ls -d /usr/lib 2>/dev/null` ; do
+                    `ls -d /usr/lib 2>/dev/null`\
+                    `ls -d /usr/lib/x86_64-linux-gnu 2>/dev/null` ; do
                 if test x"`ls $i/liblmdb* 2>/dev/null`" != x ; then
                     llibdir=`(cd $i; pwd)`
                     break
@@ -5020,9 +5479,9 @@ fi
             if test x"$llibdir" = x -o x"$lincdir" = x ; then
                 as_fn_error $? "none found" "$LINENO" 5
             else
-                { $as_echo "$as_me:${as_lineno-$LINENO}: result: found in $llibdir, includes in $lincdir" >&5
-$as_echo "found in $llibdir, includes in $lincdir" >&6; }
-                $as_echo "#define HAVE_LMDB 1" >>confdefs.h
+                { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found in $llibdir, includes in $lincdir" >&5
+printf "%s\n" "found in $llibdir, includes in $lincdir" >&6; }
+                printf "%s\n" "#define HAVE_LMDB 1" >>confdefs.h
 
                 LMDB_CFLAGS="-I\"$lincdir\""
                 LMDB_LIBS="-L\"$llibdir\" -llmdb"
@@ -5037,19 +5496,21 @@ $as_echo "found in $llibdir, includes in $lincdir" >&6; }
 #--------------------------------------------------------------------
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for NaviServer/AOLserver configuration" >&5
-$as_echo_n "checking for NaviServer/AOLserver configuration... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for NaviServer/AOLserver configuration" >&5
+printf %s "checking for NaviServer/AOLserver configuration... " >&6; }
 
 # Check whether --with-naviserver was given.
-if test "${with_naviserver+set}" = set; then :
+if test ${with_naviserver+y}
+then :
   withval=$with_naviserver; \
     with_naviserver=${withval}
 fi
 
 
-    if ${ac_cv_c_naviserver+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${ac_cv_c_naviserver+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
     if test x"${with_naviserver}" != x ; then
         if test -f "${with_naviserver}/include/ns.h" ; then
@@ -5062,12 +5523,12 @@ else
 fi
 
     if test x"${ac_cv_c_naviserver}" = x ; then
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: none found" >&5
-$as_echo "none found" >&6; }
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none found" >&5
+printf "%s\n" "none found" >&6; }
     else
         NS_DIR=${ac_cv_c_naviserver}
-        { $as_echo "$as_me:${as_lineno-$LINENO}: result: found NaviServer/AOLserver in $NS_DIR" >&5
-$as_echo "found NaviServer/AOLserver in $NS_DIR" >&6; }
+        { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: found NaviServer/AOLserver in $NS_DIR" >&5
+printf "%s\n" "found NaviServer/AOLserver in $NS_DIR" >&6; }
         NS_INCLUDES="-I\"${NS_DIR}/include\""
         if test "`uname -s`" = Darwin ; then
             aollibs=`ls ${NS_DIR}/lib/libns* 2>/dev/null`
@@ -5075,7 +5536,7 @@ $as_echo "found NaviServer/AOLserver in $NS_DIR" >&6; }
                 NS_LIBS="-L\"${NS_DIR}/lib\" -lnsd -lnsthread"
             fi
         fi
-        $as_echo "#define NS_AOLSERVER 1" >>confdefs.h
+        printf "%s\n" "#define NS_AOLSERVER 1" >>confdefs.h
 
     fi
 
@@ -5159,7 +5620,7 @@ $as_echo "found NaviServer/AOLserver in $NS_DIR" >&6; }
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -5275,19 +5736,21 @@ fi
 #--------------------------------------------------------------------
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Tcl public headers" >&5
-$as_echo_n "checking for Tcl public headers... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for Tcl public headers" >&5
+printf %s "checking for Tcl public headers... " >&6; }
 
 
 # Check whether --with-tclinclude was given.
-if test "${with_tclinclude+set}" = set; then :
+if test ${with_tclinclude+y}
+then :
   withval=$with_tclinclude; with_tclinclude=${withval}
 fi
 
 
-    if ${ac_cv_c_tclh+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${ac_cv_c_tclh+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
        # Use the value from --with-tclinclude, if it was given
 
@@ -5346,8 +5809,8 @@ fi
     if test x"${ac_cv_c_tclh}" = x ; then
        as_fn_error $? "tcl.h not found.  Please specify its location with --with-tclinclude" "$LINENO" 5
     else
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${ac_cv_c_tclh}" >&5
-$as_echo "${ac_cv_c_tclh}" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${ac_cv_c_tclh}" >&5
+printf "%s\n" "${ac_cv_c_tclh}" >&6; }
     fi
 
     # Convert to a native path and substitute into the output files.
@@ -5371,9 +5834,10 @@ $as_echo "${ac_cv_c_tclh}" >&6; }
 
 
     # Check whether --enable-threads was given.
-if test "${enable_threads+set}" = set; then :
+if test ${enable_threads+y}
+then :
   enableval=$enable_threads; tcl_ok=$enableval
-else
+else $as_nop
   tcl_ok=yes
 fi
 
@@ -5394,24 +5858,25 @@ fi
            # USE_THREAD_ALLOC tells us to try the special thread-based
            # allocator that significantly reduces lock contention
 
-$as_echo "#define USE_THREAD_ALLOC 1" >>confdefs.h
+printf "%s\n" "#define USE_THREAD_ALLOC 1" >>confdefs.h
 
 
-$as_echo "#define _REENTRANT 1" >>confdefs.h
+printf "%s\n" "#define _REENTRANT 1" >>confdefs.h
 
            if test "`uname -s`" = "SunOS" ; then
 
-$as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
+printf "%s\n" "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
 
            fi
 
-$as_echo "#define _THREAD_SAFE 1" >>confdefs.h
+printf "%s\n" "#define _THREAD_SAFE 1" >>confdefs.h
 
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lpthread" >&5
-$as_echo_n "checking for pthread_mutex_init in -lpthread... " >&6; }
-if ${ac_cv_lib_pthread_pthread_mutex_init+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lpthread" >&5
+printf %s "checking for pthread_mutex_init in -lpthread... " >&6; }
+if test ${ac_cv_lib_pthread_pthread_mutex_init+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lpthread  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5420,32 +5885,31 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char pthread_mutex_init ();
 int
-main ()
+main (void)
 {
 return pthread_mutex_init ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_pthread_pthread_mutex_init=yes
-else
+else $as_nop
   ac_cv_lib_pthread_pthread_mutex_init=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_mutex_init" >&5
-$as_echo "$ac_cv_lib_pthread_pthread_mutex_init" >&6; }
-if test "x$ac_cv_lib_pthread_pthread_mutex_init" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_mutex_init" >&5
+printf "%s\n" "$ac_cv_lib_pthread_pthread_mutex_init" >&6; }
+if test "x$ac_cv_lib_pthread_pthread_mutex_init" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
@@ -5455,11 +5919,12 @@ fi
                # defined.  We could alternatively do an AC_TRY_COMPILE with
                # pthread.h, but that will work with libpthread really doesn't
                # exist, like AIX 4.2.  [Bug: 4359]
-               { $as_echo "$as_me:${as_lineno-$LINENO}: checking for __pthread_mutex_init in -lpthread" >&5
-$as_echo_n "checking for __pthread_mutex_init in -lpthread... " >&6; }
-if ${ac_cv_lib_pthread___pthread_mutex_init+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for __pthread_mutex_init in -lpthread" >&5
+printf %s "checking for __pthread_mutex_init in -lpthread... " >&6; }
+if test ${ac_cv_lib_pthread___pthread_mutex_init+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lpthread  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5468,32 +5933,31 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char __pthread_mutex_init ();
 int
-main ()
+main (void)
 {
 return __pthread_mutex_init ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_pthread___pthread_mutex_init=yes
-else
+else $as_nop
   ac_cv_lib_pthread___pthread_mutex_init=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_mutex_init" >&5
-$as_echo "$ac_cv_lib_pthread___pthread_mutex_init" >&6; }
-if test "x$ac_cv_lib_pthread___pthread_mutex_init" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread___pthread_mutex_init" >&5
+printf "%s\n" "$ac_cv_lib_pthread___pthread_mutex_init" >&6; }
+if test "x$ac_cv_lib_pthread___pthread_mutex_init" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
@@ -5503,11 +5967,12 @@ fi
                # The space is needed
                THREADS_LIBS=" -lpthread"
            else
-               { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lpthreads" >&5
-$as_echo_n "checking for pthread_mutex_init in -lpthreads... " >&6; }
-if ${ac_cv_lib_pthreads_pthread_mutex_init+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lpthreads" >&5
+printf %s "checking for pthread_mutex_init in -lpthreads... " >&6; }
+if test ${ac_cv_lib_pthreads_pthread_mutex_init+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lpthreads  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5516,32 +5981,31 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char pthread_mutex_init ();
 int
-main ()
+main (void)
 {
 return pthread_mutex_init ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_pthreads_pthread_mutex_init=yes
-else
+else $as_nop
   ac_cv_lib_pthreads_pthread_mutex_init=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_mutex_init" >&5
-$as_echo "$ac_cv_lib_pthreads_pthread_mutex_init" >&6; }
-if test "x$ac_cv_lib_pthreads_pthread_mutex_init" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreads_pthread_mutex_init" >&5
+printf "%s\n" "$ac_cv_lib_pthreads_pthread_mutex_init" >&6; }
+if test "x$ac_cv_lib_pthreads_pthread_mutex_init" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
@@ -5549,11 +6013,12 @@ fi
                    # The space is needed
                    THREADS_LIBS=" -lpthreads"
                else
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lc" >&5
-$as_echo_n "checking for pthread_mutex_init in -lc... " >&6; }
-if ${ac_cv_lib_c_pthread_mutex_init+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lc" >&5
+printf %s "checking for pthread_mutex_init in -lc... " >&6; }
+if test ${ac_cv_lib_c_pthread_mutex_init+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lc  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5562,41 +6027,41 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char pthread_mutex_init ();
 int
-main ()
+main (void)
 {
 return pthread_mutex_init ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_c_pthread_mutex_init=yes
-else
+else $as_nop
   ac_cv_lib_c_pthread_mutex_init=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_pthread_mutex_init" >&5
-$as_echo "$ac_cv_lib_c_pthread_mutex_init" >&6; }
-if test "x$ac_cv_lib_c_pthread_mutex_init" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_pthread_mutex_init" >&5
+printf "%s\n" "$ac_cv_lib_c_pthread_mutex_init" >&6; }
+if test "x$ac_cv_lib_c_pthread_mutex_init" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
                    if test "$tcl_ok" = "no"; then
-                       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lc_r" >&5
-$as_echo_n "checking for pthread_mutex_init in -lc_r... " >&6; }
-if ${ac_cv_lib_c_r_pthread_mutex_init+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for pthread_mutex_init in -lc_r" >&5
+printf %s "checking for pthread_mutex_init in -lc_r... " >&6; }
+if test ${ac_cv_lib_c_r_pthread_mutex_init+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lc_r  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5605,32 +6070,31 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char pthread_mutex_init ();
 int
-main ()
+main (void)
 {
 return pthread_mutex_init ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_c_r_pthread_mutex_init=yes
-else
+else $as_nop
   ac_cv_lib_c_r_pthread_mutex_init=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_mutex_init" >&5
-$as_echo "$ac_cv_lib_c_r_pthread_mutex_init" >&6; }
-if test "x$ac_cv_lib_c_r_pthread_mutex_init" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_r_pthread_mutex_init" >&5
+printf "%s\n" "$ac_cv_lib_c_r_pthread_mutex_init" >&6; }
+if test "x$ac_cv_lib_c_r_pthread_mutex_init" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
@@ -5639,8 +6103,8 @@ fi
                            THREADS_LIBS=" -pthread"
                        else
                            TCL_THREADS=0
-                           { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Do not know how to find pthread lib on your system - thread support disabled" >&5
-$as_echo "$as_me: WARNING: Do not know how to find pthread lib on your system - thread support disabled" >&2;}
+                           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Do not know how to find pthread lib on your system - thread support disabled" >&5
+printf "%s\n" "$as_me: WARNING: Do not know how to find pthread lib on your system - thread support disabled" >&2;}
                        fi
                    fi
                fi
@@ -5650,27 +6114,27 @@ $as_echo "$as_me: WARNING: Do not know how to find pthread lib on your system -
        TCL_THREADS=0
     fi
     # Do checking message here to not mess up interleaved configure output
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for building with threads" >&5
-$as_echo_n "checking for building with threads... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for building with threads" >&5
+printf %s "checking for building with threads... " >&6; }
     if test "${TCL_THREADS}" = 1; then
 
-$as_echo "#define TCL_THREADS 1" >>confdefs.h
+printf "%s\n" "#define TCL_THREADS 1" >>confdefs.h
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes (default)" >&5
-$as_echo "yes (default)" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes (default)" >&5
+printf "%s\n" "yes (default)" >&6; }
     else
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
     fi
     # TCL_THREADS sanity checking.  See if our request for building with
     # threads is the same as the way Tcl was built.  If not, warn the user.
     case ${TCL_DEFS} in
        *THREADS=1*)
            if test "${TCL_THREADS}" = "0"; then
-               { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING:
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING:
     Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
     that IS thread-enabled.  It is recommended to use --enable-threads." >&5
-$as_echo "$as_me: WARNING:
+printf "%s\n" "$as_me: WARNING:
     Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
     that IS thread-enabled.  It is recommended to use --enable-threads." >&2;}
            fi
@@ -5685,12 +6149,13 @@ $as_echo "$as_me: WARNING:
 #--------------------------------------------------------------------
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to build libraries" >&5
-$as_echo_n "checking how to build libraries... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to build libraries" >&5
+printf %s "checking how to build libraries... " >&6; }
     # Check whether --enable-shared was given.
-if test "${enable_shared+set}" = set; then :
+if test ${enable_shared+y}
+then :
   enableval=$enable_shared; shared_ok=$enableval
-else
+else $as_nop
   shared_ok=yes
 fi
 
@@ -5703,9 +6168,10 @@ fi
     fi
 
     # Check whether --enable-stubs was given.
-if test "${enable_stubs+set}" = set; then :
+if test ${enable_stubs+y}
+then :
   enableval=$enable_stubs; stubs_ok=$enableval
-else
+else $as_nop
   stubs_ok=yes
 fi
 
@@ -5719,16 +6185,16 @@ fi
 
     # Stubs are always enabled for shared builds
     if test "$shared_ok" = "yes" ; then
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: shared" >&5
-$as_echo "shared" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: shared" >&5
+printf "%s\n" "shared" >&6; }
        SHARED_BUILD=1
         STUBS_BUILD=1
     else
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: static" >&5
-$as_echo "static" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: static" >&5
+printf "%s\n" "static" >&6; }
        SHARED_BUILD=0
 
-$as_echo "#define STATIC_BUILD 1" >>confdefs.h
+printf "%s\n" "#define STATIC_BUILD 1" >>confdefs.h
 
         if test "$stubs_ok" = "yes" ; then
           STUBS_BUILD=1
@@ -5738,14 +6204,14 @@ $as_echo "#define STATIC_BUILD 1" >>confdefs.h
     fi
     if test "${STUBS_BUILD}" = "1" ; then
 
-$as_echo "#define USE_TCL_STUBS 1" >>confdefs.h
+printf "%s\n" "#define USE_TCL_STUBS 1" >>confdefs.h
 
 
-$as_echo "#define USE_TCLOO_STUBS 1" >>confdefs.h
+printf "%s\n" "#define USE_TCLOO_STUBS 1" >>confdefs.h
 
       if test "${TEA_WINDOWINGSYSTEM}" != ""; then
 
-$as_echo "#define USE_TK_STUBS 1" >>confdefs.h
+printf "%s\n" "#define USE_TK_STUBS 1" >>confdefs.h
 
       fi
     fi
@@ -5763,11 +6229,12 @@ $as_echo "#define USE_TK_STUBS 1" >>confdefs.h
 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_RANLIB+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$RANLIB"; then
   ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
 else
@@ -5775,11 +6242,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -5790,11 +6261,11 @@ fi
 fi
 RANLIB=$ac_cv_prog_RANLIB
 if test -n "$RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
+printf "%s\n" "$RANLIB" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -5803,11 +6274,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_RANLIB+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_RANLIB"; then
   ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
 else
@@ -5815,11 +6287,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_RANLIB="ranlib"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -5830,11 +6306,11 @@ fi
 fi
 ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
 if test -n "$ac_ct_RANLIB"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
+printf "%s\n" "$ac_ct_RANLIB" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
   if test "x$ac_ct_RANLIB" = x; then
@@ -5842,8 +6318,8 @@ fi
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     RANLIB=$ac_ct_RANLIB
@@ -5857,44 +6333,48 @@ fi
 
     # Step 0.a: Enable 64 bit support?
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if 64bit support is requested" >&5
-$as_echo_n "checking if 64bit support is requested... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if 64bit support is requested" >&5
+printf %s "checking if 64bit support is requested... " >&6; }
     # Check whether --enable-64bit was given.
-if test "${enable_64bit+set}" = set; then :
+if test ${enable_64bit+y}
+then :
   enableval=$enable_64bit; do64bit=$enableval
-else
+else $as_nop
   do64bit=no
 fi
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $do64bit" >&5
-$as_echo "$do64bit" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $do64bit" >&5
+printf "%s\n" "$do64bit" >&6; }
 
     # Step 0.b: Enable Solaris 64 bit VIS support?
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if 64bit Sparc VIS support is requested" >&5
-$as_echo_n "checking if 64bit Sparc VIS support is requested... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if 64bit Sparc VIS support is requested" >&5
+printf %s "checking if 64bit Sparc VIS support is requested... " >&6; }
     # Check whether --enable-64bit-vis was given.
-if test "${enable_64bit_vis+set}" = set; then :
+if test ${enable_64bit_vis+y}
+then :
   enableval=$enable_64bit_vis; do64bitVIS=$enableval
-else
+else $as_nop
   do64bitVIS=no
 fi
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $do64bitVIS" >&5
-$as_echo "$do64bitVIS" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $do64bitVIS" >&5
+printf "%s\n" "$do64bitVIS" >&6; }
     # Force 64bit on with VIS
-    if test "$do64bitVIS" = "yes"; then :
+    if test "$do64bitVIS" = "yes"
+then :
   do64bit=yes
 fi
 
     # Step 0.c: Check if visibility support is available. Do this here so
     # that platform specific alternatives can be used below if this fails.
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler supports visibility \"hidden\"" >&5
-$as_echo_n "checking if compiler supports visibility \"hidden\"... " >&6; }
-if ${tcl_cv_cc_visibility_hidden+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler supports visibility \"hidden\"" >&5
+printf %s "checking if compiler supports visibility \"hidden\"... " >&6; }
+if test ${tcl_cv_cc_visibility_hidden+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
        hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -5903,58 +6383,62 @@ else
            extern __attribute__((__visibility__("hidden"))) void f(void);
            void f(void) {}
 int
-main ()
+main (void)
 {
 f();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_cc_visibility_hidden=yes
-else
+else $as_nop
   tcl_cv_cc_visibility_hidden=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
        CFLAGS=$hold_cflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_visibility_hidden" >&5
-$as_echo "$tcl_cv_cc_visibility_hidden" >&6; }
-    if test $tcl_cv_cc_visibility_hidden = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_visibility_hidden" >&5
+printf "%s\n" "$tcl_cv_cc_visibility_hidden" >&6; }
+    if test $tcl_cv_cc_visibility_hidden = yes
+then :
 
 
-$as_echo "#define MODULE_SCOPE extern __attribute__((__visibility__(\"hidden\")))" >>confdefs.h
+printf "%s\n" "#define MODULE_SCOPE extern __attribute__((__visibility__(\"hidden\")))" >>confdefs.h
 
 
-$as_echo "#define HAVE_HIDDEN 1" >>confdefs.h
+printf "%s\n" "#define HAVE_HIDDEN 1" >>confdefs.h
 
 
 fi
 
     # Step 0.d: Disable -rpath support?
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking if rpath support is requested" >&5
-$as_echo_n "checking if rpath support is requested... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if rpath support is requested" >&5
+printf %s "checking if rpath support is requested... " >&6; }
     # Check whether --enable-rpath was given.
-if test "${enable_rpath+set}" = set; then :
+if test ${enable_rpath+y}
+then :
   enableval=$enable_rpath; doRpath=$enableval
-else
+else $as_nop
   doRpath=yes
 fi
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $doRpath" >&5
-$as_echo "$doRpath" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $doRpath" >&5
+printf "%s\n" "$doRpath" >&6; }
 
     # Set the variable "system" to hold the name and version number
     # for the system.
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking system version" >&5
-$as_echo_n "checking system version... " >&6; }
-if ${tcl_cv_sys_version+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking system version" >&5
+printf %s "checking system version... " >&6; }
+if test ${tcl_cv_sys_version+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
        # TEA specific:
        if test "${TEA_PLATFORM}" = "windows" ; then
@@ -5962,8 +6446,8 @@ else
        else
            tcl_cv_sys_version=`uname -s`-`uname -r`
            if test "$?" -ne 0 ; then
-               { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: can't find uname command" >&5
-$as_echo "$as_me: WARNING: can't find uname command" >&2;}
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: can't find uname command" >&5
+printf "%s\n" "$as_me: WARNING: can't find uname command" >&2;}
                tcl_cv_sys_version=unknown
            else
                if test "`uname -s`" = "AIX" ; then
@@ -5976,8 +6460,8 @@ $as_echo "$as_me: WARNING: can't find uname command" >&2;}
        fi
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_sys_version" >&5
-$as_echo "$tcl_cv_sys_version" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_sys_version" >&5
+printf "%s\n" "$tcl_cv_sys_version" >&6; }
     system=$tcl_cv_sys_version
 
 
@@ -6002,12 +6486,13 @@ $as_echo "$tcl_cv_sys_version" >&6; }
     ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
     TCL_LIB_VERSIONS_OK=ok
     CFLAGS_DEBUG=-g
-    if test "$GCC" = yes; then :
+    if test "$GCC" = yes
+then :
 
        CFLAGS_OPTIMIZE=-O2
        CFLAGS_WARNING="-Wall"
 
-else
+else $as_nop
 
        CFLAGS_OPTIMIZE=-O
        CFLAGS_WARNING=""
@@ -6016,11 +6501,12 @@ fi
     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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_AR+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$AR"; then
   ac_cv_prog_AR="$AR" # Let the user override the test.
 else
@@ -6028,11 +6514,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_AR="${ac_tool_prefix}ar"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -6043,11 +6533,11 @@ fi
 fi
 AR=$ac_cv_prog_AR
 if test -n "$AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
-$as_echo "$AR" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
+printf "%s\n" "$AR" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -6056,11 +6546,12 @@ 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
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_AR+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_AR+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_AR"; then
   ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
 else
@@ -6068,11 +6559,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_AR="ar"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -6083,11 +6578,11 @@ fi
 fi
 ac_ct_AR=$ac_cv_prog_ac_ct_AR
 if test -n "$ac_ct_AR"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
-$as_echo "$ac_ct_AR" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
+printf "%s\n" "$ac_ct_AR" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
   if test "x$ac_ct_AR" = x; then
@@ -6095,8 +6590,8 @@ fi
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     AR=$ac_ct_AR
@@ -6107,9 +6602,10 @@ fi
 
     STLIB_LD='${AR} cr'
     LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
-    if test "x$SHLIB_VERSION" = x; then :
+    if test "x$SHLIB_VERSION" = x
+then :
   SHLIB_VERSION=""
-else
+else $as_nop
   SHLIB_VERSION=".$SHLIB_VERSION"
 fi
     case $system in
@@ -6141,7 +6637,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6166,7 +6662,7 @@ fi
     for i in $vars; do
        if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
            # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
-           i=`echo "$i" | sed -e 's/^\([^-].*\)\.lib$/-l\1/i'`
+           i=`echo "$i" | sed -e 's/^\([^-].*\)\.[lL][iI][bB]$/-l\1/'`
        fi
        PKG_LIBS="$PKG_LIBS $i"
     done
@@ -6186,11 +6682,12 @@ fi
                if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}windres", so it can be a program name with args.
 set dummy ${ac_tool_prefix}windres; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_RC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$RC"; then
   ac_cv_prog_RC="$RC" # Let the user override the test.
 else
@@ -6198,11 +6695,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_RC="${ac_tool_prefix}windres"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -6213,11 +6714,11 @@ fi
 fi
 RC=$ac_cv_prog_RC
 if test -n "$RC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RC" >&5
-$as_echo "$RC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RC" >&5
+printf "%s\n" "$RC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
 
@@ -6226,11 +6727,12 @@ if test -z "$ac_cv_prog_RC"; then
   ac_ct_RC=$RC
   # Extract the first word of "windres", so it can be a program name with args.
 set dummy windres; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RC+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+printf %s "checking for $ac_word... " >&6; }
+if test ${ac_cv_prog_ac_ct_RC+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   if test -n "$ac_ct_RC"; then
   ac_cv_prog_ac_ct_RC="$ac_ct_RC" # Let the user override the test.
 else
@@ -6238,11 +6740,15 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in $PATH
 do
   IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_RC="windres"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
@@ -6253,11 +6759,11 @@ fi
 fi
 ac_ct_RC=$ac_cv_prog_ac_ct_RC
 if test -n "$ac_ct_RC"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RC" >&5
-$as_echo "$ac_ct_RC" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RC" >&5
+printf "%s\n" "$ac_ct_RC" >&6; }
 else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
 fi
 
   if test "x$ac_ct_RC" = x; then
@@ -6265,8 +6771,8 @@ fi
   else
     case $cross_compiling:$ac_tool_warned in
 yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
 ac_tool_warned=yes ;;
 esac
     RC=$ac_ct_RC
@@ -6282,11 +6788,12 @@ fi
                LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
                LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
 
-               { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cross-compile version of gcc" >&5
-$as_echo_n "checking for cross-compile version of gcc... " >&6; }
-if ${ac_cv_cross+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for cross-compile version of gcc" >&5
+printf %s "checking for cross-compile version of gcc... " >&6; }
+if test ${ac_cv_cross+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -6295,34 +6802,35 @@ else
                            #endif
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   ac_cv_cross=yes
-else
+else $as_nop
   ac_cv_cross=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cross" >&5
-$as_echo "$ac_cv_cross" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cross" >&5
+printf "%s\n" "$ac_cv_cross" >&6; }
                      if test "$ac_cv_cross" = "yes"; then
                        case "$do64bit" in
                            amd64|x64|yes)
-                               CC="x86_64-w64-mingw32-gcc"
+                               CC="x86_64-w64-mingw32-${CC}"
                                LD="x86_64-w64-mingw32-ld"
                                AR="x86_64-w64-mingw32-ar"
                                RANLIB="x86_64-w64-mingw32-ranlib"
                                RC="x86_64-w64-mingw32-windres"
                            ;;
                            *)
-                               CC="i686-w64-mingw32-gcc"
+                               CC="i686-w64-mingw32-${CC}"
                                LD="i686-w64-mingw32-ld"
                                AR="i686-w64-mingw32-ar"
                                RANLIB="i686-w64-mingw32-ranlib"
@@ -6354,7 +6862,8 @@ $as_echo "$ac_cv_cross" >&6; }
            TCL_LIB_VERSIONS_OK=nodots
            ;;
        AIX-*)
-           if test "$GCC" != "yes"; then :
+           if test "$GCC" != "yes"
+then :
 
                # AIX requires the _r compiler when gcc isn't being used
                case "${CC}" in
@@ -6366,8 +6875,8 @@ $as_echo "$ac_cv_cross" >&6; }
                        CC=`echo "$CC" | sed -e 's/^\([^ ]*\)/\1_r/'`
                        ;;
                esac
-               { $as_echo "$as_me:${as_lineno-$LINENO}: result: Using $CC for compiling with threads" >&5
-$as_echo "Using $CC for compiling with threads" >&6; }
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Using $CC for compiling with threads" >&5
+printf "%s\n" "Using $CC for compiling with threads" >&6; }
 
 fi
            LIBS="$LIBS -lc"
@@ -6377,14 +6886,16 @@ fi
            LD_LIBRARY_PATH_VAR="LIBPATH"
 
            # Check to enable 64-bit flags for compiler/linker
-           if test "$do64bit" = yes; then :
+           if test "$do64bit" = yes
+then :
 
-               if test "$GCC" = yes; then :
+               if test "$GCC" = yes
+then :
 
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;}
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;}
 
-else
+else $as_nop
 
                    do64bit_ok=yes
                    CFLAGS="$CFLAGS -q64"
@@ -6397,35 +6908,38 @@ fi
 
 fi
 
-           if test "`uname -m`" = ia64; then :
+           if test "`uname -m`" = ia64
+then :
 
                # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               if test "$GCC" = yes; then :
+               if test "$GCC" = yes
+then :
 
-                   CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
 
-else
+else $as_nop
 
-                   CC_SEARCH_FLAGS='-R${LIB_RUNTIME_DIR}'
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
 
 fi
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
-else
+else $as_nop
 
-               if test "$GCC" = yes; then :
+               if test "$GCC" = yes
+then :
 
                    SHLIB_LD='${CC} -shared -Wl,-bexpall'
 
-else
+else $as_nop
 
                    SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
                    LDFLAGS="$LDFLAGS -brtl"
 
 fi
                SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
-               CC_SEARCH_FLAGS='-L${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -6440,11 +6954,12 @@ fi
            # -lsocket, even if the network functions are in -lnet which
            # is always linked to, for compatibility.
            #-----------------------------------------------------------
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_ntoa in -lbind" >&5
-$as_echo_n "checking for inet_ntoa in -lbind... " >&6; }
-if ${ac_cv_lib_bind_inet_ntoa+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for inet_ntoa in -lbind" >&5
+printf %s "checking for inet_ntoa in -lbind... " >&6; }
+if test ${ac_cv_lib_bind_inet_ntoa+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lbind  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6453,30 +6968,29 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char inet_ntoa ();
 int
-main ()
+main (void)
 {
 return inet_ntoa ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_bind_inet_ntoa=yes
-else
+else $as_nop
   ac_cv_lib_bind_inet_ntoa=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bind_inet_ntoa" >&5
-$as_echo "$ac_cv_lib_bind_inet_ntoa" >&6; }
-if test "x$ac_cv_lib_bind_inet_ntoa" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bind_inet_ntoa" >&5
+printf "%s\n" "$ac_cv_lib_bind_inet_ntoa" >&6; }
+if test "x$ac_cv_lib_bind_inet_ntoa" = xyes
+then :
   LIBS="$LIBS -lbind -lsocket"
 fi
 
@@ -6501,39 +7015,6 @@ fi
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Cygwin version of gcc" >&5
-$as_echo_n "checking for Cygwin version of gcc... " >&6; }
-if ${ac_cv_cygwin+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-               #ifdef __CYGWIN__
-                   #error cygwin
-               #endif
-
-int
-main ()
-{
-
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-  ac_cv_cygwin=no
-else
-  ac_cv_cygwin=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cygwin" >&5
-$as_echo "$ac_cv_cygwin" >&6; }
-           if test "$ac_cv_cygwin" = "no"; then
-               as_fn_error $? "${CC} is not a cygwin compiler." "$LINENO" 5
-           fi
            EXEEXT=".exe"
            do64bit_ok=yes
            CC_SEARCH_FLAGS=""
@@ -6552,11 +7033,12 @@ $as_echo "$ac_cv_cygwin" >&6; }
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inet_ntoa in -lnetwork" >&5
-$as_echo_n "checking for inet_ntoa in -lnetwork... " >&6; }
-if ${ac_cv_lib_network_inet_ntoa+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for inet_ntoa in -lnetwork" >&5
+printf %s "checking for inet_ntoa in -lnetwork... " >&6; }
+if test ${ac_cv_lib_network_inet_ntoa+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-lnetwork  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6565,30 +7047,29 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char inet_ntoa ();
 int
-main ()
+main (void)
 {
 return inet_ntoa ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_network_inet_ntoa=yes
-else
+else $as_nop
   ac_cv_lib_network_inet_ntoa=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_network_inet_ntoa" >&5
-$as_echo "$ac_cv_lib_network_inet_ntoa" >&6; }
-if test "x$ac_cv_lib_network_inet_ntoa" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_network_inet_ntoa" >&5
+printf "%s\n" "$ac_cv_lib_network_inet_ntoa" >&6; }
+if test "x$ac_cv_lib_network_inet_ntoa" = xyes
+then :
   LIBS="$LIBS -lnetwork"
 fi
 
@@ -6596,26 +7077,28 @@ fi
        HP-UX-*.11.*)
            # Use updated header definitions where possible
 
-$as_echo "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h
+printf "%s\n" "#define _XOPEN_SOURCE_EXTENDED 1" >>confdefs.h
 
            # TEA specific: Needed by Tcl, but not most extensions
            #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
            #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
 
-           if test "`uname -m`" = ia64; then :
+           if test "`uname -m`" = ia64
+then :
 
                SHLIB_SUFFIX=".so"
 
-else
+else $as_nop
 
                SHLIB_SUFFIX=".sl"
 
 fi
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
-$as_echo_n "checking for shl_load in -ldld... " >&6; }
-if ${ac_cv_lib_dld_shl_load+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
+printf %s "checking for shl_load in -ldld... " >&6; }
+if test ${ac_cv_lib_dld_shl_load+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-ldld  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6624,79 +7107,83 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char shl_load ();
 int
-main ()
+main (void)
 {
 return shl_load ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_dld_shl_load=yes
-else
+else $as_nop
   ac_cv_lib_dld_shl_load=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
-$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
-if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
+printf "%s\n" "$ac_cv_lib_dld_shl_load" >&6; }
+if test "x$ac_cv_lib_dld_shl_load" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
-           if test "$tcl_ok" = yes; then :
+           if test "$tcl_ok" = yes
+then :
 
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                SHLIB_LD='${CC} -shared'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
-else
+else $as_nop
 
                CFLAGS="$CFLAGS -z"
 
 fi
 
            # Check to enable 64-bit flags for compiler/linker
-           if test "$do64bit" = "yes"; then :
+           if test "$do64bit" = "yes"
+then :
 
-               if test "$GCC" = yes; then :
+               if test "$GCC" = yes
+then :
 
                    case `${CC} -dumpmachine` in
                        hppa64*)
                            # 64-bit gcc in use.  Fix flags for GNU ld.
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
-                           if test $doRpath = yes; then :
+                           if test $doRpath = yes
+then :
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
-                           { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;}
+                           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;}
                            ;;
                    esac
 
-else
+else $as_nop
 
                    do64bit_ok=yes
                    CFLAGS="$CFLAGS +DD64"
@@ -6707,11 +7194,12 @@ fi
 fi ;;
        HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
            SHLIB_SUFFIX=".sl"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
-$as_echo_n "checking for shl_load in -ldld... " >&6; }
-if ${ac_cv_lib_dld_shl_load+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
+printf %s "checking for shl_load in -ldld... " >&6; }
+if test ${ac_cv_lib_dld_shl_load+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   ac_check_lib_save_LIBS=$LIBS
 LIBS="-ldld  $LIBS"
 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -6720,43 +7208,43 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* Override any GCC internal prototype to avoid an error.
    Use char because int might match the return type of a GCC
    builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
 char shl_load ();
 int
-main ()
+main (void)
 {
 return shl_load ();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   ac_cv_lib_dld_shl_load=yes
-else
+else $as_nop
   ac_cv_lib_dld_shl_load=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
 LIBS=$ac_check_lib_save_LIBS
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
-$as_echo "$ac_cv_lib_dld_shl_load" >&6; }
-if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
+printf "%s\n" "$ac_cv_lib_dld_shl_load" >&6; }
+if test "x$ac_cv_lib_dld_shl_load" = xyes
+then :
   tcl_ok=yes
-else
+else $as_nop
   tcl_ok=no
 fi
 
-           if test "$tcl_ok" = yes; then :
+           if test "$tcl_ok" = yes
+then :
 
                SHLIB_CFLAGS="+z"
                SHLIB_LD="ld -b"
                SHLIB_LD_LIBS=""
                LDFLAGS="$LDFLAGS -Wl,-E"
-               CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
-               LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
                LD_LIBRARY_PATH_VAR="SHLIB_PATH"
 
 fi ;;
@@ -6770,27 +7258,30 @@ fi ;;
  ;;
 esac
 
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
            ;;
        IRIX-6.*)
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                CFLAGS="$CFLAGS -mabi=n32"
                LDFLAGS="$LDFLAGS -mabi=n32"
 
-else
+else $as_nop
 
                case $system in
                    IRIX-6.3)
@@ -6809,22 +7300,25 @@ fi
            SHLIB_CFLAGS=""
            SHLIB_LD="ld -n32 -shared -rdata_shared"
            SHLIB_SUFFIX=".so"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'
 fi
 
            # Check to enable 64-bit flags for compiler/linker
 
-           if test "$do64bit" = yes; then :
+           if test "$do64bit" = yes
+then :
 
-               if test "$GCC" = yes; then :
+               if test "$GCC" = yes
+then :
 
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported by gcc" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported by gcc" >&2;}
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported by gcc" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported by gcc" >&2;}
 
-else
+else $as_nop
 
                    do64bit_ok=yes
                    SHLIB_LD="ld -64 -shared -rdata_shared"
@@ -6835,7 +7329,7 @@ fi
 
 fi
            ;;
-       Linux*|GNU*|NetBSD-Debian)
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
            SHLIB_CFLAGS="-fPIC"
            SHLIB_SUFFIX=".so"
 
@@ -6845,21 +7339,39 @@ fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
-           if test $doRpath = yes; then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               if test "${TCL_THREADS}" = "1"
+then :
+
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
+fi
+           ;;
+            esac
+
+           if test $doRpath = yes
+then :
+
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-           if test "`uname -m`" = "alpha"; then :
+           if test "`uname -m`" = "alpha"
+then :
   CFLAGS="$CFLAGS -mieee"
 fi
-           if test $do64bit = yes; then :
+           if test $do64bit = yes
+then :
 
-               { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -m64 flag" >&5
-$as_echo_n "checking if compiler accepts -m64 flag... " >&6; }
-if ${tcl_cv_cc_m64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -m64 flag" >&5
+printf %s "checking if compiler accepts -m64 flag... " >&6; }
+if test ${tcl_cv_cc_m64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                    hold_cflags=$CFLAGS
                    CFLAGS="$CFLAGS -m64"
@@ -6867,25 +7379,27 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_cc_m64=yes
-else
+else $as_nop
   tcl_cv_cc_m64=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                    CFLAGS=$hold_cflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_m64" >&5
-$as_echo "$tcl_cv_cc_m64" >&6; }
-               if test $tcl_cv_cc_m64 = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_m64" >&5
+printf "%s\n" "$tcl_cv_cc_m64" >&6; }
+               if test $tcl_cv_cc_m64 = yes
+then :
 
                    CFLAGS="$CFLAGS -m64"
                    do64bit_ok=yes
@@ -6900,7 +7414,8 @@ fi
            # of overkill but it works. Disable inlining only when one of the
            # files in compat/*.c is being linked in.
 
-           if test x"${USE_COMPAT}" != x; then :
+           if test x"${USE_COMPAT}" != x
+then :
   CFLAGS="$CFLAGS -fno-inline"
 fi
            ;;
@@ -6910,10 +7425,11 @@ fi
            CFLAGS_OPTIMIZE=-02
            SHLIB_LD='${CC} -shared'
            LD_FLAGS="-Wl,--export-dynamic"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            ;;
        OpenBSD-*)
@@ -6928,13 +7444,14 @@ fi
            esac
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
-           LDFLAGS="-Wl,-export-dynamic"
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
            CFLAGS_OPTIMIZE="-O2"
            # On OpenBSD:       Compile with -pthread
            #           Don't link with -lpthread
@@ -6950,9 +7467,10 @@ fi
            SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
            SHLIB_SUFFIX=".so"
            LDFLAGS="$LDFLAGS -export-dynamic"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            # The -pthread needs to go in the CFLAGS, not LIBS
@@ -6960,32 +7478,6 @@ fi
            CFLAGS="$CFLAGS -pthread"
            LDFLAGS="$LDFLAGS -pthread"
            ;;
-       DragonFly-*|FreeBSD-*)
-           # This configuration from FreeBSD Ports.
-           SHLIB_CFLAGS="-fPIC"
-           SHLIB_LD="${CC} -shared"
-           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,-soname,\$@"
-           SHLIB_SUFFIX=".so"
-           LDFLAGS=""
-           if test $doRpath = yes; then :
-
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-fi
-           # The -pthread needs to go in the LDFLAGS, not LIBS
-           LIBS=`echo $LIBS | sed s/-pthread//`
-           CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
-           LDFLAGS="$LDFLAGS $PTHREAD_LIBS"
-           case $system in
-           FreeBSD-3.*)
-               # Version numbers are dot-stripped by system policy.
-               TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
-               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
-               SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
-               TCL_LIB_VERSIONS_OK=nodots
-               ;;
-           esac
-           ;;
        Darwin-*)
            CFLAGS_OPTIMIZE="-Os"
            SHLIB_CFLAGS="-fno-common"
@@ -6998,15 +7490,17 @@ fi
            CFLAGS="`echo " ${CFLAGS}" | \
                awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
                if (!($i~/^(isysroot|mmacosx-version-min)/)) print "-"$i}'`"
-           if test $do64bit = yes; then :
+           if test $do64bit = yes
+then :
 
                case `arch` in
                    ppc)
-                       { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -arch ppc64 flag" >&5
-$as_echo_n "checking if compiler accepts -arch ppc64 flag... " >&6; }
-if ${tcl_cv_cc_arch_ppc64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -arch ppc64 flag" >&5
+printf %s "checking if compiler accepts -arch ppc64 flag... " >&6; }
+if test ${tcl_cv_cc_arch_ppc64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                            hold_cflags=$CFLAGS
                            CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
@@ -7014,36 +7508,39 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_cc_arch_ppc64=yes
-else
+else $as_nop
   tcl_cv_cc_arch_ppc64=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                            CFLAGS=$hold_cflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_arch_ppc64" >&5
-$as_echo "$tcl_cv_cc_arch_ppc64" >&6; }
-                       if test $tcl_cv_cc_arch_ppc64 = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_arch_ppc64" >&5
+printf "%s\n" "$tcl_cv_cc_arch_ppc64" >&6; }
+                       if test $tcl_cv_cc_arch_ppc64 = yes
+then :
 
                            CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
                            do64bit_ok=yes
 
 fi;;
                    i386)
-                       { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -arch x86_64 flag" >&5
-$as_echo_n "checking if compiler accepts -arch x86_64 flag... " >&6; }
-if ${tcl_cv_cc_arch_x86_64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if compiler accepts -arch x86_64 flag" >&5
+printf %s "checking if compiler accepts -arch x86_64 flag... " >&6; }
+if test ${tcl_cv_cc_arch_x86_64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                            hold_cflags=$CFLAGS
                            CFLAGS="$CFLAGS -arch x86_64"
@@ -7051,40 +7548,43 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_cc_arch_x86_64=yes
-else
+else $as_nop
   tcl_cv_cc_arch_x86_64=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                            CFLAGS=$hold_cflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_arch_x86_64" >&5
-$as_echo "$tcl_cv_cc_arch_x86_64" >&6; }
-                       if test $tcl_cv_cc_arch_x86_64 = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cc_arch_x86_64" >&5
+printf "%s\n" "$tcl_cv_cc_arch_x86_64" >&6; }
+                       if test $tcl_cv_cc_arch_x86_64 = yes
+then :
 
                            CFLAGS="$CFLAGS -arch x86_64"
                            do64bit_ok=yes
 
 fi;;
                    *)
-                       { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Don't know how enable 64-bit on architecture \`arch\`" >&5
-$as_echo "$as_me: WARNING: Don't know how enable 64-bit on architecture \`arch\`" >&2;};;
+                       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Don't know how enable 64-bit on architecture \`arch\`" >&5
+printf "%s\n" "$as_me: WARNING: Don't know how enable 64-bit on architecture \`arch\`" >&2;};;
                esac
 
-else
+else $as_nop
 
                # Check for combined 32-bit and 64-bit fat build
                if echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
-                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '; then :
+                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '
+then :
 
                    fat_32_64=yes
 fi
@@ -7092,11 +7592,12 @@ fi
 fi
            # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
            SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ld accepts -single_module flag" >&5
-$as_echo_n "checking if ld accepts -single_module flag... " >&6; }
-if ${tcl_cv_ld_single_module+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ld accepts -single_module flag" >&5
+printf %s "checking if ld accepts -single_module flag... " >&6; }
+if test ${tcl_cv_ld_single_module+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                hold_ldflags=$LDFLAGS
                LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
@@ -7104,25 +7605,27 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 int i;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_ld_single_module=yes
-else
+else $as_nop
   tcl_cv_ld_single_module=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                LDFLAGS=$hold_ldflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_single_module" >&5
-$as_echo "$tcl_cv_ld_single_module" >&6; }
-           if test $tcl_cv_ld_single_module = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_single_module" >&5
+printf "%s\n" "$tcl_cv_ld_single_module" >&6; }
+           if test $tcl_cv_ld_single_module = yes
+then :
 
                SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
 
@@ -7132,11 +7635,12 @@ fi
            SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
            SHLIB_SUFFIX=".dylib"
            LDFLAGS="$LDFLAGS -headerpad_max_install_names"
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ld accepts -search_paths_first flag" >&5
-$as_echo_n "checking if ld accepts -search_paths_first flag... " >&6; }
-if ${tcl_cv_ld_search_paths_first+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if ld accepts -search_paths_first flag" >&5
+printf %s "checking if ld accepts -search_paths_first flag... " >&6; }
+if test ${tcl_cv_ld_search_paths_first+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                hold_ldflags=$LDFLAGS
                LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
@@ -7144,33 +7648,36 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 int i;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_ld_search_paths_first=yes
-else
+else $as_nop
   tcl_cv_ld_search_paths_first=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                LDFLAGS=$hold_ldflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_search_paths_first" >&5
-$as_echo "$tcl_cv_ld_search_paths_first" >&6; }
-           if test $tcl_cv_ld_search_paths_first = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_search_paths_first" >&5
+printf "%s\n" "$tcl_cv_ld_search_paths_first" >&6; }
+           if test $tcl_cv_ld_search_paths_first = yes
+then :
 
                LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
 
 fi
-           if test "$tcl_cv_cc_visibility_hidden" != yes; then :
+           if test "$tcl_cv_cc_visibility_hidden" != yes
+then :
 
 
-$as_echo "#define MODULE_SCOPE __private_extern__" >>confdefs.h
+printf "%s\n" "#define MODULE_SCOPE __private_extern__" >>confdefs.h
 
                tcl_cv_cc_visibility_hidden=yes
 
@@ -7180,15 +7687,18 @@ fi
            LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
            # TEA specific: for combined 32 & 64 bit fat builds of Tk
            # extensions, verify that 64-bit build is possible.
-           if test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"; then :
+           if test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"
+then :
 
-               if test "${TEA_WINDOWINGSYSTEM}" = x11; then :
+               if test "${TEA_WINDOWINGSYSTEM}" = x11
+then :
 
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for 64-bit X11" >&5
-$as_echo_n "checking for 64-bit X11... " >&6; }
-if ${tcl_cv_lib_x11_64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for 64-bit X11" >&5
+printf %s "checking for 64-bit X11... " >&6; }
+if test ${tcl_cv_lib_x11_64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                        for v in CFLAGS CPPFLAGS LDFLAGS; do
                            eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
@@ -7199,35 +7709,38 @@ else
 /* end confdefs.h.  */
 #include <X11/Xlib.h>
 int
-main ()
+main (void)
 {
 XrmInitialize();
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_lib_x11_64=yes
-else
+else $as_nop
   tcl_cv_lib_x11_64=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                        for v in CFLAGS CPPFLAGS LDFLAGS; do
                            eval $v'="$hold_'$v'"'
                        done
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_lib_x11_64" >&5
-$as_echo "$tcl_cv_lib_x11_64" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_lib_x11_64" >&5
+printf "%s\n" "$tcl_cv_lib_x11_64" >&6; }
 
 fi
-               if test "${TEA_WINDOWINGSYSTEM}" = aqua; then :
+               if test "${TEA_WINDOWINGSYSTEM}" = aqua
+then :
 
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for 64-bit Tk" >&5
-$as_echo_n "checking for 64-bit Tk... " >&6; }
-if ${tcl_cv_lib_tk_64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for 64-bit Tk" >&5
+printf %s "checking for 64-bit Tk... " >&6; }
+if test ${tcl_cv_lib_tk_64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                        for v in CFLAGS CPPFLAGS LDFLAGS; do
                            eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
@@ -7238,34 +7751,36 @@ else
 /* end confdefs.h.  */
 #include <tk.h>
 int
-main ()
+main (void)
 {
 Tk_InitStubs(NULL, "", 0);
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_lib_tk_64=yes
-else
+else $as_nop
   tcl_cv_lib_tk_64=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                        for v in CFLAGS CPPFLAGS LDFLAGS; do
                            eval $v'="$hold_'$v'"'
                        done
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_lib_tk_64" >&5
-$as_echo "$tcl_cv_lib_tk_64" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_lib_tk_64" >&5
+printf "%s\n" "$tcl_cv_lib_tk_64" >&6; }
 
 fi
                # remove 64-bit arch flags from CFLAGS et al. if configuration
                # does not support 64-bit.
-               if test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no; then :
+               if test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no
+then :
 
-                   { $as_echo "$as_me:${as_lineno-$LINENO}: Removing 64-bit architectures from compiler & linker flags" >&5
-$as_echo "$as_me: Removing 64-bit architectures from compiler & linker flags" >&6;}
+                   { printf "%s\n" "$as_me:${as_lineno-$LINENO}: Removing 64-bit architectures from compiler & linker flags" >&5
+printf "%s\n" "$as_me: Removing 64-bit architectures from compiler & linker flags" >&6;}
                    for v in CFLAGS CPPFLAGS LDFLAGS; do
                        eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
                    done
@@ -7276,30 +7791,33 @@ fi
        OS/390-*)
            CFLAGS_OPTIMIZE=""          # Optimizer is buggy
 
-$as_echo "#define _OE_SOCKETS 1" >>confdefs.h
+printf "%s\n" "#define _OE_SOCKETS 1" >>confdefs.h
 
            ;;
        OSF1-V*)
            # Digital OSF/1
            SHLIB_CFLAGS=""
-           if test "$SHARED_BUILD" = 1; then :
+           if test "$SHARED_BUILD" = 1
+then :
 
                SHLIB_LD='ld -shared -expect_unresolved "*"'
 
-else
+else $as_nop
 
                SHLIB_LD='ld -non_shared -expect_unresolved "*"'
 
 fi
            SHLIB_SUFFIX=".so"
-           if test $doRpath = yes; then :
+           if test $doRpath = yes
+then :
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
   CFLAGS="$CFLAGS -mieee"
-else
+else $as_nop
 
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"
 fi
@@ -7307,11 +7825,12 @@ fi
            CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
            CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
            LIBS=`echo $LIBS | sed s/-lpthreads//`
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                LIBS="$LIBS -lpthread -lmach -lexc"
 
-else
+else $as_nop
 
                CFLAGS="$CFLAGS -pthread"
                LDFLAGS="$LDFLAGS -pthread"
@@ -7329,12 +7848,13 @@ fi
            LD_SEARCH_FLAGS=""
            ;;
        SCO_SV-3.2*)
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                SHLIB_CFLAGS="-fPIC -melf"
                LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
 
-else
+else $as_nop
 
                SHLIB_CFLAGS="-Kpic -belf"
                LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
@@ -7353,24 +7873,25 @@ fi
            # won't define thread-safe library routines.
 
 
-$as_echo "#define _REENTRANT 1" >>confdefs.h
+printf "%s\n" "#define _REENTRANT 1" >>confdefs.h
 
 
-$as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
+printf "%s\n" "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
 
 
            SHLIB_CFLAGS="-KPIC"
            SHLIB_SUFFIX=".so"
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
-else
+else $as_nop
 
                SHLIB_LD="/usr/ccs/bin/ld -G -z text"
-               CC_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
 
 fi
@@ -7380,28 +7901,32 @@ fi
            # won't define thread-safe library routines.
 
 
-$as_echo "#define _REENTRANT 1" >>confdefs.h
+printf "%s\n" "#define _REENTRANT 1" >>confdefs.h
 
 
-$as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
+printf "%s\n" "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
 
 
            SHLIB_CFLAGS="-KPIC"
 
            # Check to enable 64-bit flags for compiler/linker
-           if test "$do64bit" = yes; then :
+           if test "$do64bit" = yes
+then :
 
                arch=`isainfo`
-               if test "$arch" = "sparcv9 sparc"; then :
+               if test "$arch" = "sparcv9 sparc"
+then :
 
-                   if test "$GCC" = yes; then :
+                   if test "$GCC" = yes
+then :
 
-                       if test "`${CC} -dumpversion | awk -F. '{print $1}'`" -lt 3; then :
+                       if test "`${CC} -dumpversion | awk -F. '{print $1}'`" -lt 3
+then :
 
-                           { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC < 3.2 on $system" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported with GCC < 3.2 on $system" >&2;}
+                           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC < 3.2 on $system" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported with GCC < 3.2 on $system" >&2;}
 
-else
+else $as_nop
 
                            do64bit_ok=yes
                            CFLAGS="$CFLAGS -m64 -mcpu=v9"
@@ -7410,15 +7935,16 @@ else
 
 fi
 
-else
+else $as_nop
 
                        do64bit_ok=yes
-                       if test "$do64bitVIS" = yes; then :
+                       if test "$do64bitVIS" = yes
+then :
 
                            CFLAGS="$CFLAGS -xarch=v9a"
                            LDFLAGS_ARCH="-xarch=v9a"
 
-else
+else $as_nop
 
                            CFLAGS="$CFLAGS -xarch=v9"
                            LDFLAGS_ARCH="-xarch=v9"
@@ -7429,10 +7955,12 @@ fi
 
 fi
 
-else
-  if test "$arch" = "amd64 i386"; then :
+else $as_nop
+  if test "$arch" = "amd64 i386"
+then :
 
-                   if test "$GCC" = yes; then :
+                   if test "$GCC" = yes
+then :
 
                        case $system in
                            SunOS-5.1[1-9]*|SunOS-5.[2-9][0-9]*)
@@ -7440,11 +7968,11 @@ else
                                CFLAGS="$CFLAGS -m64"
                                LDFLAGS="$LDFLAGS -m64";;
                            *)
-                               { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;};;
+                               { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported with GCC on $system" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported with GCC on $system" >&2;};;
                        esac
 
-else
+else $as_nop
 
                        do64bit_ok=yes
                        case $system in
@@ -7458,23 +7986,26 @@ else
 
 fi
 
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported for $arch" >&5
-$as_echo "$as_me: WARNING: 64bit mode not supported for $arch" >&2;}
+else $as_nop
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit mode not supported for $arch" >&5
+printf "%s\n" "$as_me: WARNING: 64bit mode not supported for $arch" >&2;}
 fi
 fi
 
 fi
 
            SHLIB_SUFFIX=".so"
-           if test "$GCC" = yes; then :
+           if test "$GCC" = yes
+then :
 
                SHLIB_LD='${CC} -shared'
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
-               if test "$do64bit_ok" = yes; then :
+               if test "$do64bit_ok" = yes
+then :
 
-                   if test "$arch" = "sparcv9 sparc"; then :
+                   if test "$arch" = "sparcv9 sparc"
+then :
 
                        # We need to specify -static-libgcc or we need to
                        # add the path to the sparv9 libgcc.
@@ -7486,8 +8017,9 @@ fi
                        #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
                        #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
 
-else
-  if test "$arch" = "amd64 i386"; then :
+else $as_nop
+  if test "$arch" = "amd64 i386"
+then :
 
                        # JH: static-libgcc is necessary for core Tcl, but may
                        # not be necessary for extensions.
@@ -7498,7 +8030,7 @@ fi
 
 fi
 
-else
+else $as_nop
 
                case $system in
                    SunOS-5.[1-9][0-9]*)
@@ -7507,8 +8039,8 @@ else
                    *)
                        SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
                esac
-               CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
 
 fi
            ;;
@@ -7519,11 +8051,12 @@ fi
            SHLIB_SUFFIX=".so"
            # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
            # that don't grok the -Bexport option.  Test that it does.
-           { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld accepts -Bexport flag" >&5
-$as_echo_n "checking for ld accepts -Bexport flag... " >&6; }
-if ${tcl_cv_ld_Bexport+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ld accepts -Bexport flag" >&5
+printf %s "checking for ld accepts -Bexport flag... " >&6; }
+if test ${tcl_cv_ld_Bexport+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
                hold_ldflags=$LDFLAGS
                LDFLAGS="$LDFLAGS -Wl,-Bexport"
@@ -7531,25 +8064,27 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 int i;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
+if ac_fn_c_try_link "$LINENO"
+then :
   tcl_cv_ld_Bexport=yes
-else
+else $as_nop
   tcl_cv_ld_Bexport=no
 fi
-rm -f core conftest.err conftest.$ac_objext \
+rm -f core conftest.err conftest.$ac_objext conftest.beam \
     conftest$ac_exeext conftest.$ac_ext
                LDFLAGS=$hold_ldflags
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_Bexport" >&5
-$as_echo "$tcl_cv_ld_Bexport" >&6; }
-           if test $tcl_cv_ld_Bexport = yes; then :
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_ld_Bexport" >&5
+printf "%s\n" "$tcl_cv_ld_Bexport" >&6; }
+           if test $tcl_cv_ld_Bexport = yes
+then :
 
                LDFLAGS="$LDFLAGS -Wl,-Bexport"
 
@@ -7559,10 +8094,11 @@ fi
            ;;
     esac
 
-    if test "$do64bit" = yes -a "$do64bit_ok" = no; then :
+    if test "$do64bit" = yes -a "$do64bit_ok" = no
+then :
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 64bit support being disabled -- don't know magic for this platform" >&5
-$as_echo "$as_me: WARNING: 64bit support being disabled -- don't know magic for this platform" >&2;}
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: 64bit support being disabled -- don't know magic for this platform" >&5
+printf "%s\n" "$as_me: WARNING: 64bit support being disabled -- don't know magic for this platform" >&2;}
 
 fi
 
@@ -7576,7 +8112,8 @@ fi
     # libraries to the right flags for gcc, instead of those for the
     # standard manufacturer compiler.
 
-    if test "$GCC" = yes; then :
+    if test "$GCC" = yes
+then :
 
        case $system in
            AIX-*) ;;
@@ -7591,34 +8128,39 @@ fi
        esac
 fi
 
-    if test "$tcl_cv_cc_visibility_hidden" != yes; then :
+    if test "$tcl_cv_cc_visibility_hidden" != yes
+then :
 
 
-$as_echo "#define MODULE_SCOPE extern" >>confdefs.h
+printf "%s\n" "#define MODULE_SCOPE extern" >>confdefs.h
 
 
 fi
 
-    if test "$SHARED_LIB_SUFFIX" = ""; then :
+    if test "$SHARED_LIB_SUFFIX" = ""
+then :
 
     # TEA specific: use PACKAGE_VERSION instead of VERSION
     SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'
 fi
-    if test "$UNSHARED_LIB_SUFFIX" = ""; then :
+    if test "$UNSHARED_LIB_SUFFIX" = ""
+then :
 
     # TEA specific: use PACKAGE_VERSION instead of VERSION
     UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'
 fi
 
     if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SEH support in compiler" >&5
-$as_echo_n "checking for SEH support in compiler... " >&6; }
-if ${tcl_cv_seh+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test "$cross_compiling" = yes; then :
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for SEH support in compiler" >&5
+printf %s "checking for SEH support in compiler... " >&6; }
+if test ${tcl_cv_seh+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  if test "$cross_compiling" = yes
+then :
   tcl_cv_seh=no
-else
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -7638,9 +8180,10 @@ else
            }
 
 _ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
+if ac_fn_c_try_run "$LINENO"
+then :
   tcl_cv_seh=yes
-else
+else $as_nop
   tcl_cv_seh=no
 fi
 rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
@@ -7649,11 +8192,11 @@ fi
 
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_seh" >&5
-$as_echo "$tcl_cv_seh" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_seh" >&5
+printf "%s\n" "$tcl_cv_seh" >&6; }
        if test "$tcl_cv_seh" = "no" ; then
 
-$as_echo "#define HAVE_NO_SEH 1" >>confdefs.h
+printf "%s\n" "#define HAVE_NO_SEH 1" >>confdefs.h
 
        fi
 
@@ -7663,11 +8206,12 @@ $as_echo "#define HAVE_NO_SEH 1" >>confdefs.h
        # with Cygwin's version as of 2002-04-10, define it to be int,
        # sufficient for getting the current code to work.
        #
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for EXCEPTION_DISPOSITION support in include files" >&5
-$as_echo_n "checking for EXCEPTION_DISPOSITION support in include files... " >&6; }
-if ${tcl_cv_eh_disposition+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for EXCEPTION_DISPOSITION support in include files" >&5
+printf %s "checking for EXCEPTION_DISPOSITION support in include files... " >&6; }
+if test ${tcl_cv_eh_disposition+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -7676,7 +8220,7 @@ else
 #          undef WIN32_LEAN_AND_MEAN
 
 int
-main ()
+main (void)
 {
 
                EXCEPTION_DISPOSITION x;
@@ -7685,19 +8229,20 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_eh_disposition=yes
-else
+else $as_nop
   tcl_cv_eh_disposition=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_eh_disposition" >&5
-$as_echo "$tcl_cv_eh_disposition" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_eh_disposition" >&5
+printf "%s\n" "$tcl_cv_eh_disposition" >&6; }
        if test "$tcl_cv_eh_disposition" = "no" ; then
 
-$as_echo "#define EXCEPTION_DISPOSITION int" >>confdefs.h
+printf "%s\n" "#define EXCEPTION_DISPOSITION int" >>confdefs.h
 
        fi
 
@@ -7705,11 +8250,12 @@ $as_echo "#define EXCEPTION_DISPOSITION int" >>confdefs.h
        # even if VOID has already been #defined. The win32api
        # used by mingw and cygwin is known to do this.
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for winnt.h that ignores VOID define" >&5
-$as_echo_n "checking for winnt.h that ignores VOID define... " >&6; }
-if ${tcl_cv_winnt_ignore_void+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for winnt.h that ignores VOID define" >&5
+printf %s "checking for winnt.h that ignores VOID define... " >&6; }
+if test ${tcl_cv_winnt_ignore_void+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -7719,7 +8265,7 @@ else
 #undef WIN32_LEAN_AND_MEAN
 
 int
-main ()
+main (void)
 {
 
                CHAR c;
@@ -7730,19 +8276,20 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_winnt_ignore_void=yes
-else
+else $as_nop
   tcl_cv_winnt_ignore_void=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_winnt_ignore_void" >&5
-$as_echo "$tcl_cv_winnt_ignore_void" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_winnt_ignore_void" >&5
+printf "%s\n" "$tcl_cv_winnt_ignore_void" >&6; }
        if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
 
-$as_echo "#define HAVE_WINNT_IGNORE_VOID 1" >>confdefs.h
+printf "%s\n" "#define HAVE_WINNT_IGNORE_VOID 1" >>confdefs.h
 
        fi
     fi
@@ -7751,16 +8298,17 @@ $as_echo "#define HAVE_WINNT_IGNORE_VOID 1" >>confdefs.h
        # This is used to stop gcc from printing a compiler
        # warning when initializing a union member.
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cast to union support" >&5
-$as_echo_n "checking for cast to union support... " >&6; }
-if ${tcl_cv_cast_to_union+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for cast to union support" >&5
+printf %s "checking for cast to union support... " >&6; }
+if test ${tcl_cv_cast_to_union+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 
                  union foo { int i; double d; };
@@ -7770,26 +8318,28 @@ main ()
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_cast_to_union=yes
-else
+else $as_nop
   tcl_cv_cast_to_union=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cast_to_union" >&5
-$as_echo "$tcl_cv_cast_to_union" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_cast_to_union" >&5
+printf "%s\n" "$tcl_cv_cast_to_union" >&6; }
        if test "$tcl_cv_cast_to_union" = "yes"; then
 
-$as_echo "#define HAVE_CAST_TO_UNION 1" >>confdefs.h
+printf "%s\n" "#define HAVE_CAST_TO_UNION 1" >>confdefs.h
 
        fi
 
-       ac_fn_c_check_header_mongrel "$LINENO" "stdbool.h" "ac_cv_header_stdbool_h" "$ac_includes_default"
-if test "x$ac_cv_header_stdbool_h" = xyes; then :
+       ac_fn_c_check_header_compile "$LINENO" "stdbool.h" "ac_cv_header_stdbool_h" "$ac_includes_default"
+if test "x$ac_cv_header_stdbool_h" = xyes
+then :
 
-$as_echo "#define HAVE_STDBOOL_H 1" >>confdefs.h
+printf "%s\n" "#define HAVE_STDBOOL_H 1" >>confdefs.h
 
 fi
 
 
 
 
+
     # These must be called after we do the basic CFLAGS checks and
     # verify any possible 64-bit or similar switches are necessary
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for required early compiler flags" >&5
-$as_echo_n "checking for required early compiler flags... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for required early compiler flags" >&5
+printf %s "checking for required early compiler flags... " >&6; }
     tcl_flags=""
 
-    if ${tcl_cv_flag__isoc99_source+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${tcl_cv_flag__isoc99_source+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdlib.h>
 int
-main ()
+main (void)
 {
 char *p = (char *)strtoll; char *q = (char *)strtoull;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__isoc99_source=no
-else
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #define _ISOC99_SOURCE 1
 #include <stdlib.h>
 int
-main ()
+main (void)
 {
 char *p = (char *)strtoll; char *q = (char *)strtoull;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__isoc99_source=yes
-else
+else $as_nop
   tcl_cv_flag__isoc99_source=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 
     if test "x${tcl_cv_flag__isoc99_source}" = "xyes" ; then
 
-$as_echo "#define _ISOC99_SOURCE 1" >>confdefs.h
+printf "%s\n" "#define _ISOC99_SOURCE 1" >>confdefs.h
 
        tcl_flags="$tcl_flags _ISOC99_SOURCE"
     fi
 
 
-    if ${tcl_cv_flag__largefile64_source+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${tcl_cv_flag__largefile64_source+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/stat.h>
 int
-main ()
+main (void)
 {
 struct stat64 buf; int i = stat64("/", &buf);
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__largefile64_source=no
-else
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #define _LARGEFILE64_SOURCE 1
 #include <sys/stat.h>
 int
-main ()
+main (void)
 {
 struct stat64 buf; int i = stat64("/", &buf);
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__largefile64_source=yes
-else
+else $as_nop
   tcl_cv_flag__largefile64_source=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 
     if test "x${tcl_cv_flag__largefile64_source}" = "xyes" ; then
 
-$as_echo "#define _LARGEFILE64_SOURCE 1" >>confdefs.h
+printf "%s\n" "#define _LARGEFILE64_SOURCE 1" >>confdefs.h
 
        tcl_flags="$tcl_flags _LARGEFILE64_SOURCE"
     fi
 
 
-    if ${tcl_cv_flag__largefile_source64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    if test ${tcl_cv_flag__largefile_source64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/stat.h>
 int
-main ()
+main (void)
 {
 char *p = (char *)open64;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__largefile_source64=no
-else
+else $as_nop
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #define _LARGEFILE_SOURCE64 1
 #include <sys/stat.h>
 int
-main ()
+main (void)
 {
 char *p = (char *)open64;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_flag__largefile_source64=yes
-else
+else $as_nop
   tcl_cv_flag__largefile_source64=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 
     if test "x${tcl_cv_flag__largefile_source64}" = "xyes" ; then
 
-$as_echo "#define _LARGEFILE_SOURCE64 1" >>confdefs.h
+printf "%s\n" "#define _LARGEFILE_SOURCE64 1" >>confdefs.h
 
        tcl_flags="$tcl_flags _LARGEFILE_SOURCE64"
     fi
 
     if test "x${tcl_flags}" = "x" ; then
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5
-$as_echo "none" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none" >&5
+printf "%s\n" "none" >&6; }
     else
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${tcl_flags}" >&5
-$as_echo "${tcl_flags}" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${tcl_flags}" >&5
+printf "%s\n" "${tcl_flags}" >&6; }
     fi
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for 64-bit integer type" >&5
-$as_echo_n "checking for 64-bit integer type... " >&6; }
-    if ${tcl_cv_type_64bit+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for 64-bit integer type" >&5
+printf %s "checking for 64-bit integer type... " >&6; }
+    if test ${tcl_cv_type_64bit+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
        tcl_cv_type_64bit=none
        # See if the compiler knows natively about __int64
@@ -7975,19 +8536,20 @@ else
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 __int64 value = (__int64) 0;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_type_64bit=__int64
-else
+else $as_nop
   tcl_type_64bit="long long"
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
        # See if we could use long anyway  Note that we substitute in the
        # type that is our current guess for a 64-bit type inside this check
        # program, so it should be modified only carefully...
@@ -7995,7 +8557,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 /* end confdefs.h.  */
 
 int
-main ()
+main (void)
 {
 switch (0) {
             case 1: case (sizeof(${tcl_type_64bit})==sizeof(long)): ;
@@ -8004,79 +8566,81 @@ switch (0) {
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_type_64bit=${tcl_type_64bit}
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 
     if test "${tcl_cv_type_64bit}" = none ; then
 
-$as_echo "#define TCL_WIDE_INT_IS_LONG 1" >>confdefs.h
+printf "%s\n" "#define TCL_WIDE_INT_IS_LONG 1" >>confdefs.h
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+printf "%s\n" "yes" >&6; }
     elif test "${tcl_cv_type_64bit}" = "__int64" \
                -a "${TEA_PLATFORM}" = "windows" ; then
        # TEA specific: We actually want to use the default tcl.h checks in
        # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: using Tcl header defaults" >&5
-$as_echo "using Tcl header defaults" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: using Tcl header defaults" >&5
+printf "%s\n" "using Tcl header defaults" >&6; }
     else
 
-cat >>confdefs.h <<_ACEOF
-#define TCL_WIDE_INT_TYPE ${tcl_cv_type_64bit}
-_ACEOF
+printf "%s\n" "#define TCL_WIDE_INT_TYPE ${tcl_cv_type_64bit}" >>confdefs.h
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${tcl_cv_type_64bit}" >&5
-$as_echo "${tcl_cv_type_64bit}" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${tcl_cv_type_64bit}" >&5
+printf "%s\n" "${tcl_cv_type_64bit}" >&6; }
 
        # Now check for auxiliary declarations
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct dirent64" >&5
-$as_echo_n "checking for struct dirent64... " >&6; }
-if ${tcl_cv_struct_dirent64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for struct dirent64" >&5
+printf %s "checking for struct dirent64... " >&6; }
+if test ${tcl_cv_struct_dirent64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <dirent.h>
 int
-main ()
+main (void)
 {
 struct dirent64 p;
   ;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_struct_dirent64=yes
-else
+else $as_nop
   tcl_cv_struct_dirent64=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_struct_dirent64" >&5
-$as_echo "$tcl_cv_struct_dirent64" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_struct_dirent64" >&5
+printf "%s\n" "$tcl_cv_struct_dirent64" >&6; }
        if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
 
-$as_echo "#define HAVE_STRUCT_DIRENT64 1" >>confdefs.h
+printf "%s\n" "#define HAVE_STRUCT_DIRENT64 1" >>confdefs.h
 
        fi
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DIR64" >&5
-$as_echo_n "checking for DIR64... " >&6; }
-if ${tcl_cv_DIR64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for DIR64" >&5
+printf %s "checking for DIR64... " >&6; }
+if test ${tcl_cv_DIR64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 #include <dirent.h>
 int
-main ()
+main (void)
 {
 struct dirent64 *p; DIR64 d = opendir64(".");
             p = readdir64(d); rewinddir64(d); closedir64(d);
@@ -8084,32 +8648,34 @@ struct dirent64 *p; DIR64 d = opendir64(".");
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_DIR64=yes
-else
+else $as_nop
   tcl_cv_DIR64=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_DIR64" >&5
-$as_echo "$tcl_cv_DIR64" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_DIR64" >&5
+printf "%s\n" "$tcl_cv_DIR64" >&6; }
        if test "x${tcl_cv_DIR64}" = "xyes" ; then
 
-$as_echo "#define HAVE_DIR64 1" >>confdefs.h
+printf "%s\n" "#define HAVE_DIR64 1" >>confdefs.h
 
        fi
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct stat64" >&5
-$as_echo_n "checking for struct stat64... " >&6; }
-if ${tcl_cv_struct_stat64+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for struct stat64" >&5
+printf %s "checking for struct stat64... " >&6; }
+if test ${tcl_cv_struct_stat64+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/stat.h>
 int
-main ()
+main (void)
 {
 struct stat64 p;
 
@@ -8117,44 +8683,47 @@ struct stat64 p;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_struct_stat64=yes
-else
+else $as_nop
   tcl_cv_struct_stat64=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_struct_stat64" >&5
-$as_echo "$tcl_cv_struct_stat64" >&6; }
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $tcl_cv_struct_stat64" >&5
+printf "%s\n" "$tcl_cv_struct_stat64" >&6; }
        if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
 
-$as_echo "#define HAVE_STRUCT_STAT64 1" >>confdefs.h
+printf "%s\n" "#define HAVE_STRUCT_STAT64 1" >>confdefs.h
 
        fi
 
-       for ac_func in open64 lseek64
-do :
-  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
-ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
-if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
-  cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
-_ACEOF
+       ac_fn_c_check_func "$LINENO" "open64" "ac_cv_func_open64"
+if test "x$ac_cv_func_open64" = xyes
+then :
+  printf "%s\n" "#define HAVE_OPEN64 1" >>confdefs.h
 
 fi
-done
+ac_fn_c_check_func "$LINENO" "lseek64" "ac_cv_func_lseek64"
+if test "x$ac_cv_func_lseek64" = xyes
+then :
+  printf "%s\n" "#define HAVE_LSEEK64 1" >>confdefs.h
 
-       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for off64_t" >&5
-$as_echo_n "checking for off64_t... " >&6; }
-       if ${tcl_cv_type_off64_t+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
+fi
+
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for off64_t" >&5
+printf %s "checking for off64_t... " >&6; }
+       if test ${tcl_cv_type_off64_t+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
 
            cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <sys/types.h>
 int
-main ()
+main (void)
 {
 off64_t offset;
 
@@ -8162,25 +8731,26 @@ off64_t offset;
   return 0;
 }
 _ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
+if ac_fn_c_try_compile "$LINENO"
+then :
   tcl_cv_type_off64_t=yes
-else
+else $as_nop
   tcl_cv_type_off64_t=no
 fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext
 fi
 
                        if test "x${tcl_cv_type_off64_t}" = "xyes" && \
                test "x${ac_cv_func_lseek64}" = "xyes" && \
                test "x${ac_cv_func_open64}" = "xyes" ; then
 
-$as_echo "#define HAVE_TYPE_OFF64_T 1" >>confdefs.h
+printf "%s\n" "#define HAVE_TYPE_OFF64_T 1" >>confdefs.h
 
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+printf "%s\n" "yes" >&6; }
        else
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
        fi
     fi
 
@@ -8192,50 +8762,45 @@ $as_echo "no" >&6; }
 
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for build with symbols" >&5
-$as_echo_n "checking for build with symbols... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for build with symbols" >&5
+printf %s "checking for build with symbols... " >&6; }
     # Check whether --enable-symbols was given.
-if test "${enable_symbols+set}" = set; then :
+if test ${enable_symbols+y}
+then :
   enableval=$enable_symbols; tcl_ok=$enableval
-else
+else $as_nop
   tcl_ok=no
 fi
 
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
        LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
-       { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
+       { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5
+printf "%s\n" "no" >&6; }
     else
        CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
        LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
        if test "$tcl_ok" = "yes"; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes (standard debugging)" >&5
-$as_echo "yes (standard debugging)" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes (standard debugging)" >&5
+printf "%s\n" "yes (standard debugging)" >&6; }
        fi
     fi
-    # TEA specific:
-    if test "${TEA_PLATFORM}" != "windows" ; then
-       LDFLAGS_DEFAULT="${LDFLAGS}"
-    fi
-
 
 
 
     if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
 
-$as_echo "#define TCL_MEM_DEBUG 1" >>confdefs.h
+printf "%s\n" "#define TCL_MEM_DEBUG 1" >>confdefs.h
 
     fi
 
     if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
        if test "$tcl_ok" = "all"; then
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled symbols mem debugging" >&5
-$as_echo "enabled symbols mem debugging" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: enabled symbols mem debugging" >&5
+printf "%s\n" "enabled symbols mem debugging" >&6; }
        else
-           { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled $tcl_ok debugging" >&5
-$as_echo "enabled $tcl_ok debugging" >&6; }
+           { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: enabled $tcl_ok debugging" >&5
+printf "%s\n" "enabled $tcl_ok debugging" >&6; }
        fi
     fi
 
@@ -8248,7 +8813,7 @@ $as_echo "enabled $tcl_ok debugging" >&6; }
 #--------------------------------------------------------------------
 
 
-$as_echo "#define USE_TCL_STUBS 1" >>confdefs.h
+printf "%s\n" "#define USE_TCL_STUBS 1" >>confdefs.h
 
 
 #--------------------------------------------------------------------
@@ -8258,10 +8823,10 @@ $as_echo "#define USE_TCL_STUBS 1" >>confdefs.h
 #--------------------------------------------------------------------
 
 
-$as_echo "#define TCL_TIP143 1" >>confdefs.h
+printf "%s\n" "#define TCL_TIP143 1" >>confdefs.h
 
 
-$as_echo "#define TCL_TIP285 1" >>confdefs.h
+printf "%s\n" "#define TCL_TIP285 1" >>confdefs.h
 
 
 #--------------------------------------------------------------------
@@ -8271,9 +8836,152 @@ $as_echo "#define TCL_TIP285 1" >>confdefs.h
 #--------------------------------------------------------------------
 
 
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+printf %s "checking for grep that handles long lines and -e... " >&6; }
+if test ${ac_cv_path_GREP+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  if test -z "$GREP"; then
+  ac_path_GREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_prog in grep ggrep
+   do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_GREP" || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  printf %s 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    printf "%s\n" 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_GREP=$GREP
+fi
+
+fi
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+printf "%s\n" "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+printf %s "checking for egrep... " >&6; }
+if test ${ac_cv_path_EGREP+y}
+then :
+  printf %s "(cached) " >&6
+else $as_nop
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    for ac_prog in egrep
+   do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_EGREP" || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  printf %s 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    printf "%s\n" 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+   fi
+fi
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+printf "%s\n" "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+
     if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
        MAKE_STATIC_LIB="\${STLIB_LD} -out:\$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
@@ -8283,7 +8991,8 @@ print("manifest needed")
 
 _ACEOF
 if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "manifest needed" >/dev/null 2>&1; then :
+  $EGREP "manifest needed" >/dev/null 2>&1
+then :
 
        # Could do a CHECK_PROG for mt, but should always be with MSVC8+
        VC_MANIFEST_EMBED_DLL="if test -f \$@.manifest ; then mt.exe -nologo -manifest \$@.manifest -outputresource:\$@\;2 ; fi"
@@ -8294,12 +9003,12 @@ if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
 
 
 fi
-rm -f conftest*
+rm -rf conftest*
 
        MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\$@ \$(PKG_STUB_OBJECTS)"
     else
        MAKE_STATIC_LIB="\${STLIB_LD} \$@ \$(PKG_OBJECTS)"
-       MAKE_SHARED_LIB="\${SHLIB_LD} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \$@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
        MAKE_STUB_LIB="\${STLIB_LD} \$@ \$(PKG_STUB_OBJECTS)"
     fi
 
@@ -8382,19 +9091,19 @@ rm -f conftest*
 #--------------------------------------------------------------------
 
 
-    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for tclsh" >&5
-$as_echo_n "checking for tclsh... " >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for tclsh" >&5
+printf %s "checking for tclsh... " >&6; }
     if test -f "${TCL_BIN_DIR}/Makefile" ; then
         # tclConfig.sh is in Tcl build directory
         if test "${TEA_PLATFORM}" = "windows"; then
-          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}s${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}t${EXEEXT}"
-          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}" ; then
-            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}st${EXEEXT}"
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
           fi
         else
             TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
@@ -8402,9 +9111,9 @@ $as_echo_n "checking for tclsh... " >&6; }
     else
         # tclConfig.sh is in install location
         if test "${TEA_PLATFORM}" = "windows"; then
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${TCL_DBGX}${EXEEXT}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
         else
-            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}${TCL_DBGX}"
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
         fi
         list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
               `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
@@ -8417,8 +9126,8 @@ $as_echo_n "checking for tclsh... " >&6; }
         done
         TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
     fi
-    { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${TCLSH_PROG}" >&5
-$as_echo "${TCLSH_PROG}" >&6; }
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${TCLSH_PROG}" >&5
+printf "%s\n" "${TCLSH_PROG}" >&6; }
 
 
 #TEA_PROG_WISH
@@ -8458,8 +9167,8 @@ _ACEOF
     case $ac_val in #(
     *${as_nl}*)
       case $ac_var in #(
-      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
       esac
       case $ac_var in #(
       _ | IFS | as_nl) ;; #(
@@ -8489,15 +9198,15 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
      /^ac_cv_env_/b end
      t clear
      :clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     s/^\([^=]*\)=\(.*[{}].*\)$/test ${\1+y} || &/
      t end
      s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
      :end' >>confcache
 if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
   if test -w "$cache_file"; then
     if test "x$cache_file" != "x/dev/null"; then
-      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
+      { printf "%s\n" "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+printf "%s\n" "$as_me: updating cache $cache_file" >&6;}
       if test ! -f "$cache_file" || test -h "$cache_file"; then
        cat confcache >"$cache_file"
       else
@@ -8511,8 +9220,8 @@ $as_echo "$as_me: updating cache $cache_file" >&6;}
       fi
     fi
   else
-    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+    { printf "%s\n" "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+printf "%s\n" "$as_me: not updating unwritable cache $cache_file" >&6;}
   fi
 fi
 rm -f confcache
@@ -8565,7 +9274,7 @@ U=
 for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
   # 1. Remove the extension, and $U if already installed.
   ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  ac_i=`printf "%s\n" "$ac_i" | sed "$ac_script"`
   # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
   #    will be set to the directory where LIBOBJS objects are built.
   as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
@@ -8583,8 +9292,8 @@ CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""
 ac_write_fail=0
 ac_clean_files_save=$ac_clean_files
 ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+printf "%s\n" "$as_me: creating $CONFIG_STATUS" >&6;}
 as_write_fail=0
 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
 #! $SHELL
@@ -8607,14 +9316,16 @@ cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
 
 # Be more Bourne compatible
 DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+as_nop=:
+if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1
+then :
   emulate sh
   NULLCMD=:
   # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
   setopt NO_GLOB_SUBST
-else
+else $as_nop
   case `(set -o) 2>/dev/null` in #(
   *posix*) :
     set -o posix ;; #(
@@ -8624,46 +9335,46 @@ esac
 fi
 
 
+
+# Reset variables that may have inherited troublesome values from
+# the environment.
+
+# IFS needs to be set, to space, tab, and newline, in precisely that order.
+# (If _AS_PATH_WALK were called with IFS unset, it would have the
+# side effect of setting IFS to empty, thus disabling word splitting.)
+# Quoting is to prevent editors from complaining about space-tab.
 as_nl='
 '
 export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
-    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='print -r --'
-  as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
-  as_echo='printf %s\n'
-  as_echo_n='printf %s'
-else
-  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
-    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
-    as_echo_n='/usr/ucb/echo -n'
-  else
-    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
-    as_echo_n_body='eval
-      arg=$1;
-      case $arg in #(
-      *"$as_nl"*)
-       expr "X$arg" : "X\\(.*\\)$as_nl";
-       arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
-      esac;
-      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
-    '
-    export as_echo_n_body
-    as_echo_n='sh -c $as_echo_n_body as_echo'
-  fi
-  export as_echo_body
-  as_echo='sh -c $as_echo_body as_echo'
-fi
+IFS=" ""       $as_nl"
+
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# Ensure predictable behavior from utilities with locale-dependent output.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# We cannot yet rely on "unset" to work, but we need these variables
+# to be unset--not just set to an empty or harmless value--now, to
+# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh).  This construct
+# also avoids known problems related to "unset" and subshell syntax
+# in other old shells (e.g. bash 2.01 and pdksh 5.2.14).
+for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH
+do eval test \${$as_var+y} \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+
+# Ensure that fds 0, 1, and 2 are open.
+if (exec 3>&0) 2>/dev/null; then :; else exec 0</dev/null; fi
+if (exec 3>&1) 2>/dev/null; then :; else exec 1>/dev/null; fi
+if (exec 3>&2)            ; then :; else exec 2>/dev/null; fi
 
 # The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
+if ${PATH_SEPARATOR+false} :; then
   PATH_SEPARATOR=:
   (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
     (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
@@ -8672,13 +9383,6 @@ if test "${PATH_SEPARATOR+set}" != set; then
 fi
 
 
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" ""       $as_nl"
-
 # Find who we are.  Look in the path if we contain no directory separator.
 as_myself=
 case $0 in #((
@@ -8687,8 +9391,12 @@ case $0 in #((
 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
+  case $as_dir in #(((
+    '') as_dir=./ ;;
+    */) ;;
+    *) as_dir=$as_dir/ ;;
+  esac
+    test -r "$as_dir$0" && as_myself=$as_dir$0 && break
   done
 IFS=$as_save_IFS
 
@@ -8700,30 +9408,10 @@ if test "x$as_myself" = x; then
   as_myself=$0
 fi
 if test ! -f "$as_myself"; then
-  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
   exit 1
 fi
 
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there.  '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
-  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
 
 # as_fn_error STATUS ERROR [LINENO LOG_FD]
@@ -8736,13 +9424,14 @@ as_fn_error ()
   as_status=$1; test $as_status -eq 0 && as_status=1
   if test "$4"; then
     as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+    printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
   fi
-  $as_echo "$as_me: error: $2" >&2
+  printf "%s\n" "$as_me: error: $2" >&2
   as_fn_exit $as_status
 } # as_fn_error
 
 
+
 # as_fn_set_status STATUS
 # -----------------------
 # Set $? to STATUS, without forking.
@@ -8769,18 +9458,20 @@ as_fn_unset ()
   { eval $1=; unset $1;}
 }
 as_unset=as_fn_unset
+
 # as_fn_append VAR VALUE
 # ----------------------
 # Append the text in VALUE to the end of the definition contained in VAR. Take
 # advantage of any shell optimizations that allow amortized linear growth over
 # repeated appends, instead of the typical quadratic growth present in naive
 # implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null
+then :
   eval 'as_fn_append ()
   {
     eval $1+=\$2
   }'
-else
+else $as_nop
   as_fn_append ()
   {
     eval $1=\$$1\$2
@@ -8792,12 +9483,13 @@ fi # as_fn_append
 # Perform arithmetic evaluation on the ARGs, and store the result in the
 # global $as_val. Take advantage of shells that can avoid forks. The arguments
 # must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null
+then :
   eval 'as_fn_arith ()
   {
     as_val=$(( $* ))
   }'
-else
+else $as_nop
   as_fn_arith ()
   {
     as_val=`expr "$@" || test $? -eq 1`
@@ -8828,7 +9520,7 @@ as_me=`$as_basename -- "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
         X"$0" : 'X\(//\)$' \| \
         X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
+printf "%s\n" X/"$0" |
     sed '/^.*\/\([^/][^/]*\)\/*$/{
            s//\1/
            q
@@ -8850,6 +9542,10 @@ as_cr_Letters=$as_cr_letters$as_cr_LETTERS
 as_cr_digits='0123456789'
 as_cr_alnum=$as_cr_Letters$as_cr_digits
 
+
+# Determine whether it's possible to make 'echo' print without a newline.
+# These variables are no longer used directly by Autoconf, but are AC_SUBSTed
+# for compatibility with existing Makefiles.
 ECHO_C= ECHO_N= ECHO_T=
 case `echo -n x` in #(((((
 -n*)
@@ -8863,6 +9559,12 @@ case `echo -n x` in #(((((
   ECHO_N='-n';;
 esac
 
+# For backward compatibility with old third-party macros, we provide
+# the shell variables $as_echo and $as_echo_n.  New code should use
+# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively.
+as_echo='printf %s\n'
+as_echo_n='printf %s'
+
 rm -f conf$$ conf$$.exe conf$$.file
 if test -d conf$$.dir; then
   rm -f conf$$.dir/conf$$.file
@@ -8904,7 +9606,7 @@ as_fn_mkdir_p ()
     as_dirs=
     while :; do
       case $as_dir in #(
-      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
       *) as_qdir=$as_dir;;
       esac
       as_dirs="'$as_qdir' $as_dirs"
@@ -8913,7 +9615,7 @@ $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$as_dir" : 'X\(//\)[^/]' \| \
         X"$as_dir" : 'X\(//\)$' \| \
         X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
+printf "%s\n" X"$as_dir" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
            s//\1/
            q
@@ -8975,8 +9677,8 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by thread $as_me 2.8.5, which was
-generated by GNU Autoconf 2.69.  Invocation command line was
+This file was extended by thread $as_me 2.8.6, which was
+generated by GNU Autoconf 2.70.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
   CONFIG_HEADERS  = $CONFIG_HEADERS
@@ -9025,14 +9727,16 @@ $config_files
 Report bugs to the package provider."
 
 _ACEOF
+ac_cs_config=`printf "%s\n" "$ac_configure_args" | sed "$ac_safe_unquote"`
+ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\''/g"`
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_config='$ac_cs_config_escaped'
 ac_cs_version="\\
-thread config.status 2.8.5
-configured by $0, generated by GNU Autoconf 2.69,
+thread config.status 2.8.6
+configured by $0, generated by GNU Autoconf 2.70,
   with options \\"\$ac_cs_config\\"
 
-Copyright (C) 2012 Free Software Foundation, Inc.
+Copyright (C) 2020 Free Software Foundation, Inc.
 This config.status script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it."
 
@@ -9069,21 +9773,21 @@ do
   -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
     ac_cs_recheck=: ;;
   --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    $as_echo "$ac_cs_version"; exit ;;
+    printf "%s\n" "$ac_cs_version"; exit ;;
   --config | --confi | --conf | --con | --co | --c )
-    $as_echo "$ac_cs_config"; exit ;;
+    printf "%s\n" "$ac_cs_config"; exit ;;
   --debug | --debu | --deb | --de | --d | -d )
     debug=: ;;
   --file | --fil | --fi | --f )
     $ac_shift
     case $ac_optarg in
-    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
     '') as_fn_error $? "missing file argument" ;;
     esac
     as_fn_append CONFIG_FILES " '$ac_optarg'"
     ac_need_defaults=false;;
   --he | --h |  --help | --hel | -h )
-    $as_echo "$ac_cs_usage"; exit ;;
+    printf "%s\n" "$ac_cs_usage"; exit ;;
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil | --si | --s)
     ac_cs_silent=: ;;
@@ -9111,7 +9815,7 @@ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 if \$ac_cs_recheck; then
   set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
   shift
-  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  \printf "%s\n" "running CONFIG_SHELL=$SHELL \$*" >&6
   CONFIG_SHELL='$SHELL'
   export CONFIG_SHELL
   exec "\$@"
@@ -9125,7 +9829,7 @@ exec 5>>config.log
   sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
 ## Running $as_me. ##
 _ASBOX
-  $as_echo "$ac_log"
+  printf "%s\n" "$ac_log"
 } >&5
 
 _ACEOF
@@ -9151,7 +9855,7 @@ done
 # 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_FILES+y} || CONFIG_FILES=$config_files
 fi
 
 # Have a temporary directory for convenience.  Make it in the build tree
@@ -9379,7 +10083,7 @@ do
           esac ||
           as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
       esac
-      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      case $ac_f in *\'*) ac_f=`printf "%s\n" "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
       as_fn_append ac_file_inputs " '$ac_f'"
     done
 
     # use $as_me), people would be surprised to read:
     #    /* config.h.  Generated by config.status.  */
     configure_input='Generated from '`
-         $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+         printf "%s\n" "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
        `' by configure.'
     if test x"$ac_file" != x-; then
       configure_input="$ac_file.  $configure_input"
-      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
+      { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+printf "%s\n" "$as_me: creating $ac_file" >&6;}
     fi
     # Neutralize special characters interpreted by sed in replacement strings.
     case $configure_input in #(
     *\&* | *\|* | *\\* )
-       ac_sed_conf_input=`$as_echo "$configure_input" |
+       ac_sed_conf_input=`printf "%s\n" "$configure_input" |
        sed 's/[\\\\&|]/\\\\&/g'`;; #(
     *) ac_sed_conf_input=$configure_input;;
     esac
@@ -9414,7 +10118,7 @@ $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$ac_file" : 'X\(//\)[^/]' \| \
         X"$ac_file" : 'X\(//\)$' \| \
         X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
+printf "%s\n" X"$ac_file" |
     sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
            s//\1/
            q
@@ -9438,9 +10142,9 @@ $as_echo X"$ac_file" |
 case "$ac_dir" in
 .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
 *)
-  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'`
   # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
   case $ac_top_builddir_sub in
   "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
   *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
@@ -9493,8 +10197,8 @@ ac_sed_dataroot='
 case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
 *datarootdir*) ac_datarootdir_seen=yes;;
 *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+printf "%s\n" "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
   ac_datarootdir_hack='
@@ -9536,9 +10240,9 @@ test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
   { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
   { ac_out=`sed -n '/^[         ]*datarootdir[  ]*:*=/p' \
       "$ac_tmp/out"`; test -z "$ac_out"; } &&
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&2;}
 
   rm -f "$ac_tmp/stdin"
@@ -9585,7 +10289,8 @@ if test "$no_create" != yes; then
   $ac_cs_success || as_fn_exit 1
 fi
 if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+  { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
 fi
 
+
similarity index 99%
rename from pkgs/thread2.8.5/configure.ac
rename to pkgs/thread2.8.6/configure.ac
index 303f518..3f70e0c 100644 (file)
@@ -17,7 +17,7 @@ dnl   to configure the system for the local environment.
 # so you can encode the package version directly into the source files.
 #-----------------------------------------------------------------------
 
-AC_INIT([thread], [2.8.5])
+AC_INIT([thread],[2.8.6])
 
 #--------------------------------------------------------------------
 # Call TEA_INIT as the first TEA_ macro to set up initial vars.
@@ -225,4 +225,5 @@ TEA_PROG_TCLSH
 # which require substituting th AC variables in.  Include these here.
 #--------------------------------------------------------------------
 
-AC_OUTPUT([Makefile pkgIndex.tcl])
+AC_CONFIG_FILES([Makefile pkgIndex.tcl])
+AC_OUTPUT
similarity index 93%
rename from pkgs/thread2.8.5/generic/psGdbm.c
rename to pkgs/thread2.8.6/generic/psGdbm.c
index f496d7c..c640a35 100644 (file)
@@ -374,17 +374,18 @@ static const char*
 ps_gdbm_geterr(
     ClientData handle)
 {
-   /*
-    * The problem with gdbm interface is that it uses the global
-    * gdbm_errno variable which is not per-thread nor mutex
-    * protected. This variable is used to reference array of gdbm
-    * error text strings. It is very dangeours to use this in the
-    * MT-program without proper locking. For this kind of app
-    * we should not be concerned with that, since all ps_gdbm_xxx
-    * operations are performed under shared variable lock anyway.
-    */
-
-    return gdbm_strerror(gdbm_errno);
+    (void)handle;
+    /*
+     * The problem with gdbm interface is that it uses the global
+     * gdbm_errno variable which is not per-thread nor mutex
+     * protected. This variable is used to reference array of gdbm
+     * error text strings. It is very dangerous to use this in the
+     * MT-program without proper locking. For this kind of app
+     * we should not be concerned with that, since all ps_gdbm_xxx
+     * operations are performed under shared variable lock anyway.
+     */
+
+     return gdbm_strerror(gdbm_errno);
 }
 
 #endif  /* HAVE_GDBM */
similarity index 97%
rename from pkgs/thread2.8.5/generic/psLmdb.c
rename to pkgs/thread2.8.6/generic/psLmdb.c
index d2e1413..6ed860d 100644 (file)
@@ -159,7 +159,7 @@ ps_lmdb_open(
     char *ext;
     Tcl_DString toext;
 
-    ctx = ckalloc(sizeof(*ctx));
+    ctx = (LmdbCtx)ckalloc(sizeof(*ctx));
     if (ctx == NULL)
     {
         return NULL;
@@ -268,7 +268,7 @@ ps_lmdb_get(
         return 1;
     }
 
-    *dataptrptr = data.mv_data;
+    *dataptrptr = (char *)data.mv_data;
     *lenptr = data.mv_size;
 
     /*
@@ -328,9 +328,9 @@ ps_lmdb_first(
         return 1;
     }
 
-    *dataptrptr = data.mv_data;
+    *dataptrptr = (char *)data.mv_data;
     *lenptr = data.mv_size;
-    *keyptrptr = key.mv_data;
+    *keyptrptr = (char *)key.mv_data;
 
     return 0;
 }
@@ -369,9 +369,9 @@ static int ps_lmdb_next(
         return 1;
     }
 
-    *dataptrptr = data.mv_data;
+    *dataptrptr = (char *)data.mv_data;
     *lenptr = data.mv_size;
-    *keyptrptr = key.mv_data;
+    *keyptrptr = (char *)key.mv_data;
 
     return 0;
 }
similarity index 81%
rename from pkgs/thread2.8.5/generic/tclThreadInt.h
rename to pkgs/thread2.8.6/generic/tclThreadInt.h
index bbf8213..c2c6082 100644 (file)
@@ -119,7 +119,7 @@ MODULE_SCOPE int Tpool_Init(Tcl_Interp *interp);
     return TCL_ERROR
 
 #define OPT_CMP(a,b) \
-  ((a) && (b) && (*(a)==*(b)) && (*(a+1)==*(b+1)) && (!strcmp((a),(b))))
+  ((a) && (b) && ((a)[0]==(b)[0]) && ((a)[1]==(b)[1]) && (!strcmp((a),(b))))
 
 #ifndef TCL_TSD_INIT
 #define TCL_TSD_INIT(keyPtr) \
@@ -153,18 +153,18 @@ typedef struct {
 #if defined(TCL_TIP285) && defined(USE_TCL_STUBS)
 # undef Tcl_GetErrorLine
 # define Tcl_GetErrorLine(interp) ((threadTclVersion>85)? \
-    ((int (*)(Tcl_Interp *))((&(tclStubsPtr->tcl_PkgProvideEx))[605]))(interp): \
+    ((int (*)(Tcl_Interp *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[605]))(interp): \
     (((tclInterpType *)(interp))->errorLine))
 /* TIP #270 */
 # undef Tcl_AddErrorInfo
 # define Tcl_AddErrorInfo(interp, msg) ((threadTclVersion>85)? \
-    ((void (*)(Tcl_Interp *, Tcl_Obj *))((&(tclStubsPtr->tcl_PkgProvideEx))[574]))(interp, Tcl_NewStringObj(msg, -1)): \
-    ((void (*)(Tcl_Interp *, const char *))((&(tclStubsPtr->tcl_PkgProvideEx))[66]))(interp, msg))
+    ((void (*)(Tcl_Interp *, Tcl_Obj *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[574]))(interp, Tcl_NewStringObj(msg, -1)): \
+    ((void (*)(Tcl_Interp *, const char *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[66]))(interp, msg))
 /* TIP #337 */
 # undef Tcl_BackgroundException
 # define Tcl_BackgroundException(interp, result) ((threadTclVersion>85)? \
-    ((void (*)(Tcl_Interp *, int))((&(tclStubsPtr->tcl_PkgProvideEx))[609]))(interp, result): \
-    ((void (*)(Tcl_Interp *))((&(tclStubsPtr->tcl_PkgProvideEx))[76]))(interp))
+    ((void (*)(Tcl_Interp *, int))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[609]))(interp, result): \
+    ((void (*)(Tcl_Interp *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[76]))(interp))
 #elif !TCL_MINIMUM_VERSION(8,6)
   /* 8.5, 8.4, or less - Emulate access to the error-line information */
 # define Tcl_GetErrorLine(interp) (((tclInterpType *)(interp))->errorLine)
@@ -179,15 +179,15 @@ typedef struct {
 #if defined(USE_TCL_STUBS)
 # undef Tcl_SetIntObj
 # define Tcl_SetIntObj(objPtr, value) ((threadTclVersion>86)? \
-  ((void (*)(Tcl_Obj *, Tcl_WideInt))((&(tclStubsPtr->tcl_PkgProvideEx))[489]))(objPtr, (int)(value)): \
-  ((void (*)(Tcl_Obj *, int))((&(tclStubsPtr->tcl_PkgProvideEx))[61]))(objPtr, value))
+  ((void (*)(Tcl_Obj *, Tcl_WideInt))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[489]))(objPtr, (int)(value)): \
+  ((void (*)(Tcl_Obj *, int))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[61]))(objPtr, value))
 # undef Tcl_NewIntObj
 # define Tcl_NewIntObj(value) ((threadTclVersion>86)? \
-  ((Tcl_Obj * (*)(Tcl_WideInt))((&(tclStubsPtr->tcl_PkgProvideEx))[488]))((int)(value)): \
-  ((Tcl_Obj * (*)(int))((&(tclStubsPtr->tcl_PkgProvideEx))[52]))(value))
+  ((Tcl_Obj * (*)(Tcl_WideInt))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[488]))((int)(value)): \
+  ((Tcl_Obj * (*)(int))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[52]))(value))
 # undef Tcl_GetUnicodeFromObj
 # define Tcl_GetUnicodeFromObj ((((&(tclStubsPtr->tcl_PkgProvideEx))[378]) != ((&(tclStubsPtr->tcl_PkgProvideEx))[434])) ? \
-  ((void (*)(Tcl_Obj *, int *))((&(tclStubsPtr->tcl_PkgProvideEx))[434])) : ((void (*)(Tcl_Obj *, int *)) NULL))
+  ((void (*)(Tcl_Obj *, int *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[434])) : ((void (*)(Tcl_Obj *, int *)) NULL))
 #endif
 
 #endif /* _TCL_THREAD_INT_H_ */
similarity index 99%
rename from pkgs/thread2.8.5/generic/tclXkeylist.c
rename to pkgs/thread2.8.6/generic/tclXkeylist.c
index 913b008..54cc14a 100644 (file)
@@ -51,7 +51,7 @@
  */
 #undef Tcl_RegisterObjType
 #define Tcl_RegisterObjType(typePtr) if (threadTclVersion<90) { \
-    ((void (*)(const Tcl_ObjType *))((&(tclStubsPtr->tcl_PkgProvideEx))[211]))(typePtr); \
+    ((void (*)(const Tcl_ObjType *))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[211]))(typePtr); \
 } else { \
     (typePtr)->setFromAnyProc = NULL; \
 }
@@ -555,11 +555,11 @@ FindKeyedListEntry(
     size_t       *keyLenPtr,
     const char   **nextSubKeyPtr
 ) {
-    char *keySeparPtr;
+    const char *keySeparPtr;
     size_t keyLen;
     int findIdx;
 
-    keySeparPtr = strchr (key, '.');
+    keySeparPtr = strchr(key, '.');
     if (keySeparPtr != NULL) {
         keyLen = keySeparPtr - key;
     } else {
@@ -1262,7 +1262,7 @@ Tcl_KeylgetObjCmd(
  */
 static int
 Tcl_KeylsetObjCmd(
-    void        *clientData,
+    void        *dummy,
     Tcl_Interp  *interp,
     int          objc,
     Tcl_Obj     *const objv[]
@@ -1270,6 +1270,7 @@ Tcl_KeylsetObjCmd(
     Tcl_Obj *keylVarPtr, *newVarObj;
     const char *key;
     int idx;
+    (void)dummy;
 
     if ((objc < 4) || ((objc % 2) != 0)) {
         return TclX_WrongArgs (interp, objv [0],
@@ -1325,7 +1326,7 @@ Tcl_KeylsetObjCmd(
  */
 static int
 Tcl_KeyldelObjCmd(
-    void        *clientData,
+    void        *dummy,
     Tcl_Interp  *interp,
     int          objc,
     Tcl_Obj     *const objv[]
@@ -1333,6 +1334,7 @@ Tcl_KeyldelObjCmd(
     Tcl_Obj *keylVarPtr, *keylPtr;
     const char *key;
     int idx, status;
+    (void)dummy;
 
     if (objc < 3) {
         return TclX_WrongArgs (interp, objv [0], "listvar key ?key ...?");
@@ -1387,7 +1389,7 @@ Tcl_KeyldelObjCmd(
  */
 static int
 Tcl_KeylkeysObjCmd(
-    void        *clientData,
+    void        *dummy,
     Tcl_Interp  *interp,
     int          objc,
     Tcl_Obj     *const objv[]
@@ -1395,6 +1397,7 @@ Tcl_KeylkeysObjCmd(
     Tcl_Obj *keylPtr, *listObjPtr;
     const char *key;
     int status;
+    (void)dummy;
 
     if ((objc < 2) || (objc > 3)) {
         return TclX_WrongArgs(interp, objv [0], "listvar ?key?");
similarity index 98%
rename from pkgs/thread2.8.5/generic/threadCmd.c
rename to pkgs/thread2.8.6/generic/threadCmd.c
index e4a3e93..f96dff8 100644 (file)
@@ -27,7 +27,7 @@
  * files built as part of that shell. Example: basekits.
  */
 #ifndef PACKAGE_VERSION
-#define PACKAGE_VERSION "2.8.5"
+#define PACKAGE_VERSION "2.8.6"
 #endif
 
 /*
@@ -203,7 +203,6 @@ typedef struct ThreadEvent {
 } ThreadEvent;
 
 typedef int  (ThreadSendProc) (Tcl_Interp*, ClientData);
-typedef void (ThreadSendFree) (ClientData);
 
 static ThreadSendProc ThreadSendEval;     /* Does a regular Tcl_Eval */
 static ThreadSendProc ThreadClbkSetVar;   /* Sets the named variable */
@@ -213,25 +212,25 @@ static ThreadSendProc ThreadClbkSetVar;   /* Sets the named variable */
  * threads. The ThreadSendData is used for source->target command passing,
  * while the ThreadClbkData is used for doing asynchronous callbacks.
  *
- * Important: structures below must have first three elements identical!
+ * Important: structures below must have first two elements identical!
  */
 
 typedef struct ThreadSendData {
     ThreadSendProc *execProc;             /* Func to exec in remote thread */
     ClientData clientData;                /* Ptr to pass to send function */
-    ThreadSendFree *freeProc;             /* Function to free client data */
-     /* ---- */
+    /* ---- */
     Tcl_Interp *interp;                   /* Interp to run the command */
+    char script[1];                       /* Script to be executed */
 } ThreadSendData;
 
 typedef struct ThreadClbkData {
     ThreadSendProc *execProc;             /* The callback function */
     ClientData clientData;                /* Ptr to pass to clbk function */
-    ThreadSendFree *freeProc;             /* Function to free client data */
     /* ---- */
     Tcl_Interp *interp;                   /* Interp to run the command */
     Tcl_ThreadId threadId;                /* Thread where to post callback */
     ThreadEventResult result;             /* Returns result asynchronously */
+    char var[1];                          /* Variable name to be set */
 } ThreadClbkData;
 
 /*
@@ -592,6 +591,7 @@ ThreadCreateObjCmd(
     int argc, rsrv = 0;
     const char *arg, *script;
     int flags = TCL_THREAD_NOFLAGS;
+    (void)dummy;
 
     Init(interp);
 
@@ -656,6 +656,7 @@ ThreadReserveObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     Tcl_ThreadId thrId = NULL;
+    (void)dummy;
 
     Init(interp);
 
@@ -699,6 +700,7 @@ ThreadReleaseObjCmd(
 ) {
     int wait = 0;
     Tcl_ThreadId thrId = NULL;
+    (void)dummy;
 
     Init(interp);
 
@@ -746,6 +748,8 @@ ThreadUnwindObjCmd(
     int         objc,          /* Number of arguments. */
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
+    (void)dummy;
+
     Init(interp);
 
     if (objc > 1) {
@@ -782,6 +786,7 @@ ThreadExitObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     int status = 666;
+    (void)dummy;
 
     Init(interp);
 
@@ -828,6 +833,7 @@ ThreadIdObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     char thrHandle[THREAD_HNDLMAXLEN];
+    (void)dummy;
 
     Init(interp);
 
@@ -872,6 +878,7 @@ ThreadNamesObjCmd(
     char *result, thrHandle[THREAD_HNDLMAXLEN];
     Tcl_ThreadId *thrIdArray;
     Tcl_DString threadNames;
+    (void)dummy;
 
     Init(interp);
 
@@ -921,12 +928,6 @@ ThreadNamesObjCmd(
  *----------------------------------------------------------------------
  */
 
-static void
-threadSendFree(ClientData ptr)
-{
-    ckfree((char *)ptr);
-}
-
 static int
 ThreadSendObjCmd(
     ClientData  dummy,         /* Not used. */
@@ -939,9 +940,9 @@ ThreadSendObjCmd(
     Tcl_ThreadId thrId;
     const char *script, *arg;
     Tcl_Obj *var = NULL;
-
     ThreadClbkData *clbkPtr = NULL;
     ThreadSendData *sendPtr = NULL;
+    (void)dummy;
 
     Init(interp);
 
@@ -998,23 +999,23 @@ ThreadSendObjCmd(
          * We should do a vwait on the "var" to get notified.
          */
 
-        clbkPtr = (ThreadClbkData*)ckalloc(sizeof(ThreadClbkData));
+        clbkPtr = (ThreadClbkData*)ckalloc(sizeof(ThreadClbkData) + vsize);
         clbkPtr->execProc   = ThreadClbkSetVar;
-        clbkPtr->freeProc   = threadSendFree;
         clbkPtr->interp     = interp;
         clbkPtr->threadId   = Tcl_GetCurrentThread();
-        clbkPtr->clientData = memcpy(ckalloc(vsize), varName, vsize);
+        memcpy(clbkPtr->var, varName, vsize);
+        clbkPtr->clientData = NULL;
     }
 
     /*
      * Prepare job record for the target thread
      */
 
-    sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
+    sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData) + size);
     sendPtr->interp     = NULL; /* Signal to use thread main interp */
     sendPtr->execProc   = ThreadSendEval;
-    sendPtr->freeProc   = threadSendFree;
-    sendPtr->clientData = memcpy(ckalloc(size), script, size);
+    memcpy(sendPtr->script, script, size);
+    sendPtr->clientData = NULL;
 
     ret = ThreadSend(interp, thrId, sendPtr, clbkPtr, flags);
 
@@ -1069,6 +1070,7 @@ ThreadBroadcastObjCmd(
     const char *script;
     Tcl_ThreadId *thrIdArray;
     ThreadSendData *sendPtr, job;
+    (void)dummy;
 
     Init(interp);
 
@@ -1101,7 +1103,6 @@ ThreadBroadcastObjCmd(
 
     job.interp     = NULL; /* Signal to use thread's main interp */
     job.execProc   = ThreadSendEval;
-    job.freeProc   = threadSendFree;
     job.clientData = NULL;
 
     /*
@@ -1115,9 +1116,10 @@ ThreadBroadcastObjCmd(
         if (thrIdArray[ii] == Tcl_GetCurrentThread()) {
             continue; /* Do not broadcast self */
         }
-        sendPtr  = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
+        sendPtr  = (ThreadSendData*)ckalloc(sizeof(ThreadSendData) + size);
         *sendPtr = job;
-        sendPtr->clientData = memcpy(ckalloc(size), script, size);
+        memcpy(sendPtr->script, script, size);
+        sendPtr->clientData = NULL;
         ThreadSend(interp, thrIdArray[ii], sendPtr, NULL, THREAD_SEND_HEAD);
     }
 
@@ -1151,6 +1153,8 @@ ThreadWaitObjCmd(
     int         objc,          /* Number of arguments. */
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
+    (void)dummy;
+
     Init(interp);
 
     if (objc > 1) {
@@ -1189,6 +1193,7 @@ ThreadErrorProcObjCmd(
 ) {
     size_t len;
     char *proc;
+    (void)dummy;
 
     Init(interp);
 
@@ -1225,8 +1230,10 @@ ThreadErrorProcObjCmd(
 \f
 static void
 ThreadFreeError(
-    ClientData clientData
+    ClientData dummy
 ) {
+    (void)dummy;
+
     Tcl_MutexLock(&threadMutex);
     if (errorThreadId != Tcl_GetCurrentThread()) {
         Tcl_MutexUnlock(&threadMutex);
@@ -1263,6 +1270,7 @@ ThreadJoinObjCmd(
     Tcl_Obj    *const objv[]    /* Argument objects. */
 ) {
     Tcl_ThreadId thrId;
+    (void)dummy;
 
     Init(interp);
 
@@ -1306,9 +1314,9 @@ ThreadTransferObjCmd(
     int         objc,          /* Number of arguments. */
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
-
     Tcl_ThreadId thrId;
     Tcl_Channel chan;
+    (void)dummy;
 
     Init(interp);
 
@@ -1357,6 +1365,7 @@ ThreadDetachObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     Tcl_Channel chan;
+    (void)dummy;
 
     Init(interp);
 
@@ -1402,6 +1411,7 @@ ThreadAttachObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     char *chanName;
+    (void)dummy;
 
     Init(interp);
 
@@ -1447,6 +1457,7 @@ ThreadExistsObjCmd(
     Tcl_Obj    *const objv[]   /* Argument objects. */
 ) {
     Tcl_ThreadId thrId;
+    (void)dummy;
 
     Init(interp);
 
@@ -1491,6 +1502,7 @@ ThreadConfigureObjCmd(
     int i;                      /* Iterate over arg-value pairs. */
     Tcl_DString ds;             /* DString to hold result of
                                  * calling GetThreadOption. */
+    (void)dummy;
 
     if (objc < 2 || (objc % 2 == 1 && objc != 3)) {
         Tcl_WrongNumArgs(interp, 1, objv, "threadlId ?optionName? "
@@ -1561,6 +1573,7 @@ ThreadCancelObjCmd(
     Tcl_ThreadId thrId;
     int ii, flags;
     const char *result;
+    (void)dummy;
 
     if ((objc < 2) || (objc > 4)) {
         Tcl_WrongNumArgs(interp, 1, objv, "?-unwind? id ?result?");
@@ -1612,8 +1625,9 @@ ThreadSendEval(
     ClientData clientData
 ) {
     ThreadSendData *sendPtr = (ThreadSendData*)clientData;
-    char *script = (char*)sendPtr->clientData;
+    char *script = (char *)sendPtr->clientData;
 
+    if (!script) script = sendPtr->script;
     return Tcl_EvalEx(interp, script, -1, TCL_EVAL_GLOBAL);
 }
 \f
@@ -1640,7 +1654,7 @@ ThreadClbkSetVar(
     ClientData clientData
 ) {
     ThreadClbkData *clbkPtr = (ThreadClbkData*)clientData;
-    const char *var = (const char *)clbkPtr->clientData;
+    const char *var = clbkPtr->var;
     Tcl_Obj *valObj;
     ThreadEventResult *resultPtr = &clbkPtr->result;
     int rc = TCL_OK;
@@ -1953,7 +1967,6 @@ ThreadErrorProc(
 
         sendPtr = (ThreadSendData*)ckalloc(sizeof(ThreadSendData));
         sendPtr->execProc   = ThreadSendEval;
-        sendPtr->freeProc   = threadSendFree;
         sendPtr->clientData = Tcl_Merge(3, argv);
         sendPtr->interp     = NULL;
 
@@ -2107,11 +2120,12 @@ ListRemoveInner(
 
 static int
 ThreadList(
-    Tcl_Interp *interp,
+    Tcl_Interp *dummy,
     Tcl_ThreadId **thrIdArray
 ) {
     int ii, count = 0;
     ThreadSpecificData *tsdPtr;
+    (void)dummy;
 
     Tcl_MutexLock(&threadMutex);
 
@@ -2702,7 +2716,7 @@ ThreadSend(
     if (thrId == Tcl_GetCurrentThread()) {
         Tcl_MutexUnlock(&threadMutex);
         if ((flags & THREAD_SEND_WAIT)) {
-            int code = (*send->execProc)(interp, send);
+            code = (*send->execProc)(interp, send);
             ThreadFreeProc(send);
             return code;
         } else {
@@ -3104,6 +3118,7 @@ ThreadEventProc(
     ThreadEventResult* resultPtr = eventPtr->resultPtr;
 
     int code = TCL_ERROR; /* Pessimistic assumption */
+    (void)mask;
 
     /*
      * See whether user has any preferences about which interpreter
@@ -3516,6 +3531,7 @@ TransferEventProc(
     Tcl_Interp            *interp = tsdPtr->interp;
     int code;
     const char* msg = NULL;
+    (void)mask;
 
     if (interp == NULL) {
         /*
@@ -3582,10 +3598,10 @@ ThreadFreeProc(
     ThreadSendData *anyPtr = (ThreadSendData*)clientData;
 
     if (anyPtr) {
-        if (anyPtr->clientData) {
-            (*anyPtr->freeProc)(anyPtr->clientData);
-        }
-        ckfree((char*)anyPtr);
+       if (anyPtr->clientData) {
+           ckfree((char *)anyPtr->clientData);
+       }
+       ckfree((char*)anyPtr);
     }
 }
 \f
@@ -3608,8 +3624,10 @@ ThreadFreeProc(
 static int
 ThreadDeleteEvent(
     Tcl_Event *eventPtr,       /* Really ThreadEvent */
-    ClientData clientData      /* dummy */
+    ClientData dummy      /* dummy */
 ) {
+    (void)dummy;
+
     if (eventPtr->proc == ThreadEventProc) {
         /*
          * Regular script event. Just dispose memory
similarity index 99%
rename from pkgs/thread2.8.5/generic/threadPoolCmd.c
rename to pkgs/thread2.8.6/generic/threadPoolCmd.c
index ee610c4..0d12ee6 100644 (file)
@@ -202,6 +202,7 @@ TpoolCreateObjCmd(
     int ii, minw, maxw, idle;
     char buf[64], *exs = NULL, *cmd = NULL;
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     /*
      * Syntax:  tpool::create ?-minworkers count?
@@ -343,6 +344,7 @@ TpoolPostObjCmd(
     ThreadPool *tpoolPtr;
 
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
 
     /*
      * Syntax: tpool::post ?-detached? ?-nowait? tpoolId script
@@ -517,6 +519,7 @@ TpoolWaitObjCmd(
     Tcl_HashEntry *hPtr;
 
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
 
     /*
      * Syntax: tpool::wait tpoolId jobIdList ?listVar?
@@ -629,6 +632,7 @@ TpoolCancelObjCmd(
     Tcl_Obj *doneList, *waitList, **wObjv;
     ThreadPool *tpoolPtr;
     TpoolResult *rPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::cancel tpoolId jobIdList ?listVar?
@@ -725,6 +729,7 @@ TpoolGetObjCmd(
     ThreadPool *tpoolPtr;
     TpoolResult *rPtr;
     Tcl_HashEntry *hPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::get tpoolId jobId ?result?
@@ -816,6 +821,7 @@ TpoolReserveObjCmd(
     int ret;
     char *tpoolName;
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::preserve tpoolId
@@ -871,6 +877,7 @@ TpoolReleaseObjCmd(
     size_t ret;
     char *tpoolName;
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::release tpoolId
@@ -925,6 +932,7 @@ TpoolSuspendObjCmd(
 ) {
     char *tpoolName;
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::suspend tpoolId
@@ -975,6 +983,7 @@ TpoolResumeObjCmd(
 ) {
     char *tpoolName;
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     /*
      * Syntax: tpool::resume tpoolId
@@ -1025,6 +1034,9 @@ TpoolNamesObjCmd(
 ) {
     ThreadPool *tpoolPtr;
     Tcl_Obj *listObj = Tcl_NewListObj(0, NULL);
+    (void)dummy;
+    (void)objc;
+    (void)objv;
 
     Tcl_MutexLock(&listMutex);
     for (tpoolPtr = tpoolList; tpoolPtr; tpoolPtr = tpoolPtr->nextPtr) {
@@ -1291,10 +1303,12 @@ TpoolWorker(
  */
 static int
 RunStopEvent(
-    Tcl_Event *eventPtr,
+    Tcl_Event *dummy,
     int mask
 ) {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
+    (void)mask;
 
     tsdPtr->stop = 1;
     return 1;
@@ -1880,9 +1894,10 @@ ThrExitHandler(
  */
 static void
 AppExitHandler(
-    ClientData clientData
+    ClientData dummy
 ) {
     ThreadPool *tpoolPtr;
+    (void)dummy;
 
     Tcl_MutexLock(&listMutex);
     /*
similarity index 99%
rename from pkgs/thread2.8.5/generic/threadSpCmd.c
rename to pkgs/thread2.8.6/generic/threadSpCmd.c
index a77c1ce..5e1237a 100644 (file)
@@ -187,13 +187,13 @@ ThreadMutexObjCmd(
     const char *mutexName;
     char type;
     SpMutex *mutexPtr;
-
     static const char *cmdOpts[] = {
         "create", "destroy", "lock", "unlock", NULL
     };
     enum options {
         m_CREATE, m_DESTROY, m_LOCK, m_UNLOCK
     };
+    (void)dummy;
 
     /*
      * Syntax:
@@ -371,6 +371,7 @@ ThreadRWMutexObjCmd(
     enum options {
         w_CREATE, w_DESTROY, w_RLOCK, w_WLOCK, w_UNLOCK
     };
+    (void)dummy;
 
     /*
      * Syntax:
@@ -534,6 +535,7 @@ ThreadCondObjCmd(
     enum options {
         c_CREATE, c_DESTROY, c_NOTIFY, c_WAIT
     };
+    (void)dummy;
 
     /*
      * Syntax:
@@ -695,6 +697,7 @@ ThreadEvalObjCmd(
     Tcl_Obj *scriptObj;
     SpMutex *mutexPtr = NULL;
     static Sp_RecursiveMutex evalMutex;
+    (void)dummy;
 
     /*
      * Syntax:
@@ -808,11 +811,12 @@ ThreadEvalObjCmd(
  */
 
 static Tcl_Obj*
-GetName(int type, void *addrPtr)
+GetName(int type, void *dummy)
 {
     char name[32];
     unsigned int id;
     static unsigned int idcounter;
+    (void)dummy;
 
     Tcl_MutexLock(&initMutex);
     id = idcounter++;
similarity index 99%
rename from pkgs/thread2.8.5/generic/threadSvCmd.c
rename to pkgs/thread2.8.6/generic/threadSvCmd.c
index cc3dd6b..3956641 100644 (file)
@@ -414,7 +414,7 @@ GetPsStore(const char *handle)
 {
     int i;
     const char *type = handle;
-    char *addr, *delimiter = strchr(handle, ':');
+    char *addr, *delimiter = (char *)strchr(handle, ':');
     PsStore *tmpPtr, *psPtr = NULL;
 
     /*
@@ -1446,6 +1446,7 @@ SvUnsetObjCmd(
     int ii;
     const char *arrayName;
     Array *arrayPtr;
+    (void)dummy;
 
     if (objc < 2) {
         Tcl_WrongNumArgs(interp, 1, objv, "array ?key ...?");
@@ -2033,6 +2034,7 @@ SvLockObjCmd(
     Tcl_Obj *scriptObj;
     Bucket *bucketPtr;
     Array *arrayPtr = NULL;
+    (void)dummy;
 
     /*
      * Syntax:
@@ -2100,12 +2102,13 @@ SvLockObjCmd(
  */
 static int
 SvHandlersObjCmd(
-             ClientData arg,                     /* Not used. */
+             ClientData dummy,                     /* Not used. */
              Tcl_Interp *interp,                 /* Current interpreter. */
              int objc,                           /* Number of arguments. */
              Tcl_Obj *const objv[])              /* Argument objects. */
 {
     PsStore *tmpPtr = NULL;
+    (void)dummy;
 
     /*
      * Syntax:
@@ -2340,7 +2343,7 @@ Sv_Init (
  */
 
 static void
-SvFinalize (ClientData clientData)
+SvFinalize (ClientData dummy)
 {
     int i;
     SvCmdInfo *cmdPtr;
@@ -2348,6 +2351,7 @@ SvFinalize (ClientData clientData)
 
     Tcl_HashEntry *hashPtr;
     Tcl_HashSearch search;
+    (void)dummy;
 
     /*
      * Decrement number of threads. Proceed only if I was the last one. The
similarity index 99%
rename from pkgs/thread2.8.5/generic/threadSvListCmd.c
rename to pkgs/thread2.8.6/generic/threadSvListCmd.c
index dddd12e..a23c84d 100644 (file)
@@ -25,8 +25,8 @@ typedef struct TclIntStubs {
 extern const struct TclIntStubs *tclIntStubsPtr;
 
 # undef Tcl_GetIntForIndex
-# define Tcl_GetIntForIndex(interp, obj, max, ptr) ((threadTclVersion>86)? \
-    ((int (*)(Tcl_Interp*,  Tcl_Obj *, int, int*))((&(tclStubsPtr->tcl_PkgProvideEx))[645]))((interp), (obj), (max), (ptr)): \
+# define Tcl_GetIntForIndex(interp, obj, max, ptr) ((tclIntStubsPtr->tclGetIntForIndex == NULL)? \
+    ((int (*)(Tcl_Interp*,  Tcl_Obj *, int, int*))(void *)((&(tclStubsPtr->tcl_PkgProvideEx))[645]))((interp), (obj), (max), (ptr)): \
        tclIntStubsPtr->tclGetIntForIndex((interp), (obj), (max), (ptr)))
 #elif TCL_MINOR_VERSION < 7
 extern int TclGetIntForIndex(Tcl_Interp*,  Tcl_Obj *, int, int*);
similarity index 99%
rename from pkgs/thread2.8.5/lib/ttrace.tcl
rename to pkgs/thread2.8.6/lib/ttrace.tcl
index 679d4ee..0834596 100644 (file)
@@ -73,7 +73,7 @@ namespace eval ttrace {
     }
 
     # Keep in sync with the Thread package
-    package provide Ttrace 2.8.5
+    package provide Ttrace 2.8.6
 
     # Package variables
     variable resolvers ""     ; # List of registered resolvers
diff --git a/pkgs/thread2.8.6/manifest.uuid b/pkgs/thread2.8.6/manifest.uuid
new file mode 100644 (file)
index 0000000..1aa41c1
--- /dev/null
@@ -0,0 +1 @@
+484d137f7e38441520ec2d6813a155d7a2fa4301aafe7117ce3dbefdf684ec3f
similarity index 97%
rename from pkgs/thread2.8.5/pkgIndex.tcl.in
rename to pkgs/thread2.8.6/pkgIndex.tcl.in
index 22f5f8f..2334a97 100644 (file)
@@ -23,7 +23,7 @@ if {![package vsatisfies [package provide Tcl] 8.4]} {
 # about a thread-disabled interp, instead of the message
 # "can't find package Thread".
 
-package ifneeded Thread @PACKAGE_VERSION@ [list load [file join $dir @PKG_LIB_FILE@]]
+package ifneeded Thread @PACKAGE_VERSION@ [list load [file join $dir @PKG_LIB_FILE@] [string totitle @PACKAGE_NAME@]]
 
 # package Ttrace uses some support machinery.
 
diff --git a/pkgs/thread2.8.6/tclconfig/README.txt b/pkgs/thread2.8.6/tclconfig/README.txt
new file mode 100644 (file)
index 0000000..715cb9d
--- /dev/null
@@ -0,0 +1,26 @@
+These files comprise the basic building blocks for a Tcl Extension
+Architecture (TEA) extension.  For more information on TEA see:
+
+       http://www.tcl.tk/doc/tea/
+
+This package is part of the Tcl project at SourceForge, but sources
+and bug/patch database are hosted on fossil here:
+
+       https://core.tcl-lang.org/tclconfig
+
+This package is a freely available open source package.  You can do
+virtually anything you like with it, such as modifying it, redistributing
+it, and selling it either in whole or in part.
+
+CONTENTS
+========
+The following is a short description of the files you will find in
+the sample extension.
+
+README.txt     This file
+
+install-sh     Program used for copying binaries and script files
+               to their install locations.
+
+tcl.m4         Collection of Tcl autoconf macros.  Included by a package's
+               aclocal.m4 to define TEA_* macros.
diff --git a/pkgs/thread2.8.6/tclconfig/install-sh b/pkgs/thread2.8.6/tclconfig/install-sh
new file mode 100644 (file)
index 0000000..21b733a
--- /dev/null
@@ -0,0 +1,518 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2020-07-26.22; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# 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.
+
+tab='  '
+nl='
+'
+IFS=" $tab$nl"
+
+# Set DOITPROG to "echo" to test this script.
+
+doit=${DOITPROG-}
+doit_exec=${doit:-exec}
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+is_target_a_directory=possibly
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+        shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
+
+    -o) chowncmd="$chownprog $2"
+        shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -S) stripcmd="$stripprog $2"
+        shift;;
+
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
+
+    -T) is_target_a_directory=never;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --) shift
+        break;;
+
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+        u_plus_rw=
+      else
+        u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename.
+    if test -d "$dst"; then
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
+      fi
+      dstdir=$dst
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
+      dstdir_status=0
+    else
+      dstdir=`dirname "$dst"`
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
+       else
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
+       fi
+       trap '' 0;;
+    esac
+
+    if
+      $posix_mkdir && (
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
+      esac
+
+      oIFS=$IFS
+      IFS=/
+      set -f
+      set fnord $dstdir
+      shift
+      set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # 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 $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       set +f &&
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'before-save-hook 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC0"
+# time-stamp-end: "; # UTC"
+# End:
\ No newline at end of file
diff --git a/pkgs/thread2.8.6/tclconfig/tcl.m4 b/pkgs/thread2.8.6/tclconfig/tcl.m4
new file mode 100644 (file)
index 0000000..8d24e7f
--- /dev/null
@@ -0,0 +1,4056 @@
+# tcl.m4 --
+#
+#      This file provides a set of autoconf macros to help TEA-enable
+#      a Tcl extension.
+#
+# Copyright (c) 1999-2000 Ajuba Solutions.
+# Copyright (c) 2002-2005 ActiveState Corporation.
+#
+# See the file "license.terms" for information on usage and redistribution
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+AC_PREREQ(2.57)
+
+# Possible values for key variables defined:
+#
+# TEA_WINDOWINGSYSTEM - win32 aqua x11 (mirrors 'tk windowingsystem')
+# TEA_PLATFORM        - windows unix
+# TEA_TK_EXTENSION    - True if this is a Tk extension
+#
+
+#------------------------------------------------------------------------
+# TEA_PATH_TCLCONFIG --
+#
+#      Locate the tclConfig.sh file and perform a sanity check on
+#      the Tcl compile flags
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tcl=...
+#
+#      Defines the following vars:
+#              TCL_BIN_DIR     Full path to the directory containing
+#                              the tclConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TCLCONFIG], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+    #
+    # Ok, lets find the tcl configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tcl
+    #
+
+    if test x"${no_tcl}" = x ; then
+       # we reset no_tcl in case something fails here
+       no_tcl=true
+       AC_ARG_WITH(tcl,
+           AS_HELP_STRING([--with-tcl],
+               [directory containing tcl configuration (tclConfig.sh)]),
+           [with_tclconfig="${withval}"])
+       AC_MSG_CHECKING([for Tcl configuration])
+       AC_CACHE_VAL(ac_cv_c_tclconfig,[
+
+           # First check to see if --with-tcl was specified.
+           if test x"${with_tclconfig}" != x ; then
+               case "${with_tclconfig}" in
+                   */tclConfig.sh )
+                       if test -f "${with_tclconfig}"; then
+                           AC_MSG_WARN([--with-tcl argument should refer to directory containing tclConfig.sh, not to tclConfig.sh itself])
+                           with_tclconfig="`echo "${with_tclconfig}" | sed 's!/tclConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tclconfig}/tclConfig.sh" ; then
+                   ac_cv_c_tclconfig="`(cd "${with_tclconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tclconfig} directory doesn't contain tclConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tcl installation
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ../tcl \
+                       `ls -dr ../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tcl \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tcl[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tcl \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/Network/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       `ls -d /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/Tcl.framework 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tcl.framework/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/Tcl.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tcl8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tclconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tcl \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tcl[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tclConfig.sh" ; then
+                       ac_cv_c_tclconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tclconfig}" = x ; then
+           TCL_BIN_DIR="# no Tcl configs found"
+           AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
+       else
+           no_tcl=
+           TCL_BIN_DIR="${ac_cv_c_tclconfig}"
+           AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_TKCONFIG --
+#
+#      Locate the tkConfig.sh file
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-tk=...
+#
+#      Defines the following vars:
+#              TK_BIN_DIR      Full path to the directory containing
+#                              the tkConfig.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_TKCONFIG], [
+    #
+    # Ok, lets find the tk configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-tk
+    #
+
+    if test x"${no_tk}" = x ; then
+       # we reset no_tk in case something fails here
+       no_tk=true
+       AC_ARG_WITH(tk,
+           AS_HELP_STRING([--with-tk],
+               [directory containing tk configuration (tkConfig.sh)]),
+           [with_tkconfig="${withval}"])
+       AC_MSG_CHECKING([for Tk configuration])
+       AC_CACHE_VAL(ac_cv_c_tkconfig,[
+
+           # First check to see if --with-tkconfig was specified.
+           if test x"${with_tkconfig}" != x ; then
+               case "${with_tkconfig}" in
+                   */tkConfig.sh )
+                       if test -f "${with_tkconfig}"; then
+                           AC_MSG_WARN([--with-tk argument should refer to directory containing tkConfig.sh, not to tkConfig.sh itself])
+                           with_tkconfig="`echo "${with_tkconfig}" | sed 's!/tkConfig\.sh$!!'`"
+                       fi ;;
+               esac
+               if test -f "${with_tkconfig}/tkConfig.sh" ; then
+                   ac_cv_c_tkconfig="`(cd "${with_tkconfig}"; pwd)`"
+               else
+                   AC_MSG_ERROR([${with_tkconfig} directory doesn't contain tkConfig.sh])
+               fi
+           fi
+
+           # then check for a private Tk library
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ../tk \
+                       `ls -dr ../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../tk \
+                       `ls -dr ../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../tk[[8-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../tk \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # on Darwin, check in Framework installation locations
+           if test "`uname -s`" = "Darwin" -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ~/Library/Frameworks 2>/dev/null` \
+                       `ls -d /Library/Frameworks 2>/dev/null` \
+                       `ls -d /Network/Library/Frameworks 2>/dev/null` \
+                       ; do
+                   if test -f "$i/Tk.framework/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/Tk.framework; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tk8.5 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.6 2>/dev/null` \
+                       `ls -d /usr/local/lib/tcl/tk8.5 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # TEA specific: on Windows, check in common installation locations
+           if test "${TEA_PLATFORM}" = "windows" \
+               -a x"${ac_cv_c_tkconfig}" = x ; then
+               for i in `ls -d C:/Tcl/lib 2>/dev/null` \
+                       `ls -d C:/Progra~1/Tcl/lib 2>/dev/null` \
+                       ; do
+                   if test -f "$i/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i; pwd)`"
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few other private locations
+           if test x"${ac_cv_c_tkconfig}" = x ; then
+               for i in \
+                       ${srcdir}/../tk \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]].[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../tk[[8-9]].[[0-9]]* 2>/dev/null` ; do
+                   if test "${TEA_PLATFORM}" = "windows" \
+                           -a -f "$i/win/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/win; pwd)`"
+                       break
+                   fi
+                   if test -f "$i/unix/tkConfig.sh" ; then
+                       ac_cv_c_tkconfig="`(cd $i/unix; pwd)`"
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_tkconfig}" = x ; then
+           TK_BIN_DIR="# no Tk configs found"
+           AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
+       else
+           no_tk=
+           TK_BIN_DIR="${ac_cv_c_tkconfig}"
+           AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TCLCONFIG --
+#
+#      Load the tclConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TCL_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_BIN_DIR
+#              TCL_SRC_DIR
+#              TCL_LIB_FILE
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TCLCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
+
+    if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TCL_BIN_DIR}/tclConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
+    fi
+
+    # If the TCL_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TCL_LIB_SPEC will be set to the value
+    # of TCL_BUILD_LIB_SPEC. An extension should make use of TCL_LIB_SPEC
+    # instead of TCL_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        TCL_LIB_SPEC="${TCL_BUILD_LIB_SPEC}"
+        TCL_STUB_LIB_SPEC="${TCL_BUILD_STUB_LIB_SPEC}"
+        TCL_STUB_LIB_PATH="${TCL_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tcl was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tcl.framework installed in an arbitrary location.
+       case ${TCL_DEFS} in
+           *TCL_FRAMEWORK*)
+               if test -f "${TCL_BIN_DIR}/${TCL_LIB_FILE}"; then
+                   for i in "`cd "${TCL_BIN_DIR}"; pwd`" \
+                            "`cd "${TCL_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TCL_LIB_FILE}.framework"; then
+                           TCL_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TCL_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"; then
+                   TCL_STUB_LIB_SPEC="-L`echo "${TCL_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TCL_STUB_LIB_FLAG}"
+                   TCL_STUB_LIB_PATH="${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    AC_SUBST(TCL_VERSION)
+    AC_SUBST(TCL_PATCH_LEVEL)
+    AC_SUBST(TCL_BIN_DIR)
+    AC_SUBST(TCL_SRC_DIR)
+
+    AC_SUBST(TCL_LIB_FILE)
+    AC_SUBST(TCL_LIB_FLAG)
+    AC_SUBST(TCL_LIB_SPEC)
+
+    AC_SUBST(TCL_STUB_LIB_FILE)
+    AC_SUBST(TCL_STUB_LIB_FLAG)
+    AC_SUBST(TCL_STUB_LIB_SPEC)
+
+    AC_MSG_CHECKING([platform])
+    hold_cc=$CC; CC="$TCL_CC"
+    AC_TRY_COMPILE(,[
+           #ifdef _WIN32
+               #error win32
+           #endif
+       ], [
+           # first test we've already retrieved platform (cross-compile), fallback to unix otherwise:
+           TEA_PLATFORM="${TEA_PLATFORM-unix}"
+           CYGPATH=echo
+       ], [
+           TEA_PLATFORM="windows"
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)   ]
+    )
+    CC=$hold_cc
+    AC_MSG_RESULT($TEA_PLATFORM)
+
+    # The BUILD_$pkg is to define the correct extern storage class
+    # handling when making this package
+    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
+           [Building extension source?])
+    # Do this here as we have fully defined TEA_PLATFORM now
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       EXEEXT=".exe"
+       CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
+    fi
+
+    # TEA specific:
+    AC_SUBST(CLEANFILES)
+    AC_SUBST(TCL_LIBS)
+    AC_SUBST(TCL_DEFS)
+    AC_SUBST(TCL_EXTRA_CFLAGS)
+    AC_SUBST(TCL_LD_FLAGS)
+    AC_SUBST(TCL_SHLIB_LD_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_TKCONFIG --
+#
+#      Load the tkConfig.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              TK_BIN_DIR
+#
+# Results:
+#
+#      Sets the following vars that should be in tkConfig.sh:
+#              TK_BIN_DIR
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_TKCONFIG], [
+    AC_MSG_CHECKING([for existence of ${TK_BIN_DIR}/tkConfig.sh])
+
+    if test -f "${TK_BIN_DIR}/tkConfig.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${TK_BIN_DIR}/tkConfig.sh"
+    else
+        AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
+    fi
+
+    # If the TK_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable TK_LIB_SPEC will be set to the value
+    # of TK_BUILD_LIB_SPEC. An extension should make use of TK_LIB_SPEC
+    # instead of TK_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        TK_LIB_SPEC="${TK_BUILD_LIB_SPEC}"
+        TK_STUB_LIB_SPEC="${TK_BUILD_STUB_LIB_SPEC}"
+        TK_STUB_LIB_PATH="${TK_BUILD_STUB_LIB_PATH}"
+    elif test "`uname -s`" = "Darwin"; then
+       # If Tk was built as a framework, attempt to use the libraries
+       # from the framework at the given location so that linking works
+       # against Tk.framework installed in an arbitrary location.
+       case ${TK_DEFS} in
+           *TK_FRAMEWORK*)
+               if test -f "${TK_BIN_DIR}/${TK_LIB_FILE}"; then
+                   for i in "`cd "${TK_BIN_DIR}"; pwd`" \
+                            "`cd "${TK_BIN_DIR}"/../..; pwd`"; do
+                       if test "`basename "$i"`" = "${TK_LIB_FILE}.framework"; then
+                           TK_LIB_SPEC="-F`dirname "$i" | sed -e 's/ /\\\\ /g'` -framework ${TK_LIB_FILE}"
+                           break
+                       fi
+                   done
+               fi
+               if test -f "${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"; then
+                   TK_STUB_LIB_SPEC="-L` echo "${TK_BIN_DIR}"  | sed -e 's/ /\\\\ /g'` ${TK_STUB_LIB_FLAG}"
+                   TK_STUB_LIB_PATH="${TK_BIN_DIR}/${TK_STUB_LIB_FILE}"
+               fi
+               ;;
+       esac
+    fi
+
+    # TEA specific: Ensure windowingsystem is defined
+    if test "${TEA_PLATFORM}" = "unix" ; then
+       case ${TK_DEFS} in
+           *MAC_OSX_TK*)
+               AC_DEFINE(MAC_OSX_TK, 1, [Are we building against Mac OS X TkAqua?])
+               TEA_WINDOWINGSYSTEM="aqua"
+               ;;
+           *)
+               TEA_WINDOWINGSYSTEM="x11"
+               ;;
+       esac
+    elif test "${TEA_PLATFORM}" = "windows" ; then
+       TEA_WINDOWINGSYSTEM="win32"
+    fi
+
+    AC_SUBST(TK_VERSION)
+    AC_SUBST(TK_BIN_DIR)
+    AC_SUBST(TK_SRC_DIR)
+
+    AC_SUBST(TK_LIB_FILE)
+    AC_SUBST(TK_LIB_FLAG)
+    AC_SUBST(TK_LIB_SPEC)
+
+    AC_SUBST(TK_STUB_LIB_FILE)
+    AC_SUBST(TK_STUB_LIB_FLAG)
+    AC_SUBST(TK_STUB_LIB_SPEC)
+
+    # TEA specific:
+    AC_SUBST(TK_LIBS)
+    AC_SUBST(TK_XINCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_TCLSH
+#      Determine the fully qualified path name of the tclsh executable
+#      in the Tcl build directory or the tclsh installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the tclsh executable even if tclsh has not yet been
+#      built in the build directory. The tclsh found is always
+#      associated with a tclConfig.sh file. This tclsh should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCLSH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_TCLSH], [
+    AC_MSG_CHECKING([for tclsh])
+    if test -f "${TCL_BIN_DIR}/Makefile" ; then
+        # tclConfig.sh is in Tcl build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}s${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}" ; then
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            TCLSH_PROG="${TCL_BIN_DIR}/tclsh"
+        fi
+    else
+        # tclConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}${TCL_MINOR_VERSION}${EXEEXT}"
+        else
+            TCLSH_PROG="tclsh${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TCL_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TCL_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TCL_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${TCLSH_PROG}" ; then
+                REAL_TCL_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        TCLSH_PROG="${REAL_TCL_BIN_DIR}${TCLSH_PROG}"
+    fi
+    AC_MSG_RESULT([${TCLSH_PROG}])
+    AC_SUBST(TCLSH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_PROG_WISH
+#      Determine the fully qualified path name of the wish executable
+#      in the Tk build directory or the wish installed in a bin
+#      directory. This macro will correctly determine the name
+#      of the wish executable even if wish has not yet been
+#      built in the build directory. The wish found is always
+#      associated with a tkConfig.sh file. This wish should be used
+#      only for running extension test cases. It should never be
+#      or generation of files (like pkgIndex.tcl) at build time.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              WISH_PROG
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PROG_WISH], [
+    AC_MSG_CHECKING([for wish])
+    if test -f "${TK_BIN_DIR}/Makefile" ; then
+        # tkConfig.sh is in Tk build directory
+        if test "${TEA_PLATFORM}" = "windows"; then
+          if test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}s${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}$s{EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}t${EXEEXT}"
+          elif test -f "${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}" ; then
+            WISH_PROG="${TK_BIN_DIR}/wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}st${EXEEXT}"
+          fi
+        else
+            WISH_PROG="${TK_BIN_DIR}/wish"
+        fi
+    else
+        # tkConfig.sh is in install location
+        if test "${TEA_PLATFORM}" = "windows"; then
+            WISH_PROG="wish${TK_MAJOR_VERSION}${TK_MINOR_VERSION}${EXEEXT}"
+        else
+            WISH_PROG="wish${TK_MAJOR_VERSION}.${TK_MINOR_VERSION}"
+        fi
+        list="`ls -d ${TK_BIN_DIR}/../bin 2>/dev/null` \
+              `ls -d ${TK_BIN_DIR}/..     2>/dev/null` \
+              `ls -d ${TK_PREFIX}/bin     2>/dev/null`"
+        for i in $list ; do
+            if test -f "$i/${WISH_PROG}" ; then
+                REAL_TK_BIN_DIR="`cd "$i"; pwd`/"
+                break
+            fi
+        done
+        WISH_PROG="${REAL_TK_BIN_DIR}${WISH_PROG}"
+    fi
+    AC_MSG_RESULT([${WISH_PROG}])
+    AC_SUBST(WISH_PROG)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SHARED --
+#
+#      Allows the building of shared libraries
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-shared=yes|no
+#              --enable-stubs=yes|no
+#
+#      Defines the following vars:
+#              STATIC_BUILD    Used for building import/export libraries
+#                              on Windows.
+#
+#      Sets the following vars:
+#              SHARED_BUILD    Value of 1 or 0
+#               STUBS_BUILD     Value if 1 or 0
+#               USE_TCL_STUBS   Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TCLOO_STUBS Value true: if SHARED_BUILD or --enable-stubs
+#               USE_TK_STUBS    Value true: if SHARED_BUILD or --enable-stubs
+#                                AND TEA_WINDOWING_SYSTEM != ""
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ENABLE_SHARED], [
+    AC_MSG_CHECKING([how to build libraries])
+    AC_ARG_ENABLE(shared,
+       AS_HELP_STRING([--enable-shared],
+           [build and link with shared libraries (default: on)]),
+       [shared_ok=$enableval], [shared_ok=yes])
+
+    if test "${enable_shared+set}" = set; then
+       enableval="$enable_shared"
+       shared_ok=$enableval
+    else
+       shared_ok=yes
+    fi
+
+    AC_ARG_ENABLE(stubs,
+       AS_HELP_STRING([--enable-stubs],
+           [build and link with stub libraries. Always true for shared builds (default: on)]),
+       [stubs_ok=$enableval], [stubs_ok=yes])
+
+    if test "${enable_stubs+set}" = set; then
+       enableval="$enable_stubs"
+       stubs_ok=$enableval
+    else
+       stubs_ok=yes
+    fi
+
+    # Stubs are always enabled for shared builds
+    if test "$shared_ok" = "yes" ; then
+       AC_MSG_RESULT([shared])
+       SHARED_BUILD=1
+        STUBS_BUILD=1
+    else
+       AC_MSG_RESULT([static])
+       SHARED_BUILD=0
+       AC_DEFINE(STATIC_BUILD, 1, [This a static build])
+        if test "$stubs_ok" = "yes" ; then
+          STUBS_BUILD=1
+        else
+          STUBS_BUILD=0
+        fi
+    fi
+    if test "${STUBS_BUILD}" = "1" ; then
+      AC_DEFINE(USE_TCL_STUBS, 1, [Use Tcl stubs])
+      AC_DEFINE(USE_TCLOO_STUBS, 1, [Use TclOO stubs])
+      if test "${TEA_WINDOWINGSYSTEM}" != ""; then
+        AC_DEFINE(USE_TK_STUBS, 1, [Use Tk stubs])
+      fi
+    fi
+
+    AC_SUBST(SHARED_BUILD)
+    AC_SUBST(STUBS_BUILD)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_THREADS --
+#
+#      Specify if thread support should be enabled.  If "yes" is specified
+#      as an arg (optional), threads are enabled by default, "no" means
+#      threads are disabled.  "yes" is the default.
+#
+#      TCL_THREADS is checked so that if you are compiling an extension
+#      against a threaded core, your extension must be compiled threaded
+#      as well.
+#
+#      Note that it is legal to have a thread enabled extension run in a
+#      threaded or non-threaded Tcl core, but a non-threaded extension may
+#      only run in a non-threaded Tcl core.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-threads
+#
+#      Sets the following vars:
+#              THREADS_LIBS    Thread library(s)
+#
+#      Defines the following vars:
+#              TCL_THREADS
+#              _REENTRANT
+#              _THREAD_SAFE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_THREADS], [
+    AC_ARG_ENABLE(threads,
+       AS_HELP_STRING([--enable-threads],
+           [build with threads (default: on)]),
+       [tcl_ok=$enableval], [tcl_ok=yes])
+
+    if test "${enable_threads+set}" = set; then
+       enableval="$enable_threads"
+       tcl_ok=$enableval
+    else
+       tcl_ok=yes
+    fi
+
+    if test "$tcl_ok" = "yes" -o "${TCL_THREADS}" = 1; then
+       TCL_THREADS=1
+
+       if test "${TEA_PLATFORM}" != "windows" ; then
+           # We are always OK on Windows, so check what this platform wants:
+
+           # USE_THREAD_ALLOC tells us to try the special thread-based
+           # allocator that significantly reduces lock contention
+           AC_DEFINE(USE_THREAD_ALLOC, 1,
+               [Do we want to use the threaded memory allocator?])
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           if test "`uname -s`" = "SunOS" ; then
+               AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+                       [Do we really want to follow the standard? Yes we do!])
+           fi
+           AC_DEFINE(_THREAD_SAFE, 1, [Do we want the thread-safe OS API?])
+           AC_CHECK_LIB(pthread,pthread_mutex_init,tcl_ok=yes,tcl_ok=no)
+           if test "$tcl_ok" = "no"; then
+               # Check a little harder for __pthread_mutex_init in the same
+               # library, as some systems hide it there until pthread.h is
+               # defined.  We could alternatively do an AC_TRY_COMPILE with
+               # pthread.h, but that will work with libpthread really doesn't
+               # exist, like AIX 4.2.  [Bug: 4359]
+               AC_CHECK_LIB(pthread, __pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+           fi
+
+           if test "$tcl_ok" = "yes"; then
+               # The space is needed
+               THREADS_LIBS=" -lpthread"
+           else
+               AC_CHECK_LIB(pthreads, pthread_mutex_init,
+                   tcl_ok=yes, tcl_ok=no)
+               if test "$tcl_ok" = "yes"; then
+                   # The space is needed
+                   THREADS_LIBS=" -lpthreads"
+               else
+                   AC_CHECK_LIB(c, pthread_mutex_init,
+                       tcl_ok=yes, tcl_ok=no)
+                   if test "$tcl_ok" = "no"; then
+                       AC_CHECK_LIB(c_r, pthread_mutex_init,
+                           tcl_ok=yes, tcl_ok=no)
+                       if test "$tcl_ok" = "yes"; then
+                           # The space is needed
+                           THREADS_LIBS=" -pthread"
+                       else
+                           TCL_THREADS=0
+                           AC_MSG_WARN([Do not know how to find pthread lib on your system - thread support disabled])
+                       fi
+                   fi
+               fi
+           fi
+       fi
+    else
+       TCL_THREADS=0
+    fi
+    # Do checking message here to not mess up interleaved configure output
+    AC_MSG_CHECKING([for building with threads])
+    if test "${TCL_THREADS}" = 1; then
+       AC_DEFINE(TCL_THREADS, 1, [Are we building with threads enabled?])
+       AC_MSG_RESULT([yes (default)])
+    else
+       AC_MSG_RESULT([no])
+    fi
+    # TCL_THREADS sanity checking.  See if our request for building with
+    # threads is the same as the way Tcl was built.  If not, warn the user.
+    case ${TCL_DEFS} in
+       *THREADS=1*)
+           if test "${TCL_THREADS}" = "0"; then
+               AC_MSG_WARN([
+    Building ${PACKAGE_NAME} without threads enabled, but building against Tcl
+    that IS thread-enabled.  It is recommended to use --enable-threads.])
+           fi
+           ;;
+    esac
+    AC_SUBST(TCL_THREADS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_SYMBOLS --
+#
+#      Specify if debugging symbols should be used.
+#      Memory (TCL_MEM_DEBUG) debugging can also be enabled.
+#
+# Arguments:
+#      none
+#
+#      TEA varies from core Tcl in that C|LDFLAGS_DEFAULT receives
+#      the value of C|LDFLAGS_OPTIMIZE|DEBUG already substituted.
+#      Requires the following vars to be set in the Makefile:
+#              CFLAGS_DEFAULT
+#              LDFLAGS_DEFAULT
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-symbols
+#
+#      Defines the following vars:
+#              CFLAGS_DEFAULT  Sets to $(CFLAGS_DEBUG) if true
+#                              Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
+#              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
+#                              Sets to $(LDFLAGS_OPTIMIZE) if false
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_SYMBOLS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_CONFIG_CFLAGS])
+    AC_MSG_CHECKING([for build with symbols])
+    AC_ARG_ENABLE(symbols,
+       AS_HELP_STRING([--enable-symbols],
+           [build with debugging symbols (default: off)]),
+       [tcl_ok=$enableval], [tcl_ok=no])
+    if test "$tcl_ok" = "no"; then
+       CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
+       LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
+       AC_MSG_RESULT([no])
+    else
+       CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
+       LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
+       if test "$tcl_ok" = "yes"; then
+           AC_MSG_RESULT([yes (standard debugging)])
+       fi
+    fi
+    AC_SUBST(CFLAGS_DEFAULT)
+    AC_SUBST(LDFLAGS_DEFAULT)
+
+    if test "$tcl_ok" = "mem" -o "$tcl_ok" = "all"; then
+       AC_DEFINE(TCL_MEM_DEBUG, 1, [Is memory debugging enabled?])
+    fi
+
+    if test "$tcl_ok" != "yes" -a "$tcl_ok" != "no"; then
+       if test "$tcl_ok" = "all"; then
+           AC_MSG_RESULT([enabled symbols mem debugging])
+       else
+           AC_MSG_RESULT([enabled $tcl_ok debugging])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_ENABLE_LANGINFO --
+#
+#      Allows use of modern nl_langinfo check for better l10n.
+#      This is only relevant for Unix.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --enable-langinfo=yes|no (default is yes)
+#
+#      Defines the following vars:
+#              HAVE_LANGINFO   Triggers use of nl_langinfo if defined.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_ENABLE_LANGINFO], [
+    AC_ARG_ENABLE(langinfo,
+       AS_HELP_STRING([--enable-langinfo],
+           [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
+       [langinfo_ok=$enableval], [langinfo_ok=yes])
+
+    HAVE_LANGINFO=0
+    if test "$langinfo_ok" = "yes"; then
+       AC_CHECK_HEADER(langinfo.h,[langinfo_ok=yes],[langinfo_ok=no])
+    fi
+    AC_MSG_CHECKING([whether to use nl_langinfo])
+    if test "$langinfo_ok" = "yes"; then
+       AC_CACHE_VAL(tcl_cv_langinfo_h, [
+           AC_TRY_COMPILE([#include <langinfo.h>], [nl_langinfo(CODESET);],
+                   [tcl_cv_langinfo_h=yes],[tcl_cv_langinfo_h=no])])
+       AC_MSG_RESULT([$tcl_cv_langinfo_h])
+       if test $tcl_cv_langinfo_h = yes; then
+           AC_DEFINE(HAVE_LANGINFO, 1, [Do we have nl_langinfo()?])
+       fi
+    else
+       AC_MSG_RESULT([$langinfo_ok])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_SYSTEM
+#
+#      Determine what the system is (some things cannot be easily checked
+#      on a feature-driven basis, alas). This can usually be done via the
+#      "uname" command.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Defines the following var:
+#
+#      system -        System/platform/version identification code.
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_SYSTEM], [
+    AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
+       # TEA specific:
+       if test "${TEA_PLATFORM}" = "windows" ; then
+           tcl_cv_sys_version=windows
+       else
+           tcl_cv_sys_version=`uname -s`-`uname -r`
+           if test "$?" -ne 0 ; then
+               AC_MSG_WARN([can't find uname command])
+               tcl_cv_sys_version=unknown
+           else
+               if test "`uname -s`" = "AIX" ; then
+                   tcl_cv_sys_version=AIX-`uname -v`.`uname -r`
+               fi
+               if test "`uname -s`" = "NetBSD" -a -f /etc/debian_version ; then
+                   tcl_cv_sys_version=NetBSD-Debian
+               fi
+           fi
+       fi
+    ])
+    system=$tcl_cv_sys_version
+])
+
+#--------------------------------------------------------------------
+# TEA_CONFIG_CFLAGS
+#
+#      Try to determine the proper flags to pass to the compiler
+#      for building shared libraries and other such nonsense.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substitutes the following vars:
+#
+#      DL_OBJS, DL_LIBS - removed for TEA, only needed by core.
+#       LDFLAGS -      Flags to pass to the compiler when linking object
+#                       files into an executable application binary such
+#                       as tclsh.
+#       LD_SEARCH_FLAGS-Flags to pass to ld, such as "-R /usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile. Could
+#                       be the same as CC_SEARCH_FLAGS if ${CC} is used to link.
+#       CC_SEARCH_FLAGS-Flags to pass to ${CC}, such as "-Wl,-rpath,/usr/local/tcl/lib",
+#                       that tell the run-time dynamic linker where to look
+#                       for shared libraries such as libtcl.so.  Depends on
+#                       the variable LIB_RUNTIME_DIR in the Makefile.
+#       SHLIB_CFLAGS -  Flags to pass to cc when compiling the components
+#                       of a shared library (may request position-independent
+#                       code, among other things).
+#       SHLIB_LD -      Base command to use for combining object files
+#                       into a shared library.
+#       SHLIB_LD_LIBS - Dependent libraries for the linker to scan when
+#                       creating shared libraries.  This symbol typically
+#                       goes at the end of the "ld" commands that build
+#                       shared libraries. The value of the symbol defaults to
+#                       "${LIBS}" if all of the dependent libraries should
+#                       be specified when creating a shared library.  If
+#                       dependent libraries should not be specified (as on
+#                       SunOS 4.x, where they cause the link to fail, or in
+#                       general if Tcl and Tk aren't themselves shared
+#                       libraries), then this symbol has an empty string
+#                       as its value.
+#       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
+#                       extensions.  An empty string means we don't know how
+#                       to use shared libraries on this platform.
+#       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
+#                       in a static or shared library name, using the $PACKAGE_VERSION variable
+#                       to put the version in the right place.  This is used
+#                       by platforms that need non-standard library names.
+#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
+#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
+#                       on AIX, since a shared library needs to have
+#                       a .a extension whereas shared objects for loadable
+#                       extensions have a .so extension.  Defaults to
+#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
+#      CFLAGS_DEBUG -
+#                      Flags used when running the compiler in debug mode
+#      CFLAGS_OPTIMIZE -
+#                      Flags used when running the compiler in optimize mode
+#      CFLAGS -        Additional CFLAGS added as necessary (usually 64-bit)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_CONFIG_CFLAGS], [
+    dnl TEA specific: Make sure we are initialized
+    AC_REQUIRE([TEA_INIT])
+
+    # Step 0.a: Enable 64 bit support?
+
+    AC_MSG_CHECKING([if 64bit support is requested])
+    AC_ARG_ENABLE(64bit,
+       AS_HELP_STRING([--enable-64bit],
+           [enable 64bit support (default: off)]),
+       [do64bit=$enableval], [do64bit=no])
+    AC_MSG_RESULT([$do64bit])
+
+    # Step 0.b: Enable Solaris 64 bit VIS support?
+
+    AC_MSG_CHECKING([if 64bit Sparc VIS support is requested])
+    AC_ARG_ENABLE(64bit-vis,
+       AS_HELP_STRING([--enable-64bit-vis],
+           [enable 64bit Sparc VIS support (default: off)]),
+       [do64bitVIS=$enableval], [do64bitVIS=no])
+    AC_MSG_RESULT([$do64bitVIS])
+    # Force 64bit on with VIS
+    AS_IF([test "$do64bitVIS" = "yes"], [do64bit=yes])
+
+    # Step 0.c: Check if visibility support is available. Do this here so
+    # that platform specific alternatives can be used below if this fails.
+
+    AC_CACHE_CHECK([if compiler supports visibility "hidden"],
+       tcl_cv_cc_visibility_hidden, [
+       hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -Werror"
+       AC_TRY_LINK([
+           extern __attribute__((__visibility__("hidden"))) void f(void);
+           void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
+           tcl_cv_cc_visibility_hidden=no)
+       CFLAGS=$hold_cflags])
+    AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
+       AC_DEFINE(MODULE_SCOPE,
+           [extern __attribute__((__visibility__("hidden")))],
+           [Compiler support for module scope symbols])
+       AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
+    ])
+
+    # Step 0.d: Disable -rpath support?
+
+    AC_MSG_CHECKING([if rpath support is requested])
+    AC_ARG_ENABLE(rpath,
+       AS_HELP_STRING([--disable-rpath],
+           [disable rpath support (default: on)]),
+       [doRpath=$enableval], [doRpath=yes])
+    AC_MSG_RESULT([$doRpath])
+
+    # Set the variable "system" to hold the name and version number
+    # for the system.
+
+    TEA_CONFIG_SYSTEM
+
+    # Require ranlib early so we can override it in special cases below.
+
+    AC_REQUIRE([AC_PROG_RANLIB])
+
+    # Set configuration options based on system name and version.
+    # This is similar to Tcl's unix/tcl.m4 except that we've added a
+    # "windows" case and removed some core-only vars.
+
+    do64bit_ok=no
+    # default to '{$LIBS}' and set to "" on per-platform necessary basis
+    SHLIB_LD_LIBS='${LIBS}'
+    # When ld needs options to work in 64-bit mode, put them in
+    # LDFLAGS_ARCH so they eventually end up in LDFLAGS even if [load]
+    # is disabled by the user. [Bug 1016796]
+    LDFLAGS_ARCH=""
+    UNSHARED_LIB_SUFFIX=""
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
+    ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
+    TCL_LIB_VERSIONS_OK=ok
+    CFLAGS_DEBUG=-g
+    AS_IF([test "$GCC" = yes], [
+       CFLAGS_OPTIMIZE=-O2
+       CFLAGS_WARNING="-Wall"
+    ], [
+       CFLAGS_OPTIMIZE=-O
+       CFLAGS_WARNING=""
+    ])
+    AC_CHECK_TOOL(AR, ar)
+    STLIB_LD='${AR} cr'
+    LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
+    AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION=""],[SHLIB_VERSION=".$SHLIB_VERSION"])
+    case $system in
+       # TEA specific:
+       windows)
+           MACHINE="X86"
+           if test "$do64bit" != "no" ; then
+               case "$do64bit" in
+                   amd64|x64|yes)
+                       MACHINE="AMD64" ; # default to AMD64 64-bit build
+                       ;;
+                   ia64)
+                       MACHINE="IA64"
+                       ;;
+               esac
+           fi
+
+           if test "$GCC" != "yes" ; then
+               if test "${SHARED_BUILD}" = "0" ; then
+                   runtime=-MT
+               else
+                   runtime=-MD
+               fi
+               case "x`echo \${VisualStudioVersion}`" in
+                   x1[[4-9]]*)
+                       lflags="${lflags} -nodefaultlib:libucrt.lib"
+                       TEA_ADD_LIBS([ucrt.lib])
+                   ;;
+                   *)
+                   ;;
+               esac
+
+                if test "$do64bit" != "no" ; then
+                   CC="cl.exe"
+                   RC="rc.exe"
+                   lflags="${lflags} -nologo -MACHINE:${MACHINE} "
+                   LINKBIN="link.exe"
+                   CFLAGS_DEBUG="-nologo -Zi -Od -W3 ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+                   # Avoid 'unresolved external symbol __security_cookie'
+                   # errors, c.f. http://support.microsoft.com/?id=894573
+                   TEA_ADD_LIBS([bufferoverflowU.lib])
+               else
+                   RC="rc"
+                   lflags="${lflags} -nologo"
+                   LINKBIN="link"
+                   CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
+                   CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
+               fi
+           fi
+
+           if test "$GCC" = "yes"; then
+               # mingw gcc mode
+               AC_CHECK_TOOL(RC, windres)
+               CFLAGS_DEBUG="-g"
+               CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+               SHLIB_LD='${CC} -shared'
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+               LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
+               LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
+
+               AC_CACHE_CHECK(for cross-compile version of gcc,
+                       ac_cv_cross,
+                       AC_TRY_COMPILE([
+                           #ifdef _WIN32
+                               #error cross-compiler
+                           #endif
+                       ], [],
+                       ac_cv_cross=yes,
+                       ac_cv_cross=no)
+                     )
+                     if test "$ac_cv_cross" = "yes"; then
+                       case "$do64bit" in
+                           amd64|x64|yes)
+                               CC="x86_64-w64-mingw32-${CC}"
+                               LD="x86_64-w64-mingw32-ld"
+                               AR="x86_64-w64-mingw32-ar"
+                               RANLIB="x86_64-w64-mingw32-ranlib"
+                               RC="x86_64-w64-mingw32-windres"
+                           ;;
+                           *)
+                               CC="i686-w64-mingw32-${CC}"
+                               LD="i686-w64-mingw32-ld"
+                               AR="i686-w64-mingw32-ar"
+                               RANLIB="i686-w64-mingw32-ranlib"
+                               RC="i686-w64-mingw32-windres"
+                           ;;
+                       esac
+               fi
+
+           else
+               SHLIB_LD="${LINKBIN} -dll ${lflags}"
+               # link -lib only works when -lib is the first arg
+               STLIB_LD="${LINKBIN} -lib ${lflags}"
+               UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
+               PATHTYPE=-w
+               # For information on what debugtype is most useful, see:
+               # http://msdn.microsoft.com/library/en-us/dnvc60/html/gendepdebug.asp
+               # and also
+               # http://msdn2.microsoft.com/en-us/library/y0zzbyt4%28VS.80%29.aspx
+               # This essentially turns it all on.
+               LDFLAGS_DEBUG="-debug -debugtype:cv"
+               LDFLAGS_OPTIMIZE="-release"
+               LDFLAGS_CONSOLE="-link -subsystem:console ${lflags}"
+               LDFLAGS_WINDOW="-link -subsystem:windows ${lflags}"
+           fi
+
+           SHLIB_SUFFIX=".dll"
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.dll'
+
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       AIX-*)
+           AS_IF([test "$GCC" != "yes"], [
+               # AIX requires the _r compiler when gcc isn't being used
+               case "${CC}" in
+                   *_r|*_r\ *)
+                       # ok ...
+                       ;;
+                   *)
+                       # Make sure only first arg gets _r
+                       CC=`echo "$CC" | sed -e 's/^\([[^ ]]*\)/\1_r/'`
+                       ;;
+               esac
+               AC_MSG_RESULT([Using $CC for compiling with threads])
+           ])
+           LIBS="$LIBS -lc"
+           SHLIB_CFLAGS=""
+           SHLIB_SUFFIX=".so"
+
+           LD_LIBRARY_PATH_VAR="LIBPATH"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported with GCC on $system])
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS -q64"
+                   LDFLAGS_ARCH="-q64"
+                   RANLIB="${RANLIB} -X64"
+                   AR="${AR} -X64"
+                   SHLIB_LD_FLAGS="-b64"
+               ])
+           ])
+
+           AS_IF([test "`uname -m`" = ia64], [
+               # AIX-5 uses ELF style dynamic libraries on IA-64, but not PPC
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               AS_IF([test "$GCC" = yes], [
+                   CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               ], [
+                   CC_SEARCH_FLAGS='"-R${LIB_RUNTIME_DIR}"'
+               ])
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ], [
+               AS_IF([test "$GCC" = yes], [
+                   SHLIB_LD='${CC} -shared -Wl,-bexpall'
+               ], [
+                   SHLIB_LD="/bin/ld -bhalt:4 -bM:SRE -bexpall -H512 -T512 -bnoentry"
+                   LDFLAGS="$LDFLAGS -brtl"
+               ])
+               SHLIB_LD="${SHLIB_LD} ${SHLIB_LD_FLAGS}"
+               CC_SEARCH_FLAGS='"-L${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       BeOS*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} -nostart'
+           SHLIB_SUFFIX=".so"
+
+           #-----------------------------------------------------------
+           # Check for inet_ntoa in -lbind, for BeOS (which also needs
+           # -lsocket, even if the network functions are in -lnet which
+           # is always linked to, for compatibility.
+           #-----------------------------------------------------------
+           AC_CHECK_LIB(bind, inet_ntoa, [LIBS="$LIBS -lbind -lsocket"])
+           ;;
+       BSD/OS-2.1*|BSD/OS-3*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="shlicc -r"
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       BSD/OS-4.*)
+           SHLIB_CFLAGS="-export-dynamic -fPIC"
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       CYGWIN_*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD='${CC} -shared'
+           SHLIB_SUFFIX=".dll"
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
+           EXEEXT=".exe"
+           do64bit_ok=yes
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       dgux*)
+           SHLIB_CFLAGS="-K PIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       Haiku*)
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS} -shared'
+           AC_CHECK_LIB(network, inet_ntoa, [LIBS="$LIBS -lnetwork"])
+           ;;
+       HP-UX-*.11.*)
+           # Use updated header definitions where possible
+           AC_DEFINE(_XOPEN_SOURCE_EXTENDED, 1, [Do we want to use the XOPEN network library?])
+           # TEA specific: Needed by Tcl, but not most extensions
+           #AC_DEFINE(_XOPEN_SOURCE, 1, [Do we want to use the XOPEN network library?])
+           #LIBS="$LIBS -lxnet"               # Use the XOPEN network library
+
+           AS_IF([test "`uname -m`" = ia64], [
+               SHLIB_SUFFIX=".so"
+           ], [
+               SHLIB_SUFFIX=".sl"
+           ])
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ])
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               CFLAGS="$CFLAGS -z"
+           ])
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = "yes"], [
+               AS_IF([test "$GCC" = yes], [
+                   case `${CC} -dumpmachine` in
+                       hppa64*)
+                           # 64-bit gcc in use.  Fix flags for GNU ld.
+                           do64bit_ok=yes
+                           SHLIB_LD='${CC} -shared'
+                           AS_IF([test $doRpath = yes], [
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+                           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+                           ;;
+                       *)
+                           AC_MSG_WARN([64bit mode not supported with GCC on $system])
+                           ;;
+                   esac
+               ], [
+                   do64bit_ok=yes
+                   CFLAGS="$CFLAGS +DD64"
+                   LDFLAGS_ARCH="+DD64"
+               ])
+           ]) ;;
+       HP-UX-*.08.*|HP-UX-*.09.*|HP-UX-*.10.*)
+           SHLIB_SUFFIX=".sl"
+           AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
+           AS_IF([test "$tcl_ok" = yes], [
+               SHLIB_CFLAGS="+z"
+               SHLIB_LD="ld -b"
+               SHLIB_LD_LIBS=""
+               LDFLAGS="$LDFLAGS -Wl,-E"
+               CC_SEARCH_FLAGS='"-Wl,+s,+b,${LIB_RUNTIME_DIR}:."'
+               LD_SEARCH_FLAGS='+s +b "${LIB_RUNTIME_DIR}:."'
+               LD_LIBRARY_PATH_VAR="SHLIB_PATH"
+           ]) ;;
+       IRIX-5.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AC_LIBOBJ(mkstemp)
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           ;;
+       IRIX-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+           AS_IF([test "$GCC" = yes], [
+               CFLAGS="$CFLAGS -mabi=n32"
+               LDFLAGS="$LDFLAGS -mabi=n32"
+           ], [
+               case $system in
+                   IRIX-6.3)
+                       # Use to build 6.2 compatible binaries on 6.3.
+                       CFLAGS="$CFLAGS -n32 -D_OLD_TERMIOS"
+                       ;;
+                   *)
+                       CFLAGS="$CFLAGS -n32"
+                       ;;
+               esac
+               LDFLAGS="$LDFLAGS -n32"
+           ])
+           ;;
+       IRIX64-6.*)
+           SHLIB_CFLAGS=""
+           SHLIB_LD="ld -n32 -shared -rdata_shared"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath "${LIB_RUNTIME_DIR}"'])
+
+           # Check to enable 64-bit flags for compiler/linker
+
+           AS_IF([test "$do64bit" = yes], [
+               AS_IF([test "$GCC" = yes], [
+                   AC_MSG_WARN([64bit mode not supported by gcc])
+               ], [
+                   do64bit_ok=yes
+                   SHLIB_LD="ld -64 -shared -rdata_shared"
+                   CFLAGS="$CFLAGS -64"
+                   LDFLAGS_ARCH="-64"
+               ])
+           ])
+           ;;
+       Linux*|GNU*|NetBSD-Debian|DragonFly-*|FreeBSD-*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+
+           # TEA specific:
+           CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
+
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} ${CFLAGS} ${LDFLAGS_DEFAULT} -shared'
+           LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
+
+           case $system in
+           DragonFly-*|FreeBSD-*)
+               AS_IF([test "${TCL_THREADS}" = "1"], [
+                   # The -pthread needs to go in the LDFLAGS, not LIBS
+                   LIBS=`echo $LIBS | sed s/-pthread//`
+                   CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+                   LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
+           ;;
+            esac
+
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
+           AS_IF([test $do64bit = yes], [
+               AC_CACHE_CHECK([if compiler accepts -m64 flag], tcl_cv_cc_m64, [
+                   hold_cflags=$CFLAGS
+                   CFLAGS="$CFLAGS -m64"
+                   AC_TRY_LINK(,, tcl_cv_cc_m64=yes, tcl_cv_cc_m64=no)
+                   CFLAGS=$hold_cflags])
+               AS_IF([test $tcl_cv_cc_m64 = yes], [
+                   CFLAGS="$CFLAGS -m64"
+                   do64bit_ok=yes
+               ])
+          ])
+
+           # The combo of gcc + glibc has a bug related to inlining of
+           # functions like strtod(). The -fno-builtin flag should address
+           # this problem but it does not work. The -fno-inline flag is kind
+           # of overkill but it works. Disable inlining only when one of the
+           # files in compat/*.c is being linked in.
+
+           AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
+           ;;
+       Lynx*)
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_SUFFIX=".so"
+           CFLAGS_OPTIMIZE=-02
+           SHLIB_LD='${CC} -shared'
+           LD_FLAGS="-Wl,--export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           ;;
+       OpenBSD-*)
+           arch=`arch -s`
+           case "$arch" in
+           alpha|sparc64)
+               SHLIB_CFLAGS="-fPIC"
+               ;;
+           *)
+               SHLIB_CFLAGS="-fpic"
+               ;;
+           esac
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
+           LDFLAGS="$LDFLAGS -Wl,-export-dynamic"
+           CFLAGS_OPTIMIZE="-O2"
+           # On OpenBSD:       Compile with -pthread
+           #           Don't link with -lpthread
+           LIBS=`echo $LIBS | sed s/-lpthread//`
+           CFLAGS="$CFLAGS -pthread"
+           # OpenBSD doesn't do version numbers with dots.
+           UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
+           TCL_LIB_VERSIONS_OK=nodots
+           ;;
+       NetBSD-*)
+           # NetBSD has ELF and can use 'cc -shared' to build shared libs
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD='${CC} ${SHLIB_CFLAGS} -shared'
+           SHLIB_SUFFIX=".so"
+           LDFLAGS="$LDFLAGS -export-dynamic"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
+           LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           # The -pthread needs to go in the CFLAGS, not LIBS
+           LIBS=`echo $LIBS | sed s/-pthread//`
+           CFLAGS="$CFLAGS -pthread"
+           LDFLAGS="$LDFLAGS -pthread"
+           ;;
+       Darwin-*)
+           CFLAGS_OPTIMIZE="-Os"
+           SHLIB_CFLAGS="-fno-common"
+           # To avoid discrepancies between what headers configure sees during
+           # preprocessing tests and compiling tests, move any -isysroot and
+           # -mmacosx-version-min flags from CFLAGS to CPPFLAGS:
+           CPPFLAGS="${CPPFLAGS} `echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if ([$]i~/^(isysroot|mmacosx-version-min)/) print "-"[$]i}'`"
+           CFLAGS="`echo " ${CFLAGS}" | \
+               awk 'BEGIN {FS=" +-";ORS=" "}; {for (i=2;i<=NF;i++) \
+               if (!([$]i~/^(isysroot|mmacosx-version-min)/)) print "-"[$]i}'`"
+           AS_IF([test $do64bit = yes], [
+               case `arch` in
+                   ppc)
+                       AC_CACHE_CHECK([if compiler accepts -arch ppc64 flag],
+                               tcl_cv_cc_arch_ppc64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_ppc64=yes,
+                                   tcl_cv_cc_arch_ppc64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_ppc64 = yes], [
+                           CFLAGS="$CFLAGS -arch ppc64 -mpowerpc64 -mcpu=G5"
+                           do64bit_ok=yes
+                       ]);;
+                   i386)
+                       AC_CACHE_CHECK([if compiler accepts -arch x86_64 flag],
+                               tcl_cv_cc_arch_x86_64, [
+                           hold_cflags=$CFLAGS
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           AC_TRY_LINK(,, tcl_cv_cc_arch_x86_64=yes,
+                                   tcl_cv_cc_arch_x86_64=no)
+                           CFLAGS=$hold_cflags])
+                       AS_IF([test $tcl_cv_cc_arch_x86_64 = yes], [
+                           CFLAGS="$CFLAGS -arch x86_64"
+                           do64bit_ok=yes
+                       ]);;
+                   *)
+                       AC_MSG_WARN([Don't know how enable 64-bit on architecture `arch`]);;
+               esac
+           ], [
+               # Check for combined 32-bit and 64-bit fat build
+               AS_IF([echo "$CFLAGS " |grep -E -q -- '-arch (ppc64|x86_64) ' \
+                   && echo "$CFLAGS " |grep -E -q -- '-arch (ppc|i386) '], [
+                   fat_32_64=yes])
+           ])
+           # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+           SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS_DEFAULT}'
+           AC_CACHE_CHECK([if ld accepts -single_module flag], tcl_cv_ld_single_module, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_single_module = yes], [
+               SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
+           ])
+           # TEA specific: link shlib with current and compatibility version flags
+           vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
+           SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
+           SHLIB_SUFFIX=".dylib"
+           LDFLAGS="$LDFLAGS -headerpad_max_install_names"
+           AC_CACHE_CHECK([if ld accepts -search_paths_first flag],
+                   tcl_cv_ld_search_paths_first, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_search_paths_first=yes,
+                       tcl_cv_ld_search_paths_first=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_search_paths_first = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-search_paths_first"
+           ])
+           AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+               AC_DEFINE(MODULE_SCOPE, [__private_extern__],
+                   [Compiler support for module scope symbols])
+               tcl_cv_cc_visibility_hidden=yes
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           LD_LIBRARY_PATH_VAR="DYLD_LIBRARY_PATH"
+           # TEA specific: for combined 32 & 64 bit fat builds of Tk
+           # extensions, verify that 64-bit build is possible.
+           AS_IF([test "$fat_32_64" = yes && test -n "${TK_BIN_DIR}"], [
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = x11], [
+                   AC_CACHE_CHECK([for 64-bit X11], tcl_cv_lib_x11_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -I/usr/X11R6/include"
+                       LDFLAGS="$LDFLAGS -L/usr/X11R6/lib -lX11"
+                       AC_TRY_LINK([#include <X11/Xlib.h>], [XrmInitialize();],
+                           tcl_cv_lib_x11_64=yes, tcl_cv_lib_x11_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               AS_IF([test "${TEA_WINDOWINGSYSTEM}" = aqua], [
+                   AC_CACHE_CHECK([for 64-bit Tk], tcl_cv_lib_tk_64, [
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval 'hold_'$v'="$'$v'";'$v'="`echo "$'$v' "|sed -e "s/-arch ppc / /g" -e "s/-arch i386 / /g"`"'
+                       done
+                       CPPFLAGS="$CPPFLAGS -DUSE_TCL_STUBS=1 -DUSE_TK_STUBS=1 ${TCL_INCLUDES} ${TK_INCLUDES}"
+                       LDFLAGS="$LDFLAGS ${TCL_STUB_LIB_SPEC} ${TK_STUB_LIB_SPEC}"
+                       AC_TRY_LINK([#include <tk.h>], [Tk_InitStubs(NULL, "", 0);],
+                           tcl_cv_lib_tk_64=yes, tcl_cv_lib_tk_64=no)
+                       for v in CFLAGS CPPFLAGS LDFLAGS; do
+                           eval $v'="$hold_'$v'"'
+                       done])
+               ])
+               # remove 64-bit arch flags from CFLAGS et al. if configuration
+               # does not support 64-bit.
+               AS_IF([test "$tcl_cv_lib_tk_64" = no -o "$tcl_cv_lib_x11_64" = no], [
+                   AC_MSG_NOTICE([Removing 64-bit architectures from compiler & linker flags])
+                   for v in CFLAGS CPPFLAGS LDFLAGS; do
+                       eval $v'="`echo "$'$v' "|sed -e "s/-arch ppc64 / /g" -e "s/-arch x86_64 / /g"`"'
+                   done])
+           ])
+           ;;
+       OS/390-*)
+           CFLAGS_OPTIMIZE=""          # Optimizer is buggy
+           AC_DEFINE(_OE_SOCKETS, 1,   # needed in sys/socket.h
+               [Should OS/390 do the right thing with sockets?])
+           ;;
+       OSF1-V*)
+           # Digital OSF/1
+           SHLIB_CFLAGS=""
+           AS_IF([test "$SHARED_BUILD" = 1], [
+               SHLIB_LD='ld -shared -expect_unresolved "*"'
+           ], [
+               SHLIB_LD='ld -non_shared -expect_unresolved "*"'
+           ])
+           SHLIB_SUFFIX=".so"
+           AS_IF([test $doRpath = yes], [
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
+           AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
+               CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
+           # see pthread_intro(3) for pthread support on osf1, k.furukawa
+           CFLAGS="$CFLAGS -DHAVE_PTHREAD_ATTR_SETSTACKSIZE"
+           CFLAGS="$CFLAGS -DTCL_THREAD_STACK_MIN=PTHREAD_STACK_MIN*64"
+           LIBS=`echo $LIBS | sed s/-lpthreads//`
+           AS_IF([test "$GCC" = yes], [
+               LIBS="$LIBS -lpthread -lmach -lexc"
+           ], [
+               CFLAGS="$CFLAGS -pthread"
+               LDFLAGS="$LDFLAGS -pthread"
+           ])
+           ;;
+       QNX-6*)
+           # QNX RTP
+           # This may work for all QNX, but it was only reported for v6.
+           SHLIB_CFLAGS="-fPIC"
+           SHLIB_LD="ld -Bshareable -x"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SCO_SV-3.2*)
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_CFLAGS="-fPIC -melf"
+               LDFLAGS="$LDFLAGS -melf -Wl,-Bexport"
+           ], [
+               SHLIB_CFLAGS="-Kpic -belf"
+               LDFLAGS="$LDFLAGS -belf -Wl,-Bexport"
+           ])
+           SHLIB_LD="ld -G"
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+       SunOS-5.[[0-6]])
+           # Careful to not let 5.10+ fall into this case
+
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ], [
+               SHLIB_LD="/usr/ccs/bin/ld -G -z text"
+               CC_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+           ])
+           ;;
+       SunOS-5*)
+           # Note: If _REENTRANT isn't defined, then Solaris
+           # won't define thread-safe library routines.
+
+           AC_DEFINE(_REENTRANT, 1, [Do we want the reentrant OS API?])
+           AC_DEFINE(_POSIX_PTHREAD_SEMANTICS, 1,
+               [Do we really want to follow the standard? Yes we do!])
+
+           SHLIB_CFLAGS="-KPIC"
+
+           # Check to enable 64-bit flags for compiler/linker
+           AS_IF([test "$do64bit" = yes], [
+               arch=`isainfo`
+               AS_IF([test "$arch" = "sparcv9 sparc"], [
+                   AS_IF([test "$GCC" = yes], [
+                       AS_IF([test "`${CC} -dumpversion | awk -F. '{print [$]1}'`" -lt 3], [
+                           AC_MSG_WARN([64bit mode not supported with GCC < 3.2 on $system])
+                       ], [
+                           do64bit_ok=yes
+                           CFLAGS="$CFLAGS -m64 -mcpu=v9"
+                           LDFLAGS="$LDFLAGS -m64 -mcpu=v9"
+                           SHLIB_CFLAGS="-fPIC"
+                       ])
+                   ], [
+                       do64bit_ok=yes
+                       AS_IF([test "$do64bitVIS" = yes], [
+                           CFLAGS="$CFLAGS -xarch=v9a"
+                           LDFLAGS_ARCH="-xarch=v9a"
+                       ], [
+                           CFLAGS="$CFLAGS -xarch=v9"
+                           LDFLAGS_ARCH="-xarch=v9"
+                       ])
+                       # Solaris 64 uses this as well
+                       #LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH_64"
+                   ])
+               ], [AS_IF([test "$arch" = "amd64 i386"], [
+                   AS_IF([test "$GCC" = yes], [
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               do64bit_ok=yes
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               AC_MSG_WARN([64bit mode not supported with GCC on $system]);;
+                       esac
+                   ], [
+                       do64bit_ok=yes
+                       case $system in
+                           SunOS-5.1[[1-9]]*|SunOS-5.[[2-9]][[0-9]]*)
+                               CFLAGS="$CFLAGS -m64"
+                               LDFLAGS="$LDFLAGS -m64";;
+                           *)
+                               CFLAGS="$CFLAGS -xarch=amd64"
+                               LDFLAGS="$LDFLAGS -xarch=amd64";;
+                       esac
+                   ])
+               ], [AC_MSG_WARN([64bit mode not supported for $arch])])])
+           ])
+
+           SHLIB_SUFFIX=".so"
+           AS_IF([test "$GCC" = yes], [
+               SHLIB_LD='${CC} -shared'
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
+               AS_IF([test "$do64bit_ok" = yes], [
+                   AS_IF([test "$arch" = "sparcv9 sparc"], [
+                       # We need to specify -static-libgcc or we need to
+                       # add the path to the sparv9 libgcc.
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -mcpu=v9 -static-libgcc"
+                       # for finding sparcv9 libgcc, get the regular libgcc
+                       # path, remove so name and append 'sparcv9'
+                       #v9gcclibdir="`gcc -print-file-name=libgcc_s.so` | ..."
+                       #CC_SEARCH_FLAGS="${CC_SEARCH_FLAGS},-R,$v9gcclibdir"
+                   ], [AS_IF([test "$arch" = "amd64 i386"], [
+                       # JH: static-libgcc is necessary for core Tcl, but may
+                       # not be necessary for extensions.
+                       SHLIB_LD="$SHLIB_LD -m64 -static-libgcc"
+                   ])])
+               ])
+           ], [
+               case $system in
+                   SunOS-5.[[1-9]][[0-9]]*)
+                       # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
+                       SHLIB_LD='${CC} -G -z text ${LDFLAGS_DEFAULT}';;
+                   *)
+                       SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
+               esac
+               CC_SEARCH_FLAGS='"-Wl,-R,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='-R "${LIB_RUNTIME_DIR}"'
+           ])
+           ;;
+       UNIX_SV* | UnixWare-5*)
+           SHLIB_CFLAGS="-KPIC"
+           SHLIB_LD='${CC} -G'
+           SHLIB_LD_LIBS=""
+           SHLIB_SUFFIX=".so"
+           # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
+           # that don't grok the -Bexport option.  Test that it does.
+           AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
+               hold_ldflags=$LDFLAGS
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+               AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
+               LDFLAGS=$hold_ldflags])
+           AS_IF([test $tcl_cv_ld_Bexport = yes], [
+               LDFLAGS="$LDFLAGS -Wl,-Bexport"
+           ])
+           CC_SEARCH_FLAGS=""
+           LD_SEARCH_FLAGS=""
+           ;;
+    esac
+
+    AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
+       AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
+    ])
+
+dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
+dnl # until the end of configure, as configure's compile and link tests use
+dnl # both CPPFLAGS and CFLAGS (unlike our compile and link) but configure's
+dnl # preprocessing tests use only CPPFLAGS.
+    AC_CONFIG_COMMANDS_PRE([CFLAGS="${CFLAGS} ${CPPFLAGS}"; CPPFLAGS=""])
+
+    # Add in the arch flags late to ensure it wasn't removed.
+    # Not necessary in TEA, but this is aligned with core
+    LDFLAGS="$LDFLAGS $LDFLAGS_ARCH"
+
+    # If we're running gcc, then change the C flags for compiling shared
+    # libraries to the right flags for gcc, instead of those for the
+    # standard manufacturer compiler.
+
+    AS_IF([test "$GCC" = yes], [
+       case $system in
+           AIX-*) ;;
+           BSD/OS*) ;;
+           CYGWIN_*|MINGW32_*|MINGW64_*|MSYS_*) ;;
+           IRIX*) ;;
+           NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
+           Darwin-*) ;;
+           SCO_SV-3.2*) ;;
+           windows) ;;
+           *) SHLIB_CFLAGS="-fPIC" ;;
+       esac])
+
+    AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
+       AC_DEFINE(MODULE_SCOPE, [extern],
+           [No Compiler support for module scope symbols])
+    ])
+
+    AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
+    AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
+    # TEA specific: use PACKAGE_VERSION instead of VERSION
+    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
+
+    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
+       AC_CACHE_CHECK(for SEH support in compiler,
+           tcl_cv_seh,
+       AC_TRY_RUN([
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+
+           int main(int argc, char** argv) {
+               int a, b = 0;
+               __try {
+                   a = 666 / b;
+               }
+               __except (EXCEPTION_EXECUTE_HANDLER) {
+                   return 0;
+               }
+               return 1;
+           }
+       ],
+           tcl_cv_seh=yes,
+           tcl_cv_seh=no,
+           tcl_cv_seh=no)
+       )
+       if test "$tcl_cv_seh" = "no" ; then
+           AC_DEFINE(HAVE_NO_SEH, 1,
+                   [Defined when mingw does not support SEH])
+       fi
+
+       #
+       # Check to see if the excpt.h include file provided contains the
+       # definition for EXCEPTION_DISPOSITION; if not, which is the case
+       # with Cygwin's version as of 2002-04-10, define it to be int,
+       # sufficient for getting the current code to work.
+       #
+       AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
+           tcl_cv_eh_disposition,
+           AC_TRY_COMPILE([
+#          define WIN32_LEAN_AND_MEAN
+#          include <windows.h>
+#          undef WIN32_LEAN_AND_MEAN
+           ],[
+               EXCEPTION_DISPOSITION x;
+           ],
+               tcl_cv_eh_disposition=yes,
+               tcl_cv_eh_disposition=no)
+       )
+       if test "$tcl_cv_eh_disposition" = "no" ; then
+       AC_DEFINE(EXCEPTION_DISPOSITION, int,
+               [Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
+       fi
+
+       # Check to see if winnt.h defines CHAR, SHORT, and LONG
+       # even if VOID has already been #defined. The win32api
+       # used by mingw and cygwin is known to do this.
+
+       AC_CACHE_CHECK(for winnt.h that ignores VOID define,
+           tcl_cv_winnt_ignore_void,
+           AC_TRY_COMPILE([
+#define VOID void
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+           ], [
+               CHAR c;
+               SHORT s;
+               LONG l;
+           ],
+        tcl_cv_winnt_ignore_void=yes,
+        tcl_cv_winnt_ignore_void=no)
+       )
+       if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
+           AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
+                   [Defined when cygwin/mingw ignores VOID define in winnt.h])
+       fi
+    fi
+
+       # See if the compiler supports casting to a union type.
+       # This is used to stop gcc from printing a compiler
+       # warning when initializing a union member.
+
+       AC_CACHE_CHECK(for cast to union support,
+           tcl_cv_cast_to_union,
+           AC_TRY_COMPILE([],
+           [
+                 union foo { int i; double d; };
+                 union foo f = (union foo) (int) 0;
+           ],
+           tcl_cv_cast_to_union=yes,
+           tcl_cv_cast_to_union=no)
+       )
+       if test "$tcl_cv_cast_to_union" = "yes"; then
+           AC_DEFINE(HAVE_CAST_TO_UNION, 1,
+                   [Defined when compiler supports casting to union type.])
+       fi
+
+       AC_CHECK_HEADER(stdbool.h, [AC_DEFINE(HAVE_STDBOOL_H, 1, [Do we have <stdbool.h>?])],)
+
+    AC_SUBST(CFLAGS_DEBUG)
+    AC_SUBST(CFLAGS_OPTIMIZE)
+    AC_SUBST(CFLAGS_WARNING)
+    AC_SUBST(LDFLAGS_DEBUG)
+    AC_SUBST(LDFLAGS_OPTIMIZE)
+
+    AC_SUBST(STLIB_LD)
+    AC_SUBST(SHLIB_LD)
+
+    AC_SUBST(SHLIB_LD_LIBS)
+    AC_SUBST(SHLIB_CFLAGS)
+
+    AC_SUBST(LD_LIBRARY_PATH_VAR)
+
+    # These must be called after we do the basic CFLAGS checks and
+    # verify any possible 64-bit or similar switches are necessary
+    TEA_TCL_EARLY_FLAGS
+    TEA_TCL_64BIT_FLAGS
+])
+
+#--------------------------------------------------------------------
+# TEA_SERIAL_PORT
+#
+#      Determine which interface to use to talk to the serial port.
+#      Note that #include lines must begin in leftmost column for
+#      some compilers to recognize them as preprocessor directives,
+#      and some build environments have stdin not pointing at a
+#      pseudo-terminal (usually /dev/null instead.)
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines only one of the following vars:
+#              HAVE_SYS_MODEM_H
+#              USE_TERMIOS
+#              USE_TERMIO
+#              USE_SGTTY
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_SERIAL_PORT], [
+    AC_CHECK_HEADERS(sys/modem.h)
+    AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
+    AC_TRY_RUN([
+#include <termios.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termio.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no ; then
+       AC_TRY_RUN([
+#include <termios.h>
+#include <errno.h>
+
+int main() {
+    struct termios t;
+    if (tcgetattr(0, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       cfsetospeed(&t, 0);
+       t.c_cflag |= PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=termios, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <termio.h>
+#include <errno.h>
+
+int main() {
+    struct termio t;
+    if (ioctl(0, TCGETA, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.c_cflag |= CBAUD | PARENB | PARODD | CSIZE | CSTOPB;
+       return 0;
+    }
+    return 1;
+    }], tcl_cv_api_serial=termio, tcl_cv_api_serial=no, tcl_cv_api_serial=no)
+    fi
+    if test $tcl_cv_api_serial = no; then
+       AC_TRY_RUN([
+#include <sgtty.h>
+#include <errno.h>
+
+int main() {
+    struct sgttyb t;
+    if (ioctl(0, TIOCGETP, &t) == 0
+       || errno == ENOTTY || errno == ENXIO || errno == EINVAL) {
+       t.sg_ospeed = 0;
+       t.sg_flags |= ODDP | EVENP | RAW;
+       return 0;
+    }
+    return 1;
+}], tcl_cv_api_serial=sgtty, tcl_cv_api_serial=none, tcl_cv_api_serial=none)
+    fi])
+    case $tcl_cv_api_serial in
+       termios) AC_DEFINE(USE_TERMIOS, 1, [Use the termios API for serial lines]);;
+       termio)  AC_DEFINE(USE_TERMIO, 1, [Use the termio API for serial lines]);;
+       sgtty)   AC_DEFINE(USE_SGTTY, 1, [Use the sgtty API for serial lines]);;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_PATH_X
+#
+#      Locate the X11 header files and the X11 library archive.  Try
+#      the ac_path_x macro first, but if it doesn't find the X stuff
+#      (e.g. because there's no xmkmf program) then check through
+#      a list of possible directories.  Under some conditions the
+#      autoconf macro will return an include directory that contains
+#      no include files, so double-check its result just to be safe.
+#
+#      This should be called after TEA_CONFIG_CFLAGS as setting the
+#      LIBS line can confuse some configure macro magic.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets the following vars:
+#              XINCLUDES
+#              XLIBSW
+#              PKG_LIBS (appends to)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_X], [
+    if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
+       TEA_PATH_UNIX_X
+    fi
+])
+
+AC_DEFUN([TEA_PATH_UNIX_X], [
+    AC_PATH_X
+    not_really_there=""
+    if test "$no_x" = ""; then
+       if test "$x_includes" = ""; then
+           AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
+       else
+           if test ! -r $x_includes/X11/Xlib.h; then
+               not_really_there="yes"
+           fi
+       fi
+    fi
+    if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
+       AC_MSG_CHECKING([for X11 header files])
+       found_xincludes="no"
+       AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
+       if test "$found_xincludes" = "no"; then
+           dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
+           for i in $dirs ; do
+               if test -r $i/X11/Xlib.h; then
+                   AC_MSG_RESULT([$i])
+                   XINCLUDES=" -I$i"
+                   found_xincludes="yes"
+                   break
+               fi
+           done
+       fi
+    else
+       if test "$x_includes" != ""; then
+           XINCLUDES="-I$x_includes"
+           found_xincludes="yes"
+       fi
+    fi
+    if test "$found_xincludes" = "no"; then
+       AC_MSG_RESULT([couldn't find any!])
+    fi
+
+    if test "$no_x" = yes; then
+       AC_MSG_CHECKING([for X11 libraries])
+       XLIBSW=nope
+       dirs="/usr/unsupported/lib /usr/local/lib /usr/X386/lib /usr/X11R6/lib /usr/X11R5/lib /usr/lib/X11R5 /usr/lib/X11R4 /usr/openwin/lib /usr/X11/lib /usr/sww/X11/lib"
+       for i in $dirs ; do
+           if test -r $i/libX11.a -o -r $i/libX11.so -o -r $i/libX11.sl -o -r $i/libX11.dylib; then
+               AC_MSG_RESULT([$i])
+               XLIBSW="-L$i -lX11"
+               x_libraries="$i"
+               break
+           fi
+       done
+    else
+       if test "$x_libraries" = ""; then
+           XLIBSW=-lX11
+       else
+           XLIBSW="-L$x_libraries -lX11"
+       fi
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_CHECK_LIB(Xwindow, XCreateWindow, XLIBSW=-lXwindow)
+    fi
+    if test "$XLIBSW" = nope ; then
+       AC_MSG_RESULT([could not find any!  Using -lX11.])
+       XLIBSW=-lX11
+    fi
+    # TEA specific:
+    if test x"${XLIBSW}" != x ; then
+       PKG_LIBS="${PKG_LIBS} ${XLIBSW}"
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BLOCKING_STYLE
+#
+#      The statements below check for systems where POSIX-style
+#      non-blocking I/O (O_NONBLOCK) doesn't work or is unimplemented.
+#      On these systems (mostly older ones), use the old BSD-style
+#      FIONBIO approach instead.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              HAVE_SYS_IOCTL_H
+#              HAVE_SYS_FILIO_H
+#              USE_FIONBIO
+#              O_NONBLOCK
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BLOCKING_STYLE], [
+    AC_CHECK_HEADERS(sys/ioctl.h)
+    AC_CHECK_HEADERS(sys/filio.h)
+    TEA_CONFIG_SYSTEM
+    AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
+    case $system in
+       OSF*)
+           AC_DEFINE(USE_FIONBIO, 1, [Should we use FIONBIO?])
+           AC_MSG_RESULT([FIONBIO])
+           ;;
+       *)
+           AC_MSG_RESULT([O_NONBLOCK])
+           ;;
+    esac
+])
+
+#--------------------------------------------------------------------
+# TEA_TIME_HANDLER
+#
+#      Checks how the system deals with time.h, what time structures
+#      are used on the system, and what fields the structures have.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines some of the following vars:
+#              USE_DELTA_FOR_TZ
+#              HAVE_TM_GMTOFF
+#              HAVE_TM_TZADJ
+#              HAVE_TIMEZONE_VAR
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TIME_HANDLER], [
+    AC_CHECK_HEADERS(sys/time.h)
+    AC_HEADER_TIME
+    AC_STRUCT_TIMEZONE
+
+    AC_CHECK_FUNCS(gmtime_r localtime_r mktime)
+
+    AC_CACHE_CHECK([tm_tzadj in struct tm], tcl_cv_member_tm_tzadj, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_tzadj;],
+           tcl_cv_member_tm_tzadj=yes, tcl_cv_member_tm_tzadj=no)])
+    if test $tcl_cv_member_tm_tzadj = yes ; then
+       AC_DEFINE(HAVE_TM_TZADJ, 1, [Should we use the tm_tzadj field of struct tm?])
+    fi
+
+    AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
+           tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
+    if test $tcl_cv_member_tm_gmtoff = yes ; then
+       AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
+    fi
+
+    #
+    # Its important to include time.h in this check, as some systems
+    # (like convex) have timezone functions, etc.
+    #
+    AC_CACHE_CHECK([long timezone variable], tcl_cv_timezone_long, [
+       AC_TRY_COMPILE([#include <time.h>],
+           [extern long timezone;
+           timezone += 1;
+           exit (0);],
+           tcl_cv_timezone_long=yes, tcl_cv_timezone_long=no)])
+    if test $tcl_cv_timezone_long = yes ; then
+       AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+    else
+       #
+       # On some systems (eg IRIX 6.2), timezone is a time_t and not a long.
+       #
+       AC_CACHE_CHECK([time_t timezone variable], tcl_cv_timezone_time, [
+           AC_TRY_COMPILE([#include <time.h>],
+               [extern time_t timezone;
+               timezone += 1;
+               exit (0);],
+               tcl_cv_timezone_time=yes, tcl_cv_timezone_time=no)])
+       if test $tcl_cv_timezone_time = yes ; then
+           AC_DEFINE(HAVE_TIMEZONE_VAR, 1, [Should we use the global timezone variable?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_BUGGY_STRTOD
+#
+#      Under Solaris 2.4, strtod returns the wrong value for the
+#      terminating character under some conditions.  Check for this
+#      and if the problem exists use a substitute procedure
+#      "fixstrtod" (provided by Tcl) that corrects the error.
+#      Also, on Compaq's Tru64 Unix 5.0,
+#      strtod(" ") returns 0.0 instead of a failure to convert.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Might defines some of the following vars:
+#              strtod (=fixstrtod)
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_BUGGY_STRTOD], [
+    AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
+    if test "$tcl_strtod" = 1; then
+       AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
+           AC_TRY_RUN([
+               #include <stdlib.h>
+               extern double strtod();
+               int main() {
+                   char *infString="Inf", *nanString="NaN", *spaceString=" ";
+                   char *term;
+                   double value;
+                   value = strtod(infString, &term);
+                   if ((term != infString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(nanString, &term);
+                   if ((term != nanString) && (term[-1] == 0)) {
+                       exit(1);
+                   }
+                   value = strtod(spaceString, &term);
+                   if (term == (spaceString+1)) {
+                       exit(1);
+                   }
+                   exit(0);
+               }], tcl_cv_strtod_buggy=ok, tcl_cv_strtod_buggy=buggy,
+                   tcl_cv_strtod_buggy=buggy)])
+       if test "$tcl_cv_strtod_buggy" = buggy; then
+           AC_LIBOBJ([fixstrtod])
+           USE_COMPAT=1
+           AC_DEFINE(strtod, fixstrtod, [Do we want to use the strtod() in compat?])
+       fi
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_LINK_LIBS
+#
+#      Search for the libraries needed to link the Tcl shell.
+#      Things like the math library (-lm), socket stuff (-lsocket vs.
+#      -lnsl), zlib (-lz) and libtommath (-ltommath) are dealt with here.
+#
+# Arguments:
+#      None.
+#
+# Results:
+#
+#      Might append to the following vars:
+#              LIBS
+#              MATH_LIBS
+#
+#      Might define the following vars:
+#              HAVE_NET_ERRNO_H
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_LINK_LIBS], [
+    #--------------------------------------------------------------------
+    # On a few very rare systems, all of the libm.a stuff is
+    # already in libc.a.  Set compiler flags accordingly.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_FUNC(sin, MATH_LIBS="", MATH_LIBS="-lm")
+
+    #--------------------------------------------------------------------
+    # Interactive UNIX requires -linet instead of -lsocket, plus it
+    # needs net/errno.h to define the socket-related error codes.
+    #--------------------------------------------------------------------
+
+    AC_CHECK_LIB(inet, main, [LIBS="$LIBS -linet"])
+    AC_CHECK_HEADER(net/errno.h, [
+       AC_DEFINE(HAVE_NET_ERRNO_H, 1, [Do we have <net/errno.h>?])])
+
+    #--------------------------------------------------------------------
+    #  Check for the existence of the -lsocket and -lnsl libraries.
+    #  The order here is important, so that they end up in the right
+    #  order in the command line generated by make.  Here are some
+    #  special considerations:
+    #  1. Use "connect" and "accept" to check for -lsocket, and
+    #     "gethostbyname" to check for -lnsl.
+    #  2. Use each function name only once:  can't redo a check because
+    #     autoconf caches the results of the last check and won't redo it.
+    #  3. Use -lnsl and -lsocket only if they supply procedures that
+    #     aren't already present in the normal libraries.  This is because
+    #     IRIX 5.2 has libraries, but they aren't needed and they're
+    #     bogus:  they goof up name resolution if used.
+    #  4. On some SVR4 systems, can't use -lsocket without -lnsl too.
+    #     To get around this problem, check for both libraries together
+    #     if -lsocket doesn't work by itself.
+    #--------------------------------------------------------------------
+
+    tcl_checkBoth=0
+    AC_CHECK_FUNC(connect, tcl_checkSocket=0, tcl_checkSocket=1)
+    if test "$tcl_checkSocket" = 1; then
+       AC_CHECK_FUNC(setsockopt, , [AC_CHECK_LIB(socket, setsockopt,
+           LIBS="$LIBS -lsocket", tcl_checkBoth=1)])
+    fi
+    if test "$tcl_checkBoth" = 1; then
+       tk_oldLibs=$LIBS
+       LIBS="$LIBS -lsocket -lnsl"
+       AC_CHECK_FUNC(accept, tcl_checkNsl=0, [LIBS=$tk_oldLibs])
+    fi
+    AC_CHECK_FUNC(gethostbyname, , [AC_CHECK_LIB(nsl, gethostbyname,
+           [LIBS="$LIBS -lnsl"])])
+    AC_CHECK_FUNC(mp_log_u32, , [AC_CHECK_LIB(tommath, mp_log_u32,
+           [LIBS="$LIBS -ltommath"])])
+    AC_CHECK_FUNC(deflateSetHeader, , [AC_CHECK_LIB(z, deflateSetHeader,
+           [LIBS="$LIBS -lz"])])
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_EARLY_FLAGS
+#
+#      Check for what flags are needed to be passed so the correct OS
+#      features are available.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              _ISOC99_SOURCE
+#              _LARGEFILE64_SOURCE
+#              _LARGEFILE_SOURCE64
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_EARLY_FLAG],[
+    AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
+       AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
+           AC_TRY_COMPILE([[#define ]$1[ 1
+]$2], $3,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=yes,
+               [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no)))
+    if test ["x${tcl_cv_flag_]translit($1,[A-Z],[a-z])[}" = "xyes"] ; then
+       AC_DEFINE($1, 1, [Add the ]$1[ flag when building])
+       tcl_flags="$tcl_flags $1"
+    fi
+])
+
+AC_DEFUN([TEA_TCL_EARLY_FLAGS],[
+    AC_MSG_CHECKING([for required early compiler flags])
+    tcl_flags=""
+    TEA_TCL_EARLY_FLAG(_ISOC99_SOURCE,[#include <stdlib.h>],
+       [char *p = (char *)strtoll; char *q = (char *)strtoull;])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE64_SOURCE,[#include <sys/stat.h>],
+       [struct stat64 buf; int i = stat64("/", &buf);])
+    TEA_TCL_EARLY_FLAG(_LARGEFILE_SOURCE64,[#include <sys/stat.h>],
+       [char *p = (char *)open64;])
+    if test "x${tcl_flags}" = "x" ; then
+       AC_MSG_RESULT([none])
+    else
+       AC_MSG_RESULT([${tcl_flags}])
+    fi
+])
+
+#--------------------------------------------------------------------
+# TEA_TCL_64BIT_FLAGS
+#
+#      Check for what is defined in the way of 64-bit features.
+#
+# Arguments:
+#      None
+#
+# Results:
+#
+#      Might define the following vars:
+#              TCL_WIDE_INT_IS_LONG
+#              TCL_WIDE_INT_TYPE
+#              HAVE_STRUCT_DIRENT64, HAVE_DIR64
+#              HAVE_STRUCT_STAT64
+#              HAVE_TYPE_OFF64_T
+#
+#--------------------------------------------------------------------
+
+AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
+    AC_MSG_CHECKING([for 64-bit integer type])
+    AC_CACHE_VAL(tcl_cv_type_64bit,[
+       tcl_cv_type_64bit=none
+       # See if the compiler knows natively about __int64
+       AC_TRY_COMPILE(,[__int64 value = (__int64) 0;],
+           tcl_type_64bit=__int64, tcl_type_64bit="long long")
+       # See if we could use long anyway  Note that we substitute in the
+       # type that is our current guess for a 64-bit type inside this check
+       # program, so it should be modified only carefully...
+        AC_TRY_COMPILE(,[switch (0) {
+            case 1: case (sizeof(]${tcl_type_64bit}[)==sizeof(long)): ;
+        }],tcl_cv_type_64bit=${tcl_type_64bit})])
+    if test "${tcl_cv_type_64bit}" = none ; then
+       AC_DEFINE(TCL_WIDE_INT_IS_LONG, 1, [Do 'long' and 'long long' have the same size (64-bit)?])
+       AC_MSG_RESULT([yes])
+    elif test "${tcl_cv_type_64bit}" = "__int64" \
+               -a "${TEA_PLATFORM}" = "windows" ; then
+       # TEA specific: We actually want to use the default tcl.h checks in
+       # this case to handle both TCL_WIDE_INT_TYPE and TCL_LL_MODIFIER*
+       AC_MSG_RESULT([using Tcl header defaults])
+    else
+       AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
+           [What type should be used to define wide integers?])
+       AC_MSG_RESULT([${tcl_cv_type_64bit}])
+
+       # Now check for auxiliary declarations
+       AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 p;],
+               tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
+       if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for DIR64], tcl_cv_DIR64,[
+           AC_TRY_COMPILE([#include <sys/types.h>
+#include <dirent.h>],[struct dirent64 *p; DIR64 d = opendir64(".");
+            p = readdir64(d); rewinddir64(d); closedir64(d);],
+               tcl_cv_DIR64=yes,tcl_cv_DIR64=no)])
+       if test "x${tcl_cv_DIR64}" = "xyes" ; then
+           AC_DEFINE(HAVE_DIR64, 1, [Is 'DIR64' in <sys/types.h>?])
+       fi
+
+       AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
+           AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
+],
+               tcl_cv_struct_stat64=yes,tcl_cv_struct_stat64=no)])
+       if test "x${tcl_cv_struct_stat64}" = "xyes" ; then
+           AC_DEFINE(HAVE_STRUCT_STAT64, 1, [Is 'struct stat64' in <sys/stat.h>?])
+       fi
+
+       AC_CHECK_FUNCS(open64 lseek64)
+       AC_MSG_CHECKING([for off64_t])
+       AC_CACHE_VAL(tcl_cv_type_off64_t,[
+           AC_TRY_COMPILE([#include <sys/types.h>],[off64_t offset;
+],
+               tcl_cv_type_off64_t=yes,tcl_cv_type_off64_t=no)])
+       dnl Define HAVE_TYPE_OFF64_T only when the off64_t type and the
+       dnl functions lseek64 and open64 are defined.
+       if test "x${tcl_cv_type_off64_t}" = "xyes" && \
+               test "x${ac_cv_func_lseek64}" = "xyes" && \
+               test "x${ac_cv_func_open64}" = "xyes" ; then
+           AC_DEFINE(HAVE_TYPE_OFF64_T, 1, [Is off64_t in <sys/types.h>?])
+           AC_MSG_RESULT([yes])
+       else
+           AC_MSG_RESULT([no])
+       fi
+    fi
+])
+
+##
+## Here ends the standard Tcl configuration bits and starts the
+## TEA specific functions
+##
+
+#------------------------------------------------------------------------
+# TEA_INIT --
+#
+#      Init various Tcl Extension Architecture (TEA) variables.
+#      This should be the first called TEA_* macro.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              CYGPATH
+#              EXEEXT
+#      Defines only:
+#              TEA_VERSION
+#              TEA_INITED
+#              TEA_PLATFORM (windows or unix)
+#
+# "cygpath" is used on windows to generate native path names for include
+# files. These variables should only be used with the compiler and linker
+# since they generate native path names.
+#
+# EXEEXT
+#      Select the executable extension based on the host type.  This
+#      is a lightweight replacement for AC_EXEEXT that doesn't require
+#      a compiler.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INIT], [
+    TEA_VERSION="3.13"
+
+    AC_MSG_CHECKING([TEA configuration])
+    if test x"${PACKAGE_NAME}" = x ; then
+       AC_MSG_ERROR([
+The PACKAGE_NAME variable must be defined by your TEA configure.ac])
+    fi
+    AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
+
+    # If the user did not set CFLAGS, set it now to keep macros
+    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
+    if test "${CFLAGS+set}" != "set" ; then
+       CFLAGS=""
+    fi
+
+    case "`uname -s`" in
+       *win32*|*WIN32*|*MINGW32_*|*MINGW64_*|*MSYS_*)
+           AC_CHECK_PROG(CYGPATH, cygpath, cygpath -m, echo)
+           EXEEXT=".exe"
+           TEA_PLATFORM="windows"
+           ;;
+       *CYGWIN_*)
+           EXEEXT=".exe"
+           # CYGPATH and TEA_PLATFORM are determined later in LOAD_TCLCONFIG
+           ;;
+       *)
+           CYGPATH=echo
+           # Maybe we are cross-compiling....
+           case ${host_alias} in
+               *mingw32*)
+               EXEEXT=".exe"
+               TEA_PLATFORM="windows"
+               ;;
+           *)
+               EXEEXT=""
+               TEA_PLATFORM="unix"
+               ;;
+           esac
+           ;;
+    esac
+
+    # Check if exec_prefix is set. If not use fall back to prefix.
+    # Note when adjusted, so that TEA_PREFIX can correct for this.
+    # This is needed for recursive configures, since autoconf propagates
+    # $prefix, but not $exec_prefix (doh!).
+    if test x$exec_prefix = xNONE ; then
+       exec_prefix_default=yes
+       exec_prefix=$prefix
+    fi
+
+    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
+
+    AC_SUBST(EXEEXT)
+    AC_SUBST(CYGPATH)
+
+    # This package name must be replaced statically for AC_SUBST to work
+    AC_SUBST(PKG_LIB_FILE)
+    # Substitute STUB_LIB_FILE in case package creates a stub library too.
+    AC_SUBST(PKG_STUB_LIB_FILE)
+
+    # We AC_SUBST these here to ensure they are subst'ed,
+    # in case the user doesn't call TEA_ADD_...
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+    AC_SUBST(PKG_TCL_SOURCES)
+    AC_SUBST(PKG_HEADERS)
+    AC_SUBST(PKG_INCLUDES)
+    AC_SUBST(PKG_LIBS)
+    AC_SUBST(PKG_CFLAGS)
+
+    # Configure the installer.
+    TEA_INSTALLER
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_SOURCES
+#              PKG_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       case $i in
+           [\$]*)
+               # allow $-var names
+               PKG_SOURCES="$PKG_SOURCES $i"
+               PKG_OBJECTS="$PKG_OBJECTS $i"
+               ;;
+           *)
+               # check for existence - allows for generic/win/unix VPATH
+               # To add more dirs here (like 'src'), you have to update VPATH
+               # in Makefile.in as well
+               if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+                   -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+                   -a ! -f "${srcdir}/macosx/$i" \
+                   ; then
+                   AC_MSG_ERROR([could not find source file '$i'])
+               fi
+               PKG_SOURCES="$PKG_SOURCES $i"
+               # this assumes it is in a VPATH dir
+               i=`basename $i`
+               # handle user calling this before or after TEA_SETUP_COMPILER
+               if test x"${OBJEXT}" != x ; then
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+               else
+                   j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+               fi
+               PKG_OBJECTS="$PKG_OBJECTS $j"
+               ;;
+       esac
+    done
+    AC_SUBST(PKG_SOURCES)
+    AC_SUBST(PKG_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_STUB_SOURCES --
+#
+#      Specify one or more source files.  Users should check for
+#      the right platform before adding to their list.
+#      It is not important to specify the directory, as long as it is
+#      in the generic, win or unix subdirectory of $(srcdir).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_STUB_SOURCES
+#              PKG_STUB_OBJECTS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_STUB_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence - allows for generic/win/unix VPATH
+       if test ! -f "${srcdir}/$i" -a ! -f "${srcdir}/generic/$i" \
+           -a ! -f "${srcdir}/win/$i" -a ! -f "${srcdir}/unix/$i" \
+           -a ! -f "${srcdir}/macosx/$i" \
+           ; then
+           AC_MSG_ERROR([could not find stub source file '$i'])
+       fi
+       PKG_STUB_SOURCES="$PKG_STUB_SOURCES $i"
+       # this assumes it is in a VPATH dir
+       i=`basename $i`
+       # handle user calling this before or after TEA_SETUP_COMPILER
+       if test x"${OBJEXT}" != x ; then
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.${OBJEXT}"
+       else
+           j="`echo $i | sed -e 's/\.[[^.]]*$//'`.\${OBJEXT}"
+       fi
+       PKG_STUB_OBJECTS="$PKG_STUB_OBJECTS $j"
+    done
+    AC_SUBST(PKG_STUB_SOURCES)
+    AC_SUBST(PKG_STUB_OBJECTS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_TCL_SOURCES --
+#
+#      Specify one or more Tcl source files.  These should be platform
+#      independent runtime files.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_TCL_SOURCES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_TCL_SOURCES], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find tcl source file '${srcdir}/$i'])
+       fi
+       PKG_TCL_SOURCES="$PKG_TCL_SOURCES $i"
+    done
+    AC_SUBST(PKG_TCL_SOURCES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_HEADERS --
+#
+#      Specify one or more source headers.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_HEADERS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_HEADERS], [
+    vars="$@"
+    for i in $vars; do
+       # check for existence, be strict because it is installed
+       if test ! -f "${srcdir}/$i" ; then
+           AC_MSG_ERROR([could not find header file '${srcdir}/$i'])
+       fi
+       PKG_HEADERS="$PKG_HEADERS $i"
+    done
+    AC_SUBST(PKG_HEADERS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_INCLUDES --
+#
+#      Specify one or more include dirs.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_INCLUDES
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_INCLUDES], [
+    vars="$@"
+    for i in $vars; do
+       PKG_INCLUDES="$PKG_INCLUDES $i"
+    done
+    AC_SUBST(PKG_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_LIBS --
+#
+#      Specify one or more libraries.  Users should check for
+#      the right platform before adding to their list.  For Windows,
+#      libraries provided in "foo.lib" format will be converted to
+#      "-lfoo" when using GCC (mingw).
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_LIBS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_LIBS], [
+    vars="$@"
+    for i in $vars; do
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" = "yes" ; then
+           # Convert foo.lib to -lfoo for GCC.  No-op if not *.lib
+           i=`echo "$i" | sed -e 's/^\([[^-]].*\)\.[[lL]][[iI]][[bB]][$]/-l\1/'`
+       fi
+       PKG_LIBS="$PKG_LIBS $i"
+    done
+    AC_SUBST(PKG_LIBS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CFLAGS --
+#
+#      Specify one or more CFLAGS.  Users should check for
+#      the right platform before adding to their list.
+#
+# Arguments:
+#      one or more file names
+#
+# Results:
+#
+#      Defines and substs the following vars:
+#              PKG_CFLAGS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CFLAGS], [
+    PKG_CFLAGS="$PKG_CFLAGS $@"
+    AC_SUBST(PKG_CFLAGS)
+])
+
+#------------------------------------------------------------------------
+# TEA_ADD_CLEANFILES --
+#
+#      Specify one or more CLEANFILES.
+#
+# Arguments:
+#      one or more file names to clean target
+#
+# Results:
+#
+#      Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ADD_CLEANFILES], [
+    CLEANFILES="$CLEANFILES $@"
+])
+
+#------------------------------------------------------------------------
+# TEA_PREFIX --
+#
+#      Handle the --prefix=... option by defaulting to what Tcl gave
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      If --prefix or --exec-prefix was not specified, $prefix and
+#      $exec_prefix will be set to the values given to Tcl when it was
+#      configured.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_PREFIX], [
+    if test "${prefix}" = "NONE"; then
+       prefix_default=yes
+       if test x"${TCL_PREFIX}" != x; then
+           AC_MSG_NOTICE([--prefix defaulting to TCL_PREFIX ${TCL_PREFIX}])
+           prefix=${TCL_PREFIX}
+       else
+           AC_MSG_NOTICE([--prefix defaulting to /usr/local])
+           prefix=/usr/local
+       fi
+    fi
+    if test "${exec_prefix}" = "NONE" -a x"${prefix_default}" = x"yes" \
+       -o x"${exec_prefix_default}" = x"yes" ; then
+       if test x"${TCL_EXEC_PREFIX}" != x; then
+           AC_MSG_NOTICE([--exec-prefix defaulting to TCL_EXEC_PREFIX ${TCL_EXEC_PREFIX}])
+           exec_prefix=${TCL_EXEC_PREFIX}
+       else
+           AC_MSG_NOTICE([--exec-prefix defaulting to ${prefix}])
+           exec_prefix=$prefix
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER_CC --
+#
+#      Do compiler checks the way we want.  This is just a replacement
+#      for AC_PROG_CC in TEA configure.ac files to make them cleaner.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER_CC], [
+    # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
+    # in this macro, they need to go into TEA_SETUP_COMPILER instead.
+
+    AC_PROG_CC
+    AC_PROG_CPP
+
+    #--------------------------------------------------------------------
+    # Checks to see if the make program sets the $MAKE variable.
+    #--------------------------------------------------------------------
+
+    AC_PROG_MAKE_SET
+
+    #--------------------------------------------------------------------
+    # Find ranlib
+    #--------------------------------------------------------------------
+
+    AC_CHECK_TOOL(RANLIB, ranlib)
+
+    #--------------------------------------------------------------------
+    # Determines the correct binary file extension (.o, .obj, .exe etc.)
+    #--------------------------------------------------------------------
+
+    AC_OBJEXT
+    AC_EXEEXT
+])
+
+#------------------------------------------------------------------------
+# TEA_SETUP_COMPILER --
+#
+#      Do compiler checks that use the compiler.  This must go after
+#      TEA_SETUP_COMPILER_CC, which does the actual compiler check.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Sets up CC var and other standard bits we need to make executables.
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_SETUP_COMPILER], [
+    # Any macros that use the compiler (e.g. AC_TRY_COMPILE) have to go here.
+    AC_REQUIRE([TEA_SETUP_COMPILER_CC])
+
+    #------------------------------------------------------------------------
+    # If we're using GCC, see if the compiler understands -pipe. If so, use it.
+    # It makes compiling go faster.  (This is only a performance feature.)
+    #------------------------------------------------------------------------
+
+    if test -z "$no_pipe" -a -n "$GCC"; then
+       AC_CACHE_CHECK([if the compiler understands -pipe],
+           tcl_cv_cc_pipe, [
+           hold_cflags=$CFLAGS; CFLAGS="$CFLAGS -pipe"
+           AC_TRY_COMPILE(,, tcl_cv_cc_pipe=yes, tcl_cv_cc_pipe=no)
+           CFLAGS=$hold_cflags])
+       if test $tcl_cv_cc_pipe = yes; then
+           CFLAGS="$CFLAGS -pipe"
+       fi
+    fi
+
+    #--------------------------------------------------------------------
+    # Common compiler flag setup
+    #--------------------------------------------------------------------
+
+    AC_C_BIGENDIAN
+])
+
+#------------------------------------------------------------------------
+# TEA_MAKE_LIB --
+#
+#      Generate a line that can be used to build a shared/unshared library
+#      in a platform independent manner.
+#
+# Arguments:
+#      none
+#
+#      Requires:
+#
+# Results:
+#
+#      Defines the following vars:
+#      CFLAGS -        Done late here to note disturb other AC macros
+#       MAKE_LIB -      Command to execute to build the Tcl library;
+#                       differs depending on whether or not Tcl is being
+#                       compiled as a shared library.
+#      MAKE_SHARED_LIB Makefile rule for building a shared library
+#      MAKE_STATIC_LIB Makefile rule for building a static library
+#      MAKE_STUB_LIB   Makefile rule for building a stub library
+#      VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
+#      VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_MAKE_LIB], [
+    if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
+       MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       AC_EGREP_CPP([manifest needed], [
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+print("manifest needed")
+#endif
+       ], [
+       # Could do a CHECK_PROG for mt, but should always be with MSVC8+
+       VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
+       VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
+       MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
+       TEA_ADD_CLEANFILES([*.manifest])
+       ])
+       MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
+    else
+       MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
+       MAKE_SHARED_LIB="\${SHLIB_LD} \${LDFLAGS} \${LDFLAGS_DEFAULT} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
+       MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
+    fi
+
+    if test "${SHARED_BUILD}" = "1" ; then
+       MAKE_LIB="${MAKE_SHARED_LIB} "
+    else
+       MAKE_LIB="${MAKE_STATIC_LIB} "
+    fi
+
+    #--------------------------------------------------------------------
+    # Shared libraries and static libraries have different names.
+    # Use the double eval to make sure any variables in the suffix is
+    # substituted. (@@@ Might not be necessary anymore)
+    #--------------------------------------------------------------------
+
+    if test "${TEA_PLATFORM}" = "windows" ; then
+       if test "${SHARED_BUILD}" = "1" ; then
+           # We force the unresolved linking of symbols that are really in
+           # the private libraries of Tcl and Tk.
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
+           fi
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
+           if test "$GCC" = "yes"; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
+           fi
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+       else
+           eval eval "PKG_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+           if test "$GCC" = "yes"; then
+               PKG_LIB_FILE=lib${PKG_LIB_FILE}
+           fi
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+       if test "$GCC" = "yes"; then
+           PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
+       fi
+       # These aren't needed on Windows (either MSVC or gcc)
+       RANLIB=:
+       RANLIB_STUB=:
+    else
+       RANLIB_STUB="${RANLIB}"
+       if test "${SHARED_BUILD}" = "1" ; then
+           SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TCL_STUB_LIB_SPEC}"
+           if test x"${TK_BIN_DIR}" != x ; then
+               SHLIB_LD_LIBS="${SHLIB_LD_LIBS} ${TK_STUB_LIB_SPEC}"
+           fi
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
+           RANLIB=:
+       else
+           eval eval "PKG_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
+       fi
+       # Some packages build their own stubs libraries
+       eval eval "PKG_STUB_LIB_FILE=lib${PACKAGE_LIB_PREFIX}${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
+    fi
+
+    # These are escaped so that only CFLAGS is picked up at configure time.
+    # The other values will be substituted at make time.
+    CFLAGS="${CFLAGS} \${CFLAGS_DEFAULT} \${CFLAGS_WARNING}"
+    if test "${SHARED_BUILD}" = "1" ; then
+       CFLAGS="${CFLAGS} \${SHLIB_CFLAGS}"
+    fi
+
+    AC_SUBST(MAKE_LIB)
+    AC_SUBST(MAKE_SHARED_LIB)
+    AC_SUBST(MAKE_STATIC_LIB)
+    AC_SUBST(MAKE_STUB_LIB)
+    AC_SUBST(RANLIB_STUB)
+    AC_SUBST(VC_MANIFEST_EMBED_DLL)
+    AC_SUBST(VC_MANIFEST_EMBED_EXE)
+])
+
+#------------------------------------------------------------------------
+# TEA_LIB_SPEC --
+#
+#      Compute the name of an existing object library located in libdir
+#      from the given base name and produce the appropriate linker flags.
+#
+# Arguments:
+#      basename        The base name of the library without version
+#                      numbers, extensions, or "lib" prefixes.
+#      extra_dir       Extra directory in which to search for the
+#                      library.  This location is used first, then
+#                      $prefix/$exec-prefix, then some defaults.
+#
+# Requires:
+#      TEA_INIT and TEA_PREFIX must be called first.
+#
+# Results:
+#
+#      Defines the following vars:
+#              ${basename}_LIB_NAME    The computed library name.
+#              ${basename}_LIB_SPEC    The computed linker flags.
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LIB_SPEC], [
+    AC_MSG_CHECKING([for $1 library])
+
+    # Look in exec-prefix for the library (defined by TEA_PREFIX).
+
+    tea_lib_name_dir="${exec_prefix}/lib"
+
+    # Or in a user-specified location.
+
+    if test x"$2" != x ; then
+       tea_extra_lib_dir=$2
+    else
+       tea_extra_lib_dir=NONE
+    fi
+
+    for i in \
+           `ls -dr ${tea_extra_lib_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_extra_lib_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr ${tea_lib_name_dir}/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/lib64/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/lib64/lib$1[[0-9]]* 2>/dev/null ` \
+           `ls -dr /usr/local/lib/$1[[0-9]]*.lib 2>/dev/null ` \
+           `ls -dr /usr/local/lib/lib$1[[0-9]]* 2>/dev/null ` ; do
+       if test -f "$i" ; then
+           tea_lib_name_dir=`dirname $i`
+           $1_LIB_NAME=`basename $i`
+           $1_LIB_PATH_NAME=$i
+           break
+       fi
+    done
+
+    if test "${TEA_PLATFORM}" = "windows"; then
+       $1_LIB_SPEC=\"`${CYGPATH} ${$1_LIB_PATH_NAME} 2>/dev/null`\"
+    else
+       # Strip off the leading "lib" and trailing ".a" or ".so"
+
+       tea_lib_name_lib=`echo ${$1_LIB_NAME}|sed -e 's/^lib//' -e 's/\.[[^.]]*$//' -e 's/\.so.*//'`
+       $1_LIB_SPEC="-L${tea_lib_name_dir} -l${tea_lib_name_lib}"
+    fi
+
+    if test "x${$1_LIB_NAME}" = x ; then
+       AC_MSG_ERROR([not found])
+    else
+       AC_MSG_RESULT([${$1_LIB_SPEC}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TCL_HEADERS --
+#
+#      Locate the private Tcl include files
+#
+# Arguments:
+#
+#      Requires:
+#              TCL_SRC_DIR     Assumes that TEA_LOAD_TCLCONFIG has
+#                              already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TCL_TOP_DIR_NATIVE
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
+    # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
+    AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
+    AC_MSG_CHECKING([for Tcl private include files])
+
+    TCL_SRC_DIR_NATIVE=`${CYGPATH} ${TCL_SRC_DIR}`
+    TCL_TOP_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}\"
+
+    # Check to see if tcl<Plat>Port.h isn't already with the public headers
+    # Don't look for tclInt.h because that resides with tcl.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tclh}/tclWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tclh}/tclUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TCL_GENERIC_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/generic\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/win\"
+       else
+           TCL_PLATFORM_DIR_NATIVE=\"${TCL_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TCL_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TCL_INCLUDES="-I${TCL_GENERIC_DIR_NATIVE} -I${TCL_PLATFORM_DIR_NATIVE}"
+       if test "`uname -s`" = "Darwin"; then
+            # If Tcl was built as a framework, attempt to use
+            # the framework's Headers and PrivateHeaders directories
+            case ${TCL_DEFS} in
+               *TCL_FRAMEWORK*)
+                   if test -d "${TCL_BIN_DIR}/Headers" -a \
+                           -d "${TCL_BIN_DIR}/PrivateHeaders"; then
+                       TCL_INCLUDES="-I\"${TCL_BIN_DIR}/Headers\" -I\"${TCL_BIN_DIR}/PrivateHeaders\" ${TCL_INCLUDES}"
+                   else
+                       TCL_INCLUDES="${TCL_INCLUDES} ${TCL_INCLUDE_SPEC} `echo "${TCL_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                   fi
+                   ;;
+           esac
+           result="Using ${TCL_INCLUDES}"
+       else
+           if test ! -f "${TCL_SRC_DIR}/generic/tclInt.h" ; then
+               AC_MSG_ERROR([Cannot find private header tclInt.h in ${TCL_SRC_DIR}])
+           fi
+           result="Using srcdir found in tclConfig.sh: ${TCL_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TCL_TOP_DIR_NATIVE)
+
+    AC_SUBST(TCL_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TCL_HEADERS --
+#
+#      Locate the installed public Tcl header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tclinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TCL_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
+    AC_MSG_CHECKING([for Tcl public headers])
+
+    AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tclh, [
+       # Use the value from --with-tclinclude, if it was given
+
+       if test x"${with_tclinclude}" != x ; then
+           if test -f "${with_tclinclude}/tcl.h" ; then
+               ac_cv_c_tclh=${with_tclinclude}
+           else
+               AC_MSG_ERROR([${with_tclinclude} directory does not contain tcl.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tcl was built as a framework, attempt to use
+               # the framework's Headers directory
+               case ${TCL_DEFS} in
+                   *TCL_FRAMEWORK*)
+                       list="`ls -d ${TCL_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tcl is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TCL_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TCL_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TCL_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TCL_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tcl.h" ; then
+                   ac_cv_c_tclh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tclh}" = x ; then
+       AC_MSG_ERROR([tcl.h not found.  Please specify its location with --with-tclinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tclh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tclh}`
+
+    TCL_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TCL_INCLUDES)
+])
+
+#------------------------------------------------------------------------
+# TEA_PRIVATE_TK_HEADERS --
+#
+#      Locate the private Tk include files
+#
+# Arguments:
+#
+#      Requires:
+#              TK_SRC_DIR      Assumes that TEA_LOAD_TKCONFIG has
+#                               already been called.
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
+    # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
+    AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
+    AC_MSG_CHECKING([for Tk private include files])
+
+    TK_SRC_DIR_NATIVE=`${CYGPATH} ${TK_SRC_DIR}`
+    TK_TOP_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}\"
+
+    # Check to see if tk<Plat>Port.h isn't already with the public headers
+    # Don't look for tkInt.h because that resides with tk.h in the core
+    # sources, but the <plat>Port headers are in a different directory
+    if test "${TEA_PLATFORM}" = "windows" -a \
+       -f "${ac_cv_c_tkh}/tkWinPort.h"; then
+       result="private headers found with public headers"
+    elif test "${TEA_PLATFORM}" = "unix" -a \
+       -f "${ac_cv_c_tkh}/tkUnixPort.h"; then
+       result="private headers found with public headers"
+    else
+       TK_GENERIC_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/generic\"
+       TK_XLIB_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/xlib\"
+       if test "${TEA_PLATFORM}" = "windows"; then
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/win\"
+       else
+           TK_PLATFORM_DIR_NATIVE=\"${TK_SRC_DIR_NATIVE}/unix\"
+       fi
+       # Overwrite the previous TK_INCLUDES as this should capture both
+       # public and private headers in the same set.
+       # We want to ensure these are substituted so as not to require
+       # any *_NATIVE vars be defined in the Makefile
+       TK_INCLUDES="-I${TK_GENERIC_DIR_NATIVE} -I${TK_PLATFORM_DIR_NATIVE}"
+       # Detect and add ttk subdir
+       if test -d "${TK_SRC_DIR}/generic/ttk"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/generic/ttk\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_XLIB_DIR_NATIVE}\""
+       fi
+       if test "${TEA_WINDOWINGSYSTEM}" = "aqua"; then
+          TK_INCLUDES="${TK_INCLUDES} -I\"${TK_SRC_DIR_NATIVE}/macosx\""
+       fi
+       if test "`uname -s`" = "Darwin"; then
+           # If Tk was built as a framework, attempt to use
+           # the framework's Headers and PrivateHeaders directories
+           case ${TK_DEFS} in
+               *TK_FRAMEWORK*)
+                       if test -d "${TK_BIN_DIR}/Headers" -a \
+                               -d "${TK_BIN_DIR}/PrivateHeaders"; then
+                           TK_INCLUDES="-I\"${TK_BIN_DIR}/Headers\" -I\"${TK_BIN_DIR}/PrivateHeaders\" ${TK_INCLUDES}"
+                       else
+                           TK_INCLUDES="${TK_INCLUDES} ${TK_INCLUDE_SPEC} `echo "${TK_INCLUDE_SPEC}" | sed -e 's/Headers/PrivateHeaders/'`"
+                       fi
+                       ;;
+           esac
+           result="Using ${TK_INCLUDES}"
+       else
+           if test ! -f "${TK_SRC_DIR}/generic/tkInt.h" ; then
+              AC_MSG_ERROR([Cannot find private header tkInt.h in ${TK_SRC_DIR}])
+           fi
+           result="Using srcdir found in tkConfig.sh: ${TK_SRC_DIR}"
+       fi
+    fi
+
+    AC_SUBST(TK_TOP_DIR_NATIVE)
+    AC_SUBST(TK_XLIB_DIR_NATIVE)
+
+    AC_SUBST(TK_INCLUDES)
+    AC_MSG_RESULT([${result}])
+])
+
+#------------------------------------------------------------------------
+# TEA_PUBLIC_TK_HEADERS --
+#
+#      Locate the installed public Tk header files
+#
+# Arguments:
+#      None.
+#
+# Requires:
+#      CYGPATH must be set
+#
+# Results:
+#
+#      Adds a --with-tkinclude switch to configure.
+#      Result is cached.
+#
+#      Substitutes the following vars:
+#              TK_INCLUDES
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
+    AC_MSG_CHECKING([for Tk public headers])
+
+    AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
+
+    AC_CACHE_VAL(ac_cv_c_tkh, [
+       # Use the value from --with-tkinclude, if it was given
+
+       if test x"${with_tkinclude}" != x ; then
+           if test -f "${with_tkinclude}/tk.h" ; then
+               ac_cv_c_tkh=${with_tkinclude}
+           else
+               AC_MSG_ERROR([${with_tkinclude} directory does not contain tk.h])
+           fi
+       else
+           list=""
+           if test "`uname -s`" = "Darwin"; then
+               # If Tk was built as a framework, attempt to use
+               # the framework's Headers directory.
+               case ${TK_DEFS} in
+                   *TK_FRAMEWORK*)
+                       list="`ls -d ${TK_BIN_DIR}/Headers 2>/dev/null`"
+                       ;;
+               esac
+           fi
+
+           # Look in the source dir only if Tk is not installed,
+           # and in that situation, look there before installed locations.
+           if test -f "${TK_BIN_DIR}/Makefile" ; then
+               list="$list `ls -d ${TK_SRC_DIR}/generic 2>/dev/null`"
+           fi
+
+           # Check order: pkg --prefix location, Tk's --prefix location,
+           # relative to directory of tkConfig.sh, Tcl's --prefix location,
+           # relative to directory of tclConfig.sh.
+
+           eval "temp_includedir=${includedir}"
+           list="$list \
+               `ls -d ${temp_includedir}        2>/dev/null` \
+               `ls -d ${TK_PREFIX}/include      2>/dev/null` \
+               `ls -d ${TK_BIN_DIR}/../include  2>/dev/null` \
+               `ls -d ${TCL_PREFIX}/include     2>/dev/null` \
+               `ls -d ${TCL_BIN_DIR}/../include 2>/dev/null`"
+           if test "${TEA_PLATFORM}" != "windows" -o "$GCC" = "yes"; then
+               list="$list /usr/local/include /usr/include"
+               if test x"${TK_INCLUDE_SPEC}" != x ; then
+                   d=`echo "${TK_INCLUDE_SPEC}" | sed -e 's/^-I//'`
+                   list="$list `ls -d ${d} 2>/dev/null`"
+               fi
+           fi
+           for i in $list ; do
+               if test -f "$i/tk.h" ; then
+                   ac_cv_c_tkh=$i
+                   break
+               fi
+           done
+       fi
+    ])
+
+    # Print a message based on how we determined the include path
+
+    if test x"${ac_cv_c_tkh}" = x ; then
+       AC_MSG_ERROR([tk.h not found.  Please specify its location with --with-tkinclude])
+    else
+       AC_MSG_RESULT([${ac_cv_c_tkh}])
+    fi
+
+    # Convert to a native path and substitute into the output files.
+
+    INCLUDE_DIR_NATIVE=`${CYGPATH} ${ac_cv_c_tkh}`
+
+    TK_INCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+
+    AC_SUBST(TK_INCLUDES)
+
+    if test "${TEA_WINDOWINGSYSTEM}" != "x11"; then
+       # On Windows and Aqua, we need the X compat headers
+       AC_MSG_CHECKING([for X11 header files])
+       if test ! -r "${INCLUDE_DIR_NATIVE}/X11/Xlib.h"; then
+           INCLUDE_DIR_NATIVE="`${CYGPATH} ${TK_SRC_DIR}/xlib`"
+           TK_XINCLUDES=-I\"${INCLUDE_DIR_NATIVE}\"
+           AC_SUBST(TK_XINCLUDES)
+       fi
+       AC_MSG_RESULT([${INCLUDE_DIR_NATIVE}])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_PATH_CONFIG --
+#
+#      Locate the ${1}Config.sh file and perform a sanity check on
+#      the ${1} compile flags.  These are used by packages like
+#      [incr Tk] that load *Config.sh files from more than Tcl and Tk.
+#
+# Arguments:
+#      none
+#
+# Results:
+#
+#      Adds the following arguments to configure:
+#              --with-$1=...
+#
+#      Defines the following vars:
+#              $1_BIN_DIR      Full path to the directory containing
+#                              the $1Config.sh file
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_PATH_CONFIG], [
+    #
+    # Ok, lets find the $1 configuration
+    # First, look for one uninstalled.
+    # the alternative search directory is invoked by --with-$1
+    #
+
+    if test x"${no_$1}" = x ; then
+       # we reset no_$1 in case something fails here
+       no_$1=true
+       AC_ARG_WITH($1, [  --with-$1              directory containing $1 configuration ($1Config.sh)], with_$1config=${withval})
+       AC_MSG_CHECKING([for $1 configuration])
+       AC_CACHE_VAL(ac_cv_c_$1config,[
+
+           # First check to see if --with-$1 was specified.
+           if test x"${with_$1config}" != x ; then
+               case ${with_$1config} in
+                   */$1Config.sh )
+                       if test -f ${with_$1config}; then
+                           AC_MSG_WARN([--with-$1 argument should refer to directory containing $1Config.sh, not to $1Config.sh itself])
+                           with_$1config=`echo ${with_$1config} | sed 's!/$1Config\.sh$!!'`
+                       fi;;
+               esac
+               if test -f "${with_$1config}/$1Config.sh" ; then
+                   ac_cv_c_$1config=`(cd ${with_$1config}; pwd)`
+               else
+                   AC_MSG_ERROR([${with_$1config} directory doesn't contain $1Config.sh])
+               fi
+           fi
+
+           # then check for a private $1 installation
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in \
+                       ../$1 \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../$1 \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ../../../$1 \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ../../../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ${srcdir}/../$1 \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]*.[[0-9]]* 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]][[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]] 2>/dev/null` \
+                       `ls -dr ${srcdir}/../$1*[[0-9]].[[0-9]]* 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+                   if test -f "$i/unix/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i/unix; pwd)`
+                       break
+                   fi
+               done
+           fi
+
+           # check in a few common install locations
+           if test x"${ac_cv_c_$1config}" = x ; then
+               for i in `ls -d ${libdir} 2>/dev/null` \
+                       `ls -d ${exec_prefix}/lib 2>/dev/null` \
+                       `ls -d ${prefix}/lib 2>/dev/null` \
+                       `ls -d /usr/local/lib 2>/dev/null` \
+                       `ls -d /usr/contrib/lib 2>/dev/null` \
+                       `ls -d /usr/pkg/lib 2>/dev/null` \
+                       `ls -d /usr/lib 2>/dev/null` \
+                       `ls -d /usr/lib64 2>/dev/null` \
+                       ; do
+                   if test -f "$i/$1Config.sh" ; then
+                       ac_cv_c_$1config=`(cd $i; pwd)`
+                       break
+                   fi
+               done
+           fi
+       ])
+
+       if test x"${ac_cv_c_$1config}" = x ; then
+           $1_BIN_DIR="# no $1 configs found"
+           AC_MSG_WARN([Cannot find $1 configuration definitions])
+           exit 0
+       else
+           no_$1=
+           $1_BIN_DIR=${ac_cv_c_$1config}
+           AC_MSG_RESULT([found $$1_BIN_DIR/$1Config.sh])
+       fi
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG --
+#
+#      Load the $1Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1_BIN_DIR
+#
+# Results:
+#
+#      Substitutes the following vars:
+#              $1_SRC_DIR
+#              $1_LIB_FILE
+#              $1_LIB_SPEC
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_LOAD_CONFIG], [
+    AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
+
+    if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
+        AC_MSG_RESULT([loading])
+       . "${$1_BIN_DIR}/$1Config.sh"
+    else
+        AC_MSG_RESULT([file not found])
+    fi
+
+    #
+    # If the $1_BIN_DIR is the build directory (not the install directory),
+    # then set the common variable name to the value of the build variables.
+    # For example, the variable $1_LIB_SPEC will be set to the value
+    # of $1_BUILD_LIB_SPEC. An extension should make use of $1_LIB_SPEC
+    # instead of $1_BUILD_LIB_SPEC since it will work with both an
+    # installed and uninstalled version of Tcl.
+    #
+
+    if test -f "${$1_BIN_DIR}/Makefile" ; then
+       AC_MSG_WARN([Found Makefile - using build library specs for $1])
+        $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
+        $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
+        $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
+        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
+        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
+    fi
+
+    AC_SUBST($1_VERSION)
+    AC_SUBST($1_BIN_DIR)
+    AC_SUBST($1_SRC_DIR)
+
+    AC_SUBST($1_LIB_FILE)
+    AC_SUBST($1_LIB_SPEC)
+
+    AC_SUBST($1_STUB_LIB_FILE)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    # Allow the caller to prevent this auto-check by specifying any 2nd arg
+    AS_IF([test "x$2" = x], [
+       # Check both upper and lower-case variants
+       # If a dev wanted non-stubs libs, this function could take an option
+       # to not use _STUB in the paths below
+       AS_IF([test "x${$1_STUB_LIB_SPEC}" = x],
+           [TEA_LOAD_CONFIG_LIB(translit($1,[a-z],[A-Z])_STUB)],
+           [TEA_LOAD_CONFIG_LIB($1_STUB)])
+    ])
+])
+
+#------------------------------------------------------------------------
+# TEA_LOAD_CONFIG_LIB --
+#
+#      Helper function to load correct library from another extension's
+#      ${PACKAGE}Config.sh.
+#
+# Results:
+#      Adds to LIBS the appropriate extension library
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
+    AC_MSG_CHECKING([For $1 library for LIBS])
+    # This simplifies the use of stub libraries by automatically adding
+    # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
+    # but this is called before CONFIG_CFLAGS.  More importantly, this adds
+    # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
+    if test "x${$1_LIB_SPEC}" != "x" ; then
+       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes" ; then
+           TEA_ADD_LIBS([\"`${CYGPATH} ${$1_LIB_PATH}`\"])
+           AC_MSG_RESULT([using $1_LIB_PATH ${$1_LIB_PATH}])
+       else
+           TEA_ADD_LIBS([${$1_LIB_SPEC}])
+           AC_MSG_RESULT([using $1_LIB_SPEC ${$1_LIB_SPEC}])
+       fi
+    else
+       AC_MSG_RESULT([file not found])
+    fi
+])
+
+#------------------------------------------------------------------------
+# TEA_EXPORT_CONFIG --
+#
+#      Define the data to insert into the ${PACKAGE}Config.sh file
+#
+# Arguments:
+#
+#      Requires the following vars to be set:
+#              $1
+#
+# Results:
+#      Substitutes the following vars:
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_EXPORT_CONFIG], [
+    #--------------------------------------------------------------------
+    # These are for $1Config.sh
+    #--------------------------------------------------------------------
+
+    # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
+    eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
+    if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
+       eval $1_LIB_FLAG="-l$1${PACKAGE_VERSION}"
+       eval $1_STUB_LIB_FLAG="-l$1stub${PACKAGE_VERSION}"
+    else
+       eval $1_LIB_FLAG="-l$1`echo ${PACKAGE_VERSION} | tr -d .`"
+       eval $1_STUB_LIB_FLAG="-l$1stub`echo ${PACKAGE_VERSION} | tr -d .`"
+    fi
+    $1_BUILD_LIB_SPEC="-L`$CYGPATH $(pwd)` ${$1_LIB_FLAG}"
+    $1_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` ${$1_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_SPEC="-L`$CYGPATH $(pwd)` [$]{$1_STUB_LIB_FLAG}"
+    $1_STUB_LIB_SPEC="-L`$CYGPATH ${pkglibdir}` [$]{$1_STUB_LIB_FLAG}"
+    $1_BUILD_STUB_LIB_PATH="`$CYGPATH $(pwd)`/[$]{PKG_STUB_LIB_FILE}"
+    $1_STUB_LIB_PATH="`$CYGPATH ${pkglibdir}`/[$]{PKG_STUB_LIB_FILE}"
+
+    AC_SUBST($1_BUILD_LIB_SPEC)
+    AC_SUBST($1_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_SPEC)
+    AC_SUBST($1_STUB_LIB_SPEC)
+    AC_SUBST($1_BUILD_STUB_LIB_PATH)
+    AC_SUBST($1_STUB_LIB_PATH)
+
+    AC_SUBST(MAJOR_VERSION)
+    AC_SUBST(MINOR_VERSION)
+    AC_SUBST(PATCHLEVEL)
+])
+
+
+#------------------------------------------------------------------------
+# TEA_INSTALLER --
+#
+#      Configure the installer.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              INSTALL
+#              INSTALL_DATA_DIR
+#              INSTALL_DATA
+#              INSTALL_PROGRAM
+#              INSTALL_SCRIPT
+#              INSTALL_LIBRARY
+#------------------------------------------------------------------------
+
+AC_DEFUN([TEA_INSTALLER], [
+    INSTALL='$(SHELL) $(srcdir)/tclconfig/install-sh -c'
+    INSTALL_DATA_DIR='${INSTALL} -d -m 755'
+    INSTALL_DATA='${INSTALL} -m 644'
+    INSTALL_PROGRAM='${INSTALL} -m 755'
+    INSTALL_SCRIPT='${INSTALL} -m 755'
+
+    TEA_CONFIG_SYSTEM
+    case $system in
+       HP-UX-*) INSTALL_LIBRARY='${INSTALL} -m 755' ;;
+             *) INSTALL_LIBRARY='${INSTALL} -m 644' ;;
+    esac
+
+    AC_SUBST(INSTALL)
+    AC_SUBST(INSTALL_DATA_DIR)
+    AC_SUBST(INSTALL_DATA)
+    AC_SUBST(INSTALL_PROGRAM)
+    AC_SUBST(INSTALL_SCRIPT)
+    AC_SUBST(INSTALL_LIBRARY)
+])
+
+###
+# Tip 430 - ZipFS Modifications
+###
+#------------------------------------------------------------------------
+# SC_ZIPFS_SUPPORT
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              TCL_ZIP_FILE
+#              TCL_ZIPFS_SUPPORT
+#              TCL_ZIPFS_FLAG
+#              ZIP_PROG
+#------------------------------------------------------------------------
+
+#------------------------------------------------------------------------
+# SC_PROG_ZIP
+#      Locate a zip encoder installed on the system path, or none.
+#
+# Arguments:
+#      none
+#
+# Results:
+#      Substitutes the following vars:
+#              ZIP_PROG
+#       ZIP_PROG_OPTIONS
+#       ZIP_PROG_VFSSEARCH
+#       ZIP_INSTALL_OBJS
+#------------------------------------------------------------------------
+AC_DEFUN([TEA_ZIPFS_SUPPORT], [
+    AC_MSG_CHECKING([for zipfs support])
+    ZIP_PROG=""
+    ZIP_PROG_OPTIONS=""
+    ZIP_PROG_VFSSEARCH=""
+    INSTALL_MSGS=""
+    # If our native tclsh processes the "install" command line option
+    # we can use it to mint zip files
+    AS_IF([$TCLSH_PROG install],[
+      ZIP_PROG=${TCLSH_PROG}
+      ZIP_PROG_OPTIONS="install mkzip"
+      ZIP_PROG_VFSSEARCH="."
+      AC_MSG_RESULT([Can use Native Tclsh for Zip encoding])
+    ])
+    if test "x$ZIP_PROG" = "x" ; then
+        AC_CACHE_VAL(ac_cv_path_zip, [
+        search_path=`echo ${PATH} | sed -e 's/:/ /g'`
+        for dir in $search_path ; do
+            for j in `ls -r $dir/zip 2> /dev/null` \
+                `ls -r $dir/zip 2> /dev/null` ; do
+            if test x"$ac_cv_path_zip" = x ; then
+                if test -f "$j" ; then
+                ac_cv_path_zip=$j
+                break
+                fi
+            fi
+            done
+        done
+        ])
+        if test -f "$ac_cv_path_zip" ; then
+            ZIP_PROG="$ac_cv_path_zip "
+            AC_MSG_RESULT([$ZIP_PROG])
+            ZIP_PROG_OPTIONS="-rq"
+            ZIP_PROG_VFSSEARCH="."
+            AC_MSG_RESULT([Found INFO Zip in environment])
+            # Use standard arguments for zip
+        fi
+    fi
+    if test "x$ZIP_PROG" = "x" ; then
+           # It is not an error if an installed version of Zip can't be located.
+        ZIP_PROG=""
+        ZIP_PROG_OPTIONS=""
+        ZIP_PROG_VFSSEARCH=""
+        TCL_ZIPFS_SUPPORT=0
+        TCL_ZIPFS_FLAG=
+    else
+        # ZIPFS Support
+       eval "TCL_ZIP_FILE=\"${TCL_ZIP_FILE}\""
+       if test ${TCL_ZIP_FILE} = "" ; then
+          TCL_ZIPFS_SUPPORT=0
+          TCL_ZIPFS_FLAG=
+          INSTALL_LIBRARIES=install-libraries
+          INSTALL_MSGS=install-msgs
+       else
+           if test ${SHARED_BUILD} = 1 ; then
+              TCL_ZIPFS_SUPPORT=1
+              INSTALL_LIBRARIES=install-libraries-zipfs-shared
+           else
+              TCL_ZIPFS_SUPPORT=2
+              INSTALL_LIBRARIES=install-libraries-zipfs-static
+           fi
+          TCL_ZIPFS_FLAG=-DTCL_ZIPFS_SUPPORT
+       fi
+    fi
+
+    AC_SUBST(TCL_ZIP_FILE)
+    AC_SUBST(TCL_ZIPFS_SUPPORT)
+    AC_SUBST(TCL_ZIPFS_FLAG)
+    AC_SUBST(ZIP_PROG)
+    AC_SUBST(ZIP_PROG_OPTIONS)
+    AC_SUBST(ZIP_PROG_VFSSEARCH)
+    AC_SUBST(INSTALL_LIBRARIES)
+    AC_SUBST(INSTALL_MSGS)
+])
+
+# Local Variables:
+# mode: autoconf
+# End:
similarity index 89%
rename from pkgs/thread2.8.5/win/makefile.vc
rename to pkgs/thread2.8.6/win/makefile.vc
index 1b39eb7..dada887 100644 (file)
@@ -8,7 +8,7 @@
 #   nmake /f makefile.vc INSTALLDIR=c:\tcl install\r
 #\r
 # For other build options (debug, static etc.),\r
-# See TIP 477 (https://core.tcl.tk/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl.tk/tips/doc/main/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # In addition to the command line macros described there the following\r
@@ -50,6 +50,10 @@ PRJ_OBJS = \
 install:    default-install-docs-html\r
 pkgindex:   default-pkgindex-tea\r
 \r
+$(ROOT)\manifest.uuid:\r
+   copy $(WIN_DIR)\gitmanifest.in $(ROOT)\manifest.uuid\r
+   git rev-parse HEAD >>$(ROOT)\manifest.uuid\r
+\r
 # Explicit dependency rules\r
 $(GENERICDIR)\psGdbm.c: $(GENERICDIR)\psGdbm.h\r
 $(GENERICDIR)\psLmdb.c: $(GENERICDIR)\psLmdb.h\r
similarity index 78%
rename from pkgs/thread2.8.5/win/pkg.vc
rename to pkgs/thread2.8.6/win/pkg.vc
index 432fd9c..6d8d2d5 100644 (file)
@@ -3,4 +3,4 @@
 \r
 PACKAGE_MAJOR  = 2\r
 PACKAGE_MINOR  = 8\r
-PACKAGE_VERSION        = "2.8.5"\r
+PACKAGE_VERSION        = "2.8.6"\r
diff --git a/pkgs/thread2.8.6/win/rules-ext.vc b/pkgs/thread2.8.6/win/rules-ext.vc
new file mode 100644 (file)
index 0000000..6da5689
--- /dev/null
@@ -0,0 +1,118 @@
+# This file should only be included in makefiles for Tcl extensions,\r
+# NOT in the makefile for Tcl itself.\r
+\r
+!ifndef _RULES_EXT_VC\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+!if "$(PROJECT)" == "tcl"\r
+!error The rules-ext.vc file is not intended for Tcl itself.\r
+!endif\r
+\r
+# We extract version numbers using the nmakehlp program. For now use\r
+# the local copy of nmakehlp. Once we locate Tcl, we will use that\r
+# one if it is newer.\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
+!endif\r
+\r
+# First locate the Tcl directory that we are working with.\r
+!if "$(TCLDIR)" != ""\r
+\r
+_RULESDIR = $(TCLDIR:/=\)\r
+\r
+!else\r
+\r
+# If an installation path is specified, that is also the Tcl directory.\r
+# Also Tk never builds against an installed Tcl, it needs Tcl sources\r
+!if defined(INSTALLDIR) && "$(PROJECT)" != "tk"\r
+_RULESDIR=$(INSTALLDIR:/=\)\r
+!else\r
+# Locate Tcl sources\r
+!if [echo _RULESDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+_RULESDIR = ..\..\tcl\r
+!else\r
+!include nmakehlp.out\r
+!endif\r
+\r
+!endif # defined(INSTALLDIR)....\r
+\r
+!endif # ifndef TCLDIR\r
+\r
+# Now look for the targets.vc file under the Tcl root. Note we check this\r
+# file and not rules.vc because the latter also exists on older systems.\r
+!if exist("$(_RULESDIR)\lib\nmake\targets.vc") # Building against installed Tcl\r
+_RULESDIR = $(_RULESDIR)\lib\nmake\r
+!elseif exist("$(_RULESDIR)\win\targets.vc")   # Building against Tcl sources\r
+_RULESDIR = $(_RULESDIR)\win\r
+!else\r
+# If we have not located Tcl's targets file, most likely we are compiling\r
+# against an older version of Tcl and so must use our own support files.\r
+_RULESDIR = .\r
+!endif\r
+\r
+!if "$(_RULESDIR)" != "."\r
+# Potentially using Tcl's support files. If this extension has its own\r
+# nmake support files, need to compare the versions and pick newer.\r
+\r
+!if exist("rules.vc") # The extension has its own copy\r
+\r
+!if [echo TCL_RULES_MAJOR = \> versions.vc] \\r
+   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
+!endif\r
+!if [echo TCL_RULES_MINOR = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_RULESDIR)\rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
+!endif\r
+\r
+!if [echo OUR_RULES_MAJOR = \>> versions.vc] \\r
+   && [nmakehlp -V "rules.vc" RULES_VERSION_MAJOR >> versions.vc]\r
+!endif\r
+!if [echo OUR_RULES_MINOR = \>> versions.vc] \\r
+   && [nmakehlp -V "rules.vc" RULES_VERSION_MINOR >> versions.vc]\r
+!endif\r
+!include versions.vc\r
+# We have a newer version of the support files, use them\r
+!if ($(TCL_RULES_MAJOR) != $(OUR_RULES_MAJOR)) || ($(TCL_RULES_MINOR) < $(OUR_RULES_MINOR))\r
+_RULESDIR = .\r
+!endif\r
+\r
+!endif # if exist("rules.vc")\r
+\r
+!endif # if $(_RULESDIR) != "."\r
+\r
+# Let rules.vc know what copy of nmakehlp.c to use.\r
+NMAKEHLPC = $(_RULESDIR)\nmakehlp.c\r
+\r
+# Get rid of our internal defines before calling rules.vc\r
+!undef TCL_RULES_MAJOR\r
+!undef TCL_RULES_MINOR\r
+!undef OUR_RULES_MAJOR\r
+!undef OUR_RULES_MINOR\r
+\r
+!if exist("$(_RULESDIR)\rules.vc")\r
+!message *** Using $(_RULESDIR)\rules.vc\r
+!include "$(_RULESDIR)\rules.vc"\r
+!else\r
+!error *** Could not locate rules.vc in $(_RULESDIR)\r
+!endif\r
+\r
+!endif # _RULES_EXT_VC
\ No newline at end of file
diff --git a/pkgs/thread2.8.6/win/rules.vc b/pkgs/thread2.8.6/win/rules.vc
new file mode 100644 (file)
index 0000000..13e3879
--- /dev/null
@@ -0,0 +1,1852 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# rules.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file does all the hard work in terms of parsing build options,\r
+# compiler switches, defining common targets and macros. The Tcl makefile\r
+# directly includes this. Extensions include it via "rules-ext.vc".\r
+#\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
+# detailed documentation.\r
+#\r
+# See the file "license.terms" for information on usage and redistribution\r
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.\r
+#\r
+# Copyright (c) 2001-2003 David Gravereaux.\r
+# Copyright (c) 2003-2008 Patrick Thoyts\r
+# Copyright (c) 2017      Ashok P. Nadkarni\r
+#------------------------------------------------------------------------------\r
+\r
+!ifndef _RULES_VC\r
+_RULES_VC = 1\r
+\r
+# The following macros define the version of the rules.vc nmake build system\r
+# For modifications that are not backward-compatible, you *must* change\r
+# the major version.\r
+RULES_VERSION_MAJOR = 1\r
+RULES_VERSION_MINOR = 8\r
+\r
+# The PROJECT macro must be defined by parent makefile.\r
+!if "$(PROJECT)" == ""\r
+!error *** Error: Macro PROJECT not defined! Please define it before including rules.vc\r
+!endif\r
+\r
+!if "$(PRJ_PACKAGE_TCLNAME)" == ""\r
+PRJ_PACKAGE_TCLNAME = $(PROJECT)\r
+!endif\r
+\r
+# Also special case Tcl and Tk to save some typing later\r
+DOING_TCL = 0\r
+DOING_TK  = 0\r
+!if "$(PROJECT)" == "tcl"\r
+DOING_TCL = 1\r
+!elseif "$(PROJECT)" == "tk"\r
+DOING_TK = 1\r
+!endif\r
+\r
+!ifndef NEED_TK\r
+# Backwards compatibility\r
+!ifdef PROJECT_REQUIRES_TK\r
+NEED_TK = $(PROJECT_REQUIRES_TK)\r
+!else\r
+NEED_TK = 0\r
+!endif\r
+!endif\r
+\r
+!ifndef NEED_TCL_SOURCE\r
+NEED_TCL_SOURCE = 0\r
+!endif\r
+\r
+!ifdef NEED_TK_SOURCE\r
+!if $(NEED_TK_SOURCE)\r
+NEED_TK = 1\r
+!endif\r
+!else\r
+NEED_TK_SOURCE = 0\r
+!endif\r
+\r
+################################################################\r
+# Nmake is a pretty weak environment in syntax and capabilities\r
+# so this file is necessarily verbose. It's broken down into\r
+# the following parts.\r
+#\r
+# 0. Sanity check that compiler environment is set up and initialize\r
+#    any built-in settings from the parent makefile\r
+# 1. First define the external tools used for compiling, copying etc.\r
+#    as this is independent of everything else.\r
+# 2. Figure out our build structure in terms of the directory, whether\r
+#    we are building Tcl or an extension, etc.\r
+# 3. Determine the compiler and linker versions\r
+# 4. Build the nmakehlp helper application\r
+# 5. Determine the supported compiler options and features\r
+# 6. Parse the OPTS macro value for user-specified build configuration\r
+# 7. Parse the STATS macro value for statistics instrumentation\r
+# 8. Parse the CHECKS macro for additional compilation checks\r
+# 9. Extract Tcl, and possibly Tk, version numbers from the headers\r
+# 10. Based on this selected configuration, construct the output\r
+#     directory and file paths\r
+# 11. Construct the paths where the package is to be installed\r
+# 12. Set up the actual options passed to compiler and linker based\r
+#     on the information gathered above.\r
+# 13. Define some standard build targets and implicit rules. These may\r
+#     be optionally disabled by the parent makefile.\r
+# 14. (For extensions only.) Compare the configuration of the target\r
+#     Tcl and the extensions and warn against discrepancies.\r
+#\r
+# One final note about the macro names used. They are as they are\r
+# for historical reasons. We would like legacy extensions to\r
+# continue to work with this make include file so be wary of\r
+# changing them for consistency or clarity.\r
+\r
+# 0. Sanity check compiler environment\r
+\r
+# Check to see we are configured to build with MSVC (MSDEVDIR, MSVCDIR or\r
+# VCINSTALLDIR) or with the MS Platform SDK (MSSDK or WindowsSDKDir)\r
+\r
+!if !defined(MSDEVDIR) && !defined(MSVCDIR) && !defined(VCINSTALLDIR) && !defined(MSSDK) && !defined(WINDOWSSDKDIR)\r
+MSG = ^\r
+Visual C++ compiler environment not initialized.\r
+!error $(MSG)\r
+!endif\r
+\r
+# We need to run from the directory the parent makefile is located in.\r
+# nmake does not tell us what makefile was used to invoke it so parent\r
+# makefile has to set the MAKEFILEVC macro or we just make a guess and\r
+# warn if we think that is not the case.\r
+!if "$(MAKEFILEVC)" == ""\r
+\r
+!if exist("$(PROJECT).vc")\r
+MAKEFILEVC = $(PROJECT).vc\r
+!elseif exist("makefile.vc")\r
+MAKEFILEVC = makefile.vc\r
+!endif\r
+!endif # "$(MAKEFILEVC)" == ""\r
+\r
+!if !exist("$(MAKEFILEVC)")\r
+MSG = ^\r
+You must run nmake from the directory containing the project makefile.^\r
+If you are doing that and getting this message, set the MAKEFILEVC^\r
+macro to the name of the project makefile.\r
+!message WARNING: $(MSG)\r
+!endif\r
+\r
+\r
+################################################################\r
+# 1. Define external programs being used\r
+\r
+#----------------------------------------------------------\r
+# Set the proper copy method to avoid overwrite questions\r
+# to the user when copying files and selecting the right\r
+# "delete all" method.\r
+#----------------------------------------------------------\r
+\r
+RMDIR  = rmdir /S /Q\r
+CPY    = xcopy /i /y >NUL\r
+CPYDIR  = xcopy /e /i /y >NUL\r
+COPY   = copy /y >NUL\r
+MKDIR   = mkdir\r
+\r
+######################################################################\r
+# 2. Figure out our build environment in terms of what we're building.\r
+#\r
+# (a) Tcl itself\r
+# (b) Tk\r
+# (c) a Tcl extension using libraries/includes from an *installed* Tcl\r
+# (d) a Tcl extension using libraries/includes from Tcl source directory\r
+#\r
+# This last is needed because some extensions still need\r
+# some Tcl interfaces that are not publicly exposed.\r
+#\r
+# The fragment will set the following macros:\r
+# ROOT - root of this module sources\r
+# COMPATDIR - source directory that holds compatibility sources\r
+# DOCDIR - source directory containing documentation files\r
+# GENERICDIR - platform-independent source directory\r
+# WIN_DIR - Windows-specific source directory\r
+# TESTDIR - directory containing test files\r
+# TOOLSDIR - directory containing build tools\r
+# _TCLDIR - root of the Tcl installation OR the Tcl sources. Not set\r
+#    when building Tcl itself.\r
+# _INSTALLDIR - native form of the installation path. For Tcl\r
+#    this will be the root of the Tcl installation. For extensions\r
+#    this will be the lib directory under the root.\r
+# TCLINSTALL  - set to 1 if _TCLDIR refers to\r
+#    headers and libraries from an installed Tcl, and 0 if built against\r
+#    Tcl sources. Not set when building Tcl itself. Yes, not very well\r
+#    named.\r
+# _TCL_H - native path to the tcl.h file\r
+#\r
+# If Tk is involved, also sets the following\r
+# _TKDIR - native form Tk installation OR Tk source. Not set if building\r
+#    Tk itself.\r
+# TKINSTALL - set 1 if _TKDIR refers to installed Tk and 0 if Tk sources\r
+# _TK_H - native path to the tk.h file\r
+\r
+# Root directory for sources and assumed subdirectories\r
+ROOT = $(MAKEDIR)\..\r
+# The following paths CANNOT have spaces in them as they appear on the\r
+# left side of implicit rules.\r
+!ifndef COMPATDIR\r
+COMPATDIR      = $(ROOT)\compat\r
+!endif\r
+!ifndef DOCDIR\r
+DOCDIR         = $(ROOT)\doc\r
+!endif\r
+!ifndef GENERICDIR\r
+GENERICDIR     = $(ROOT)\generic\r
+!endif\r
+!ifndef TOOLSDIR\r
+TOOLSDIR       = $(ROOT)\tools\r
+!endif\r
+!ifndef TESTDIR\r
+TESTDIR        = $(ROOT)\tests\r
+!endif\r
+!ifndef LIBDIR\r
+!if exist("$(ROOT)\library")\r
+LIBDIR          = $(ROOT)\library\r
+!else\r
+LIBDIR          = $(ROOT)\lib\r
+!endif\r
+!endif\r
+!ifndef DEMODIR\r
+!if exist("$(LIBDIR)\demos")\r
+DEMODIR                = $(LIBDIR)\demos\r
+!else\r
+DEMODIR                = $(ROOT)\demos\r
+!endif\r
+!endif # ifndef DEMODIR\r
+# Do NOT use WINDIR because it is Windows internal environment\r
+# variable to point to c:\windows!\r
+WIN_DIR                = $(ROOT)\win\r
+\r
+!ifndef RCDIR\r
+!if exist("$(WIN_DIR)\rc")\r
+RCDIR           = $(WIN_DIR)\rc\r
+!else\r
+RCDIR           = $(WIN_DIR)\r
+!endif\r
+!endif\r
+RCDIR = $(RCDIR:/=\)\r
+\r
+# The target directory where the built packages and binaries will be installed.\r
+# INSTALLDIR is the (optional) path specified by the user.\r
+# _INSTALLDIR is INSTALLDIR using the backslash separator syntax\r
+!ifdef INSTALLDIR\r
+### Fix the path separators.\r
+_INSTALLDIR    = $(INSTALLDIR:/=\)\r
+!else\r
+### Assume the normal default.\r
+_INSTALLDIR    = $(HOMEDRIVE)\Tcl\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+\r
+# BEGIN Case 2(a) - Building Tcl itself\r
+\r
+# Only need to define _TCL_H\r
+_TCL_H = ..\generic\tcl.h\r
+\r
+# END Case 2(a) - Building Tcl itself\r
+\r
+!elseif $(DOING_TK)\r
+\r
+# BEGIN Case 2(b) - Building Tk\r
+\r
+TCLINSTALL = 0 # Tk always builds against Tcl source, not an installed Tcl\r
+!if "$(TCLDIR)" == ""\r
+!if [echo TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+!endif # TCLDIR == ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+_TCL_H  = $(_TCLDIR)\generic\tcl.h\r
+!if !exist("$(_TCL_H)")\r
+!error Could not locate tcl.h. Please set the TCLDIR macro to point to the Tcl *source* directory.\r
+!endif\r
+\r
+_TK_H = ..\generic\tk.h\r
+\r
+# END Case 2(b) - Building Tk\r
+\r
+!else\r
+\r
+# BEGIN Case 2(c) or (d) - Building an extension other than Tk\r
+\r
+# If command line has specified Tcl location through TCLDIR, use it\r
+# else default to the INSTALLDIR setting\r
+!if "$(TCLDIR)" != ""\r
+\r
+_TCLDIR        = $(TCLDIR:/=\)\r
+!if exist("$(_TCLDIR)\include\tcl.h") # Case 2(c) with TCLDIR defined\r
+TCLINSTALL     = 1\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+!elseif exist("$(_TCLDIR)\generic\tcl.h") # Case 2(d) with TCLDIR defined\r
+TCLINSTALL     = 0\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+!endif\r
+\r
+!else  #  # Case 2(c) for extensions with TCLDIR undefined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tcl.h") && !$(NEED_TCL_SOURCE)\r
+\r
+TCLINSTALL     = 1\r
+TCLDIR          = $(_INSTALLDIR)\..\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TCLDIR                = $(_INSTALLDIR)\..\r
+_TCL_H          = $(_TCLDIR)\include\tcl.h\r
+\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!if [echo _TCLDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
+!error *** Could not locate Tcl source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TCLINSTALL      = 0\r
+TCLDIR         = $(_TCLDIR)\r
+_TCL_H          = $(_TCLDIR)\generic\tcl.h\r
+\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
+\r
+!endif # TCLDIR\r
+\r
+!ifndef _TCL_H\r
+MSG =^\r
+Failed to find tcl.h. The TCLDIR macro is set incorrectly or is not set and default path does not contain tcl.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+# Now do the same to locate Tk headers and libs if project requires Tk\r
+!if $(NEED_TK)\r
+\r
+!if "$(TKDIR)" != ""\r
+\r
+_TKDIR = $(TKDIR:/=\)\r
+!if exist("$(_TKDIR)\include\tk.h")\r
+TKINSTALL      = 1\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+!elseif exist("$(_TKDIR)\generic\tk.h")\r
+TKINSTALL      = 0\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+!endif\r
+\r
+!else # TKDIR not defined\r
+\r
+# Need to locate Tcl depending on whether it needs Tcl source or not.\r
+# If we don't, check the INSTALLDIR for an installed Tcl first\r
+\r
+!if exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+TKINSTALL      = 1\r
+# NOTE: we will be resetting _INSTALLDIR to _INSTALLDIR/lib for extensions\r
+# later so the \.. accounts for the /lib\r
+_TKDIR         = $(_INSTALLDIR)\..\r
+_TK_H          = $(_TKDIR)\include\tk.h\r
+TKDIR          = $(_TKDIR)\r
+\r
+!else # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!if [echo _TKDIR = \> nmakehlp.out] \\r
+   || [nmakehlp -L generic\tk.h >> nmakehlp.out]\r
+!error *** Could not locate Tk source directory.\r
+!endif\r
+!include nmakehlp.out\r
+TKINSTALL      = 0\r
+TKDIR          = $(_TKDIR)\r
+_TK_H          = $(_TKDIR)\generic\tk.h\r
+\r
+!endif # exist("$(_INSTALLDIR)\include\tk.h") && !$(NEED_TK_SOURCE)\r
+\r
+!endif # TKDIR\r
+\r
+!ifndef _TK_H\r
+MSG =^\r
+Failed to find tk.h. The TKDIR macro is set incorrectly or is not set and default path does not contain tk.h.\r
+!error $(MSG)\r
+!endif\r
+\r
+!endif # NEED_TK\r
+\r
+!if $(NEED_TCL_SOURCE) && $(TCLINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tcl.^\r
+*** Please set the TCLDIR macro to point to the Tcl sources.\r
+!error $(MSG)\r
+!endif\r
+\r
+!if $(NEED_TK_SOURCE)\r
+!if $(TKINSTALL)\r
+MSG = ^\r
+*** Warning: This extension requires the source distribution of Tk.^\r
+*** Please set the TKDIR macro to point to the Tk sources.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+\r
+# If INSTALLDIR set to Tcl installation root dir then reset to the\r
+# lib dir for installing extensions\r
+!if exist("$(_INSTALLDIR)\include\tcl.h")\r
+_INSTALLDIR=$(_INSTALLDIR)\lib\r
+!endif\r
+\r
+# END Case 2(c) or (d) - Building an extension\r
+!endif # if $(DOING_TCL)\r
+\r
+################################################################\r
+# 3. Determine compiler version and architecture\r
+# In this section, we figure out the compiler version and the\r
+# architecture for which we are building. This sets the\r
+# following macros:\r
+# VCVERSION - the internal compiler version as 1200, 1400, 1910 etc.\r
+#     This is also printed by the compiler in dotted form 19.10 etc.\r
+# VCVER - the "marketing version", for example Visual C++ 6 for internal\r
+#     compiler version 1200. This is kept only for legacy reasons as it\r
+#     does not make sense for recent Microsoft compilers. Only used for\r
+#     output directory names.\r
+# ARCH - set to IX86 or AMD64 depending on 32- or 64-bit target\r
+# NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
+# MACHINE - same as $(ARCH) - legacy\r
+# _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
+\r
+cc32           = $(CC)   # built-in default.\r
+link32         = link\r
+lib32          = lib\r
+rc32           = $(RC)   # built-in default.\r
+\r
+#----------------------------------------------------------------\r
+# Figure out the compiler architecture and version by writing\r
+# the C macros to a file, preprocessing them with the C\r
+# preprocessor and reading back the created file\r
+\r
+_HASH=^#\r
+_VC_MANIFEST_EMBED_EXE=\r
+_VC_MANIFEST_EMBED_DLL=\r
+VCVER=0\r
+!if ![echo VCVERSION=_MSC_VER > vercl.x] \\r
+    && ![echo $(_HASH)if defined(_M_IX86) >> vercl.x] \\r
+    && ![echo ARCH=IX86 >> vercl.x] \\r
+    && ![echo $(_HASH)elif defined(_M_AMD64) >> vercl.x] \\r
+    && ![echo ARCH=AMD64 >> vercl.x] \\r
+    && ![echo $(_HASH)endif >> vercl.x] \\r
+    && ![$(cc32) -nologo -TC -P vercl.x 2>NUL]\r
+!include vercl.i\r
+!if $(VCVERSION) < 1900\r
+!if ![echo VCVER= ^\> vercl.vc] \\r
+    && ![set /a $(VCVERSION) / 100 - 6 >> vercl.vc]\r
+!include vercl.vc\r
+!endif\r
+!else\r
+# The simple calculation above does not apply to new Visual Studio releases\r
+# Keep the compiler version in its native form.\r
+VCVER = $(VCVERSION)\r
+!endif\r
+!endif\r
+\r
+!if ![del 2>NUL /q/f vercl.x vercl.i vercl.vc]\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# The MACHINE macro is used by legacy makefiles so set it as well\r
+!ifdef MACHINE\r
+!if "$(MACHINE)" == "x86"\r
+!undef MACHINE\r
+MACHINE = IX86\r
+!elseif "$(MACHINE)" == "x64"\r
+!undef MACHINE\r
+MACHINE = AMD64\r
+!endif\r
+!if "$(MACHINE)" != "$(ARCH)"\r
+!error Specified MACHINE macro $(MACHINE) does not match detected target architecture $(ARCH).\r
+!endif\r
+!else\r
+MACHINE=$(ARCH)\r
+!endif\r
+\r
+#---------------------------------------------------------------\r
+# The PLATFORM_IDENTIFY macro matches the values returned by\r
+# the Tcl platform::identify command\r
+!if "$(MACHINE)" == "AMD64"\r
+PLATFORM_IDENTIFY = win32-x86_64\r
+!else\r
+PLATFORM_IDENTIFY = win32-ix86\r
+!endif\r
+\r
+# The MULTIPLATFORM macro controls whether binary extensions are installed\r
+# in platform-specific directories. Intended to be set/used by extensions.\r
+!ifndef MULTIPLATFORM_INSTALL\r
+MULTIPLATFORM_INSTALL = 0\r
+!endif\r
+\r
+#------------------------------------------------------------\r
+# Figure out the *host* architecture by reading the registry\r
+\r
+!if ![reg query HKLM\Hardware\Description\System\CentralProcessor\0 /v Identifier | findstr /i x86]\r
+NATIVE_ARCH=IX86\r
+!else\r
+NATIVE_ARCH=AMD64\r
+!endif\r
+\r
+# Since MSVC8 we must deal with manifest resources.\r
+!if $(VCVERSION) >= 1400\r
+_VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;1\r
+_VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
+!endif\r
+\r
+################################################################\r
+# 4. Build the nmakehlp program\r
+# This is a helper app we need to overcome nmake's limiting\r
+# environment. We will call out to it to get various bits of\r
+# information about supported compiler options etc.\r
+#\r
+# Tcl itself will always use the nmakehlp.c program which is\r
+# in its own source. It will be kept updated there.\r
+#\r
+# Extensions built against an installed Tcl will use the installed\r
+# copy of Tcl's nmakehlp.c if there is one and their own version\r
+# otherwise. In the latter case, they would also be using their own\r
+# rules.vc. Note that older versions of Tcl do not install nmakehlp.c\r
+# or rules.vc.\r
+#\r
+# Extensions built against Tcl sources will use the one from the Tcl source.\r
+#\r
+# When building an extension using a sufficiently new version of Tcl,\r
+# rules-ext.vc will define NMAKEHLPC appropriately to point to the\r
+# copy of nmakehlp.c to be used.\r
+\r
+!ifndef NMAKEHLPC\r
+# Default to the one in the current directory (the extension's own nmakehlp.c)\r
+NMAKEHLPC = nmakehlp.c\r
+\r
+!if !$(DOING_TCL)\r
+!if $(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
+!endif\r
+!else # !$(TCLINSTALL)\r
+!if exist("$(_TCLDIR)\win\nmakehlp.c")\r
+NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
+!endif\r
+!endif # $(TCLINSTALL)\r
+!endif # !$(DOING_TCL)\r
+\r
+!endif # NMAKEHLPC\r
+\r
+# We always build nmakehlp even if it exists since we do not know\r
+# what source it was built from.\r
+!if [$(cc32) -nologo "$(NMAKEHLPC)" -link -subsystem:console > nul]\r
+!endif\r
+\r
+################################################################\r
+# 5. Test for compiler features\r
+# Visual C++ compiler options have changed over the years. Check\r
+# which options are supported by the compiler in use.\r
+#\r
+# The following macros are set:\r
+# OPTIMIZATIONS - the compiler flags to be used for optimized builds\r
+# DEBUGFLAGS - the compiler flags to be used for debug builds\r
+# LINKERFLAGS - Flags passed to the linker\r
+#\r
+# Note that these are the compiler settings *available*, not those\r
+# that will be *used*. The latter depends on the OPTS macro settings\r
+# which we have not yet parsed.\r
+#\r
+# Also note that some of the flags in OPTIMIZATIONS are not really\r
+# related to optimization. They are placed there only for legacy reasons\r
+# as some extensions expect them to be included in that macro.\r
+\r
+# -Op improves float consistency. Note only needed for older compilers\r
+# Newer compilers do not need or support this option.\r
+!if [nmakehlp -c -Op]\r
+FPOPTS  = -Op\r
+!endif\r
+\r
+# Strict floating point semantics - present in newer compilers in lieu of -Op\r
+!if [nmakehlp -c -fp:strict]\r
+FPOPTS  = $(FPOPTS) -fp:strict\r
+!endif\r
+\r
+!if "$(MACHINE)" == "IX86"\r
+### test for pentium errata\r
+!if [nmakehlp -c -QI0f]\r
+!message *** Compiler has 'Pentium 0x0f fix'\r
+FPOPTS  = $(FPOPTS) -QI0f\r
+!else\r
+!message *** Compiler does not have 'Pentium 0x0f fix'\r
+!endif\r
+!endif\r
+\r
+### test for optimizations\r
+# /O2 optimization includes /Og /Oi /Ot /Oy /Ob2 /Gs /GF /Gy as per\r
+# documentation. Note we do NOT want /Gs as that inserts a _chkstk\r
+# stack probe at *every* function entry, not just those with more than\r
+# a page of stack allocation resulting in a performance hit.  However,\r
+# /O2 documentation is misleading as its stack probes are simply the\r
+# default page size locals allocation probes and not what is implied\r
+# by an explicit /Gs option.\r
+\r
+OPTIMIZATIONS = $(FPOPTS)\r
+\r
+!if [nmakehlp -c -O2]\r
+OPTIMIZING = 1\r
+OPTIMIZATIONS   = $(OPTIMIZATIONS) -O2\r
+!else\r
+# Legacy, really. All modern compilers support this\r
+!message *** Compiler does not have 'Optimizations'\r
+OPTIMIZING = 0\r
+!endif\r
+\r
+# Checks for buffer overflows in local arrays\r
+!if [nmakehlp -c -GS]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GS\r
+!endif\r
+\r
+# Link time optimization. Note that this option (potentially) makes\r
+# generated libraries only usable by the specific VC++ version that\r
+# created it. Requires /LTCG linker option\r
+!if [nmakehlp -c -GL]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -GL\r
+CC_GL_OPT_ENABLED = 1\r
+!else\r
+# In newer compilers -GL and -YX are incompatible.\r
+!if [nmakehlp -c -YX]\r
+OPTIMIZATIONS  = $(OPTIMIZATIONS) -YX\r
+!endif\r
+!endif # [nmakehlp -c -GL]\r
+\r
+DEBUGFLAGS     = $(FPOPTS)\r
+\r
+# Run time error checks. Not available or valid in a release, non-debug build\r
+# RTC is for modern compilers, -GZ is legacy\r
+!if [nmakehlp -c -RTC1]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -RTC1\r
+!elseif [nmakehlp -c -GZ]\r
+DEBUGFLAGS     = $(DEBUGFLAGS) -GZ\r
+!endif\r
+\r
+#----------------------------------------------------------------\r
+# Linker flags\r
+\r
+# LINKER_TESTFLAGS are for internal use when we call nmakehlp to test\r
+# if the linker supports a specific option. Without these flags link will\r
+# return "LNK1561: entry point must be defined" error compiling from VS-IDE:\r
+# They are not passed through to the actual application / extension\r
+# link rules.\r
+!ifndef LINKER_TESTFLAGS\r
+LINKER_TESTFLAGS = /DLL /NOENTRY /OUT:nmakehlp.out\r
+!endif\r
+\r
+LINKERFLAGS     =\r
+\r
+# If compiler has enabled link time optimization, linker must too with -ltcg\r
+!ifdef CC_GL_OPT_ENABLED\r
+!if [nmakehlp -l -ltcg $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS     = $(LINKERFLAGS) -ltcg\r
+!endif\r
+!endif\r
+\r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
+########################################################################\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
+# Based on this, we will construct the actual switches to be passed to the\r
+# compiler and linker using the macros defined in the previous section.\r
+# The following macros are defined by this section based on OPTS\r
+# STATIC_BUILD - 0 -> Tcl is to be built as a shared library\r
+#                1 -> build as a static library and shell\r
+# TCL_THREADS - legacy but always 1 on Windows since winsock requires it.\r
+# DEBUG - 1 -> debug build, 0 -> release builds\r
+# SYMBOLS - 1 -> generate PDB's, 0 -> no PDB's\r
+# PROFILE - 1 -> generate profiling info, 0 -> no profiling\r
+# PGO     - 1 -> profile based optimization, 0 -> no\r
+# MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
+#           0 -> link to static C runtime for static Tcl build.\r
+#           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
+# TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
+# USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
+#           0 -> Use the non-thread allocator.\r
+# UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
+#           C runtime, 0 -> use the debug C runtime.\r
+# USE_STUBS - 1 -> compile to use stubs interfaces, 0 -> direct linking\r
+# CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
+#           configuration (ignored for Tcl itself)\r
+# _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
+# Further, LINKERFLAGS are modified based on above.\r
+\r
+# Default values for all the above\r
+STATIC_BUILD   = 0\r
+TCL_THREADS    = 1\r
+DEBUG          = 0\r
+SYMBOLS                = 0\r
+PROFILE                = 0\r
+PGO            = 0\r
+MSVCRT         = 1\r
+TCL_USE_STATIC_PACKAGES        = 0\r
+USE_THREAD_ALLOC = 1\r
+UNCHECKED      = 0\r
+CONFIG_CHECK    = 1\r
+!if $(DOING_TCL)\r
+USE_STUBS       = 0\r
+!else\r
+USE_STUBS       = 1\r
+!endif\r
+\r
+# If OPTS is not empty AND does not contain "none" which turns off all OPTS\r
+# set the above macros based on OPTS content\r
+!if "$(OPTS)" != "" && ![nmakehlp -f "$(OPTS)" "none"]\r
+\r
+# OPTS are specified, parse them\r
+\r
+!if [nmakehlp -f $(OPTS) "static"]\r
+!message *** Doing static\r
+STATIC_BUILD   = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nostubs"]\r
+!message *** Not using stubs\r
+USE_STUBS      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+!message *** Doing nomsvcrt\r
+MSVCRT         = 0\r
+!else\r
+!if [nmakehlp -f $(OPTS) "msvcrt"]\r
+!message *** Doing msvcrt\r
+!else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
+MSVCRT         = 0\r
+!endif\r
+!endif\r
+!endif # [nmakehlp -f $(OPTS) "nomsvcrt"]\r
+\r
+!if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
+!message *** Doing staticpkg\r
+TCL_USE_STATIC_PACKAGES        = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "nothreads"]\r
+!message *** Compile explicitly for non-threaded tcl\r
+TCL_THREADS = 0\r
+USE_THREAD_ALLOC= 0\r
+!endif\r
+\r
+!if $(TCL_MAJOR_VERSION) == 8\r
+!if [nmakehlp -f $(OPTS) "time64bit"]\r
+!message *** Force 64-bit time_t\r
+_USE_64BIT_TIME_T = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
+# Yes, it's weird that the "symbols" option controls DEBUG and\r
+# the "pdbs" option controls SYMBOLS. That's historical.\r
+!if [nmakehlp -f $(OPTS) "symbols"]\r
+!message *** Doing symbols\r
+DEBUG          = 1\r
+!else\r
+DEBUG          = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pdbs"]\r
+!message *** Doing pdbs\r
+SYMBOLS                = 1\r
+!else\r
+SYMBOLS                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "profile"]\r
+!message *** Doing profile\r
+PROFILE                = 1\r
+!else\r
+PROFILE                = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "pgi"]\r
+!message *** Doing profile guided optimization instrumentation\r
+PGO            = 1\r
+!elseif [nmakehlp -f $(OPTS) "pgo"]\r
+!message *** Doing profile guided optimization\r
+PGO            = 2\r
+!else\r
+PGO            = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "loimpact"]\r
+!message *** Warning: ignoring option "loimpact" - deprecated on modern Windows.\r
+!endif\r
+\r
+# TBD - should get rid of this option\r
+!if [nmakehlp -f $(OPTS) "thrdalloc"]\r
+!message *** Doing thrdalloc\r
+USE_THREAD_ALLOC = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "tclalloc"]\r
+USE_THREAD_ALLOC = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "unchecked"]\r
+!message *** Doing unchecked\r
+UNCHECKED = 1\r
+!else\r
+UNCHECKED = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(OPTS) "noconfigcheck"]\r
+CONFIG_CHECK = 1\r
+!else\r
+CONFIG_CHECK = 0\r
+!endif\r
+\r
+!endif # "$(OPTS)" != ""  && ... parsing of OPTS\r
+\r
+# Set linker flags based on above\r
+\r
+!if $(PGO) > 1\r
+!if [nmakehlp -l -ltcg:pgoptimize $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pgoptimize\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!elseif $(PGO) > 0\r
+!if [nmakehlp -l -ltcg:pginstrument $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS    = $(LINKERFLAGS:-ltcg=) -ltcg:pginstrument\r
+!else\r
+MSG=^\r
+This compiler does not support profile guided optimization.\r
+!error $(MSG)\r
+!endif\r
+!endif\r
+\r
+################################################################\r
+# 8. Parse the STATS macro to configure code instrumentation\r
+# The following macros are set by this section:\r
+# TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
+#                 0 -> disables\r
+# TCL_COMPILE_DEBUG - 1 -> enables byte compiler logging\r
+#                     0 -> disables\r
+\r
+# Default both are off\r
+TCL_MEM_DEBUG      = 0\r
+TCL_COMPILE_DEBUG   = 0\r
+\r
+!if "$(STATS)" != "" && ![nmakehlp -f "$(STATS)" "none"]\r
+\r
+!if [nmakehlp -f $(STATS) "memdbg"]\r
+!message *** Doing memdbg\r
+TCL_MEM_DEBUG      = 1\r
+!else\r
+TCL_MEM_DEBUG      = 0\r
+!endif\r
+\r
+!if [nmakehlp -f $(STATS) "compdbg"]\r
+!message *** Doing compdbg\r
+TCL_COMPILE_DEBUG   = 1\r
+!else\r
+TCL_COMPILE_DEBUG   = 0\r
+!endif\r
+\r
+!endif\r
+\r
+####################################################################\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
+# The following macros are set by this section:\r
+# WARNINGS - compiler switches that control the warnings level\r
+# TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
+#                     0 -> enable deprecated functions\r
+\r
+# Defaults - Permit deprecated functions and warning level 3\r
+TCL_NO_DEPRECATED          = 0\r
+WARNINGS                   = -W3\r
+\r
+!if "$(CHECKS)" != "" && ![nmakehlp -f "$(CHECKS)" "none"]\r
+\r
+!if [nmakehlp -f $(CHECKS) "nodep"]\r
+!message *** Doing nodep check\r
+TCL_NO_DEPRECATED          = 1\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "fullwarn"]\r
+!message *** Doing full warnings check\r
+WARNINGS                   = -W4\r
+!if [nmakehlp -l -warn:3 $(LINKER_TESTFLAGS)]\r
+LINKERFLAGS                = $(LINKERFLAGS) -warn:3\r
+!endif\r
+!endif\r
+\r
+!if [nmakehlp -f $(CHECKS) "64bit"] && [nmakehlp -c -Wp64]\r
+!message *** Doing 64bit portability warnings\r
+WARNINGS                   = $(WARNINGS) -Wp64\r
+!endif\r
+\r
+!endif\r
+\r
+\r
+################################################################\r
+# 10. Construct output directory and file paths\r
+# Figure-out how to name our intermediate and output directories.\r
+# In order to avoid inadvertent mixing of object files built using\r
+# different compilers, build configurations etc.,\r
+#\r
+# Naming convention (suffixes):\r
+#   t = full thread support. (Not used for Tcl >= 8.7)\r
+#   s = static library (as opposed to an import library)\r
+#   g = linked to the debug enabled C run-time.\r
+#   x = special static build when it links to the dynamic C run-time.\r
+#\r
+# The following macros are set in this section:\r
+# SUFX - the suffix to use for binaries based on above naming convention\r
+# BUILDDIRTOP - the toplevel default output directory\r
+#      is of the form {Release,Debug}[_AMD64][_COMPILERVERSION]\r
+# TMP_DIR - directory where object files are created\r
+# OUT_DIR - directory where output executables are created\r
+# Both TMP_DIR and OUT_DIR are defaulted only if not defined by the\r
+# parent makefile (or command line). The default values are\r
+# based on BUILDDIRTOP.\r
+# STUBPREFIX - name of the stubs library for this project\r
+# PRJIMPLIB - output path of the generated project import library\r
+# PRJLIBNAME - name of generated project library\r
+# PRJLIB     - output path of generated project library\r
+# PRJSTUBLIBNAME - name of the generated project stubs library\r
+# PRJSTUBLIB - output path of the generated project stubs library\r
+# RESFILE - output resource file (only if not static build)\r
+\r
+SUFX       = tsgx\r
+\r
+!if $(DEBUG)\r
+BUILDDIRTOP = Debug\r
+!else\r
+BUILDDIRTOP = Release\r
+!endif\r
+\r
+!if "$(MACHINE)" != "IX86"\r
+BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)\r
+!endif\r
+!if $(VCVER) > 6\r
+BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
+!endif\r
+\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
+SUFX       = $(SUFX:g=)\r
+!endif\r
+\r
+TMP_DIRFULL = .\$(BUILDDIRTOP)\$(PROJECT)_ThreadedDynamicStaticX\r
+\r
+!if !$(STATIC_BUILD)\r
+TMP_DIRFULL = $(TMP_DIRFULL:Static=)\r
+SUFX       = $(SUFX:s=)\r
+EXT        = dll\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!else\r
+TMP_DIRFULL = $(TMP_DIRFULL:Dynamic=)\r
+EXT        = lib\r
+!if !$(MSVCRT)\r
+TMP_DIRFULL = $(TMP_DIRFULL:X=)\r
+SUFX       = $(SUFX:x=)\r
+!endif\r
+!endif\r
+\r
+!if !$(TCL_THREADS) || $(TCL_VERSION) > 86\r
+TMP_DIRFULL = $(TMP_DIRFULL:Threaded=)\r
+SUFX       = $(SUFX:t=)\r
+!endif\r
+\r
+!ifndef TMP_DIR\r
+TMP_DIR            = $(TMP_DIRFULL)\r
+!ifndef OUT_DIR\r
+OUT_DIR            = .\$(BUILDDIRTOP)\r
+!endif\r
+!else\r
+!ifndef OUT_DIR\r
+OUT_DIR            = $(TMP_DIR)\r
+!endif\r
+!endif\r
+\r
+# Relative paths -> absolute\r
+!if [echo OUT_DIR = \> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(OUT_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path OUT_DIR=$(OUT_DIR)\r
+!endif\r
+!if [echo TMP_DIR = \>> nmakehlp.out] \\r
+   || [nmakehlp -Q "$(TMP_DIR)" >> nmakehlp.out]\r
+!error *** Could not fully qualify path TMP_DIR=$(TMP_DIR)\r
+!endif\r
+!include nmakehlp.out\r
+\r
+# The name of the stubs library for the project being built\r
+STUBPREFIX      = $(PROJECT)stub\r
+\r
+#\r
+# Set up paths to various Tcl executables and libraries needed by extensions\r
+#\r
+\r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
+TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
+TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
+TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
+\r
+TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
+TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+\r
+!else # !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+\r
+# When building extensions, we need to locate tclsh. Depending on version\r
+# of Tcl we are building against, this may or may not have a "t" suffix.\r
+# Try various possibilities in turn.\r
+TCLSH          = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist("$(TCLSH)")\r
+TCLSH           = $(_TCLDIR)\bin\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+\r
+TCLSTUBLIB     = $(_TCLDIR)\lib\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\lib\r
+TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
+TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
+\r
+!else # Building against Tcl sources\r
+\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)$(SUFX:t=).exe\r
+!if !exist($(TCLSH))\r
+TCLSH          = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclsh$(TCL_VERSION)t$(SUFX:t=).exe\r
+!endif\r
+TCLSTUBLIB     = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclstub$(TCL_VERSION).lib\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)$(SUFX:t=).lib\r
+# When building extensions, may be linking against Tcl that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TCLIMPLIB)")\r
+TCLIMPLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib\r
+!endif\r
+TCL_LIBRARY    = $(_TCLDIR)\library\r
+TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
+TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
+TCLTOOLSDIR    = $(_TCLDIR)\tools\r
+TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
+\r
+!endif # TCLINSTALL\r
+\r
+tcllibs = "$(TCLSTUBLIB)" "$(TCLIMPLIB)"\r
+\r
+!endif # $(DOING_TCL)\r
+\r
+# We need a tclsh that will run on the host machine as part of the build.\r
+# IX86 runs on all architectures.\r
+!ifndef TCLSH_NATIVE\r
+!if "$(MACHINE)" == "IX86" || "$(MACHINE)" == "$(NATIVE_ARCH)"\r
+TCLSH_NATIVE   = $(TCLSH)\r
+!else\r
+!error You must explicitly set TCLSH_NATIVE for cross-compilation\r
+!endif\r
+!endif\r
+\r
+# Do the same for Tk and Tk extensions that require the Tk libraries\r
+!if $(DOING_TK) || $(NEED_TK)\r
+WISHNAMEPREFIX = wish\r
+WISHNAME = $(WISHNAMEPREFIX)$(TK_VERSION)$(SUFX).exe\r
+TKLIBNAME      = $(PROJECT)$(TK_VERSION)$(SUFX).$(EXT)\r
+TKSTUBLIBNAME  = tkstub$(TK_VERSION).lib\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX).lib\r
+\r
+!if $(DOING_TK)\r
+WISH           = $(OUT_DIR)\$(WISHNAME)\r
+TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
+TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
+\r
+!else # effectively NEED_TK\r
+\r
+!if $(TKINSTALL) # Building against installed Tk\r
+WISH           = $(_TKDIR)\bin\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\lib\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
+!else # Building against Tk sources\r
+\r
+WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
+TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+# When building extensions, may be linking against Tk that does not add\r
+# "t" suffix (e.g. 8.5 or 8.7). If lib not found check for that possibility.\r
+!if !exist("$(TKIMPLIB)")\r
+TKIMPLIBNAME   = tk$(TK_VERSION)$(SUFX:t=).lib\r
+TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
+!endif\r
+TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
+!endif # TKINSTALL\r
+\r
+tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
+\r
+!endif # $(DOING_TK)\r
+!endif # $(DOING_TK) || $(NEED_TK)\r
+\r
+# Various output paths\r
+PRJIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
+PRJLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
+PRJLIB         = $(OUT_DIR)\$(PRJLIBNAME)\r
+\r
+PRJSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
+PRJSTUBLIB     = $(OUT_DIR)\$(PRJSTUBLIBNAME)\r
+\r
+# If extension parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+!if !$(DOING_TCL) && !$(DOING_TK) && !$(STATIC_BUILD)\r
+!ifdef RCFILE\r
+RESFILE = $(TMP_DIR)\$(RCFILE:.rc=.res)\r
+!else\r
+RESFILE = $(TMP_DIR)\$(PROJECT).res\r
+!endif\r
+!endif\r
+\r
+###################################################################\r
+# 11. Construct the paths for the installation directories\r
+# The following macros get defined in this section:\r
+# LIB_INSTALL_DIR - where libraries should be installed\r
+# BIN_INSTALL_DIR - where the executables should be installed\r
+# DOC_INSTALL_DIR - where documentation should be installed\r
+# SCRIPT_INSTALL_DIR - where scripts should be installed\r
+# INCLUDE_INSTALL_DIR - where C include files should be installed\r
+# DEMO_INSTALL_DIR - where demos should be installed\r
+# PRJ_INSTALL_DIR - where package will be installed (not set for Tcl and Tk)\r
+\r
+!if $(DOING_TCL) || $(DOING_TK)\r
+LIB_INSTALL_DIR                = $(_INSTALLDIR)\lib\r
+BIN_INSTALL_DIR                = $(_INSTALLDIR)\bin\r
+DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
+!if $(DOING_TCL)\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
+!else # DOING_TK\r
+SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!endif\r
+DEMO_INSTALL_DIR       = $(SCRIPT_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\include\r
+\r
+!else # extension other than Tk\r
+\r
+PRJ_INSTALL_DIR         = $(_INSTALLDIR)\$(PROJECT)$(DOTVERSION)\r
+!if $(MULTIPLATFORM_INSTALL)\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\$(PLATFORM_IDENTIFY)\r
+!else\r
+LIB_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+BIN_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+!endif\r
+DOC_INSTALL_DIR                = $(PRJ_INSTALL_DIR)\r
+SCRIPT_INSTALL_DIR     = $(PRJ_INSTALL_DIR)\r
+DEMO_INSTALL_DIR       = $(PRJ_INSTALL_DIR)\demos\r
+INCLUDE_INSTALL_DIR    = $(_INSTALLDIR)\..\include\r
+\r
+!endif\r
+\r
+###################################################################\r
+# 12. Set up actual options to be passed to the compiler and linker\r
+# Now we have all the information we need, set up the actual flags and\r
+# options that we will pass to the compiler and linker. The main\r
+# makefile should use these in combination with whatever other flags\r
+# and switches are specific to it.\r
+# The following macros are defined, names are for historical compatibility:\r
+# OPTDEFINES - /Dxxx C macro flags based on user-specified OPTS\r
+# COMPILERFLAGS - /Dxxx C macro flags independent of any configuration opttions\r
+# crt - Compiler switch that selects the appropriate C runtime\r
+# cdebug - Compiler switches related to debug AND optimizations\r
+# cwarn - Compiler switches that set warning levels\r
+# cflags - complete compiler switches (subsumes cdebug and cwarn)\r
+# ldebug - Linker switches controlling debug information and optimization\r
+# lflags - complete linker switches (subsumes ldebug) except subsystem type\r
+# dlllflags - complete linker switches to build DLLs (subsumes lflags)\r
+# conlflags - complete linker switches for console program (subsumes lflags)\r
+# guilflags - complete linker switches for GUI program (subsumes lflags)\r
+# baselibs - minimum Windows libraries required. Parent makefile can\r
+#    define PRJ_LIBS before including rules.rc if additional libs are needed\r
+\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
+\r
+!if $(TCL_MEM_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
+!endif\r
+!if $(TCL_COMPILE_DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_COMPILE_DEBUG /DTCL_COMPILE_STATS\r
+!endif\r
+!if $(TCL_THREADS) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_THREADS=1\r
+!if $(USE_THREAD_ALLOC) && $(TCL_VERSION) < 87\r
+OPTDEFINES     = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1\r
+!endif\r
+!endif\r
+!if $(STATIC_BUILD)\r
+OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
+!endif\r
+!if $(TCL_NO_DEPRECATED)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
+!endif\r
+\r
+!if $(USE_STUBS)\r
+# Note we do not define USE_TCL_STUBS even when building tk since some\r
+# test targets in tk do not use stubs\r
+!if !$(DOING_TCL)\r
+USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
+!if $(NEED_TK)\r
+USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
+!endif\r
+!endif\r
+!endif # USE_STUBS\r
+\r
+!if !$(DEBUG)\r
+OPTDEFINES     = $(OPTDEFINES) /DNDEBUG\r
+!if $(OPTIMIZING)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_OPTIMIZED\r
+!endif\r
+!endif\r
+!if $(PROFILE)\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_PROFILED\r
+!endif\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
+!endif\r
+!if $(VCVERSION) < 1300\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
+!endif\r
+\r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
+!if "$(_USE_64BIT_TIME_T)" == "1"\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
+!endif\r
+\r
+# _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
+COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
+\r
+# Like the TEA system only set this non empty for non-Tk extensions\r
+# Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
+# so we pass both\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+PKGNAMEFLAGS = /DPACKAGE_NAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_TCLNAME="\"$(PRJ_PACKAGE_TCLNAME)\"" \\r
+               /DPACKAGE_VERSION="\"$(DOTVERSION)\"" \\r
+               /DMODULE_SCOPE=extern\r
+!endif\r
+\r
+# crt picks the C run time based on selected OPTS\r
+!if $(MSVCRT)\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MDd\r
+!else\r
+crt = -MD\r
+!endif\r
+!else\r
+!if $(DEBUG) && !$(UNCHECKED)\r
+crt = -MTd\r
+!else\r
+crt = -MT\r
+!endif\r
+!endif\r
+\r
+# cdebug includes compiler options for debugging as well as optimization.\r
+!if $(DEBUG)\r
+\r
+# In debugging mode, optimizations need to be disabled\r
+cdebug = -Zi -Od $(DEBUGFLAGS)\r
+\r
+!else\r
+\r
+cdebug = $(OPTIMIZATIONS)\r
+!if $(SYMBOLS)\r
+cdebug = $(cdebug) -Zi\r
+!endif\r
+\r
+!endif # $(DEBUG)\r
+\r
+# cwarn includes default warning levels.\r
+cwarn = $(WARNINGS)\r
+\r
+!if "$(MACHINE)" == "AMD64"\r
+# Disable pointer<->int warnings related to cast between different sizes\r
+# There are a gadzillion of these due to use of ClientData and\r
+# clutter up compiler\r
+# output increasing chance of a real warning getting lost. So disable them.\r
+# Eventually some day, Tcl will be 64-bit clean.\r
+cwarn = $(cwarn) -wd4311 -wd4312\r
+!endif\r
+\r
+### Common compiler options that are architecture specific\r
+!if "$(MACHINE)" == "ARM"\r
+carch = /D_ARM_WINAPI_PARTITION_DESKTOP_SDK_AVAILABLE\r
+!else\r
+carch =\r
+!endif\r
+\r
+!if $(DEBUG)\r
+# Turn warnings into errors\r
+cwarn = $(cwarn) -WX\r
+!endif\r
+\r
+INCLUDES = $(TCL_INCLUDES) $(TK_INCLUDES) $(PRJ_INCLUDES)\r
+!if !$(DOING_TCL) && !$(DOING_TK)\r
+INCLUDES = $(INCLUDES) -I"$(GENERICDIR)" -I"$(WIN_DIR)" -I"$(COMPATDIR)"\r
+!endif\r
+\r
+# These flags are defined roughly in the order of the pre-reform\r
+# rules.vc/makefile.vc to help visually compare that the pre- and\r
+# post-reform build logs\r
+\r
+# cflags contains generic flags used for building practically all object files\r
+cflags = -nologo -c $(COMPILERFLAGS) $(carch) $(cwarn) -Fp$(TMP_DIR)^\ $(cdebug)\r
+\r
+# appcflags contains $(cflags) and flags for building the application\r
+# object files (e.g. tclsh, or wish) pkgcflags contains $(cflags) plus\r
+# flags used for building shared object files The two differ in the\r
+# BUILD_$(PROJECT) macro which should be defined only for the shared\r
+# library *implementation* and not for its caller interface\r
+\r
+appcflags_nostubs = $(cflags) $(crt) $(INCLUDES) $(TCL_DEFINES) $(PRJ_DEFINES) $(OPTDEFINES)\r
+appcflags = $(appcflags_nostubs) $(USE_STUBS_DEFS)\r
+pkgcflags = $(appcflags) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+pkgcflags_nostubs = $(appcflags_nostubs) $(PKGNAMEFLAGS) /DBUILD_$(PROJECT)\r
+\r
+# stubscflags contains $(cflags) plus flags used for building a stubs\r
+# library for the package.  Note: /DSTATIC_BUILD is defined in\r
+# $(OPTDEFINES) only if the OPTS configuration indicates a static\r
+# library. However the stubs library is ALWAYS static hence included\r
+# here irrespective of the OPTS setting.\r
+#\r
+# TBD - tclvfs has a comment that stubs libs should not be compiled with -GL\r
+# without stating why. Tcl itself compiled stubs libs with this flag.\r
+# so we do not remove it from cflags. -GL may prevent extensions\r
+# compiled with one VC version to fail to link against stubs library\r
+# compiled with another VC version. Check for this and fix accordingly.\r
+stubscflags = $(cflags) $(PKGNAMEFLAGS) $(PRJ_DEFINES) $(OPTDEFINES) -Zl /DSTATIC_BUILD $(INCLUDES) $(USE_STUBS_DEFS)\r
+\r
+# Link flags\r
+\r
+!if $(DEBUG)\r
+ldebug = -debug -debugtype:cv\r
+!else\r
+ldebug = -release -opt:ref -opt:icf,3\r
+!if $(SYMBOLS)\r
+ldebug = $(ldebug) -debug -debugtype:cv\r
+!endif\r
+!endif\r
+\r
+# Note: Profiling is currently only possible with the Visual Studio Enterprise\r
+!if $(PROFILE)\r
+ldebug= $(ldebug) -profile\r
+!endif\r
+\r
+### Declarations common to all linker versions\r
+lflags = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+lflags = $(lflags) -nodefaultlib:libucrt.lib\r
+!endif\r
+\r
+dlllflags = $(lflags) -dll\r
+conlflags = $(lflags) -subsystem:console\r
+guilflags = $(lflags) -subsystem:windows\r
+\r
+# Libraries that are required for every image.\r
+# Extensions should define any additional libraries with $(PRJ_LIBS)\r
+winlibs   = kernel32.lib advapi32.lib\r
+\r
+!if $(NEED_TK)\r
+winlibs = $(winlibs) gdi32.lib user32.lib uxtheme.lib\r
+!endif\r
+\r
+# Avoid 'unresolved external symbol __security_cookie' errors.\r
+# c.f. http://support.microsoft.com/?id=894573\r
+!if "$(MACHINE)" == "AMD64"\r
+!if $(VCVERSION) > 1399 && $(VCVERSION) < 1500\r
+winlibs   = $(winlibs) bufferoverflowU.lib\r
+!endif\r
+!endif\r
+\r
+baselibs = $(winlibs) $(PRJ_LIBS)\r
+\r
+!if $(MSVCRT) && !($(DEBUG) && !$(UNCHECKED)) && $(VCVERSION) >= 1900\r
+baselibs   = $(baselibs) ucrt.lib\r
+!endif\r
+\r
+################################################################\r
+# 13. Define standard commands, common make targets and implicit rules\r
+\r
+CCPKGCMD = $(cc32) $(pkgcflags) -Fo$(TMP_DIR)^\\r
+CCAPPCMD = $(cc32) $(appcflags) -Fo$(TMP_DIR)^\\r
+CCSTUBSCMD = $(cc32) $(stubscflags) -Fo$(TMP_DIR)^\\r
+\r
+LIBCMD = $(lib32) -nologo $(LINKERFLAGS) -out:$@\r
+DLLCMD = $(link32) $(dlllflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+\r
+CONEXECMD = $(link32) $(conlflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)\r
+RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
+           $(TCL_INCLUDES) \\r
+           /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
+           /DDOTVERSION=\"$(DOTVERSION)\" \\r
+           /DVERSION=\"$(VERSION)\" \\r
+           /DSUFX=\"$(SUFX)\" \\r
+           /DPROJECT=\"$(PROJECT)\" \\r
+           /DPRJLIBNAME=\"$(PRJLIBNAME)\"\r
+\r
+!ifndef DEFAULT_BUILD_TARGET\r
+DEFAULT_BUILD_TARGET = $(PROJECT)\r
+!endif\r
+\r
+default-target: $(DEFAULT_BUILD_TARGET)\r
+\r
+!if $(MULTIPLATFORM_INSTALL)\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!else\r
+default-pkgindex:\r
+       @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+!endif\r
+\r
+default-pkgindex-tea:\r
+       @if exist $(ROOT)\pkgIndex.tcl.in nmakehlp -s << $(ROOT)\pkgIndex.tcl.in > $(OUT_DIR)\pkgIndex.tcl\r
+@PACKAGE_VERSION@    $(DOTVERSION)\r
+@PACKAGE_NAME@       $(PRJ_PACKAGE_TCLNAME)\r
+@PACKAGE_TCLNAME@    $(PRJ_PACKAGE_TCLNAME)\r
+@PKG_LIB_FILE@       $(PRJLIBNAME)\r
+<<\r
+\r
+default-install: default-install-binaries default-install-libraries\r
+!if $(SYMBOLS)\r
+default-install: default-install-pdbs\r
+!endif\r
+\r
+# Again to deal with historical brokenness, there is some confusion\r
+# in terminlogy. For extensions, the "install-binaries" was used to\r
+# locate target directory for *binary shared libraries* and thus\r
+# the appropriate macro is LIB_INSTALL_DIR since BIN_INSTALL_DIR is\r
+# for executables (exes). On the other hand the "install-libraries"\r
+# target is for *scripts* and should have been called "install-scripts".\r
+default-install-binaries: $(PRJLIB)\r
+       @echo Installing binaries to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) $(PRJLIB) "$(LIB_INSTALL_DIR)" >NUL\r
+\r
+# Alias for default-install-scripts\r
+default-install-libraries: default-install-scripts\r
+\r
+default-install-scripts: $(OUT_DIR)\pkgIndex.tcl\r
+       @echo Installing libraries to '$(SCRIPT_INSTALL_DIR)'\r
+       @if exist $(LIBDIR) $(CPY) $(LIBDIR)\*.tcl "$(SCRIPT_INSTALL_DIR)"\r
+       @echo Installing package index in '$(SCRIPT_INSTALL_DIR)'\r
+       @$(CPY) $(OUT_DIR)\pkgIndex.tcl $(SCRIPT_INSTALL_DIR)\r
+\r
+default-install-stubs:\r
+       @echo Installing stubs library to '$(SCRIPT_INSTALL_DIR)'\r
+       @if not exist "$(SCRIPT_INSTALL_DIR)" mkdir "$(SCRIPT_INSTALL_DIR)"\r
+       @$(CPY) $(PRJSTUBLIB) "$(SCRIPT_INSTALL_DIR)" >NUL\r
+\r
+default-install-pdbs:\r
+       @echo Installing PDBs to '$(LIB_INSTALL_DIR)'\r
+       @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
+       @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
+\r
+# "emacs font-lock highlighting fix\r
+\r
+default-install-docs-html:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.html" "$(DOCDIR)\*.css" "$(DOCDIR)\*.png") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-docs-n:\r
+       @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
+       @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
+       @if exist $(DOCDIR) for %f in ("$(DOCDIR)\*.n") do @$(COPY) %f "$(DOC_INSTALL_DIR)"\r
+\r
+default-install-demos:\r
+       @echo Installing demos to '$(DEMO_INSTALL_DIR)'\r
+       @if not exist "$(DEMO_INSTALL_DIR)" mkdir "$(DEMO_INSTALL_DIR)"\r
+       @if exist $(DEMODIR) $(CPYDIR) "$(DEMODIR)" "$(DEMO_INSTALL_DIR)"\r
+\r
+default-clean:\r
+       @echo Cleaning $(TMP_DIR)\* ...\r
+       @if exist $(TMP_DIR)\nul $(RMDIR) $(TMP_DIR)\r
+       @echo Cleaning $(WIN_DIR)\nmakehlp.obj, nmakehlp.exe ...\r
+       @if exist $(WIN_DIR)\nmakehlp.obj del $(WIN_DIR)\nmakehlp.obj\r
+       @if exist $(WIN_DIR)\nmakehlp.exe del $(WIN_DIR)\nmakehlp.exe\r
+       @if exist $(WIN_DIR)\nmakehlp.out del $(WIN_DIR)\nmakehlp.out\r
+       @echo Cleaning $(WIN_DIR)\nmhlp-out.txt ...\r
+       @if exist $(WIN_DIR)\nmhlp-out.txt del $(WIN_DIR)\nmhlp-out.txt\r
+       @echo Cleaning $(WIN_DIR)\_junk.pch ...\r
+       @if exist $(WIN_DIR)\_junk.pch del $(WIN_DIR)\_junk.pch\r
+       @echo Cleaning $(WIN_DIR)\vercl.x, vercl.i ...\r
+       @if exist $(WIN_DIR)\vercl.x del $(WIN_DIR)\vercl.x\r
+       @if exist $(WIN_DIR)\vercl.i del $(WIN_DIR)\vercl.i\r
+       @echo Cleaning $(WIN_DIR)\versions.vc, version.vc ...\r
+       @if exist $(WIN_DIR)\versions.vc del $(WIN_DIR)\versions.vc\r
+       @if exist $(WIN_DIR)\version.vc del $(WIN_DIR)\version.vc\r
+\r
+default-hose: default-clean\r
+       @echo Hosing $(OUT_DIR)\* ...\r
+       @if exist $(OUT_DIR)\nul $(RMDIR) $(OUT_DIR)\r
+\r
+# Only for backward compatibility\r
+default-distclean: default-hose\r
+\r
+default-setup:\r
+       @if not exist $(OUT_DIR)\nul mkdir $(OUT_DIR)\r
+       @if not exist $(TMP_DIR)\nul mkdir $(TMP_DIR)\r
+\r
+!if "$(TESTPAT)" != ""\r
+TESTFLAGS = $(TESTFLAGS) -file $(TESTPAT)\r
+!endif\r
+\r
+default-test: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       cd "$(TESTDIR)" && $(DEBUGGER) $(TCLSH) all.tcl $(TESTFLAGS)\r
+\r
+default-shell: default-setup $(PROJECT)\r
+       @set TCLLIBPATH=$(OUT_DIR:\=/)\r
+       @if exist $(LIBDIR) for %f in ("$(LIBDIR)\*.tcl") do @$(COPY) %f "$(OUT_DIR)"\r
+       $(DEBUGGER) $(TCLSH)\r
+\r
+# Generation of Windows version resource\r
+!ifdef RCFILE\r
+\r
+# Note: don't use $** in below rule because there may be other dependencies\r
+# and only the "main" rc must be passed to the resource compiler\r
+$(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
+       $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
+\r
+!else\r
+\r
+# If parent makefile has not defined a resource definition file,\r
+# we will generate one from standard template.\r
+$(TMP_DIR)\$(PROJECT).res: $(TMP_DIR)\$(PROJECT).rc\r
+\r
+$(TMP_DIR)\$(PROJECT).rc:\r
+       @$(COPY) << $(TMP_DIR)\$(PROJECT).rc\r
+#include <winver.h>\r
+\r
+VS_VERSION_INFO VERSIONINFO\r
+ FILEVERSION   COMMAVERSION\r
+ PRODUCTVERSION        COMMAVERSION\r
+ FILEFLAGSMASK 0x3fL\r
+#ifdef DEBUG\r
+ FILEFLAGS     VS_FF_DEBUG\r
+#else\r
+ FILEFLAGS     0x0L\r
+#endif\r
+ FILEOS                VOS_NT_WINDOWS32\r
+ FILETYPE      VFT_DLL\r
+ FILESUBTYPE   0x0L\r
+BEGIN\r
+    BLOCK "StringFileInfo"\r
+    BEGIN\r
+        BLOCK "040904b0"\r
+        BEGIN\r
+            VALUE "FileDescription",  "Tcl extension " PROJECT\r
+            VALUE "OriginalFilename", PRJLIBNAME\r
+            VALUE "FileVersion",      DOTVERSION\r
+            VALUE "ProductName",      "Package " PROJECT " for Tcl"\r
+            VALUE "ProductVersion",   DOTVERSION\r
+        END\r
+    END\r
+    BLOCK "VarFileInfo"\r
+    BEGIN\r
+        VALUE "Translation", 0x409, 1200\r
+    END\r
+END\r
+\r
+<<\r
+\r
+!endif # ifdef RCFILE\r
+\r
+!ifndef DISABLE_IMPLICIT_RULES\r
+DISABLE_IMPLICIT_RULES = 0\r
+!endif\r
+\r
+!if !$(DISABLE_IMPLICIT_RULES)\r
+# Implicit rule definitions - only for building library objects. For stubs and\r
+# main application, the makefile should define explicit rules.\r
+\r
+{$(ROOT)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(WIN_DIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(GENERICDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(COMPATDIR)}.c{$(TMP_DIR)}.obj::\r
+       $(CCPKGCMD) @<<\r
+$<\r
+<<\r
+\r
+{$(RCDIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(WIN_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+{$(TMP_DIR)}.rc{$(TMP_DIR)}.res:\r
+       $(RESCMD) $<\r
+\r
+.SUFFIXES:\r
+.SUFFIXES:.c .rc\r
+\r
+!endif\r
+\r
+################################################################\r
+# 14. Sanity check selected options against Tcl build options\r
+# When building an extension, certain configuration options should\r
+# match the ones used when Tcl was built. Here we check and\r
+# warn on a mismatch.\r
+!if !$(DOING_TCL)\r
+\r
+!if $(TCLINSTALL) # Building against an installed Tcl\r
+!if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
+!endif\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
+!endif\r
+!endif # TCLINSTALL\r
+\r
+!if $(CONFIG_CHECK)\r
+!ifdef TCLNMAKECONFIG\r
+!include $(TCLNMAKECONFIG)\r
+\r
+!if defined(CORE_MACHINE) && "$(CORE_MACHINE)" != "$(MACHINE)"\r
+!error ERROR: Build target ($(MACHINE)) does not match the Tcl library architecture ($(CORE_MACHINE)).\r
+!endif\r
+!if $(TCL_VERSION) < 87 && defined(CORE_USE_THREAD_ALLOC) && $(CORE_USE_THREAD_ALLOC) != $(USE_THREAD_ALLOC)\r
+!message WARNING: Value of USE_THREAD_ALLOC ($(USE_THREAD_ALLOC)) does not match its Tcl core value ($(CORE_USE_THREAD_ALLOC)).\r
+!endif\r
+!if defined(CORE_DEBUG) && $(CORE_DEBUG) != $(DEBUG)\r
+!message WARNING: Value of DEBUG ($(DEBUG)) does not match its Tcl library configuration ($(DEBUG)).\r
+!endif\r
+!endif\r
+\r
+!endif # TCLNMAKECONFIG\r
+\r
+!endif # !$(DOING_TCL)\r
+\r
+\r
+#----------------------------------------------------------\r
+# Display stats being used.\r
+#----------------------------------------------------------\r
+\r
+!if !$(DOING_TCL)\r
+!message *** Building against Tcl at '$(_TCLDIR)'\r
+!endif\r
+!if !$(DOING_TK) && $(NEED_TK)\r
+!message *** Building against Tk at '$(_TKDIR)'\r
+!endif\r
+!message *** Intermediate directory will be '$(TMP_DIR)'\r
+!message *** Output directory will be '$(OUT_DIR)'\r
+!message *** Installation, if selected, will be in '$(_INSTALLDIR)'\r
+!message *** Suffix for binaries will be '$(SUFX)'\r
+!message *** Compiler version $(VCVER). Target $(MACHINE), host $(NATIVE_ARCH).\r
+\r
+!endif # ifdef _RULES_VC\r
diff --git a/pkgs/thread2.8.6/win/targets.vc b/pkgs/thread2.8.6/win/targets.vc
new file mode 100644 (file)
index 0000000..077e8f7
--- /dev/null
@@ -0,0 +1,98 @@
+#------------------------------------------------------------- -*- makefile -*-\r
+# targets.vc --\r
+#\r
+# Part of the nmake based build system for Tcl and its extensions.\r
+# This file defines some standard targets for the convenience of extensions\r
+# and can be optionally included by the extension makefile.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
+\r
+$(PROJECT): setup pkgindex $(PRJLIB)\r
+\r
+!ifdef PRJ_STUBOBJS\r
+$(PROJECT): $(PRJSTUBLIB)\r
+$(PRJSTUBLIB): $(PRJ_STUBOBJS)\r
+       $(LIBCMD) $**\r
+\r
+$(PRJ_STUBOBJS):\r
+       $(CCSTUBSCMD) %s\r
+!endif # PRJ_STUBOBJS\r
+\r
+!ifdef PRJ_MANIFEST\r
+$(PROJECT): $(PRJLIB).manifest\r
+$(PRJLIB).manifest: $(PRJ_MANIFEST)\r
+       @nmakehlp -s << $** >$@\r
+@MACHINE@        $(MACHINE:IX86=X86)\r
+<<\r
+!endif\r
+\r
+!if "$(PROJECT)" != "tcl" && "$(PROJECT)" != "tk"\r
+$(PRJLIB): $(PRJ_OBJS) $(RESFILE)\r
+!if $(STATIC_BUILD)\r
+       $(LIBCMD) $**\r
+!else\r
+       $(DLLCMD) $**\r
+       $(_VC_MANIFEST_EMBED_DLL)\r
+!endif\r
+       -@del $*.exp\r
+!endif\r
+\r
+!if "$(PRJ_HEADERS)" != "" && "$(PRJ_OBJS)" != ""\r
+$(PRJ_OBJS): $(PRJ_HEADERS)\r
+!endif\r
+\r
+# If parent makefile has defined stub objects, add their installation\r
+# to the default install\r
+!if "$(PRJ_STUBOBJS)" != ""\r
+default-install: default-install-stubs\r
+!endif\r
+\r
+# Unlike the other default targets, these cannot be in rules.vc because\r
+# the executed command depends on existence of macro PRJ_HEADERS_PUBLIC\r
+# that the parent makefile will not define until after including rules-ext.vc\r
+!if "$(PRJ_HEADERS_PUBLIC)" != ""\r
+default-install: default-install-headers\r
+default-install-headers:\r
+       @echo Installing headers to '$(INCLUDE_INSTALL_DIR)'\r
+       @for %f in ($(PRJ_HEADERS_PUBLIC)) do @$(COPY) %f "$(INCLUDE_INSTALL_DIR)"\r
+!endif\r
+\r
+!if "$(DISABLE_STANDARD_TARGETS)" == ""\r
+DISABLE_STANDARD_TARGETS = 0\r
+!endif\r
+\r
+!if "$(DISABLE_TARGET_setup)" == ""\r
+DISABLE_TARGET_setup = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_install)" == ""\r
+DISABLE_TARGET_install = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_clean)" == ""\r
+DISABLE_TARGET_clean = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_test)" == ""\r
+DISABLE_TARGET_test = 0\r
+!endif\r
+!if "$(DISABLE_TARGET_shell)" == ""\r
+DISABLE_TARGET_shell = 0\r
+!endif\r
+\r
+!if !$(DISABLE_STANDARD_TARGETS)\r
+!if !$(DISABLE_TARGET_setup)\r
+setup: default-setup\r
+!endif\r
+!if !$(DISABLE_TARGET_install)\r
+install: default-install\r
+!endif\r
+!if !$(DISABLE_TARGET_clean)\r
+clean: default-clean\r
+realclean: hose\r
+hose: default-hose\r
+distclean: realclean default-distclean\r
+!endif\r
+!if !$(DISABLE_TARGET_test)\r
+test: default-test\r
+!endif\r
+!if !$(DISABLE_TARGET_shell)\r
+shell: default-shell\r
+!endif\r
+!endif # DISABLE_STANDARD_TARGETS\r
index ce2382e..e86100f 100644 (file)
@@ -59,7 +59,7 @@ should correspond to the Tcl or C code file that they are testing.
 For example, the test file for the C file "tclCmdAH.c" is
 "cmdAH.test".  Test files that contain black-box tests may not
 correspond to any Tcl or C code file so they should match the pattern
-"*_bb.test". 
+"*_bb.test".
 
 Be sure your new test file can be run from any working directory.
 
@@ -72,12 +72,12 @@ as well as an installation environment.  If your test file contains
 tests that should not be run in one or more of those cases, please use
 the constraints mechanism to skip those tests.
 
-4. Incompatibilities of package tcltest 2.1 with 
+4. Incompatibilities of package tcltest 2.1 with
    testing machinery of very old versions of Tcl:
 ------------------------------------------------
 
 1) Global variables such as VERBOSE, TESTS, and testConfig of the
-   old machinery correspond to the [configure -verbose], 
+   old machinery correspond to the [configure -verbose],
    [configure -match], and [testConstraint] commands of tcltest 2.1,
    respectively.
 
index 3ba5167..d4d2a7c 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 52c8763..5ac2abb 100644 (file)
@@ -10,7 +10,6 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package prefer latest
 package require Tcl 8.5-
 package require tcltest 2.5
 namespace import ::tcltest::*
index 8fa4e61..0b06c8f 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 unset -nocomplain x
@@ -32,7 +32,7 @@ test append-1.3 {append command} {
 
 test append-2.1 {long appends} {
     set x ""
-    for {set i 0} {$i < 1000} {set i [expr $i+1]} {
+    for {set i 0} {$i < 1000} {incr i} {
        append x "foobar "
     }
     set y "foobar"
@@ -158,7 +158,7 @@ test append-5.1 {long lappends} -setup {
        if {$l != $size} {
            return "length mismatch: should have been $size, was $l"
        }
-       for {set i 0} {$i < $size} {set i [expr $i+1]} {
+       for {set i 0} {$i < $size} {incr i} {
            set j [lindex $var $i]
            if {$j ne "item $i"} {
                return "element $i should have been \"item $i\", was \"$j\""
index bbf5f9c..a6e78d2 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 catch {unset x}
@@ -41,7 +41,7 @@ test appendComp-1.3 {append command} {
 test appendComp-2.1 {long appends} {
     proc foo {} {
        set x ""
-       for {set i 0} {$i < 1000} {set i [expr $i+1]} {
+       for {set i 0} {$i < 1000} {incr i} {
            append x "foobar "
        }
        set y "foobar"
@@ -223,7 +223,7 @@ test appendComp-5.1 {long lappends} -setup {
     }
 } -body {
     set x ""
-    for {set i 0} {$i < 300} {set i [expr $i+1]} {
+    for {set i 0} {$i < 300} {incr i} {
        lappend x "item $i"
     }
     check $x 300
@@ -359,9 +359,9 @@ test appendComp-7.9 {append var does not trigger read trace} -setup {
 } -result {0}
 
 test appendComp-8.1 {defer error to runtime} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave eval {
+    child eval {
        proc foo {} {
            proc append args {}
            append
@@ -369,7 +369,7 @@ test appendComp-8.1 {defer error to runtime} -setup {
        foo
     }
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {}
 
 # New tests for bug 3057639 to show off the more consistent behaviour of
index ba19b81..0a64aa0 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2.2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -25,7 +25,7 @@ testConstraint memory [llength [info commands memory]]
 \f
 # Tests for wrong number of arguments
 
-test apply-1.1 {too few arguments} -returnCodes error -body {
+test apply-1.1 {not enough arguments} -returnCodes error -body {
     apply
 } -result {wrong # args: should be "apply lambdaExpr ?arg ...?"}
 
index 40c132d..d2e626b 100644 (file)
@@ -12,7 +12,7 @@
 # Commands covered: assemble
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2.2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 namespace eval tcl::unsupported {namespace export assemble}
@@ -1535,61 +1535,35 @@ test assemble-14.7 {incrArrayStkImm} {
 
 # assemble-15 - listIndexImm
 
-test assemble-15.1 {listIndexImm - wrong # args} {
-    -body {
-       assemble {listIndexImm}
-    }
-    -returnCodes error
-    -match glob
-    -result {wrong # args*}
-}
-test assemble-15.2 {listIndexImm - wrong # args} {
-    -body {
-       assemble {listIndexImm too many}
-    }
-    -returnCodes error
-    -match glob
-    -result {wrong # args*}
-}
-test assemble-15.3 {listIndexImm - bad substitution} {
-    -body {
-       list [catch {assemble {listIndexImm $foo}} result] $result $::errorCode
-    }
-    -result {1 {assembly code may not contain substitutions} {TCL ASSEM NOSUBST}}
-    -cleanup {unset result}
-}
-test assemble-15.4 {listIndexImm - invalid index} {
-    -body {
-       assemble {listIndexImm rubbish}
-    }
-    -returnCodes error
-    -match glob
-    -result {bad index "rubbish"*}
-}
-test assemble-15.5 {listIndexImm} {
-    -body {
-       assemble {push {a b c}; listIndexImm 2}
-    }
-    -result c
-}
-test assemble-15.6 {listIndexImm} {
-    -body {
-       assemble {push {a b c}; listIndexImm end-1}
-    }
-    -result b
-}
-test assemble-15.7 {listIndexImm} {
-    -body {
-       assemble {push {a b c}; listIndexImm end}
-    }
-    -result c
-}
-test assemble-15.8 {listIndexImm} {
+test assemble-15.1 {listIndexImm - wrong # args} -body {
+    assemble {listIndexImm}
+} -returnCodes error -match glob -result {wrong # args*}
+test assemble-15.2 {listIndexImm - wrong # args} -body {
+    assemble {listIndexImm too many}
+} -returnCodes error -match glob -result {wrong # args*}
+test assemble-15.3 {listIndexImm - bad substitution} -body {
+    list [catch {assemble {listIndexImm $foo}} result] $result $::errorCode
+} -cleanup {
+    unset result
+} -result {1 {assembly code may not contain substitutions} {TCL ASSEM NOSUBST}}
+test assemble-15.4 {listIndexImm - invalid index} -body {
+    assemble {listIndexImm rubbish}
+} -returnCodes error -match glob -result {bad index "rubbish"*}
+test assemble-15.5 {listIndexImm} -body {
+    assemble {push {a b c}; listIndexImm 2}
+} -result c
+test assemble-15.6 {listIndexImm} -body {
+    assemble {push {a b c}; listIndexImm end-1}
+} -result b
+test assemble-15.7 {listIndexImm} -body {
+    assemble {push {a b c}; listIndexImm end}
+} -result c
+test assemble-15.8 {listIndexImm} -body {
     assemble {push {a b c}; listIndexImm end+2}
-} {}
-test assemble-15.9 {listIndexImm} {
+} -result {}
+test assemble-15.9 {listIndexImm} -body {
     assemble {push {a b c}; listIndexImm -1-1}
-} {}
+} -result {}
 
 # assemble-16 - invokeStk
 
index edf55c4..863bf78 100644 (file)
@@ -11,7 +11,7 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+package require tcltest 2.5
 namespace import ::tcltest::*
 
 ::tcltest::loadTestedCommands
index 4e7eadf..86527bf 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -21,7 +21,7 @@ catch [list package require -exact Tcltest [info patchlevel]]
 
 testConstraint testasync [llength [info commands testasync]]
 testConstraint threaded [::tcl::pkgconfig get threaded]
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+testConstraint notWinCI [expr {$::tcl_platform(platform) != "windows" || ![info exists ::env(CI)]}]
 
 proc async1 {result code} {
     global aresult acode
@@ -204,7 +204,7 @@ test async-4.2 {async interrupting straight bytecode sequence} -constraints {
     testasync delete $hm
 }
 test async-4.3 {async interrupting loop-less bytecode sequence} -constraints {
-    testasync threaded knownMsvcBug
+    testasync threaded notWinCI
 } -setup {
     set hm [testasync create async3]
 } -body {
diff --git a/tests/auto0/auto1/file1.tcl b/tests/auto0/auto1/file1.tcl
new file mode 100644 (file)
index 0000000..bd8b92b
--- /dev/null
@@ -0,0 +1,3 @@
+proc report1 {args} {
+    return ok1
+}
diff --git a/tests/auto0/auto1/package1.tcl b/tests/auto0/auto1/package1.tcl
new file mode 100644 (file)
index 0000000..32d7c56
--- /dev/null
@@ -0,0 +1,5 @@
+proc HeresPackage1 {args} {
+    return OK1
+}
+
+package provide SafeTestPackage1 1.2.3
diff --git a/tests/auto0/auto1/pkgIndex.tcl b/tests/auto0/auto1/pkgIndex.tcl
new file mode 100644 (file)
index 0000000..babb6d5
--- /dev/null
@@ -0,0 +1,11 @@
+# Tcl package index file, version 1.1
+# This file is generated by the "pkg_mkIndex" command
+# and sourced either when an application starts up or
+# by a "package unknown" script.  It invokes the
+# "package ifneeded" command to set up package-related
+# information so that packages will be loaded automatically
+# in response to "package require" commands.  When this
+# script is sourced, the variable $dir must contain the
+# full path name of this file's directory.
+
+package ifneeded SafeTestPackage1 1.2.3 [list source [file join $dir package1.tcl]]
diff --git a/tests/auto0/auto1/tclIndex b/tests/auto0/auto1/tclIndex
new file mode 100644 (file)
index 0000000..bbfa6d4
--- /dev/null
@@ -0,0 +1,9 @@
+# Tcl autoload index file, version 2.0
+# This file is generated by the "auto_mkindex" command
+# and sourced to set up indexing information for one or
+# more commands.  Typically each line is a command that
+# sets an element in the auto_index array, where the
+# element name is the name of a command and the value is
+# a script that loads the command.
+
+set auto_index(report1) [list source [file join $dir file1.tcl]]
diff --git a/tests/auto0/auto2/file2.tcl b/tests/auto0/auto2/file2.tcl
new file mode 100644 (file)
index 0000000..5bc622f
--- /dev/null
@@ -0,0 +1,3 @@
+proc report2 {args} {
+    return ok2
+}
diff --git a/tests/auto0/auto2/package2.tcl b/tests/auto0/auto2/package2.tcl
new file mode 100644 (file)
index 0000000..61774df
--- /dev/null
@@ -0,0 +1,5 @@
+proc HeresPackage2 {args} {
+    return OK2
+}
+
+package provide SafeTestPackage2 2.3.4
diff --git a/tests/auto0/auto2/pkgIndex.tcl b/tests/auto0/auto2/pkgIndex.tcl
new file mode 100644 (file)
index 0000000..1022691
--- /dev/null
@@ -0,0 +1,11 @@
+# Tcl package index file, version 1.1
+# This file is generated by the "pkg_mkIndex" command
+# and sourced either when an application starts up or
+# by a "package unknown" script.  It invokes the
+# "package ifneeded" command to set up package-related
+# information so that packages will be loaded automatically
+# in response to "package require" commands.  When this
+# script is sourced, the variable $dir must contain the
+# full path name of this file's directory.
+
+package ifneeded SafeTestPackage2 2.3.4 [list source [file join $dir package2.tcl]]
diff --git a/tests/auto0/auto2/tclIndex b/tests/auto0/auto2/tclIndex
new file mode 100644 (file)
index 0000000..9cd2a74
--- /dev/null
@@ -0,0 +1,9 @@
+# Tcl autoload index file, version 2.0
+# This file is generated by the "auto_mkindex" command
+# and sourced to set up indexing information for one or
+# more commands.  Typically each line is a command that
+# sets an element in the auto_index array, where the
+# element name is the name of a command and the value is
+# a script that loads the command.
+
+set auto_index(report2) [list source [file join $dir file2.tcl]]
diff --git a/tests/auto0/modules/mod1/test1-1.0.tm b/tests/auto0/modules/mod1/test1-1.0.tm
new file mode 100644 (file)
index 0000000..927fa6f
--- /dev/null
@@ -0,0 +1,5 @@
+namespace eval mod1::test1 {}
+
+proc mod1::test1::try1 args {
+    return res1
+}
diff --git a/tests/auto0/modules/mod2/test2-2.0.tm b/tests/auto0/modules/mod2/test2-2.0.tm
new file mode 100644 (file)
index 0000000..b5cd45b
--- /dev/null
@@ -0,0 +1,5 @@
+namespace eval mod2::test2 {}
+
+proc mod2::test2::try2 args {
+    return res2
+}
diff --git a/tests/auto0/modules/test0-0.5.tm b/tests/auto0/modules/test0-0.5.tm
new file mode 100644 (file)
index 0000000..19f3613
--- /dev/null
@@ -0,0 +1,5 @@
+namespace eval test0 {}
+
+proc test0::try0 args {
+    return res0
+}
index 4721553..6adb403 100644 (file)
@@ -10,7 +10,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -40,8 +40,8 @@ namespace import -force blt::*
 # Should be able to handle "proc" definitions, even if they are preceded by
 # white space.
 
-proc normal {x y} {return [expr $x+$y]}
-  proc indented {x y} {return [expr $x+$y]}
+proc normal {x y} {return [expr {$x+$y}]}
+  proc indented {x y} {return [expr {$x+$y}]}
 
 #
 # Should be able to handle proc declarations within namespaces, even if they
@@ -146,10 +146,10 @@ test autoMkindex-1.3 {examine tclIndex} -setup {
 
 test autoMkindex-2.1 {commands on the autoload path can be imported} -setup {
     file delete tclIndex
-    interp create slave
+    interp create child
 } -body {
     auto_mkindex . autoMkindex.tcl
-    slave eval {
+    child eval {
         namespace eval blt {}
         set auto_path [linsert $auto_path 0 .]
         set info [list [catch {namespace import buried::*} result] $result]
@@ -159,7 +159,7 @@ test autoMkindex-2.1 {commands on the autoload path can be imported} -setup {
         return $info
     }
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result "0 {} pub_one ::buried::pub_one pub_two ::buried::pub_two"
 
 # Test auto_mkindex hooks
@@ -180,7 +180,7 @@ test autoMkindex-3.1 {slaveHook} -setup {
 } -cleanup {
     # Reset initCommands to avoid trashing other tests
     AutoMkindexTestReset
-} -result 1 
+} -result 1
 # The auto_mkindex_parser::command is used to register commands that create
 # new commands.
 test autoMkindex-3.2 {auto_mkindex_parser::command} -setup {
@@ -335,14 +335,14 @@ test autoMkindex-5.2 {correctly locate auto loaded procs with []} -setup {
        proc {[magic mojo proc]} {} {}
     } [file join pkg magicchar2.tcl]
     set result {}
-    interp create slave
+    interp create child
 } -body {
     auto_mkindex . pkg/magicchar2.tcl
-    # Make a slave interp to test the autoloading
-    slave eval {lappend auto_path [pwd]}
-    slave eval {catch {{[magic mojo proc]}}}
+    # Make a child interp to test the autoloading
+    child eval {lappend auto_path [pwd]}
+    child eval {catch {{[magic mojo proc]}}}
 } -cleanup {
-    interp delete slave
+    interp delete child
     removeFile [file join pkg magicchar2.tcl]
     removeDirectory pkg
 } -result 0
index 5066877..bf2b08f 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
@@ -256,7 +258,7 @@ test basic-18.1 {TclRenameCommand, name of existing cmd can have namespace quali
     }
     list [test_ns_basic::p] \
          [rename test_ns_basic::p test_ns_basic::q] \
-         [test_ns_basic::q] 
+         [test_ns_basic::q]
 } {{p in ::test_ns_basic} {} {p in ::test_ns_basic}}
 test basic-18.2 {TclRenameCommand, existing cmd must be found} {
     catch {namespace delete {*}[namespace children :: test_ns_*]}
@@ -469,11 +471,11 @@ test basic-26.2 {Tcl_EvalObjEx, pure-list branch: preserve "objv"} -body {
     #   a - the pure-list internal rep is destroyed by shimmering
     #   b - the command returns an error
     # As the error code in Tcl_EvalObjv accesses the list elements, this will
-    # cause a segfault if [Bug 1119369] has not been fixed. 
+    # cause a segfault if [Bug 1119369] has not been fixed.
     # NOTE: a MEM_DEBUG build may be necessary to guarantee the segfault.
     #
 
-    set SRC [list foo 1] ;# pure-list command 
+    set SRC [list foo 1] ;# pure-list command
     proc foo str {
        # Shimmer pure-list to cmdName, cleanup and error
        proc $::SRC {} {}; $::SRC
@@ -491,11 +493,11 @@ test basic-26.3 {Tcl_EvalObjEx, pure-list branch: preserve "objv"} -body {
     # Follow the pure-list branch in a manner that
     #   a - the pure-list internal rep is destroyed by shimmering
     #   b - the command accesses its command line
-    # This will cause a segfault if [Bug 1119369] has not been fixed. 
+    # This will cause a segfault if [Bug 1119369] has not been fixed.
     # NOTE: a MEM_DEBUG build may be necessary to guarantee the segfault.
     #
 
-    set SRC [list foo 1] ;# pure-list command 
+    set SRC [list foo 1] ;# pure-list command
     proc foo str {
        # Shimmer pure-list to cmdName, cleanup and error
        proc $::SRC {} {}; $::SRC
@@ -607,7 +609,7 @@ test basic-46.2 {Tcl_AllowExceptions: exception return not allowed} -setup {
 invoked "break" outside of a loop
     while executing
 "break"
-    (file "*BREAKtest" line 3)}    
+    (file "*BREAKtest" line 3)}
 
 test basic-46.3 {Tcl_AllowExceptions: exception return not allowed} -setup {
     set fName [makeFile {
@@ -624,7 +626,7 @@ test basic-46.3 {Tcl_AllowExceptions: exception return not allowed} -setup {
 } -returnCodes error -match glob -result {invoked "break" outside of a loop
     while executing
 "break"
-    (file "*BREAKtest" line 4)}    
+    (file "*BREAKtest" line 4)}
 
 test basic-46.4 {Tcl_AllowExceptions: exception return not allowed} -setup {
     set fName [makeFile {
@@ -672,7 +674,7 @@ proc l3 {} {
 # Do all tests once byte compiled and once with direct string evaluation
 for {set noComp 0} {$noComp <= 1} {incr noComp} {
 
-if $noComp {
+if {$noComp} {
     interp alias {} run {} testevalex
     set constraints testevalex
 } else {
@@ -752,7 +754,7 @@ test basic-48.1.$noComp {expansion: parsing} $constraints {
                # Another comment
                list 1  2\
                        3   {*}$::l1
-            
+
                # Comment again
        }
 } {1 2 3 a {b b} c d}
@@ -825,7 +827,7 @@ test basic-48.13.$noComp {expansion: odd usage} $constraints {
 test basic-48.14.$noComp {expansion: hash command} -setup {
         catch {rename \# ""}
         set cmd "#"
-    } -constraints $constraints -body { 
+    } -constraints $constraints -body {
            run { {*}$cmd apa bepa }
     } -cleanup {
        unset cmd
@@ -885,7 +887,7 @@ test basic-48.16.$noComp {expansion: testing for leaks} -setup {
             stress
             set tmp $end
             set end [getbytes]
-        }    
+        }
         set leak [expr {$end - $tmp}]
     } -cleanup {
        unset end i tmp
@@ -896,7 +898,7 @@ test basic-48.16.$noComp {expansion: testing for leaks} -setup {
 test basic-48.17.$noComp {expansion: object safety} -setup {
         set old_precision $::tcl_precision
         set ::tcl_precision 4
-    } -constraints $constraints -body { 
+    } -constraints $constraints -body {
             set third [expr {1.0/3.0}]
             set l [list $third $third]
             set x [run {list $third {*}$l $third}]
@@ -1003,13 +1005,13 @@ test basic-49.2 {Tcl_EvalEx: verify TCL_EVAL_GLOBAL operation} testevalex {
 } {global}
 
 test basic-50.1 {[586e71dce4] EvalObjv level #0 exception handling} -setup {
-    interp create slave
-    interp alias {} foo slave return
+    interp create child
+    interp alias {} foo child return
 } -body {
     list [catch foo m] $m
 } -cleanup {
     unset -nocomplain m
-    interp delete slave
+    interp delete child
 } -result {0 {}}
 
 # Clean up after expand tests
index 8c1dedb..07ecf6f 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 testConstraint bigEndian [expr {$tcl_platform(byteOrder) eq "bigEndian"}]
@@ -2624,6 +2624,9 @@ test binary-72.27 {binary encode base64} -body {
 test binary-72.28 {binary encode base64} -body {
     binary encode base64 -maxlen 6 -wrapchar 0123456789 abcabcabc
 } -result {YWJjYW0123456789JjYWJj}
+test binary-72.29 {binary encode base64} {
+    string length [binary encode base64 -maxlen 3 -wrapchar \xca abc]
+} 5
 
 test binary-73.1 {binary decode base64} -body {
     binary decode base64
@@ -2637,19 +2640,19 @@ test binary-73.3 {binary decode base64} -body {
 test binary-73.4 {binary decode base64} -body {
     binary decode base64 [string repeat YWJj 20]
 } -result [string repeat abc 20]
-test binary-73.5 {binary encode base64} -body {
+test binary-73.5 {binary decode base64} -body {
     binary decode base64 AAECAwQAAQID
 } -result "\0\1\2\3\4\0\1\2\3"
-test binary-73.6 {binary encode base64} -body {
+test binary-73.6 {binary decode base64} -body {
     binary decode base64 AA==
 } -result "\0"
-test binary-73.7 {binary encode base64} -body {
+test binary-73.7 {binary decode base64} -body {
     binary decode base64 AAA=
 } -result "\0\0"
-test binary-73.8 {binary encode base64} -body {
+test binary-73.8 {binary decode base64} -body {
     binary decode base64 AAAA
 } -result "\0\0\0"
-test binary-73.9 {binary encode base64} -body {
+test binary-73.9 {binary decode base64} -body {
     binary decode base64 AAAAAA==
 } -result "\0\0\0\0"
 test binary-73.10 {binary decode base64} -body {
@@ -2709,7 +2712,7 @@ test binary-73.30 {binary decode base64} -body {
     list [string length [set r [binary decode base64 -strict WFla\n]]] $r
 } -returnCodes error -match glob -result {invalid base64 character *}
 test binary-73.31 {binary decode base64} -body {
-    list [string length [set r [binary decode base64 WA==WFla]]] $r
+    list [string length [set r [binary decode base64 -strict WA==WFla]]] $r
 } -returnCodes error -match glob -result {invalid base64 character *}
 test binary-73.32 {binary decode base64, bug [00d04c4f12]} -body {
     list \
@@ -2751,6 +2754,9 @@ test binary-73.36 {binary decode base64: check encoded & decoded equals original
     }
     join $r \n
 } -result {}
+test binary-73.37 {binary decode base64: Bug ffeb2097af} {
+    binary decode base64 [binary encode base64 -maxlen 3 -wrapchar : abc]
+} abc
 
 test binary-74.1 {binary encode uuencode} -body {
     binary encode uuencode
@@ -2788,11 +2794,17 @@ test binary-74.10 {binary encode uuencode} -returnCodes error -body {
     binary encode uuencode -foo 30 abcabcabc
 } -result {bad option "-foo": must be -maxlen or -wrapchar}
 test binary-74.11 {binary encode uuencode} -returnCodes error -body {
-    binary encode uuencode -maxlen 1 abcabcabc
+    binary encode uuencode -maxlen 4 abcabcabc
 } -result {line length out of range}
 test binary-74.12 {binary encode uuencode} -body {
-    binary encode uuencode -maxlen 3 -wrapchar | abcabcabc
-} -result {!80|!8@|!8P|!80|!8@|!8P|!80|!8@|!8P|}
+    binary encode uuencode -maxlen 5 -wrapchar \t abcabcabc
+} -result #86)C\t#86)C\t#86)C\t
+test binary-74.13 {binary encode uuencode} -body {
+    binary encode uuencode -maxlen 85 -wrapchar \t abcabcabc
+} -result )86)C86)C86)C\t
+test binary-74.14 {binary encode uuencode} -returnCodes error -body {
+    binary encode uuencode -maxlen 86 abcabcabc
+} -result {line length out of range}
 
 test binary-75.1 {binary decode uuencode} -body {
     binary decode uuencode
@@ -2889,6 +2901,17 @@ test binary-76.2 {binary string appending growth algorithm} win {
     # Append to it
     string length [append str [binary format a* foo]]
 } 3
+
+testConstraint testsetbytearraylength \
+               [expr {"testsetbytearraylength" in [info commands]}]
+
+test binary-79.1 {Tcl_SetByteArrayLength} testsetbytearraylength {
+    testsetbytearraylength [string cat A B C] 1
+} A
+test binary-79.2 {Tcl_SetByteArrayLength} testsetbytearraylength {
+    testsetbytearraylength [string cat \u0141 B C] 1
+} A
+
 \f
 # ----------------------------------------------------------------------
 # cleanup
index 6d63cea..d32d7d3 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index d8390e2..49afdc6 100644 (file)
@@ -7,8 +7,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -173,7 +173,7 @@ test chan-16.9 {chan command: pending input subcommand} -setup {
 
         lappend ::chan-16.9-data $r $l $e $b $i
 
-        if {$r != -1 || $e || $l || !$b || $i > 128} {
+        if {$r >= 0 || $e || $l || !$b || $i > 128} {
             set data [read $sock $i]
             lappend ::chan-16.9-data [string range $data 0 2]
             lappend ::chan-16.9-data [string range $data end-2 end]
index 85d7c44..5381a88 100644 (file)
@@ -13,9 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-# TODO: This test is likely worthless. Confirm and remove
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
 }
 
 namespace eval ::tcl::test::io {
@@ -39,11 +38,13 @@ namespace eval ::tcl::test::io {
 
     testConstraint testbytestring   [llength [info commands testbytestring]]
     testConstraint testchannel      [llength [info commands testchannel]]
-    testConstraint openpipe         1
     testConstraint testfevent       [llength [info commands testfevent]]
     testConstraint testchannelevent [llength [info commands testchannelevent]]
     testConstraint testmainthread   [llength [info commands testmainthread]]
-    testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+    testConstraint testservicemode  [llength [info commands testservicemode]]
+    testConstraint notWinCI       [expr {
+       $::tcl_platform(platform) ne "windows" || ![info exists ::env(CI)]}]
+    testConstraint notOSX [expr {$::tcl_platform(os) ne "Darwin"}]
 
     # You need a *very* special environment to do some tests.  In particular,
     # many file systems do not support large-files...
@@ -448,7 +449,7 @@ test chan-io-6.6 {Tcl_GetsObj: loop test} -body {
 } -cleanup {
     chan close $f
 } -result [list 256 $a]
-test chan-io-6.7 {Tcl_GetsObj: error in input} -constraints {stdio openpipe} -body {
+test chan-io-6.7 {Tcl_GetsObj: error in input} -constraints stdio -body {
     # if (FilterInputBytes(chanPtr, &gs) != 0)
     set f [openpipe w+ $path(cat)]
     chan puts -nonewline $f "hi\nwould"
@@ -709,7 +710,7 @@ test chan-io-6.30 {Tcl_GetsObj: crlf mode: buffer exhausted} -constraints {testc
 } -result [list 15 "123456789012345" 15]
 test chan-io-6.31 {Tcl_GetsObj: crlf mode: buffer exhausted, blocked} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # (FilterInputBytes() != 0)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {crlf lf} -buffering none
@@ -849,7 +850,7 @@ test chan-io-6.42 {Tcl_GetsObj: auto mode: several chars} -setup {
 } -result {4 abcd 4 efgh 4 ijkl 4 mnop -1 {}}
 test chan-io-6.43 {Tcl_GetsObj: input saw cr} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # if (chanPtr->flags & INPUT_SAW_CR)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto lf} -buffering none
@@ -867,7 +868,7 @@ test chan-io-6.43 {Tcl_GetsObj: input saw cr} -setup {
 } -result {bbbbbbbbbbbbbbb 15 123456789abcdef 1 4 abcd 0 3 efg}
 test chan-io-6.44 {Tcl_GetsObj: input saw cr, not followed by cr} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # not (*eol == '\n')
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto lf} -buffering none
@@ -885,7 +886,7 @@ test chan-io-6.44 {Tcl_GetsObj: input saw cr, not followed by cr} -setup {
 } -result {bbbbbbbbbbbbbbb 15 123456789abcdef 1 4 abcd 0 3 efg}
 test chan-io-6.45 {Tcl_GetsObj: input saw cr, skip right number of bytes} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # Tcl_ExternalToUtf()
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto lf} -buffering none
@@ -903,7 +904,7 @@ test chan-io-6.45 {Tcl_GetsObj: input saw cr, skip right number of bytes} -setup
 } -result {15 123456789abcdef 1 4 abcd 0}
 test chan-io-6.46 {Tcl_GetsObj: input saw cr, followed by just \n should give eof} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # memmove()
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto lf} -buffering none
@@ -1021,7 +1022,7 @@ test chan-io-6.55 {Tcl_GetsObj: overconverted} -body {
 test chan-io-6.56 {Tcl_GetsObj: incomplete lines should disable file events} -setup {
     update
     variable x {}
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set f [openpipe w+ $path(cat)]
     chan configure $f -buffering none
     chan puts -nonewline $f "foobar"
@@ -1088,7 +1089,7 @@ test chan-io-7.3 {FilterInputBytes: split up character at EOF} -setup {
 } -result [list 15 "1234567890123\uff10\uff11" 18 0 1 -1 ""]
 test chan-io-7.4 {FilterInputBytes: recover from split up character} -setup {
     variable x ""
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set f [openpipe w+ $path(cat)]
     chan configure $f -encoding binary -buffering none
     chan puts -nonewline $f "1234567890123\x82\x4f\x82\x50\x82"
@@ -1122,7 +1123,7 @@ test chan-io-8.1 {PeekAhead: only go to device if no more cached data} -constrai
 } -result 7
 test chan-io-8.2 {PeekAhead: only go to device if no more cached data} -setup {
     variable x {}
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # not (bufPtr->nextPtr == NULL)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation lf -encoding ascii -buffering none
@@ -1139,7 +1140,7 @@ test chan-io-8.2 {PeekAhead: only go to device if no more cached data} -setup {
 } -cleanup {
     chan close $f
 } -result {-1 {} 42 15 123456789012345 25}
-test chan-io-8.3 {PeekAhead: no cached data available} -constraints {stdio testchannel openpipe fileevent} -body {
+test chan-io-8.3 {PeekAhead: no cached data available} -constraints {stdio testchannel fileevent} -body {
     # (bytesLeft == 0)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto binary}
@@ -1168,7 +1169,7 @@ test chan-io-8.4 {PeekAhead: cached data available in this buffer} -body {
     chan close $f
 } -result $a
 unset a
-test chan-io-8.5 {PeekAhead: don't peek if last read was short} -constraints {stdio testchannel openpipe fileevent} -body {
+test chan-io-8.5 {PeekAhead: don't peek if last read was short} -constraints {stdio testchannel fileevent} -body {
     # (bufPtr->nextAdded < bufPtr->length)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto binary}
@@ -1179,7 +1180,7 @@ test chan-io-8.5 {PeekAhead: don't peek if last read was short} -constraints {st
 } -cleanup {
     chan close $f
 } -result {15 abcdefghijklmno 1}
-test chan-io-8.6 {PeekAhead: change to non-blocking mode} -constraints {stdio testchannel openpipe fileevent} -body {
+test chan-io-8.6 {PeekAhead: change to non-blocking mode} -constraints {stdio testchannel fileevent} -body {
     # ((chanPtr->flags & CHANNEL_NONBLOCKING) == 0)
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto binary} -buffersize 16
@@ -1192,7 +1193,7 @@ test chan-io-8.6 {PeekAhead: change to non-blocking mode} -constraints {stdio te
 } -result {15 abcdefghijklmno 1}
 test chan-io-8.7 {PeekAhead: cleanup} -setup {
     set x ""
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # Make sure bytes are removed from buffer.
     set f [openpipe w+ $path(cat)]
     chan configure $f -translation {auto binary} -buffering none
@@ -1343,7 +1344,7 @@ test chan-io-12.3 {ReadChars: allocate more space} -body {
 } -result {abcdefghijklmnopqrstuvwxyz}
 test chan-io-12.4 {ReadChars: split-up char} -setup {
     variable x {}
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # (srcRead == 0)
     set f [openpipe w+ $path(cat)]
     chan configure $f -encoding binary -buffering none -buffersize 16
@@ -1365,7 +1366,7 @@ test chan-io-12.4 {ReadChars: split-up char} -setup {
 } -result [list "123456789012345" 1 "\u672c" 0]
 test chan-io-12.5 {ReadChars: chan events on partial characters} -setup {
     variable x {}
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set path(test1) [makeFile {
        chan configure stdout -encoding binary -buffering none
        chan gets stdin; chan puts -nonewline "\xe7"
@@ -1458,7 +1459,7 @@ test chan-io-13.5 {TranslateInputEOL: crlf mode: naked lf} -body {
 test chan-io-13.6 {TranslateInputEOL: auto mode: saw cr in last segment} -setup {
     variable x {}
     variable y {}
-} -constraints {stdio testchannel openpipe fileevent} -body {
+} -constraints {stdio testchannel fileevent} -body {
     # (chanPtr->flags & INPUT_SAW_CR)
     # This test may fail on slower machines.
     set f [openpipe w+ $path(cat)]
@@ -1476,7 +1477,7 @@ test chan-io-13.6 {TranslateInputEOL: auto mode: saw cr in last segment} -setup
 } -cleanup {
     chan close $f
 } -result [list "abcdefghj\n" 1 "01234" 0]
-test chan-io-13.7 {TranslateInputEOL: auto mode: naked \r} -constraints {testchannel openpipe} -body {
+test chan-io-13.7 {TranslateInputEOL: auto mode: naked \r} -constraints testchannel -body {
     # (src >= srcMax)
     set f [open $path(test1) w]
     chan configure $f -translation lf
@@ -1577,7 +1578,7 @@ test chan-io-14.2 {Tcl_SetStdChannel and Tcl_GetStdChannel} -setup {
     interp delete x
 } -result {line line none}
 set path(test3) [makeFile {} test3]
-test chan-io-14.3 {Tcl_SetStdChannel & Tcl_GetStdChannel} -constraints {exec openpipe} -body {
+test chan-io-14.3 {Tcl_SetStdChannel & Tcl_GetStdChannel} -constraints exec -body {
     set f [open $path(test1) w]
     chan puts -nonewline $f {
        chan close stdin
@@ -1674,7 +1675,7 @@ set path(script) [makeFile {} script]
 test chan-io-14.8 {reuse of stdio special channels} -setup {
     file delete $path(script)
     file delete $path(test1)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f [open $path(script) w]
     chan puts -nonewline $f {
        chan close stderr
@@ -1697,7 +1698,7 @@ test chan-io-14.8 {reuse of stdio special channels} -setup {
 test chan-io-14.9 {reuse of stdio special channels} -setup {
     file delete $path(script)
     file delete $path(test1)
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set f [open $path(script) w]
     chan puts $f {
         array set path [lindex $argv 0]
@@ -1881,7 +1882,7 @@ test chan-io-20.3 {Tcl_CreateChannel: initial settings} -constraints {unix} -bod
 } -result {{{} {}} {auto lf}}
 test chan-io-20.5 {Tcl_CreateChannel: install channel in empty slot} -setup {
     set path(stdout) [makeFile {} stdout]
-} -constraints {stdio openpipe knownMsvcBug} -body {
+} -constraints {stdio notWinCI} -body {
     set f [open $path(script) w]
     chan puts -nonewline $f {
        chan close stdout
@@ -1966,7 +1967,7 @@ test chan-io-26.1 {Tcl_GetChannelInstanceData} -body {
     # Don't care what pid is (but must be a number), just want to exercise it.
     set f [openpipe r << exit]
     pid $f
-} -constraints {stdio openpipe} -cleanup {
+} -constraints stdio -cleanup {
     chan close $f
 } -match regexp -result {^\d+$}
 
@@ -2041,7 +2042,7 @@ set path(output) [makeFile {} output]
 test chan-io-27.6 {FlushChannel, async flushing, async chan close} -setup {
     file delete $path(pipe)
     file delete $path(output)
-} -constraints {stdio asyncPipeChan Close openpipe} -body {
+} -constraints {stdio asyncPipeChan Close} -body {
     set f [open $path(pipe) w]
     chan puts $f "set f \[[list open $path(output) w]]"
     chan puts $f {
@@ -2111,7 +2112,7 @@ test chan-io-28.2 {Chan CloseChannel called when all references are dropped} -se
 test chan-io-28.3 {Chan CloseChannel, not called before output queue is empty} -setup {
     file delete $path(pipe)
     file delete $path(output)
-} -constraints {stdio asyncPipeChan Close nonPortable openpipe} -body {
+} -constraints {stdio asyncPipeChan Close nonPortable} -body {
     set f [open $path(pipe) w]
     chan puts $f {
        # Need to not have eof char appended on chan close, because the other
@@ -2165,7 +2166,7 @@ test chan-io-28.4 {Tcl_Chan Close} -constraints {testchannel} -setup {
 } -result ok
 test chan-io-28.5 {Tcl_Chan Close vs standard handles} -setup {
     file delete $path(script)
-} -constraints {stdio unix testchannel openpipe} -body {
+} -constraints {stdio unix testchannel} -body {
     set f [open $path(script) w]
     chan puts $f {
        chan close stdin
@@ -2382,7 +2383,7 @@ test chan-io-29.11 {Tcl_WriteChars, no newline, implicit flush} -setup {
 test chan-io-29.12 {Tcl_WriteChars on a pipe} -setup {
     file delete $path(test1)
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 "set f1 \[[list open $path(longfile) r]]"
     chan puts $f1 {
@@ -2409,7 +2410,7 @@ test chan-io-29.12 {Tcl_WriteChars on a pipe} -setup {
 test chan-io-29.13 {Tcl_WriteChars to a pipe, line buffered} -setup {
     file delete $path(test1)
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {
        chan puts [chan gets stdin]
@@ -2462,7 +2463,7 @@ test chan-io-29.15 {Tcl_Flush, channel not open for writing} -setup {
 } -match glob -result {channel "*" wasn't opened for writing}
 test chan-io-29.16 {Tcl_Flush on pipe opened only for reading} -setup {
     set fd [openpipe r cat longfile]
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     chan flush $fd
 } -returnCodes error -cleanup {
     catch {chan close $fd}
@@ -2538,7 +2539,7 @@ test chan-io-29.20 {Implicit flush when buffer is full} -setup {
 } -result {4096 12288 12600}
 test chan-io-29.21 {Tcl_Flush to pipe} -setup {
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {set x [chan read stdin 6]}
     chan puts $f1 {set cnt [string length $x]}
@@ -2553,7 +2554,7 @@ test chan-io-29.21 {Tcl_Flush to pipe} -setup {
 } -result "read 6 characters"
 test chan-io-29.22 {Tcl_Flush called at other end of pipe} -setup {
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {
        chan configure stdout -buffering full
@@ -2577,7 +2578,7 @@ test chan-io-29.22 {Tcl_Flush called at other end of pipe} -setup {
 } -result {hello hello bye}
 test chan-io-29.23 {Tcl_Flush and line buffering at end of pipe} -setup {
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {
        chan puts hello
@@ -2614,7 +2615,7 @@ test chan-io-29.24 {Tcl_WriteChars and Tcl_Flush move end of file} -setup {
 } -result "{} {Line 1\nLine 2}"
 test chan-io-29.25 {Implicit flush with Tcl_Flush to command pipelines} -setup {
     file delete $path(test3)
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set f [openpipe w $path(cat) | [interpreter] $path(cat) > $path(test3)]
     chan puts $f "Line 1"
     chan puts $f "Line 2"
@@ -2625,7 +2626,7 @@ test chan-io-29.25 {Implicit flush with Tcl_Flush to command pipelines} -setup {
 } -cleanup {
     chan close $f
 } -result "Line 1\nLine 2\n"
-test chan-io-29.26 {Tcl_Flush, Tcl_Write on bidirectional pipelines} -constraints {stdio unixExecs openpipe} -body {
+test chan-io-29.26 {Tcl_Flush, Tcl_Write on bidirectional pipelines} -constraints {stdio unixExecs} -body {
     set f [open "|[list cat -u]" r+]
     chan puts $f "Line1"
     chan flush $f
@@ -2638,7 +2639,7 @@ test chan-io-29.27 {Tcl_Flush on chan closed pipeline} -setup {
     set f [open $path(pipe) w]
     chan puts $f {exit}
     chan close $f
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f [openpipe r+ $path(pipe)]
     chan gets $f
     chan puts $f output
@@ -2691,7 +2692,7 @@ test chan-io-29.30 {Tcl_WriteChars, crlf mode} -setup {
 test chan-io-29.31 {Tcl_WriteChars, background flush} -setup {
     file delete $path(pipe)
     file delete $path(output)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f [open $path(pipe) w]
     chan puts $f "set f \[[list open $path(output)  w]]"
     chan puts $f {chan configure $f -translation lf}
@@ -2724,7 +2725,7 @@ test chan-io-29.31 {Tcl_WriteChars, background flush} -setup {
        set result ok
     }
     # allow a little time for the background process to chan close.
-    # otherwise, the following test fails on the [file delete $path(output)
+    # otherwise, the following test fails on the [file delete $path(output)]
     # on Windows because a process still has the file open.
     after 100 set v 1; vwait v
     return $result
@@ -2732,7 +2733,7 @@ test chan-io-29.31 {Tcl_WriteChars, background flush} -setup {
 test chan-io-29.32 {Tcl_WriteChars, background flush to slow reader} -setup {
     file delete $path(pipe)
     file delete $path(output)
-} -constraints {stdio asyncPipeChan Close openpipe} -body {
+} -constraints {stdio asyncPipeChan Close} -body {
     set f [open $path(pipe) w]
     chan puts $f "set f \[[list open $path(output) w]]"
     chan puts $f {chan configure $f -translation lf}
@@ -2791,7 +2792,7 @@ test chan-io-29.34 {Tcl_Chan Close, async flush on chan close, using sockets} -s
            chan puts $s $l
        }
     }
-} -constraints {socket tempNotMac fileevent knownMsvcBug} -body {
+} -constraints {socket tempNotMac fileevent notWinCI} -body {
     proc accept {s a p} {
        variable x
        chan event $s readable [namespace code [list readit $s]]
@@ -3045,7 +3046,7 @@ test chan-io-30.13 {Tcl_Write crlf on block boundary, Tcl_Read auto} -setup {
     string length [chan read $f]
 } -cleanup {
     chan close $f
-} -result [expr 700*15+1]
+} -result [expr {700*15 + 1}]
 test chan-io-30.14 {Tcl_Write crlf on block boundary, Tcl_Read crlf} -setup {
     file delete $path(test1)
 } -body {
@@ -3062,7 +3063,7 @@ test chan-io-30.14 {Tcl_Write crlf on block boundary, Tcl_Read crlf} -setup {
     string length [chan read $f]
 } -cleanup {
     chan close $f
-} -result [expr 700*15+1]
+} -result [expr {700*15 + 1}]
 test chan-io-30.15 {Tcl_Write mixed, Tcl_Read auto} -setup {
     file delete $path(test1)
 } -body {
@@ -3904,7 +3905,7 @@ test chan-io-31.31 {Tcl_Write crlf on block boundary, Tcl_Gets crlf} -setup {
     }
     chan close $f
     string length $c
-} -result [expr 700*15+1]
+} -result [expr {700*15 + 1}]
 test chan-io-31.32 {Tcl_Write crlf on block boundary, Tcl_Gets auto} -setup {
     file delete $path(test1)
     set c ""
@@ -3924,7 +3925,7 @@ test chan-io-31.32 {Tcl_Write crlf on block boundary, Tcl_Gets auto} -setup {
     }
     chan close $f
     string length $c
-} -result [expr 700*15+1]
+} -result [expr {700*15 + 1}]
 
 # Test Tcl_Read and buffering.
 
@@ -4005,7 +4006,7 @@ test chan-io-32.9 {Tcl_Read, read to end of file} {
 } ok
 test chan-io-32.10 {Tcl_Read from a pipe} -setup {
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {chan puts [chan gets stdin]}
     chan close $f1
@@ -4019,7 +4020,7 @@ test chan-io-32.10 {Tcl_Read from a pipe} -setup {
 test chan-io-32.11 {Tcl_Read from a pipe} -setup {
     file delete $path(pipe)
     set x ""
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {chan puts [chan gets stdin]}
     chan puts $f1 {chan puts [chan gets stdin]}
@@ -4131,7 +4132,7 @@ test chan-io-33.2 {Tcl_Gets into variable} {
 } ok
 test chan-io-33.3 {Tcl_Gets from pipe} -setup {
     file delete $path(pipe)
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {chan puts [chan gets stdin]}
     chan close $f1
@@ -4341,7 +4342,7 @@ test chan-io-34.7 {Tcl_Seek to offset from end of file, then to current position
 } -result {44 rstuv 49}
 test chan-io-34.8 {Tcl_Seek on pipes: not supported} -setup {
     set pipe [openpipe]
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     chan seek $pipe 0 current
 } -returnCodes error -cleanup {
     chan close $pipe
@@ -4451,13 +4452,13 @@ test chan-io-34.15 {Tcl_Tell combined with seeking} -setup {
 } -cleanup {
     chan close $f1
 } -result {10 20}
-test chan-io-34.16 {Tcl_Tell on pipe: always -1} -constraints {stdio openpipe} -body {
+test chan-io-34.16 {Tcl_Tell on pipe: always -1} -constraints stdio -body {
     set f1 [openpipe]
     chan tell $f1
 } -cleanup {
     chan close $f1
 } -result -1
-test chan-io-34.17 {Tcl_Tell on pipe: always -1} {stdio openpipe} {
+test chan-io-34.17 {Tcl_Tell on pipe: always -1} stdio {
     set f1 [openpipe]
     chan puts $f1 {chan puts hello}
     chan flush $f1
@@ -4559,7 +4560,7 @@ test chan-io-35.1 {Tcl_Eof} -setup {
 } -cleanup {
     chan close $f
 } -result {0 0 0 0 1 1}
-test chan-io-35.2 {Tcl_Eof with pipe} -constraints {stdio openpipe} -setup {
+test chan-io-35.2 {Tcl_Eof with pipe} -constraints stdio -setup {
     file delete $path(pipe)
 } -body {
     set f1 [open $path(pipe) w]
@@ -4578,7 +4579,7 @@ test chan-io-35.2 {Tcl_Eof with pipe} -constraints {stdio openpipe} -setup {
 } -cleanup {
     chan close $f1
 } -result {0 0 0 1}
-test chan-io-35.3 {Tcl_Eof with pipe} -constraints {stdio openpipe} -setup {
+test chan-io-35.3 {Tcl_Eof with pipe} -constraints stdio -setup {
     file delete $path(pipe)
 } -body {
     set f1 [open $path(pipe) w]
@@ -4616,7 +4617,7 @@ test chan-io-35.4 {Tcl_Eof, eof detection on nonblocking file} -setup {
 test chan-io-35.5 {Tcl_Eof, eof detection on nonblocking pipe} -setup {
     file delete $path(pipe)
     set l ""
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f [open $path(pipe) w]
     chan puts $f {
        exit
@@ -4801,7 +4802,7 @@ test chan-io-35.17 {Tcl_Eof, eof char in middle, crlf write, crlf read} -setup {
 
 test chan-io-36.1 {Tcl_InputBlocked on nonblocking pipe} -setup {
     set x ""
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [openpipe]
     chan puts $f1 {chan puts hello_from_pipe}
     chan flush $f1
@@ -4821,7 +4822,7 @@ test chan-io-36.1 {Tcl_InputBlocked on nonblocking pipe} -setup {
 } -result {{} 1 hello 0 {} 1}
 test chan-io-36.2 {Tcl_InputBlocked on blocking pipe} -setup {
     set x ""
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [openpipe]
     chan configure $f1 -buffering line
     chan puts $f1 {chan puts hello_from_pipe}
@@ -5095,7 +5096,7 @@ test chan-io-39.9 {Tcl_SetChannelOption, blocking mode} -setup {
 test chan-io-39.10 {Tcl_SetChannelOption, blocking mode} -setup {
     file delete $path(pipe)
     set x ""
-} -constraints {stdio openpipe} -body {
+} -constraints stdio -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {
        chan gets stdin
@@ -5192,7 +5193,7 @@ test chan-io-39.16 {Tcl_SetChannelOption: -encoding, errors} -setup {
 } -result {unknown encoding "foobar"}
 test chan-io-39.17 {Tcl_SetChannelOption: -encoding, clearing CHANNEL_NEED_MORE_DATA} -setup {
     variable x {}
-} -constraints {stdio openpipe fileevent} -body {
+} -constraints {stdio fileevent} -body {
     set f [openpipe r+ $path(cat)]
     chan configure $f -encoding binary
     chan puts -nonewline $f "\xe7"
@@ -5333,24 +5334,24 @@ test chan-io-40.1 {POSIX open access modes: RDWR} -setup {
 test chan-io-40.2 {POSIX open access modes: CREAT} -setup {
     file delete $path(test3)
 } -constraints {unix} -body {
-    set f [open $path(test3) {WRONLY CREAT} 0600]
+    set f [open $path(test3) {WRONLY CREAT} 0o600]
     file stat $path(test3) stats
-    set x [format "%#o" [expr $stats(mode)&0o777]]
+    set x [format 0o%03o [expr {$stats(mode) & 0o777}]]
     chan puts $f "line 1"
     chan close $f
     set f [open $path(test3) r]
     lappend x [chan gets $f]
 } -cleanup {
     chan close $f
-} -result {0600 {line 1}}
+} -result {0o600 {line 1}}
 test chan-io-40.3 {POSIX open access modes: CREAT} -setup {
     file delete $path(test3)
 } -constraints {unix umask} -body {
     # This test only works if your umask is 2, like ouster's.
     chan close [open $path(test3) {WRONLY CREAT}]
     file stat $path(test3) stats
-    format "%#o" [expr $stats(mode)&0o777]
-} -result [format %#4o [expr {0o666 & ~ $umaskValue}]]
+    format "0o%03o" [expr {$stats(mode) & 0o777}]
+} -result [format 0o%03o [expr {0o666 & ~ $umaskValue}]]
 test chan-io-40.4 {POSIX open access modes: CREAT} -setup {
     file delete $path(test3)
 } -body {
@@ -5552,7 +5553,7 @@ test chan-io-43.2 {Tcl_FileeventCmd: deleting when many present} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
     set result {}
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     lappend result [chan event $f r] [chan event $f2 r] [chan event $f3 r]
     chan event $f r "chan read f"
     chan event $f2 r "chan read f2"
@@ -5572,7 +5573,7 @@ test chan-io-43.2 {Tcl_FileeventCmd: deleting when many present} -setup {
 test chan-io-44.1 {FileEventProc procedure: normal read event} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     chan event $f2 readable [namespace code {
        set x [chan gets $f2]; chan event $f2 readable {}
     }]
@@ -5592,7 +5593,7 @@ test chan-io-44.2 {FileEventProc procedure: error in read event} -setup {
     }
     set handler [interp bgerror {}]
     interp bgerror {} [namespace which myHandler]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     chan event $f2 readable {error bogus}
     chan puts $f2 text; chan flush $f2
     variable x initial
@@ -5606,7 +5607,7 @@ test chan-io-44.2 {FileEventProc procedure: error in read event} -setup {
 test chan-io-44.3 {FileEventProc procedure: normal write event} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     chan event $f2 writable [namespace code {
        lappend x "triggered"
        incr count -1
@@ -5632,7 +5633,7 @@ test chan-io-44.4 {FileEventProc procedure: eror in write event} -setup {
     }
     set handler [interp bgerror {}]
     interp bgerror {} [namespace which myHandler]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     chan event $f2 writable {error bad-write}
     variable x initial
     vwait [namespace which -variable x]
@@ -5642,7 +5643,9 @@ test chan-io-44.4 {FileEventProc procedure: eror in write event} -setup {
     catch {chan close $f2}
     catch {chan close $f3}
 } -result {bad-write {}}
-test chan-io-44.5 {FileEventProc procedure: end of file} {stdio unixExecs openpipe fileevent} {
+test chan-io-44.5 {FileEventProc procedure: end of file} -constraints {
+    stdio unixExecs fileevent
+} -body {
     set f4 [openpipe r $path(cat) << foo]
     chan event $f4 readable [namespace code {
        if {[chan gets $f4 line] < 0} {
@@ -5655,9 +5658,10 @@ test chan-io-44.5 {FileEventProc procedure: end of file} {stdio unixExecs openpi
     variable x initial
     vwait [namespace which -variable x]
     vwait [namespace which -variable x]
-    chan close $f4
     set x
-} {initial foo eof}
+} -cleanup {
+    chan close $f4
+} -result {initial foo eof}
 
 chan close $f
 makeFile "foo bar" foo
@@ -5718,7 +5722,7 @@ test chan-io-45.3 {DeleteFileEvent, cleanup on chan close} {fileevent} {
 
 # Execute these tests only if the "testfevent" command is present.
 
-test chan-io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileevent} {
+test chan-io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileevent notOSX} {
     testfevent create
     set script "set f \[[list open $path(foo) r]]\n"
     append script {
@@ -5728,9 +5732,10 @@ test chan-io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileeven
            chan event $f readable {}
        }]
     }
+    set timer [after 10 lappend x timeout]
     testfevent cmd $script
-    after 1    ;# We must delay because Windows takes a little time to notice
-    update
+    vwait x
+    after cancel $timer
     testfevent cmd {chan close $f}
     list [testfevent cmd {set x}] [testfevent cmd {info commands after}]
 } {{f triggered: foo bar} after}
@@ -5918,7 +5923,7 @@ test chan-io-48.2 {testing readability conditions} {nonBlockFiles fileevent} {
 set path(my_script) [makeFile {} my_script]
 test chan-io-48.3 {testing readability conditions} -setup {
     set l ""
-} -constraints {stdio unix nonBlockFiles openpipe fileevent} -body {
+} -constraints {stdio unix nonBlockFiles fileevent} -body {
     set f [open $path(bar) w]
     chan puts $f abcdefg
     chan puts $f abcdefg
@@ -6372,17 +6377,21 @@ test chan-io-49.5 {testing crlf reading, leftover cr disgorgment} -setup {
 
 test chan-io-50.1 {testing handler deletion} -setup {
     file delete $path(test1)
-} -constraints {testchannelevent} -body {
+} -constraints testchannelevent -body {
     set f [open $path(test1) w]
     chan close $f
     set f [open $path(test1) r]
+    variable z not_called
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
     testchannelevent $f add readable [namespace code {
        variable z called
        testchannelevent $f delete 0
     }]
-    variable z not_called
-    update
-    return $z
+    testservicemode 1
+    vwait z
+    after cancel $timer
+    set z
 } -cleanup {
     chan close $f
 } -result called
@@ -6390,16 +6399,21 @@ test chan-io-50.2 {testing handler deletion with multiple handlers} -setup {
     file delete $path(test1)
     chan close [open $path(test1) w]
     set z ""
-} -constraints {testchannelevent} -body {
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list delhandler $f 1]]
-    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+} -constraints {testchannelevent testservicemode} -body {
     proc delhandler {f i} {
        variable z
        lappend z "called delhandler $f $i"
        testchannelevent $f delete 0
     }
-    update
+    set z ""
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list delhandler $f 1]]
+    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+    testservicemode 1
+    vwait z
+    after cancel $timer
     string equal $z \
        [list [list called delhandler $f 0] [list called delhandler $f 1]]
 } -cleanup {
@@ -6408,11 +6422,7 @@ test chan-io-50.2 {testing handler deletion with multiple handlers} -setup {
 test chan-io-50.3 {testing handler deletion with multiple handlers} -setup {
     file delete $path(test1)
     chan close [open $path(test1) w]
-    set z ""
-} -constraints {testchannelevent} -body {
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list notcalled $f 1]]
-    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+} -constraints {testchannelevent testservicemode} -body {
     proc notcalled {f i} {
        variable z
        lappend z "notcalled was called!! $f $i"
@@ -6424,7 +6434,15 @@ test chan-io-50.3 {testing handler deletion with multiple handlers} -setup {
        testchannelevent $f delete 0
        lappend z "delhandler $f $i deleted myself"
     }
-    update
+    set z ""
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list notcalled $f 1]]
+    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+    testservicemode 1
+    vwait z
+    after cancel $timer
     string equal $z \
        [list [list delhandler $f 0 called] \
              [list delhandler $f 0 deleted myself]]
@@ -6435,7 +6453,7 @@ test chan-io-50.4 {testing handler deletion vs reentrant calls} -setup {
     file delete $path(test1)
     set f [open $path(test1) w]
     chan close $f
-} -constraints {testchannelevent} -body {
+} -constraints testchannelevent -body {
     set f [open $path(test1) r]
     testchannelevent $f add readable [namespace code {
        if {$u eq "recursive"} {
@@ -6449,19 +6467,20 @@ test chan-io-50.4 {testing handler deletion vs reentrant calls} -setup {
     }]
     variable u toplevel
     variable z ""
-    update
-    return $z
+    set timer [after 50 lappend z timeout]
+    vwait z
+    after cancel $timer
+    set z
 } -cleanup {
     chan close $f
+    update
 } -result {{delrecursive calling recursive} {delrecursive deleting recursive}}
 test chan-io-50.5 {testing handler deletion vs reentrant calls} -setup {
     file delete $path(test1)
     set f [open $path(test1) w]
     chan close $f
-} -constraints {testchannelevent} -body {
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list notcalled $f]]
-    testchannelevent $f add readable [namespace code [list del $f]]
+    update
+} -constraints {testchannelevent testservicemode notOSX} -body {
     proc notcalled {f} {
        variable z
        lappend z "notcalled was called!! $f"
@@ -6477,33 +6496,46 @@ test chan-io-50.5 {testing handler deletion vs reentrant calls} -setup {
        } else {
            set u recursive
            lappend z "del calling recursive"
-           update
+           set timer [after 50 lappend z timeout]
+           set mode [testservicemode 1]
+           vwait z
+           after cancel $timer
+           testservicemode $mode
            lappend z "del after update"
        }
     }
     set z ""
     set u toplevel
-    update
-    return $z
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list notcalled $f]]
+    testchannelevent $f add readable [namespace code [list del $f]]
+    testservicemode 1
+    vwait z
+    after cancel $timer
+    set z
 } -cleanup {
     chan close $f
+    update
 } -result [list {del calling recursive} {del deleted notcalled} \
               {del deleted myself} {del after update}]
 test chan-io-50.6 {testing handler deletion vs reentrant calls} -setup {
     file delete $path(test1)
     set f [open $path(test1) w]
     chan close $f
-} -constraints {testchannelevent} -body {
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list second $f]]
-    testchannelevent $f add readable [namespace code [list first $f]]
+} -constraints {testchannelevent testservicemode} -body {
     proc first {f} {
        variable u
        variable z
        if {$u eq "toplevel"} {
            lappend z "first called"
+           set mode [testservicemode 1]
+           set timer [after 50 lappend z timeout]
            set u first
-           update
+           vwait z
+           after cancel $timer
+           testservicemode $mode
            lappend z "first after update"
        } else {
            lappend z "first called not toplevel"
@@ -6526,8 +6558,15 @@ test chan-io-50.6 {testing handler deletion vs reentrant calls} -setup {
     }
     set z ""
     set u toplevel
-    update
-    return $z
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list second $f]]
+    testchannelevent $f add readable [namespace code [list first $f]]
+    testservicemode 1
+    vwait z
+    after cancel $timer
+    set z
 } -cleanup {
     chan close $f
 } -result [list {first called} {first called not toplevel} \
@@ -6678,7 +6717,7 @@ test chan-io-52.6 {TclCopyChannel} -setup {
     set f2 [open $path(test1) w]
     chan configure $f1 -translation lf -blocking 0
     chan configure $f2 -translation lf -blocking 0
-    set s0 [chan copy $f1 $f2 -size [expr [file size $thisScript] + 5]]
+    set s0 [chan copy $f1 $f2 -size [expr {[file size $thisScript] + 5}]]
     set result [list [chan configure $f1 -blocking] [chan configure $f2 -blocking]]
     chan close $f1
     chan close $f2
@@ -6709,7 +6748,7 @@ test chan-io-52.7 {TclCopyChannel} -constraints {fcopy} -setup {
 test chan-io-52.8 {TclCopyChannel} -setup {
     file delete $path(test1)
     file delete $path(pipe)
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     set f1 [open $path(pipe) w]
     chan configure $f1 -translation lf
     chan puts $f1 "
@@ -6830,7 +6869,7 @@ test chan-io-53.2 {CopyData} -setup {
 test chan-io-53.3 {CopyData: background read underflow} -setup {
     file delete $path(test1)
     file delete $path(pipe)
-} -constraints {stdio unix openpipe fcopy} -body {
+} -constraints {stdio unix fcopy} -body {
     set f1 [open $path(pipe) w]
     chan puts -nonewline $f1 {
        chan puts ready
@@ -6868,7 +6907,7 @@ test chan-io-53.4 {CopyData: background write overflow} -setup {
     }
     file delete $path(test1)
     file delete $path(pipe)
-} -constraints {stdio unix openpipe fileevent fcopy} -body {
+} -constraints {stdio unix fileevent fcopy} -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 {
        chan puts ready
@@ -6920,7 +6959,7 @@ test chan-io-53.5 {CopyData: error during chan copy} {socket fcopy} {
     chan close $listen ;# This means the socket open never really succeeds
     chan copy $in $out -command [namespace code FcopyTestDone]
     variable fcopyTestDone
-    if ![info exists fcopyTestDone] {
+    if {![info exists fcopyTestDone]} {
        vwait [namespace which -variable fcopyTestDone]         ;# The error occurs here in the b.g.
     }
     chan close $in
@@ -6932,7 +6971,7 @@ test chan-io-53.6 {CopyData: error during chan copy} -setup {
     file delete $path(pipe)
     file delete $path(test1)
     catch {unset fcopyTestDone}
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     set f1 [open $path(pipe) w]
     chan puts $f1 "exit 1"
     chan close $f1
@@ -6940,7 +6979,7 @@ test chan-io-53.6 {CopyData: error during chan copy} -setup {
     set out [open $path(test1) w]
     chan copy $in $out -command [namespace code FcopyTestDone]
     variable fcopyTestDone
-    if ![info exists fcopyTestDone] {
+    if {![info exists fcopyTestDone]} {
        vwait [namespace which -variable fcopyTestDone]
     }
     return $fcopyTestDone      ;# 0 for plain end of file
@@ -6966,7 +7005,7 @@ test chan-io-53.7 {CopyData: Flooding chan copy from pipe} -setup {
     variable fcopyTestDone
     file delete $path(pipe)
     catch {unset fcopyTestDone}
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     set fcopyTestCount 0
     set f1 [open $path(pipe) w]
     chan puts $f1 {
@@ -6993,7 +7032,7 @@ test chan-io-53.7 {CopyData: Flooding chan copy from pipe} -setup {
        vwait [namespace which -variable fcopyTestDone]
     }
     # -1=error 0=script error N=number of bytes
-    expr ($fcopyTestDone == 0) ? $fcopyTestCount : -1
+    expr {($fcopyTestDone == 0) ? $fcopyTestCount : -1}
 } -cleanup {
     catch {chan close $in}
     chan close $out
@@ -7016,7 +7055,7 @@ test chan-io-53.8 {CopyData: async callback and error handling, Bug 1932639} -se
     # Channels to copy between
     set f [open $foo r] ; fconfigure $f -translation binary
     set g [open $bar w] ; fconfigure $g -translation binary -buffering none
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Record input size, so that result is always defined
     lappend ::RES [file size $bar]
     # Run the copy. Should not invoke -command now.
@@ -7056,7 +7095,7 @@ test chan-io-53.8a {CopyData: async callback and error handling, Bug 1932639, at
     # Channels to copy between
     set f [open $foo r] ; chan configure $f -translation binary
     set g [open $bar w] ; chan configure $g -translation binary -buffering none
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Initialize and force eof on the input.
     chan seek $f 0 end ; chan read $f 1
     set ::RES [chan eof $f]
@@ -7114,7 +7153,7 @@ test chan-io-53.9 {CopyData: -size and event interaction, Bug 780533} -setup {
     }
     set ::forever {}
     set out [open $out w]
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     chan copy $pipe $out -size 6 -command ::done
     set token [after 5000 {
        set ::forever {fcopy hangs}
@@ -7187,7 +7226,7 @@ test chan-io-53.10 {Bug 1350564, multi-directional fcopy} -setup {
     chan configure $b -translation binary -buffering none
     chan event  $a readable [namespace code "done $a"]
     chan event  $b readable [namespace code "done $b"]
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Now pass data through the server in both directions.
     set ::forever {}
     chan puts $a AB
@@ -7409,7 +7448,7 @@ test chan-io-57.2 {buffered data and file events, read} -setup {
     chan close $server
 } -result {1 readable 234567890 timer}
 
-test chan-io-58.1 {Tcl_NotifyChannel and error when closing} {stdio unixOrWin openpipe fileevent} {
+test chan-io-58.1 {Tcl_NotifyChannel and error when closing} {stdio unixOrWin fileevent} {
     set out [open $path(script) w]
     chan puts $out {
        chan puts "normal message from pipe"
@@ -7447,7 +7486,7 @@ test chan-io-59.1 {Thread reference of channels} {testmainthread testchannel} {
     string equal $result [testmainthread]
 } {1}
 
-test chan-io-60.1 {writing illegal utf sequences} {openpipe fileevent testbytestring} {
+test chan-io-60.1 {writing illegal utf sequences} {fileevent testbytestring} {
     # This test will hang in older revisions of the core.
     set out [open $path(script) w]
     chan puts $out "catch {load $::tcltestlib Tcltest}"
index 8d73bf2..db43a67 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -32,6 +32,10 @@ testConstraint detroit \
 testConstraint y2038 \
     [expr {[clock format 2158894800 -format %z -timezone :America/Detroit] eq {-0400}}]
 
+if {[namespace which -command ::tcl::unsupported::timerate] ne ""} {
+    namespace import ::tcl::unsupported::timerate
+}
+
 # TEST PLAN
 
 # clock-1:
@@ -250,18 +254,6 @@ proc ::testClock::registry { cmd path key } {
     return [dict get $reg $path $key]
 }
 
-proc timeWithinDuration {duration start end} {
-    regexp {([\d.]+)(s|ms|us)} $duration -> duration unit
-    if {[llength $start] > 1} { set start [expr "([join $start +])/[llength $start]"] }
-    if {[llength $end] > 1} { set end [expr "([join $end +])/[llength $end]"] }
-    set delta [expr {$end - $start}]
-    expr {
-         ($delta > 0) && ($delta <= $duration) ?
-         "ok" :
-         "test should have taken 0-$duration $unit, actually took $delta"}
-}
-
-
 # Test some of the basics of [clock format]
 
 test clock-1.0 "clock format - wrong # args" {
@@ -35036,6 +35028,24 @@ test clock-30.8 {clock add months, negative} {
     set x4 [clock format $f4 -format %Y-%m-%d -timezone :UTC]
     list $x1 $x2 $x3 $x4
 } {2000-02-29 2000-01-31 1999-12-31 1999-11-30}
+test clock-30.8a {clock add months, negative, over threshold of a year} {
+    set t [clock scan 2019-01-31 -format %Y-%m-%d -gmt 1]
+    list [clock format [clock add $t -1 month -gmt 1] -format %Y-%m-%d -gmt 1] \
+        [clock format [clock add $t -2 month -gmt 1] -format %Y-%m-%d -gmt 1] \
+        [clock format [clock add $t -3 month -gmt 1] -format %Y-%m-%d -gmt 1] \
+        [clock format [clock add $t -4 month -gmt 1] -format %Y-%m-%d -gmt 1]
+} {2018-12-31 2018-11-30 2018-10-31 2018-09-30}
+test clock-30.8b {clock add months, negative, over threshold of a year} {
+    set t [clock scan 2000-01-28 -format %Y-%m-%d -gmt 1]
+    for {set i 1} {$i < 24} {incr i 1} {
+       set f1 [clock add $t -$i month -gmt 1]
+       set f2 [clock add $f1 $i month -gmt 1]
+       if {$f2 != $t} {
+           error "\[clock add $t -$i month -gmt 1\] does not consider\
+                  \[clock add $f1 $i month -gmt 1\] != $t"
+       }
+    }
+} {}
 test clock-30.9 {clock add days} {
     set t [clock scan {2000-01-01 12:34:56} -format {%Y-%m-%d %H:%M:%S} \
               -timezone :UTC]
@@ -35430,7 +35440,7 @@ test clock-32.1 {scan/format across the Gregorian change} {
 
 # clock clicks
 test clock-33.1 {clock clicks tests} {
-    expr [clock clicks]+1
+    expr {[clock clicks] + 1}
     concat {}
 } {}
 test clock-33.2 {clock clicks tests} {
@@ -35443,7 +35453,7 @@ test clock-33.3 {clock clicks tests} {
     list [catch {clock clicks foo} msg] $msg
 } {1 {bad option "foo": must be -milliseconds or -microseconds}}
 test clock-33.4 {clock clicks tests} {
-    expr [clock clicks -milliseconds]+1
+    expr {[clock clicks -milliseconds] + 1}
     concat {}
 } {}
 test clock-33.4a {clock milliseconds} {
@@ -35451,22 +35461,36 @@ test clock-33.4a {clock milliseconds} {
     concat {}
 } {}
 test clock-33.5 {clock clicks tests, millisecond timing test} {
-    set start [set end {}]
-    lassign [time {
-       lappend start [clock clicks -milli]
-       after 1 {lappend end [clock clicks -milli]}
-       vwait end
-    } 5] tm
-    timeWithinDuration [expr {int($tm/1000 + 1)}]ms $start $end
+    # This test can fail on a system that is so heavily loaded that
+    # the test takes >60 ms to run.
+    if {[lindex [timerate {
+       set start [clock clicks -milli]
+       timerate {} 10; # short but precise busy wait
+       set end [clock clicks -milli]
+    } 1 1] 0] > 60000} {
+       ::tcltest::Skip "timing issue"
+    }
+    # 60 msecs seems to be the max time slice under Windows 95/98
+    expr {
+         ($end > $start) && (($end - $start) <= 60) ?
+         "ok" :
+         "test should have taken 0-60 ms, actually took [expr $end - $start]"}
 } {ok}
 test clock-33.5a {clock tests, millisecond timing test} {
-    set start [set end {}]
-    lassign [time {
-       lappend start [clock milliseconds]
-       after 1 {lappend end [clock milliseconds]}
-       vwait end
-    } 5] tm
-    timeWithinDuration [expr {int($tm/1000 + 1)}]ms $start $end
+    # This test can fail on a system that is so heavily loaded that
+    # the test takes >60 ms to run.
+    if {[lindex [timerate {
+       set start [clock milliseconds]
+       timerate {} 10; # short but precise busy wait
+       set end [clock milliseconds]
+    } 1 1] 0] > 60000} {
+       ::tcltest::Skip "timing issue"
+    }
+    # 60 msecs seems to be the max time slice under Windows 95/98
+    expr {
+         ($end > $start) && (($end - $start) <= 60) ?
+         "ok" :
+         "test should have taken 0-60 ms, actually took [expr $end - $start]"}
 } {ok}
 test clock-33.6 {clock clicks, milli with too much abbreviation} {
     list [catch { clock clicks ? } msg] $msg
@@ -35476,23 +35500,29 @@ test clock-33.7 {clock clicks, milli with too much abbreviation} {
 } {1 {ambiguous option "-": must be -milliseconds or -microseconds}}
 
 test clock-33.8 {clock clicks test, microsecond timing test} {
-    set start [set end {}]
-    lassign [time {
-       lappend start [clock clicks -micro]
-       after 1 {lappend end [clock clicks -micro]}
-       vwait end
-    } 5] tm
-    timeWithinDuration [expr {int($tm + 10)}]us $start $end
-} {ok}
+    # This test can fail on a system that is so heavily loaded that
+    # the test takes >60 ms to run.
+    if {[lindex [timerate {
+       set start [clock clicks -micro]
+       timerate {} 10; # short but precise busy wait
+       set end [clock clicks -micro]
+    } 1 1] 0] > 60000} {
+       ::tcltest::Skip "timing issue"
+    }
+    expr {($end > $start) && (($end - $start) <= 60000)}
+} {1}
 test clock-33.8a {clock test, microsecond timing test} {
-    set start [set end {}]
-    lassign [time {
-       lappend start [clock microseconds]
-       after 1 {lappend end [clock microseconds]}
-       vwait end
-    } 5] tm
-    timeWithinDuration [expr {int($tm + 10)}]us $start $end
-} {ok}
+    # This test can fail on a system that is so heavily loaded that
+    # the test takes >60 ms to run.
+    if {[lindex [timerate {
+       set start [clock microseconds]
+       timerate {} 10; # short but precise busy wait
+       set end [clock microseconds]
+    } 1 1] 0] > 60000} {
+       ::tcltest::Skip "timing issue"
+    }
+    expr {($end > $start) && (($end - $start) <= 60000)}
+} {1}
 
 test clock-33.9 {clock clicks test, millis align with seconds} {
     set t1 [clock seconds]
@@ -35604,7 +35634,6 @@ test clock-34.11 {clock scan tests} {
     set time [clock scan "1/1/37" -gmt true]
     clock format $time -format {%b %d,%Y %H:%M GMT} -gmt true
 } {Jan 01,2037 00:00 GMT}
-
 test clock-34.12 {clock scan, relative times} {
     set time [clock scan "Oct 23, 1992 -1 day"]
     clock format $time -format {%b %d, %Y}
@@ -35756,7 +35785,6 @@ test clock-34.43 {last monday in november} {
     }
     set res
 } {1991-11-25 1992-11-30 1993-11-29 1994-11-28 1995-11-27 1996-11-25}
-
 test clock-34.44 {2nd monday in november} {
     set res {}
     foreach i {91 92 93 94 95 96} {
@@ -35789,42 +35817,99 @@ test clock-34.47 {ago with multiple relative units} {
     set res [clock scan "2 days 2 hours ago" -base $base]
     expr {$base - $res}
 } 180000
-
 test clock-34.48 {more than one ToD} {*}{
     -body {clock scan {10:00 11:00}}
     -returnCodes error
     -result {unable to convert date-time string "10:00 11:00": more than one time of day in string}
 }
-
 test clock-34.49 {more than one date} {*}{
     -body {clock scan {1/1/2001 2/2/2002}}
     -returnCodes error
     -result {unable to convert date-time string "1/1/2001 2/2/2002": more than one date in string}
 }
-
 test clock-34.50 {more than one time zone} {*}{
     -body {clock scan {10:00 EST CST}}
     -returnCodes error
     -result {unable to convert date-time string "10:00 EST CST": more than one time zone in string}
 }
-
 test clock-34.51 {more than one weekday} {*}{
     -body {clock scan {Monday Tuesday}}
     -returnCodes error
     -result {unable to convert date-time string "Monday Tuesday": more than one weekday in string}
 }
-
 test clock-34.52 {more than one ordinal month} {*}{
     -body {clock scan {next January next March}}
     -returnCodes error
     -result {unable to convert date-time string "next January next March": more than one ordinal month in string}
 }
-
-
+test clock-34.53 {clock scan, ISO 8601 point in time format} {
+    set time [clock scan "19921023T00:00:00"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} "Oct 23, 1992 00:00:00"
+test clock-34.54 {clock scan, ISO 8601 point in time format} {
+    set time [clock scan "1992-10-23T00:00:00"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} "Oct 23, 1992 00:00:00"
+test clock-34.55 {clock scan, ISO 8601 invalid TZ} -body {
+    set time [clock scan "19921023MST000000"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} -returnCodes error -match glob -result {unable to convert date-time string*}
+test clock-34.56 {clock scan, ISO 8601 invalid TZ} -body {
+    set time [clock scan "19921023M000000"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} -returnCodes error -match glob -result {unable to convert date-time string*}
+test clock-34.57 {clock scan, ISO 8601 invalid TZ} -body {
+    set time [clock scan "1992-10-23M00:00:00"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} -returnCodes error -match glob -result {unable to convert date-time string*}
+test clock-34.58 {clock scan, ISO 8601 invalid TZ} -body {
+    set time [clock scan "1992-10-23MST00:00:00"]
+    clock format $time -format {%b %d, %Y %H:%M:%S}
+} -returnCodes error -match glob -result {unable to convert date-time string*}
+test clock-34.59 {clock scan tests (-TZ)} {
+    set time [clock scan "31 Jan 14 23:59:59 -0100"]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Feb 01,2014 00:59:59 GMT}
+test clock-34.60 {clock scan tests (+TZ)} {
+    set time [clock scan "31 Jan 14 23:59:59 +0100"]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 31,2014 22:59:59 GMT}
+test clock-34.61 {clock scan tests (-TZ)} {
+    set time [clock scan "23:59:59 -0100" -base 0 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 02,1970 00:59:59 GMT}
+test clock-34.62 {clock scan tests (+TZ)} {
+    set time [clock scan "23:59:59 +0100" -base 0 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 01,1970 22:59:59 GMT}
+test clock-34.63 {clock scan tests (TZ)} {
+    set time [clock scan "Mon, 30 Jun 2014 23:59:59 CEST"]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jun 30,2014 21:59:59 GMT}
+test clock-34.64 {clock scan tests (TZ)} {
+    set time [clock scan "Fri, 31 Jan 2014 23:59:59 CET"]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 31,2014 22:59:59 GMT}
+test clock-34.65 {clock scan tests (relspec, day unit not TZ)} {
+    set time [clock scan "23:59:59 +15 day" -base 2000000 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Feb 08,1970 23:59:59 GMT}
+test clock-34.66 {clock scan tests (relspec, day unit not TZ)} {
+    set time [clock scan "23:59:59 -15 day" -base 2000000 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 09,1970 23:59:59 GMT}
+test clock-34.67 {clock scan tests (merid and TZ)} {
+    set time [clock scan "10:59 pm CET" -base 2000000 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 24,1970 21:59:00 GMT}
+test clock-34.68 {clock scan tests (merid and TZ)} {
+    set time [clock scan "10:59 pm +0100" -base 2000000 -gmt true]
+    clock format $time -format {%b %d,%Y %H:%M:%S %Z} -gmt true
+} {Jan 24,1970 21:59:00 GMT}
 
 # clock seconds
 test clock-35.1 {clock seconds tests} {
-    expr [clock seconds]+1
+    expr {[clock seconds] + 1}
     concat {}
 } {}
 test clock-35.2 {clock seconds tests} {
@@ -36920,12 +37005,10 @@ test clock-67.2 {Bug d19a30db57} -body {
     # error, not segfault
     tcl::clock::GetJulianDayFromEraYearMonthDay {} 2361222
 } -returnCodes error -match glob -result *
-
 test clock-67.3 {Bug d19a30db57} -body {
     # error, not segfault
     tcl::clock::GetJulianDayFromEraYearWeekDay {} 2361222
 } -returnCodes error -match glob -result *
-
 test clock-67.4 {Change format %x output on global locale change [Bug 4a0c163d24]} -setup {
     package require msgcat
     set current [msgcat::mclocale]
@@ -36937,7 +37020,6 @@ test clock-67.4 {Change format %x output on global locale change [Bug 4a0c163d24
 } -cleanup {
     msgcat::mclocale $current
 } -result {1 1}
-
 test clock-67.5 {Change scan %x output on global locale change [Bug 4a0c163d24]} -setup {
     package require msgcat
     set current [msgcat::mclocale]
index f19e11a..bb3ad98 100644 (file)
@@ -965,10 +965,10 @@ test cmdAH-19.11 {Tcl_FileObjCmd: exists} -constraints {unix notRoot} -setup {
 } -body {
     makeDirectory /tmp/tcl.foo.dir
     makeFile 12345 /tmp/tcl.foo.dir/file
-    file attributes /tmp/tcl.foo.dir -permissions 0000
+    file attributes /tmp/tcl.foo.dir -permissions 0o000
     file exists /tmp/tcl.foo.dir/file
 } -cleanup {
-    file attributes /tmp/tcl.foo.dir -permissions 0775
+    file attributes /tmp/tcl.foo.dir -permissions 0o775
     removeFile /tmp/tcl.foo.dir/file
     removeDirectory /tmp/tcl.foo.dir
 } -result 0
@@ -991,7 +991,7 @@ test cmdAH-19.12 {Bug 3608360: [file exists] mustn't do globbing} -setup {
 catch {testsetplatform $platform}
 removeFile $gorpfile
 set gorpfile [makeFile "Test string" gorp.file]
-catch {file attributes $gorpfile -permissions 0765}
+catch {file attributes $gorpfile -permissions 0o765}
 
 # avoid problems with non-local filesystems
 if {[testConstraint unix] && [file exists /tmp]} {
@@ -1092,7 +1092,7 @@ test cmdAH-23.4 {Tcl_FileObjCmd: lstat} -setup {
     unset -nocomplain stat
 } -constraints {unix nonPortable} -body {
     file lstat $linkfile stat
-    list $stat(nlink) [expr $stat(mode)&0777] $stat(type)
+    list $stat(nlink) [expr {$stat(mode) & 0o777}] $stat(type)
 } -result {1 511 link}
 test cmdAH-23.5 {Tcl_FileObjCmd: lstat errors} {nonPortable} {
     list [catch {file lstat _bogus_ stat} msg] [string tolower $msg] \
@@ -1407,7 +1407,7 @@ test cmdAH-27.4.1 {
 catch {testsetplatform $platform}
 removeFile $gorpfile
 set gorpfile [makeFile "Test string" gorp.file]
-catch {file attributes $gorpfile -permissions 0765}
+catch {file attributes $gorpfile -permissions 0o765}
 
 # stat
 test cmdAH-28.1 {Tcl_FileObjCmd: stat} -returnCodes error -body {
@@ -1434,8 +1434,8 @@ test cmdAH-28.5 {Tcl_FileObjCmd: stat} -constraints {unix} -setup {
     unset -nocomplain stat
 } -body {
     file stat $gorpfile stat
-    expr {$stat(mode) & 0o777}
-} -result {501}
+    format 0o%03o [expr {$stat(mode) & 0o777}]
+} -result 0o765
 test cmdAH-28.6 {Tcl_FileObjCmd: stat} {
     list [catch {file stat _bogus_ stat} msg] [string tolower $msg] $errorCode
 } {1 {could not read "_bogus_": no such file or directory} {POSIX ENOENT {no such file or directory}}}
@@ -1638,7 +1638,7 @@ test cmdAH-31.9 {Tcl_FileObjCmd: channels in other interp} {
     lsort [safeInterp eval [list file channels]]
 } [lsort [list stdout $newFileId]]
 test cmdAH-31.10 {Tcl_FileObjCmd: channels in other interp} {
-    # we can now write to $newFileId from slave
+    # we can now write to $newFileId from child
     safeInterp eval [list puts $newFileId "hello"]
 } {}
 interp transfer {} $newFileId safeInterp
@@ -1715,7 +1715,7 @@ unset -nocomplain platform
 
 # Tcl_ForObjCmd is tested in for.test
 
-catch {file attributes $dirfile -permissions 0777}
+catch {file attributes $dirfile -permissions 0o777}
 removeDirectory $dirfile
 removeFile $gorpfile
 # No idea how well [removeFile] copes with links...
index 68122dd..06171e4 100644 (file)
@@ -8,8 +8,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -19,6 +19,8 @@ catch [list package require -exact Tcltest [info patchlevel]]
 # Used for constraining memory leak tests
 testConstraint memory [llength [info commands memory]]
 testConstraint testobj [llength [info commands testobj]]
+source [file join [file dirname [info script]] internals.tcl]
+namespace import -force ::tcltest::internals::*
 
 test cmdIL-1.1 {Tcl_LsortObjCmd procedure} -returnCodes error -body {
     lsort
@@ -496,7 +498,7 @@ test cmdIL-5.5 {lsort with list style index and sharing} -body {
        foreach e $l {lappend n [list [expr {rand()}] $e]}
        lindex [lsort -real -index $l $n] 1 1
     }
-    expr srand(1)
+    expr {srand(1)}
     test_lsort 0
 } -result 0 -cleanup {
     rename test_lsort ""
@@ -504,6 +506,21 @@ test cmdIL-5.5 {lsort with list style index and sharing} -body {
 test cmdIL-5.6 {lsort with multiple list-style index options} {
     lsort -index {1 2 3} -index 0 {{a b} {c d} {b e}}
 } {{a b} {b e} {c d}}
+test cmdIL-5.7 {lsort memory exhaustion} -constraints {testWithLimit} -body {
+    # test it in child process (with limited address space) ca. 80MB extra memory
+    # on x64 system it would be not enough to sort 4M items (the half 2M only),
+    # warn and skip if no error (enough memory) or error by list creation:
+    testWithLimit \
+       -warn-on-code 0 -warn-on-alloc-error 1 \
+       -addmem [expr {$tcl_platform(pointerSize)*4000000 + $tcl_platform(pointerSize)*3*2000000}] \
+    {
+       # create list and get length (avoid too long output in interactive shells):
+       llength [set l [lrepeat 4000000 ""]]
+       # test OOM:
+       llength [lsort $l]
+    }
+    # expecting error no memory by sort
+} -returnCodes 1 -result {no enough memory to proccess sort of 4000000 items}
 
 # Compiled version
 test cmdIL-6.1 {lassign command syntax} -returnCodes error -body {
index 0a587e8..e690002 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
index 0f42f2f..fb2ca4a 100644 (file)
@@ -63,7 +63,7 @@ test cmdMZ-1.4 {Tcl_PwdObjCmd: failure} -setup {
     # This test fails on various unix platforms (eg Linux) where permissions
     # caching causes this to fail. The caching is strictly incorrect, but we
     # have no control over that.
-    file attr . -permissions 000
+    file attr . -permissions 0o000
     pwd
 } -returnCodes error -cleanup {
     cd $cwd
index bae26a0..826fbc6 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -590,13 +590,13 @@ test compExpr-old-15.3 {CompileMathFuncCall: too many arguments} -body {
 test compExpr-old-15.4 {CompileMathFuncCall: ')' found before last required arg} -body {
     catch {expr sin()} msg
     set ::errorInfo
-} -match glob -result {too few arguments for math function*
+} -match glob -result {not enough arguments for math function*
     while *ing
 "expr sin()"}
-test compExpr-old-15.5 {CompileMathFuncCall: too few arguments} -body {
+test compExpr-old-15.5 {CompileMathFuncCall: not enough arguments} -body {
     catch {expr pow(1)} msg
     set ::errorInfo
-} -match glob -result {too few arguments for math function*
+} -match glob -result {not enough arguments for math function*
     while *ing
 "expr pow(1)"}
 test compExpr-old-15.6 {CompileMathFuncCall: missing ')'} -body {
index 14c875d..7257726 100644 (file)
@@ -9,7 +9,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -314,7 +314,7 @@ test compExpr-4.9 {CompileCondExpr procedure, error in "false" clause} {
 } {0 15}
 
 test compExpr-5.1 {CompileMathFuncCall procedure, math function found} {
-    format %.6g [expr atan2(1.0, 2.0)]
+    format %.6g [expr {atan2(1.0, 2.0)}]
 } 0.463648
 test compExpr-5.2 {CompileMathFuncCall procedure, math function not found} -body {
     expr {do_it()}
@@ -325,11 +325,11 @@ test compExpr-5.3 {CompileMathFuncCall: call registered math function} testmathf
 test compExpr-5.4 {CompileMathFuncCall: call registered math function} testmathfunctions {
     expr T2()*3
 } 1035
-test compExpr-5.5 {CompileMathFuncCall procedure, too few arguments} -body {
+test compExpr-5.5 {CompileMathFuncCall procedure, not enough arguments} -body {
     expr {atan2(1.0)}
-} -returnCodes error -match glob -result {too few arguments for math function*}
+} -returnCodes error -match glob -result {not enough arguments for math function*}
 test compExpr-5.6 {CompileMathFuncCall procedure, complex argument} {
-    format %.6g [expr pow(2.1, 27.5-(24.4*(5%2)))]
+    format %.6g [expr {pow(2.1, 27.5-(24.4*(5%2)))}]
 } 9.97424
 test compExpr-5.7 {CompileMathFuncCall procedure, error in argument} -body {
     expr {sinh(2.*)}
@@ -353,9 +353,9 @@ test compExpr-7.1 {Memory Leak} -constraints memory -setup {
 } -body {
     set end [getbytes]
     for {set i 0} {$i < 5} {incr i} {
-       interp create slave
-       slave eval expr 1+2+3+4+5+6+7+8+9+10+11+12+13
-       interp delete slave
+       interp create child
+       child eval expr 1+2+3+4+5+6+7+8+9+10+11+12+13
+       interp delete child
        set tmp $end
        set end [getbytes]
     }
index cb41063..4a65330 100644 (file)
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
@@ -122,7 +124,7 @@ test compile-3.4 {TclCompileCatchCmd: bcc'ed [return] is caught} {
     proc foo {} {
        set fail [catch {
            return 1
-       }] ; # {}       
+       }] ; # {}
        return 2
     }
     foo
@@ -132,8 +134,8 @@ test compile-3.5 {TclCompileCatchCmd: recover from error, [Bug 705406]} {
        catch {
            if {[a]} {
                if b {}
-           }   
-       }   
+           }
+       }
     }
     list [catch foo msg] $msg
 } {0 1}
@@ -201,7 +203,7 @@ test compile-4.1 {TclCompileForCmd: command substituted test expression} {
     set i 0
     set j 0
     # Should be "forever"
-    for {} [expr $i < 3] {} {
+    for {} [expr {$i < 3}] {} {
        set j [incr i]
        if {$j > 3} break
     }
@@ -275,7 +277,7 @@ test compile-7.1 {TclCompileWhileCmd: command substituted test expression} {
     set i 0
     set j 0
     # Should be "forever"
-    while [expr $i < 3] {
+    while [expr {$i < 3}] {
        set j [incr i]
        if {$j > 3} break
     }
@@ -334,7 +336,7 @@ test compile-11.6 {Tcl_Append*: ensure Tcl_ResetResult is used properly} -body {
     apply {{} { set r [list foobar] ; incr}}
 } -returnCodes error -result {wrong # args: should be "incr varName ?increment?"}
 test compile-11.7 {Tcl_Append*: ensure Tcl_ResetResult is used properly} -body {
-    apply {{} { set r [list foobar] ; expr !a }}
+    apply {{} { set r [list foobar] ; expr [concat !a] }}
 } -returnCodes error -match glob -result *
 test compile-11.8 {Tcl_Append*: ensure Tcl_ResetResult is used properly} -body {
     apply {{} { set r [list foobar] ; expr {!a} }}
@@ -344,13 +346,13 @@ test compile-11.9 {Tcl_Append*: ensure Tcl_ResetResult is used properly} -body {
     list [catch {p} msg] $msg
 } -returnCodes error -result {unmatched open brace in list}
 
-# 
+#
 # Special section for tests of tclLiteral.c
 # The following tests check for incorrect memory handling in
 # TclReleaseLiteral. They are only effective when tcl is compiled with
 # TCL_MEM_DEBUG
 #
-# Special test for leak on interp delete [Bug 467523]. 
+# Special test for leak on interp delete [Bug 467523].
 test compile-12.1 {testing literal leak on interp delete} -setup {
     proc getbytes {} {
        set lines [split [memory info] "\n"]
@@ -359,10 +361,10 @@ test compile-12.1 {testing literal leak on interp delete} -setup {
 } -constraints memory -body {
     set end [getbytes]
     for {set i 0} {$i < 5} {incr i} {
-       interp create foo 
-       foo eval { 
+       interp create foo
+       foo eval {
            namespace eval bar {}
-       } 
+       }
        interp delete foo
        set tmp $end
        set end [getbytes]
@@ -383,7 +385,7 @@ test compile-12.2 {testing error on literal deletion} -constraints {memory exec}
        }
        puts 0
     } source.file]
-    exec [interpreter] $sourceFile 
+    exec [interpreter] $sourceFile
 } -cleanup {
     catch {removeFile $sourceFile}
 } -result 0
@@ -508,7 +510,7 @@ test compile-13.3 {TclCompileScript: testing check of max depth by nested script
     ti eval {set result {}}
 } -body {
     # Test different compilation variants (instructions evalStk, invokeStk, etc),
-    # with 500 nested scripts (bodies). It must generate "too many nested compilations" 
+    # with 500 nested scripts (bodies). It must generate "too many nested compilations"
     # error for any variant we're testing here:
     ti eval {foreach cmd {eval "if 1" try catch} {
        set c [gencode 500 $cmd]
@@ -516,7 +518,7 @@ test compile-13.3 {TclCompileScript: testing check of max depth by nested script
     }}
     #puts $errors
     # all of nested calls exceed the limit, so must end with "too many nested compilations"
-    # (or evaluations, depending on compile method/instruction and "mixed" compile within 
+    # (or evaluations, depending on compile method/instruction and "mixed" compile within
     # evaliation), so no one succeeds, the result must be empty:
     ti eval {set result}
 } -result {}
@@ -537,7 +539,7 @@ test compile-14.1 {testing errors in element name; segfault?} {} {
 test compile-14.2 {testing element name "$"} -body {
     unset -nocomplain a
     set a() 1
-    set a(1) 2 
+    set a(1) 2
     set a($) 3
     list [set a()] [set a(1)] [set a($)] [unset a() a(1); lindex [array names a] 0]
 } -cleanup {unset a} -result [list 1 2 3 {$}]
@@ -562,7 +564,7 @@ test compile-15.5 {proper TCL_RETURN code from [return]} {
 
 for {set noComp 0} {$noComp <= 1} {incr noComp} {
 
-if $noComp {
+if {$noComp} {
     interp alias {} run {} testevalex
     set constraints testevalex
 } else {
index eeb11ca..8ff5500 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index d14837e..15be790 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index df545f5..c60b568 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -66,7 +66,7 @@ test coroutine-1.3 {yield returns new arg} -setup {
            incr i
        }
     }
-    coroutine foo ::apply [list {{start 2} {stop 10}} $body] 
+    coroutine foo ::apply [list {{start 2} {stop 10}} $body]
     set res {}
 } -body {
     for {set k 1} {$k < 4} {incr k} {
@@ -476,7 +476,7 @@ test coroutine-5.1 {right numLevels on coro return} -constraints {testnrelevels}
        expr {[lindex [testnrelevels] 1] - 1}
     }
     proc relativeLevel base {
-       # remove the level for this proc's call 
+       # remove the level for this proc's call
        expr {[getNumLevel] - $base - 1}
     }
     proc foo {} {
@@ -517,7 +517,7 @@ test coroutine-5.2 {right numLevels within coro} -constraints {testnrelevels} \
        expr {[lindex [testnrelevels] 1] - 1}
     }
     proc relativeLevel base {
-       # remove the level for this proc's call 
+       # remove the level for this proc's call
        expr {[getNumLevel] - $base - 1}
     }
     proc foo base {
@@ -588,7 +588,7 @@ test coroutine-7.2 {multi-argument yielding with yieldto} -body {
     coroutine a corobody
     coroutine b corobody
     list [a x] [a y z] [a \{p] [a \{q r] [a] [a] [rename a {}] \
-       [b ok] [rename b {}] 
+       [b ok] [rename b {}]
 } -cleanup {
     rename corobody {}
 } -result {x {y z 2} \{p {\{q r 2} {} 0 {} ok {}}
@@ -771,25 +771,25 @@ test coroutine-8.0.1 {coro inject after error} -body {
     lappend ::result [catch {demo} err] $err
 } -result {inject-executed 1 test}
 test coroutine-8.1.1 {coro inject, ticket 42202ba1e5ff566e} -body {
-    interp create slave
-    slave eval {
+    interp create child
+    child eval {
        coroutine demo apply {{} { while {1} yield }}
        demo
        tcl::unsupported::inject demo set ::result inject-executed
     }
-    interp delete slave
+    interp delete child
 } -result {}
 test coroutine-8.1.2 {coro inject with result, ticket 42202ba1e5ff566e} -body {
-    interp create slave
-    slave eval {
+    interp create child
+    child eval {
        coroutine demo apply {{} { while {1} yield }}
        demo
        tcl::unsupported::inject demo set ::result inject-executed
     }
-    slave eval demo
-    set result [slave eval {set ::result}]
+    child eval demo
+    set result [child eval {set ::result}]
 
-    interp delete slave
+    interp delete child
     set result
 } -result {inject-executed}
 
index 41dd777..7d86135 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
index a6b0cb4..6ede398 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 06121a3..8a24ebe 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -180,16 +180,37 @@ test dstring-2.12 {appending list elements} -constraints testdstring -setup {
 } -cleanup {
     testdstring free
 } -result {x #}
-test dstring-2.13 {appending list elements} -constraints testdstring -body {
-    # This test shows lack of sophistication in Tcl_DStringAppendElement's
-    # decision about whether #-quoting can be disabled.
+test dstring-2.13 {appending list elements} -constraints testdstring -setup {
     testdstring free
+} -body {
+    # This test checks the sophistication in Tcl_DStringAppendElement's
+    # decision about whether #-quoting can be disabled.
     testdstring append "x " -1
     testdstring element #
     testdstring get
 } -cleanup {
     testdstring free
-} -result {x {#}}
+} -result {x #}
+test dstring-2.14 {appending list elements} -constraints testdstring -setup {
+    testdstring free
+} -body {
+    testdstring append "  " -1
+    testdstring element #
+    testdstring get
+} -cleanup {
+    testdstring free
+} -result {  {#}}
+test dstring-2.15 {appending list elements} -constraints testdstring -setup {
+    testdstring free
+} -body {
+    # This test checks the sophistication in Tcl_DStringAppendElement's
+    # decision about whether #-quoting can be disabled.
+    testdstring append "x  " -1
+    testdstring element #
+    testdstring get
+} -cleanup {
+    testdstring free
+} -result {x  #}
 
 test dstring-3.1 {nested sublists} -constraints testdstring -setup {
     testdstring free
@@ -306,10 +327,11 @@ test dstring-3.9 {appending list elements} -constraints testdstring -setup {
 } -cleanup {
     testdstring free
 } -result {x {x #}}
-test dstring-3.10 {appending list elements} -constraints testdstring -body {
-    # This test shows lack of sophistication in Tcl_DStringAppendElement's
-    # decision about whether #-quoting can be disabled.
+test dstring-3.10 {appending list elements} -constraints testdstring -setup {
     testdstring free
+} -body {
+    # This test checks the sophistication in Tcl_DStringAppendElement's
+    # decision about whether #-quoting can be disabled.
     testdstring append x -1
     testdstring start
     testdstring append "x " -1
@@ -318,7 +340,33 @@ test dstring-3.10 {appending list elements} -constraints testdstring -body {
     testdstring get
 } -cleanup {
     testdstring free
-} -result {x {x {#}}}
+} -result {x {x #}}
+test dstring-3.11 {appending list elements} -constraints testdstring -setup {
+    testdstring free
+} -body {
+    testdstring append x -1
+    testdstring start
+    testdstring append "  " -1
+    testdstring element #
+    testdstring end
+    testdstring get
+} -cleanup {
+    testdstring free
+} -result {x {  {#}}}
+test dstring-3.12 {appending list elements} -constraints testdstring -setup {
+    testdstring free
+} -body {
+    # This test checks the sophistication in Tcl_DStringAppendElement's
+    # decision about whether #-quoting can be disabled.
+    testdstring append x -1
+    testdstring start
+    testdstring append "x  " -1
+    testdstring element #
+    testdstring end
+    testdstring get
+} -cleanup {
+    testdstring free
+} -result {x {x  #}}
 
 test dstring-4.1 {truncation} -constraints testdstring -setup {
     testdstring free
index 36fcff6..72d218b 100644 (file)
@@ -8,13 +8,14 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 namespace eval ::tcl::test::encoding {
     variable x
 
-namespace import -force ::tcltest::*
-
 catch {
     ::tcltest::loadTestedCommands
     package require -exact Tcltest [info patchlevel]
@@ -34,7 +35,10 @@ proc runtests {} {
 
 # Some tests require the testencoding command
 testConstraint testencoding [llength [info commands testencoding]]
-testConstraint fullutf [expr {[format %c 0x010000] != "\ufffd"}]
+testConstraint testbytestring [llength [info commands testbytestring]]
+testConstraint teststringbytes [llength [info commands teststringbytes]]
+testConstraint ucs2 [expr {[format %c 0x010000] eq "\uFFFD"}]
+testConstraint fullutf [expr {[format %c 0x010000] ne "\uFFFD"}]
 testConstraint exec [llength [info commands exec]]
 testConstraint testgetdefenc [llength [info commands testgetdefenc]]
 \f
@@ -282,16 +286,16 @@ test encoding-11.6 {LoadEncodingFile: invalid file} -constraints {testencoding}
 # OpenEncodingFile is fully tested by the rest of the tests in this file.
 
 test encoding-12.1 {LoadTableEncoding: normal encoding} {
-    set x [encoding convertto iso8859-3 \u120]
-    append x [encoding convertto iso8859-3 \ud5]
-    append x [encoding convertfrom iso8859-3 \xd5]
+    set x [encoding convertto iso8859-3 \u0120]
+    append x [encoding convertto iso8859-3 \xD5]
+    append x [encoding convertfrom iso8859-3 \xD5]
 } "\xd5?\u120"
 test encoding-12.2 {LoadTableEncoding: single-byte encoding} {
     set x [encoding convertto iso8859-3 ab\u0120g]
-    append x [encoding convertfrom iso8859-3 ab\xd5g]
+    append x [encoding convertfrom iso8859-3 ab\xD5g]
 } "ab\xd5gab\u120g"
 test encoding-12.3 {LoadTableEncoding: multi-byte encoding} {
-    set x [encoding convertto shiftjis ab\u4e4eg]
+    set x [encoding convertto shiftjis ab\u4E4Eg]
     append x [encoding convertfrom shiftjis ab\x8c\xc1g]
 } "ab\x8c\xc1gab\u4e4eg"
 test encoding-12.4 {LoadTableEncoding: double-byte encoding} {
@@ -303,6 +307,9 @@ test encoding-12.5 {LoadTableEncoding: symbol encoding} {
     append x [encoding convertto symbol \u67]
     append x [encoding convertfrom symbol \x67]
 } "\x67\x67\u3b3"
+test encoding-12.6 {LoadTableEncoding: overflow in char value} ucs2 {
+    encoding convertto iso8859-3 \U010000
+} "?"
 
 test encoding-13.1 {LoadEscapeTable} {
     viewable [set x [encoding convertto iso2022 ab\u4e4e\u68d9g]]
@@ -315,35 +322,31 @@ test encoding-14.1 {BinaryProc} {
 test encoding-15.1 {UtfToUtfProc} {
     encoding convertto utf-8 \xa3
 } "\xc2\xa3"
-test encoding-15.2 {UtfToUtfProc null character output} {
-    set x \u0000
-    set y [encoding convertto utf-8 \u0000]
-    set y [encoding convertfrom identity $y]
-    binary scan $y H* z
-    list [string bytelength $x] [string bytelength $y] $z
-} {2 1 00}
-test encoding-15.3 {UtfToUtfProc null character input} {
-    set x [encoding convertfrom identity \x00]
-    set y [encoding convertfrom utf-8 $x]
-    binary scan [encoding convertto identity $y] H* z
-    list [string bytelength $x] [string bytelength $y] $z
-} {1 2 c080}
-test encoding-15.4 {UtfToUtfProc emoji character input} {
+test encoding-15.2 {UtfToUtfProc null character output} testbytestring {
+    binary scan [testbytestring [encoding convertto utf-8 \u0000]] H* z
+    set z
+} 00
+test encoding-15.3 {UtfToUtfProc null character input} teststringbytes {
+    set y [encoding convertfrom utf-8 [encoding convertto utf-8 \u0000]]
+    binary scan [teststringbytes $y] H* z
+    set z
+} c080
+test encoding-15.4 {UtfToUtfProc emoji character input} -body {
     set x \xED\xA0\xBD\xED\xB8\x82
     set y [encoding convertfrom utf-8 \xED\xA0\xBD\xED\xB8\x82]
-    list [string length $x] [string length $y] $y
-} "6 2 \uD83D\uDE02"
+    list [string length $x] $y
+} -result "6 \uD83D\uDE02"
 test encoding-15.5 {UtfToUtfProc emoji character input} {
     set x \xF0\x9F\x98\x82
     set y [encoding convertfrom utf-8 \xF0\x9F\x98\x82]
-    list [string length $x] [string length $y] $y
-} "4 \uD83D\uDE02"
+    list [string length $x] $y
+} "4 \uD83D\uDE02"
 test encoding-15.6 {UtfToUtfProc emoji character output} {
     set x \uDE02\uD83D\uDE02\uD83D
     set y [encoding convertto utf-8 \uDE02\uD83D\uDE02\uD83D]
     binary scan $y H* z
-    list [string length $x] [string length $y] $z
-} {10 edb882f09f9882eda0bd}
+    list [string length $y] $z
+} {10 edb882f09f9882eda0bd}
 test encoding-15.7 {UtfToUtfProc emoji character output} {
     set x \uDE02\uD83D\uD83D
     set y [encoding convertto utf-8 \uDE02\uD83D\uD83D]
@@ -362,19 +365,70 @@ test encoding-15.9 {UtfToUtfProc emoji character output} {
     binary scan $y H* z
     list [string length $x] [string length $y] $z
 } {3 7 edb882eda0bd58}
+test encoding-15.10 {UtfToUtfProc high surrogate character output} {
+    set x \uDE02\xE9
+    set y [encoding convertto utf-8 \uDE02\xE9]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {2 5 edb882c3a9}
+test encoding-15.11 {UtfToUtfProc low surrogate character output} {
+    set x \uDA02\xE9
+    set y [encoding convertto utf-8 \uDA02\xE9]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {2 5 eda882c3a9}
+test encoding-15.12 {UtfToUtfProc high surrogate character output} {
+    set x \uDE02Y
+    set y [encoding convertto utf-8 \uDE02Y]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {2 4 edb88259}
+test encoding-15.13 {UtfToUtfProc low surrogate character output} {
+    set x \uDA02Y
+    set y [encoding convertto utf-8 \uDA02Y]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {2 4 eda88259}
+test encoding-15.14 {UtfToUtfProc high surrogate character output} {
+    set x \uDE02
+    set y [encoding convertto utf-8 \uDE02]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {1 3 edb882}
+test encoding-15.15 {UtfToUtfProc low surrogate character output} {
+    set x \uDA02
+    set y [encoding convertto utf-8 \uDA02]
+    binary scan $y H* z
+    list [string length $x] [string length $y] $z
+} {1 3 eda882}
+test encoding-15.16 {UtfToUtfProc: Invalid 4-byte UTF-8, see [ed29806ba]} {
+    set x \xF0\xA0\xA1\xC2
+    set y [encoding convertfrom utf-8 \xF0\xA0\xA1\xC2]
+    list [string length $x] $y
+} "4 \xF0\xA0\xA1\xC2"
 
 test encoding-16.1 {UnicodeToUtfProc} {
     set val [encoding convertfrom unicode NN]
     list $val [format %x [scan $val %c]]
 } "\u4e4e 4e4e"
 test encoding-16.2 {UnicodeToUtfProc} -constraints fullutf -body {
-    set val [encoding convertfrom unicode "\xd8\xd8\xdc\xdc"]
+    set val [encoding convertfrom unicode "\xD8\xD8\xDC\xDC"]
+    list $val [format %x [scan $val %c]]
+} -result "\U460DC 460dc"
+test encoding-16.3 {UnicodeToUtfProc} -body {
+    set val [encoding convertfrom unicode "\xDC\xDC"]
     list $val [format %x [scan $val %c]]
-} -result "\U460dc 460dc"
+} -result "\uDCDC dcdc"
 
 test encoding-17.1 {UtfToUnicodeProc} -constraints fullutf -body {
-    encoding convertto unicode "\U460dc"
-} -result "\xd8\xd8\xdc\xdc"
+    encoding convertto unicode "\U460DC"
+} -result "\xD8\xD8\xDC\xDC"
+test encoding-17.2 {UtfToUnicodeProc} -body {
+    encoding convertto unicode "\uDCDC"
+} -result "\xDC\xDC"
+test encoding-17.3 {UtfToUnicodeProc} -body {
+    encoding convertto unicode "\uD8D8"
+} -result "\xD8\xD8"
 
 test encoding-18.1 {TableToUtfProc} {
 } {}
@@ -661,6 +715,21 @@ test encoding-27.2 {encoding dirs basic behavior} -returnCodes error -body {
 } -result "expected directory list but got \"\{not a list\""
 
 }
+
+
+test encoding-28.0 {all encodings load} -body {
+       set string hello
+       foreach name [encoding names] {
+               incr count
+               encoding convertto $name $string
+
+               # discard the cached internal representation of Tcl_Encoding
+               # Unfortunately, without this, encoding 2-1 fails.
+               llength $name
+       }
+       return $count
+} -result 81
+
 runtests
 
 }
index e6ce44d..036c7a2 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -100,7 +100,7 @@ proc cleanup1 {} {
 variable keep {
     TCL_LIBRARY PATH LD_LIBRARY_PATH LIBPATH PURE_PROG_NAME DISPLAY
     SHLIB_PATH SYSTEMDRIVE SYSTEMROOT DYLD_LIBRARY_PATH DYLD_FRAMEWORK_PATH
-    DYLD_NEW_LOCAL_SHARED_REGIONS DYLD_NO_FIX_PREBINDING
+    DYLD_NEW_LOCAL_SHARED_REGIONS DYLD_NO_FIX_PREBINDING MSYSTEM
     __CF_USER_TEXT_ENCODING SECURITYSESSIONID LANG WINDIR TERM
     CommonProgramFiles ProgramFiles CommonProgramW6432 ProgramW6432
 }
@@ -217,6 +217,26 @@ test env-2.4 {
 NAME2=more
 XYZZY=garbage}
 
+test env-2.5 {different encoding (wide chars)} -constraints {win exec} -setup {
+    # be sure set of (unicode) environment occurs if single-byte encoding is used:
+    encodingswitch cp1252
+    # german (cp1252) and russian (cp1251) characters together encoded as utf-8:
+    set val 2d2dc3a4c3b6c3bcc39f2dd182d0b5d181d1822d2d
+    set env(XYZZY) [encoding convertfrom utf-8 [binary decode hex $val]]
+    # now switch to utf-8 (to see correct values from test):
+    encoding system utf-8
+} -body {
+    exec [interpreter] << [string map [list \$val $val] {
+       encoding system utf-8; fconfigure stdout -encoding utf-8
+       set test [encoding convertfrom utf-8 [binary decode hex $val]]
+       puts "[expr {$env(XYZZY) eq $test}] \ngot:\t\
+           $env(XYZZY) ([binary encode hex [encoding convertto $env(XYZZY)]]) \nexp:\t\
+           $test ([binary encode hex [encoding convertto $test]])"
+    }]
+} -cleanup {
+    encodingrestore
+    unset -nocomplain val f env(XYZZY)
+} -match glob -result {1 *}
 
 test env-3.1 {
     changing environment variables
@@ -304,11 +324,11 @@ test env-5.2 {corner cases - unset the env array} -setup {
 } -result {0}
 
 
-test env-5.3 {corner cases: unset the env in master should unset child} -setup {
+test env-5.3 {corner cases: unset the env in parent should unset child} -setup {
     setup1
     interp create i
 } -body {
-    # Variables deleted in a master interp should be deleted in child interp
+    # Variables deleted in a parent interp should be deleted in child interp
     # too.
     i eval {set env(THIS_SHOULD_EXIST) a}
     set result [set env(THIS_SHOULD_EXIST)]
index af07ed7..a111c80 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 70ceac8..d473fdf 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index 67a980b..77f13d3 100644 (file)
@@ -9,8 +9,10 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 catch {
     ::tcltest::loadTestedCommands
@@ -23,16 +25,18 @@ testConstraint testfilehandler [llength [info commands testfilehandler]]
 testConstraint testexithandler [llength [info commands testexithandler]]
 testConstraint testfilewait [llength [info commands testfilewait]]
 testConstraint exec [llength [info commands exec]]
-\f
+testConstraint notOSX [expr {$::tcl_platform(os) ne "Darwin"}]
+
 test event-1.1 {Tcl_CreateFileHandler, reading} -setup {
     testfilehandler close
     set result ""
-} -constraints {testfilehandler} -body {
+} -constraints {testfilehandler notOSX} -body {
     testfilehandler create 0 readable off
     testfilehandler clear 0
     testfilehandler oneevent
     lappend result [testfilehandler counts 0]
     testfilehandler fillpartial 0
+    update idletasks
     testfilehandler oneevent
     lappend result [testfilehandler counts 0]
     testfilehandler oneevent
@@ -595,16 +599,16 @@ test event-11.7 {Bug 16828b3744} {
 test event-11.8 {Bug 16828b3744} -setup {
     oo::class create A {
        variable continue
-    
+
        method start {} {
            after idle [self] destroy
-        
+
            set continue 0
            vwait [namespace current]::continue
        }
        destructor {
            set continue 1
-       }       
+       }
     }
 } -body {
     [A new] start
index 6570e57..af7aae5 100644 (file)
 # There is no point in running Valgrind on cases where [exec] forks but then
 # fails and the child process doesn't go through full cleanup.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 package require tcltests
 
 # All tests require the "exec" command.
 # Skip them if exec is not defined.
 testConstraint exec [llength [info commands exec]]
+# Some skips when running in a macOS CI environment
+testConstraint noosxCI [expr {![info exists ::env(MAC_CI)]}]
+
 unset -nocomplain path
 
 # Utilities that are like bourne shell stalwarts, but cross-platform.
@@ -667,7 +672,9 @@ test exec-18.2 {exec cat deals with weird file names} -body {
 # Note that this test cannot be adapted to work on Windows; that platform has
 # no kernel support for an analog of O_APPEND. OTOH, that means we can assume
 # that there is a POSIX shell...
-test exec-19.1 {exec >> uses O_APPEND} -constraints {exec unix notValgrind} -setup {
+#
+# This test also fails in some cases when building with macOS
+test exec-19.1 {exec >> uses O_APPEND} -constraints {exec unix notValgrind noosxCI} -setup {
     set tmpfile [makeFile {0} tmpfile.exec-19.1]
 } -body {
     # Note that we have to allow for the current contents of the temporary
@@ -703,9 +710,6 @@ test exec-20.1 {exec .CMD file} -constraints {win} -body {
     exec [makeFile "echo %1> $log" exec201.CMD] "Testing exec-20.1"
     viewFile $log
 } -result "\"Testing exec-20.1\""
-    
-
-
 \f
 # ----------------------------------------------------------------------
 # cleanup
index 468901d..4b0f87f 100644 (file)
@@ -15,7 +15,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -657,56 +657,56 @@ test execute-6.8 {TclCompEvalObj: bytecode name resolution epoch validation} -se
     namespace delete foo
 } -result {0 AHA!}
 test execute-6.9 {TclCompEvalObj: bytecode interp validation} -setup {
-    interp create slave
+    interp create child
 } -body {
     set script { llength {} }
-    slave eval {proc llength args {return AHA!}}
+    child eval {proc llength args {return AHA!}}
     set result {}
     lappend result [if 1 $script]
-    lappend result [slave eval $script]
+    lappend result [child eval $script]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {0 AHA!}
 test execute-6.10 {TclCompEvalObj: bytecode interp validation} -body {
     set script { llength {} }
-    interp create slave
+    interp create child
     set result {}
-    lappend result [slave eval $script]
-    interp delete slave
-    interp create slave
-    lappend result [slave eval $script]
+    lappend result [child eval $script]
+    interp delete child
+    interp create child
+    lappend result [child eval $script]
 } -cleanup {
-    catch {interp delete slave}
+    catch {interp delete child}
 } -result {0 0}
 test execute-6.11 {Tcl_ExprObj: exprcode interp validation} -setup {
-    interp create slave
+    interp create child
 } -constraints testexprlongobj -body {
     set e { [llength {}]+1 }
     set result {}
-    load {} Tcltest slave
-    interp alias {} e slave testexprlongobj
+    load {} Tcltest child
+    interp alias {} e child testexprlongobj
     lappend result [e $e]
-    interp delete slave
-    interp create slave
-    load {} Tcltest slave
-    interp alias {} e slave testexprlongobj
+    interp delete child
+    interp create child
+    load {} Tcltest child
+    interp alias {} e child testexprlongobj
     lappend result [e $e]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {{This is a result: 1} {This is a result: 1}}
 test execute-6.12 {Tcl_ExprObj: exprcode interp validation} -setup {
-    interp create slave
+    interp create child
 } -body {
     set e { [llength {}]+1 }
     set result {}
-    interp alias {} e slave expr
+    interp alias {} e child expr
     lappend result [e $e]
-    interp delete slave
-    interp create slave
-    interp alias {} e slave expr 
+    interp delete child
+    interp create child
+    interp alias {} e child expr
     lappend result [e $e]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {1 1}
 test execute-6.13 {Tcl_ExprObj: exprcode epoch validation} -body {
     set e { [llength {}]+1 }
@@ -747,16 +747,16 @@ test execute-6.15 {Tcl_ExprObj: exprcode name resolution epoch validation} -setu
     namespace delete foo
 } -result {1 2}
 test execute-6.16 {Tcl_ExprObj: exprcode interp validation} -setup {
-    interp create slave
+    interp create child
 } -body {
     set e { [llength {}]+1 }
-    interp alias {} e slave expr
-    slave eval {proc llength args {return 1}}
+    interp alias {} e child expr
+    child eval {proc llength args {return 1}}
     set result {}
     lappend result [expr $e]
     lappend result [e $e]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {1 2}
 test execute-6.17 {Tcl_ExprObj: exprcode context validation} -body {
     proc foo e {set v 0; expr $e}
@@ -821,49 +821,49 @@ test execute-7.10 {Wide int handling in INST_MOD} {
     expr {((wide(1)<<60)-1) % 0x400000000}
 } 17179869183
 test execute-7.11 {Wide int handling in INST_LSHIFT} {
-    expr wide(42)<<30
+    expr {wide(42) << 30}
 } 45097156608
 test execute-7.12 {Wide int handling in INST_LSHIFT} {
-    expr 12345678901<<3
+    expr {12345678901 << 3}
 } 98765431208
 test execute-7.13 {Wide int handling in INST_RSHIFT} {
-    expr 0x543210febcda9876>>7
+    expr {0x543210febcda9876 >> 7}
 } 47397893236700464
 test execute-7.14 {Wide int handling in INST_RSHIFT} {
-    expr wide(0x9876543210febcda)>>7
+    expr {wide(0x9876543210febcda) >> 7}
 } -58286587177206407
 test execute-7.15 {Wide int handling in INST_BITOR} {
-    expr wide(0x9876543210febcda) | 0x543210febcda9876
+    expr {wide(0x9876543210febcda) | 0x543210febcda9876}
 } -2560765885044310786
 test execute-7.16 {Wide int handling in INST_BITXOR} {
-    expr wide(0x9876543210febcda) ^ 0x543210febcda9876
+    expr {wide(0x9876543210febcda) ^ 0x543210febcda9876}
 } -3727778945703861076
 test execute-7.17 {Wide int handling in INST_BITAND} {
-    expr wide(0x9876543210febcda) & 0x543210febcda9876
+    expr {wide(0x9876543210febcda) & 0x543210febcda9876}
 } 1167013060659550290
 test execute-7.18 {Wide int handling in INST_ADD} {
-    expr wide(0x7fffffff)+wide(0x7fffffff)
+    expr {wide(0x7fffffff) + wide(0x7fffffff)}
 } 4294967294
 test execute-7.19 {Wide int handling in INST_ADD} {
-    expr 0x7fffffff+wide(0x7fffffff)
+    expr {0x7fffffff + wide(0x7fffffff)}
 } 4294967294
 test execute-7.20 {Wide int handling in INST_ADD} {
-    expr wide(0x7fffffff)+0x7fffffff
+    expr {wide(0x7fffffff) + 0x7fffffff}
 } 4294967294
 test execute-7.21 {Wide int handling in INST_ADD} {
-    expr double(0x7fffffff)+wide(0x7fffffff)
+    expr {double(0x7fffffff) + wide(0x7fffffff)}
 } 4294967294.0
 test execute-7.22 {Wide int handling in INST_ADD} {
-    expr wide(0x7fffffff)+double(0x7fffffff)
+    expr {wide(0x7fffffff) + double(0x7fffffff)}
 } 4294967294.0
 test execute-7.23 {Wide int handling in INST_SUB} {
-    expr 0x123456789a-0x20406080a
+    expr {0x123456789a - 0x20406080a}
 } 69530054800
 test execute-7.24 {Wide int handling in INST_MULT} {
-    expr 0x123456789a*193
+    expr {0x123456789a * 193}
 } 15090186251290
 test execute-7.25 {Wide int handling in INST_DIV} {
-    expr 0x123456789a/193
+    expr {0x123456789a / 193}
 } 405116546
 test execute-7.26 {Wide int handling in INST_UPLUS} {
     set x 0x123456871234568
@@ -982,9 +982,9 @@ test execute-8.5 {Bug 2038069} -setup {
 "catch \[list error FOO\] m o"} -errorline 2}
 
 test execute-8.6 {Compile epoch bump in global level (bug [fa6bf38d07])} -setup {
-    interp create slave
-    slave eval {
-       package require tcltest
+    interp create child
+    child eval {
+       package require tcltest 2.5
        catch [list package require -exact Tcltest [info patchlevel]]
        ::tcltest::loadTestedCommands
        if {[namespace which -command testbumpinterpepoch] eq ""} {
@@ -992,32 +992,32 @@ test execute-8.6 {Compile epoch bump in global level (bug [fa6bf38d07])} -setup
        }
     }
 } -body {
-    slave eval {
+    child eval {
        lappend res A; testbumpinterpepoch; lappend res B; return; lappend res C;
     }
-    slave eval {
+    child eval {
        set i 0; while {[incr i] < 3} {
            lappend res A; testbumpinterpepoch; lappend res B; return; lappend res C;
        }
     }
-    slave eval {
+    child eval {
        set i 0; while {[incr i] < 3} {
            lappend res A; testbumpinterpepoch; lappend res B; break; lappend res C;
        }
     }
-    slave eval {
+    child eval {
        catch {
            lappend res A; testbumpinterpepoch; lappend res B; error test; lappend res C;
        }
     }
-    slave eval {set res}
+    child eval {set res}
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result [lrepeat 4 A B]
 test execute-8.7 {Compile epoch bump in global level (bug [fa6bf38d07]), exception case} -setup {
-    interp create slave
-    slave eval {
-       package require tcltest
+    interp create child
+    child eval {
+       package require tcltest 2.5
        catch [list package require -exact Tcltest [info patchlevel]]
        ::tcltest::loadTestedCommands
        if {[namespace which -command testbumpinterpepoch] eq ""} {
@@ -1027,28 +1027,28 @@ test execute-8.7 {Compile epoch bump in global level (bug [fa6bf38d07]), excepti
 } -body {
     set res {}
     lappend res [catch {
-       slave eval {
+       child eval {
           lappend res A; testbumpinterpepoch; lappend res B; return -code error test; lappend res C;
        }
     } e] $e
     lappend res [catch {
-       slave eval {
+       child eval {
           lappend res A; testbumpinterpepoch; lappend res B; error test; lappend res C;
        }
     } e] $e
     lappend res [catch {
-       slave eval {
+       child eval {
           lappend res A; testbumpinterpepoch; lappend res B; return -code return test; lappend res C;
        }
     } e] $e
     lappend res [catch {
-       slave eval {
+       child eval {
           lappend res A; testbumpinterpepoch; lappend res B; break; lappend res C;
        }
     } e] $e
-    list $res [slave eval {set res}]
+    list $res [child eval {set res}]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result [list {1 test 1 test 2 test 3 {}} [lrepeat 4 A B]]
 
 test execute-9.1 {Interp result resetting [Bug 1522803]} {
@@ -1069,16 +1069,16 @@ test execute-10.1 {TclExecuteByteCode, INST_CONCAT1, bytearrays} {
     apply {s {binary scan $s c x; list $x [scan $s$s %c%c]}} \u0130
 } {48 {304 304}}
 test execute-10.2 {Bug 2802881} -setup {
-    interp create slave
+    interp create child
 } -body {
     # If [Bug 2802881] is not fixed, this will segfault
-    slave eval {
+    child eval {
        trace add variable ::errorInfo write {expr {$foo} ;#}
        proc demo {} {a {}{}}
        demo
     }
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -match glob -result *
 test execute-10.3 {Bug 3072640} -setup {
     proc generate {n} {
@@ -1086,8 +1086,8 @@ test execute-10.3 {Bug 3072640} -setup {
            yield $i
        }
     }
-    proc t {args} { 
-       incr ::foo 
+    proc t {args} {
+       incr ::foo
     }
     set ::foo 0
     trace add execution ::generate enterstep ::t
@@ -1103,9 +1103,9 @@ test execute-10.3 {Bug 3072640} -setup {
 } -result 4
 
 test execute-11.1 {Bug 3142026: GrowEvaluationStack off-by-one} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave eval {
+    child eval {
        set x [lrepeat 1320 199]
        for {set i 0} {$i < 20} {incr i} {
            lappend x $i
@@ -1115,7 +1115,7 @@ test execute-11.1 {Bug 3142026: GrowEvaluationStack off-by-one} -setup {
        return ok
     }
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result ok
 
 test execute-11.2 {Bug 268b23df11} -setup {
index 06a00ba..28ec346 100644 (file)
@@ -861,7 +861,7 @@ test expr-old-32.46 {math functions in expressions} -body {
 } -match glob -result {1 {too many arguments for math function*}}
 test expr-old-32.47 {math functions in expressions} -body {
     list [catch {expr srand()} msg] $msg
-} -match glob -result {1 {too few arguments for math function*}}
+} -match glob -result {1 {not enough arguments for math function*}}
 test expr-old-32.48 {math functions in expressions} -body {
     expr srand(3.79)
 } -returnCodes error -match glob -result *
@@ -918,7 +918,7 @@ test expr-old-34.6 {errors in math functions} -body {
 } -returnCodes error -match glob -result *
 test expr-old-34.7 {errors in math functions} -body {
     list [catch {expr hypot(1.0)} msg] $msg
-} -match glob -result {1 {too few arguments for math function*}}
+} -match glob -result {1 {not enough arguments for math function*}}
 test expr-old-34.8 {errors in math functions} -body {
     list [catch {expr hypot(1.0, 2.0, 3.0)} msg] $msg
 } -match glob -result {1 {too many arguments for math function*}}
@@ -1160,7 +1160,7 @@ test expr-old-40.2 {min math function} -body {
 } -result 0.0
 test expr-old-40.3 {min math function} -body {
     list [catch {expr {min()}} msg] $msg
-} -result {1 {too few arguments to math function "min"}}
+} -result {1 {not enough arguments to math function "min"}}
 test expr-old-40.4 {min math function} -body {
     expr {min(wide(-1) << 30, 4.5, -10)}
 } -result [expr {wide(-1) << 30}]
@@ -1179,7 +1179,7 @@ test expr-old-41.2 {max math function} -body {
 } -result 0.0
 test expr-old-41.3 {max math function} -body {
     list [catch {expr {max()}} msg] $msg
-} -result {1 {too few arguments to math function "max"}}
+} -result {1 {not enough arguments to math function "max"}}
 test expr-old-41.4 {max math function} -body {
     expr {max(wide(1) << 30, 4.5, -10)}
 } -result [expr {wide(1) << 30}]
index 6e6a358..37d8fe3 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2.1
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -673,13 +673,13 @@ test expr-15.3 {CompileMathFuncCall: too many arguments} -body {
 test expr-15.4 {CompileMathFuncCall: ')' found before last required arg} -body {
     catch {expr sin()} msg
     set ::errorInfo
-} -match glob -result {too few arguments for math function*
+} -match glob -result {not enough arguments for math function*
     while *ing
 "expr sin()"}
-test expr-15.5 {CompileMathFuncCall: too few arguments} -body {
+test expr-15.5 {CompileMathFuncCall: not enough arguments} -body {
     catch {expr pow(1)} msg
     set ::errorInfo
-} -match glob -result {too few arguments for math function*
+} -match glob -result {not enough arguments for math function*
     while *ing
 "expr pow(1)"}
 test expr-15.6 {CompileMathFuncCall: missing ')'} -body {
@@ -6845,6 +6845,72 @@ test expr-41.2 {exponent underflow} {
     expr 1.0e-2147483630
 } 0.0
 
+test expr-41.3 {exponent overflow} {
+    expr 1e2147483647
+} Inf
+test expr-41.4 {exponent overflow} {
+    expr 1e2147483648
+} Inf
+test expr-41.5 {exponent overflow} {
+    expr 100e2147483645
+} Inf
+test expr-41.6 {exponent overflow} {
+    expr 100e2147483646
+} Inf
+test expr-41.7 {exponent overflow} {
+    expr 1.0e2147483647
+} Inf
+test expr-41.8 {exponent overflow} {
+    expr 1.0e2147483648
+} Inf
+test expr-41.9 {exponent overflow} {
+    expr 1.2e2147483647
+} Inf
+test expr-41.10 {exponent overflow} {
+    expr 1.2e2147483648
+} Inf
+
+test expr-41.11 {exponent overflow} {
+    expr 1e-2147483648
+} 0.0
+test expr-41.12 {exponent overflow} {
+    expr 1e-2147483649
+} 0.0
+test expr-41.13 {exponent overflow} {
+    expr 100e-2147483650
+} 0.0
+test expr-41.14 {exponent overflow} {
+    expr 100e-2147483651
+} 0.0 
+test expr-41.15 {exponent overflow} {
+    expr 1.0e-2147483648
+} 0.0 
+test expr-41.16 {exponent overflow} {
+    expr 1.0e-2147483649
+} 0.0 
+test expr-41.17 {exponent overflow} {
+    expr 1.23e-2147483646
+} 0.0
+test expr-41.18 {exponent overflow} {
+    expr 1.23e-2147483647
+} 0.0 
+
+test expr-41.19 {numSigDigs == 0} {
+    expr 0e309
+} 0.0
+test expr-41.20 {numSigDigs == 0} {
+    expr 0e310
+} 0.0
+test expr-41.21 {negative zero, large exponent} {
+    expr -0e309
+} -0.0
+test expr-41.22 {negative zero, large exponent} {
+    expr -0e310
+} -0.0
+test expr-41.23 {floating point overflow on significand (Bug 1de6b0629e)} {
+    expr 123[string repeat 0 309]1e-310
+} 123.0
+
 test expr-42.1 {denormals} ieeeFloatingPoint {
     expr 7e-324
 } 5e-324
index 260fde9..f175e41 100644 (file)
@@ -11,7 +11,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -24,6 +24,7 @@ testConstraint testsetplatform [llength [info commands testsetplatform]]
 testConstraint testchmod [llength [info commands testchmod]]
 testConstraint winVista 0
 testConstraint win2000orXP 0
+testConstraint winLessThan10 0
 # Don't know how to determine this constraint correctly
 testConstraint notNetworkFilesystem 0
 testConstraint reg 0
@@ -64,13 +65,16 @@ if {[testConstraint unix]} {
 }
 
 # Also used in winFCmd...
-if {[testConstraint win]} {
-    if {[testConstraint nt] && $::tcl_platform(osVersion) >= 5.0} {
-        if {$::tcl_platform(osVersion) >= 6.0} {
-            testConstraint winVista 1
-        } else {
-            testConstraint win2000orXP 1
-        }
+if {[testConstraint win] && [testConstraint nt]} {
+    if {$::tcl_platform(osVersion) >= 5.0} {
+       if {$::tcl_platform(osVersion) < 10.0} {
+           testConstraint winLessThan10 1
+       }
+       if {$::tcl_platform(osVersion) >= 6.0} {
+           testConstraint winVista 1
+       } else {
+           testConstraint win2000orXP 1
+       }
     }
 }
 
@@ -80,6 +84,7 @@ testConstraint darwin9 [expr {
     && [package vsatisfies 1.$::tcl_platform(osVersion) 1.9]
 }]
 testConstraint notDarwin9 [expr {![testConstraint darwin9]}]
+testConstraint notContinuousIntegration [expr {![info exists ::env(CI)]}]
 
 testConstraint fileSharing 0
 testConstraint notFileSharing 1
@@ -623,10 +628,10 @@ test fCmd-6.23 {CopyRenameOneFile: TclpCopyDirectory failed} -setup {
     cleanup $tmpspace
 } -constraints {xdev notRoot} -body {
     file mkdir td1/td2/td3
-    file attributes td1 -permissions 0000
+    file attributes td1 -permissions 0o000
     file rename td1 $tmpspace
 } -returnCodes error -cleanup {
-    file attributes td1 -permissions 0755
+    file attributes td1 -permissions 0o755
     cleanup
 } -match regexp -result {^error renaming "td1"( to "/tmp/tcl\d+/td1")?: permission denied$}
 test fCmd-6.24 {CopyRenameOneFile: error uses original name} -setup {
@@ -634,10 +639,10 @@ test fCmd-6.24 {CopyRenameOneFile: error uses original name} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir ~/td1/td2
     set td1name [file join [file dirname ~] [file tail ~] td1]
-    file attributes $td1name -permissions 0000
+    file attributes $td1name -permissions 0o000
     file copy ~/td1 td1
 } -returnCodes error -cleanup {
-    file attributes $td1name -permissions 0755
+    file attributes $td1name -permissions 0o755
     file delete -force ~/td1
 } -result {error copying "~/td1": permission denied}
 test fCmd-6.25 {CopyRenameOneFile: error uses original name} -setup {
@@ -646,10 +651,10 @@ test fCmd-6.25 {CopyRenameOneFile: error uses original name} -setup {
     file mkdir td2
     file mkdir ~/td1
     set td1name [file join [file dirname ~] [file tail ~] td1]
-    file attributes $td1name -permissions 0000
+    file attributes $td1name -permissions 0o000
     file copy td2 ~/td1
 } -returnCodes error -cleanup {
-    file attributes $td1name -permissions 0755
+    file attributes $td1name -permissions 0o755
     file delete -force ~/td1
 } -result {error copying "td2" to "~/td1/td2": permission denied}
 test fCmd-6.26 {CopyRenameOneFile: doesn't use original name} -setup {
@@ -657,10 +662,10 @@ test fCmd-6.26 {CopyRenameOneFile: doesn't use original name} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir ~/td1/td2
     set td2name [file join [file dirname ~] [file tail ~] td1 td2]
-    file attributes $td2name -permissions 0000
+    file attributes $td2name -permissions 0o000
     file copy ~/td1 td1
 } -returnCodes error -cleanup {
-    file attributes $td2name -permissions 0755
+    file attributes $td2name -permissions 0o755
     file delete -force ~/td1
 } -result "error copying \"~/td1\" to \"td1\": \"[file join $::env(HOME) td1 td2]\": permission denied"
 test fCmd-6.27 {CopyRenameOneFile: TclpCopyDirectory failed} -setup {
@@ -675,10 +680,10 @@ test fCmd-6.28 {CopyRenameOneFile: TclpCopyDirectory failed} -setup {
     cleanup $tmpspace
 } -constraints {notRoot xdev} -body {
     file mkdir td1/td2/td3
-    file attributes td1/td2/td3 -permissions 0000
+    file attributes td1/td2/td3 -permissions 0o000
     file rename td1 $tmpspace
 } -returnCodes error -cleanup {
-    file attributes td1/td2/td3 -permissions 0755
+    file attributes td1/td2/td3 -permissions 0o755
     cleanup $tmpspace
 } -match glob -result {error renaming "td1" to "/tmp/tcl*/td1": "td1/td2/td3": permission denied}
 test fCmd-6.29 {CopyRenameOneFile: TclpCopyDirectory passed} -setup {
@@ -1342,10 +1347,10 @@ test fCmd-12.8 {renamefile: generic error} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir tfa
     file mkdir tfa/dir
-    file attributes tfa -permissions 0555
+    file attributes tfa -permissions 0o555
     catch {file rename tfa/dir tfa2}
 } -cleanup {
-    catch {file attributes tfa -permissions 0777}
+    catch {file attributes tfa -permissions 0o777}
     file delete -force tfa
 } -result {1}
 test fCmd-12.9 {renamefile: moving a file across volumes} -setup {
@@ -1528,10 +1533,10 @@ test fCmd-14.8 {copyfile: copy directory failing} -setup {
     catch {file delete -force -- tfa}
 } -constraints {unix notRoot} -body {
     file mkdir tfa/dir/a/b/c
-    file attributes tfa/dir -permissions 0000
+    file attributes tfa/dir -permissions 0o000
     catch {file copy tfa tfa2}
 } -cleanup {
-    file attributes tfa/dir -permissions 0777
+    file attributes tfa/dir -permissions 0o777
     file delete -force tfa tfa2
 } -result {1}
 
@@ -1571,10 +1576,10 @@ test fCmd-15.4 {TclMakeDirsCmd - stat failing} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir tfa
     createfile tfa/file
-    file attributes tfa -permissions 0000
+    file attributes tfa -permissions 0o000
     catch {file mkdir tfa/file}
 } -cleanup {
-    file attributes tfa -permissions 0777
+    file attributes tfa -permissions 0o777
     file delete -force tfa
 } -result {1}
 test fCmd-15.5 {TclMakeDirsCmd: - making a directory several levels deep} -setup {
@@ -1671,7 +1676,7 @@ test fCmd-16.9 {error while deleting file} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir tfa
     createfile tfa/a
-    file attributes tfa -permissions 0555
+    file attributes tfa -permissions 0o555
     catch {file delete tfa/a}
     #######
     #######  If any directory in a tree that is being removed does not have
@@ -1679,7 +1684,7 @@ test fCmd-16.9 {error while deleting file} -setup {
     #######  with "rm -rf"
     #######
 } -cleanup {
-    file attributes tfa -permissions 0777
+    file attributes tfa -permissions 0o777
     file delete -force tfa
 } -result {1}
 test fCmd-16.10 {deleting multiple files} -constraints {notRoot} -setup {
@@ -1701,10 +1706,10 @@ test fCmd-17.1 {mkdir stat failing on target but not ENOENT} -setup {
      catch {file delete -force -- tfa1}
 } -constraints {unix notRoot} -body {
      file mkdir tfa1
-     file attributes tfa1 -permissions 0555
+     file attributes tfa1 -permissions 0o555
      catch {file mkdir tfa1/tfa2}
 } -cleanup {
-     file attributes tfa1 -permissions 0777
+     file attributes tfa1 -permissions 0o777
      file delete -force tfa1
 } -result {1}
 test fCmd-17.2 {mkdir several levels deep - relative} -setup {
@@ -1912,10 +1917,10 @@ test fCmd-19.2 {rmdir error besides EEXIST} -setup {
 } -constraints {unix notRoot} -body {
     file mkdir tfa
     file mkdir tfa/a
-    file attributes tfa -permissions 0555
+    file attributes tfa -permissions 0o555
     catch {file delete tfa/a}
 } -cleanup {
-    file attributes tfa -permissions 0777
+    file attributes tfa -permissions 0o777
     file delete -force tfa
 } -result {1}
 test fCmd-19.3 {recursive remove} -constraints {notRoot} -setup {
@@ -1940,10 +1945,10 @@ test fCmd-20.1 {TraverseUnixTree : failure opening a subdirectory directory} -se
 } -constraints {unix notRoot} -body {
     file mkdir tfa
     file mkdir tfa/a
-    file attributes tfa/a -permissions 0000
+    file attributes tfa/a -permissions 0o000
     catch {file delete -force tfa}
 } -cleanup {
-    file attributes tfa/a -permissions 0777
+    file attributes tfa/a -permissions 0o777
     file delete -force tfa
 } -result {1}
 test fCmd-20.2 {TraverseUnixTree : recursive delete of large directory: Bug 1034337} -setup {
@@ -2354,13 +2359,15 @@ test fCmd-28.7 {file link: source already exists} -setup {
 } -returnCodes error -cleanup {
     cd [workingDirectory]
 } -result {could not create new link "abc.file": that path already exists}
-test fCmd-28.8 {file link} -constraints {linkFile win} -setup {
+# In Windows 10 developer mode, we _can_ create symbolic links to files!
+test fCmd-28.8 {file link} -constraints {linkFile winLessThan10} -setup {
     cd [temporaryDirectory]
 } -body {
     file link -symbolic abc.link abc.file
-} -returnCodes error -cleanup {
+} -cleanup {
+    file delete -force abc.link
     cd [workingDirectory]
-} -result {could not create new link "abc.link" pointing to "abc.file": not a directory}
+} -returnCodes error -result {could not create new link "abc.link" pointing to "abc.file": invalid argument}
 test fCmd-28.9 {file link: success with file} -constraints {linkFile} -setup {
     cd [temporaryDirectory]
     file delete -force abc.link
@@ -2582,7 +2589,11 @@ test fCmd-30.2 {file readable on 'NTUSER.DAT'} -constraints {win} -body {
           && [file exists $env(USERPROFILE)/NTUSER.DAT]
           && [file readable $env(USERPROFILE)/NTUSER.DAT]}
 } -result {1}
-test fCmd-30.3 {file readable on 'pagefile.sys'} -constraints {win} -body {
+# At least one CI environment (GitHub Actions) is set up with the page file in
+# an unusual location; skip the test if that is so.
+test fCmd-30.3 {file readable on 'pagefile.sys'} -constraints {
+    win notContinuousIntegration
+} -body {
     set r {}
     if {[info exists env(SystemDrive)]} {
         set path $env(SystemDrive)/pagefile.sys
index 0e4cb9e..2648049 100644 (file)
@@ -11,7 +11,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -1083,6 +1083,12 @@ test filename-11.48 {Tcl_GlobCmd} -returnCodes error -body {
 test filename-11.49 {Tcl_GlobCmd} -returnCodes error -body {
     glob -types abcde -path foo -join * *
 } -result {bad argument to "-types": abcde}
+test filename-11.50 {Tcl_GlobCmd} -returnCodes error -body {
+    glob -path hello -path salut *
+} -result {"-path" may only be used once}
+test filename-11.51 {Tcl_GlobCmd} -returnCodes error -body {
+    glob -dir hello -dir salut *
+} -result {"-directory" may only be used once}
 
 file rename $horribleglobname globTest
 file delete -force $tildeglobname
@@ -1321,7 +1327,7 @@ unset globname
 # AFS, "000" protection doesn't prevent access by owner, so the following test
 # is not portable.
 
-catch {file attributes globTest/a1 -permissions 0000}
+catch {file attributes globTest/a1 -permissions 0o000}
 test filename-15.1 {unix specific globbing} {unix nonPortable} {
     string tolower [list [catch {glob globTest/a1/*} msg] $msg $errorCode]
 } {1 {couldn't read directory "globtest/a1": permission denied} {posix eacces {permission denied}}}
@@ -1333,7 +1339,7 @@ test filename-15.3 {unix specific no complain: no errors, good result} \
     # test fails because if an error occurs, the interp's result is reset...
     glob -nocomplain globTest/a2 globTest/a1/* globTest/a3
 } {globTest/a2 globTest/a3}
-catch {file attributes globTest/a1 -permissions 0755}
+catch {file attributes globTest/a1 -permissions 0o755}
 test filename-15.4 {unix specific no complain: no errors, good result} \
        {unix nonPortable} {
     # test fails because if an error occurs, the interp's result is reset...
index d9264ee..8af4f53 100644 (file)
@@ -9,7 +9,11 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
+
 namespace eval ::tcl::test::fileSystem {
     namespace import ::tcltest::*
 
@@ -34,7 +38,9 @@ catch {
 testConstraint testfilesystem              [llength [info commands ::testfilesystem]]
 testConstraint testsetplatform             [llength [info commands ::testsetplatform]]
 testConstraint testsimplefilesystem [llength [info commands ::testsimplefilesystem]]
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+# Some things fail under all Continuous Integration systems for subtle reasons
+# such as CI often running with elevated privileges in a container.
+testConstraint notInCIenv           [expr {![info exists ::env(CI)]}]
 
 cd [tcltest::temporaryDirectory]
 makeFile "test file" gorp.file
@@ -313,7 +319,7 @@ test filesystem-1.37 {file normalisation with '/./'} -body {
 } -match regexp -result {^(?:[^/]|/(?:[^/]|$))+$}
 test filesystem-1.38 {file normalisation with volume relative} -setup {
     set dir [pwd]
-} -constraints {win moreThanOneDrive knownMsvcBug} -body {
+} -constraints {win moreThanOneDrive notInCIenv} -body {
     set path "[string range [lindex $drives 0] 0 1]foo"
     cd [lindex $drives 1]
     file norm $path
@@ -562,7 +568,7 @@ test filesystem-7.1.1 {load from vfs} -setup {
     cd [file dirname $::ddelib]
     testsimplefilesystem 1
     # This loads dde via a complex copy-to-temp operation
-    load simplefs:/[file tail $::ddelib] dde
+    load simplefs:/[file tail $::ddelib] Dde
     testsimplefilesystem 0
     return ok
     # The real result of this test is what happens when Tcl exits.
@@ -689,7 +695,7 @@ test filesystem-7.5 {cross-filesystem file copy with -force} -setup {
     # First copy should succeed
     set res [catch {file copy simplefs:/simplefile file2} err]
     lappend res $err
-    file attributes file2 -permissions 0000
+    file attributes file2 -permissions 0o000
     # Second copy should fail (no -force)
     lappend res [catch {file copy simplefs:/simplefile file2} err]
     lappend res $err
index da301ce..40a0090 100644 (file)
@@ -7,8 +7,11 @@ if {[string equal $::tcl_platform(os) "Windows NT"]} {
 }
 
 namespace eval ::tcl::test::fileSystemEncoding {
-    package require tcltest 2
-    namespace import ::tcltest::*
+
+    if {"::tcltest" ni [namespace children]} {
+       package require tcltest 2.5
+       namespace import -force ::tcltest::*
+    }
 
     variable fname1 \u767b\u9e1b\u9d72\u6a13
 
index a11a791..baf40fa 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -22,23 +22,23 @@ if {[lsearch [namespace children] ::tcltest] == -1} {
 catch {unset a i}
 test for-old-1.1 {for tests} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
+    for {set i 1} {$i<6} {incr i} {
        set a [concat $a $i]
     }
     set a
 } {1 2 3 4 5}
 test for-old-1.2 {for tests} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 continue
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==4} continue
        set a [concat $a $i]
     }
     set a
 } {1 2 3 5}
 test for-old-1.3 {for tests} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 break
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==4} break
        set a [concat $a $i]
     }
     set a
@@ -55,12 +55,12 @@ test for-old-1.7 {for tests} {
 } {wrong # args: should be "for start test next command"}
 test for-old-1.8 {for tests} {
     set a {xyz}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {}
+    for {set i 1} {$i<6} {incr i} {}
     set a
 } xyz
 test for-old-1.9 {for tests} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]; if $i==4 break} {
+    for {set i 1} {$i<6} {incr i; if {$i==4} break} {
        set a [concat $a $i]
     }
     set a
index 1a65274..a13ee54 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -62,15 +62,15 @@ test for-1.8 {TclCompileForCmd: error compiling command body} -body {
 catch {unset a}
 test for-1.9 {TclCompileForCmd: simple command body} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 break
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==4} break
        set a [concat $a $i]
     }
     set a
 } {1 2 3}
 test for-1.10 {TclCompileForCmd: command body in quotes} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} "append a x"
+    for {set i 1} {$i<6} {incr i} "append a x"
     set a
 } {xxxxx}
 test for-1.11 {TclCompileForCmd: computed command body} {
@@ -81,7 +81,7 @@ test for-1.11 {TclCompileForCmd: computed command body} {
     set bb {break}
     set x2 {; append a x2}
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} $x1$bb$x2
+    for {set i 1} {$i<6} {incr i} $x1$bb$x2
     set a
 } {x1}
 test for-1.12 {TclCompileForCmd: error in "next" command} -body {
@@ -92,9 +92,9 @@ test for-1.12 {TclCompileForCmd: error in "next" command} -body {
 "set"*}
 test for-1.13 {TclCompileForCmd: long command body} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 break
-       if $i>5 continue
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -129,7 +129,7 @@ test for-1.14 {TclCompileForCmd: for command result} {
     set a
 } {}
 test for-1.15 {TclCompileForCmd: for command result} {
-    set a [for {set i 0} {$i < 5} {incr i} {if $i==3 break}]
+    set a [for {set i 0} {$i < 5} {incr i} {if {$i==3} break}]
     set a
 } {}
 
@@ -144,7 +144,7 @@ test for-2.2 {TclCompileContinueCmd: continue result} {
 } 4
 test for-2.3 {continue tests} {
     set a {}
-    for {set i 1} {$i <= 4} {set i [expr $i+1]} {
+    for {set i 1} {$i <= 4} {incr i} {
        if {$i == 2} continue
        set a [concat $a $i]
     }
@@ -152,7 +152,7 @@ test for-2.3 {continue tests} {
 } {1 3 4}
 test for-2.4 {continue tests} {
     set a {}
-    for {set i 1} {$i <= 4} {set i [expr $i+1]} {
+    for {set i 1} {$i <= 4} {incr i} {
        if {$i != 2} continue
        set a [concat $a $i]
     }
@@ -170,10 +170,10 @@ test for-2.5 {continue tests, nested loops} {
 } {1.1 1.2 2.1 3.1 4.1}
 test for-2.6 {continue tests, long command body} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==2 continue
-       if $i==4 break
-       if $i>5 continue
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==2} continue
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -246,10 +246,10 @@ test for-3.4 {break tests, nested loops} {
 } {1.1 1.2 2.1 3.1 4.1}
 test for-3.5 {break tests, long command body} {
     set a {}
-    for {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==2 continue
-       if $i==5 break
-       if $i>5 continue
+    for {set i 1} {$i<6} {incr i} {
+       if {$i==2} continue
+       if {$i==5} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -265,7 +265,7 @@ test for-3.5 {break tests, long command body} {
            catch {incr i 5} msg
            catch {incr i -5} msg
        }
-       if $i==4 break
+       if {$i==4} break
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -303,35 +303,35 @@ proc formatMail {} {
         16 {This page contains information about Tcl 7.6 and Tk4.2, which are the most recent} \
         17 {releases of the Tcl scripting language and the Tk toolkit. The first beta versions of these} \
         18 {releases were released on August 30, 1996. These releases contain only minor changes,} \
-        19 {so we hope to have only a single beta release and to go final in early October, 1996. } \
+        19 {so we hope to have only a single beta release and to go final in early October, 1996.} \
         20 {} \
         21 {} \
-        22 {What's new } \
+        22 {What's new} \
         23 {} \
         24 {The most important changes in the releases are summarized below. See the README} \
         25 {and changes files in the distributions for more complete information on what has} \
-        26 {changed, including both feature changes and bug fixes. } \
+        26 {changed, including both feature changes and bug fixes.} \
         27 {} \
         28 {     There are new options to the file command for copying files (file copy),} \
         29 {     deleting files and directories (file delete), creating directories (file} \
-        30 {     mkdir), and renaming files (file rename). } \
+        30 {     mkdir), and renaming files (file rename).} \
         31 {     The implementation of exec has been improved greatly for Windows 95 and} \
-        32 {     Windows NT. } \
+        32 {     Windows NT.} \
         33 {     There is a new memory allocator for the Macintosh version, which should be} \
-        34 {     more efficient than the old one. } \
+        34 {     more efficient than the old one.} \
         35 {     Tk's grid geometry manager has been completely rewritten. The layout} \
         36 {     algorithm produces much better layouts than before, especially where rows or} \
-        37 {     columns were stretchable. } \
+        37 {     columns were stretchable.} \
         38 {     There are new commands for creating common dialog boxes:} \
         39 {     tk_chooseColor, tk_getOpenFile, tk_getSaveFile and} \
-        40 {     tk_messageBox. These use native dialog boxes if they are available. } \
+        40 {     tk_messageBox. These use native dialog boxes if they are available.} \
         41 {     There is a new virtual event mechanism for handling events in a more portable} \
         42 {     way. See the new command event. It also allows events (both physical and} \
-        43 {     virtual) to be generated dynamically. } \
+        43 {     virtual) to be generated dynamically.} \
         44 {} \
         45 {Tcl 7.6 and Tk 4.2 are backwards-compatible with Tcl 7.5 and Tk 4.1 except for} \
         46 {changes in the C APIs for custom channel drivers. Scripts written for earlier releases} \
-        47 {should work on these new releases as well. } \
+        47 {should work on these new releases as well.} \
         48 {} \
         49 {Obtaining The Releases} \
         50 {} \
@@ -342,7 +342,7 @@ proc formatMail {} {
         55 {     Windows 3.1, Windows 95, and Windows NT: Fetch} \
         56 {     ftp://ftp.sunlabs.com/pub/tcl/win42b1.exe, then execute it. The file is a} \
         57 {     self-extracting executable. It will install the Tcl and Tk libraries, the wish and} \
-        58 {     tclsh programs, and documentation. } \
+        58 {     tclsh programs, and documentation.} \
         59 {     Macintosh (both 68K and PowerPC): Fetch} \
         60 {     ftp://ftp.sunlabs.com/pub/tcl/mactk4.2b1.sea.hqx. The file is in binhex format,} \
         61 {     which is understood by Fetch, StuffIt, and many other Mac utilities. The} \
@@ -386,7 +386,7 @@ proc formatMail {} {
                continue
            }
        }
-       if $inheaders {
+       if {$inheaders} {
            set limit 55
        } else {
            set limit 55
@@ -430,12 +430,12 @@ proc formatMail {} {
                continue
            }
        }
-       set climit [expr $limit-1]
+       set climit [expr {$limit-1}]
        set cutoff 50
        set continuation 0
 
        while {[string length $line] > $limit} {
-           for {set c [expr $limit-1]} {$c >= $cutoff} {incr c -1} {
+           for {set c [expr {$limit-1}]} {$c >= $cutoff} {incr c -1} {
                set char [string index $line $c]
                if {$char == " " || $char == "\t"} {
                    break
@@ -446,12 +446,12 @@ proc formatMail {} {
            }
            if {$c < $cutoff} {
                if {! $inheaders} {
-                   set c [expr $limit-1]
+                   set c [expr {$limit-1}]
                } else {
                    set c [string length $line]
                }
            }
-           set newline [string range $line 0 $c]
+           set newline [string trimright [string range $line 0 $c]]
            if {! $continuation} {
                append result $newline $NL
            } else {
@@ -507,76 +507,76 @@ releases of the Tcl scripting language and the Tk toolk
 it. The first beta versions of these
 releases were released on August 30, 1996. These releas
 es contain only minor changes,
-so we hope to have only a single beta release and to 
+so we hope to have only a single beta release and to
 go final in early October, 1996.
 
 
-What's new 
+What's new
 
 The most important changes in the releases are summariz
 ed below. See the README
 and changes files in the distributions for more complet
 e information on what has
-changed, including both feature changes and bug fixes. 
+changed, including both feature changes and bug fixes.
 
-     There are new options to the file command for 
+     There are new options to the file command for
 copying files (file copy),
-     deleting files and directories (file delete), 
+     deleting files and directories (file delete),
 creating directories (file
-     mkdir), and renaming files (file rename). 
+     mkdir), and renaming files (file rename).
      The implementation of exec has been improved great
 ly for Windows 95 and
-     Windows NT. 
-     There is a new memory allocator for the Macintosh 
+     Windows NT.
+     There is a new memory allocator for the Macintosh
 version, which should be
-     more efficient than the old one. 
-     Tk's grid geometry manager has been completely 
+     more efficient than the old one.
+     Tk's grid geometry manager has been completely
 rewritten. The layout
      algorithm produces much better layouts than before
 , especially where rows or
-     columns were stretchable. 
-     There are new commands for creating common dialog 
+     columns were stretchable.
+     There are new commands for creating common dialog
 boxes:
      tk_chooseColor, tk_getOpenFile, tk_getSaveFile and
-     tk_messageBox. These use native dialog boxes if 
+     tk_messageBox. These use native dialog boxes if
 they are available.
      There is a new virtual event mechanism for handlin
 g events in a more portable
-     way. See the new command event. It also allows 
+     way. See the new command event. It also allows
 events (both physical and
-     virtual) to be generated dynamically. 
+     virtual) to be generated dynamically.
 
-Tcl 7.6 and Tk 4.2 are backwards-compatible with Tcl 
+Tcl 7.6 and Tk 4.2 are backwards-compatible with Tcl
 7.5 and Tk 4.1 except for
 changes in the C APIs for custom channel drivers. Scrip
 ts written for earlier releases
-should work on these new releases as well. 
+should work on these new releases as well.
 
 Obtaining The Releases
 
 Binary Releases
 
-Pre-compiled releases are available for the following 
+Pre-compiled releases are available for the following
 platforms:
 
      Windows 3.1, Windows 95, and Windows NT: Fetch
-     ftp://ftp.sunlabs.com/pub/tcl/win42b1.exe, then 
+     ftp://ftp.sunlabs.com/pub/tcl/win42b1.exe, then
 execute it. The file is a
-     self-extracting executable. It will install the 
+     self-extracting executable. It will install the
 Tcl and Tk libraries, the wish and
-     tclsh programs, and documentation. 
+     tclsh programs, and documentation.
      Macintosh (both 68K and PowerPC): Fetch
-     ftp://ftp.sunlabs.com/pub/tcl/mactk4.2b1.sea.hqx. 
+     ftp://ftp.sunlabs.com/pub/tcl/mactk4.2b1.sea.hqx.
 The file is in binhex format,
-     which is understood by Fetch, StuffIt, and many 
+     which is understood by Fetch, StuffIt, and many
 other Mac utilities. The
-     unpacked file is a self-installing executable: 
+     unpacked file is a self-installing executable:
 double-click on it and it will create a
-     folder containing all that you need to run Tcl 
+     folder containing all that you need to run Tcl
 and Tk.
-        UNIX (Solaris 2.* and SunOS, other systems 
+        UNIX (Solaris 2.* and SunOS, other systems
 soon to follow). Easy to install
-     binary packages are now for sale at the Sun Labs 
+     binary packages are now for sale at the Sun Labs
 Tcl/Tk Shop. Check it out!
 }
 
@@ -585,7 +585,7 @@ Tcl/Tk Shop. Check it out!
 test for-4.1 {break must reset the interp result} {
     catch {
         set z GLOBTESTDIR/dir2/file2.c
-        if [string match GLOBTESTDIR/dir2/* $z] {
+        if {[string match GLOBTESTDIR/dir2/* $z]} {
             break
         }
     } j
@@ -696,8 +696,8 @@ test for-6.9 {Tcl_ForObjCmd: error executing command body} -body {
 test for-6.10 {Tcl_ForObjCmd: simple command body} {
     set z for
     set a {}
-    $z {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 break
+    $z {set i 1} {$i<6} {incr i} {
+       if {$i==4} break
        set a [concat $a $i]
     }
     set a
@@ -705,7 +705,7 @@ test for-6.10 {Tcl_ForObjCmd: simple command body} {
 test for-6.11 {Tcl_ForObjCmd: command body in quotes} {
     set z for
     set a {}
-    $z {set i 1} {$i<6} {set i [expr $i+1]} "append a x"
+    $z {set i 1} {$i<6} {incr i} "append a x"
     set a
 } {xxxxx}
 test for-6.12 {Tcl_ForObjCmd: computed command body} {
@@ -717,7 +717,7 @@ test for-6.12 {Tcl_ForObjCmd: computed command body} {
     set bb {break}
     set x2 {; append a x2}
     set a {}
-    $z {set i 1} {$i<6} {set i [expr $i+1]} $x1$bb$x2
+    $z {set i 1} {$i<6} {incr i} $x1$bb$x2
     set a
 } {x1}
 test for-6.13 {Tcl_ForObjCmd: error in "next" command} -body {
@@ -733,9 +733,9 @@ test for-6.13 {Tcl_ForObjCmd: error in "next" command} -body {
 test for-6.14 {Tcl_ForObjCmd: long command body} {
     set z for
     set a {}
-    $z {set i 1} {$i<6} {set i [expr $i+1]} {
-       if $i==4 break
-       if $i>5 continue
+    $z {set i 1} {$i<6} {incr i} {
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
index 84af4bd..cdbfc85 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index c26bbe9..11cb4b7 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
 # %u output depends on word length, so this test is not portable.
 testConstraint longIs32bit [expr {int(0x80000000) < 0}]
 testConstraint longIs64bit [expr {int(0x8000000000000000) < 0}]
-testConstraint wideIs64bit \
-       [expr {(wide(0x80000000) > 0) && (wide(0x8000000000000000) < 0)}]
+testConstraint wideIs64bit [expr {
+    (wide(0x80000000) > 0) && (wide(0x8000000000000000) < 0)}]
 testConstraint wideBiggerThanInt [expr {wide(0x80000000) != int(0x80000000)}]
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+# MSVC uses a broken libc that gets sprintf("%g") wrong. This is a pain
+# particularly in Continuous Integration, and there isn't anything much we can
+# do about it.
+testConstraint notWinCI [expr {
+    ($::tcl_platform(platform) ne "windows") || ![info exists ::env(CI)]}]
 \f
 test format-1.1 {integer formatting} {
     format "%*d %d %d %d" 6 34 16923 -12 -1
@@ -274,13 +278,13 @@ test format-6.1 {floating-point zeroes} {eformat} {
 test format-6.2 {floating-point zeroes} {eformat} {
     format "%.4e %.4f %.4g" 0.0 0.0 0.0 0.0
 } {0.0000e+00 0.0000 0}
-test format-6.3 {floating-point zeroes} {eformat knownMsvcBug} {
+test format-6.3 {floating-point zeroes} {eformat notWinCI} {
     format "%#.4e %#.4f %#.4g" 0.0 0.0 0.0 0.0
 } {0.0000e+00 0.0000 0.000}
 test format-6.4 {floating-point zeroes} {eformat} {
     format "%.0e %.0f %.0g" 0.0 0.0 0.0 0.0
 } {0e+00 0 0}
-test format-6.5 {floating-point zeroes} {eformat knownMsvcBug} {
+test format-6.5 {floating-point zeroes} {eformat notWinCI} {
     format "%#.0e %#.0f %#.0g" 0.0 0.0 0.0 0.0
 } {0.e+00 0. 0.}
 test format-6.6 {floating-point zeroes} {
index 7aa06c1..b9a83ac 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 3201ad7..b6a2755 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
   
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -40,7 +40,7 @@ test history-1.1 {event option} history {history event -1} \
        {set b [format {A test %s} string]}
 test history-1.2 {event option} history {history event $num} \
        {set a 12345}
-test history-1.3 {event option} history {history event [expr $num+2]} \
+test history-1.3 {event option} history {history event [expr {$num+2}]} \
        {Another test}
 test history-1.4 {event option} history {history event set} \
        {set b [format {A test %s} string]}
@@ -149,11 +149,11 @@ test history-5.1 {info option} history {history info} [format {%6d  set a {b
 %6d  set b 1234
 %6d  set c {a
        b
-       c}} $num [expr $num+1] [expr $num+2]]
+       c}} $num [expr {$num+1}] [expr {$num+2}]]
 test history-5.2 {info option} history {history i 2} [format {%6d  set b 1234
 %6d  set c {a
        b
-       c}} [expr $num+1] [expr $num+2]]
+       c}} [expr {$num+1}] [expr {$num+2}]]
 test history-5.3 {info option} history {catch {history i 2 3}} 1
 test history-5.4 {info option} history {
     catch {history i 2 3} msg
@@ -164,7 +164,7 @@ test history-5.5 {info option} history {history} [format {%6d  set a {b
 %6d  set b 1234
 %6d  set c {a
        b
-       c}} $num [expr $num+1] [expr $num+2]]
+       c}} $num [expr {$num+1}] [expr {$num+2}]]
 
 # "history keep"
 
@@ -174,7 +174,9 @@ if {[testConstraint history]} {
     history add "foo3"
     history keep 2
 }
-test history-6.1 {keep option} history {history event [expr [history n]-1]} foo3
+test history-6.1 {keep option} history {
+    history event [expr {[history n]-1}]
+} foo3
 test history-6.2 {keep option} history {history event -1} foo2
 test history-6.3 {keep option} history {catch {history event -3}} 1
 test history-6.4 {keep option} history {
@@ -216,7 +218,7 @@ if {[testConstraint history]} {
     history add "Testing2"
 }
 test history-7.1 {nextid option} history {history event} "Testing"
-test history-7.2 {nextid option} history {history next} [expr $num+2]
+test history-7.2 {nextid option} history {history next} [expr {$num+2}]
 test history-7.3 {nextid option} history {catch {history nextid garbage}} 1
 test history-7.4 {nextid option} history {
     catch {history nextid garbage} msg
@@ -262,7 +264,7 @@ test history-10.1 {references kept by history} -constraints history -setup {
 } -body {
     histtest eval {
        # A fresh object, refcount 1 from the variable we write it to
-       set obj [expr rand()]
+       set obj [expr {rand()}]
        set baseline [refcount $obj]
        lappend result [refcount $obj]
        history add [list list $obj]
@@ -288,7 +290,7 @@ test history-10.2 {references kept by history} -constraints history -setup {
 } -body {
     histtest eval {
        # A fresh object, refcount 1 from the variable we write it to
-       set obj [expr rand()]
+       set obj [expr {rand()}]
        set baseline [refcount $obj]
        lappend result [refcount $obj]
        history add [list list $obj]
index 73fe10c..c45a45a 100644 (file)
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 if {[catch {package require http 2} version]} {
     if {[info exists http2]} {
        catch {puts "Cannot load http 2.* package"}
        return
     } else {
-       catch {puts "Running http 2.* tests in slave interp"}
+       catch {puts "Running http 2.* tests in child interp"}
        set interp [interp create http2]
        $interp eval [list set http2 "running"]
        $interp eval [list set argv $argv]
@@ -36,13 +38,10 @@ proc bgerror {args} {
     puts stderr $errorInfo
 }
 
-if {$::tcl_platform(os) eq "Darwin"} {
-    # Name resolution often a problem on OSX; not focus of HTTP package anyway
-    set HOST localhost
-} else {
-    set HOST [info hostname]
-}
-
+# Do not use [info hostname].
+# Name resolution is often a problem on OSX; not focus of HTTP package anyway.
+# Also a problem on other platforms for http-4.14 (test with bad port number).
+set HOST localhost
 set port 8010
 set bindata "This is binary data\x0d\x0amore\x0dmore\x0amore\x00null"
 catch {unset data}
@@ -79,6 +78,8 @@ if {[catch {package present Thread}] == 0 && [file exists $httpdFile]} {
        unset port
        return
     } else {
+       # Running httpd in the current thread overwrites the values of port
+       # (here) and HOST (in the sourced server file).
        set port [lindex [fconfigure $listen -sockname] 2]
     }
 }
@@ -126,7 +127,7 @@ test http-3.2 {http::geturl} -returnCodes error -body {
     http::geturl http:junk
 } -result {Unsupported URL: http:junk}
 set url //${::HOST}:$port
-set badurl //${::HOST}:[expr $port+1]
+set badurl //${::HOST}:[expr {$port+1}]
 test http-3.3 {http::geturl} -body {
     set token [http::geturl $url]
     http::data $token
@@ -446,6 +447,9 @@ test http-3.33 {http::geturl application/xml is text} -body {
 } -cleanup {
     catch { http::cleanup $token }
 } -result {test 4660 /test}
+test http-3.34 {http::geturl -headers not a dict} -returnCodes error -body {
+    http::geturl http://test/t -headers NoDict
+} -result {Bad value for -headers (NoDict), must be dict}
 
 test http-4.1 {http::Event} -body {
     set token [http::geturl $url -keepalive 0]
index 1e30802..f243e56 100644 (file)
@@ -7,17 +7,19 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
-package require http 2.8
+package require http 2.9
 
 # start the server
 variable httpd_output
 proc create_httpd {} {
     proc httpd_read {chan} {
         variable httpd_output
-        if {[gets $chan line] != -1} {
+        if {[gets $chan line] >= 0} {
             #puts stderr "read '$line'"
             set httpd_output $line
         }
@@ -60,6 +62,20 @@ proc meta {tok {key ""}} {
     return $meta
 }
 
+proc state {tok {key ""}} {
+    upvar 1 $tok state
+    if {$key ne ""} {
+        if {[array names state -exact $key] ne {}} {
+            return $state($key)
+        } else {
+            return ""
+        }
+    }
+    set res [array get state]
+    dict set res body <elided>
+    return $res
+}
+
 proc check_crc {tok args} {
     set crc [meta $tok x-crc32]
     set data [expr {[llength $args] ? [lindex $args 0] : [http::data $tok]}]
@@ -241,8 +257,45 @@ test http11-1.12 "normal,identity,chunked" -setup {
     halt_httpd
 } -result {ok {HTTP/1.1 200 OK} ok {} chunked}
 
+test http11-1.13 "normal, 1.1 and keepalive as server default, no zip" -setup {
+    variable httpd [create_httpd]
+    set zipTmp [http::config -zip]
+    http::config -zip 0
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?transfer= \
+                 -protocol 1.1 -keepalive 1 -timeout 10000]
+    http::wait $tok
+    set res1 [list [http::status $tok] [http::code $tok] [check_crc $tok] \
+        [meta $tok connection] [meta $tok transfer-encoding] [state $tok reusing] [state $tok connection]]
+    set toj [http::geturl http://localhost:$httpd_port/testdoc.html?transfer= \
+                 -protocol 1.1 -keepalive 1 -timeout 10000]
+    http::wait $toj
+    set res2 [list [http::status $toj] [http::code $toj] [check_crc $toj] \
+        [meta $toj connection] [meta $toj transfer-encoding] [state $toj reusing] [state $toj connection]]
+    concat $res1 -- $res2
+} -cleanup {
+    http::cleanup $tok
+    http::cleanup $toj
+    halt_httpd
+    http::config -zip $zipTmp
+} -result {ok {HTTP/1.1 200 OK} ok {} {} 0 keep-alive -- ok {HTTP/1.1 200 OK} ok {} {} 1 keep-alive}
+
 # -------------------------------------------------------------------------
 
+proc progress {var token total current} {
+    upvar #0 $var log
+    set log [list $current $total]
+    return
+}
+
+proc progressPause {var token total current} {
+    upvar #0 $var log
+    set log [list $current $total]
+    after 100 set ::WaitHere 0
+    vwait ::WaitHere
+    return
+}
+
 test http11-2.0 "-channel" -setup {
     variable httpd [create_httpd]
     set chan [open [makeFile {} testfile.tmp] wb+]
@@ -339,6 +392,58 @@ test http11-2.4 "-channel,encoding identity" -setup {
     halt_httpd
 } -result {ok {HTTP/1.1 200 OK} ok close {} chunked}
 
+test http11-2.4.1 "-channel,encoding identity with -progress" -setup {
+    variable httpd [create_httpd]
+    set chan [open [makeFile {} testfile.tmp] wb+]
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html \
+                 -timeout 5000 -channel $chan \
+                 -headers {accept-encoding identity} \
+                 -progress [namespace code [list progress logdata]]]
+
+    http::wait $tok
+    seek $chan 0
+    set data [read $chan]
+    list [http::status $tok] [http::code $tok] [check_crc $tok $data]\
+        [meta $tok connection] [meta $tok content-encoding]\
+        [meta $tok transfer-encoding] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length $data]}]
+} -cleanup {
+    http::cleanup $tok
+    close $chan
+    removeFile testfile.tmp
+    halt_httpd
+    unset -nocomplain logdata data
+} -result {ok {HTTP/1.1 200 OK} ok close {} chunked 0 0}
+
+test http11-2.4.2 "-channel,encoding identity with -progress progressPause enters event loop" -constraints knownBug -setup {
+    variable httpd [create_httpd]
+    set chan [open [makeFile {} testfile.tmp] wb+]
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html \
+                 -timeout 5000 -channel $chan \
+                 -headers {accept-encoding identity} \
+                 -progress [namespace code [list progressPause logdata]]]
+
+    http::wait $tok
+    seek $chan 0
+    set data [read $chan]
+    list [http::status $tok] [http::code $tok] [check_crc $tok $data]\
+        [meta $tok connection] [meta $tok content-encoding]\
+        [meta $tok transfer-encoding] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length $data]}]
+} -cleanup {
+    http::cleanup $tok
+    close $chan
+    removeFile testfile.tmp
+    halt_httpd
+    unset -nocomplain logdata data ::WaitHere
+} -result {ok {HTTP/1.1 200 OK} ok close {} chunked 0 0}
+
 test http11-2.5 "-channel,encoding unsupported" -setup {
     variable httpd [create_httpd]
     set chan [open [makeFile {} testfile.tmp] wb+]
@@ -518,6 +623,16 @@ proc handler {var sock token} {
     return [string length $chunk]
 }
 
+proc handlerPause {var sock token} {
+    upvar #0 $var data
+    set chunk [read $sock]
+    append data $chunk
+    #::http::Log "handler read [string length $chunk] ([chan configure $sock -buffersize])"
+    after 100 set ::WaitHere 0
+    vwait ::WaitHere
+    return [string length $chunk]
+}
+
 test http11-3.0 "-handler,close,identity" -setup {
     variable httpd [create_httpd]
     set testdata ""
@@ -589,6 +704,135 @@ test http11-3.3 "-handler,keepalive,chunked" -setup {
     halt_httpd
 } -result {ok {HTTP/1.0 200 OK} ok close {} {} 0}
 
+# http11-3.4
+# This test is a blatant attempt to confuse the client by instructing the server
+# to send neither "Connection: close" nor "Content-Length" when in non-chunked
+# mode.
+# The client has no way to know the response-body is complete unless the
+# server signals this by closing the connection.
+# In an HTTP/1.1 response the absence of "Connection: close" means
+# "Connection: keep-alive", i.e. the server will keep the connection
+# open.  In HTTP/1.0 this is not the case, and this is a test that
+# the Tcl client assumes "Connection: close" by default in HTTP/1.0.
+test http11-3.4 "-handler,close,identity; HTTP/1.0 server does not send Connection: close header or Content-Length" -setup {
+    variable httpd [create_httpd]
+    set testdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1&nosendclose=any \
+                 -timeout 10000 -handler [namespace code [list handler testdata]]]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok $testdata]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length $testdata]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain testdata
+    halt_httpd
+} -result {ok {HTTP/1.0 200 OK} ok {} {} {} 0}
+
+# It is not forbidden for a handler to enter the event loop.
+test http11-3.5 "-handler,close,identity as http11-3.0 but handlerPause enters event loop" -setup {
+    variable httpd [create_httpd]
+    set testdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1 \
+                 -timeout 10000 -handler [namespace code [list handlerPause testdata]]]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok $testdata]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length $testdata]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain testdata ::WaitHere
+    halt_httpd
+} -result {ok {HTTP/1.0 200 OK} ok close {} {} 0}
+
+test http11-3.6 "-handler,close,identity as http11-3.0 but with -progress" -setup {
+    variable httpd [create_httpd]
+    set testdata ""
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1 \
+                 -timeout 10000 -handler [namespace code [list handler testdata]] \
+                 -progress [namespace code [list progress logdata]]]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok $testdata]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length $testdata]}] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length $testdata]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain testdata logdata ::WaitHere
+    halt_httpd
+} -result {ok {HTTP/1.0 200 OK} ok close {} {} 0 0 0}
+
+test http11-3.7 "-handler,close,identity as http11-3.0 but with -progress progressPause enters event loop" -setup {
+    variable httpd [create_httpd]
+    set testdata ""
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1 \
+                 -timeout 10000 -handler [namespace code [list handler testdata]] \
+                 -progress [namespace code [list progressPause logdata]]]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok $testdata]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length $testdata]}] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length $testdata]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain testdata logdata ::WaitHere
+    halt_httpd
+} -result {ok {HTTP/1.0 200 OK} ok close {} {} 0 0 0}
+
+test http11-3.8 "close,identity no -handler but with -progress" -setup {
+    variable httpd [create_httpd]
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1 \
+                 -timeout 10000 \
+                 -progress [namespace code [list progress logdata]] \
+                 -headers {accept-encoding {}}]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length [http::data $tok]]}] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length [http::data $tok]]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain logdata ::WaitHere
+    halt_httpd
+} -result {ok {HTTP/1.1 200 OK} ok close {} {} 0 0 0}
+
+test http11-3.9 "close,identity no -handler but with -progress progressPause enters event loop" -setup {
+    variable httpd [create_httpd]
+    set logdata ""
+} -body {
+    set tok [http::geturl http://localhost:$httpd_port/testdoc.html?close=1 \
+                 -timeout 10000 \
+                 -progress [namespace code [list progressPause logdata]] \
+                 -headers {accept-encoding {}}]
+    http::wait $tok
+    list [http::status $tok] [http::code $tok] [check_crc $tok]\
+        [meta $tok connection] [meta $tok content-encoding] \
+        [meta $tok transfer-encoding] \
+        [expr {[file size testdoc.html]-[string length [http::data $tok]]}] \
+        [expr {[lindex $logdata 0] - [lindex $logdata 1]}] \
+        [expr {[lindex $logdata 0] - [string length [http::data $tok]]}]
+} -cleanup {
+    http::cleanup $tok
+    unset -nocomplain logdata ::WaitHere
+    halt_httpd
+} -result {ok {HTTP/1.1 200 OK} ok close {} {} 0 0 0}
+
 test http11-4.0 "normal post request" -setup {
     variable httpd [create_httpd]
 } -body {
index 8de79b9..4306149 100644 (file)
@@ -8,10 +8,12 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
-package require http 2.8
+package require http 2.9
 
 set sourcedir [file normalize [file dirname [info script]]]
 source [file join $sourcedir httpTest.tcl]
index 326b361..6a2226e 100644 (file)
@@ -60,7 +60,7 @@ proc http::Log {args} {
     variable TestStartTimeInMs
     set time [expr {[clock milliseconds] - $TestStartTimeInMs}]
     set txt [list $time {*}$args]
-    if {[string first ^ $txt] != -1} {
+    if {[string first ^ $txt] >= 0} {
         ::httpTest::LogRecord $txt
         ::httpTest::Puts $txt
     } elseif {$::httpTest::testOptions(-verbose) > 1} {
@@ -82,7 +82,7 @@ proc httpTest::LogRecord {txt} {
         puts stdout "Fix this call to Log in http-*.tm so it has ^ then\
                a letter then a numeral."
         flush stdout
-    } elseif {$pos == -1} {
+    } elseif {$pos < 0} {
         # Called by mistake.
     } else {
         set letter [string index $txt [incr pos]]
@@ -149,7 +149,7 @@ proc httpTest::TestOverlaps {someResults n term msg badTrans notPiped} {
         set myStart   [lsearch -exact $someResults [list B $i]]
         set myEnd     [lsearch -exact $someResults [list $term $i]]
 
-        if {($myStart == -1 || $myEnd == -1)} {
+        if {($myStart < 0 || $myEnd < 0)} {
             set res "Cannot find positions of transaction $i"
            append msg $res \n
            Puts $res
@@ -370,7 +370,7 @@ proc httpTest::ProcessRetries {someResults n msg skipOverlaps notIncluded notPip
     variable testOptions
 
     set nextRetry [lsearch -glob -index 0 $someResults {[PQR]}]
-    if {$nextRetry == -1} {
+    if {$nextRetry < 0} {
         return [MostAnalysis $someResults $n $msg $skipOverlaps $notIncluded $notPiped]
     }
     set badTrans $notIncluded
@@ -387,7 +387,7 @@ proc httpTest::ProcessRetries {someResults n msg skipOverlaps notIncluded notPip
     for {set i 1} {$i <= $n} {incr i} {
         set first [lsearch -exact $beforeTry [list A $i]]
         set last  [lsearch -exact $beforeTry [list F $i]]
-        if {$first == -1} {
+        if {$first < 0} {
            set res "Transaction $i was not started in connection number $tryCount"
            # So lappend it to badTrans and don't include it in the call below of MostAnalysis.
            # append msg $res \n
@@ -396,7 +396,7 @@ proc httpTest::ProcessRetries {someResults n msg skipOverlaps notIncluded notPip
                lappend badTrans $i
            } else {
            }
-        } elseif {$last == -1} {
+        } elseif {$last < 0} {
            set res "Transaction $i was started but unfinished in connection number $tryCount"
            # So lappend it to badTrans and don't include it in the call below of MostAnalysis.
            # append msg $res \n
index 16e0382..4f5f600 100644 (file)
 
 #set httpLog 1
 
-if {$::tcl_platform(os) eq "Darwin"} {
-    # Name resolution often a problem on OSX; not focus of HTTP package anyway
-    set HOST localhost
-} else {
-    set HOST [info hostname]
-}
+# Do not use [info hostname].
+# Name resolution is often a problem on OSX; not focus of HTTP package anyway.
+# Also a problem on other platforms for http-4.14 (test with bad port number).
+set HOST localhost
 
 proc httpd_init {{port 8015}} {
     socket -server httpdAccept $port
index 7880494..89590ec 100644 (file)
@@ -170,14 +170,19 @@ proc Service {chan addr port} {
             set close 1
         }
 
+        set nosendclose 0
         foreach pair [split $query &] {
             if {[scan $pair {%[^=]=%s} key val] != 2} {set val ""}
             switch -exact -- $key {
+                nosendclose  {set nosendclose 1}
                 close        {set close 1 ; set transfer 0}
                 transfer     {set transfer $val}
                 content-type {set type $val}
             }
         }
+        if {$protocol eq "HTTP/1.1"} {
+            set nosendclose 0
+        }
 
         chan configure $chan -buffering line -encoding iso8859-1 -translation crlf
         Puts $chan "$protocol $code"
@@ -186,12 +191,16 @@ proc Service {chan addr port} {
         if {$req eq "POST"} {
             Puts $chan [format "x-query-length: %d" [string length $query]]
         }
-        if {$close} {
+        if {$close && (!$nosendclose)} {
             Puts $chan "connection: close"
         }
        Puts $chan "x-requested-encodings: [dict get? $meta accept-encoding]"
-        if {$encoding eq "identity"} {
+        if {$encoding eq "identity" && (!$nosendclose)} {
             Puts $chan "content-length: [string length $data]"
+        } elseif {$encoding eq "identity"} {
+            # This is a blatant attempt to confuse the client by sending neither
+            # "Connection: close" nor "Content-Length" when in non-chunked mode.
+            # See test http11-3.4.
         } else {
             Puts $chan "content-encoding: $encoding"
         }
@@ -228,7 +237,7 @@ proc Accept {chan addr port} {
 }
 
 proc Control {chan} {
-    if {[gets $chan line] != -1} {
+    if {[gets $chan line] >= 0} {
         if {[string trim $line] eq "quit"} {
             set ::forever 1
         }
index e63bcda..e5d974c 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -22,7 +22,7 @@ if {[catch {package require http 1.0}]} {
        ::tcltest::cleanupTests
        return
     } else {
-       catch {puts "Running http 1.0 tests in slave interp"}
+       catch {puts "Running http 1.0 tests in child interp"}
        set interp [interp create httpold]
        $interp eval [list set httpold "running"]
        $interp eval [list set argv $argv]
@@ -33,23 +33,22 @@ if {[catch {package require http 1.0}]} {
     }
 }
 
-if {$::tcl_platform(os) eq "Darwin"} {
-    # Name resolution often a problem on OSX; not focus of HTTP package anyway
-    set HOST localhost
-} else {
-    set HOST [info hostname]
-}
+# Do not use [info hostname].
+# Name resolution is often a problem on OSX; not focus of HTTP package anyway.
+# Also a problem on other platforms for http-4.14 (test with bad port number).
+set HOST localhost
 
 set bindata "This is binary data\x0d\x0amore\x0dmore\x0amore\x00null"
 catch {unset data}
 
 ##
 ## The httpd script implement a stub http server
+## Sourcing httpd overwrites the value of HOST.
 ##
 source [file join [file dirname [info script]] httpd]
 
 set port 8010
-if [catch {httpd_init $port} listen] {
+if {[catch {httpd_init $port} listen]} {
     puts "Cannot start http server, http test skipped"
     unset port
     ::tcltest::cleanupTests
index fbcf56c..e537fea 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 040364a..e589351 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -142,7 +142,7 @@ test if-1.16 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -165,7 +165,7 @@ test if-1.16 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -239,7 +239,7 @@ test if-2.5 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -262,7 +262,7 @@ test if-2.5 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -287,7 +287,7 @@ test if-2.5 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 5
@@ -310,7 +310,7 @@ test if-2.5 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 6
@@ -389,7 +389,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -412,7 +412,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -437,7 +437,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 5
@@ -460,7 +460,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 6
@@ -485,7 +485,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 8
@@ -508,7 +508,7 @@ test if-3.6 {TclCompileIfCmd: test jumpFalse instruction replacement after long
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 9
@@ -713,7 +713,7 @@ test if-5.16 {if cmd with computed command names: test jumpFalse instruction rep
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -736,7 +736,7 @@ test if-5.16 {if cmd with computed command names: test jumpFalse instruction rep
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -816,7 +816,7 @@ test if-6.5 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -839,7 +839,7 @@ test if-6.5 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -864,7 +864,7 @@ test if-6.5 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 5
@@ -887,7 +887,7 @@ test if-6.5 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 6
@@ -975,7 +975,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 2
@@ -998,7 +998,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 3
@@ -1023,7 +1023,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 5
@@ -1046,7 +1046,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 6
@@ -1071,7 +1071,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 8
@@ -1094,7 +1094,7 @@ test if-7.6 {if cmd with computed command names: test jumpFalse instruction repl
                    set i $i
                    set i [lindex $s $i]
                }
-               set i [expr $i-1]
+               incr i -1
            }
        }
        set a 9
index ed457cf..5d792e1 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 9243be0..af15f5e 100644 (file)
@@ -11,7 +11,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 646cb02..60ee61a 100644 (file)
@@ -8,8 +8,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 5fe2240..fb9e0de 100644 (file)
@@ -16,7 +16,7 @@
 # DO NOT DELETE THIS LINE
 
 if {{::tcltest} ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -325,7 +325,7 @@ test info-9.2 {info level option} {
 } {1 {t1 146 testString}}
 test info-9.3 {info level option} {
     proc t1 {a b} {
-        t2 [expr $a*2] $b
+        t2 [expr {$a*2}] $b
     }
     proc t2 {x y} {
         list [info level] [info level 1] [info level 2] [info level -1] \
@@ -2099,7 +2099,7 @@ proc foo::bar {} {
     foreach {*}{
        x y
        {set res [info frame 0]}
-    } 
+    }
     return $res
 }
 test info-33.13 {{*}, literal, simple, bytecompiled} -body {
@@ -2114,7 +2114,7 @@ proc foo::bar {} {
     if {*}{
        {[return [info frame 0]]}
        {}
-    } 
+    }
 }
 test info-33.14 {{*}, literal, simple, bytecompiled} -body {
     reduce [foo::bar]
@@ -2128,7 +2128,7 @@ proc foo::bar {} {
     if 0 {*}{
        {} else
        {return [info frame 0]}
-    } 
+    }
 }
 test info-33.15 {{*}, literal, simple, bytecompiled} -body {
     reduce [foo::bar]
@@ -2229,7 +2229,7 @@ namespace eval foo {}
 proc foo::bar {} {
     try {*}{
        {set res [info frame 0]}
-    } 
+    }
     return $res
 }
 test info-33.23 {{*}, literal, simple, bytecompiled} -body {
index 639389f..e8d484b 100644 (file)
@@ -18,6 +18,19 @@ if {"::tcltest" ni [namespace children]} {
 # Clear out any namespaces called test_ns_*
 catch {namespace delete {*}[namespace children :: test_ns_*]}
 \f
+test init-0.1 {no error on initialization phase (init.tcl)} -setup {
+    interp create child
+} -body {
+    child eval {
+       list [set v [info exists ::errorInfo]] \
+               [if {$v} {set ::errorInfo}] \
+            [set v [info exists ::errorCode]] \
+               [if {$v} {set ::errorCode}]
+    }
+} -cleanup {
+    interp delete child
+} -result {0 {} 0 {}}
+
 # Six cases - white box testing
 
 test init-1.1 {auto_qualify - absolute cmd - namespace} {
@@ -46,11 +59,11 @@ test init-1.8 {auto_qualify - multiple colons 2} {
     auto_qualify :::foo ::bar
 } foo
 \f
-# We use a sub-interp and auto_reset and double the tests because there is 2
+# We use a child interp and auto_reset and double the tests because there is 2
 # places where auto_loading occur (before loading the indexes files and after)
 
 set testInterp [interp create]
-tcltest::loadIntoSlaveInterpreter $testInterp {*}$argv
+tcltest::loadIntoChildInterpreter $testInterp {*}$argv
 interp eval $testInterp {
     namespace import -force ::tcltest::*
     customMatch pairwise {apply {{mode pair} {
diff --git a/tests/internals.tcl b/tests/internals.tcl
new file mode 100644 (file)
index 0000000..6b5bb87
--- /dev/null
@@ -0,0 +1,96 @@
+# This file contains internal facilities for Tcl tests.
+#
+# Source this file in the related tests to include from tcl-tests:
+#
+#   source [file join [file dirname [info script]] internals.tcl]
+#
+# Copyright (c) 2020 Sergey G. Brester (sebres).
+#
+# See the file "license.terms" for information on usage and redistribution
+# of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+if {[namespace which -command ::tcltest::internals::scriptpath] eq ""} {namespace eval ::tcltest::internals {
+
+namespace path ::tcltest
+
+::tcltest::ConstraintInitializer testWithLimit { expr {[testConstraint macOrUnix] && ![catch { exec prlimit --version }]} }
+
+# test-with-limit --
+#
+# Usage: test-with-limit ?-addmem bytes? ?-maxmem bytes? command
+# Options:
+#      -addmem - set additional memory limit (in bytes) as difference (extra memory needed to run a test)
+#      -maxmem - set absolute maximum address space limit (in bytes)
+# 
+proc testWithLimit args {
+    set body [lindex $args end]
+    array set in [lrange $args 0 end-1]
+    # test in child process (with limits):
+    set pipe {}
+    if {[catch {
+       # start new process:
+       set pipe [open |[list [interpreter]] r+]
+       set ppid [pid $pipe]
+       # create prlimit args:
+       set args {}
+       # with limited address space:
+       if {[info exists in(-addmem)] || [info exists in(-maxmem)]} {
+           if {[info exists in(-addmem)]} {
+               # as differnce to normal usage, so try to retrieve current memory usage:
+               if {[catch {
+                   # using ps (vsz is in KB):
+                   incr in(-addmem) [expr {[lindex [exec ps -hq $ppid -o vsz] end] * 1024}]
+               }]} {
+                   # ps failed, use default size 20MB:
+                   incr in(-addmem) 20000000
+                   # + size of locale-archive (may be up to 100MB):
+                   incr in(-addmem) [expr {
+                       [file exists /usr/lib/locale/locale-archive] ? 
+                       [file size /usr/lib/locale/locale-archive] : 0
+                   }]
+               }
+               if {![info exists in(-maxmem)]} {
+                   set in(-maxmem) $in(-addmem)
+               }
+               set in(-maxmem) [expr { max($in(-addmem), $in(-maxmem)) }]
+           }
+           append args --as=$in(-maxmem)
+       }
+       # apply limits:
+       exec prlimit -p $ppid {*}$args
+    } msg opt]} {
+       catch {close $pipe}
+       tcltest::Warn "testWithLimit: error - [regsub {^\s*([^\n]*).*$} $msg {\1}]"
+       tcltest::Skip testWithLimit
+    }
+    # execute body, close process and return:
+    set ret [catch {
+       chan configure $pipe -buffering line
+       puts $pipe "puts \[$body\]"
+       puts $pipe exit
+       set result [read $pipe]
+       close $pipe
+       set pipe {}
+       set result
+    } result opt]
+    if {$pipe ne ""} { catch { close $pipe } }
+    if {$ret && [dict get $opt -errorcode] eq "BYPASS-SKIPPED-TEST"} {
+       return {*}$opt $result
+    }
+    if { ( [info exists in(-warn-on-code)] && $ret in $in(-warn-on-code) )
+      || ( $ret && [info exists in(-warn-on-alloc-error)] && $in(-warn-on-alloc-error)
+           && [regexp {\munable to (?:re)?alloc\M} $result] )
+    } {
+       tcltest::Warn "testWithLimit: wrong limit, result: $result"
+       tcltest::Skip testWithLimit
+    }
+    return {*}$opt $result
+}
+
+# export all routines starting with test
+namespace export test*
+
+# for script path & as mark for loaded
+proc scriptpath {} [list return [info script]]
+
+}}; # end of internals.
\ No newline at end of file
index 5b7b157..d742484 100644 (file)
@@ -22,7 +22,7 @@ testConstraint testinterpdelete [llength [info commands testinterpdelete]]
 
 set hidden_cmds {cd encoding exec exit fconfigure file glob load open pwd socket source tcl:encoding:dirs tcl:file:atime tcl:file:attributes tcl:file:copy tcl:file:delete tcl:file:dirname tcl:file:executable tcl:file:exists tcl:file:extension tcl:file:isdirectory tcl:file:isfile tcl:file:link tcl:file:lstat tcl:file:mkdir tcl:file:mtime tcl:file:nativename tcl:file:normalize tcl:file:owned tcl:file:readable tcl:file:readlink tcl:file:rename tcl:file:rootname tcl:file:size tcl:file:stat tcl:file:tail tcl:file:tempfile tcl:file:type tcl:file:volumes tcl:file:writable unload}
 
-foreach i [interp slaves] {
+foreach i [interp children] {
   interp delete $i
 }
 \f
@@ -32,7 +32,7 @@ test interp-1.1 {options for interp command} -returnCodes error -body {
 } -result {wrong # args: should be "interp cmd ?arg ...?"}
 test interp-1.2 {options for interp command} -returnCodes error -body {
     interp frobox
-} -result {bad option "frobox": must be alias, aliases, bgerror, cancel, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
+} -result {bad option "frobox": must be alias, aliases, bgerror, cancel, children, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
 test interp-1.3 {options for interp command} {
     interp delete
 } ""
@@ -46,17 +46,17 @@ test interp-1.5 {options for interp command} -returnCodes error -body {
 # test interp-0.6 was removed
 #
 test interp-1.6 {options for interp command} -returnCodes error -body {
-    interp slaves foo bar zop
-} -result {wrong # args: should be "interp slaves ?path?"}
+    interp children foo bar zop
+} -result {wrong # args: should be "interp children ?path?"}
 test interp-1.7 {options for interp command} -returnCodes error -body {
     interp hello
-} -result {bad option "hello": must be alias, aliases, bgerror, cancel, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
+} -result {bad option "hello": must be alias, aliases, bgerror, cancel, children, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
 test interp-1.8 {options for interp command} -returnCodes error -body {
     interp -froboz
-} -result {bad option "-froboz": must be alias, aliases, bgerror, cancel, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
+} -result {bad option "-froboz": must be alias, aliases, bgerror, cancel, children, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
 test interp-1.9 {options for interp command} -returnCodes error -body {
     interp -froboz -safe
-} -result {bad option "-froboz": must be alias, aliases, bgerror, cancel, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer} 
+} -result {bad option "-froboz": must be alias, aliases, bgerror, cancel, children, create, debug, delete, eval, exists, expose, hide, hidden, issafe, invokehidden, limit, marktrusted, recursionlimit, slaves, share, target, or transfer}
 test interp-1.10 {options for interp command} -returnCodes error -body {
     interp target
 } -result {wrong # args: should be "interp target path alias"}
@@ -70,7 +70,7 @@ test interp-2.2 {basic interpreter creation} {
 } 0
 test interp-2.3 {basic interpreter creation} {
     catch {interp create -safe}
-} 0 
+} 0
 test interp-2.4 {basic interpreter creation} -setup {
     catch {interp create a}
 } -returnCodes error -body {
@@ -105,8 +105,8 @@ test interp-2.11 {anonymous interps vs existing procs} {
     proc interp$thenum {} {}
     set x [interp create]
     regexp "interp(\[0-9]+)" $x dummy anothernum
-    expr $anothernum > $thenum
-} 1    
+    expr {$anothernum > $thenum}
+} 1
 test interp-2.12 {anonymous interps vs existing procs} {
     set x [interp create -safe]
     regexp "interp(\[0-9]+)" $x dummy thenum
@@ -114,51 +114,51 @@ test interp-2.12 {anonymous interps vs existing procs} {
     proc interp$thenum {} {}
     set x [interp create -safe]
     regexp "interp(\[0-9]+)" $x dummy anothernum
-    expr $anothernum - $thenum
+    expr {$anothernum - $thenum}
 } 1
 test interp-2.13 {correct default when no $path arg is given} -body {
     interp create --
 } -match regexp -result {interp[0-9]+}
 
-foreach i [interp slaves] {
+foreach i [interp children] {
     interp delete $i
 }
 
-# Part 2: Testing "interp slaves" and "interp exists"
-test interp-3.1 {testing interp exists and interp slaves} {
-    interp slaves
+# Part 2: Testing "interp children" and "interp exists"
+test interp-3.1 {testing interp exists and interp children} {
+    interp children
 } ""
-test interp-3.2 {testing interp exists and interp slaves} {
+test interp-3.2 {testing interp exists and interp children} {
     interp create a
     interp exists a
 } 1
-test interp-3.3 {testing interp exists and interp slaves} {
+test interp-3.3 {testing interp exists and interp children} {
     interp exists nonexistent
 } 0
-test interp-3.4 {testing interp exists and interp slaves} -body {
-    interp slaves a b c
-} -returnCodes error -result {wrong # args: should be "interp slaves ?path?"}
-test interp-3.5 {testing interp exists and interp slaves} -body {
+test interp-3.4 {testing interp exists and interp children} -body {
+    interp children a b c
+} -returnCodes error -result {wrong # args: should be "interp children ?path?"}
+test interp-3.5 {testing interp exists and interp children} -body {
     interp exists a b c
 } -returnCodes error -result {wrong # args: should be "interp exists ?path?"}
-test interp-3.6 {testing interp exists and interp slaves} {
+test interp-3.6 {testing interp exists and interp children} {
     interp exists
 } 1
-test interp-3.7 {testing interp exists and interp slaves} -setup {
+test interp-3.7 {testing interp exists and interp children} -setup {
     catch {interp create a}
 } -body {
-    interp slaves
+    interp children
 } -result a
-test interp-3.8 {testing interp exists and interp slaves} -body {
-    interp slaves a b c
-} -returnCodes error -result {wrong # args: should be "interp slaves ?path?"}
-test interp-3.9 {testing interp exists and interp slaves} -setup {
+test interp-3.8 {testing interp exists and interp children} -body {
+    interp children a b c
+} -returnCodes error -result {wrong # args: should be "interp children ?path?"}
+test interp-3.9 {testing interp exists and interp children} -setup {
     catch {interp create a}
 } -body {
     interp create {a a2} -safe
-    expr {"a2" in [interp slaves a]}
+    expr {"a2" in [interp children a]}
 } -result 1
-test interp-3.10 {testing interp exists and interp slaves} -setup {
+test interp-3.10 {testing interp exists and interp children} -setup {
     catch {interp create a}
     catch {interp create {a a2}}
 } -body {
@@ -186,7 +186,7 @@ test interp-4.5 {testing interp delete} {
     interp create a
     interp create {a x1}
     interp delete {a x1}
-    expr {"x1" in [interp slaves a]}
+    expr {"x1" in [interp children a]}
 } 0
 test interp-4.6 {testing interp delete} {
     interp create c1
@@ -203,14 +203,14 @@ test interp-4.8 {testing interp delete} -returnCodes error -body {
     interp delete {}
 } -result {cannot delete the current interpreter}
 
-foreach i [interp slaves] {
+foreach i [interp children] {
     interp delete $i
 }
 
 # Part 4: Consistency checking - all nondeleted interpreters should be
 # there:
 test interp-5.1 {testing consistency} {
-    interp slaves
+    interp children
 } ""
 test interp-5.2 {testing consistency} {
     interp exists a
@@ -224,22 +224,22 @@ interp create a
 
 # Part 5: Testing eval in interpreter object command and with interp command
 test interp-6.1 {testing eval} {
-    a eval expr 3 + 5
+    a eval expr {{3 + 5}}
 } 8
 test interp-6.2 {testing eval} -returnCodes error -body {
     a eval foo
 } -result {invalid command name "foo"}
 test interp-6.3 {testing eval} {
-    a eval {proc foo {} {expr 3 + 5}}
+    a eval {proc foo {} {expr {3 + 5}}}
     a eval foo
 } 8
-catch {a eval {proc foo {} {expr 3 + 5}}}
+catch {a eval {proc foo {} {expr {3 + 5}}}}
 test interp-6.4 {testing eval} {
     interp eval a foo
 } 8
 test interp-6.5 {testing eval} {
     interp create {a x2}
-    interp eval {a x2} {proc frob {} {expr 4 * 9}}
+    interp eval {a x2} {proc frob {} {expr {4 * 9}}}
     interp eval {a x2} frob
 } 36
 catch {interp create {a x2}}
@@ -247,27 +247,27 @@ test interp-6.6 {testing eval} -returnCodes error -body {
     interp eval {a x2} foo
 } -result {invalid command name "foo"}
 
-# UTILITY PROCEDURE RUNNING IN MASTER INTERPRETER:
-proc in_master {args} {
-     return [list seen in master: $args]
+# UTILITY PROCEDURE RUNNING IN PARENT INTERPRETER:
+proc in_parent {args} {
+     return [list seen in parent: $args]
 }
 
 # Part 6: Testing basic alias creation
 test interp-7.1 {testing basic alias creation} {
-    a alias foo in_master
+    a alias foo in_parent
 } foo
-catch {a alias foo in_master}
+catch {a alias foo in_parent}
 test interp-7.2 {testing basic alias creation} {
-    a alias bar in_master a1 a2 a3
+    a alias bar in_parent a1 a2 a3
 } bar
-catch {a alias bar in_master a1 a2 a3}
+catch {a alias bar in_parent a1 a2 a3}
 # Test 6.3 has been deleted.
 test interp-7.3 {testing basic alias creation} {
     a alias foo
-} in_master
+} in_parent
 test interp-7.4 {testing basic alias creation} {
     a alias bar
-} {in_master a1 a2 a3}
+} {in_parent a1 a2 a3}
 test interp-7.5 {testing basic alias creation} {
     lsort [a aliases]
 } {bar foo}
@@ -278,14 +278,14 @@ test interp-7.6 {testing basic aliases arg checking} -returnCodes error -body {
 # Part 7: testing basic alias invocation
 test interp-8.1 {testing basic alias invocation} {
     catch {interp create a}
-    a alias foo in_master
+    a alias foo in_parent
     a eval foo s1 s2 s3
-} {seen in master: {s1 s2 s3}}
+} {seen in parent: {s1 s2 s3}}
 test interp-8.2 {testing basic alias invocation} {
     catch {interp create a}
-    a alias bar in_master a1 a2 a3
+    a alias bar in_parent a1 a2 a3
     a eval bar s1 s2 s3
-} {seen in master: {a1 a2 a3 s1 s2 s3}}
+} {seen in parent: {a1 a2 a3 s1 s2 s3}}
 test interp-8.3 {testing basic alias invocation} -returnCodes error -body {
    catch {interp create a}
    a alias
@@ -294,13 +294,13 @@ test interp-8.3 {testing basic alias invocation} -returnCodes error -body {
 # Part 8: Testing aliases for non-existent or hidden targets
 test interp-9.1 {testing aliases for non-existent targets} {
     catch {interp create a}
-    a alias zop nonexistent-command-in-master
+    a alias zop nonexistent-command-in-parent
     list [catch {a eval zop} msg] $msg
-} {1 {invalid command name "nonexistent-command-in-master"}}
+} {1 {invalid command name "nonexistent-command-in-parent"}}
 test interp-9.2 {testing aliases for non-existent targets} {
     catch {interp create a}
-    a alias zop nonexistent-command-in-master
-    proc nonexistent-command-in-master {} {return i_exist!}
+    a alias zop nonexistent-command-in-parent
+    proc nonexistent-command-in-parent {} {return i_exist!}
     a eval zop
 } i_exist!
 test interp-9.3 {testing aliases for hidden commands} {
@@ -329,8 +329,8 @@ test interp-9.4 {testing aliases and namespace commands} {
     set res
  } {GLOBAL GLOBAL}
 
-if {[info command nonexistent-command-in-master] != ""} {
-    rename nonexistent-command-in-master {}
+if {[info command nonexistent-command-in-parent] != ""} {
+    rename nonexistent-command-in-parent {}
 }
 
 # Part 9: Aliasing between interpreters
@@ -380,9 +380,9 @@ test interp-10.6 {testing aliasing between interpreters} {
     interp create a
     interp create b
     interp alias a a_command b b_command a1 a2 a3
-    b alias b_command in_master b1 b2 b3
+    b alias b_command in_parent b1 b2 b3
     a eval a_command m1 m2 m3
-} {seen in master: {b1 b2 b3 a1 a2 a3 m1 m2 m3}}
+} {seen in parent: {b1 b2 b3 a1 a2 a3 m1 m2 m3}}
 test interp-10.7 {testing aliases between interpreters} {
     catch {interp delete a}
     interp create a
@@ -513,7 +513,7 @@ test interp-14.3 {testing interp aliases} {
     interp alias {a x3} froboz "" puts
     interp aliases {a x3}
 } froboz
-test interp-14.4 {testing interp alias - alias over master} {
+test interp-14.4 {testing interp alias - alias over parent} {
     # SF Bug 641195
     catch {interp delete a}
     interp create a
@@ -746,7 +746,7 @@ test interp-16.5 {testing deletion order, bgerror} {
     xxx eval {proc bgerror {args} {exit}}
     xxx alias exit kill xxx
     proc kill {i} {interp delete $i}
-    xxx eval after 100 expr a + b
+    xxx eval after 100 expr {a + b}
     after 200
     update
     interp exists xxx
@@ -793,32 +793,32 @@ test interp-17.6 {alias loop prevention} {
 } {1 {cannot define or rename alias "b": would create a loop}}
 
 #
-# Test robustness of Tcl_DeleteInterp when applied to a slave interpreter.
+# Test robustness of Tcl_DeleteInterp when applied to a child interpreter.
 # If there are bugs in the implementation these tests are likely to expose
 # the bugs as a core dump.
 #
 
-test interp-18.1 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.1 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     list [catch {testinterpdelete} msg] $msg
 } {1 {wrong # args: should be "testinterpdelete path"}}
-test interp-18.2 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.2 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     catch {interp delete a}
     interp create a
     testinterpdelete a
 } ""
-test interp-18.3 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.3 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     catch {interp delete a}
     interp create a
     interp create {a b}
     testinterpdelete {a b}
 } ""
-test interp-18.4 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.4 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     catch {interp delete a}
     interp create a
     interp create {a b}
     testinterpdelete a
 } ""
-test interp-18.5 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.5 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     catch {interp delete a}
     interp create a
     interp create {a b}
@@ -826,7 +826,7 @@ test interp-18.5 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
     proc dodel {x} {testinterpdelete $x}
     list [catch {interp eval {a b} {dodel {a b}}} msg] $msg
 } {0 {}}
-test interp-18.6 {testing Tcl_DeleteInterp vs slaves} testinterpdelete {
+test interp-18.6 {testing Tcl_DeleteInterp vs children} testinterpdelete {
     catch {interp delete a}
     interp create a
     interp create {a b}
@@ -876,12 +876,12 @@ test interp-18.9 {eval in deleted interp, bug 495830} {
     interp create tst
     interp alias tst suicide {} interp delete tst
     list [catch {tst eval {suicide; set a 5}} msg] $msg
-} {1 {attempt to call eval in deleted interpreter}}     
+} {1 {attempt to call eval in deleted interpreter}}
 test interp-18.10 {eval in deleted interp, bug 495830} {
     interp create tst
     interp alias tst suicide {} interp delete tst
     list [catch {tst eval {set set set; suicide; $set a 5}} msg] $msg
-} {1 {attempt to call eval in deleted interpreter}}     
+} {1 {attempt to call eval in deleted interpreter}}
 
 # Test alias deletion
 
@@ -966,12 +966,12 @@ test interp-19.9 {alias deletion, renaming} {
     interp create a
     interp alias a foo a bar
     interp eval a rename foo blotz
-    interp eval a {proc foo {} {expr 34 * 34}}
+    interp eval a {proc foo {} {expr {34 * 34}}}
     interp alias a foo {}
     set l [interp eval a foo]
     interp delete a
     set l
-} 1156    
+} 1156
 
 test interp-20.1 {interp hide, interp expose and interp invokehidden} {
     set a [interp create]
@@ -1192,7 +1192,7 @@ test interp-20.21 {interp hide vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {a hide list} msg]    
+    lappend l [catch {a hide list} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1201,7 +1201,7 @@ test interp-20.22 {interp hide vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {interp hide a list} msg]    
+    lappend l [catch {interp hide a list} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1210,7 +1210,7 @@ test interp-20.23 {interp hide vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {a eval {interp hide {} list}} msg]    
+    lappend l [catch {a eval {interp hide {} list}} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1220,7 +1220,7 @@ test interp-20.24 {interp hide vs safety} {
     interp create a -safe
     interp create {a b}
     set l ""
-    lappend l [catch {a eval {interp hide b list}} msg]    
+    lappend l [catch {a eval {interp hide b list}} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1239,7 +1239,7 @@ test interp-20.26 {interp expoose vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {a hide list} msg]    
+    lappend l [catch {a hide list} msg]
     lappend l $msg
     lappend l [catch {a expose list} msg]
     lappend l $msg
@@ -1250,9 +1250,9 @@ test interp-20.27 {interp expose vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {interp hide a list} msg]    
+    lappend l [catch {interp hide a list} msg]
     lappend l $msg
-    lappend l [catch {interp expose a list} msg]    
+    lappend l [catch {interp expose a list} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1261,7 +1261,7 @@ test interp-20.28 {interp expose vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {a hide list} msg]    
+    lappend l [catch {a hide list} msg]
     lappend l $msg
     lappend l [catch {a eval {interp expose {} list}} msg]
     lappend l $msg
@@ -1272,9 +1272,9 @@ test interp-20.29 {interp expose vs safety} {
     catch {interp delete a}
     interp create a -safe
     set l ""
-    lappend l [catch {interp hide a list} msg]    
+    lappend l [catch {interp hide a list} msg]
     lappend l $msg
-    lappend l [catch {a eval {interp expose {} list}} msg]    
+    lappend l [catch {a eval {interp expose {} list}} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1284,9 +1284,9 @@ test interp-20.30 {interp expose vs safety} {
     interp create a -safe
     interp create {a b}
     set l ""
-    lappend l [catch {interp hide {a b} list} msg]    
+    lappend l [catch {interp hide {a b} list} msg]
     lappend l $msg
-    lappend l [catch {a eval {interp expose b list}} msg]    
+    lappend l [catch {a eval {interp expose b list}} msg]
     lappend l $msg
     interp delete a
     set l
@@ -1296,7 +1296,7 @@ test interp-20.31 {interp expose vs safety} {
     interp create a -safe
     interp create {a b}
     set l ""
-    lappend l [catch {interp hide {a b} list} msg]    
+    lappend l [catch {interp hide {a b} list} msg]
     lappend l $msg
     lappend l [catch {interp expose {a b} list} msg]
     lappend l $msg
@@ -1615,36 +1615,36 @@ test interp-20.49 {interp invokehidden -namespace} -setup {
     set script [makeFile {
        set x [namespace current]
     } script]
-    interp create -safe slave
+    interp create -safe child
 } -body {
-    slave invokehidden -namespace ::foo source $script
-    slave eval {set ::foo::x}
+    child invokehidden -namespace ::foo source $script
+    child eval {set ::foo::x}
 } -cleanup {
-    interp delete slave
+    interp delete child
     removeFile script
 } -result ::foo
 test interp-20.50 {Bug 2486550} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave hide coroutine
-    slave invokehidden coroutine
+    child hide coroutine
+    child invokehidden coroutine
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -match glob -result *
 test interp-20.50.1 {Bug 2486550} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave hide coroutine
-    catch {slave invokehidden coroutine} m o
+    child hide coroutine
+    catch {child invokehidden coroutine} m o
     dict get $o -errorinfo
 } -cleanup {
     unset -nocomplain m 0
-    interp delete slave
+    interp delete child
 } -returnCodes ok -result {wrong # args: should be "coroutine name cmd ?arg ...?"
     while executing
 "coroutine"
     invoked from within
-"slave invokehidden coroutine"}
+"child invokehidden coroutine"}
 
 test interp-21.1 {interp hidden} {
     interp hidden {}
@@ -1676,7 +1676,7 @@ test interp-21.5 {interp hidden} -setup {
     lsort [interp hidden a]
 } -cleanup {
     interp delete a
-} -result $hidden_cmds 
+} -result $hidden_cmds
 test interp-21.6 {interp hidden vs interp hide, interp expose} -setup {
     catch {interp delete a}
     set l ""
@@ -2058,8 +2058,8 @@ test interp-25.1 {testing aliasing of string commands} -setup {
 
 test interp-26.1 {result code transmission : interp eval direct} {
     # Test that all the possibles error codes from Tcl get passed up
-    # from the slave interp's context to the master, even though the
-    # slave nominally thinks the command is running at the root level.
+    # from the child interp's context to the parent, even though the
+    # child nominally thinks the command is running at the root level.
     catch {interp delete a}
     interp create a
     set res {}
@@ -2085,7 +2085,7 @@ test interp-26.2 {result code transmission : interp eval indirect} {
 } {-1 ret-1 0 ret0 1 ret1 0 ret2 3 ret3 4 ret4 5 ret5}
 test interp-26.3 {result code transmission : aliases} {
     # Test that all the possibles error codes from Tcl get passed up from the
-    # slave interp's context to the master, even though the slave nominally
+    # child interp's context to the parent, even though the child nominally
     # thinks the command is running at the root level.
     catch {interp delete a}
     interp create a
@@ -2180,7 +2180,7 @@ test interp-26.8 {errorInfo transmission: safe interps--bug 1637} -setup {
 } -constraints knownBug -body {
     # this test fails because the errorInfo is fully transmitted whether the
     # interp is safe or not.  The errorInfo should never report data from the
-    # master interpreter because it could contain sensitive information.
+    # parent interpreter because it could contain sensitive information.
     proc MyError {secret} {
        return -code error "msg"
     }
@@ -2200,7 +2200,7 @@ test interp-27.1 {interp aliases & namespaces} -setup {
     set i [interp create]
 } -body {
     set aliasTrace {}
-    proc tstAlias {args} { 
+    proc tstAlias {args} {
        global aliasTrace
        lappend aliasTrace [list [namespace current] $args]
     }
@@ -2214,7 +2214,7 @@ test interp-27.2 {interp aliases & namespaces} -setup {
     set i [interp create]
 } -body {
     set aliasTrace {}
-    proc tstAlias {args} { 
+    proc tstAlias {args} {
        global aliasTrace
        lappend aliasTrace [list [namespace current] $args]
     }
@@ -2228,7 +2228,7 @@ test interp-27.3 {interp aliases & namespaces} -setup {
     set i [interp create]
 } -body {
     set aliasTrace {}
-    proc tstAlias {args} { 
+    proc tstAlias {args} {
        global aliasTrace
        lappend aliasTrace [list [namespace current] $args]
     }
@@ -2244,7 +2244,7 @@ test interp-27.4 {interp aliases & namespaces} -setup {
 } -body {
     namespace eval foo2 {
        variable aliasTrace {}
-       proc bar {args} { 
+       proc bar {args} {
            variable aliasTrace
            lappend aliasTrace [list [namespace current] $args]
        }
@@ -2275,22 +2275,22 @@ test interp-27.5 {interp hidden & namespaces} -setup {
 test interp-27.6 {interp hidden & aliases & namespaces} -setup {
     set i [interp create]
 } -constraints knownBug -body {
-    set v root-master
+    set v root-parent
     namespace eval foo {
-       variable v foo-master
+       variable v foo-parent
        proc bar {interp args} {
            variable v
-           list "master bar called ($v) ([namespace current]) ($args)"\
+           list "parent bar called ($v) ([namespace current]) ($args)"\
                [interp invokehidden $interp foo::bar $args]
        }
     }
     interp eval $i {
        namespace eval foo {
            namespace export *
-           variable v foo-slave
+           variable v foo-child
            proc bar {args} {
                variable v
-               return "slave bar called ($v) ([namespace current]) ($args)"
+               return "child bar called ($v) ([namespace current]) ($args)"
            }
        }
     }
@@ -2298,7 +2298,7 @@ test interp-27.6 {interp hidden & aliases & namespaces} -setup {
     $i hide foo::bar
     $i alias foo::bar foo::bar $i
     set res [concat $res [interp eval $i {
-       set v root-slave
+       set v root-child
        namespace eval test {
            variable v foo-test
            namespace import ::foo::*
@@ -2308,29 +2308,29 @@ test interp-27.6 {interp hidden & aliases & namespaces} -setup {
 } -cleanup {
     namespace delete foo
     interp delete $i
-} -result {{slave bar called (foo-slave) (::foo) (test1)} {master bar called (foo-master) (::foo) (test2)} {slave bar called (foo-slave) (::foo) (test2)}}
+} -result {{child bar called (foo-child) (::foo) (test1)} {parent bar called (foo-parent) (::foo) (test2)} {child bar called (foo-child) (::foo) (test2)}}
 test interp-27.7 {interp hidden & aliases & imports & namespaces} -setup {
     set i [interp create]
 } -constraints knownBug -body {
-    set v root-master
+    set v root-parent
     namespace eval mfoo {
-       variable v foo-master
+       variable v foo-parent
        proc bar {interp args} {
            variable v
-           list "master bar called ($v) ([namespace current]) ($args)"\
+           list "parent bar called ($v) ([namespace current]) ($args)"\
                [interp invokehidden $interp test::bar $args]
        }
     }
     interp eval $i {
        namespace eval foo {
            namespace export *
-           variable v foo-slave
+           variable v foo-child
            proc bar {args} {
                variable v
-               return "slave bar called ($v) ([info level 0]) ([uplevel namespace current]) ([namespace current]) ($args)"
+               return "child bar called ($v) ([info level 0]) ([uplevel namespace current]) ([namespace current]) ($args)"
            }
        }
-       set v root-slave
+       set v root-child
        namespace eval test {
            variable v foo-test
            namespace import ::foo::*
@@ -2343,7 +2343,7 @@ test interp-27.7 {interp hidden & aliases & imports & namespaces} -setup {
 } -cleanup {
     namespace delete mfoo
     interp delete $i
-} -result {{slave bar called (foo-slave) (bar test1) (::tcltest) (::foo) (test1)} {master bar called (foo-master) (::mfoo) (test2)} {slave bar called (foo-slave) (test::bar test2) (::) (::foo) (test2)}}
+} -result {{child bar called (foo-child) (bar test1) (::tcltest) (::foo) (test1)} {parent bar called (foo-parent) (::mfoo) (test2)} {child bar called (foo-child) (test::bar test2) (::) (::foo) (test2)}}
 test interp-27.8 {hiding, namespaces and integrity} knownBug {
     namespace eval foo {
        variable v 3
@@ -2355,25 +2355,25 @@ test interp-27.8 {hiding, namespaces and integrity} knownBug {
     list [catch {interp invokehidden {} foo::bar} msg] $msg
 } {1 {invalid hidden command name "foo"}}
 
-test interp-28.1 {getting fooled by slave's namespace ?} -setup {
+test interp-28.1 {getting fooled by child's namespace ?} -setup {
     set i [interp create -safe]
-    proc master {interp args} {interp hide $interp list}
+    proc parent {interp args} {interp hide $interp list}
 } -body {
-    $i alias master master $i
+    $i alias parent parent $i
     set r [interp eval $i {
         namespace eval foo {
            proc list {args} {
                return "dummy foo::list"
            }
-           master
+           parent
        }
        info commands list
     }]
 } -cleanup {
-    rename master {}
+    rename parent {}
     interp delete $i
 } -result {}
-test interp-28.2 {master's nsName cache should not cross} -setup {
+test interp-28.2 {parent's nsName cache should not cross} -setup {
     set i [interp create]
     $i eval {proc filter lst {lsearch -all -inline -not $lst "::tcl"}}
 } -body {
@@ -2432,31 +2432,31 @@ test interp-29.1.7 {interp recursionlimit argument checking} {
     interp delete moo
     list $result [string range $msg 0 35]
 } {1 {integer value too large to represent}}
-test interp-29.1.8 {slave recursionlimit argument checking} {
+test interp-29.1.8 {child recursionlimit argument checking} {
     interp create moo
     set result [catch {moo recursionlimit foo bar} msg]
     interp delete moo
     list $result $msg
 } {1 {wrong # args: should be "moo recursionlimit ?newlimit?"}}
-test interp-29.1.9 {slave recursionlimit argument checking} {
+test interp-29.1.9 {child recursionlimit argument checking} {
     interp create moo
     set result [catch {moo recursionlimit foo} msg]
     interp delete moo
     list $result $msg
 } {1 {expected integer but got "foo"}}
-test interp-29.1.10 {slave recursionlimit argument checking} {
+test interp-29.1.10 {child recursionlimit argument checking} {
     interp create moo
     set result [catch {moo recursionlimit 0} msg]
     interp delete moo
     list $result $msg
 } {1 {recursion limit must be > 0}}
-test interp-29.1.11 {slave recursionlimit argument checking} {
+test interp-29.1.11 {child recursionlimit argument checking} {
     interp create moo
     set result [catch {moo recursionlimit -1} msg]
     interp delete moo
     list $result $msg
 } {1 {recursion limit must be > 0}}
-test interp-29.1.12 {slave recursionlimit argument checking} {
+test interp-29.1.12 {child recursionlimit argument checking} {
     interp create moo
     set result [catch {moo recursionlimit [expr {wide(1)<<32}]} msg]
     interp delete moo
@@ -2549,8 +2549,8 @@ test interp-29.3.3 {recursion limit} {
    set r
 } {1 {too many nested evaluations (infinite loop?)} 49}
 test interp-29.3.4 {recursion limit error reporting} {
-    interp create slave
-    set r1 [slave eval {
+    interp create child
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2564,13 +2564,13 @@ test interp-29.3.4 {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {falling back due to new recursion limit}}
 test interp-29.3.5 {recursion limit error reporting} {
-    interp create slave
-    set r1 [slave eval {
+    interp create child
+    set r1 [child eval {
         catch {                        # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2584,13 +2584,13 @@ test interp-29.3.5 {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {falling back due to new recursion limit}}
 test interp-29.3.6 {recursion limit error reporting} {
-    interp create slave
-    set r1 [slave eval {
+    interp create child
+    set r1 [child eval {
         catch {                        # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2604,8 +2604,8 @@ test interp-29.3.6 {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 #
@@ -2613,9 +2613,9 @@ test interp-29.3.6 {recursion limit error reporting} {
 # level will only be verified when it invokes a non-bcc'd command.
 #
 test interp-29.3.7a {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 5}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 5}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2629,14 +2629,14 @@ test interp-29.3.7a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.7b {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 5}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 5}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2650,14 +2650,14 @@ test interp-29.3.7b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.7c {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 5}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 5}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2672,14 +2672,14 @@ test interp-29.3.7c {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {too many nested evaluations (infinite loop?)}}
 test interp-29.3.8a {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 4}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 4}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2693,14 +2693,14 @@ test interp-29.3.8a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.8b {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 4}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 4}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2714,14 +2714,14 @@ test interp-29.3.8b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {too many nested evaluations (infinite loop?)}}
 test interp-29.3.9a {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 6}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 6}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2735,14 +2735,14 @@ test interp-29.3.9a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.9b {recursion limit error reporting} {
-    interp create slave
-    after 0 {interp recursionlimit slave 6}
-    set r1 [slave eval {
+    interp create child
+    after 0 {interp recursionlimit child 6}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2756,14 +2756,14 @@ test interp-29.3.9b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.10a {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 4}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 4}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2777,14 +2777,14 @@ test interp-29.3.10a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.10b {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 4}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 4}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2798,14 +2798,14 @@ test interp-29.3.10b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {too many nested evaluations (infinite loop?)}}
 test interp-29.3.11a {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 5}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 5}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2819,14 +2819,14 @@ test interp-29.3.11a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.11b {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 5}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 5}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2841,14 +2841,14 @@ test interp-29.3.11b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {1 {too many nested evaluations (infinite loop?)}}
 test interp-29.3.12a {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 6}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 6}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2862,14 +2862,14 @@ test interp-29.3.12a {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.3.12b {recursion limit error reporting} {
-    interp create slave
-    after 0 {slave recursionlimit 6}
-    set r1 [slave eval {
+    interp create child
+    after 0 {child recursionlimit 6}
+    set r1 [child eval {
         catch {                # nesting level 1
            eval {              # 2
                eval {          # 3
@@ -2884,8 +2884,8 @@ test interp-29.3.12b {recursion limit error reporting} {
            }
        } msg
     }]
-    set r2 [slave eval { set msg }]
-    interp delete slave
+    set r2 [child eval { set msg }]
+    interp delete child
     list $r1 $r2
 } {0 ok}
 test interp-29.4.1 {recursion limit inheritance} {
@@ -2916,121 +2916,121 @@ test interp-29.4.2 {recursion limit inheritance} {
    interp delete $i
    set r
 } 50
-test interp-29.5.1 {does slave recursion limit affect master?} {
+test interp-29.5.1 {does child recursion limit affect parent?} {
     set before [interp recursionlimit {}]
     set i [interp create]
     interp recursionlimit $i 20000
     set after [interp recursionlimit {}]
-    set slavelimit [interp recursionlimit $i]
+    set childlimit [interp recursionlimit $i]
     interp delete $i
-    list [expr {$before == $after}] $slavelimit
+    list [expr {$before == $after}] $childlimit
 } {1 20000}
-test interp-29.5.2 {does slave recursion limit affect master?} {
+test interp-29.5.2 {does child recursion limit affect parent?} {
     set before [interp recursionlimit {}]
     set i [interp create]
     interp recursionlimit $i 20000
     set after [interp recursionlimit {}]
-    set slavelimit [$i recursionlimit]
+    set childlimit [$i recursionlimit]
     interp delete $i
-    list [expr {$before == $after}] $slavelimit
+    list [expr {$before == $after}] $childlimit
 } {1 20000}
-test interp-29.5.3 {does slave recursion limit affect master?} {
+test interp-29.5.3 {does child recursion limit affect parent?} {
     set before [interp recursionlimit {}]
     set i [interp create]
     $i recursionlimit 20000
     set after [interp recursionlimit {}]
-    set slavelimit [interp recursionlimit $i]
+    set childlimit [interp recursionlimit $i]
     interp delete $i
-    list [expr {$before == $after}] $slavelimit
+    list [expr {$before == $after}] $childlimit
 } {1 20000}
-test interp-29.5.4 {does slave recursion limit affect master?} {
+test interp-29.5.4 {does child recursion limit affect parent?} {
     set before [interp recursionlimit {}]
     set i [interp create]
     $i recursionlimit 20000
     set after [interp recursionlimit {}]
-    set slavelimit [$i recursionlimit]
+    set childlimit [$i recursionlimit]
     interp delete $i
-    list [expr {$before == $after}] $slavelimit
+    list [expr {$before == $after}] $childlimit
 } {1 20000}
 test interp-29.6.1 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n [interp recursionlimit slave]
-    interp delete slave
+    interp create child -safe
+    set n [interp recursionlimit child]
+    interp delete child
     set n
 } 1000
 test interp-29.6.2 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n [slave recursionlimit]
-    interp delete slave
+    interp create child -safe
+    set n [child recursionlimit]
+    interp delete child
     set n
 } 1000
 test interp-29.6.3 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n1 [interp recursionlimit slave 42]
-    set n2 [interp recursionlimit slave]
-    interp delete slave
+    interp create child -safe
+    set n1 [interp recursionlimit child 42]
+    set n2 [interp recursionlimit child]
+    interp delete child
     list $n1 $n2
 } {42 42}
 test interp-29.6.4 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n1 [slave recursionlimit 42]
-    set n2 [interp recursionlimit slave]
-    interp delete slave
+    interp create child -safe
+    set n1 [child recursionlimit 42]
+    set n2 [interp recursionlimit child]
+    interp delete child
     list $n1 $n2
 } {42 42}
 test interp-29.6.5 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n1 [interp recursionlimit slave 42]
-    set n2 [slave recursionlimit]
-    interp delete slave
+    interp create child -safe
+    set n1 [interp recursionlimit child 42]
+    set n2 [child recursionlimit]
+    interp delete child
     list $n1 $n2
 } {42 42}
 test interp-29.6.6 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n1 [slave recursionlimit 42]
-    set n2 [slave recursionlimit]
-    interp delete slave
+    interp create child -safe
+    set n1 [child recursionlimit 42]
+    set n2 [child recursionlimit]
+    interp delete child
     list $n1 $n2
 } {42 42}
 test interp-29.6.7 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n1 [slave recursionlimit 42]
-    set n2 [slave recursionlimit]
-    interp delete slave
+    interp create child -safe
+    set n1 [child recursionlimit 42]
+    set n2 [child recursionlimit]
+    interp delete child
     list $n1 $n2
 } {42 42}
 test interp-29.6.8 {safe interpreter recursion limit} {
-    interp create slave -safe
-    set n [catch {slave eval {interp recursionlimit {} 42}} msg]
-    interp delete slave
+    interp create child -safe
+    set n [catch {child eval {interp recursionlimit {} 42}} msg]
+    interp delete child
     list $n $msg
 } {1 {permission denied: safe interpreters cannot change recursion limit}}
 test interp-29.6.9 {safe interpreter recursion limit} {
-    interp create slave -safe
+    interp create child -safe
     set result [
-       slave eval {
-           interp create slave2 -safe
+       child eval {
+           interp create child2 -safe
            set n [catch {
-               interp recursionlimit slave2 42
+               interp recursionlimit child2 42
             } msg]
             list $n $msg
         }
     ]
-    interp delete slave
+    interp delete child
     set result
 } {1 {permission denied: safe interpreters cannot change recursion limit}}
 test interp-29.6.10 {safe interpreter recursion limit} {
-    interp create slave -safe
+    interp create child -safe
     set result [
-        slave eval {
-           interp create slave2 -safe
+        child eval {
+           interp create child2 -safe
            set n [catch {
-               slave2 recursionlimit 42
+               child2 recursionlimit 42
             } msg]
             list $n $msg
         }
     ]
-    interp delete slave
+    interp delete child
     set result
 } {1 {permission denied: safe interpreters cannot change recursion limit}}
 
@@ -3171,7 +3171,7 @@ test interp-34.3.1 {basic test of limits - pure inside-command loop} -body {
        }
     }
     # We use a time limit here; command limits don't trap this case
-    $i limit time -seconds [expr {[clock seconds]+2}]
+    $i limit time -seconds [expr {[clock seconds] + 2}]
     $i eval foobar
 } -returnCodes error -result {time limit exceeded} -cleanup {
     interp delete $i
@@ -3193,8 +3193,8 @@ test interp-34.4 {limits with callbacks: extending limits} -setup {
 } -body {
     interp alias $i foo {} cb1
     set curlim [$i eval info cmdcount]
-    $i limit command -command "cb2 [expr $curlim+100]" \
-           -value [expr {$curlim+10}]
+    $i limit command -command "cb2 [expr {$curlim + 100}]" \
+           -value [expr {$curlim + 10}]
     $i eval {for {set i 0} {$i<10} {incr i} {foo}}
     list $a $b $c
 } -result {6 4 b} -cleanup {
@@ -3222,7 +3222,7 @@ test interp-34.5 {limits with callbacks: removing limits} -setup {
 } -body {
     interp alias $i foo {} cb1
     set curlim [$i eval info cmdcount]
-    $i limit command -command "cb2 {}" -value [expr {$curlim+10}]
+    $i limit command -command "cb2 {}" -value [expr {$curlim + 10}]
     $i eval {for {set i 0} {$i<10} {incr i} {foo}}
     list $a $b $c
 } -result {6 4 b} -cleanup {
@@ -3247,7 +3247,7 @@ test interp-34.6 {limits with callbacks: removing limits and handlers} -setup {
 } -body {
     interp alias $i foo {} cb1
     set curlim [$i eval info cmdcount]
-    $i limit command -command cb2 -value [expr {$curlim+10}]
+    $i limit command -command cb2 -value [expr {$curlim + 10}]
     $i eval {for {set i 0} {$i<10} {incr i} {foo}}
     list $a $b $c
 } -result {6 4 b} -cleanup {
@@ -3266,7 +3266,7 @@ test interp-34.7 {limits with callbacks: deleting the handler interp} -setup {
        proc cb2 {args} {
            global c i curlim
            set c b
-           $i limit command -value [expr {$curlim+1000}]
+           $i limit command -value [expr {$curlim + 1000}]
            trapToParent
        }
     }
@@ -3289,7 +3289,7 @@ test interp-34.7 {limits with callbacks: deleting the handler interp} -setup {
        set c a
        interp alias $i foo {} cb1
        set curlim [$i eval info cmdcount]
-       $i limit command -command cb2 -value [expr {$curlim+10}]
+       $i limit command -command cb2 -value [expr {$curlim + 10}]
     }
     $i eval {
        $i eval {
@@ -3304,7 +3304,7 @@ test interp-34.7 {limits with callbacks: deleting the handler interp} -setup {
 # Bug 1085023
 test interp-34.8 {time limits trigger in vwaits} -body {
     set i [interp create]
-    interp limit $i time -seconds [expr {[clock seconds]+1}] -granularity 1
+    interp limit $i time -seconds [expr {[clock seconds] + 1}] -granularity 1
     $i eval {
        set x {}
        vwait x
@@ -3321,7 +3321,7 @@ test interp-34.9 {time limits trigger in blocking after} {
     } msg]
     set t1 [clock seconds]
     interp delete $i
-    list $code $msg [expr {($t1-$t0) < 3 ? "OK" : $t1-$t0}] 
+    list $code $msg [expr {($t1-$t0) < 3 ? "OK" : $t1-$t0}]
 } {1 {time limit exceeded} OK}
 test interp-34.10 {time limits trigger in vwaits: Bug 1221395} -body {
     set i [interp create]
@@ -3352,8 +3352,8 @@ test interp-34.11 {time limit extension in callbacks} -setup {
 } -body {
     set i [interp create]
     set t0 [clock seconds]
-    $i limit time -seconds [expr {$t0+1}] -granularity 1 \
-       -command "cb1 $i [expr {$t0+2}]"
+    $i limit time -seconds [expr {$t0 + 1}] -granularity 1 \
+       -command "cb1 $i [expr {$t0 + 2}]"
     set ::result {}
     lappend ::result [catch {
        $i eval {
@@ -3380,8 +3380,8 @@ test interp-34.12 {time limit extension in callbacks} -setup {
 } -body {
     set i [interp create]
     set t0 [clock seconds]
-    set ::times "[expr {$t0+2}] [expr {$t0+100}]"
-    $i limit time -seconds [expr {$t0+1}] -granularity 1 -command "cb1 $i"
+    set ::times "[expr {$t0 + 2}] [expr {$t0 + 100}]"
+    $i limit time -seconds [expr {$t0 + 1}] -granularity 1 -command "cb1 $i"
     set ::result {}
     lappend ::result [catch {
        $i eval {
@@ -3555,48 +3555,48 @@ test interp-35.24 {interp time limits can't touch current interp} -body {
 test interp-36.1 {interp bgerror syntax} -body {
     interp bgerror
 } -returnCodes error -result {wrong # args: should be "interp bgerror path ?cmdPrefix?"}
-test interp-36.2 {interp bgerror syntax} -body { 
+test interp-36.2 {interp bgerror syntax} -body {
     interp bgerror x y z
 } -returnCodes error -result {wrong # args: should be "interp bgerror path ?cmdPrefix?"}
 test interp-36.3 {interp bgerror syntax} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave bgerror x y
+    child bgerror x y
 } -cleanup {
-    interp delete slave
-} -returnCodes error -result {wrong # args: should be "slave bgerror ?cmdPrefix?"}
-test interp-36.4 {SlaveBgerror syntax} -setup {
-    interp create slave
+    interp delete child
+} -returnCodes error -result {wrong # args: should be "child bgerror ?cmdPrefix?"}
+test interp-36.4 {ChildBgerror syntax} -setup {
+    interp create child
 } -body {
-    slave bgerror \{
+    child bgerror \{
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -result {cmdPrefix must be list of length >= 1}
-test interp-36.5 {SlaveBgerror syntax} -setup {
-    interp create slave
+test interp-36.5 {ChildBgerror syntax} -setup {
+    interp create child
 } -body {
-    slave bgerror {}
+    child bgerror {}
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -result {cmdPrefix must be list of length >= 1}
-test interp-36.6 {SlaveBgerror returns handler} -setup {
-    interp create slave
+test interp-36.6 {ChildBgerror returns handler} -setup {
+    interp create child
 } -body {
-    slave bgerror {foo bar soom}
+    child bgerror {foo bar soom}
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {foo bar soom}
-test interp-36.7 {SlaveBgerror sets error handler of slave [1999035]} -setup {
-    interp create slave
-    slave alias handler handler
-    slave bgerror handler
+test interp-36.7 {ChildBgerror sets error handler of child [1999035]} -setup {
+    interp create child
+    child alias handler handler
+    child bgerror handler
     variable result {untouched}
     proc handler {args} {
         variable result
         set result [lindex $args 0]
     }
 } -body {
-    slave eval {
+    child eval {
         variable done {}
         after 0 error foo
         after 10 [list ::set [namespace which -variable done] {}]
@@ -3606,7 +3606,7 @@ test interp-36.7 {SlaveBgerror sets error handler of slave [1999035]} -setup {
 } -cleanup {
     variable result {}
     unset -nocomplain result
-    interp delete slave
+    interp delete child
 } -result foo
 
 test interp-37.1 {safe interps and min() and max(): Bug 2895741} -setup {
@@ -3615,8 +3615,8 @@ test interp-37.1 {safe interps and min() and max(): Bug 2895741} -setup {
     set result {}
 } -body {
     interp create {a b} -safe
-    lappend result [interp eval a {expr min(5,2,3)*max(7,13,11)}]
-    lappend result [interp eval {a b} {expr min(5,2,3)*max(7,13,11)}]
+    lappend result [interp eval a {expr {min(5,2,3)*max(7,13,11)}}]
+    lappend result [interp eval {a b} {expr {min(5,2,3)*max(7,13,11)}}]
 } -cleanup {
     unset -nocomplain result
     interp delete a
@@ -3667,7 +3667,7 @@ test interp-38.8 {interp debug basic setup} -body {
 \f
 # cleanup
 unset -nocomplain hidden_cmds
-foreach i [interp slaves] {
+foreach i [interp children] {
     interp delete $i
 }
 ::tcltest::cleanupTests
index 1b23534..8bf3303 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
-}
-
 namespace eval ::tcl::test::io {
-    namespace import ::tcltest::*
+
+    if {"::tcltest" ni [namespace children]} {
+       package require tcltest 2.5
+       namespace import -force ::tcltest::*
+    }
 
     variable umaskValue
     variable path
@@ -38,12 +38,16 @@ namespace eval ::tcl::test::io {
 
 testConstraint testbytestring [llength [info commands testbytestring]]
 testConstraint testchannel      [llength [info commands testchannel]]
-testConstraint openpipe         1
 testConstraint testfevent       [llength [info commands testfevent]]
 testConstraint testchannelevent [llength [info commands testchannelevent]]
 testConstraint testmainthread   [llength [info commands testmainthread]]
 testConstraint testobj         [llength [info commands testobj]]
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+testConstraint testservicemode  [llength [info commands testservicemode]]
+# Some things fail under Windows in Continuous Integration systems for subtle
+# reasons such as CI often running with elevated privileges in a container.
+testConstraint notWinCI [expr {
+    $::tcl_platform(platform) ne "windows" || ![info exists ::env(CI)]}]
+testConstraint notOSX [expr {$::tcl_platform(os) ne "Darwin"}]
 
 # You need a *very* special environment to do some tests.  In
 # particular, many file systems do not support large-files...
@@ -73,7 +77,7 @@ set path(cat) [makeFile {
     if {$argv != ""} {
        set f [open [lindex $argv 0]]
     }
-    fconfigure $f -encoding binary -translation lf -blocking 0 -eofchar \x1a
+    fconfigure $f -encoding binary -translation lf -blocking 0 -eofchar \x1A
     fconfigure stdout -encoding binary -translation lf -buffering none
     fileevent $f readable "foo $f"
     proc foo {f} {
@@ -123,10 +127,10 @@ test io-1.8 {Tcl_WriteChars: WriteChars} {
     # applied to tcl will cause tcl, more specifically WriteChars, to
     # go into an infinite loop.
 
-    set f [open $path(test2) w] 
-    fconfigure      $f -encoding iso2022-jp 
-    puts -nonewline $f [format %s%c [string repeat " " 4] 12399] 
-    close           $f 
+    set f [open $path(test2) w]
+    fconfigure      $f -encoding iso2022-jp
+    puts -nonewline $f [format %s%c [string repeat " " 4] 12399]
+    close           $f
     contents $path(test2)
 } "    \x1b\$B\$O\x1b(B"
 
@@ -192,7 +196,7 @@ test io-1.9 {Tcl_WriteChars: WriteChars} {
 
 test io-2.1 {WriteBytes} {
     # loop until all bytes are written
-    
+
     set f [open $path(test1) w]
     fconfigure $f  -encoding binary -buffersize 16 -translation crlf
     puts $f "abcdefghijklmnopqrstuvwxyz"
@@ -214,7 +218,7 @@ test io-2.3 {WriteBytes: flush on line} {
     # Tcl "line" buffering has weird behavior: if current buffer contains
     # a \n, entire buffer gets flushed.  Logical behavior would be to flush
     # only up to the \n.
-    
+
     set f [open $path(test1) w]
     fconfigure $f -encoding binary -buffering line -translation crlf
     puts -nonewline $f "\n12"
@@ -234,7 +238,7 @@ test io-2.4 {WriteBytes: reset sawLF after each buffer} {
 
 test io-3.1 {WriteChars: compatibility with WriteBytes} {
     # loop until all bytes are written
-    
+
     set f [open $path(test1) w]
     fconfigure $f -encoding ascii -buffersize 16 -translation crlf
     puts $f "abcdefghijklmnopqrstuvwxyz"
@@ -256,7 +260,7 @@ test io-3.3 {WriteChars: compatibility with WriteBytes: flush on line} {
     # Tcl "line" buffering has weird behavior: if current buffer contains
     # a \n, entire buffer gets flushed.  Logical behavior would be to flush
     # only up to the \n.
-    
+
     set f [open $path(test1) w]
     fconfigure $f -encoding ascii -buffering line -translation crlf
     puts -nonewline $f "\n12"
@@ -268,7 +272,7 @@ test io-3.4 {WriteChars: loop over stage buffer} {
     # stage buffer maps to more than can be queued at once.
 
     set f [open $path(test1) w]
-    fconfigure $f -encoding jis0208 -buffersize 16 
+    fconfigure $f -encoding jis0208 -buffersize 16
     puts -nonewline $f "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
     set x [list [contents $path(test1)]]
     close $f
@@ -280,7 +284,7 @@ test io-3.5 {WriteChars: saved != 0} {
     # requested buffersize.
 
     set f [open $path(test1) w]
-    fconfigure $f -encoding jis0208 -buffersize 17 
+    fconfigure $f -encoding jis0208 -buffersize 17
     puts -nonewline $f "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
     set x [list [contents $path(test1)]]
     close $f
@@ -311,7 +315,7 @@ test io-3.7 {WriteChars: (bufPtr->nextAdded > bufPtr->length)} {
     # of the next channel buffer.
 
     set f [open $path(test1) w]
-    fconfigure $f -encoding jis0208 -buffersize 17 
+    fconfigure $f -encoding jis0208 -buffersize 17
     puts -nonewline $f "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"
     set x [list [contents $path(test1)]]
     close $f
@@ -381,7 +385,7 @@ test io-4.5 {TranslateOutputEOL: crlf} {
 
 test io-5.1 {CheckFlush: not full} {
     set f [open $path(test1) w]
-    fconfigure $f 
+    fconfigure $f
     puts -nonewline $f "12345678901234567890"
     set x [list [contents $path(test1)]]
     close $f
@@ -470,7 +474,7 @@ set a "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
 append a $a
 append a $a
 test io-6.6 {Tcl_GetsObj: loop test} {
-    # if (dst >= dstEnd) 
+    # if (dst >= dstEnd)
 
     set f [open $path(test1) w]
     puts $f $a
@@ -481,7 +485,7 @@ test io-6.6 {Tcl_GetsObj: loop test} {
     close $f
     set x
 } [list 256 $a]
-test io-6.7 {Tcl_GetsObj: error in input} {stdio openpipe} {
+test io-6.7 {Tcl_GetsObj: error in input} stdio {
     # if (FilterInputBytes(chanPtr, &gs) != 0)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -495,10 +499,10 @@ test io-6.7 {Tcl_GetsObj: error in input} {stdio openpipe} {
 } {-1}
 test io-6.8 {Tcl_GetsObj: remember if EOF is seen} {
     set f [open $path(test1) w]
-    puts $f "abcdef\x1aghijk\nwombat"
+    puts $f "abcdef\x1Aghijk\nwombat"
     close $f
     set f [open $path(test1)]
-    fconfigure $f -eofchar \x1a
+    fconfigure $f -eofchar \x1A
     set x [list [gets $f line] $line [gets $f line] $line]
     close $f
     set x
@@ -508,7 +512,7 @@ test io-6.9 {Tcl_GetsObj: remember if EOF is seen} {
     puts $f "abcdefghijk\nwom\u001abat"
     close $f
     set f [open $path(test1)]
-    fconfigure $f -eofchar \x1a
+    fconfigure $f -eofchar \x1A
     set x [list [gets $f line] $line [gets $f line] $line]
     close $f
     set x
@@ -741,7 +745,7 @@ test io-6.30 {Tcl_GetsObj: crlf mode: buffer exhausted} {testchannel} {
     close $f
     set x
 } [list 15 "123456789012345" 15]
-test io-6.31 {Tcl_GetsObj: crlf mode: buffer exhausted, blocked} {stdio testchannel openpipe fileevent} {
+test io-6.31 {Tcl_GetsObj: crlf mode: buffer exhausted, blocked} {stdio testchannel fileevent} {
     # (FilterInputBytes() != 0)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -769,7 +773,7 @@ test io-6.32 {Tcl_GetsObj: crlf mode: buffer exhausted, more data} {testchannel}
 } [list 15 "123456789012345" 17 3]
 test io-6.33 {Tcl_GetsObj: crlf mode: buffer exhausted, at eof} {
     # eol still equals dstEnd
-    
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456789012345\r"
@@ -781,8 +785,8 @@ test io-6.33 {Tcl_GetsObj: crlf mode: buffer exhausted, at eof} {
     set x
 } [list 16 "123456789012345\r" 1]
 test io-6.34 {Tcl_GetsObj: crlf mode: buffer exhausted, not followed by \n} {
-    # not (*eol == '\n') 
-    
+    # not (*eol == '\n')
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456789012345\rabcd\r\nefg"
@@ -880,7 +884,7 @@ test io-6.42 {Tcl_GetsObj: auto mode: several chars} {
     close $f
     set x
 } [list 4 "abcd" 4 "efgh" 4 "ijkl" 4 "mnop" -1 ""]
-test io-6.43 {Tcl_GetsObj: input saw cr} {stdio testchannel openpipe fileevent} {
+test io-6.43 {Tcl_GetsObj: input saw cr} {stdio testchannel fileevent} {
     # if (chanPtr->flags & INPUT_SAW_CR)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -889,16 +893,16 @@ test io-6.43 {Tcl_GetsObj: input saw cr} {stdio testchannel openpipe fileevent}
     fconfigure $f -buffersize 16
     set x [list [gets $f]]
     fconfigure $f -blocking 0
-    lappend x [gets $f line] $line [testchannel queuedcr $f] 
+    lappend x [gets $f line] $line [testchannel queuedcr $f]
     fconfigure $f -blocking 1
-    puts -nonewline $f "\nabcd\refg\x1a"
+    puts -nonewline $f "\nabcd\refg\x1A"
     lappend x [gets $f line] $line [testchannel queuedcr $f]
     lappend x [gets $f line] $line
     close $f
     set x
 } [list "bbbbbbbbbbbbbbb" 15 "123456789abcdef" 1 4 "abcd" 0 3 "efg"]
-test io-6.44 {Tcl_GetsObj: input saw cr, not followed by cr} {stdio testchannel openpipe fileevent} {
-    # not (*eol == '\n') 
+test io-6.44 {Tcl_GetsObj: input saw cr, not followed by cr} {stdio testchannel fileevent} {
+    # not (*eol == '\n')
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
     fconfigure $f -translation {auto lf} -buffering none
@@ -906,15 +910,15 @@ test io-6.44 {Tcl_GetsObj: input saw cr, not followed by cr} {stdio testchannel
     fconfigure $f -buffersize 16
     set x [list [gets $f]]
     fconfigure $f -blocking 0
-    lappend x [gets $f line] $line [testchannel queuedcr $f] 
+    lappend x [gets $f line] $line [testchannel queuedcr $f]
     fconfigure $f -blocking 1
-    puts -nonewline $f "abcd\refg\x1a"
+    puts -nonewline $f "abcd\refg\x1A"
     lappend x [gets $f line] $line [testchannel queuedcr $f]
     lappend x [gets $f line] $line
     close $f
     set x
 } [list "bbbbbbbbbbbbbbb" 15 "123456789abcdef" 1 4 "abcd" 0 3 "efg"]
-test io-6.45 {Tcl_GetsObj: input saw cr, skip right number of bytes} {stdio testchannel openpipe fileevent} {
+test io-6.45 {Tcl_GetsObj: input saw cr, skip right number of bytes} {stdio testchannel fileevent} {
     # Tcl_ExternalToUtf()
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -931,7 +935,7 @@ test io-6.45 {Tcl_GetsObj: input saw cr, skip right number of bytes} {stdio test
     close $f
     set x
 } [list 15 "123456789abcdef" 1 4 "abcd" 0]
-test io-6.46 {Tcl_GetsObj: input saw cr, followed by just \n should give eof} {stdio testchannel openpipe fileevent} {
+test io-6.46 {Tcl_GetsObj: input saw cr, followed by just \n should give eof} {stdio testchannel fileevent} {
     # memmove()
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -942,7 +946,7 @@ test io-6.46 {Tcl_GetsObj: input saw cr, followed by just \n should give eof} {s
     fconfigure $f -blocking 0
     set x [list [gets $f line] $line [testchannel queuedcr $f]]
     fconfigure $f -blocking 1
-    puts -nonewline $f "\n\x1a"
+    puts -nonewline $f "\n\x1A"
     lappend x [gets $f line] $line [testchannel queuedcr $f]
     close $f
     set x
@@ -959,10 +963,10 @@ test io-6.47 {Tcl_GetsObj: auto mode: \r at end of buffer, peek for \n} {testcha
     set x [list [gets $f] [testchannel inputbuffered $f]]
     close $f
     set x
-} [list "123456789012345" 15]    
+} [list "123456789012345" 15]
 test io-6.48 {Tcl_GetsObj: auto mode: \r at end of buffer, no more avail} {testchannel} {
     # PeekAhead() did not get any, so (eol >= dstEnd)
-    
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456789012345\r"
@@ -975,7 +979,7 @@ test io-6.48 {Tcl_GetsObj: auto mode: \r at end of buffer, no more avail} {testc
 } [list "123456789012345" 1]
 test io-6.49 {Tcl_GetsObj: auto mode: \r followed by \n} {testchannel} {
     # if (*eol == '\n') {skip++}
-    
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456\r\n78901"
@@ -986,8 +990,8 @@ test io-6.49 {Tcl_GetsObj: auto mode: \r followed by \n} {testchannel} {
     set x
 } [list "123456" 0 8 "78901"]
 test io-6.50 {Tcl_GetsObj: auto mode: \r not followed by \n} {testchannel} {
-    # not (*eol == '\n') 
-    
+    # not (*eol == '\n')
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456\r78901"
@@ -999,7 +1003,7 @@ test io-6.50 {Tcl_GetsObj: auto mode: \r not followed by \n} {testchannel} {
 } [list "123456" 0 7 "78901"]
 test io-6.51 {Tcl_GetsObj: auto mode: \n} {
     # else if (*eol == '\n') {goto gotoeol;}
-    
+
     set f [open $path(test1) w]
     fconfigure $f -translation lf
     puts -nonewline $f "123456\n78901"
@@ -1014,10 +1018,10 @@ test io-6.52 {Tcl_GetsObj: saw EOF character} {testchannel} {
 
     set f [open $path(test1) w]
     fconfigure $f -translation lf
-    puts -nonewline $f "123456\x1ak9012345\r"
+    puts -nonewline $f "123456\x1Ak9012345\r"
     close $f
     set f [open $path(test1)]
-    fconfigure $f -eofchar \x1a
+    fconfigure $f -eofchar \x1A
     set x [list [gets $f] [testchannel queuedcr $f] [tell $f] [gets $f]]
     close $f
     set x
@@ -1056,7 +1060,7 @@ test io-6.55 {Tcl_GetsObj: overconverted} {
     close $f
     set x
 } [list 8 "there\u4e00ok" 11 "\u4e01more bytes" 4 "here"]
-test io-6.56 {Tcl_GetsObj: incomplete lines should disable file events} {stdio openpipe fileevent} {
+test io-6.56 {Tcl_GetsObj: incomplete lines should disable file events} {stdio fileevent} {
     update
     set f [open "|[list [interpreter] $path(cat)]" w+]
     fconfigure $f -buffering none
@@ -1092,7 +1096,7 @@ test io-7.1 {FilterInputBytes: split up character at end of buffer} {
 } "1234567890123\uff10\uff11\uff12\uff13\uff14"
 test io-7.2 {FilterInputBytes: split up character in middle of buffer} {
     # (bufPtr->nextAdded < bufPtr->bufLength)
-    
+
     set f [open $path(test1) w]
     fconfigure $f -encoding binary
     puts -nonewline $f "1234567890\n123\x82\x4f\x82\x50\x82"
@@ -1116,7 +1120,7 @@ test io-7.3 {FilterInputBytes: split up character at EOF} {testchannel} {
     close $f
     set x
 } [list 15 "1234567890123\uff10\uff11" 18 0 1 -1 ""]
-test io-7.4 {FilterInputBytes: recover from split up character} {stdio openpipe fileevent} {
+test io-7.4 {FilterInputBytes: recover from split up character} {stdio fileevent} {
     set f [open "|[list [interpreter] $path(cat)]" w+]
     fconfigure $f -encoding binary -buffering none
     puts -nonewline $f "1234567890123\x82\x4f\x82\x50\x82"
@@ -1151,7 +1155,7 @@ test io-8.1 {PeekAhead: only go to device if no more cached data} {testchannel}
     close $f
     set x
 } "7"
-test io-8.2 {PeekAhead: only go to device if no more cached data} {stdio testchannel openpipe fileevent} {
+test io-8.2 {PeekAhead: only go to device if no more cached data} {stdio testchannel fileevent} {
     # not (bufPtr->nextPtr == NULL)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -1171,7 +1175,7 @@ test io-8.2 {PeekAhead: only go to device if no more cached data} {stdio testcha
     close $f
     set x
 } [list -1 "" 42 15 "123456789012345" 25]
-test io-8.3 {PeekAhead: no cached data available} {stdio testchannel openpipe fileevent} {
+test io-8.3 {PeekAhead: no cached data available} {stdio testchannel fileevent} {
     # (bytesLeft == 0)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -1201,10 +1205,10 @@ test io-8.4 {PeekAhead: cached data available in this buffer} {
 
     set x [gets $f]
     close $f
-    set x    
+    set x
 } $a
 unset a
-test io-8.5 {PeekAhead: don't peek if last read was short} {stdio testchannel openpipe fileevent} {
+test io-8.5 {PeekAhead: don't peek if last read was short} {stdio testchannel fileevent} {
     # (bufPtr->nextAdded < bufPtr->length)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -1216,8 +1220,8 @@ test io-8.5 {PeekAhead: don't peek if last read was short} {stdio testchannel op
     close $f
     set x
 } {15 abcdefghijklmno 1}
-test io-8.6 {PeekAhead: change to non-blocking mode} {stdio testchannel openpipe fileevent} {
-    # ((chanPtr->flags & CHANNEL_NONBLOCKING) == 0) 
+test io-8.6 {PeekAhead: change to non-blocking mode} {stdio testchannel fileevent} {
+    # ((chanPtr->flags & CHANNEL_NONBLOCKING) == 0)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
     fconfigure $f -translation {auto binary} -buffersize 16
@@ -1228,7 +1232,7 @@ test io-8.6 {PeekAhead: change to non-blocking mode} {stdio testchannel openpipe
     close $f
     set x
 } {15 abcdefghijklmno 1}
-test io-8.7 {PeekAhead: cleanup} {stdio testchannel openpipe fileevent} {
+test io-8.7 {PeekAhead: cleanup} {stdio testchannel fileevent} {
     # Make sure bytes are removed from buffer.
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -1236,7 +1240,7 @@ test io-8.7 {PeekAhead: cleanup} {stdio testchannel openpipe fileevent} {
     puts -nonewline $f "abcdefghijklmno\r"
     # here
     set x [list [gets $f line] $line [testchannel queuedcr $f]]
-    puts -nonewline $f "\x1a"
+    puts -nonewline $f "\x1A"
     lappend x [gets $f line] $line
     close $f
     set x
@@ -1393,7 +1397,7 @@ test io-12.3 {ReadChars: allocate more space} {
     close $f
     set x
 } {abcdefghijklmnopqrstuvwxyz}
-test io-12.4 {ReadChars: split-up char} {stdio testchannel openpipe fileevent} {
+test io-12.4 {ReadChars: split-up char} {stdio testchannel fileevent} {
     # (srcRead == 0)
 
     set f [open "|[list [interpreter] $path(cat)]" w+]
@@ -1418,7 +1422,7 @@ test io-12.4 {ReadChars: split-up char} {stdio testchannel openpipe fileevent} {
     close $f
     set x
 } [list "123456789012345" 1 "\u672c" 0]
-test io-12.5 {ReadChars: fileevents on partial characters} {stdio openpipe fileevent} {
+test io-12.5 {ReadChars: fileevents on partial characters} {stdio fileevent} {
     set path(test1) [makeFile {
        fconfigure stdout -encoding binary -buffering none
        gets stdin; puts -nonewline "\xe7"
@@ -1574,7 +1578,7 @@ test io-13.2 {TranslateInputEOL: crlf mode} {
     set x
 } "abcd\ndef\n"
 test io-13.3 {TranslateInputEOL: crlf mode: naked cr} {
-    # (src >= srcMax) 
+    # (src >= srcMax)
 
     set f [open $path(test1) w]
     fconfigure $f -translation lf
@@ -1587,7 +1591,7 @@ test io-13.3 {TranslateInputEOL: crlf mode: naked cr} {
     set x
 } "abcd\ndef\r"
 test io-13.4 {TranslateInputEOL: crlf mode: cr followed by not \n} {
-    # (src >= srcMax) 
+    # (src >= srcMax)
 
     set f [open $path(test1) w]
     fconfigure $f -translation lf
@@ -1600,7 +1604,7 @@ test io-13.4 {TranslateInputEOL: crlf mode: cr followed by not \n} {
     set x
 } "abcd\ndef\rfgh"
 test io-13.5 {TranslateInputEOL: crlf mode: naked lf} {
-    # (src >= srcMax) 
+    # (src >= srcMax)
 
     set f [open $path(test1) w]
     fconfigure $f -translation lf
@@ -1612,7 +1616,7 @@ test io-13.5 {TranslateInputEOL: crlf mode: naked lf} {
     close $f
     set x
 } "abcd\ndef\nfgh"
-test io-13.6 {TranslateInputEOL: auto mode: saw cr in last segment} {stdio testchannel openpipe fileevent} {
+test io-13.6 {TranslateInputEOL: auto mode: saw cr in last segment} {stdio testchannel fileevent} {
     # (chanPtr->flags & INPUT_SAW_CR)
     # This test may fail on slower machines.
 
@@ -1638,7 +1642,7 @@ test io-13.6 {TranslateInputEOL: auto mode: saw cr in last segment} {stdio testc
     close $f
     set x
 } [list "abcdefghj\n" 1 "01234" 0]
-test io-13.7 {TranslateInputEOL: auto mode: naked \r} {testchannel openpipe} {
+test io-13.7 {TranslateInputEOL: auto mode: naked \r} testchannel {
     # (src >= srcMax)
 
     set f [open $path(test1) w]
@@ -1715,7 +1719,7 @@ test io-13.9 {TranslateInputEOL: auto mode: \r followed by not \n} {
     set x
 } "abcd\ndef"
 test io-13.10 {TranslateInputEOL: auto mode: \n} {
-    # not (*src == '\r') 
+    # not (*src == '\r')
 
     set f [open $path(test1) w]
     fconfigure $f -translation lf
@@ -1783,7 +1787,7 @@ test io-14.2 {Tcl_SetStdChannel and Tcl_GetStdChannel} {
     set l
 } {line line none}
 set path(test3) [makeFile {} test3]
-test io-14.3 {Tcl_SetStdChannel & Tcl_GetStdChannel} {exec openpipe} {
+test io-14.3 {Tcl_SetStdChannel & Tcl_GetStdChannel} exec {
     set f [open $path(test1) w]
     puts -nonewline $f {
        close stdin
@@ -1873,7 +1877,7 @@ test io-14.7 {Tcl_GetChannel: stdio name translation} {
     set result
 } {{} {} {can not find channel named "stderr"}}
 set path(script) [makeFile {} script]
-test io-14.8 {reuse of stdio special channels} {stdio openpipe} {
+test io-14.8 {reuse of stdio special channels} stdio {
     file delete $path(script)
     file delete $path(test1)
     set f [open $path(script) w]
@@ -1895,7 +1899,7 @@ test io-14.8 {reuse of stdio special channels} {stdio openpipe} {
     close $f
     set c
 } hello
-test io-14.9 {reuse of stdio special channels} {stdio openpipe fileevent} {
+test io-14.9 {reuse of stdio special channels} {stdio fileevent} {
     file delete $path(script)
     file delete $path(test1)
     set f [open $path(script) w]
@@ -2064,13 +2068,13 @@ test io-20.1 {Tcl_CreateChannel: initial settings} {
     encoding system $old
        close $a
     set x
-} {ascii}    
+} {ascii}
 test io-20.2 {Tcl_CreateChannel: initial settings} {win} {
     set f [open $path(test1) w+]
     set x [list [fconfigure $f -eofchar] [fconfigure $f -translation]]
     close $f
     set x
-} [list [list \x1a ""] {auto crlf}]
+} [list [list \x1A ""] {auto crlf}]
 test io-20.3 {Tcl_CreateChannel: initial settings} {unix} {
     set f [open $path(test1) w+]
     set x [list [fconfigure $f -eofchar] [fconfigure $f -translation]]
@@ -2078,7 +2082,7 @@ test io-20.3 {Tcl_CreateChannel: initial settings} {unix} {
     set x
 } {{{} {}} {auto lf}}
 set path(stdout) [makeFile {} stdout]
-test io-20.5 {Tcl_CreateChannel: install channel in empty slot} {stdio openpipe} {
+test io-20.5 {Tcl_CreateChannel: install channel in empty slot} stdio {
     set f [open $path(script) w]
     puts -nonewline $f {
        close stdout
@@ -2152,14 +2156,14 @@ test io-25.2 {Tcl_GetChannelHandle, output} {testchannel} {
     set l
 } {6 6 0 6}
 
-test io-26.1 {Tcl_GetChannelInstanceData} {stdio openpipe} {
+test io-26.1 {Tcl_GetChannelInstanceData} stdio {
     # "pid" command uses Tcl_GetChannelInstanceData
     # Don't care what pid is (but must be a number), just want to exercise it.
 
     set f [open "|[list [interpreter] << exit]"]
     expr [pid $f]
     close $f
-} {}    
+} {}
 
 # Test flushing. The functions tested here are FlushChannel.
 
@@ -2229,7 +2233,7 @@ test io-27.5 {FlushChannel, implicit flush when buffer fills and on close} \
 set path(pipe)   [makeFile {} pipe]
 set path(output) [makeFile {} output]
 test io-27.6 {FlushChannel, async flushing, async close} \
-       {stdio asyncPipeClose openpipe knownMsvcBug} {
+       {stdio asyncPipeClose notWinCI} {
     # This test may fail on old Unix systems (seen on IRIX64 6.5) with
     # obsolete gettimeofday() calls.  See Tcl Bugs 3530533, 1942197.
     file delete $path(pipe)
@@ -2298,7 +2302,7 @@ test io-28.2 {CloseChannel called when all references are dropped} {
     set l
 } abcdef
 test io-28.3 {CloseChannel, not called before output queue is empty} \
-       {stdio asyncPipeClose nonPortable openpipe} {
+       {stdio asyncPipeClose nonPortable} {
     file delete $path(pipe)
     file delete $path(output)
     set f [open $path(pipe) w]
@@ -2355,7 +2359,7 @@ test io-28.4 {Tcl_Close} {testchannel} {
                $consoleFileNames]
     string compare $l $x
 } 0
-test io-28.5 {Tcl_Close vs standard handles} {stdio unix testchannel openpipe} {
+test io-28.5 {Tcl_Close vs standard handles} {stdio unix testchannel} {
     file delete $path(script)
     set f [open $path(script) w]
     puts $f {
@@ -2494,7 +2498,7 @@ test io-29.11 {Tcl_WriteChars, no newline, implicit flush} {
     close $f2
     file size $path(test1)
 } 377
-test io-29.12 {Tcl_WriteChars on a pipe} {stdio openpipe} {
+test io-29.12 {Tcl_WriteChars on a pipe} stdio {
     file delete $path(test1)
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
@@ -2519,7 +2523,7 @@ test io-29.12 {Tcl_WriteChars on a pipe} {stdio openpipe} {
     close $f2
     set y
 } ok
-test io-29.13 {Tcl_WriteChars to a pipe, line buffered} {stdio openpipe} {
+test io-29.13 {Tcl_WriteChars to a pipe, line buffered} stdio {
     file delete $path(test1)
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
@@ -2570,7 +2574,7 @@ test io-29.15 {Tcl_Flush, channel not open for writing} {
     string compare $x \
        [list 1 "channel \"$fd\" wasn't opened for writing"]
 } 0
-test io-29.16 {Tcl_Flush on pipe opened only for reading} {stdio openpipe} {
+test io-29.16 {Tcl_Flush on pipe opened only for reading} stdio {
     set fd [open "|[list [interpreter] cat longfile]" r]
     set x [list [catch {flush $fd} msg] $msg]
     catch {close $fd}
@@ -2644,7 +2648,7 @@ test io-29.20 {Implicit flush when buffer is full} {
     lappend z [file size $path(test1)]
     set z
 } {4096 12288 12600}
-test io-29.21 {Tcl_Flush to pipe} {stdio openpipe} {
+test io-29.21 {Tcl_Flush to pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {set x [read stdin 6]}
@@ -2658,7 +2662,7 @@ test io-29.21 {Tcl_Flush to pipe} {stdio openpipe} {
     catch {close $f1}
     set x
 } "read 6 characters"
-test io-29.22 {Tcl_Flush called at other end of pipe} {stdio openpipe} {
+test io-29.22 {Tcl_Flush called at other end of pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {
@@ -2681,7 +2685,7 @@ test io-29.22 {Tcl_Flush called at other end of pipe} {stdio openpipe} {
     close $f1
     set x
 } {hello hello bye}
-test io-29.23 {Tcl_Flush and line buffering at end of pipe} {stdio openpipe} {
+test io-29.23 {Tcl_Flush and line buffering at end of pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {
@@ -2716,7 +2720,7 @@ test io-29.24 {Tcl_WriteChars and Tcl_Flush move end of file} {
     close $f
     set x
 } "{} {Line 1\nLine 2}"
-test io-29.25 {Implicit flush with Tcl_Flush to command pipelines} {stdio openpipe fileevent} {
+test io-29.25 {Implicit flush with Tcl_Flush to command pipelines} {stdio fileevent} {
     file delete $path(test3)
     set f [open "|[list [interpreter] $path(cat) | [interpreter] $path(cat) > $path(test3)]" w]
     puts $f "Line 1"
@@ -2728,7 +2732,7 @@ test io-29.25 {Implicit flush with Tcl_Flush to command pipelines} {stdio openpi
     close $f
     set x
 } "Line 1\nLine 2\n"
-test io-29.26 {Tcl_Flush, Tcl_Write on bidirectional pipelines} {stdio unixExecs openpipe} {
+test io-29.26 {Tcl_Flush, Tcl_Write on bidirectional pipelines} {stdio unixExecs} {
     set f [open "|[list cat -u]" r+]
     puts $f "Line1"
     flush $f
@@ -2736,7 +2740,7 @@ test io-29.26 {Tcl_Flush, Tcl_Write on bidirectional pipelines} {stdio unixExecs
     close $f
     set x
 } {Line1}
-test io-29.27 {Tcl_Flush on closed pipeline} {stdio openpipe} {
+test io-29.27 {Tcl_Flush on closed pipeline} stdio {
     file delete $path(pipe)
     set f [open $path(pipe) w]
     puts $f {exit}
@@ -2790,7 +2794,7 @@ test io-29.30 {Tcl_WriteChars, crlf mode} {
     close $f
     file size $path(test1)
 } 25
-test io-29.31 {Tcl_WriteChars, background flush} {stdio openpipe} {
+test io-29.31 {Tcl_WriteChars, background flush} stdio {
     # This test may fail on old Unix systems (seen on IRIX64 6.5) with
     # obsolete gettimeofday() calls.  See Tcl Bugs 3530533, 1942197.
     file delete $path(pipe)
@@ -2827,13 +2831,13 @@ test io-29.31 {Tcl_WriteChars, background flush} {stdio openpipe} {
        set result ok
     }
     # allow a little time for the background process to close.
-    # otherwise, the following test fails on the [file delete $path(output)
+    # otherwise, the following test fails on the [file delete $path(output)]
     # on Windows because a process still has the file open.
     after 100 set v 1; vwait v
     set result
 } ok
 test io-29.32 {Tcl_WriteChars, background flush to slow reader} \
-       {stdio asyncPipeClose openpipe knownMsvcBug} {
+       {stdio asyncPipeClose notWinCI} {
     # This test may fail on old Unix systems (seen on IRIX64 6.5) with
     # obsolete gettimeofday() calls.  See Tcl Bugs 3530533, 1942197.
     file delete $path(pipe)
@@ -3057,7 +3061,7 @@ test io-30.6 {Tcl_Write cr, Tcl_Read crlf} {
     fconfigure $f -translation crlf
     set x [read $f]
     close $f
-    set x 
+    set x
 } "hello\rthere\rand\rhere\r"
 test io-30.7 {Tcl_Write crlf, Tcl_Read crlf} {
     file delete $path(test1)
@@ -3195,10 +3199,10 @@ test io-30.16 {Tcl_Write ^Z at end, Tcl_Read auto} {
     file delete $path(test1)
     set f [open $path(test1) w]
     fconfigure $f -translation lf
-    puts -nonewline $f hello\nthere\nand\rhere\n\x1a
+    puts -nonewline $f hello\nthere\nand\rhere\n\x1A
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set c [read $f]
     close $f
     set c
@@ -3210,11 +3214,11 @@ here
 test io-30.17 {Tcl_Write, implicit ^Z at end, Tcl_Read auto} {win} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -eofchar \x1a -translation lf
+    fconfigure $f -eofchar \x1A -translation lf
     puts $f hello\nthere\nand\rhere
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set c [read $f]
     close $f
     set c
@@ -3231,7 +3235,7 @@ test io-30.18 {Tcl_Write, ^Z in middle, Tcl_Read auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3251,7 +3255,7 @@ test io-30.19 {Tcl_Write, ^Z no newline in middle, Tcl_Read auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3284,7 +3288,7 @@ test io-30.20 {Tcl_Write, ^Z in middle ignored, Tcl_Read lf} {
     lappend l [eof $f]
     close $f
     set l
-} "abc def 0 \x1aghi 0 qrs 0 {} 1"
+} "abc def 0 \x1Aghi 0 qrs 0 {} 1"
 test io-30.21 {Tcl_Write, ^Z in middle ignored, Tcl_Read cr} {
     file delete $path(test1)
     set f [open $path(test1) w]
@@ -3296,7 +3300,7 @@ test io-30.21 {Tcl_Write, ^Z in middle ignored, Tcl_Read cr} {
     fconfigure $f -translation cr -eofchar {}
     set l ""
     set x [gets $f]
-    lappend l [string compare $x "abc\ndef\n\x1aghi\nqrs\n"]
+    lappend l [string compare $x "abc\ndef\n\x1Aghi\nqrs\n"]
     lappend l [eof $f]
     lappend l [gets $f]
     lappend l [eof $f]
@@ -3314,7 +3318,7 @@ test io-30.22 {Tcl_Write, ^Z in middle ignored, Tcl_Read crlf} {
     fconfigure $f -translation crlf -eofchar {}
     set l ""
     set x [gets $f]
-    lappend l [string compare $x "abc\ndef\n\x1aghi\nqrs\n"]
+    lappend l [string compare $x "abc\ndef\n\x1Aghi\nqrs\n"]
     lappend l [eof $f]
     lappend l [gets $f]
     lappend l [eof $f]
@@ -3329,7 +3333,7 @@ test io-30.23 {Tcl_Write lf, ^Z in middle, Tcl_Read auto} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3343,7 +3347,7 @@ test io-30.24 {Tcl_Write lf, ^Z in middle, Tcl_Read lf} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3357,7 +3361,7 @@ test io-30.25 {Tcl_Write cr, ^Z in middle, Tcl_Read auto} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3371,7 +3375,7 @@ test io-30.26 {Tcl_Write cr, ^Z in middle, Tcl_Read cr} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3385,7 +3389,7 @@ test io-30.27 {Tcl_Write crlf, ^Z in middle, Tcl_Read auto} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3399,7 +3403,7 @@ test io-30.28 {Tcl_Write crlf, ^Z in middle, Tcl_Read crlf} {
     puts $f $c
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set c [string length [read $f]]
     set e [eof $f]
     close $f
@@ -3732,7 +3736,7 @@ test io-31.18 {Tcl_Write ^Z at end, Tcl_Gets auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3747,11 +3751,11 @@ test io-31.18 {Tcl_Write ^Z at end, Tcl_Gets auto} {
 test io-31.19 {Tcl_Write, implicit ^Z at end, Tcl_Gets auto} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -eofchar \x1a -translation lf
+    fconfigure $f -eofchar \x1A -translation lf
     puts $f hello\nthere\nand\rhere
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3771,7 +3775,7 @@ test io-31.20 {Tcl_Write, ^Z in middle, Tcl_Gets auto, eofChar} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a
+    fconfigure $f -eofchar \x1A
     fconfigure $f -translation auto
     set l ""
     lappend l [gets $f]
@@ -3790,7 +3794,7 @@ test io-31.21 {Tcl_Write, no newline ^Z in middle, Tcl_Gets auto, eofChar} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3821,7 +3825,7 @@ test io-31.22 {Tcl_Write, ^Z in middle ignored, Tcl_Gets lf} {
     lappend l [eof $f]
     close $f
     set l
-} "abc def 0 \x1aqrs 0 tuv 0 {} 1"
+} "abc def 0 \x1Aqrs 0 tuv 0 {} 1"
 test io-31.23 {Tcl_Write, ^Z in middle ignored, Tcl_Gets cr} {
     file delete $path(test1)
     set f [open $path(test1) w]
@@ -3843,7 +3847,7 @@ test io-31.23 {Tcl_Write, ^Z in middle ignored, Tcl_Gets cr} {
     lappend l [eof $f]
     close $f
     set l
-} "abc def 0 \x1aqrs 0 tuv 0 {} 1"
+} "abc def 0 \x1Aqrs 0 tuv 0 {} 1"
 test io-31.24 {Tcl_Write, ^Z in middle ignored, Tcl_Gets crlf} {
     file delete $path(test1)
     set f [open $path(test1) w]
@@ -3865,7 +3869,7 @@ test io-31.24 {Tcl_Write, ^Z in middle ignored, Tcl_Gets crlf} {
     lappend l [eof $f]
     close $f
     set l
-} "abc def 0 \x1aqrs 0 tuv 0 {} 1"
+} "abc def 0 \x1Aqrs 0 tuv 0 {} 1"
 test io-31.25 {Tcl_Write lf, ^Z in middle, Tcl_Gets auto} {
     file delete $path(test1)
     set f [open $path(test1) w]
@@ -3874,7 +3878,7 @@ test io-31.25 {Tcl_Write lf, ^Z in middle, Tcl_Gets auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3892,7 +3896,7 @@ test io-31.26 {Tcl_Write lf, ^Z in middle, Tcl_Gets lf} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3910,7 +3914,7 @@ test io-31.27 {Tcl_Write cr, ^Z in middle, Tcl_Gets auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3928,7 +3932,7 @@ test io-31.28 {Tcl_Write cr, ^Z in middle, Tcl_Gets cr} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3946,7 +3950,7 @@ test io-31.29 {Tcl_Write crlf, ^Z in middle, Tcl_Gets auto} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3964,7 +3968,7 @@ test io-31.30 {Tcl_Write crlf, ^Z in middle, Tcl_Gets crlf} {
     puts $f $s
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l ""
     lappend l [gets $f]
     lappend l [gets $f]
@@ -3985,7 +3989,7 @@ test io-31.31 {Tcl_Write crlf on block boundary, Tcl_Gets crlf} {
     }
     close $f
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf 
+    fconfigure $f -translation crlf
     set c ""
     while {[gets $f line] >= 0} {
        append c $line\n
@@ -4093,7 +4097,7 @@ test io-32.9 {Tcl_Read, read to end of file} {
     }
     set x
 } ok
-test io-32.10 {Tcl_Read from a pipe} {stdio openpipe} {
+test io-32.10 {Tcl_Read from a pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {puts [gets stdin]}
@@ -4105,7 +4109,7 @@ test io-32.10 {Tcl_Read from a pipe} {stdio openpipe} {
     close $f1
     set x
 } "hello\n"
-test io-32.11 {Tcl_Read from a pipe} {stdio openpipe} {
+test io-32.11 {Tcl_Read from a pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {puts [gets stdin]}
@@ -4124,7 +4128,7 @@ test io-32.11 {Tcl_Read from a pipe} {stdio openpipe} {
 } {{hello
 } {hello
 }}
-test io-32.11.1 {Tcl_Read from a pipe} {stdio openpipe} {
+test io-32.11.1 {Tcl_Read from a pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {chan configure stdout -translation crlf}
@@ -4144,7 +4148,7 @@ test io-32.11.1 {Tcl_Read from a pipe} {stdio openpipe} {
 } {{hello
 } {hello
 }}
-test io-32.11.2 {Tcl_Read from a pipe} {stdio openpipe} {
+test io-32.11.2 {Tcl_Read from a pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {chan configure stdout -translation crlf}
@@ -4255,7 +4259,7 @@ test io-33.2 {Tcl_Gets into variable} {
     close $f1
     set z
 } ok
-test io-33.3 {Tcl_Gets from pipe} {stdio openpipe} {
+test io-33.3 {Tcl_Gets from pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {puts [gets stdin]}
@@ -4563,7 +4567,7 @@ test io-34.7 {Tcl_Seek to offset from end of file, then to current position} {
     close $f1
     list $c1 $r1 $c2
 } {44 rstuv 49}
-test io-34.8 {Tcl_Seek on pipes: not supported} {stdio openpipe} {
+test io-34.8 {Tcl_Seek on pipes: not supported} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     set x [list [catch {seek $f1 0 current} msg] $msg]
     close $f1
@@ -4671,13 +4675,13 @@ test io-34.15 {Tcl_Tell combined with seeking} {
     close $f1
     list $c1 $c2
 } {10 20}
-test io-34.16 {Tcl_Tell on pipe: always -1} {stdio openpipe} {
+test io-34.16 {Tcl_Tell on pipe: always -1} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     set c [tell $f1]
     close $f1
     set c
 } -1
-test io-34.17 {Tcl_Tell on pipe: always -1} {stdio openpipe} {
+test io-34.17 {Tcl_Tell on pipe: always -1} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     puts $f1 {puts hello}
     flush $f1
@@ -4776,7 +4780,7 @@ test io-35.1 {Tcl_Eof} {
     close $f
     set x
 } {0 0 0 0 1 1}
-test io-35.2 {Tcl_Eof with pipe} {stdio openpipe} {
+test io-35.2 {Tcl_Eof with pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {gets stdin}
@@ -4794,7 +4798,7 @@ test io-35.2 {Tcl_Eof with pipe} {stdio openpipe} {
     close $f1
     set x
 } {0 0 0 1}
-test io-35.3 {Tcl_Eof with pipe} {stdio openpipe} {
+test io-35.3 {Tcl_Eof with pipe} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {gets stdin}
@@ -4828,7 +4832,7 @@ test io-35.4 {Tcl_Eof, eof detection on nonblocking file} {nonBlockFiles} {
     close $f
     set l
 } {{} 1}
-test io-35.5 {Tcl_Eof, eof detection on nonblocking pipe} {stdio openpipe} {
+test io-35.5 {Tcl_Eof, eof detection on nonblocking pipe} stdio {
     file delete $path(pipe)
     set f [open $path(pipe) w]
     puts $f {
@@ -4845,12 +4849,12 @@ test io-35.5 {Tcl_Eof, eof detection on nonblocking pipe} {stdio openpipe} {
 test io-35.6 {Tcl_Eof, eof char, lf write, auto read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4859,12 +4863,12 @@ test io-35.6 {Tcl_Eof, eof char, lf write, auto read} {
 test io-35.7 {Tcl_Eof, eof char, lf write, lf read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4873,12 +4877,12 @@ test io-35.7 {Tcl_Eof, eof char, lf write, lf read} {
 test io-35.8 {Tcl_Eof, eof char, cr write, auto read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4887,12 +4891,12 @@ test io-35.8 {Tcl_Eof, eof char, cr write, auto read} {
 test io-35.9 {Tcl_Eof, eof char, cr write, cr read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4901,12 +4905,12 @@ test io-35.9 {Tcl_Eof, eof char, cr write, cr read} {
 test io-35.10 {Tcl_Eof, eof char, crlf write, auto read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4915,12 +4919,12 @@ test io-35.10 {Tcl_Eof, eof char, crlf write, auto read} {
 test io-35.11 {Tcl_Eof, eof char, crlf write, crlf read} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4935,7 +4939,7 @@ test io-35.12 {Tcl_Eof, eof char in middle, lf write, auto read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4950,7 +4954,7 @@ test io-35.13 {Tcl_Eof, eof char in middle, lf write, lf read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4965,7 +4969,7 @@ test io-35.14 {Tcl_Eof, eof char in middle, cr write, auto read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4980,7 +4984,7 @@ test io-35.15 {Tcl_Eof, eof char in middle, cr write, cr read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -4995,7 +4999,7 @@ test io-35.16 {Tcl_Eof, eof char in middle, crlf write, auto read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -5010,7 +5014,7 @@ test io-35.17 {Tcl_Eof, eof char in middle, crlf write, crlf read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [read $f]]
     set e [eof $f]
     close $f
@@ -5033,12 +5037,12 @@ test io-35.18 {Tcl_Eof, eof char, cr write, crlf read} -body {
 test io-35.18a {Tcl_Eof, eof char, cr write, crlf read} -body {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     puts $f abc\ndef
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [set in [read $f]]]
     set e [eof $f]
     close $f
@@ -5047,12 +5051,12 @@ test io-35.18a {Tcl_Eof, eof char, cr write, crlf read} -body {
 test io-35.18b {Tcl_Eof, eof char, cr write, crlf read} -body {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     puts $f {}
     close $f
     set s [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [set in [read $f]]]
     set e [eof $f]
     close $f
@@ -5081,7 +5085,7 @@ test io-35.19 {Tcl_Eof, eof char in middle, cr write, crlf read} -body {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [set in [read $f]]]
     set e [eof $f]
     close $f
@@ -5096,7 +5100,7 @@ test io-35.20 {Tcl_Eof, eof char in middle, cr write, crlf read} {
     close $f
     set c [file size $path(test1)]
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     set l [string length [set in [read $f]]]
     set e [eof $f]
     close $f
@@ -5105,7 +5109,7 @@ test io-35.20 {Tcl_Eof, eof char in middle, cr write, crlf read} {
 
 # Test Tcl_InputBlocked
 
-test io-36.1 {Tcl_InputBlocked on nonblocking pipe} {stdio openpipe} {
+test io-36.1 {Tcl_InputBlocked on nonblocking pipe} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     puts $f1 {puts hello_from_pipe}
     flush $f1
@@ -5124,7 +5128,7 @@ test io-36.1 {Tcl_InputBlocked on nonblocking pipe} {stdio openpipe} {
     close $f1
     set x
 } {{} 1 hello 0 {} 1}
-test io-36.1.1 {Tcl_InputBlocked on nonblocking binary pipe} {stdio openpipe} {
+test io-36.1.1 {Tcl_InputBlocked on nonblocking binary pipe} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     chan configure $f1 -encoding binary -translation lf -eofchar {}
     puts $f1 {
@@ -5147,7 +5151,7 @@ test io-36.1.1 {Tcl_InputBlocked on nonblocking binary pipe} {stdio openpipe} {
     close $f1
     set x
 } {{} 1 hello 0 {} 1}
-test io-36.2 {Tcl_InputBlocked on blocking pipe} {stdio openpipe} {
+test io-36.2 {Tcl_InputBlocked on blocking pipe} stdio {
     set f1 [open "|[list [interpreter]]" r+]
     fconfigure $f1 -buffering line
     puts $f1 {puts hello_from_pipe}
@@ -5411,7 +5415,7 @@ test io-39.9 {Tcl_SetChannelOption, blocking mode} {nonBlockFiles} {
     close $f1
     set x
 } {1 0 {} {} 0 1}
-test io-39.10 {Tcl_SetChannelOption, blocking mode} {stdio openpipe} {
+test io-39.10 {Tcl_SetChannelOption, blocking mode} stdio {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts $f1 {
@@ -5474,7 +5478,7 @@ test io-39.13 {Tcl_SetChannelOption, Tcl_GetChannelOption, buffer size} {
 test io-39.14 {Tcl_SetChannelOption: -encoding, binary & utf-8} {
     file delete $path(test1)
     set f [open $path(test1) w]
-    fconfigure $f -encoding {} 
+    fconfigure $f -encoding {}
     puts -nonewline $f \xe7\x89\xa6
     close $f
     set f [open $path(test1) r]
@@ -5502,7 +5506,7 @@ test io-39.16 {Tcl_SetChannelOption: -encoding, errors} {
     close $f
     set result
 } {1 {unknown encoding "foobar"}}
-test io-39.17 {Tcl_SetChannelOption: -encoding, clearing CHANNEL_NEED_MORE_DATA} {stdio openpipe fileevent} {
+test io-39.17 {Tcl_SetChannelOption: -encoding, clearing CHANNEL_NEED_MORE_DATA} {stdio fileevent} {
     set f [open "|[list [interpreter] $path(cat)]" r+]
     fconfigure $f -encoding binary
     puts -nonewline $f "\xe7"
@@ -5651,8 +5655,8 @@ test io-40.3 {POSIX open access modes: CREAT} {unix umask} {
     set f [open $path(test3) {WRONLY CREAT}]
     close $f
     file stat $path(test3) stats
-    format "%#o" [expr $stats(mode)&0o777]
-} [format %#4o [expr {0o666 & ~ $umaskValue}]]
+    format "0o%03o" [expr $stats(mode)&0o777]
+} [format "0o%03o" [expr {0o666 & ~ $umaskValue}]]
 test io-40.4 {POSIX open access modes: CREAT} {
     file delete $path(test3)
     set f [open $path(test3) w]
@@ -5851,7 +5855,7 @@ test io-43.1 {Tcl_FileeventCmd: creating, deleting, querying} {stdio unixExecs f
 test io-43.2 {Tcl_FileeventCmd: deleting when many present} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     set result {}
     lappend result [fileevent $f r] [fileevent $f2 r] [fileevent $f3 r]
     fileevent $f r "read f"
@@ -5872,7 +5876,7 @@ test io-43.2 {Tcl_FileeventCmd: deleting when many present} -setup {
 test io-44.1 {FileEventProc procedure: normal read event} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     fileevent $f2 readable [namespace code {
        set x [gets $f2]; fileevent $f2 readable {}
     }]
@@ -5885,7 +5889,7 @@ test io-44.1 {FileEventProc procedure: normal read event} -setup {
     catch {close $f3}
 } -result {text}
 test io-44.2 {FileEventProc procedure: error in read event} -constraints {
-    stdio unixExecs fileevent openpipe
+    stdio unixExecs fileevent
 } -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
@@ -5908,7 +5912,7 @@ test io-44.2 {FileEventProc procedure: error in read event} -constraints {
 test io-44.3 {FileEventProc procedure: normal write event} -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
-} -constraints {stdio unixExecs fileevent openpipe} -body {
+} -constraints {stdio unixExecs fileevent} -body {
     fileevent $f2 writable [namespace code {
        lappend x "triggered"
        incr count -1
@@ -5927,7 +5931,7 @@ test io-44.3 {FileEventProc procedure: normal write event} -setup {
     catch {close $f3}
 } -result {initial triggered triggered triggered}
 test io-44.4 {FileEventProc procedure: eror in write event} -constraints {
-    stdio unixExecs fileevent openpipe
+    stdio unixExecs fileevent
 } -setup {
     set f2 [open "|[list cat -u]" r+]
     set f3 [open "|[list cat -u]" r+]
@@ -5946,7 +5950,9 @@ test io-44.4 {FileEventProc procedure: eror in write event} -constraints {
     catch {close $f2}
     catch {close $f3}
 } -result {bad-write {}}
-test io-44.5 {FileEventProc procedure: end of file} {stdio unixExecs openpipe fileevent} {
+test io-44.5 {FileEventProc procedure: end of file} -constraints {
+    stdio unixExecs fileevent
+} -body {
     set f4 [open "|[list [interpreter] $path(cat) << foo]" r]
     fileevent $f4 readable [namespace code {
        if {[gets $f4 line] < 0} {
@@ -5959,9 +5965,10 @@ test io-44.5 {FileEventProc procedure: end of file} {stdio unixExecs openpipe fi
     variable x initial
     vwait [namespace which -variable x]
     vwait [namespace which -variable x]
-    close $f4
     set x
-} {initial foo eof}
+} -cleanup {
+    close $f4
+} -result {initial foo eof}
 
 close $f
 makeFile "foo bar" foo
@@ -6020,7 +6027,7 @@ test io-45.3 {DeleteFileEvent, cleanup on close} {fileevent} {
 
 # Execute these tests only if the "testfevent" command is present.
 
-test io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileevent} {
+test io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileevent notOSX} {
     testfevent create
     set script "set f \[[list open $path(foo) r]]\n"
     append script {
@@ -6030,9 +6037,10 @@ test io-46.1 {Tcl event loop vs multiple interpreters} {testfevent fileevent} {
            fileevent $f readable {}
        }]
     }
+    set timer [after 10 lappend x timeout]
     testfevent cmd $script
-    after 1    ;# We must delay because Windows takes a little time to notice
-    update
+    vwait x
+    after cancel $timer
     testfevent cmd {close $f}
     list [testfevent cmd {set x}] [testfevent cmd {info commands after}]
 } {{f triggered: foo bar} after}
@@ -6221,7 +6229,7 @@ test io-48.2 {testing readability conditions} {nonBlockFiles fileevent} {
     list $x $l
 } {done {called called called called called called called}}
 set path(my_script) [makeFile {} my_script]
-test io-48.3 {testing readability conditions} {stdio unix nonBlockFiles openpipe fileevent} {
+test io-48.3 {testing readability conditions} {stdio unix nonBlockFiles fileevent} {
     set f [open $path(bar) w]
     puts $f abcdefg
     puts $f abcdefg
@@ -6291,7 +6299,7 @@ test io-48.4 {lf write, testing readability, ^Z termination, auto read mode} {fi
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6319,7 +6327,7 @@ test io-48.5 {lf write, testing readability, ^Z in middle, auto read mode} {file
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6347,7 +6355,7 @@ test io-48.6 {cr write, testing readability, ^Z termination, auto read mode} {fi
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6375,7 +6383,7 @@ test io-48.7 {cr write, testing readability, ^Z in middle, auto read mode} {file
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6403,7 +6411,7 @@ test io-48.8 {crlf write, testing readability, ^Z termination, auto read mode} {
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation auto -eofchar \x1a
+    fconfigure $f -translation auto -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6431,7 +6439,7 @@ test io-48.9 {crlf write, testing readability, ^Z in middle, auto read mode} {fi
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation auto
+    fconfigure $f -eofchar \x1A -translation auto
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6459,7 +6467,7 @@ test io-48.10 {lf write, testing readability, ^Z in middle, lf read mode} {filee
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation lf
+    fconfigure $f -eofchar \x1A -translation lf
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6487,7 +6495,7 @@ test io-48.11 {lf write, testing readability, ^Z termination, lf read mode} {fil
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation lf -eofchar \x1a
+    fconfigure $f -translation lf -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6515,7 +6523,7 @@ test io-48.12 {cr write, testing readability, ^Z in middle, cr read mode} {filee
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation cr
+    fconfigure $f -eofchar \x1A -translation cr
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6543,7 +6551,7 @@ test io-48.13 {cr write, testing readability, ^Z termination, cr read mode} {fil
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation cr -eofchar \x1a
+    fconfigure $f -translation cr -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6571,7 +6579,7 @@ test io-48.14 {crlf write, testing readability, ^Z in middle, crlf read mode} {f
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -eofchar \x1a -translation crlf
+    fconfigure $f -eofchar \x1A -translation crlf
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6599,7 +6607,7 @@ test io-48.15 {crlf write, testing readability, ^Z termi, crlf read mode} {filee
     set c 0
     set l ""
     set f [open $path(test1) r]
-    fconfigure $f -translation crlf -eofchar \x1a
+    fconfigure $f -translation crlf -eofchar \x1A
     fileevent $f readable [namespace code [list consume $f]]
     variable x
     vwait [namespace which -variable x]
@@ -6719,47 +6727,57 @@ test io-49.5 {testing crlf reading, leftover cr disgorgment} {
     set l
 } [list 7 a\rb\rc 7 {} 7 1]
 
-test io-50.1 {testing handler deletion} {testchannelevent} {
+test io-50.1 {testing handler deletion} -constraints {testchannelevent testservicemode} -setup {
     file delete $path(test1)
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list delhandler $f]]
+    update
     proc delhandler {f} {
        variable z
        set z called
        testchannelevent $f delete 0
     }
     set z not_called
-    update
-    close $f
+    set timer [after 50 lappend z timeout]
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list delhandler $f]]
+    testservicemode 1
+    vwait z
+    after cancel $timer
     set z
-} called
-test io-50.2 {testing handler deletion with multiple handlers} {testchannelevent} {
+} -cleanup {
+    close $f
+} -result called
+test io-50.2 {testing handler deletion with multiple handlers} -constraints {testchannelevent testservicemode} -setup {
     file delete $path(test1)
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list delhandler $f 1]]
-    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
     proc delhandler {f i} {
        variable z
-       lappend z "called delhandler $f $i"
+       lappend z "called delhandler $i"
        testchannelevent $f delete 0
     }
     set z ""
-    update
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list delhandler $f 1]]
+    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+    testservicemode 1
+    set timer [after 50 lappend z timeout]
+    vwait z
+    after cancel $timer
+    set z
+} -cleanup {
     close $f
-    string compare [string tolower $z] \
-       [list [list called delhandler $f 0] [list called delhandler $f 1]]
-} 0
-test io-50.3 {testing handler deletion with multiple handlers} {testchannelevent} {
+} -result {{called delhandler 0} {called delhandler 1}}
+test io-50.3 {testing handler deletion with multiple handlers} -constraints {testchannelevent testservicemode} -setup {
     file delete $path(test1)
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list notcalled $f 1]]
-    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
     set z ""
     proc notcalled {f i} {
        variable z
@@ -6768,23 +6786,30 @@ test io-50.3 {testing handler deletion with multiple handlers} {testchannelevent
     proc delhandler {f i} {
        variable z
        testchannelevent $f delete 1
-       lappend z "delhandler $f $i called"
+       lappend z "delhandler $i called"
        testchannelevent $f delete 0
-       lappend z "delhandler $f $i deleted myself"
+       lappend z "delhandler $i deleted myself"
     }
     set z ""
-    update
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list notcalled $f 1]]
+    testchannelevent $f add readable [namespace code [list delhandler $f 0]]
+    testservicemode 1
+    set timer [after 50 lappend z timeout]
+    vwait z
+    after cancel $timer
+    set z
+} -cleanup {
     close $f
-    string compare [string tolower $z] \
-       [list [list delhandler $f 0 called] \
-             [list delhandler $f 0 deleted myself]]
-} 0
-test io-50.4 {testing handler deletion vs reentrant calls} {testchannelevent} {
+} -result {{delhandler 0 called} {delhandler 0 deleted myself}}
+test io-50.4 {testing handler deletion vs reentrant calls} -constraints {testchannelevent testservicemode} -setup {
     file delete $path(test1)
+    update
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list delrecursive $f]]
+    update
     proc delrecursive {f} {
        variable z
        variable u
@@ -6799,18 +6824,22 @@ test io-50.4 {testing handler deletion vs reentrant calls} {testchannelevent} {
     }
     variable u toplevel
     variable z ""
-    update
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list delrecursive $f]]
+    testservicemode 1
+    set timer [after 50 lappend z timeout]
+    vwait z
+    after cancel $timer
+    set z
+} -cleanup {
     close $f
-    string compare [string tolower $z] \
-       {{delrecursive calling recursive} {delrecursive deleting recursive}}
-} 0
-test io-50.5 {testing handler deletion vs reentrant calls} {testchannelevent} {
+} -result {{delrecursive calling recursive} {delrecursive deleting recursive}}
+test io-50.5 {testing handler deletion vs reentrant calls} -constraints {testchannelevent testservicemode notOSX} -setup {
     file delete $path(test1)
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list notcalled $f]]
-    testchannelevent $f add readable [namespace code [list del $f]]
     proc notcalled {f} {
        variable z
        lappend z "notcalled was called!! $f"
@@ -6820,39 +6849,50 @@ test io-50.5 {testing handler deletion vs reentrant calls} {testchannelevent} {
        variable z
        if {"$u" == "recursive"} {
            testchannelevent $f delete 1
-           testchannelevent $f delete 0
            lappend z "del deleted notcalled"
+           testchannelevent $f delete 0
            lappend z "del deleted myself"
        } else {
            set u recursive
            lappend z "del calling recursive"
-           update
-           lappend z "del after update"
+           set timer [after 50 lappend z timeout]
+           vwait z
+           after cancel $timer
+           lappend z "del after recursive"
        }
     }
     set z ""
     set u toplevel
-    update
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list notcalled $f]]
+    testchannelevent $f add readable [namespace code [list del $f]]
+    testservicemode 1
+    set timer [after 50 set z timeout]
+    vwait z
+    after cancel $timer
+    set z
+} -cleanup {
     close $f
-    string compare [string tolower $z] \
-       [list {del calling recursive} {del deleted notcalled} \
-             {del deleted myself} {del after update}]
-} 0
-test io-50.6 {testing handler deletion vs reentrant calls} {testchannelevent} {
+} -result [list {del calling recursive} {del deleted notcalled} \
+              {del deleted myself} {del after recursive}]
+test io-50.6 {testing handler deletion vs reentrant calls} -constraints {testchannelevent testservicemode} -setup {
     file delete $path(test1)
+} -body {
     set f [open $path(test1) w]
     close $f
-    set f [open $path(test1) r]
-    testchannelevent $f add readable [namespace code [list second $f]]
-    testchannelevent $f add readable [namespace code [list first $f]]
     proc first {f} {
        variable u
        variable z
+       variable done
        if {"$u" == "toplevel"} {
            lappend z "first called"
            set u first
-           update
-           lappend z "first after update"
+           set timer [after 50 lappend z timeout]
+           vwait z
+           after cancel $timer
+           lappend z "first after toplevel"
+           set done 1
        } else {
            lappend z "first called not toplevel"
        }
@@ -6874,14 +6914,24 @@ test io-50.6 {testing handler deletion vs reentrant calls} {testchannelevent} {
     }
     set z ""
     set u toplevel
+    set done 0
+    testservicemode 0
+    set f [open $path(test1) r]
+    testchannelevent $f add readable [namespace code [list second $f]]
+    testchannelevent $f add readable [namespace code [list first $f]]
+    testservicemode 1
     update
+    if {!$done} {
+       set timer2 [after 200 set done 1]
+       vwait done
+       after cancel $timer2
+    }
+    set z
+} -cleanup {
     close $f
-    string compare [string tolower $z] \
-       [list {first called} {first called not toplevel} \
-             {second called, first time} {second called, second time} \
-             {first after update}]
-} 0
-
+} -result [list {first called} {first called not toplevel} \
+       {second called, first time} {second called, second time} \
+       {first after toplevel}]
 test io-51.1 {Test old socket deletion on Macintosh} {socket} {
     set x 0
     set result ""
@@ -7071,7 +7121,7 @@ test io-52.7 {TclCopyChannel} {fcopy} {
     }
     set result
 } {0 0 ok}
-test io-52.8 {TclCopyChannel} {stdio openpipe fcopy} {
+test io-52.8 {TclCopyChannel} {stdio fcopy} {
     file delete $path(test1)
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
@@ -7351,7 +7401,7 @@ test io-53.2 {CopyData} {fcopy} {
     }
     set result
 } {0 0 ok}
-test io-53.3 {CopyData: background read underflow} {stdio unix openpipe fcopy} {
+test io-53.3 {CopyData: background read underflow} {stdio unix fcopy} {
     file delete $path(test1)
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
@@ -7383,7 +7433,7 @@ test io-53.3 {CopyData: background read underflow} {stdio unix openpipe fcopy} {
     close $f
     set result
 } "ready line1 line2 {done\n}"
-test io-53.4 {CopyData: background write overflow} {stdio openpipe fileevent fcopy} {
+test io-53.4 {CopyData: background write overflow} {stdio fileevent fcopy} {
     set big bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n
     variable x
     for {set x 0} {$x < 12} {incr x} {
@@ -7467,14 +7517,14 @@ test io-53.5 {CopyData: error during fcopy} {socket fcopy} {
     close $listen      ;# This means the socket open never really succeeds
     fcopy $in $out -command [namespace code FcopyTestDone]
     variable fcopyTestDone
-    if ![info exists fcopyTestDone] {
+    if {![info exists fcopyTestDone]} {
        vwait [namespace which -variable fcopyTestDone]         ;# The error occurs here in the b.g.
     }
     close $in
     close $out
     set fcopyTestDone  ;# 1 for error condition
 } 1
-test io-53.6 {CopyData: error during fcopy} {stdio openpipe fcopy} {
+test io-53.6 {CopyData: error during fcopy} {stdio fcopy} {
     variable fcopyTestDone
     file delete $path(pipe)
     file delete $path(test1)
@@ -7486,7 +7536,7 @@ test io-53.6 {CopyData: error during fcopy} {stdio openpipe fcopy} {
     set out [open $path(test1) w]
     fcopy $in $out -command [namespace code FcopyTestDone]
     variable fcopyTestDone
-    if ![info exists fcopyTestDone] {
+    if {![info exists fcopyTestDone]} {
        vwait [namespace which -variable fcopyTestDone]
     }
     catch {close $in}
@@ -7507,7 +7557,7 @@ proc doFcopy {in out {bytes 0} {error {}}} {
                -command [namespace code [list doFcopy $in $out]]]
     }
 }
-test io-53.7 {CopyData: Flooding fcopy from pipe} {stdio openpipe fcopy} {
+test io-53.7 {CopyData: Flooding fcopy from pipe} {stdio fcopy} {
     variable fcopyTestDone
     file delete $path(pipe)
     catch {unset fcopyTestDone}
@@ -7533,7 +7583,7 @@ test io-53.7 {CopyData: Flooding fcopy from pipe} {stdio openpipe fcopy} {
     set out [open $path(test1) w]
     doFcopy $in $out
     variable fcopyTestDone
-    if ![info exists fcopyTestDone] {
+    if {![info exists fcopyTestDone]} {
        vwait [namespace which -variable fcopyTestDone]
     }
     catch {close $in}
@@ -7559,7 +7609,7 @@ test io-53.8 {CopyData: async callback and error handling, Bug 1932639} -setup {
     # Channels to copy between
     set f [open $foo r] ; fconfigure $f -translation binary
     set g [open $bar w] ; fconfigure $g -translation binary -buffering none
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Record input size, so that result is always defined
     lappend ::RES [file size $bar]
     # Run the copy. Should not invoke -command now.
@@ -7600,7 +7650,7 @@ test io-53.8a {CopyData: async callback and error handling, Bug 1932639, at eof}
     # Channels to copy between
     set f [open $foo r] ; fconfigure $f -translation binary
     set g [open $bar w] ; fconfigure $g -translation binary -buffering none
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Initialize and force eof on the input.
     seek $f 0 end ; read $f 1
     set ::RES [eof $f]
@@ -7640,7 +7690,7 @@ test io-53.8b {CopyData: async callback and -size 0} -setup {
     # Channels to copy between
     set f [open $foo r] ; fconfigure $f -translation binary
     set g [open $bar w] ; fconfigure $g -translation binary -buffering none
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
        set ::RES {}
     # Run the copy. Should not invoke -command now.
     fcopy $f $g -size 0 -command ::cmd
@@ -7697,7 +7747,7 @@ test io-53.9 {CopyData: -size and event interaction, Bug 780533} -setup {
     }
     set ::forever {}
     set out [open $out w]
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     fcopy $pipe $out -size 6 -command ::done
     set token [after 5000 {
        set ::forever {fcopy hangs}
@@ -7767,7 +7817,7 @@ test io-53.10 {Bug 1350564, multi-directional fcopy} -setup {
     fconfigure $b -translation binary -buffering none
     fileevent  $a readable [list ::done $a]
     fileevent  $b readable [list ::done $b]
-} -constraints {stdio openpipe fcopy} -body {
+} -constraints {stdio fcopy} -body {
     # Now pass data through the server in both directions.
     set ::forever {}
     puts $a AB
@@ -7815,7 +7865,7 @@ test io-53.11 {Bug 2895565} -setup {
     removeFile out
     removeFile in
 } -result {40 bytes copied}
-test io-53.12 {CopyData: foreground short reads, aka bug 3096275} {stdio unix openpipe fcopy} {
+test io-53.12 {CopyData: foreground short reads, aka bug 3096275} {stdio unix fcopy} {
     file delete $path(pipe)
     set f1 [open $path(pipe) w]
     puts -nonewline $f1 {
@@ -8021,7 +8071,7 @@ test io-53.17 {[7c187a3773] MBWrite: proper inQueueTail handling} -setup {
     removeFile out
 } -result {line 100 line}
 
-test io-54.1 {Recursive channel events} {socket fileevent knownMsvcBug} {
+test io-54.1 {Recursive channel events} {socket fileevent notWinCI} {
     # This test checks to see if file events are delivered during recursive
     # event loops when there is buffered data on the channel.
 
@@ -8230,7 +8280,7 @@ test io-57.2 {buffered data and file events, read} {fileevent} {
     set result
 } {1 readable 234567890 timer}
 
-test io-58.1 {Tcl_NotifyChannel and error when closing} {stdio unixOrWin openpipe fileevent} {
+test io-58.1 {Tcl_NotifyChannel and error when closing} {stdio unixOrWin fileevent} {
     set out [open $path(script) w]
     puts $out {
        puts "normal message from pipe"
@@ -8270,7 +8320,7 @@ test io-59.1 {Thread reference of channels} {testmainthread testchannel} {
     string equal $result [testmainthread]
 } {1}
 
-test io-60.1 {writing illegal utf sequences} {openpipe fileevent testbytestring} {
+test io-60.1 {writing illegal utf sequences} {fileevent testbytestring} {
     # This test will hang in older revisions of the core.
 
     set out [open $path(script) w]
@@ -8648,16 +8698,16 @@ test io-74.1 {[104f2885bb] improper cache validity check} -setup {
     set fn [makeFile {} io-74.1]
     set rfd [open $fn r]
     testobj freeallvars
-    interp create slave
+    interp create child
 } -constraints testobj -body {
     teststringobj set 1 [string range $rfd 0 end]
-    read [teststringobj get 1]         
+    read [teststringobj get 1]
     testobj duplicate 1 2
-    interp transfer {} $rfd slave
+    interp transfer {} $rfd child
     catch {read [teststringobj get 1]}
-    read [teststringobj get 2]         
+    read [teststringobj get 2]
 } -cleanup {
-    interp delete slave
+    interp delete child
     testobj freeallvars
     removeFile io-74.1
 } -returnCodes error -match glob -result {can not find channel named "*"}
index 5c45630..898d076 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -2029,7 +2029,7 @@ test iocmd-32.0 {origin interpreter of moved channel gone} -match glob -body {
     set ida [interp create];#puts <<$ida>>
     set idb [interp create];#puts <<$idb>>
 
-    # Magic to get the test* commands in the slaves
+    # Magic to get the test* commands in the children
     load {} Tcltest $ida
     load {} Tcltest $idb
 
@@ -2067,7 +2067,7 @@ test iocmd-32.1 {origin interpreter of moved channel destroyed during access} -m
     set ida [interp create];#puts <<$ida>>
     set idb [interp create];#puts <<$idb>>
 
-    # Magic to get the test* commands in the slaves
+    # Magic to get the test* commands in the children
     load {} Tcltest $ida
     load {} Tcltest $idb
 
@@ -2109,13 +2109,13 @@ test iocmd-32.2 {delete interp of reflected chan} {
     # Bug 3034840
     # Run this test in an interp with memory debugging to panic
     # on the double free
-    interp create slave
-    slave eval {
+    interp create child
+    child eval {
         proc no-op args {}
         proc driver {sub args} {return {initialize finalize watch read}}
         chan event [chan create read driver] readable no-op
     }
-    interp delete slave
+    interp delete child
 } {}
 
 # ### ### ### ######### ######### #########
index 85e427a..f185117 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -36,8 +36,8 @@ testConstraint thread [expr {0 == [catch {package require Thread 2.7-}]}]
 # can access this variable.
 
 set helperscript {
-    if {[lsearch [namespace children] ::tcltest] == -1} {
-       package require tcltest 2
+    if {"::tcltest" ni [namespace children]} {
+       package require tcltest 2.5
        namespace import -force ::tcltest::*
     }
 
@@ -1162,7 +1162,7 @@ test iortrans-8.3 {chan flush, bug 2921116} -match glob -setup {
 test iortrans-11.0 {origin interpreter of moved transform gone} -setup {
     set ida [interp create];   #puts <<$ida>>
     set idb [interp create];   #puts <<$idb>>
-    # Magic to get the test* commands in the slaves
+    # Magic to get the test* commands in the children
     load {} Tcltest $ida
     load {} Tcltest $idb
 } -constraints {testchannel} -match glob -body {
@@ -1205,7 +1205,7 @@ test iortrans-11.0 {origin interpreter of moved transform gone} -setup {
 test iortrans-11.1 {origin interpreter of moved transform destroyed during access} -setup {
     set ida [interp create];   #puts <<$ida>>
     set idb [interp create];   #puts <<$idb>>
-    # Magic to get the test* commands in the slaves
+    # Magic to get the test* commands in the children
     load {} Tcltest $ida
     load {} Tcltest $idb
 } -constraints {testchannel} -match glob -body {
@@ -1244,16 +1244,16 @@ test iortrans-11.1 {origin interpreter of moved transform destroyed during acces
     tempdone
 } -result {Owner lost}
 test iortrans-11.2 {delete interp of reflected transform} -setup {
-    interp create slave
-    # Magic to get the test* commands into the slave
-    load {} Tcltest slave
+    interp create child
+    # Magic to get the test* commands into the child
+    load {} Tcltest child
 } -constraints {testchannel} -body {
-    # Get base channel into the slave
+    # Get base channel into the child
     set c [tempchan]
     testchannel cut $c
-    interp eval slave [list testchannel splice $c]
-    interp eval slave [list set c $c]
-    slave eval {
+    interp eval child [list testchannel splice $c]
+    interp eval child [list set c $c]
+    child eval {
        proc no-op args {}
        proc driver {c sub args} {
            return {initialize finalize read write}
@@ -1261,7 +1261,7 @@ test iortrans-11.2 {delete interp of reflected transform} -setup {
        set t [chan push $c [list driver $c]]
        chan event $c readable no-op
     }
-    interp delete slave
+    interp delete child
 } -cleanup {
     tempdone
 } -result {}
@@ -1320,7 +1320,7 @@ proc inthread {chan script args} {
     # forwarded channel operations.
 
     set ::tres ""
-    thread::send -async $tid { 
+    thread::send -async $tid {
        after 50
        catch {s} res;  # This runs the script, 's' was defined at (*)
        thread::send -async $mid [list set ::tres $res]
index 4aeb093..9ea554d 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index e513b62..dadf275 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2.2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 189762e..d37f08a 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 4939e5c..ddc56a9 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 2686bd7..864fad0 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -98,26 +98,26 @@ concat {}
 
 proc slowsort list {
     set result {}
-    set last [expr [llength $list] - 1]
+    set last [expr {[llength $list] - 1}]
     while {$last > 0} {
-       set minIndex [expr [llength $list] - 1]
+       set minIndex [expr {[llength $list] - 1}]
        set min [lindex $list $last]
-       set i [expr $minIndex-1]
+       set i [expr {$minIndex - 1}]
        while {$i >= 0} {
            if {[string compare [lindex $list $i] $min] < 0} {
                set minIndex $i
                set min [lindex $list $i]
            }
-           set i [expr $i-1]
+           incr i -1
        }
        set result [concat $result [list $min]]
        if {$minIndex == 0} {
            set list [lrange $list 1 end]
        } else {
-           set list [concat [lrange $list 0 [expr $minIndex-1]] \
-                         [lrange $list [expr $minIndex+1] end]]
+           set list [concat [lrange $list 0 [expr {$minIndex - 1}]] \
+                         [lrange $list [expr {$minIndex + 1}] end]]
        }
-       set last [expr $last-1]
+       set last [expr {$last - 1}]
     }
     return [concat $result $list]
 }
index d7fb46c..ce6c978 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 169c7ca..a2770c0 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 08035d9..432e195 100644 (file)
@@ -14,7 +14,7 @@
 # RCS: @(#) $Id: $
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 4cd1fcd..c79ddf4 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -45,30 +45,30 @@ testConstraint teststaticpkg [llength [info commands teststaticpkg]]
 testConstraint testsimplefilesystem \
        [llength [info commands testsimplefilesystem]]
 \f
-test load-1.1 {basic errors} {} {
-    list [catch {load} msg] $msg
-} "1 {wrong \# args: should be \"load ?-global? ?-lazy? ?--? fileName ?packageName? ?interp?\"}"
-test load-1.2 {basic errors} {} {
-    list [catch {load a b c d} msg] $msg
-} "1 {wrong \# args: should be \"load ?-global? ?-lazy? ?--? fileName ?packageName? ?interp?\"}"
-test load-1.3 {basic errors} {} {
-    list [catch {load a b foobar} msg] $msg
-} {1 {could not find interpreter "foobar"}}
-test load-1.4 {basic errors} {} {
-    list [catch {load -global {}} msg] $msg
-} {1 {must specify either file name or package name}}
-test load-1.5 {basic errors} {} {
-    list [catch {load -lazy {} {}} msg] $msg
-} {1 {must specify either file name or package name}}
-test load-1.6 {basic errors} {} {
-    list [catch {load {} Unknown} msg] $msg
-} {1 {package "Unknown" isn't loaded statically}}
-test load-1.7 {basic errors} {} {
-    list [catch {load -abc foo} msg] $msg
-} "1 {bad option \"-abc\": must be -global, -lazy, or --}"
-test load-1.8 {basic errors} {} {
-    list [catch {load -global} msg] $msg
-} "1 {couldn't figure out package name for -global}"
+test load-1.1 {basic errors} -returnCodes error -body {
+    load
+} -result {wrong # args: should be "load ?-global? ?-lazy? ?--? fileName ?packageName? ?interp?"}
+test load-1.2 {basic errors} -returnCodes error -body {
+    load a b c d
+} -result {wrong # args: should be "load ?-global? ?-lazy? ?--? fileName ?packageName? ?interp?"}
+test load-1.3 {basic errors} -returnCodes error -body {
+    load a b foobar
+} -result {could not find interpreter "foobar"}
+test load-1.4 {basic errors} -returnCodes error -body {
+    load -global {}
+} -result {must specify either file name or package name}
+test load-1.5 {basic errors} -returnCodes error -body {
+    load -lazy {} {}
+} -result {must specify either file name or package name}
+test load-1.6 {basic errors} -returnCodes error -body {
+    load {} Unknown
+} -result {package "Unknown" isn't loaded statically}
+test load-1.7 {basic errors} -returnCodes error -body {
+    load -abc foo
+} -result {bad option "-abc": must be -global, -lazy, or --}
+test load-1.8 {basic errors} -returnCodes error -body {
+    load -global
+} -result {couldn't figure out package name for -global}
 
 test load-2.1 {basic loading, with guess for package name} \
        [list $dll $loaded] {
@@ -103,7 +103,7 @@ test load-3.1 {error in _Init procedure, same interpreter} \
 "if 44 {open non_existent}"
     invoked from within
 "load [file join $testDir pkge$ext] pkge"} {POSIX ENOENT {no such file or directory}}}
-test load-3.2 {error in _Init procedure, slave interpreter} \
+test load-3.2 {error in _Init procedure, child interpreter} \
        [list $dll $loaded] {
     catch {interp delete x}
     interp create x
@@ -130,16 +130,16 @@ test load-4.2 {reloading package into same interpreter} -setup {
     load [file join $testDir pkga$ext] pkgb
 } -result "file \"[file join $testDir pkga$ext]\" is already loaded for package \"Pkga\""
 
-test load-5.1 {file name not specified and no static package: pick default} \
-       [list $dll $loaded] {
+test load-5.1 {file name not specified and no static package: pick default} -setup {
     catch {interp delete x}
     interp create x
+} -constraints [list $dll $loaded] -body {
     load -global [file join $testDir pkga$ext] pkga
     load {} pkga x
-    set result [info loaded x]
+    info loaded x
+} -cleanup {
     interp delete x
-    set result
-} [list [list [file join $testDir pkga$ext] Pkga]]
+} -result [list [list [file join $testDir pkga$ext] Pkga]]
 
 # On some platforms, like SunOS 4.1.3, these tests can't be run because
 # they cause the process to exit.
@@ -185,16 +185,16 @@ test load-7.4 {Tcl_StaticPackage procedure, redundant calls} -setup {
     info loaded
 } -result [list {{} Double} {{} More} {{} Another} {{} Test} {*}$currentRealPackages {*}$alreadyTotalLoaded]
 
-testConstraint teststaticpkg_8.x \
-    [if {[testConstraint teststaticpkg]} {
+testConstraint teststaticpkg_8.x 0
+if {[testConstraint teststaticpkg]} {
+    catch {
        teststaticpkg Test 1 1
        teststaticpkg Another 0 1
        teststaticpkg More 0 1
        teststaticpkg Double 0 1
-       expr 1
-    } else {
-       expr 0
-    }]
+       testConstraint teststaticpkg_8.x 1
+    }
+}
 
 test load-8.1 {TclGetLoadedPackages procedure} [list teststaticpkg_8.x $dll $loaded] {
     lsort -index 1 [info loaded]
@@ -214,30 +214,32 @@ test load-8.4 {TclGetLoadedPackages procedure} [list teststaticpkg_8.x $dll $loa
 } [list [lsort -index 1 [concat [list [list [file join $testDir pkgb$ext] Pkgb] {{} Double} {{} More} {{} Another} {{} Test} [list [file join $testDir pkga$ext] Pkga]] $alreadyLoaded]] {pkgb_demo pkgb_sub pkgb_unsafe}]
 interp delete child
 
-test load-9.1 {Tcl_StaticPackage, load already-loaded package into another interp} \
-    -constraints {teststaticpkg} \
-    -setup {
-       interp create child1
-       interp create child2
-       load {} Tcltest child1
-       load {} Tcltest child2
-    } \
-    -body {
-       child1 eval { teststaticpkg Loadninepointone 0 1 }
-       child2 eval { teststaticpkg Loadninepointone 0 1 }
-       list \
-           [child1 eval { info loaded {} }] \
-           [child2 eval { info loaded {} }]
-    } \
-    -match glob -result {{{{} Loadninepointone} {* Tcltest}} {{{} Loadninepointone} {* Tcltest}}} \
-    -cleanup { interp delete child1 ; interp delete child2 }
-
-test load-10.1 {load from vfs} \
-    -constraints [list $dll $loaded testsimplefilesystem] \
-    -setup {set dir [pwd]; cd $testDir; testsimplefilesystem 1} \
-    -body {list [catch {load simplefs:/pkgd$ext pkgd} msg] $msg} \
-    -result {0 {}} \
-    -cleanup {testsimplefilesystem 0; cd $dir; unset dir}
+test load-9.1 {Tcl_StaticPackage, load already-loaded package into another interp} -setup {
+    interp create child1
+    interp create child2
+    load {} Tcltest child1
+    load {} Tcltest child2
+} -constraints {teststaticpkg} -body {
+    child1 eval { teststaticpkg Loadninepointone 0 1 }
+    child2 eval { teststaticpkg Loadninepointone 0 1 }
+    list [child1 eval { info loaded {} }] \
+       [child2 eval { info loaded {} }]
+} -match glob -cleanup {
+    interp delete child1
+    interp delete child2
+} -result {{{{} Loadninepointone} {* Tcltest}} {{{} Loadninepointone} {* Tcltest}}}
+
+test load-10.1 {load from vfs} -setup {
+    set dir [pwd]
+    cd $testDir
+    testsimplefilesystem 1
+} -constraints [list $dll $loaded testsimplefilesystem] -body {
+    list [catch {load simplefs:/pkgd$ext pkgd} msg] $msg
+} -result {0 {}} -cleanup {
+    testsimplefilesystem 0
+    cd $dir
+    unset dir
+}
 
 test load-11.1 {Load TclOO extension using Stubs (Bug [f51efe99a7])} \
        [list $dll $loaded] {
index d5676ad..4bce1b3 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 788bb9b..61f2b62 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index fd2f7f8..b7caf47 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index 5e8a1f8..27ae4aa 100644 (file)
@@ -12,7 +12,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
@@ -149,14 +149,14 @@ test lsearch-5.2 {binary search} {
     }
     set res
 } $decreasingIntegers
-test lsearch-5.3 {binary search finds leftmost occurances} {
+test lsearch-5.3 {binary search finds leftmost occurrences} {
     set res {}
     for {set i 0} {$i < 10} {incr i} {
        lappend res [lsearch -integer -sorted $repeatingIncreasingIntegers $i]
     }
     set res
 } [list 0 5 10 15 20 25 30 35 40 45]
-test lsearch-5.4 {binary search -decreasing finds leftmost occurances} {
+test lsearch-5.4 {binary search -decreasing finds leftmost occurrences} {
     set res {}
     for {set i 9} {$i >= 0} {incr i -1} {
        lappend res [lsearch -sorted -integer -decreasing \
@@ -384,7 +384,7 @@ test lsearch-14.8 {combinations: -start, -inline and -not} {
 } {c4}
 
 test lsearch-15.1 {make sure no shimmering occurs} {
-    set x [expr int(sin(0))]
+    set x [expr {int(sin(0))}]
     lsearch -start $x $x $x
 } 0
 
@@ -404,16 +404,16 @@ test lsearch-17.2 {lsearch -index option, basic functionality} {
     lsearch -index 1 -exact {{a c} {a b} {a a}} a
 } 2
 test lsearch-17.3 {lsearch -index option, basic functionality} {
-    lsearch -index 1 -glob {{ab cb} {ab bb} {ab ab}} b* 
+    lsearch -index 1 -glob {{ab cb} {ab bb} {ab ab}} b*
 } 1
 test lsearch-17.4 {lsearch -index option, basic functionality} {
     lsearch -index 1 -regexp {{ab cb} {ab bb} {ab ab}} {[cb]b}
-} 0 
+} 0
 test lsearch-17.5 {lsearch -index option, basic functionality} {
     lsearch -all -index 0 -exact {{a c} {a b} {d a}} a
 } {0 1}
 test lsearch-17.6 {lsearch -index option, basic functionality} {
-    lsearch -all -index 1 -glob {{ab cb} {ab bb} {db bx}} b* 
+    lsearch -all -index 1 -glob {{ab cb} {ab bb} {db bx}} b*
 } {1 2}
 test lsearch-17.7 {lsearch -index option, basic functionality} {
     lsearch -all -index 1 -regexp {{ab cb} {ab bb} {ab ab}} {[cb]b}
@@ -454,11 +454,11 @@ test lsearch-18.2 {lsearch -index option, list as index basic functionality} {
     lsearch -index {2 0} -exact {{{x x} {x b} {a d}} {{a c} {a b} {a a}}} a
 } 0
 test lsearch-18.3 {lsearch -index option, list as index basic functionality} {
-    lsearch -index {1 1} -glob {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} b* 
+    lsearch -index {1 1} -glob {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} b*
 } 0
 test lsearch-18.4 {lsearch -index option, list as index basic functionality} {
     lsearch -index {0 1} -regexp {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} {[cb]b}
-} 0 
+} 0
 test lsearch-18.5 {lsearch -index option, list as index basic functionality} {
     lsearch -all -index {0 0} -exact {{{a c} {a b} {d a}} {{a c} {a b} {d a}}} a
 } {0 1}
@@ -470,11 +470,11 @@ test lsearch-19.2 {lsearch -subindices option} {
     lsearch -subindices -index {2 0} -exact {{{x x} {x b} {a d}} {{a c} {a b} {a a}}} a
 } {0 2 0}
 test lsearch-19.3 {lsearch -subindices option} {
-    lsearch -subindices -index {1 1} -glob {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} b* 
+    lsearch -subindices -index {1 1} -glob {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} b*
 } {0 1 1}
 test lsearch-19.4 {lsearch -subindices option} {
     lsearch -subindices -index {0 1} -regexp {{{ab cb} {ab bb} {ab ab}} {{ab cb} {ab bb} {ab ab}}} {[cb]b}
-} {0 0 1} 
+} {0 0 1}
 test lsearch-19.5 {lsearch -subindices option} {
     lsearch -subindices -all -index {0 0} -exact {{{a c} {a b} {d a}} {{a c} {a b} {d a}}} a
 } {{0 0 0} {1 0 0}}
index 1c1300b..a130fe9 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 6846cbf..d50e0b2 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -22,7 +22,7 @@ if {[lsearch [namespace children] ::tcltest] == -1} {
 proc evalInProc { script } {
     proc testProc {} $script
     set status [catch {
-       testProc 
+       testProc
     } result]
     rename testProc {}
     return [list $status $result]
@@ -60,69 +60,69 @@ test lsetComp-2.3 {lset, compiled, list of args, scalar, one-byte offset} {
 
 test lsetComp-2.4 {lset, compiled, list of args, scalar, four-byte offset} {
     evalInProc {
-       set x0 0; set x1 0; set x2 0; set x3 0; 
-       set x4 0; set x5 0; set x6 0; set x7 0; 
-       set x8 0; set x9 0; set x10 0; set x11 0; 
-       set x12 0; set x13 0; set x14 0; set x15 0; 
-       set x16 0; set x17 0; set x18 0; set x19 0; 
-       set x20 0; set x21 0; set x22 0; set x23 0; 
-       set x24 0; set x25 0; set x26 0; set x27 0; 
-       set x28 0; set x29 0; set x30 0; set x31 0; 
-       set x32 0; set x33 0; set x34 0; set x35 0; 
-       set x36 0; set x37 0; set x38 0; set x39 0; 
-       set x40 0; set x41 0; set x42 0; set x43 0; 
-       set x44 0; set x45 0; set x46 0; set x47 0; 
-       set x48 0; set x49 0; set x50 0; set x51 0; 
-       set x52 0; set x53 0; set x54 0; set x55 0; 
-       set x56 0; set x57 0; set x58 0; set x59 0; 
-       set x60 0; set x61 0; set x62 0; set x63 0; 
-       set x64 0; set x65 0; set x66 0; set x67 0; 
-       set x68 0; set x69 0; set x70 0; set x71 0; 
-       set x72 0; set x73 0; set x74 0; set x75 0; 
-       set x76 0; set x77 0; set x78 0; set x79 0; 
-       set x80 0; set x81 0; set x82 0; set x83 0; 
-       set x84 0; set x85 0; set x86 0; set x87 0; 
-       set x88 0; set x89 0; set x90 0; set x91 0; 
-       set x92 0; set x93 0; set x94 0; set x95 0; 
-       set x96 0; set x97 0; set x98 0; set x99 0; 
-       set x100 0; set x101 0; set x102 0; set x103 0; 
-       set x104 0; set x105 0; set x106 0; set x107 0; 
-       set x108 0; set x109 0; set x110 0; set x111 0; 
-       set x112 0; set x113 0; set x114 0; set x115 0; 
-       set x116 0; set x117 0; set x118 0; set x119 0; 
-       set x120 0; set x121 0; set x122 0; set x123 0; 
-       set x124 0; set x125 0; set x126 0; set x127 0; 
-       set x128 0; set x129 0; set x130 0; set x131 0; 
-       set x132 0; set x133 0; set x134 0; set x135 0; 
-       set x136 0; set x137 0; set x138 0; set x139 0; 
-       set x140 0; set x141 0; set x142 0; set x143 0; 
-       set x144 0; set x145 0; set x146 0; set x147 0; 
-       set x148 0; set x149 0; set x150 0; set x151 0; 
-       set x152 0; set x153 0; set x154 0; set x155 0; 
-       set x156 0; set x157 0; set x158 0; set x159 0; 
-       set x160 0; set x161 0; set x162 0; set x163 0; 
-       set x164 0; set x165 0; set x166 0; set x167 0; 
-       set x168 0; set x169 0; set x170 0; set x171 0; 
-       set x172 0; set x173 0; set x174 0; set x175 0; 
-       set x176 0; set x177 0; set x178 0; set x179 0; 
-       set x180 0; set x181 0; set x182 0; set x183 0; 
-       set x184 0; set x185 0; set x186 0; set x187 0; 
-       set x188 0; set x189 0; set x190 0; set x191 0; 
-       set x192 0; set x193 0; set x194 0; set x195 0; 
-       set x196 0; set x197 0; set x198 0; set x199 0; 
-       set x200 0; set x201 0; set x202 0; set x203 0; 
-       set x204 0; set x205 0; set x206 0; set x207 0; 
-       set x208 0; set x209 0; set x210 0; set x211 0; 
-       set x212 0; set x213 0; set x214 0; set x215 0; 
-       set x216 0; set x217 0; set x218 0; set x219 0; 
-       set x220 0; set x221 0; set x222 0; set x223 0; 
-       set x224 0; set x225 0; set x226 0; set x227 0; 
-       set x228 0; set x229 0; set x230 0; set x231 0; 
-       set x232 0; set x233 0; set x234 0; set x235 0; 
-       set x236 0; set x237 0; set x238 0; set x239 0; 
-       set x240 0; set x241 0; set x242 0; set x243 0; 
-       set x244 0; set x245 0; set x246 0; set x247 0; 
-       set x248 0; set x249 0; set x250 0; set x251 0; 
+       set x0 0; set x1 0; set x2 0; set x3 0;
+       set x4 0; set x5 0; set x6 0; set x7 0;
+       set x8 0; set x9 0; set x10 0; set x11 0;
+       set x12 0; set x13 0; set x14 0; set x15 0;
+       set x16 0; set x17 0; set x18 0; set x19 0;
+       set x20 0; set x21 0; set x22 0; set x23 0;
+       set x24 0; set x25 0; set x26 0; set x27 0;
+       set x28 0; set x29 0; set x30 0; set x31 0;
+       set x32 0; set x33 0; set x34 0; set x35 0;
+       set x36 0; set x37 0; set x38 0; set x39 0;
+       set x40 0; set x41 0; set x42 0; set x43 0;
+       set x44 0; set x45 0; set x46 0; set x47 0;
+       set x48 0; set x49 0; set x50 0; set x51 0;
+       set x52 0; set x53 0; set x54 0; set x55 0;
+       set x56 0; set x57 0; set x58 0; set x59 0;
+       set x60 0; set x61 0; set x62 0; set x63 0;
+       set x64 0; set x65 0; set x66 0; set x67 0;
+       set x68 0; set x69 0; set x70 0; set x71 0;
+       set x72 0; set x73 0; set x74 0; set x75 0;
+       set x76 0; set x77 0; set x78 0; set x79 0;
+       set x80 0; set x81 0; set x82 0; set x83 0;
+       set x84 0; set x85 0; set x86 0; set x87 0;
+       set x88 0; set x89 0; set x90 0; set x91 0;
+       set x92 0; set x93 0; set x94 0; set x95 0;
+       set x96 0; set x97 0; set x98 0; set x99 0;
+       set x100 0; set x101 0; set x102 0; set x103 0;
+       set x104 0; set x105 0; set x106 0; set x107 0;
+       set x108 0; set x109 0; set x110 0; set x111 0;
+       set x112 0; set x113 0; set x114 0; set x115 0;
+       set x116 0; set x117 0; set x118 0; set x119 0;
+       set x120 0; set x121 0; set x122 0; set x123 0;
+       set x124 0; set x125 0; set x126 0; set x127 0;
+       set x128 0; set x129 0; set x130 0; set x131 0;
+       set x132 0; set x133 0; set x134 0; set x135 0;
+       set x136 0; set x137 0; set x138 0; set x139 0;
+       set x140 0; set x141 0; set x142 0; set x143 0;
+       set x144 0; set x145 0; set x146 0; set x147 0;
+       set x148 0; set x149 0; set x150 0; set x151 0;
+       set x152 0; set x153 0; set x154 0; set x155 0;
+       set x156 0; set x157 0; set x158 0; set x159 0;
+       set x160 0; set x161 0; set x162 0; set x163 0;
+       set x164 0; set x165 0; set x166 0; set x167 0;
+       set x168 0; set x169 0; set x170 0; set x171 0;
+       set x172 0; set x173 0; set x174 0; set x175 0;
+       set x176 0; set x177 0; set x178 0; set x179 0;
+       set x180 0; set x181 0; set x182 0; set x183 0;
+       set x184 0; set x185 0; set x186 0; set x187 0;
+       set x188 0; set x189 0; set x190 0; set x191 0;
+       set x192 0; set x193 0; set x194 0; set x195 0;
+       set x196 0; set x197 0; set x198 0; set x199 0;
+       set x200 0; set x201 0; set x202 0; set x203 0;
+       set x204 0; set x205 0; set x206 0; set x207 0;
+       set x208 0; set x209 0; set x210 0; set x211 0;
+       set x212 0; set x213 0; set x214 0; set x215 0;
+       set x216 0; set x217 0; set x218 0; set x219 0;
+       set x220 0; set x221 0; set x222 0; set x223 0;
+       set x224 0; set x225 0; set x226 0; set x227 0;
+       set x228 0; set x229 0; set x230 0; set x231 0;
+       set x232 0; set x233 0; set x234 0; set x235 0;
+       set x236 0; set x237 0; set x238 0; set x239 0;
+       set x240 0; set x241 0; set x242 0; set x243 0;
+       set x244 0; set x245 0; set x246 0; set x247 0;
+       set x248 0; set x249 0; set x250 0; set x251 0;
        set x252 0; set x253 0; set x254 0; set x255 0;
        set x {{1 2} {3 4}}
        lset x {1 1} 5
@@ -145,69 +145,69 @@ test lsetComp-2.6 {lset, compiled, list of args, array, one-byte offset} {
 
 test lsetComp-2.7 {lset, compiled, list of args, array, four-byte offset} {
     evalInProc {
-       set x0 0; set x1 0; set x2 0; set x3 0; 
-       set x4 0; set x5 0; set x6 0; set x7 0; 
-       set x8 0; set x9 0; set x10 0; set x11 0; 
-       set x12 0; set x13 0; set x14 0; set x15 0; 
-       set x16 0; set x17 0; set x18 0; set x19 0; 
-       set x20 0; set x21 0; set x22 0; set x23 0; 
-       set x24 0; set x25 0; set x26 0; set x27 0; 
-       set x28 0; set x29 0; set x30 0; set x31 0; 
-       set x32 0; set x33 0; set x34 0; set x35 0; 
-       set x36 0; set x37 0; set x38 0; set x39 0; 
-       set x40 0; set x41 0; set x42 0; set x43 0; 
-       set x44 0; set x45 0; set x46 0; set x47 0; 
-       set x48 0; set x49 0; set x50 0; set x51 0; 
-       set x52 0; set x53 0; set x54 0; set x55 0; 
-       set x56 0; set x57 0; set x58 0; set x59 0; 
-       set x60 0; set x61 0; set x62 0; set x63 0; 
-       set x64 0; set x65 0; set x66 0; set x67 0; 
-       set x68 0; set x69 0; set x70 0; set x71 0; 
-       set x72 0; set x73 0; set x74 0; set x75 0; 
-       set x76 0; set x77 0; set x78 0; set x79 0; 
-       set x80 0; set x81 0; set x82 0; set x83 0; 
-       set x84 0; set x85 0; set x86 0; set x87 0; 
-       set x88 0; set x89 0; set x90 0; set x91 0; 
-       set x92 0; set x93 0; set x94 0; set x95 0; 
-       set x96 0; set x97 0; set x98 0; set x99 0; 
-       set x100 0; set x101 0; set x102 0; set x103 0; 
-       set x104 0; set x105 0; set x106 0; set x107 0; 
-       set x108 0; set x109 0; set x110 0; set x111 0; 
-       set x112 0; set x113 0; set x114 0; set x115 0; 
-       set x116 0; set x117 0; set x118 0; set x119 0; 
-       set x120 0; set x121 0; set x122 0; set x123 0; 
-       set x124 0; set x125 0; set x126 0; set x127 0; 
-       set x128 0; set x129 0; set x130 0; set x131 0; 
-       set x132 0; set x133 0; set x134 0; set x135 0; 
-       set x136 0; set x137 0; set x138 0; set x139 0; 
-       set x140 0; set x141 0; set x142 0; set x143 0; 
-       set x144 0; set x145 0; set x146 0; set x147 0; 
-       set x148 0; set x149 0; set x150 0; set x151 0; 
-       set x152 0; set x153 0; set x154 0; set x155 0; 
-       set x156 0; set x157 0; set x158 0; set x159 0; 
-       set x160 0; set x161 0; set x162 0; set x163 0; 
-       set x164 0; set x165 0; set x166 0; set x167 0; 
-       set x168 0; set x169 0; set x170 0; set x171 0; 
-       set x172 0; set x173 0; set x174 0; set x175 0; 
-       set x176 0; set x177 0; set x178 0; set x179 0; 
-       set x180 0; set x181 0; set x182 0; set x183 0; 
-       set x184 0; set x185 0; set x186 0; set x187 0; 
-       set x188 0; set x189 0; set x190 0; set x191 0; 
-       set x192 0; set x193 0; set x194 0; set x195 0; 
-       set x196 0; set x197 0; set x198 0; set x199 0; 
-       set x200 0; set x201 0; set x202 0; set x203 0; 
-       set x204 0; set x205 0; set x206 0; set x207 0; 
-       set x208 0; set x209 0; set x210 0; set x211 0; 
-       set x212 0; set x213 0; set x214 0; set x215 0; 
-       set x216 0; set x217 0; set x218 0; set x219 0; 
-       set x220 0; set x221 0; set x222 0; set x223 0; 
-       set x224 0; set x225 0; set x226 0; set x227 0; 
-       set x228 0; set x229 0; set x230 0; set x231 0; 
-       set x232 0; set x233 0; set x234 0; set x235 0; 
-       set x236 0; set x237 0; set x238 0; set x239 0; 
-       set x240 0; set x241 0; set x242 0; set x243 0; 
-       set x244 0; set x245 0; set x246 0; set x247 0; 
-       set x248 0; set x249 0; set x250 0; set x251 0; 
+       set x0 0; set x1 0; set x2 0; set x3 0;
+       set x4 0; set x5 0; set x6 0; set x7 0;
+       set x8 0; set x9 0; set x10 0; set x11 0;
+       set x12 0; set x13 0; set x14 0; set x15 0;
+       set x16 0; set x17 0; set x18 0; set x19 0;
+       set x20 0; set x21 0; set x22 0; set x23 0;
+       set x24 0; set x25 0; set x26 0; set x27 0;
+       set x28 0; set x29 0; set x30 0; set x31 0;
+       set x32 0; set x33 0; set x34 0; set x35 0;
+       set x36 0; set x37 0; set x38 0; set x39 0;
+       set x40 0; set x41 0; set x42 0; set x43 0;
+       set x44 0; set x45 0; set x46 0; set x47 0;
+       set x48 0; set x49 0; set x50 0; set x51 0;
+       set x52 0; set x53 0; set x54 0; set x55 0;
+       set x56 0; set x57 0; set x58 0; set x59 0;
+       set x60 0; set x61 0; set x62 0; set x63 0;
+       set x64 0; set x65 0; set x66 0; set x67 0;
+       set x68 0; set x69 0; set x70 0; set x71 0;
+       set x72 0; set x73 0; set x74 0; set x75 0;
+       set x76 0; set x77 0; set x78 0; set x79 0;
+       set x80 0; set x81 0; set x82 0; set x83 0;
+       set x84 0; set x85 0; set x86 0; set x87 0;
+       set x88 0; set x89 0; set x90 0; set x91 0;
+       set x92 0; set x93 0; set x94 0; set x95 0;
+       set x96 0; set x97 0; set x98 0; set x99 0;
+       set x100 0; set x101 0; set x102 0; set x103 0;
+       set x104 0; set x105 0; set x106 0; set x107 0;
+       set x108 0; set x109 0; set x110 0; set x111 0;
+       set x112 0; set x113 0; set x114 0; set x115 0;
+       set x116 0; set x117 0; set x118 0; set x119 0;
+       set x120 0; set x121 0; set x122 0; set x123 0;
+       set x124 0; set x125 0; set x126 0; set x127 0;
+       set x128 0; set x129 0; set x130 0; set x131 0;
+       set x132 0; set x133 0; set x134 0; set x135 0;
+       set x136 0; set x137 0; set x138 0; set x139 0;
+       set x140 0; set x141 0; set x142 0; set x143 0;
+       set x144 0; set x145 0; set x146 0; set x147 0;
+       set x148 0; set x149 0; set x150 0; set x151 0;
+       set x152 0; set x153 0; set x154 0; set x155 0;
+       set x156 0; set x157 0; set x158 0; set x159 0;
+       set x160 0; set x161 0; set x162 0; set x163 0;
+       set x164 0; set x165 0; set x166 0; set x167 0;
+       set x168 0; set x169 0; set x170 0; set x171 0;
+       set x172 0; set x173 0; set x174 0; set x175 0;
+       set x176 0; set x177 0; set x178 0; set x179 0;
+       set x180 0; set x181 0; set x182 0; set x183 0;
+       set x184 0; set x185 0; set x186 0; set x187 0;
+       set x188 0; set x189 0; set x190 0; set x191 0;
+       set x192 0; set x193 0; set x194 0; set x195 0;
+       set x196 0; set x197 0; set x198 0; set x199 0;
+       set x200 0; set x201 0; set x202 0; set x203 0;
+       set x204 0; set x205 0; set x206 0; set x207 0;
+       set x208 0; set x209 0; set x210 0; set x211 0;
+       set x212 0; set x213 0; set x214 0; set x215 0;
+       set x216 0; set x217 0; set x218 0; set x219 0;
+       set x220 0; set x221 0; set x222 0; set x223 0;
+       set x224 0; set x225 0; set x226 0; set x227 0;
+       set x228 0; set x229 0; set x230 0; set x231 0;
+       set x232 0; set x233 0; set x234 0; set x235 0;
+       set x236 0; set x237 0; set x238 0; set x239 0;
+       set x240 0; set x241 0; set x242 0; set x243 0;
+       set x244 0; set x245 0; set x246 0; set x247 0;
+       set x248 0; set x249 0; set x250 0; set x251 0;
        set x252 0; set x253 0; set x254 0; set x255 0;
        set y(0) {{1 2} {3 4}}
        lset y(0) {1 1} 5
@@ -253,69 +253,69 @@ test lsetComp-3.3 {lset, compiled, flat args, scalar, one-byte offset} {
 
 test lsetComp-3.4 {lset, compiled, scalar, four-byte offset} {
     evalInProc {
-       set x0 0; set x1 0; set x2 0; set x3 0; 
-       set x4 0; set x5 0; set x6 0; set x7 0; 
-       set x8 0; set x9 0; set x10 0; set x11 0; 
-       set x12 0; set x13 0; set x14 0; set x15 0; 
-       set x16 0; set x17 0; set x18 0; set x19 0; 
-       set x20 0; set x21 0; set x22 0; set x23 0; 
-       set x24 0; set x25 0; set x26 0; set x27 0; 
-       set x28 0; set x29 0; set x30 0; set x31 0; 
-       set x32 0; set x33 0; set x34 0; set x35 0; 
-       set x36 0; set x37 0; set x38 0; set x39 0; 
-       set x40 0; set x41 0; set x42 0; set x43 0; 
-       set x44 0; set x45 0; set x46 0; set x47 0; 
-       set x48 0; set x49 0; set x50 0; set x51 0; 
-       set x52 0; set x53 0; set x54 0; set x55 0; 
-       set x56 0; set x57 0; set x58 0; set x59 0; 
-       set x60 0; set x61 0; set x62 0; set x63 0; 
-       set x64 0; set x65 0; set x66 0; set x67 0; 
-       set x68 0; set x69 0; set x70 0; set x71 0; 
-       set x72 0; set x73 0; set x74 0; set x75 0; 
-       set x76 0; set x77 0; set x78 0; set x79 0; 
-       set x80 0; set x81 0; set x82 0; set x83 0; 
-       set x84 0; set x85 0; set x86 0; set x87 0; 
-       set x88 0; set x89 0; set x90 0; set x91 0; 
-       set x92 0; set x93 0; set x94 0; set x95 0; 
-       set x96 0; set x97 0; set x98 0; set x99 0; 
-       set x100 0; set x101 0; set x102 0; set x103 0; 
-       set x104 0; set x105 0; set x106 0; set x107 0; 
-       set x108 0; set x109 0; set x110 0; set x111 0; 
-       set x112 0; set x113 0; set x114 0; set x115 0; 
-       set x116 0; set x117 0; set x118 0; set x119 0; 
-       set x120 0; set x121 0; set x122 0; set x123 0; 
-       set x124 0; set x125 0; set x126 0; set x127 0; 
-       set x128 0; set x129 0; set x130 0; set x131 0; 
-       set x132 0; set x133 0; set x134 0; set x135 0; 
-       set x136 0; set x137 0; set x138 0; set x139 0; 
-       set x140 0; set x141 0; set x142 0; set x143 0; 
-       set x144 0; set x145 0; set x146 0; set x147 0; 
-       set x148 0; set x149 0; set x150 0; set x151 0; 
-       set x152 0; set x153 0; set x154 0; set x155 0; 
-       set x156 0; set x157 0; set x158 0; set x159 0; 
-       set x160 0; set x161 0; set x162 0; set x163 0; 
-       set x164 0; set x165 0; set x166 0; set x167 0; 
-       set x168 0; set x169 0; set x170 0; set x171 0; 
-       set x172 0; set x173 0; set x174 0; set x175 0; 
-       set x176 0; set x177 0; set x178 0; set x179 0; 
-       set x180 0; set x181 0; set x182 0; set x183 0; 
-       set x184 0; set x185 0; set x186 0; set x187 0; 
-       set x188 0; set x189 0; set x190 0; set x191 0; 
-       set x192 0; set x193 0; set x194 0; set x195 0; 
-       set x196 0; set x197 0; set x198 0; set x199 0; 
-       set x200 0; set x201 0; set x202 0; set x203 0; 
-       set x204 0; set x205 0; set x206 0; set x207 0; 
-       set x208 0; set x209 0; set x210 0; set x211 0; 
-       set x212 0; set x213 0; set x214 0; set x215 0; 
-       set x216 0; set x217 0; set x218 0; set x219 0; 
-       set x220 0; set x221 0; set x222 0; set x223 0; 
-       set x224 0; set x225 0; set x226 0; set x227 0; 
-       set x228 0; set x229 0; set x230 0; set x231 0; 
-       set x232 0; set x233 0; set x234 0; set x235 0; 
-       set x236 0; set x237 0; set x238 0; set x239 0; 
-       set x240 0; set x241 0; set x242 0; set x243 0; 
-       set x244 0; set x245 0; set x246 0; set x247 0; 
-       set x248 0; set x249 0; set x250 0; set x251 0; 
+       set x0 0; set x1 0; set x2 0; set x3 0;
+       set x4 0; set x5 0; set x6 0; set x7 0;
+       set x8 0; set x9 0; set x10 0; set x11 0;
+       set x12 0; set x13 0; set x14 0; set x15 0;
+       set x16 0; set x17 0; set x18 0; set x19 0;
+       set x20 0; set x21 0; set x22 0; set x23 0;
+       set x24 0; set x25 0; set x26 0; set x27 0;
+       set x28 0; set x29 0; set x30 0; set x31 0;
+       set x32 0; set x33 0; set x34 0; set x35 0;
+       set x36 0; set x37 0; set x38 0; set x39 0;
+       set x40 0; set x41 0; set x42 0; set x43 0;
+       set x44 0; set x45 0; set x46 0; set x47 0;
+       set x48 0; set x49 0; set x50 0; set x51 0;
+       set x52 0; set x53 0; set x54 0; set x55 0;
+       set x56 0; set x57 0; set x58 0; set x59 0;
+       set x60 0; set x61 0; set x62 0; set x63 0;
+       set x64 0; set x65 0; set x66 0; set x67 0;
+       set x68 0; set x69 0; set x70 0; set x71 0;
+       set x72 0; set x73 0; set x74 0; set x75 0;
+       set x76 0; set x77 0; set x78 0; set x79 0;
+       set x80 0; set x81 0; set x82 0; set x83 0;
+       set x84 0; set x85 0; set x86 0; set x87 0;
+       set x88 0; set x89 0; set x90 0; set x91 0;
+       set x92 0; set x93 0; set x94 0; set x95 0;
+       set x96 0; set x97 0; set x98 0; set x99 0;
+       set x100 0; set x101 0; set x102 0; set x103 0;
+       set x104 0; set x105 0; set x106 0; set x107 0;
+       set x108 0; set x109 0; set x110 0; set x111 0;
+       set x112 0; set x113 0; set x114 0; set x115 0;
+       set x116 0; set x117 0; set x118 0; set x119 0;
+       set x120 0; set x121 0; set x122 0; set x123 0;
+       set x124 0; set x125 0; set x126 0; set x127 0;
+       set x128 0; set x129 0; set x130 0; set x131 0;
+       set x132 0; set x133 0; set x134 0; set x135 0;
+       set x136 0; set x137 0; set x138 0; set x139 0;
+       set x140 0; set x141 0; set x142 0; set x143 0;
+       set x144 0; set x145 0; set x146 0; set x147 0;
+       set x148 0; set x149 0; set x150 0; set x151 0;
+       set x152 0; set x153 0; set x154 0; set x155 0;
+       set x156 0; set x157 0; set x158 0; set x159 0;
+       set x160 0; set x161 0; set x162 0; set x163 0;
+       set x164 0; set x165 0; set x166 0; set x167 0;
+       set x168 0; set x169 0; set x170 0; set x171 0;
+       set x172 0; set x173 0; set x174 0; set x175 0;
+       set x176 0; set x177 0; set x178 0; set x179 0;
+       set x180 0; set x181 0; set x182 0; set x183 0;
+       set x184 0; set x185 0; set x186 0; set x187 0;
+       set x188 0; set x189 0; set x190 0; set x191 0;
+       set x192 0; set x193 0; set x194 0; set x195 0;
+       set x196 0; set x197 0; set x198 0; set x199 0;
+       set x200 0; set x201 0; set x202 0; set x203 0;
+       set x204 0; set x205 0; set x206 0; set x207 0;
+       set x208 0; set x209 0; set x210 0; set x211 0;
+       set x212 0; set x213 0; set x214 0; set x215 0;
+       set x216 0; set x217 0; set x218 0; set x219 0;
+       set x220 0; set x221 0; set x222 0; set x223 0;
+       set x224 0; set x225 0; set x226 0; set x227 0;
+       set x228 0; set x229 0; set x230 0; set x231 0;
+       set x232 0; set x233 0; set x234 0; set x235 0;
+       set x236 0; set x237 0; set x238 0; set x239 0;
+       set x240 0; set x241 0; set x242 0; set x243 0;
+       set x244 0; set x245 0; set x246 0; set x247 0;
+       set x248 0; set x249 0; set x250 0; set x251 0;
        set x252 0; set x253 0; set x254 0; set x255 0;
        set x {{1 2} {3 4}}
        lset x 1 1 5
@@ -338,69 +338,69 @@ test lsetComp-3.6 {lset, compiled, flat args, array, one-byte offset} {
 
 test lsetComp-3.7 {lset, compiled, flat args, array, four-byte offset} {
     evalInProc {
-       set x0 0; set x1 0; set x2 0; set x3 0; 
-       set x4 0; set x5 0; set x6 0; set x7 0; 
-       set x8 0; set x9 0; set x10 0; set x11 0; 
-       set x12 0; set x13 0; set x14 0; set x15 0; 
-       set x16 0; set x17 0; set x18 0; set x19 0; 
-       set x20 0; set x21 0; set x22 0; set x23 0; 
-       set x24 0; set x25 0; set x26 0; set x27 0; 
-       set x28 0; set x29 0; set x30 0; set x31 0; 
-       set x32 0; set x33 0; set x34 0; set x35 0; 
-       set x36 0; set x37 0; set x38 0; set x39 0; 
-       set x40 0; set x41 0; set x42 0; set x43 0; 
-       set x44 0; set x45 0; set x46 0; set x47 0; 
-       set x48 0; set x49 0; set x50 0; set x51 0; 
-       set x52 0; set x53 0; set x54 0; set x55 0; 
-       set x56 0; set x57 0; set x58 0; set x59 0; 
-       set x60 0; set x61 0; set x62 0; set x63 0; 
-       set x64 0; set x65 0; set x66 0; set x67 0; 
-       set x68 0; set x69 0; set x70 0; set x71 0; 
-       set x72 0; set x73 0; set x74 0; set x75 0; 
-       set x76 0; set x77 0; set x78 0; set x79 0; 
-       set x80 0; set x81 0; set x82 0; set x83 0; 
-       set x84 0; set x85 0; set x86 0; set x87 0; 
-       set x88 0; set x89 0; set x90 0; set x91 0; 
-       set x92 0; set x93 0; set x94 0; set x95 0; 
-       set x96 0; set x97 0; set x98 0; set x99 0; 
-       set x100 0; set x101 0; set x102 0; set x103 0; 
-       set x104 0; set x105 0; set x106 0; set x107 0; 
-       set x108 0; set x109 0; set x110 0; set x111 0; 
-       set x112 0; set x113 0; set x114 0; set x115 0; 
-       set x116 0; set x117 0; set x118 0; set x119 0; 
-       set x120 0; set x121 0; set x122 0; set x123 0; 
-       set x124 0; set x125 0; set x126 0; set x127 0; 
-       set x128 0; set x129 0; set x130 0; set x131 0; 
-       set x132 0; set x133 0; set x134 0; set x135 0; 
-       set x136 0; set x137 0; set x138 0; set x139 0; 
-       set x140 0; set x141 0; set x142 0; set x143 0; 
-       set x144 0; set x145 0; set x146 0; set x147 0; 
-       set x148 0; set x149 0; set x150 0; set x151 0; 
-       set x152 0; set x153 0; set x154 0; set x155 0; 
-       set x156 0; set x157 0; set x158 0; set x159 0; 
-       set x160 0; set x161 0; set x162 0; set x163 0; 
-       set x164 0; set x165 0; set x166 0; set x167 0; 
-       set x168 0; set x169 0; set x170 0; set x171 0; 
-       set x172 0; set x173 0; set x174 0; set x175 0; 
-       set x176 0; set x177 0; set x178 0; set x179 0; 
-       set x180 0; set x181 0; set x182 0; set x183 0; 
-       set x184 0; set x185 0; set x186 0; set x187 0; 
-       set x188 0; set x189 0; set x190 0; set x191 0; 
-       set x192 0; set x193 0; set x194 0; set x195 0; 
-       set x196 0; set x197 0; set x198 0; set x199 0; 
-       set x200 0; set x201 0; set x202 0; set x203 0; 
-       set x204 0; set x205 0; set x206 0; set x207 0; 
-       set x208 0; set x209 0; set x210 0; set x211 0; 
-       set x212 0; set x213 0; set x214 0; set x215 0; 
-       set x216 0; set x217 0; set x218 0; set x219 0; 
-       set x220 0; set x221 0; set x222 0; set x223 0; 
-       set x224 0; set x225 0; set x226 0; set x227 0; 
-       set x228 0; set x229 0; set x230 0; set x231 0; 
-       set x232 0; set x233 0; set x234 0; set x235 0; 
-       set x236 0; set x237 0; set x238 0; set x239 0; 
-       set x240 0; set x241 0; set x242 0; set x243 0; 
-       set x244 0; set x245 0; set x246 0; set x247 0; 
-       set x248 0; set x249 0; set x250 0; set x251 0; 
+       set x0 0; set x1 0; set x2 0; set x3 0;
+       set x4 0; set x5 0; set x6 0; set x7 0;
+       set x8 0; set x9 0; set x10 0; set x11 0;
+       set x12 0; set x13 0; set x14 0; set x15 0;
+       set x16 0; set x17 0; set x18 0; set x19 0;
+       set x20 0; set x21 0; set x22 0; set x23 0;
+       set x24 0; set x25 0; set x26 0; set x27 0;
+       set x28 0; set x29 0; set x30 0; set x31 0;
+       set x32 0; set x33 0; set x34 0; set x35 0;
+       set x36 0; set x37 0; set x38 0; set x39 0;
+       set x40 0; set x41 0; set x42 0; set x43 0;
+       set x44 0; set x45 0; set x46 0; set x47 0;
+       set x48 0; set x49 0; set x50 0; set x51 0;
+       set x52 0; set x53 0; set x54 0; set x55 0;
+       set x56 0; set x57 0; set x58 0; set x59 0;
+       set x60 0; set x61 0; set x62 0; set x63 0;
+       set x64 0; set x65 0; set x66 0; set x67 0;
+       set x68 0; set x69 0; set x70 0; set x71 0;
+       set x72 0; set x73 0; set x74 0; set x75 0;
+       set x76 0; set x77 0; set x78 0; set x79 0;
+       set x80 0; set x81 0; set x82 0; set x83 0;
+       set x84 0; set x85 0; set x86 0; set x87 0;
+       set x88 0; set x89 0; set x90 0; set x91 0;
+       set x92 0; set x93 0; set x94 0; set x95 0;
+       set x96 0; set x97 0; set x98 0; set x99 0;
+       set x100 0; set x101 0; set x102 0; set x103 0;
+       set x104 0; set x105 0; set x106 0; set x107 0;
+       set x108 0; set x109 0; set x110 0; set x111 0;
+       set x112 0; set x113 0; set x114 0; set x115 0;
+       set x116 0; set x117 0; set x118 0; set x119 0;
+       set x120 0; set x121 0; set x122 0; set x123 0;
+       set x124 0; set x125 0; set x126 0; set x127 0;
+       set x128 0; set x129 0; set x130 0; set x131 0;
+       set x132 0; set x133 0; set x134 0; set x135 0;
+       set x136 0; set x137 0; set x138 0; set x139 0;
+       set x140 0; set x141 0; set x142 0; set x143 0;
+       set x144 0; set x145 0; set x146 0; set x147 0;
+       set x148 0; set x149 0; set x150 0; set x151 0;
+       set x152 0; set x153 0; set x154 0; set x155 0;
+       set x156 0; set x157 0; set x158 0; set x159 0;
+       set x160 0; set x161 0; set x162 0; set x163 0;
+       set x164 0; set x165 0; set x166 0; set x167 0;
+       set x168 0; set x169 0; set x170 0; set x171 0;
+       set x172 0; set x173 0; set x174 0; set x175 0;
+       set x176 0; set x177 0; set x178 0; set x179 0;
+       set x180 0; set x181 0; set x182 0; set x183 0;
+       set x184 0; set x185 0; set x186 0; set x187 0;
+       set x188 0; set x189 0; set x190 0; set x191 0;
+       set x192 0; set x193 0; set x194 0; set x195 0;
+       set x196 0; set x197 0; set x198 0; set x199 0;
+       set x200 0; set x201 0; set x202 0; set x203 0;
+       set x204 0; set x205 0; set x206 0; set x207 0;
+       set x208 0; set x209 0; set x210 0; set x211 0;
+       set x212 0; set x213 0; set x214 0; set x215 0;
+       set x216 0; set x217 0; set x218 0; set x219 0;
+       set x220 0; set x221 0; set x222 0; set x223 0;
+       set x224 0; set x225 0; set x226 0; set x227 0;
+       set x228 0; set x229 0; set x230 0; set x231 0;
+       set x232 0; set x233 0; set x234 0; set x235 0;
+       set x236 0; set x237 0; set x238 0; set x239 0;
+       set x240 0; set x241 0; set x242 0; set x243 0;
+       set x244 0; set x245 0; set x246 0; set x247 0;
+       set x248 0; set x249 0; set x250 0; set x251 0;
        set x252 0; set x253 0; set x254 0; set x255 0;
        set y(0) {{1 2} {3 4}}
        lset y(0) 1 1 5
index f1758f5..0a147f0 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 12c77e0..e68c4bb 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
+
 set oldTSF $::tcltest::testSingleFile
 set ::tcltest::testSingleFile false
 
index b0edb84..c4bb48d 100644 (file)
@@ -613,7 +613,7 @@ namespace eval ::tcl::test::main {
        variable wait
        chan event $f readable \
                [list set [namespace which -variable wait] "child exit"]
-       set id [after 2000 [list set [namespace which -variable wait] timeout]]
+       set id [after 5000 [list set [namespace which -variable wait] timeout]]
        vwait [namespace which -variable wait]
        after cancel $id
        set wait
@@ -636,7 +636,7 @@ namespace eval ::tcl::test::main {
        variable wait
        chan event $f readable \
                [list set [namespace which -variable wait] "child exit"]
-       set id [after 2000 [list set [namespace which -variable wait] timeout]]
+       set id [after 5000 [list set [namespace which -variable wait] timeout]]
        vwait [namespace which -variable wait]
        after cancel $id
        set wait
@@ -719,7 +719,7 @@ namespace eval ::tcl::test::main {
     } -result "Exit MainLoop\nIn exit\neven 0\n"
 
     test Tcl_Main-5.9 {
-       Tcl_Main: interactive mode: delete interp 
+       Tcl_Main: interactive mode: delete interp
                -> main loop & exit handlers, but no [exit]
     } -constraints {
        exec Tcltest
index a1a3f80..12a4e7f 100644 (file)
@@ -10,7 +10,7 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
+if {"::tcltest" ni [namespace children]} {
     package require tcltest 2.1
     namespace import -force ::tcltest::*
 }
@@ -901,10 +901,10 @@ test mathop-22.2 { bitwise ops on bignums } {
     set exp {}
     foreach d {5 7 2  1 D C  1 F E  0 -D -D  8 -9 -1  -0 -E E} {
         if {[string match "-*" $d]} {
-            set d [format %X [expr 15-0x[string range $d 1 end]]]
-            set val [expr -0x[string repeat $d $dig]-1]
+            set d [format %X [expr {15-"0x[string range $d 1 end]"}]]
+            set val [expr {-"0x[string repeat $d $dig]"-1}]
         } else {
-            set val [expr 0x[string repeat $d $dig]]
+            set val [expr {"0x[string repeat $d $dig]"}]
         }
         lappend exp $val
     }
index d4ece74..8b6e1b7 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 1c3ce58..9a6eac0 100644 (file)
 # Note that after running these tests, entries will be left behind in the
 # message catalogs for locales foo, foo_BAR, and foo_BAR_baz.
 
-package require Tcl 8.5-
-if {[catch {package require tcltest 2}]} {
-    puts stderr "Skipping tests in [info script].  tcltest 2 required."
-    return
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
 }
+
 if {[catch {package require msgcat 1.6}]} {
     puts stderr "Skipping tests in [info script].  No msgcat 1.6 found to test."
     return
index 1d6a805..e4715f8 100644 (file)
@@ -749,13 +749,13 @@ test namespace-old-9.14 {imported commands can be removed} {
 } {{} 1 {invalid command name "cmd1"}}
 test namespace-old-9.15 {existing commands can't be overwritten} {
     proc cmd1 {x y} {
-        return [expr $x+$y]
+        return [expr {$x+$y}]
     }
     list [catch {namespace import test_ns_import::cmd?} msg] $msg \
          [cmd1 3 5]
 } {1 {can't import command "cmd1": already exists} 8}
 test namespace-old-9.16 {use "-force" option to override existing commands} {
-    proc cmd1 {x y} { return [expr $x+$y] }
+    proc cmd1 {x y} { return [expr {$x+$y}] }
     list [cmd1 3 5] \
          [namespace import -force test_ns_import::cmd?] \
          [cmd1 3 5]
index dd71697..8209cf3 100644 (file)
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 testConstraint memory [llength [info commands memory]]
 
 ::tcltest::loadTestedCommands
@@ -56,7 +58,7 @@ test namespace-2.2 {Tcl_GetCurrentNamespace} {
 
 test namespace-3.1 {Tcl_GetGlobalNamespace} {
     namespace eval test_ns_1 {namespace eval foo {namespace eval bar {} } }
-    # namespace children uses Tcl_GetGlobalNamespace 
+    # namespace children uses Tcl_GetGlobalNamespace
     namespace eval test_ns_1 {namespace children foo b*}
 } {::test_ns_1::foo::bar}
 
@@ -108,7 +110,7 @@ test namespace-6.2 {Tcl_CreateNamespace, odd number of :'s in name is okay} {
          [namespace eval test_ns_2:::::foo {namespace current}]
 } {::test_ns_1::foo ::test_ns_2::foo}
 test namespace-6.3 {Tcl_CreateNamespace, trailing ::s in ns name are ignored} {
-    list [catch {namespace eval test_ns_7::: {namespace current}} msg] $msg 
+    list [catch {namespace eval test_ns_7::: {namespace current}} msg] $msg
 } {0 ::test_ns_7}
 test namespace-6.4 {Tcl_CreateNamespace, trailing ::s in ns name are ignored} {
     catch {namespace delete {*}[namespace children :: test_ns_*]}
@@ -179,21 +181,21 @@ test namespace-7.6 {recursive Tcl_DeleteNamespace, no active call frames in ns}
     namespace delete test_ns_2
 } {}
 test namespace-7.7 {Bug 1655305} -setup {
-    interp create slave
+    interp create child
     # Can't invoke through the ensemble, since deleting the global namespace
     # (indirectly, via deleting ::tcl) deletes the ensemble.
-    slave eval {rename ::tcl::info::commands ::infocommands}
-    slave hide infocommands
-    slave eval {
+    child eval {rename ::tcl::info::commands ::infocommands}
+    child hide infocommands
+    child eval {
        proc foo {} {
            namespace delete ::
        }
     }
 } -body {
-    slave eval foo
-    slave invokehidden infocommands
+    child eval foo
+    child invokehidden infocommands
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {}
 
 test namespace-7.8 {Bug ba1419303b4c} -setup {
@@ -205,7 +207,7 @@ test namespace-7.8 {Bug ba1419303b4c} -setup {
        namespace delete ns1
     }
 } -body {
-    # No segmentation fault given --enable-symbols=mem. 
+    # No segmentation fault given --enable-symbols=mem.
     namespace delete ns1
 } -result {}
 
@@ -269,28 +271,28 @@ test namespace-8.4 {TclTeardownNamespace, cmds imported from deleted ns go away}
          [info commands test_ns_import::*]
 } [list [lsort {::test_ns_import::p ::test_ns_import::cmd1 ::test_ns_import::cmd2}] {} ::test_ns_import::p]
 test namespace-8.5 {TclTeardownNamespace: preserve errorInfo; errorCode values} {
-    interp create slave
-    slave eval {trace add execution error leave {namespace delete :: ;#}}
-    catch {slave eval error foo bar baz}
-    interp delete slave
+    interp create child
+    child eval {trace add execution error leave {namespace delete :: ;#}}
+    catch {child eval error foo bar baz}
+    interp delete child
     set ::errorInfo
 } {bar
     invoked from within
-"slave eval error foo bar baz"}
+"child eval error foo bar baz"}
 test namespace-8.6 {TclTeardownNamespace: preserve errorInfo; errorCode values} {
-    interp create slave 
-    slave eval {trace add variable errorCode write {namespace delete :: ;#}}
-    catch {slave eval error foo bar baz}
-    interp delete slave
+    interp create child
+    child eval {trace add variable errorCode write {namespace delete :: ;#}}
+    catch {child eval error foo bar baz}
+    interp delete child
     set ::errorInfo
 } {bar
     invoked from within
-"slave eval error foo bar baz"}
+"child eval error foo bar baz"}
 test namespace-8.7 {TclTeardownNamespace: preserve errorInfo; errorCode values} {
-    interp create slave
-    slave eval {trace add execution error leave {namespace delete :: ;#}}
-    catch {slave eval error foo bar baz}
-    interp delete slave
+    interp create child
+    child eval {trace add execution error leave {namespace delete :: ;#}}
+    catch {child eval error foo bar baz}
+    interp delete child
     set ::errorCode
 } baz
 
@@ -1098,17 +1100,17 @@ test namespace-22.5 {NamespaceCodeCmd, in other namespace} {
         namespace code cmd
     }
 } {::namespace inscope ::test_ns_1 cmd}
-test namespace-22.6 {NamespaceCodeCmd, in other namespace} { 
-    namespace eval test_ns_1 { 
-       variable v 42 
-    } 
-    namespace eval test_ns_2 { 
-       proc namespace args {} 
-    } 
-    namespace eval test_ns_2 [namespace eval test_ns_1 { 
-       namespace code {set v} 
-    }] 
-} {42} 
+test namespace-22.6 {NamespaceCodeCmd, in other namespace} {
+    namespace eval test_ns_1 {
+       variable v 42
+    }
+    namespace eval test_ns_2 {
+       proc namespace args {}
+    }
+    namespace eval test_ns_2 [namespace eval test_ns_1 {
+       namespace code {set v}
+    }]
+} {42}
 test namespace-22.7 {NamespaceCodeCmd, Bug 3202171} {
     namespace eval demo {
        proc namespace args {puts $args}
@@ -1659,7 +1661,7 @@ test namespace-40.1 {Ignoring namespace proc "unknown"} -setup {
     namespace eval ns {proc unknown args {return local}}
     list [namespace eval ns aaa bbb] [namespace eval ns aaa]
 } -cleanup {
-    rename unknown {}   
+    rename unknown {}
     rename _unknown unknown
     namespace delete ns
 } -result {global global}
@@ -1670,7 +1672,7 @@ test namespace-41.1 {Shadowing byte-compiled commands, Bug: 231259} {
        set res {}
        proc test {} {
            set ::g 0
-       }  
+       }
        lappend ::res [test]
        proc set {a b} {
            ::set a [incr b]
@@ -2797,9 +2799,9 @@ test namespace-51.15 {namespace resolution path control} -body {
     namespace delete ::test_ns_2
 }
 test namespace-51.16 {Bug 1566526} {
-    interp create slave
-    slave eval namespace eval demo namespace path ::
-    interp delete slave
+    interp create child
+    child eval namespace eval demo namespace path ::
+    interp delete child
 } {}
 test namespace-51.17 {resolution epoch handling: Bug 2898722} -setup {
     set result {}
@@ -3000,19 +3002,19 @@ test namespace-52.11 {unknown: with TCL_EVAL_INVOKE} -setup {
        }
     }
     catch {rename ::noSuchCommand {}}
-    set ::slave [interp create]
+    set ::child [interp create]
 } -body {
-    $::slave alias bar noSuchCommand
+    $::child alias bar noSuchCommand
     namespace eval test_ns_1 {
        namespace unknown unknown
        proc unknown args {
            return FAIL
        }
-       $::slave eval bar
+       $::child eval bar
     }
 } -cleanup {
-    interp delete $::slave
-    unset ::slave
+    interp delete $::child
+    unset ::child
     namespace delete test_ns_1
     rename ::unknown {}
     rename unknown.save ::unknown
@@ -3337,6 +3339,49 @@ test namespace-56.5 {Bug 8b9854c3d8} -setup {
     namespace delete namespace-56.5
 } -result 1
 
+
+
+test namespace-57.0 {
+    an imported alias should be usable in the deletion trace for the alias
+
+    see 29e8848eb976
+} -body {
+    variable res {}
+    namespace eval ns2 {
+       namespace export *
+       proc p1 {oldname newname op} {
+           return success
+       }
+
+       interp alias {} [namespace current]::p2 {} [namespace which p1]
+    }
+
+
+    namespace eval ns3 {
+       namespace import ::ns2::p2
+    }
+
+
+    set ondelete [list apply [list {oldname newname op} {
+       variable res
+       catch {
+               ns3::p2 $oldname $newname $op
+       } cres
+       lappend res $cres
+    } [namespace current]]]
+
+
+    trace add command ::ns2::p2 delete $ondelete
+    rename ns2::p2 {}
+    return $res
+} -cleanup {
+    unset res
+    namespace delete ns2
+    namespace delete ns3
+} -result success
+
+
+
 \f
 # cleanup
 catch {rename cmd1 {}}
index d2b9123..7375f83 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 09061d2..e420b06 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 7273b40..e5fec9a 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -36,7 +36,7 @@ test obj-1.1 {Tcl_AppendAllObjTypes, and InitTypeTable, Tcl_RegisterObjType} tes
        string
     } {
         set first [string first $t [testobj types]]
-        set r [expr {$r && ($first != -1)}]
+        set r [expr {$r && ($first >= 0)}]
     }
     set result $r
 } {1}
index 77fca68..0f58c5d 100644 (file)
@@ -8,8 +8,8 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 package require TclOO 1.0.3
-package require tcltest 2
-if {"::tcltest" in [namespace children]} {
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -113,8 +113,8 @@ test oo-0.8 {leak in variable management} -setup {
 } -result 0
 test oo-0.9 {various types of presence of the TclOO package} {
     list [lsearch -nocase -all -inline [package names] tcloo] \
-       [package present TclOO] [package versions TclOO]
-} [list TclOO $::oo::patchlevel $::oo::patchlevel]
+       [package present TclOO] [expr {$::oo::patchlevel in [package versions TclOO]}]
+} [list TclOO $::oo::patchlevel 1]
 
 test oo-1.1 {basic test of OO functionality: no classes} {
     set result {}
@@ -142,7 +142,7 @@ test oo-1.4 {basic test of OO functionality} -body {
     oo::object create {}
 } -returnCodes 1 -result {object name must not be empty}
 test oo-1.4.1 {fully-qualified nested name} -body {
-    oo::object create ::one::two::three 
+    oo::object create ::one::two::three
 } -result {::one::two::three}
 test oo-1.4.2 {automatic command name has same name as namespace} -body {
     set obj [oo::object new]
@@ -306,15 +306,49 @@ test oo-1.18.2 {Bug 75b8433707: memory leak in oo-1.18} -setup {
     rename test-oo-1.18 {}
 } -result 0
 test oo-1.18.3 {Bug 21c144f0f5} -setup {
-    interp create slave
+    interp create child
 } -body {
-    slave eval {
+    child eval {
        oo::define [oo::class create foo] superclass oo::class
        oo::class destroy
     }
 } -cleanup {
-    interp delete slave
-} 
+    interp delete child
+}
+test oo-1.18.4 {correct handling of cleanup in superclass set error} -setup {
+    interp create child
+} -body {
+    child eval {
+       oo::class create A
+       oo::class create B {
+           superclass oo::class
+           constructor {} {
+               next {superclass A}
+               next {superclass -append A}
+           }
+       }
+       [B create C] create d
+    }
+} -returnCodes error -cleanup {
+    interp delete child
+} -result {class should only be a direct superclass once}
+test oo-1.18.5 {correct handling of cleanup in superclass set error} -setup {
+    interp create child
+} -body {
+    child eval {
+       oo::class create A
+       oo::class create B {
+           superclass oo::class
+           constructor {c} {
+               next {superclass A}
+               next [list superclass -append {*}$c]
+           }
+       }
+       [B create C {B C}] create d
+    }
+} -returnCodes error -cleanup {
+    interp delete child
+} -result {attempt to form circular dependency graph}
 test oo-1.19 {basic test of OO functionality: teardown order} -body {
     oo::object create o
     namespace delete [info object namespace o]
@@ -1336,16 +1370,16 @@ test oo-7.8 {OO: next at the end of the method chain} -setup {
 } -result {foo2 foo 1 {no next method implementation}}
 test oo-7.9 {OO: defining inheritance in namespaces} -setup {
     set ::result {}
-    oo::class create ::master
+    oo::class create ::parent
     namespace eval ::foo {
-       oo::class create mixin {superclass ::master}
+       oo::class create mixin {superclass ::parent}
     }
 } -cleanup {
-    ::master destroy
+    ::parent destroy
     namespace delete ::foo
 } -body {
     namespace eval ::foo {
-       oo::class create bar {superclass master}
+       oo::class create bar {superclass parent}
        oo::class create boo
        oo::define boo {superclass bar}
        oo::define boo {mixin mixin}
@@ -1864,7 +1898,7 @@ test oo-13.5 {OO: changing an object's class: non-class to class} -setup {
        class oo::class
     }
     oo::define fooObj {
-       method x {} {expr 1+2+3}
+       method x {} {expr {1+2+3}}
     }
     [fooObj new] x
 } -cleanup {
@@ -1876,7 +1910,7 @@ test oo-13.6 {OO: changing an object's class: class to non-class} -setup {
 } -body {
     set result dangling
     oo::define foo {
-       method x {} {expr 1+2+3}
+       method x {} {expr {1+2+3}}
     }
     oo::class create boo {
        superclass foo
@@ -1899,7 +1933,7 @@ test oo-13.7 {OO: changing an object's class} -setup {
 } -body {
     oo::define bar method x {} {return ok}
     oo::define foo {
-       method x {} {expr 1+2+3}
+       method x {} {expr {1+2+3}}
        self mixin foo
     }
     lappend result [foo x]
@@ -1913,7 +1947,7 @@ test oo-13.8 {OO: changing an object's class to itself} -setup {
     oo::class create foo
 } -body {
     oo::define foo {
-       method x {} {expr 1+2+3}
+       method x {} {expr {1+2+3}}
     }
     oo::objdefine foo class foo
 } -cleanup {
@@ -2032,18 +2066,18 @@ test oo-14.5 {OO and mixins and filters - advanced case} -setup {
     mix destroy
 } -result >>foobar<<
 test oo-14.6 {OO and mixins of mixins - Bug 1960703} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create A {
-       superclass master
+       superclass parent
        method egg {} {
            return chicken
        }
     }
     oo::class create B {
-       superclass master
+       superclass parent
        mixin A
        method bar {} {
            # mixin from A
@@ -2051,7 +2085,7 @@ test oo-14.6 {OO and mixins of mixins - Bug 1960703} -setup {
        }
     }
     oo::class create C {
-       superclass master
+       superclass parent
        mixin B
        method foo {} {
            # mixin from B
@@ -2061,12 +2095,12 @@ test oo-14.6 {OO and mixins of mixins - Bug 1960703} -setup {
     [C new] foo
 } -result chicken
 test oo-14.7 {OO and filters from mixins of mixins} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create A {
-       superclass master
+       superclass parent
        method egg {} {
            return chicken
        }
@@ -2077,7 +2111,7 @@ test oo-14.7 {OO and filters from mixins of mixins} -setup {
        }
     }
     oo::class create B {
-       superclass master
+       superclass parent
        mixin A
        filter f
        method bar {} {
@@ -2086,7 +2120,7 @@ test oo-14.7 {OO and filters from mixins of mixins} -setup {
        }
     }
     oo::class create C {
-       superclass master
+       superclass parent
        mixin B
        filter f
        method foo {} {
@@ -2098,18 +2132,18 @@ test oo-14.7 {OO and filters from mixins of mixins} -setup {
 } -result {(foo) (bar) (egg) chicken (egg) (bar) (foo)}
 test oo-14.8 {OO: class mixin order - Bug 1998221} -setup {
     set ::result {}
-    oo::class create master {
+    oo::class create parent {
        method test {} {}
     }
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create mix {
-       superclass master
+       superclass parent
        method test {} {lappend ::result mix; next; return $::result}
     }
     oo::class create cls {
-       superclass master
+       superclass parent
        mixin mix
        method test {} {lappend ::result cls; next; return $::result}
     }
@@ -2257,7 +2291,7 @@ test oo-15.10 {variable binding must not bleed through oo::copy} -setup {
 } -body {
     set obj1 [FooClass new]
     oo::objdefine $obj1 {
-       variable var 
+       variable var
        method m {} {
            set var foo
        }
@@ -2306,7 +2340,7 @@ test oo-15.13.1 {
 } -cleanup {
     Cls destroy
     Cls2 destroy
-} -result done 
+} -result done
 test oo-15.13.2 {OO: object cloning with target NS} -setup {
     oo::class create Super
     oo::class create Cls {superclass Super}
@@ -2334,7 +2368,7 @@ test oo-15.15 {method cloning must ensure that there is a string representation
 } -body {
     cls create foo
     oo::objdefine foo {
-       method m1 {} [string map {a b} {return hello}] 
+       method m1 {} [string map {a b} {return hello}]
     }
     [oo::copy foo] m1
 } -cleanup {
@@ -2744,13 +2778,13 @@ test oo-18.7 {OO: objdefine command support} -setup {
     invoked from within
 "oo::objdefine inst {rename ::inst ::INST;error foo}"}}
 test oo-18.8 {OO: define/self command support} -setup {
-    oo::class create master
-    oo::class create ::foo {superclass master}
+    oo::class create parent
+    oo::class create ::foo {superclass parent}
 } -body {
     catch {oo::define foo {rename ::foo ::bar; self {error foobar}}} msg opt
     dict get $opt -errorinfo
 } -cleanup {
-    master destroy
+    parent destroy
 } -result {foobar
     while executing
 "error foobar"
@@ -2761,15 +2795,15 @@ test oo-18.8 {OO: define/self command support} -setup {
     invoked from within
 "oo::define foo {rename ::foo ::bar; self {error foobar}}"}
 test oo-18.9 {OO: define/self command support} -setup {
-    oo::class create master
+    oo::class create parent
     set c [oo::class create now_this_is_a_very_very_long_class_name_indeed {
-        superclass master
+        superclass parent
     }]
 } -body {
     catch {oo::define $c {error err}} msg opt
     dict get $opt -errorinfo
 } -cleanup {
-    master destroy
+    parent destroy
 } -result {err
     while executing
 "error err"
@@ -2777,13 +2811,13 @@ test oo-18.9 {OO: define/self command support} -setup {
     invoked from within
 "oo::define $c {error err}"}
 test oo-18.10 {OO: define/self command support} -setup {
-    oo::class create master
-    oo::class create ::foo {superclass master}
+    oo::class create parent
+    oo::class create ::foo {superclass parent}
 } -body {
     catch {oo::define foo {self {rename ::foo {}; error foobar}}} msg opt
     dict get $opt -errorinfo
 } -cleanup {
-    master destroy
+    parent destroy
 } -result {foobar
     while executing
 "error foobar"
@@ -2794,13 +2828,13 @@ test oo-18.10 {OO: define/self command support} -setup {
     invoked from within
 "oo::define foo {self {rename ::foo {}; error foobar}}"}
 test oo-18.11 {OO: define/self command support} -setup {
-    oo::class create master
-    oo::class create ::foo {superclass master}
+    oo::class create parent
+    oo::class create ::foo {superclass parent}
 } -body {
     catch {oo::define foo {rename ::foo {}; self {error foobar}}} msg opt
     dict get $opt -errorinfo
 } -cleanup {
-    master destroy
+    parent destroy
 } -result {this command cannot be called when the object has been deleted
     while executing
 "self {error foobar}"
@@ -2995,7 +3029,7 @@ test oo-20.10 {OO: variable and varname methods refer to same things} -setup {
 test oo-20.11 {OO: variable mustn't crash when recursing} -body {
     oo::class create A {
        constructor {name} {
-           my variable np_name 
+           my variable np_name
            set np_name $name
        }
        method copy {nm} {
@@ -3010,7 +3044,7 @@ test oo-20.11 {OO: variable mustn't crash when recursing} -body {
                        lappend objs [$ref copy {}]
                    }
                    $cpy prop $var $objs
-               } else { 
+               } else {
                    $cpy prop $var $val
                }
            }
@@ -3423,12 +3457,12 @@ test oo-27.2 {variables declaration - object introspection} -setup {
     info object variables foo
 } -result {a b c}
 test oo-27.3 {variables declaration - basic behaviour} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x!
        constructor {} {set x! 1}
        method y {} {incr x!}
@@ -3438,13 +3472,13 @@ test oo-27.3 {variables declaration - basic behaviour} -setup {
     bar y
 } -result 3
 test oo-27.4 {variables declaration - destructors too} -setup {
-    oo::class create master
+    oo::class create parent
     set result bad!
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x!
        constructor {} {set x! 1}
        method y {} {incr x!}
@@ -3469,12 +3503,12 @@ test oo-27.5 {variables declaration - object-bound variables} -setup {
     foo y
 } -result 2
 test oo-27.6 {variables declaration - non-interference of levels} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x!
        constructor {} {set x! 1}
        method y {} {incr x!}
@@ -3489,12 +3523,12 @@ test oo-27.6 {variables declaration - non-interference of levels} -setup {
     list [bar y] [lsort [info object vars bar]] [bar eval {info vars *!}]
 } -result {{3 2 y! {}} {x! y!} {x! y!}}
 test oo-27.7 {variables declaration - one underlying variable space} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x!
        constructor {} {set x! 1}
        method y {} {incr x!}
@@ -3521,12 +3555,12 @@ test oo-27.9 {variables declaration - error cases - arrays} -body {
     oo::define oo::object variable bad(var)
 } -returnCodes error -result {invalid declared variable name "bad(var)": must not refer to an array element}
 test oo-27.10 {variables declaration - no instance var leaks with class resolvers} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable clsvar
        constructor {} {
            set clsvar 0
@@ -3549,12 +3583,12 @@ test oo-27.10 {variables declaration - no instance var leaks with class resolver
     list [inst1 value] [inst2 value]
 } -result {3 2}
 test oo-27.11 {variables declaration - no instance var leaks with class resolvers} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable clsvar
        constructor {} {
            set clsvar 0
@@ -3622,12 +3656,12 @@ test oo-27.13 {variables declaration: Bug 3185009: require refcount management}
     foo destroy
 } -result {0 7 1 7 {} 0 1 {can't read "x": no such variable}}
 test oo-27.14 {variables declaration - multiple use} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x
        variable y
        method boo {} {
@@ -3638,12 +3672,12 @@ test oo-27.14 {variables declaration - multiple use} -setup {
     list [bar boo] [bar boo]
 } -result {1,1 2,2}
 test oo-27.15 {variables declaration - multiple use} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable
        variable x y
        method boo {} {
@@ -3654,12 +3688,12 @@ test oo-27.15 {variables declaration - multiple use} -setup {
     list [bar boo] [bar boo]
 } -result {1,1 2,2}
 test oo-27.16 {variables declaration - multiple use} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x
        variable -clear
        variable y
@@ -3671,12 +3705,12 @@ test oo-27.16 {variables declaration - multiple use} -setup {
     list [bar boo] [bar boo]
 } -result {1,1 1,2}
 test oo-27.17 {variables declaration - multiple use} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x
        variable -set y
        method boo {} {
@@ -3687,12 +3721,12 @@ test oo-27.17 {variables declaration - multiple use} -setup {
     list [bar boo] [bar boo]
 } -result {1,1 1,2}
 test oo-27.18 {variables declaration - multiple use} -setup {
-    oo::class create master
+    oo::class create parent
 } -cleanup {
-    master destroy
+    parent destroy
 } -body {
     oo::class create foo {
-       superclass master
+       superclass parent
        variable x
        variable -? y
        method boo {} {
@@ -3790,12 +3824,12 @@ test oo-27.22 {variables declaration uniqueifies: Bug 3396896} -setup {
 } -result {v t}
 test oo-27.23 {variable resolver leakage: Bug 1493a43044} -setup {
     oo::class create Super
-    oo::class create Master {
+    oo::class create parent {
        superclass Super
        variable member1 member2
        constructor {} {
-           set member1 master1
-           set member2 master2
+           set member1 parent1
+           set member2 parent2
        }
        method getChild {} {
            Child new [self]
@@ -3816,10 +3850,10 @@ test oo-27.23 {variable resolver leakage: Bug 1493a43044} -setup {
        method result {} {return $result}
     }
 } -body {
-    [[Master new] getChild] result
+    [[parent new] getChild] result
 } -cleanup {
     Super destroy
-} -result {master1 master2 master1 master2 master1 master2 master1 master2}
+} -result {parent1 parent2 parent1 parent2 parent1 parent2 parent1 parent2}
 
 # A feature that's not supported because the mechanism may change without
 # warning, but is supposed to work...
@@ -4147,7 +4181,7 @@ test oo-35.6 {
     return done
 } -cleanup {
     rename obj {}
-} -result done 
+} -result done
 
 
 \f
index 6a48d28..0ec7cdd 100644 (file)
@@ -8,8 +8,8 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 package require TclOO 1.0.3
-package require tcltest 2
-if {"::tcltest" in [namespace children]} {
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -882,9 +882,9 @@ test oo-call-3.4 {current call introspection: in destructors} -setup {
 #      caller
 set testopts {
     -setup {
-       oo::class create Master
+       oo::class create Parent
        oo::class create Foo {
-           superclass Master
+           superclass Parent
            method bar {} {
                puts abc
                tailcall puts hi
@@ -892,11 +892,11 @@ set testopts {
            }
        }
        oo::class create Foo2 {
-           superclass Master
+           superclass Parent
        }
     }
     -cleanup {
-       Master destroy
+       Parent destroy
     }
 }
 
index 2732d40..419e6bf 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
 # the package we are going to test
-package require opt 0.4.6
+package require opt 0.4.8
 
 # we are using implementation specifics to test the package
 
@@ -27,8 +27,8 @@ package require opt 0.4.6
 set n $::tcl::OptDescN
 
 test opt-1.1 {OptKeyRegister / check that auto allocation is skipping existing keys} {
-    list [::tcl::OptKeyRegister {} $n] [::tcl::OptKeyRegister {} [expr $n+1]] [::tcl::OptKeyRegister {}]
-} "$n [expr $n+1] [expr $n+2]"
+    list [::tcl::OptKeyRegister {} $n] [::tcl::OptKeyRegister {} [expr {$n+1}]] [::tcl::OptKeyRegister {}]
+} "$n [expr {$n+1}] [expr {$n+2}]"
 
 test opt-2.1 {OptKeyDelete} {
     list [::tcl::OptKeyRegister {} testkey] \
index bc73003..a147457 100644 (file)
@@ -17,9 +17,9 @@ if {"::tcltest" ni [namespace children]} {
     namespace import -force ::tcltest::*
 }
 
-# Do all this in a slave interp to avoid garbaging the package list
+# Do all this in a child interp to avoid garbaging the package list
 set i [interp create]
-tcltest::loadIntoSlaveInterpreter $i {*}$argv
+tcltest::loadIntoChildInterpreter $i {*}$argv
 interp eval $i {
 namespace import -force ::tcltest::*
 package forget {*}[package names]
@@ -862,15 +862,15 @@ test package-4.56 {Tcl_PackageCmd procedure, "vsatisfies" option} -body {
 # No tests for FindPackage; can't think up anything detectable errors.
 
 test package-5.1 {TclFreePackageInfo procedure} {
-    interp create slave
-    slave eval {
+    interp create child
+    child eval {
        package ifneeded t 2.3 x
        package ifneeded t 2.4 y
        package ifneeded x 3.1 z
        package provide q 4.3
        package unknown "will this get freed?"
     }
-    interp delete slave
+    interp delete child
 } {}
 test package-5.2 {TclFreePackageInfo procedure} -body {
     interp create foo
index d73c725..4370acb 100644 (file)
@@ -369,7 +369,7 @@ test parse-8.8 {Tcl_EvalObjv procedure, async handlers} -constraints {
     variable ::aresult
     variable ::acode
     proc async1 {result code} {
-       variable ::aresult 
+       variable ::aresult
        variable ::acode
        set aresult $result
        set acode $code
@@ -405,14 +405,14 @@ test parse-8.11 {Tcl_EvalObjv procedure, TCL_EVAL_INVOKE} testevalobjv {
     proc ::unknown args {lappend ::info [info level]; uplevel 1 foo}
     proc ::foo args {lappend ::info global}
     catch {rename ::noSuchCommand {}}
-    set ::slave [interp create]
-    $::slave alias bar noSuchCommand
+    set ::child [interp create]
+    $::child alias bar noSuchCommand
     set ::info {}
     namespace eval test_ns_1 {
        proc foo args {lappend ::info namespace}
-       $::slave eval bar
-       testevalobjv 1 [list $::slave eval bar]
-       uplevel #0 [list $::slave eval bar]
+       $::child eval bar
+       testevalobjv 1 [list $::child eval bar]
+       uplevel #0 [list $::child eval bar]
     }
     namespace delete test_ns_1
     rename ::foo {}
@@ -429,14 +429,14 @@ test parse-8.12 {Tcl_EvalObjv procedure, TCL_EVAL_INVOKE} {
             lappend ::info ns
         }]
     catch {rename ::noSuchCommand {}}
-    set ::slave [interp create]
-    $::slave alias bar noSuchCommand
+    set ::child [interp create]
+    $::child alias bar noSuchCommand
     set ::info {}
     namespace eval test_ns_1 {
-        $::slave eval bar
+        $::child eval bar
     }
     namespace delete test_ns_1
-    interp delete $::slave
+    interp delete $::child
     catch {rename ::noSuchCommand {}}
     set ::info
 } global
@@ -481,7 +481,7 @@ test parse-10.2 {Tcl_EvalTokens, backslash sequences} testevalex {
     testevalex {concat test\063\062test}
 } {test32test}
 test parse-10.3 {Tcl_EvalTokens, nested commands} testevalex {
-    testevalex {concat [expr 2 + 6]}
+    testevalex {concat [expr {2 + 6}]}
 } {8}
 test parse-10.4 {Tcl_EvalTokens, nested commands} testevalex {
     unset -nocomplain a
@@ -499,7 +499,7 @@ test parse-10.6 {Tcl_EvalTokens, array variables} testevalex {
 test parse-10.7 {Tcl_EvalTokens, array variables} testevalex {
     unset -nocomplain a
     set a(12) 46
-    testevalex {concat $a(1[expr 3 - 1])}
+    testevalex {concat $a(1[expr {3 - 1}])}
 } {46}
 test parse-10.8 {Tcl_EvalTokens, array variables} testevalex {
     unset -nocomplain a
index ef05454..bb0920e 100644 (file)
@@ -8,8 +8,10 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
index 504d063..c2d7c23 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
@@ -133,7 +135,7 @@ format %s $b
 } a22b
 test parseOld-4.4 {command substitution} {
     set a 7.7
-    if [catch {expr int($a)}] {set a foo}
+    if {[catch {expr {int($a)}}]} {set a foo}
     set a
 } 7.7
 
@@ -458,72 +460,6 @@ expr 1+1
 ]"
 } {2}
 
-test parseOld-14.1 {TclWordEnd procedure} {testwordend} {
-    testwordend "      \n abc"
-} {c}
-test parseOld-14.2 {TclWordEnd procedure} {testwordend} {
-    testwordend "   \\\n"
-} {}
-test parseOld-14.3 {TclWordEnd procedure} {testwordend} {
-    testwordend "   \\\n "
-} { }
-test parseOld-14.4 {TclWordEnd procedure} {testwordend} {
-    testwordend {"abc"}
-} {"}
-#" Emacs formatting :^(
-test parseOld-14.5 {TclWordEnd procedure} {testwordend} {
-    testwordend {{xyz}}
-} \}
-test parseOld-14.6 {TclWordEnd procedure} {testwordend} {
-    testwordend {{a{}b{}\}} xyz}
-} "\} xyz"
-test parseOld-14.7 {TclWordEnd procedure} {testwordend} {
-    testwordend {abc[this is a]def ghi}
-} {f ghi}
-test parseOld-14.8 {TclWordEnd procedure} {testwordend} {
-    testwordend "puts\\\n\n  "
-} "s\\\n\n  "
-test parseOld-14.9 {TclWordEnd procedure} {testwordend} {
-    testwordend "puts\\\n      "
-} "s\\\n       "
-test parseOld-14.10 {TclWordEnd procedure} {testwordend} {
-    testwordend "puts\\\n      xyz"
-} "s\\\n       xyz"
-test parseOld-14.11 {TclWordEnd procedure} {testwordend} {
-    testwordend {a$x.$y(a long index) foo}
-} ") foo"
-test parseOld-14.12 {TclWordEnd procedure} {testwordend} {
-    testwordend {abc; def}
-} {; def}
-test parseOld-14.13 {TclWordEnd procedure} {testwordend} {
-    testwordend {abc def}
-} {c def}
-test parseOld-14.14 {TclWordEnd procedure} {testwordend} {
-    testwordend {abc   def}
-} {c   def}
-test parseOld-14.15 {TclWordEnd procedure} {testwordend} {
-    testwordend "abc\ndef"
-} "c\ndef"
-test parseOld-14.16 {TclWordEnd procedure} {testwordend} {
-    testwordend "abc"
-} {c}
-test parseOld-14.17 {TclWordEnd procedure} {testwordend} {
-    testwordend "a\000bc"
-} {c}
-test parseOld-14.18 {TclWordEnd procedure} {testwordend} {
-    testwordend \[a\000\]
-} {]}
-test parseOld-14.19 {TclWordEnd procedure} {testwordend} {
-    testwordend \"a\000\"
-} {"}
-#" Emacs formatting :^(
-test parseOld-14.20 {TclWordEnd procedure} {testwordend} {
-    testwordend a{\000}b
-} {b}
-test parseOld-14.21 {TclWordEnd procedure} {testwordend} {
-    testwordend "   \000b"
-} {b}
-
 test parseOld-15.1 {TclScriptEnd procedure} {
     info complete {puts [
        expr 1+1
index af21f30..47f753b 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 84c82ce..ad328f8 100644 (file)
@@ -8,8 +8,10 @@
 # Copyright (c) 1998-1999 by Scriptics Corporation.
 # All rights reserved.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 set fullPkgPath [makeDirectory pkg]
 
@@ -72,11 +74,11 @@ proc pkgtest::parseArgs { args } {
 #  of the command line.
 
 proc pkgtest::parseIndex { filePath } {
-    # create a slave interpreter, where we override "package ifneeded"
+    # create a child interpreter, where we override "package ifneeded"
 
-    set slave [interp create]
+    set child [interp create]
     if {[catch {
-       $slave eval {
+       $child eval {
            rename package package_original
            proc package { args } {
                if {[lindex $args 0] eq "ifneeded"} {
@@ -91,17 +93,17 @@ proc pkgtest::parseIndex { filePath } {
        }
 
        set dir [file dirname $filePath]
-       $slave eval {set curdir [pwd]}
-       $slave eval [list cd $dir]
-       $slave eval [list set dir $dir]
-       $slave eval [list source [file tail $filePath]]
-       $slave eval {cd $curdir}
+       $child eval {set curdir [pwd]}
+       $child eval [list cd $dir]
+       $child eval [list set dir $dir]
+       $child eval [list source [file tail $filePath]]
+       $child eval {cd $curdir}
 
        # Create the list in sorted order, so that we don't get spurious
        # errors because the order has changed.
 
        array set P {}
-       foreach {k v} [$slave eval {array get ::PKGS}] {
+       foreach {k v} [$child eval {array get ::PKGS}] {
            set P($k) $v
        }
 
@@ -113,12 +115,12 @@ proc pkgtest::parseIndex { filePath } {
        set ei [dict get $opts -errorinfo]
        set ec [dict get $opts -errorcode]
 
-       catch {interp delete $slave}
+       catch {interp delete $child}
 
        error $ei $ec
     }
 
-    interp delete $slave
+    interp delete $child
 
     return $PKGS
 }
@@ -231,7 +233,7 @@ proc pkgtest::runCreatedIndex {rv args} {
            set result [list 0 [makePkgList [parseIndex $idxFile]]]
        } err]} {
            set result [list 1 $err]
-       } 
+       }
        file delete $idxFile
     } else {
        set result $rv
@@ -313,7 +315,7 @@ namespace eval pkg2 {
     namespace export p2-1
 }
 proc pkg2::p2-1 { num } {
-    return [expr $num * 2]
+    return [expr {$num * 2}]
 }
 } [file join pkg pkg2_a.tcl]
 
@@ -326,7 +328,7 @@ namespace eval pkg2 {
     namespace export p2-2
 }
 proc pkg2::p2-2 { num } {
-    return [expr $num * 3]
+    return [expr {$num * 3}]
 }
 } [file join pkg pkg2_b.tcl]
 
@@ -407,10 +409,10 @@ namespace eval pkg3 {
     namespace export p3-1 p3-2
 }
 proc pkg3::p3-1 { num } {
-    return {[expr $num * 2]}
+    return {[expr {$num * 2}]}
 }
 proc pkg3::p3-2 { num } {
-    return {[expr $num * 3]}
+    return {[expr {$num * 3}]}
 }
 } [file join pkg pkg3.tcl]
 
@@ -518,10 +520,10 @@ namespace eval circ2 {
     namespace export c2-1 c2-2
 }
 proc circ2::c2-1 { num } {
-    return [expr $num * [circ3::c3-1]]
+    return [expr {$num * [circ3::c3-1]}]
 }
 proc circ2::c2-2 { num } {
-    return [expr $num * [circ3::c3-2]]
+    return [expr {$num * [circ3::c3-2]}]
 }
 } [file join pkg circ2.tcl]
 
index e5a4c90..e40ff39 100644 (file)
@@ -9,7 +9,7 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+package require tcltest 2.5
 package require tcltests
 
 namespace eval ::tcl::test::platform {
index e45cf5c..a92c6ab 100644 (file)
@@ -14,8 +14,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -25,7 +25,7 @@ catch {rename foo ""}
 proc tproc {} {return a; return b}
 test proc-old-1.1 {simple procedure call and return} {tproc} a
 proc tproc x {
-    set x [expr $x+1]
+    set x [expr {$x + 1}]
     return $x
 }
 test proc-old-1.2 {simple procedure call and return} {tproc 2} 3
@@ -49,7 +49,7 @@ test proc-old-1.6 {simple procedure call and return (shared proc body string)} {
 
 test proc-old-2.1 {local and global variables} {
     proc tproc x {
-       set x [expr $x+1]
+       set x [expr {$x + 1}]
        return $x
     }
     set x 42
@@ -57,7 +57,7 @@ test proc-old-2.1 {local and global variables} {
 } {7 42}
 test proc-old-2.2 {local and global variables} {
     proc tproc x {
-       set y [expr $x+1]
+       set y [expr {$x + 1}]
        return $y
     }
     set y 18
@@ -66,7 +66,7 @@ test proc-old-2.2 {local and global variables} {
 test proc-old-2.3 {local and global variables} {
     proc tproc x {
        global y
-       set y [expr $x+1]
+       set y [expr {$x + 1}]
        return $y
     }
     set y 189
@@ -75,7 +75,7 @@ test proc-old-2.3 {local and global variables} {
 test proc-old-2.4 {local and global variables} {
     proc tproc x {
        global y
-       return [expr $x+$y]
+       return [expr {$x + $y}]
     }
     set y 189
     list [tproc 6] $y
@@ -504,7 +504,7 @@ test proc-old-10.1 {ByteCode epoch change during recursive proc execution} {
         set y 20
         rename expr expr.old
         rename expr.old expr
-        if $x then {t1 0} ;# recursive call after foo's code is invalidated
+        if {$x} then {t1 0} ;# recursive call after foo's code is invalidated
         return 20
     }
     t1 1
index 9be056f..4b539c4 100644 (file)
@@ -14,7 +14,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -99,15 +99,15 @@ test proc-1.6 {Tcl_ProcObjCmd, namespace code ignores single ":"s in middle or e
 test proc-1.7 {Tcl_ProcObjCmd, check that formal parameter names are not array elements} -setup {
     catch {rename p ""}
 } -returnCodes error -body {
-    proc p {a(1) a(2)} { 
-       set z [expr $a(1)+$a(2)]
+    proc p {a(1) a(2)} {
+       set z [expr {$a(1)+$a(2)}]
        puts "$z=z, $a(1)=$a(1)"
     }
 } -result {formal parameter "a(1)" is an array element}
 test proc-1.8 {Tcl_ProcObjCmd, check that formal parameter names are simple names} -setup {
     catch {rename p ""}
 } -body {
-    proc p {b:a b::a} { 
+    proc p {b:a b::a} {
     }
 } -returnCodes error -result {formal parameter "b::a" is not a simple name}
 test proc-1.9 {Tcl_ProcObjCmd, arguments via canonical list (string-representation bug [631b4c45df])} -body {
@@ -340,7 +340,7 @@ test proc-5.1 {Bytecompiling noop; test for correct argument substitution} -body
 } -cleanup {
     catch {rename p ""}
     catch {rename t ""}
-} -result {aba}    
+} -result {aba}
 
 test proc-6.1 {ProcessProcResultCode: Bug 647307 (negative return code)} -body {
     proc a {} {return -code -5}
@@ -389,9 +389,9 @@ test proc-7.3 {Returning loop exception from redefined cmd: Bug 729692} -body {
 test proc-7.4 {Proc struct outlives its interp: Bug 3532959} {
     set lambda x
     lappend lambda {set a 1}
-    interp create slave
-    slave eval [list apply $lambda foo]
-    interp delete slave
+    interp create child
+    child eval [list apply $lambda foo]
+    interp delete child
     unset lambda
 } {}
 
index 175c852..3d4cffd 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -20,9 +20,10 @@ test pwd-1.1 {simple pwd} {
     catch pwd
 } 0
 test pwd-1.2 {simple pwd} {
-    expr [string length pwd]>0
+    expr {[string length [pwd]]>0}
 } 1
-test pwd-1.3 {pwd takes no args} -body {
+
+test pwd-2.1 {pwd takes no args} -body {
     pwd foobar
 } -returnCodes error -result "wrong \# args: should be \"pwd\""
 
index d040632..063b091 100644 (file)
@@ -9,8 +9,8 @@
 #
 # Copyright (c) 1998, 1999 Henry Spencer.  All rights reserved.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
 }
 
 ::tcltest::loadTestedCommands
@@ -49,9 +49,9 @@ catch [list package require -exact Tcltest [info patchlevel]]
 # subexpressions, checking where empty substrings are located,
 # etc. should be done using expectIndices and expectPartial.
 
-# The flag characters are complex and a bit eclectic.  Generally speaking, 
+# The flag characters are complex and a bit eclectic.  Generally speaking,
 # lowercase letters are compile options, uppercase are expected re_info
-# bits, and nonalphabetics are match options, controls for how the test is 
+# bits, and nonalphabetics are match options, controls for how the test is
 # run, or testing options.  The one small surprise is that AREs are the
 # default, and you must explicitly request lesser flavors of RE.  The flags
 # are as follows.  It is admitted that some are not very mnemonic.
@@ -287,7 +287,7 @@ namespace eval RETest {
        set infoflags [TestInfoFlags $flags]
        set ccmd [list testregexp -about {*}$f $re]
        set nsub [expr {[llength $args] - 1}]
-       if {$nsub == -1} {
+       if {$nsub < 0} {
            # didn't tell us number of subexps
            set ccmd "lreplace \[$ccmd\] 0 0"
            set info [list $infoflags]
@@ -311,7 +311,7 @@ namespace eval RETest {
     # match expected (full fanciness)
     # expectIndices testno flags re target mat submat ...
     proc expectIndices {args} {
-       MatchExpected -indices {*}$args 
+       MatchExpected -indices {*}$args
     }
 
     # partial match expected
@@ -626,6 +626,7 @@ expectMatch 13.14 P         "a\\rb"         "a\rb"  "a\rb"
 expectMatch    13.15 P         "a\\tb"         "a\tb"  "a\tb"
 expectMatch    13.16 P         "a\\u0008x"     "a\bx"  "a\bx"
 expectMatch    13.17 P         {a\u008x}       "a\bx"  "a\bx"
+expectError    13.17.1 -       {a\ux}          EESCAPE
 expectMatch    13.18 P         "a\\u00088x"    "a\b8x" "a\b8x"
 expectMatch    13.19 P         "a\\U00000008x" "a\bx"  "a\bx"
 expectMatch    13.20 P         {a\U0000008x}   "a\bx"  "a\bx"
index 9fff262..563a5ee 100644 (file)
@@ -12,7 +12,7 @@
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -178,6 +178,17 @@ test regexp-3.7 {getting substrings back from regexp} {
     set foo 1; set f2 1; set f3 1; set f4 1
     list [regexp -indices (a)(b)?(c) xacy foo f2 f3 f4] $foo $f2 $f3 $f4
 } {1 {1 2} {1 1} {-1 -1} {2 2}}
+test regexp-3.8a {-indices by multi-byte utf-8} {
+    regexp -inline -indices {(\w+)-(\w+)} \
+       "gr\u00FC\u00DF-\u043F\u0440\u0438\u0432\u0435\u0442"
+} {{0 10} {0 3} {5 10}}
+test regexp-3.8b {-indices by multi-byte utf-8, from -start position} {
+    list\
+       [regexp -inline -indices -start 3 {(\w+)-(\w+)} \
+       "gr\u00FC\u00DF-\u043F\u0440\u0438\u0432\u0435\u0442"] \
+       [regexp -inline -indices -start 4 {(\w+)-(\w+)} \
+       "gr\u00FC\u00DF-\u043F\u0440\u0438\u0432\u0435\u0442"]
+} {{{3 10} {3 3} {5 10}} {}}
 
 test regexp-4.1 {-nocase option to regexp} {
     regexp -nocase foo abcFOo
index 01ef06d..2fd7f88 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 86f4ef3..53e48fe 100644 (file)
@@ -10,8 +10,8 @@
 # Copyright (c) 1997 by Sun Microsystems, Inc.  All rights reserved.
 # Copyright (c) 1998-1999 by Scriptics Corporation.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -19,7 +19,7 @@ testConstraint reg 0
 if {[testConstraint win]} {
     if {![catch {
            ::tcltest::loadTestedCommands
-           set ::regver [package require registry 1.3.4]
+           set ::regver [package require registry 1.3.5]
        }]} {
        testConstraint reg 1
     }
@@ -33,7 +33,7 @@ testConstraint english [expr {
 \f
 test registry-1.0 {check if we are testing the right dll} {win reg} {
     set ::regver
-} {1.3.4}
+} {1.3.5}
 test registry-1.1 {argument parsing for registry command} {win reg} {
     list [catch {registry} msg] $msg
 } {1 {wrong # args: should be "registry ?-32bit|-64bit? option ?arg ...?"}}
index 097e41f..3c2fb51 100644 (file)
@@ -91,8 +91,8 @@ if {![info exists serverPort]} {
 if {![info exists serverPort]} {
     for {set i 0} {$i < $argc} {incr i} {
        if {[string compare -port [lindex $argv $i]] == 0} {
-           if {$i < [expr $argc - 1]} {
-               set serverPort [lindex $argv [expr $i + 1]]
+           if {$i < $argc - 1} {
+               set serverPort [lindex $argv [expr {$i + 1}]]
            }
            break
        }
@@ -110,8 +110,8 @@ if {![info exists serverAddress]} {
 if {![info exists serverAddress]} {
     for {set i 0} {$i < $argc} {incr i} {
        if {[string compare -address [lindex $argv $i]] == 0} {
-           if {$i < [expr $argc - 1]} {
-               set serverAddress [lindex $argv [expr $i + 1]]
+           if {$i < $argc - 1} {
+               set serverAddress [lindex $argv [expr {$i + 1}]]
            }
            break
        }
index ebf5425..ddda909 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index b0b395d..9916529 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-if {"::tcltest" in [namespace children]} {
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -203,7 +203,7 @@ test resolver-2.1 {compiled var resolver: Bug #3383616} -setup {
 # resolver-agnostic).
 #
 # In order to make the test cases for the per-interpreter cmd literal pool
-# reproducable and to minimize interactions between test cases, we use a slave
+# reproducable and to minimize interactions between test cases, we use a child
 # interpreter per test-case.
 #
 #
index 9e8a66b..6e51e4e 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
diff --git a/tests/safe-stock.test b/tests/safe-stock.test
new file mode 100644 (file)
index 0000000..7be483e
--- /dev/null
@@ -0,0 +1,109 @@
+# safe-stock.test --
+#
+# This file contains tests for safe Tcl that were previously in the file
+# safe.test, and use files and packages of stock Tcl 8.6 to perform the tests.
+# These files may be changed or disappear in future revisions of Tcl,
+# for example package http 1.0 will be removed from Tcl 8.7.
+#
+# The tests are replaced in safe.tcl with tests that use files provided in the
+# tests directory.  Test numbering is for comparison with similar tests in
+# safe.test.
+#
+# Sourcing this file into tcl runs the tests and generates output for errors.
+# No output means no errors were found.
+#
+# Copyright (c) 1995-1996 Sun Microsystems, Inc.
+# Copyright (c) 1998-1999 by Scriptics Corporation.
+#
+# See the file "license.terms" for information on usage and redistribution of
+# this file, and for a DISCLAIMER OF ALL WARRANTIES.
+
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
+
+foreach i [interp children] {
+    interp delete $i
+}
+
+set SaveAutoPath $::auto_path
+set ::auto_path [info library]
+set TestsDir [file normalize [file dirname [info script]]]
+set PathMapp [list $tcl_library TCLLIB $TestsDir TESTSDIR]
+
+proc mapList {map listIn} {
+    set listOut {}
+    foreach element $listIn {
+        lappend listOut [string map $map $element]
+    }
+    return $listOut
+}
+
+# Force actual loading of the safe package because we use un-exported (and
+# thus un-autoindexed) APIs in this test result arguments:
+catch {safe::interpConfigure}
+
+# high level general test
+test safe-stock-7.1 {tests that everything works at high level, uses http 2} -body {
+    set i [safe::interpCreate]
+    # no error shall occur:
+    # (because the default access_path shall include 1st level sub dirs so
+    #  package require in a child works like in the parent)
+    set v [interp eval $i {package require http 2}]
+    # no error shall occur:
+    interp eval $i {http::config}
+    safe::interpDelete $i
+    set v
+} -match glob -result 2.*
+test safe-stock-7.2 {tests specific path and interpFind/AddToAccessPath, uses http1.0} -body {
+    set i [safe::interpCreate -nostat -nested 1 -accessPath [list [info library]]]
+    # should not add anything (p0)
+    set token1 [safe::interpAddToAccessPath $i [info library]]
+    # should add as p1
+    set token2 [safe::interpAddToAccessPath $i "/dummy/unixlike/test/path"]
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    # an error shall occur (http is not anymore in the secure 0-level
+    # provided deep path)
+    list $token1 $token2 -- \
+           [catch {interp eval $i {package require http 1}} msg] $msg -- \
+           $mappA -- [safe::interpDelete $i]
+} -match glob -result {{$p(:0:)} {$p(:*:)} -- 1 {can't find package http 1} --\
+        {TCLLIB */dummy/unixlike/test/path} -- {}}
+test safe-stock-7.4 {tests specific path and positive search, uses http1.0} -body {
+    set i [safe::interpCreate -nostat -nested 1 -accessPath [list [info library]]]
+    # should not add anything (p0)
+    set token1 [safe::interpAddToAccessPath $i [info library]]
+    # should add as p1
+    set token2 [safe::interpAddToAccessPath $i [file join [info library] http1.0]]
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    # this time, unlike test safe-stock-7.2, http should be found
+    list $token1 $token2 -- \
+           [catch {interp eval $i {package require http 1}} msg] $msg -- \
+           $mappA -- [safe::interpDelete $i]
+} -match glob -result {{$p(:0:)} {$p(:*:)} -- 0 1.0 -- {TCLLIB *TCLLIB/http1.0} -- {}}
+
+# The following test checks whether the definition of tcl_endOfWord can be
+# obtained from auto_loading.  It was previously test "safe-5.1".
+test safe-stock-9.8 {test auto-loading in safe interpreters, was test 5.1} -setup {
+    catch {safe::interpDelete a}
+    safe::interpCreate a
+} -body {
+    interp eval a {tcl_endOfWord "" 0}
+} -cleanup {
+    safe::interpDelete a
+} -result -1
+\f
+set ::auto_path $SaveAutoPath
+unset SaveAutoPath TestsDir PathMapp
+rename mapList {}
+
+# cleanup
+::tcltest::cleanupTests
+return
+
+# Local Variables:
+# mode: tcl
+# End:
index 11ad2a9..e4c3442 100644 (file)
@@ -4,27 +4,53 @@
 # using safe interpreters. Sourcing this file into tcl runs the tests and
 # generates output for errors. No output means no errors were found.
 #
+# The package http 1.0 is convenient for testing package loading, but will soon
+# be removed.
+# - Tests that use http are replaced here with tests that use example packages
+#   provided in subdirectory auto0 of the tests directory, which are independent
+#   of any changes made to the packages provided with Tcl itself.
+#   - These are tests 7.1 7.2 7.4 9.11 9.13
+#   - Tests 5.* test the example packages themselves before they
+#     are used to test Safe Base interpreters.
+# - Alternative tests using stock packages of Tcl 8.6 are in file
+#   safe-stock.test.
+#
 # Copyright (c) 1995-1996 Sun Microsystems, Inc.
 # Copyright (c) 1998-1999 by Scriptics Corporation.
 #
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require Tcl 8.5-
-
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
-foreach i [interp slaves] {
+foreach i [interp children] {
     interp delete $i
 }
 
-set saveAutoPath $::auto_path
+set SaveAutoPath $::auto_path
 set ::auto_path [info library]
+set TestsDir [file normalize [file dirname [info script]]]
+set PathMapp [list $tcl_library TCLLIB $TestsDir TESTSDIR]
+
+proc mapList {map listIn} {
+    set listOut {}
+    foreach element $listIn {
+        lappend listOut [string map $map $element]
+    }
+    return $listOut
+}
+proc mapAndSortList {map listIn} {
+    set listOut {}
+    foreach element $listIn {
+        lappend listOut [string map $map $element]
+    }
+    lsort $listOut
+}
 
-# Force actual loading of the safe package because we use un exported (and
+# Force actual loading of the safe package because we use un-exported (and
 # thus un-autoindexed) APIs in this test result arguments:
 catch {safe::interpConfigure}
 
@@ -66,6 +92,8 @@ test safe-2.2 {creating interpreters, should have no aliases} -setup {
     a aliases
 } -cleanup {
     safe::interpDelete a
+    # This (ab)use of safe::interpDelete to delete non-Safe-Base interpreters
+    # is regrettable and should be removed at the next major revision.
 } -result ""
 test safe-2.3 {creating safe interpreters, should have no unexpected aliases} -setup {
     catch {safe::interpDelete a}
@@ -115,6 +143,8 @@ test safe-4.1 {safe::interpDelete} -setup {
 } -body {
     interp create a
     safe::interpDelete a
+    # This (ab)use of safe::interpDelete to delete non-Safe-Base interpreters
+    # is regrettable and should be removed at the next major revision.
 } -result ""
 test safe-4.2 {safe::interpDelete, indirectly} -setup {
     catch {safe::interpDelete a}
@@ -122,6 +152,8 @@ test safe-4.2 {safe::interpDelete, indirectly} -setup {
     interp create a
     a alias exit safe::interpDelete a
     a eval exit
+    # This (ab)use of safe::interpDelete to delete non-Safe-Base interpreters
+    # is regrettable and should be removed at the next major revision.
 } -result ""
 test safe-4.5 {safe::interpDelete} -setup {
     catch {safe::interpDelete a}
@@ -138,17 +170,120 @@ test safe-4.6 {safe::interpDelete, indirectly} -setup {
     a eval exit
 } -result ""
 
-# The following test checks whether the definition of tcl_endOfWord can be
-# obtained from auto_loading.
+# The old test "safe-5.1" has been moved to "safe-stock-9.8".
+# A replacement test using example files is "safe-9.8".
+# Tests 5.* test the example files before using them to test safe interpreters.
 
-test safe-5.1 {test auto-loading in safe interpreters} -setup {
-    catch {safe::interpDelete a}
-    safe::interpCreate a
+unset -nocomplain path
+
+test safe-5.1 {example tclIndex commands, test in parent interpreter} -setup {
+    set tmpAutoPath $::auto_path
+    lappend ::auto_path [file join $TestsDir auto0 auto1] [file join $TestsDir auto0 auto2]
 } -body {
-    interp eval a {tcl_endOfWord "" 0}
+    # Try to load the commands.
+    set code3 [catch report1 msg3]
+    set code4 [catch report2 msg4]
+    list $code3 $msg3 $code4 $msg4
 } -cleanup {
-    safe::interpDelete a
-} -result -1
+    catch {rename report1 {}}
+    catch {rename report2 {}}
+    set ::auto_path $tmpAutoPath
+    auto_reset
+} -match glob -result {0 ok1 0 ok2}
+test safe-5.2 {example tclIndex commands, negative test in parent interpreter} -setup {
+    set tmpAutoPath $::auto_path
+    lappend ::auto_path [file join $TestsDir auto0]
+} -body {
+    # Try to load the commands.
+    set code3 [catch report1 msg3]
+    set code4 [catch report2 msg4]
+    list $code3 $msg3 $code4 $msg4
+} -cleanup {
+    catch {rename report1 {}}
+    catch {rename report2 {}}
+    set ::auto_path $tmpAutoPath
+    auto_reset
+} -match glob -result {1 {invalid command name "report1"} 1 {invalid command name "report2"}}
+test safe-5.3 {example pkgIndex.tcl packages, test in parent interpreter, child directories} -setup {
+    set tmpAutoPath $::auto_path
+    lappend ::auto_path [file join $TestsDir auto0]
+} -body {
+    # Try to load the packages and run a command from each one.
+    set code3 [catch {package require SafeTestPackage1} msg3]
+    set code4 [catch {package require SafeTestPackage2} msg4]
+    set code5 [catch HeresPackage1 msg5]
+    set code6 [catch HeresPackage2 msg6]
+    list $code3 $msg3 $code4 $msg4 $code5 $msg5 $code6 $msg6
+} -cleanup {
+    set ::auto_path $tmpAutoPath
+    catch {package forget SafeTestPackage1}
+    catch {package forget SafeTestPackage2}
+    catch {rename HeresPackage1 {}}
+    catch {rename HeresPackage2 {}}
+} -match glob -result {0 1.2.3 0 2.3.4 0 OK1 0 OK2}
+test safe-5.4 {example pkgIndex.tcl packages, test in parent interpreter, main directories} -setup {
+    set tmpAutoPath $::auto_path
+    lappend ::auto_path [file join $TestsDir auto0 auto1] \
+                        [file join $TestsDir auto0 auto2]
+} -body {
+    # Try to load the packages and run a command from each one.
+    set code3 [catch {package require SafeTestPackage1} msg3]
+    set code4 [catch {package require SafeTestPackage2} msg4]
+    set code5 [catch HeresPackage1 msg5]
+    set code6 [catch HeresPackage2 msg6]
+    list $code3 $msg3 $code4 $msg4 $code5 $msg5 $code6 $msg6
+} -cleanup {
+    set ::auto_path $tmpAutoPath
+    catch {package forget SafeTestPackage1}
+    catch {package forget SafeTestPackage2}
+    catch {rename HeresPackage1 {}}
+    catch {rename HeresPackage2 {}}
+} -match glob -result {0 1.2.3 0 2.3.4 0 OK1 0 OK2}
+test safe-5.5 {example modules packages, test in parent interpreter, replace path} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    # Try to load the modules and run a command from each one.
+    set code0 [catch {package require test0} msg0]
+    set code1 [catch {package require mod1::test1} msg1]
+    set code2 [catch {package require mod2::test2} msg2]
+    set out0  [test0::try0]
+    set out1  [mod1::test1::try1]
+    set out2  [mod2::test2::try2]
+    list $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    catch {package forget test0}
+    catch {package forget mod1::test1}
+    catch {package forget mod2::test2}
+    catch {namespace delete ::test0}
+    catch {namespace delete ::mod1}
+} -match glob -result {0 0.5 0 1.0 0 2.0 -- res0 res1 res2}
+test safe-5.6 {example modules packages, test in parent interpreter, append to path} -setup {
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    # Try to load the modules and run a command from each one.
+    set code0 [catch {package require test0} msg0]
+    set code1 [catch {package require mod1::test1} msg1]
+    set code2 [catch {package require mod2::test2} msg2]
+    set out0  [test0::try0]
+    set out1  [mod1::test1::try1]
+    set out2  [mod2::test2::try2]
+    list $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    catch {package forget test0}
+    catch {package forget mod1::test1}
+    catch {package forget mod2::test2}
+    catch {namespace delete ::test0}
+    catch {namespace delete ::mod1}
+} -match glob -result {0 0.5 0 1.0 0 2.0 -- res0 res1 res2}
 
 # test safe interps 'information leak'
 proc SafeEval {script} {
@@ -176,59 +311,121 @@ test safe-6.3 {test safe interpreters knowledge of the world} {
     lsort $r
 } {byteOrder engine pathSeparator platform pointerSize wordSize}
 
+rename SafeEval {}
 # More test should be added to check that hostname, nameofexecutable, aren't
 # leaking infos, but they still do...
 
 # high level general test
-test safe-7.1 {tests that everything works at high level} -body {
+# Use example packages not http1.0 etc
+test safe-7.1 {tests that everything works at high level} -setup {
+    set tmpAutoPath $::auto_path
+    lappend ::auto_path [file join $TestsDir auto0]
     set i [safe::interpCreate]
+    set ::auto_path $tmpAutoPath
+} -body {
     # no error shall occur:
     # (because the default access_path shall include 1st level sub dirs so
-    #  package require in a slave works like in the master)
-    set v [interp eval $i {package require http 2}]
+    #  package require in a child works like in the parent)
+    set v [interp eval $i {package require SafeTestPackage1}]
     # no error shall occur:
-    interp eval $i {http::config}
-    safe::interpDelete $i
+    interp eval $i {HeresPackage1}
     set v
-} -match glob -result 2.*
-test safe-7.2 {tests specific path and interpFind/AddToAccessPath} -body {
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result 1.2.3
+test safe-7.2 {tests specific path and interpFind/AddToAccessPath} -setup {
+} -body {
     set i [safe::interpCreate -nostat -nested 1 -accessPath [list [info library]]]
     # should not add anything (p0)
     set token1 [safe::interpAddToAccessPath $i [info library]]
-    # should add as p1
+    # should add as p* (not p1 if parent has a module path)
     set token2 [safe::interpAddToAccessPath $i "/dummy/unixlike/test/path"]
-    # an error shall occur (http is not anymore in the secure 0-level
+    # should add as p* (not p2 if parent has a module path)
+    set token3 [safe::interpAddToAccessPath $i [file join $TestsDir auto0]]
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    # an error shall occur (SafeTestPackage1 is not anymore in the secure 0-level
     # provided deep path)
-    list $token1 $token2 \
-           [catch {interp eval $i {package require http 1}} msg] $msg \
-           [safe::interpConfigure $i]\
-           [safe::interpDelete $i]
-} -match glob -result "{\$p(:0:)} {\$p(:*:)} 1 {can't find package http 1} {-accessPath {[list $tcl_library */dummy/unixlike/test/path]} -statics 0 -nested 1 -deleteHook {}} {}"
+    list $token1 $token2 $token3 -- \
+           [catch {interp eval $i {package require SafeTestPackage1}} msg] $msg -- \
+           $mappA -- [safe::interpDelete $i]
+} -cleanup {
+} -match glob -result {{$p(:0:)} {$p(:*:)} {$p(:*:)} --\
+        1 {can't find package SafeTestPackage1} --\
+        {TCLLIB */dummy/unixlike/test/path TESTSDIR/auto0} -- {}}
 test safe-7.3 {check that safe subinterpreters work} {
+    set g [interp children]
+    if {$g ne {}} {
+        append g { -- residue of an earlier test}
+    }
+    set h [info vars ::safe::S*]
+    if {$h ne {}} {
+        append h { -- residue of an earlier test}
+    }
     set i [safe::interpCreate]
     set j [safe::interpCreate [list $i x]]
-    list [interp eval $j {join {o k} ""}] [safe::interpDelete $i] [interp exists $j]
-} {ok {} 0}
+    list $g $h [interp eval $j {join {o k} ""}] [safe::interpDelete $i] \
+            [interp exists $j] [info vars ::safe::S*]
+} {{} {} ok {} 0 {}}
+test safe-7.3.1 {check that safe subinterpreters work with namespace names} -setup {
+} -body {
+    set g [interp children]
+    if {$g ne {}} {
+        append g { -- residue of an earlier test}
+    }
+    set h [info vars ::safe::S*]
+    if {$h ne {}} {
+        append h { -- residue of an earlier test}
+    }
+    set i [safe::interpCreate foo::bar]
+    set j [safe::interpCreate [list $i hello::world]]
+    list $g $h [interp eval $j {join {o k} ""}] \
+            [foo::bar eval {hello::world eval {join {o k} ""}}] \
+            [safe::interpDelete $i] \
+            [interp exists $j] [info vars ::safe::S*]
+} -match glob -result {{} {} ok ok {} 0 {}}
+test safe-7.4 {tests specific path and positive search} -setup {
+} -body {
+    set i [safe::interpCreate -nostat -nested 1 -accessPath [list [info library]]]
+    # should not add anything (p0)
+    set token1 [safe::interpAddToAccessPath $i [info library]]
+    # should add as p* (not p1 if parent has a module path)
+    set token2 [safe::interpAddToAccessPath $i [file join $TestsDir auto0 auto1]]
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    # this time, unlike test safe-7.2, SafeTestPackage1 should be found
+    list $token1 $token2 -- \
+           [catch {interp eval $i {package require SafeTestPackage1}} msg] $msg -- \
+           $mappA -- [safe::interpDelete $i]
+    # Note that the glob match elides directories (those from the module path)
+    # other than the first and last in the access path.
+} -cleanup {
+} -match glob -result {{$p(:0:)} {$p(:*:)} -- 0 1.2.3 --\
+        {TCLLIB * TESTSDIR/auto0/auto1} -- {}}
 
 # test source control on file name
-set i "a"
 test safe-8.1 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
 } -body {
     safe::interpCreate $i
     $i eval {source}
 } -returnCodes error -cleanup {
     safe::interpDelete $i
+    unset i
 } -result {wrong # args: should be "source ?-encoding E? fileName"}
 test safe-8.2 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
 } -body {
     safe::interpCreate $i
     $i eval {source a b c d e}
 } -returnCodes error -cleanup {
     safe::interpDelete $i
+    unset i
 } -result {wrong # args: should be "source ?-encoding E? fileName"}
 test safe-8.3 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set log {}
     proc safe-test-log {str} {lappend ::log $str}
@@ -239,10 +436,12 @@ test safe-8.3 {safe source control on file} -setup {
     list [catch {$i eval {source .}} msg] $msg $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
     safe::interpDelete $i
+    rename safe-test-log {}
+    unset i log
 } -result {1 {permission denied} {{ERROR for slave a : ".": is a directory}}}
 test safe-8.4 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set log {}
     proc safe-test-log {str} {global log; lappend log $str}
@@ -253,10 +452,12 @@ test safe-8.4 {safe source control on file} -setup {
     list [catch {$i eval {source /abc/def}} msg] $msg $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
     safe::interpDelete $i
+    rename safe-test-log {}
+    unset i log
 } -result {1 {permission denied} {{ERROR for slave a : "/abc/def": not in access_path}}}
 test safe-8.5 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set log {}
     proc safe-test-log {str} {global log; lappend log $str}
@@ -271,10 +472,12 @@ test safe-8.5 {safe source control on file} -setup {
     } msg] $msg $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
     safe::interpDelete $i
+    rename safe-test-log {}
+    unset i log
 } -result [list 1 {no such file or directory} [list "ERROR for slave a : [file join [info library] blah]:no such file or directory"]]
 test safe-8.6 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set log {}
     proc safe-test-log {str} {global log; lappend log $str}
@@ -287,10 +490,12 @@ test safe-8.6 {safe source control on file} -setup {
     } msg] $msg $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
     safe::interpDelete $i
+    rename safe-test-log {}
+    unset i log
 } -result [list 1 {no such file or directory} [list "ERROR for slave a : [file join [info library] blah.tcl]:no such file or directory"]]
 test safe-8.7 {safe source control on file} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set log {}
     proc safe-test-log {str} {global log; lappend log $str}
@@ -305,14 +510,16 @@ test safe-8.7 {safe source control on file} -setup {
     } msg] $msg $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
     safe::interpDelete $i
+    rename safe-test-log {}
+    unset i log
 } -result [list 1 {no such file or directory} [list "ERROR for slave a : [file join [info library] xxxxxxxxxxx.tcl]:no such file or directory"]]
 test safe-8.8 {safe source forbids -rsrc} emptyTest {
     # Disabled this test.  It was only useful for long unsupported
     # Mac OS 9 systems. [Bug 860a9f1945]
 } {}
 test safe-8.9 {safe source and return} -setup {
+    set i "a"
     set returnScript [makeFile {return "ok"} return.tcl]
     catch {safe::interpDelete $i}
 } -body {
@@ -322,8 +529,10 @@ test safe-8.9 {safe source and return} -setup {
 } -cleanup {
     catch {safe::interpDelete $i}
     removeFile $returnScript
+    unset i
 } -result ok
 test safe-8.10 {safe source and return} -setup {
+    set i "a"
     set returnScript [makeFile {return -level 2 "ok"} return.tcl]
     catch {safe::interpDelete $i}
 } -body {
@@ -336,10 +545,11 @@ test safe-8.10 {safe source and return} -setup {
 } -cleanup {
     catch {safe::interpDelete $i}
     removeFile $returnScript
+    unset i
 } -result ok
 
-set i "a"
 test safe-9.1 {safe interps' deleteHook} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set res {}
 } -body {
@@ -352,8 +562,12 @@ test safe-9.1 {safe interps' deleteHook} -setup {
     }
     safe::interpCreate $i -deleteHook "testDelHook arg1 arg2"
     list [interp eval $i exit] $res
+} -cleanup {
+    catch {rename testDelHook {}}
+    unset i res
 } -result {{} {arg1 arg2 a}}
 test safe-9.2 {safe interps' error in deleteHook} -setup {
+    set i "a"
     catch {safe::interpDelete $i}
     set res {}
     set log {}
@@ -374,7 +588,9 @@ test safe-9.2 {safe interps' error in deleteHook} -setup {
     list [safe::interpDelete $i] $res $log
 } -cleanup {
     safe::setLogCmd $prevlog
-    unset log
+    catch {rename testDelHook {}}
+    rename safe-test-log {}
+    unset i log res
 } -result {{} {arg1 arg2 a} {{NOTICE for slave a : About to delete} {ERROR for slave a : Delete hook error (being catched)} {NOTICE for slave a : Deleted}}}
 test safe-9.3 {dual specification of statics} -returnCodes error -body {
     safe::interpCreate -stat true -nostat
@@ -403,7 +619,546 @@ test safe-9.6 {interpConfigure widget like behaviour} -body {
         safe::interpConfigure $i]\
        [safe::interpConfigure $i -deleteHook toto -nosta -nested 0
         safe::interpConfigure $i]
-} -match glob -result {{-accessPath * -statics 0 -nested 1 -deleteHook {foo bar}} {-accessPath *} {-nested 1} {-statics 0} {-deleteHook {foo bar}} {-accessPath * -statics 1 -nested 1 -deleteHook {foo bar}} {-accessPath * -statics 0 -nested 0 -deleteHook toto}}
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{-accessPath * -statics 0 -nested 1 -deleteHook {foo bar}}\
+        {-accessPath *} {-nested 1} {-statics 0} {-deleteHook {foo bar}}\
+        {-accessPath * -statics 1 -nested 1 -deleteHook {foo bar}}\
+        {-accessPath * -statics 0 -nested 0 -deleteHook toto}}
+test safe-9.7 {interpConfigure widget like behaviour (demystified)} -body {
+   # this test shall work, believed equivalent to 9.6
+    set i [safe::interpCreate \
+           -noStatics \
+           -nestedLoadOk \
+           -deleteHook {foo bar}]
+          safe::interpConfigure $i -accessPath /foo/bar
+    set a [safe::interpConfigure $i]
+    set b [safe::interpConfigure $i -aCCess]
+    set c [safe::interpConfigure $i -nested]
+    set d [safe::interpConfigure $i -statics]
+    set e [safe::interpConfigure $i -DEL]
+          safe::interpConfigure $i -accessPath /blah -statics 1
+    set f [safe::interpConfigure $i]
+          safe::interpConfigure $i -deleteHook toto -nosta -nested 0
+    set g [safe::interpConfigure $i]
+
+    list $a $b $c $d $e $f $g
+} -cleanup {
+    safe::interpDelete $i
+    unset -nocomplain a b c d e f g i
+} -match glob -result {{-accessPath * -statics 0 -nested 1 -deleteHook {foo bar}}\
+        {-accessPath *} {-nested 1} {-statics 0} {-deleteHook {foo bar}}\
+        {-accessPath * -statics 1 -nested 1 -deleteHook {foo bar}}\
+        {-accessPath * -statics 0 -nested 0 -deleteHook toto}}
+test safe-9.8 {test autoloading commands indexed in tclIndex files} -setup {
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load and run the commands.
+    set code1 [catch {interp eval $i {report1}} msg1]
+    set code2 [catch {interp eval $i {report2}} msg2]
+
+    list $path1 $path2 -- $code1 $msg1 $code2 $msg2 -- $mappA
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:1:)} {$p(:2:)} -- 0 ok1 0 ok2 --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*}}
+test safe-9.9 {interpConfigure change the access path; tclIndex commands unaffected by token rearrangement (dummy test of doreset)} -setup {
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load auto_load data.
+    interp eval $i {catch nonExistentCommand}
+
+    # Load and run the commands.
+    # This guarantees the test will pass even if the tokens are swapped.
+    set code1 [catch {interp eval $i {report1}} msg1]
+    set code2 [catch {interp eval $i {report2}} msg2]
+
+    # Rearrange access path.  Swap tokens {$p(:1:)} and {$p(:2:)}.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto2] \
+                                           [file join $TestsDir auto0 auto1]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set mappB [mapList $PathMapp [dict get $confB -accessPath]]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Run the commands.
+    set code3 [catch {interp eval $i {report1}} msg3]
+    set code4 [catch {interp eval $i {report2}} msg4]
+
+    list $path1 $path2 -- $path3 $path4 -- $code3 $msg3 $code4 $msg4 -- $mappA -- $mappB
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:1:)} {$p(:2:)} -- {$p(:2:)} {$p(:1:)} -- 0 ok1 0 ok2 --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*} --\
+        {TCLLIB TESTSDIR/auto0/auto2 TESTSDIR/auto0/auto1*}}
+test safe-9.10 {interpConfigure change the access path; tclIndex commands unaffected by token rearrangement (actual test of doreset)} -setup {
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load auto_load data.
+    interp eval $i {catch nonExistentCommand}
+
+    # Do not load the commands.  With the tokens swapped, the test
+    # will pass only if the Safe Base has called auto_reset.
+
+    # Rearrange access path.  Swap tokens {$p(:1:)} and {$p(:2:)}.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto2] \
+                                           [file join $TestsDir auto0 auto1]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set mappB [mapList $PathMapp [dict get $confB -accessPath]]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load and run the commands.
+    set code3 [catch {interp eval $i {report1}} msg3]
+    set code4 [catch {interp eval $i {report2}} msg4]
+
+    list $path1 $path2 -- $path3 $path4 -- $code3 $msg3 $code4 $msg4 -- $mappA -- $mappB
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:1:)} {$p(:2:)} -- {$p(:2:)} {$p(:1:)} --\
+        0 ok1 0 ok2 --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*} --\
+        {TCLLIB TESTSDIR/auto0/auto2 TESTSDIR/auto0/auto1*}}
+test safe-9.11 {interpConfigure change the access path; pkgIndex.tcl packages unaffected by token rearrangement} -setup {
+} -body {
+    # For complete correspondence to safe-9.10opt, include auto0 in access path.
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0] \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load pkgIndex.tcl data.
+    catch {interp eval $i {package require NOEXIST}}
+
+    # Rearrange access path.  Swap tokens {$p(:2:)} and {$p(:3:)}.
+    # This would have no effect because the records in Pkg of these directories
+    # were from access as children of {$p(:1:)}.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0] \
+                                           [file join $TestsDir auto0 auto2] \
+                                           [file join $TestsDir auto0 auto1]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set mappB [mapList $PathMapp [dict get $confB -accessPath]]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Try to load the packages and run a command from each one.
+    set code3 [catch {interp eval $i {package require SafeTestPackage1}} msg3 opts3]
+    set code4 [catch {interp eval $i {package require SafeTestPackage2}} msg4 opts4]
+    set code5 [catch {interp eval $i {HeresPackage1}} msg5 opts5]
+    set code6 [catch {interp eval $i {HeresPackage2}} msg6 opts6]
+
+    list $path1 $path2 -- $path3 $path4 -- $code3 $msg3 $code4 $msg4 -- \
+         $mappA -- $mappB -- $code5 $msg5 $code6 $msg6
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:2:)} {$p(:3:)} -- {$p(:3:)} {$p(:2:)} -- 0 1.2.3 0 2.3.4 --\
+        {TCLLIB TESTSDIR/auto0 TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*} --\
+        {TCLLIB TESTSDIR/auto0 TESTSDIR/auto0/auto2 TESTSDIR/auto0/auto1*} --\
+        0 OK1 0 OK2}
+test safe-9.12 {interpConfigure change the access path; pkgIndex.tcl packages unaffected by token rearrangement, 9.10 without path auto0} -setup {
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load pkgIndex.tcl data.
+    catch {interp eval $i {package require NOEXIST}}
+
+    # Rearrange access path.  Swap tokens {$p(:1:)} and {$p(:2:)}.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto2] \
+                                           [file join $TestsDir auto0 auto1]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set mappB [mapList $PathMapp [dict get $confB -accessPath]]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Try to load the packages and run a command from each one.
+    set code3 [catch {interp eval $i {package require SafeTestPackage1}} msg3 opts3]
+    set code4 [catch {interp eval $i {package require SafeTestPackage2}} msg4 opts4]
+    set code5 [catch {interp eval $i {HeresPackage1}} msg5 opts5]
+    set code6 [catch {interp eval $i {HeresPackage2}} msg6 opts6]
+
+    list $path1 $path2 -- $path3 $path4 -- $code3 $msg3 $code4 $msg4 -- \
+            $mappA -- $mappB -- \
+            $code5 $msg5 $code6 $msg6
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:1:)} {$p(:2:)} -- {$p(:2:)} {$p(:1:)} --\
+        0 1.2.3 0 2.3.4 --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*} --\
+        {TCLLIB TESTSDIR/auto0/auto2 TESTSDIR/auto0/auto1*} --\
+        0 OK1 0 OK2}
+test safe-9.13 {interpConfigure change the access path; pkgIndex.tcl packages fail if directory de-listed} -setup {
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library \
+                                            [file join $TestsDir auto0 auto1] \
+                                            [file join $TestsDir auto0 auto2]]]
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set mappA [mapList $PathMapp [dict get $confA -accessPath]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]]
+
+    # Load pkgIndex.tcl data.
+    catch {interp eval $i {package require NOEXIST}}
+
+    # Limit access path.  Remove tokens {$p(:1:)} and {$p(:2:)}.
+    safe::interpConfigure $i -accessPath [list $tcl_library]
+
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set mappB [mapList $PathMapp [dict get $confB -accessPath]]
+    set code4 [catch {::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto1]} path4]
+    set code5 [catch {::safe::interpFindInAccessPath $i [file join $TestsDir auto0 auto2]} path5]
+
+    # Try to load the packages.
+    set code3 [catch {interp eval $i {package require SafeTestPackage1}} msg3]
+    set code6 [catch {interp eval $i {package require SafeTestPackage2}} msg6]
+
+    list $path1 $path2 -- $code4 $path4 -- $code5 $path5 -- $code3 $code6 -- \
+            $mappA -- $mappB
+} -cleanup {
+    safe::interpDelete $i
+} -match glob -result {{$p(:1:)} {$p(:2:)} -- 1 {* not found in access path} --\
+        1 {* not found in access path} -- 1 1 --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2*} -- {TCLLIB*}}
+test safe-9.20 {check module loading} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library]]
+
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set sortA [mapAndSortList $PathMapp [dict get $confA -accessPath]]
+    set modsA [interp eval $i {tcl::tm::path list}]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Try to load the packages and run a command from each one.
+    set code0 [catch {interp eval $i {package require test0}} msg0]
+    set code1 [catch {interp eval $i {package require mod1::test1}} msg1]
+    set code2 [catch {interp eval $i {package require mod2::test2}} msg2]
+    set out0  [interp eval $i {test0::try0}]
+    set out1  [interp eval $i {mod1::test1::try1}]
+    set out2  [interp eval $i {mod2::test2::try2}]
+
+    list [lsort [list $path0 $path1 $path2]] -- $modsA -- \
+            $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $sortA -- $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    safe::interpDelete $i
+} -match glob -result {{{$p(:1:)} {$p(:2:)} {$p(:3:)}} -- {{$p(:1:)}} --\
+        0 0.5 0 1.0 0 2.0 --\
+        {TCLLIB TESTSDIR/auto0/modules TESTSDIR/auto0/modules/mod1\
+         TESTSDIR/auto0/modules/mod2} -- res0 res1 res2}
+# - The command safe::InterpSetConfig adds the parent's [tcl::tm::list] in
+#   tokenized form to the child's access path, and then adds all the
+#   descendants, discovered recursively by using glob.
+# - The order of the directories in the list returned by glob is system-dependent,
+#   and therefore this is true also for (a) the order of token assignment to
+#   descendants of the [tcl::tm::list] roots; and (b) the order of those same
+#   directories in the access path.  Both those things must be sorted before
+#   comparing with expected results.  The test is therefore not totally strict,
+#   but will notice missing or surplus directories.
+test safe-9.21 {interpConfigure change the access path; check module loading; stale data case 1} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library]]
+
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set sortA [mapAndSortList $PathMapp [dict get $confA -accessPath]]
+    set modsA [interp eval $i {tcl::tm::path list}]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Add to access path.
+    # This injects more tokens, pushing modules to higher token numbers.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto1] \
+                                           [file join $TestsDir auto0 auto2]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set sortB [mapAndSortList $PathMapp [dict get $confB -accessPath]]
+    set modsB [interp eval $i {tcl::tm::path list}]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path5 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Load pkg data.
+    catch {interp eval $i {package require NOEXIST}}
+    catch {interp eval $i {package require mod1::NOEXIST}}
+    catch {interp eval $i {package require mod2::NOEXIST}}
+
+    # Try to load the packages and run a command from each one.
+    set code0 [catch {interp eval $i {package require test0}} msg0]
+    set code1 [catch {interp eval $i {package require mod1::test1}} msg1]
+    set code2 [catch {interp eval $i {package require mod2::test2}} msg2]
+    set out0  [interp eval $i {test0::try0}]
+    set out1  [interp eval $i {mod1::test1::try1}]
+    set out2  [interp eval $i {mod2::test2::try2}]
+
+    list [lsort [list $path0 $path1 $path2]] -- $modsA -- \
+            [lsort [list $path3 $path4 $path5]] -- $modsB -- \
+            $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $sortA -- $sortB -- \
+            $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    safe::interpDelete $i
+} -match glob -result {{{$p(:1:)} {$p(:2:)} {$p(:3:)}} -- {{$p(:1:)}} --\
+        {{$p(:3:)} {$p(:4:)} {$p(:5:)}} -- {{$p(:3:)}} --\
+        0 0.5 0 1.0 0 2.0 --\
+        {TCLLIB TESTSDIR/auto0/modules TESTSDIR/auto0/modules/mod1\
+         TESTSDIR/auto0/modules/mod2} --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2 TESTSDIR/auto0/modules\
+         TESTSDIR/auto0/modules/mod1 TESTSDIR/auto0/modules/mod2} --\
+        res0 res1 res2}
+# See comments on lsort after test safe-9.20.
+test safe-9.22 {interpConfigure change the access path; check module loading; stale data case 0} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library]]
+
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set sortA [mapAndSortList $PathMapp [dict get $confA -accessPath]]
+    set modsA [interp eval $i {tcl::tm::path list}]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Add to access path.
+    # This injects more tokens, pushing modules to higher token numbers.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                          [file join $TestsDir auto0 auto1] \
+                                          [file join $TestsDir auto0 auto2]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set sortB [mapAndSortList $PathMapp [dict get $confB -accessPath]]
+    set modsB [interp eval $i {tcl::tm::path list}]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path5 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Try to load the packages and run a command from each one.
+    set code0 [catch {interp eval $i {package require test0}} msg0]
+    set code1 [catch {interp eval $i {package require mod1::test1}} msg1]
+    set code2 [catch {interp eval $i {package require mod2::test2}} msg2]
+    set out0  [interp eval $i {test0::try0}]
+    set out1  [interp eval $i {mod1::test1::try1}]
+    set out2  [interp eval $i {mod2::test2::try2}]
+
+    list [lsort [list $path0 $path1 $path2]] -- $modsA -- \
+            [lsort [list $path3 $path4 $path5]] -- $modsB -- \
+            $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $sortA -- $sortB -- \
+            $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    safe::interpDelete $i
+} -match glob -result {{{$p(:1:)} {$p(:2:)} {$p(:3:)}} -- {{$p(:1:)}} --\
+        {{$p(:3:)} {$p(:4:)} {$p(:5:)}} -- {{$p(:3:)}} --\
+        0 0.5 0 1.0 0 2.0 --\
+        {TCLLIB TESTSDIR/auto0/modules TESTSDIR/auto0/modules/mod1\
+         TESTSDIR/auto0/modules/mod2} --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2 TESTSDIR/auto0/modules\
+         TESTSDIR/auto0/modules/mod1 TESTSDIR/auto0/modules/mod2} --\
+        res0 res1 res2}
+# See comments on lsort after test safe-9.20.
+test safe-9.23 {interpConfigure change the access path; check module loading; stale data case 3} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library]]
+
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set sortA [mapAndSortList $PathMapp [dict get $confA -accessPath]]
+    set modsA [interp eval $i {tcl::tm::path list}]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Force the interpreter to acquire pkg data which will soon become stale.
+    catch {interp eval $i {package require NOEXIST}}
+    catch {interp eval $i {package require mod1::NOEXIST}}
+    catch {interp eval $i {package require mod2::NOEXIST}}
+
+    # Add to access path.
+    # This injects more tokens, pushing modules to higher token numbers.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto1] \
+                                           [file join $TestsDir auto0 auto2]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set sortB [mapAndSortList $PathMapp [dict get $confB -accessPath]]
+    set modsB [interp eval $i {tcl::tm::path list}]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path5 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Refresh stale pkg data.
+    catch {interp eval $i {package require NOEXIST}}
+    catch {interp eval $i {package require mod1::NOEXIST}}
+    catch {interp eval $i {package require mod2::NOEXIST}}
+
+    # Try to load the packages and run a command from each one.
+    set code0 [catch {interp eval $i {package require test0}} msg0]
+    set code1 [catch {interp eval $i {package require mod1::test1}} msg1]
+    set code2 [catch {interp eval $i {package require mod2::test2}} msg2]
+    set out0  [interp eval $i {test0::try0}]
+    set out1  [interp eval $i {mod1::test1::try1}]
+    set out2  [interp eval $i {mod2::test2::try2}]
+
+    list [lsort [list $path0 $path1 $path2]] -- $modsA -- \
+            [lsort [list $path3 $path4 $path5]] -- $modsB -- \
+            $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $sortA -- $sortB -- \
+            $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    safe::interpDelete $i
+} -match glob -result {{{$p(:1:)} {$p(:2:)} {$p(:3:)}} -- {{$p(:1:)}} --\
+        {{$p(:3:)} {$p(:4:)} {$p(:5:)}} -- {{$p(:3:)}} --\
+        0 0.5 0 1.0 0 2.0 --\
+        {TCLLIB TESTSDIR/auto0/modules TESTSDIR/auto0/modules/mod1\
+         TESTSDIR/auto0/modules/mod2} --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2 TESTSDIR/auto0/modules\
+         TESTSDIR/auto0/modules/mod1 TESTSDIR/auto0/modules/mod2} --\
+        res0 res1 res2}
+# See comments on lsort after test safe-9.20.
+test safe-9.24 {interpConfigure change the access path; check module loading; stale data case 2 (worst case)} -setup {
+    set oldTm [tcl::tm::path list]
+    foreach path $oldTm {
+        tcl::tm::path remove $path
+    }
+    tcl::tm::path add [file join $TestsDir auto0 modules]
+} -body {
+    set i [safe::interpCreate -accessPath [list $tcl_library]]
+
+    # Inspect.
+    set confA [safe::interpConfigure $i]
+    set sortA [mapAndSortList $PathMapp [dict get $confA -accessPath]]
+    set modsA [interp eval $i {tcl::tm::path list}]
+    set path0 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path1 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path2 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Force the interpreter to acquire pkg data which will soon become stale.
+    catch {interp eval $i {package require NOEXIST}}
+    catch {interp eval $i {package require mod1::NOEXIST}}
+    catch {interp eval $i {package require mod2::NOEXIST}}
+
+    # Add to access path.
+    # This injects more tokens, pushing modules to higher token numbers.
+    safe::interpConfigure $i -accessPath [list $tcl_library \
+                                           [file join $TestsDir auto0 auto1] \
+                                           [file join $TestsDir auto0 auto2]]
+    # Inspect.
+    set confB [safe::interpConfigure $i]
+    set sortB [mapAndSortList $PathMapp [dict get $confB -accessPath]]
+    set modsB [interp eval $i {tcl::tm::path list}]
+    set path3 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules]]
+    set path4 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod1]]
+    set path5 [::safe::interpFindInAccessPath $i [file join $TestsDir auto0 modules mod2]]
+
+    # Try to load the packages and run a command from each one.
+    set code0 [catch {interp eval $i {package require test0}} msg0]
+    set code1 [catch {interp eval $i {package require mod1::test1}} msg1]
+    set code2 [catch {interp eval $i {package require mod2::test2}} msg2]
+    set out0  [interp eval $i {test0::try0}]
+    set out1  [interp eval $i {mod1::test1::try1}]
+    set out2  [interp eval $i {mod2::test2::try2}]
+
+    list [lsort [list $path0 $path1 $path2]] -- $modsA -- \
+            [lsort [list $path3 $path4 $path5]] -- $modsB -- \
+            $code0 $msg0 $code1 $msg1 $code2 $msg2 -- $sortA -- $sortB -- \
+            $out0 $out1 $out2
+} -cleanup {
+    tcl::tm::path remove [file join $TestsDir auto0 modules]
+    foreach path [lreverse $oldTm] {
+        tcl::tm::path add $path
+    }
+    safe::interpDelete $i
+} -match glob -result {{{$p(:1:)} {$p(:2:)} {$p(:3:)}} -- {{$p(:1:)}} --\
+        {{$p(:3:)} {$p(:4:)} {$p(:5:)}} -- {{$p(:3:)}} --\
+        0 0.5 0 1.0 0 2.0 --\
+        {TCLLIB TESTSDIR/auto0/modules TESTSDIR/auto0/modules/mod1\
+         TESTSDIR/auto0/modules/mod2} --\
+        {TCLLIB TESTSDIR/auto0/auto1 TESTSDIR/auto0/auto2 TESTSDIR/auto0/modules\
+         TESTSDIR/auto0/modules/mod1 TESTSDIR/auto0/modules/mod2} --\
+        res0 res1 res2}
+# See comments on lsort after test safe-9.20.
 
 catch {teststaticpkg Safepkg1 0 0}
 test safe-10.1 {testing statics loading} -constraints TcltestPackage -setup {
@@ -412,7 +1167,7 @@ test safe-10.1 {testing statics loading} -constraints TcltestPackage -setup {
     interp eval $i {load {} Safepkg1}
 } -returnCodes error -cleanup {
     safe::interpDelete $i
-} -result {can't use package in a safe interpreter: no Safepkg1_SafeInit procedure}
+} -result {load of binary library for package Safepkg1 failed: can't use package in a safe interpreter: no Safepkg1_SafeInit procedure}
 test safe-10.1.1 {testing statics loading} -constraints TcltestPackage -setup {
     set i [safe::interpCreate]
 } -body {
@@ -421,7 +1176,7 @@ test safe-10.1.1 {testing statics loading} -constraints TcltestPackage -setup {
 } -returnCodes ok -cleanup {
     unset -nocomplain m o
     safe::interpDelete $i
-} -result {can't use package in a safe interpreter: no Safepkg1_SafeInit procedure
+} -result {load of binary library for package Safepkg1 failed: can't use package in a safe interpreter: no Safepkg1_SafeInit procedure
     invoked from within
 "load {} Safepkg1"
     invoked from within
@@ -444,7 +1199,7 @@ test safe-10.4 {testing nested statics loading / -nestedloadok} -constraints Tcl
     interp eval $i {interp create x; load {} Safepkg1 x}
 } -returnCodes error -cleanup {
     safe::interpDelete $i
-} -result {can't use package in a safe interpreter: no Safepkg1_SafeInit procedure}
+} -result {load of binary library for package Safepkg1 failed: can't use package in a safe interpreter: no Safepkg1_SafeInit procedure}
 test safe-10.4.1 {testing nested statics loading / -nestedloadok} -constraints TcltestPackage -body {
     set i [safe::interpCreate -nestedloadok]
     catch {interp eval $i {interp create x; load {} Safepkg1 x}} m o
@@ -452,7 +1207,7 @@ test safe-10.4.1 {testing nested statics loading / -nestedloadok} -constraints T
 } -returnCodes ok -cleanup {
     unset -nocomplain m o
     safe::interpDelete $i
-} -result {can't use package in a safe interpreter: no Safepkg1_SafeInit procedure
+} -result {load of binary library for package Safepkg1 failed: can't use package in a safe interpreter: no Safepkg1_SafeInit procedure
     invoked from within
 "load {} Safepkg1 x"
     invoked from within
@@ -612,6 +1367,15 @@ proc buildEnvironment {filename} {
     set testdir2 [makeDirectory deletemetoo $testdir]
     set testfile [makeFile {} $filename $testdir2]
 }
+proc buildEnvironment2 {filename} {
+    upvar 1 testdir testdir testdir2 testdir2 testfile testfile
+    upvar 1 testdir3 testdir3 testfile2 testfile2
+    set testdir [makeDirectory deletethisdir]
+    set testdir2 [makeDirectory deletemetoo $testdir]
+    set testfile [makeFile {} $filename $testdir2]
+    set testdir3 [makeDirectory deleteme $testdir]
+    set testfile2 [makeFile {} $filename $testdir3]
+}
 #### New tests for Safe base glob, with patches @ Bug 2964715
 test safe-13.1 {glob is restricted [Bug 2964715]} -setup {
     set i [safe::interpCreate]
@@ -683,21 +1447,33 @@ test safe-13.6 {as 13.4 but test silent failure when result is outside access_pa
     safe::interpDelete $i
     removeDirectory $testdir
 } -result {}
-test safe-13.7 {mimic the glob call by tclPkgUnknown which gives a deliberate error in a safe interpreter [Bug 2964715]} -setup {
+test safe-13.7 {mimic the glob call by tclPkgUnknown in a safe interpreter [Bug 2964715]} -setup {
     set i [safe::interpCreate]
     buildEnvironment pkgIndex.tcl
 } -body {
     set safeTD [::safe::interpAddToAccessPath $i $testdir]
     ::safe::interpAddToAccessPath $i $testdir2
-    string map [list $safeTD EXPECTED] [$i eval [list \
+    mapList [list $safeTD EXPECTED] [$i eval [list \
+       glob -directory $safeTD -join * pkgIndex.tcl]]
+} -cleanup {
+    safe::interpDelete $i
+    removeDirectory $testdir
+} -result {EXPECTED/deletemetoo/pkgIndex.tcl}
+test safe-13.7.1 {mimic the glob call by tclPkgUnknown in a safe interpreter with multiple subdirectories} -setup {
+    set i [safe::interpCreate]
+    buildEnvironment2 pkgIndex.tcl
+} -body {
+    set safeTD [::safe::interpAddToAccessPath $i $testdir]
+    ::safe::interpAddToAccessPath $i $testdir2
+    ::safe::interpAddToAccessPath $i $testdir3
+    mapAndSortList [list $safeTD EXPECTED] [$i eval [list \
        glob -directory $safeTD -join * pkgIndex.tcl]]
 } -cleanup {
     safe::interpDelete $i
     removeDirectory $testdir
-} -result {{EXPECTED/deletemetoo/pkgIndex.tcl}}
-# Note the extra {} around the result above; that's *expected* because of the
-# format of virtual path roots.
-test safe-13.8 {mimic the glob call by tclPkgUnknown without the deliberate error that is specific to pkgIndex.tcl [Bug 2964715]} -setup {
+} -result {EXPECTED/deleteme/pkgIndex.tcl EXPECTED/deletemetoo/pkgIndex.tcl}
+# See comments on lsort after test safe-9.20.
+test safe-13.8 {mimic the glob call by tclPkgUnknown without the special treatment that is specific to pkgIndex.tcl [Bug 2964715]} -setup {
     set i [safe::interpCreate]
     buildEnvironment notIndex.tcl
 } -body {
@@ -735,9 +1511,10 @@ test safe-13.10 {as 13.8 but test silent failure when result is outside access_p
     removeDirectory $testdir
 } -result {}
 rename buildEnvironment {}
+rename buildEnvironment2 {}
 
 #### Test for the module path
-test safe-14.1 {Check that module path is the same as in the master interpreter [Bug 2964715]} -setup {
+test safe-14.1 {Check that module path is the same as in the parent interpreter [Bug 2964715]} -setup {
     set i [safe::interpCreate]
 } -body {
     set tm {}
@@ -765,7 +1542,7 @@ test safe-15.1 {safe file ensemble does not surprise code} -setup {
     unset -nocomplain msg
     interp delete $i
 } -result {1 {a b c} 1 {a b c} 1 {invalid command name "file"} 1 0 {a b c} 1 {not allowed to invoke subcommand isdirectory of file}}
-test safe-15.1.1 {safe file ensemble does not surprise code} -setup {
+test safe-15.2 {safe file ensemble does not surprise code} -setup {
     set i [interp create -safe]
 } -body {
     set result [expr {"file" in [interp hidden $i]}]
@@ -799,6 +1576,7 @@ test safe-16.1 {Bug 3529949: defang ~ in paths} -setup {
 } -cleanup {
     safe::interpDelete $i
     set env(HOME) $savedHOME
+    unset savedHOME
 } -result {./~}
 test safe-16.2 {Bug 3529949: defang ~user in paths} -setup {
     set i [safe::interpCreate]
@@ -808,6 +1586,7 @@ test safe-16.2 {Bug 3529949: defang ~user in paths} -setup {
            "file join \[file dirname ~$user\] \[file tail ~$user\]"]
 } -cleanup {
     safe::interpDelete $i
+    unset user
 } -result {./~USER}
 test safe-16.3 {Bug 3529949: defang ~ in globs} -setup {
     set syntheticHOME [makeDirectory foo]
@@ -822,6 +1601,7 @@ test safe-16.3 {Bug 3529949: defang ~ in globs} -setup {
     safe::interpDelete $i
     set env(HOME) $savedHOME
     removeDirectory $syntheticHOME
+    unset savedHOME syntheticHOME
 } -result {}
 test safe-16.4 {Bug 3529949: defang ~user in globs} -setup {
     set i [safe::interpCreate]
@@ -831,9 +1611,59 @@ test safe-16.4 {Bug 3529949: defang ~user in globs} -setup {
 } -cleanup {
     safe::interpDelete $i
 } -result {}
+test safe-16.5 {Bug 3529949: defang ~ in paths used by AliasGlob (1)} -setup {
+    set savedHOME $env(HOME)
+    set env(HOME) /foo/bar
+    set i [safe::interpCreate]
+} -body {
+    $i eval {
+       set d [format %c 126]
+       file join {$p(:0:)} $d
+    }
+} -cleanup {
+    safe::interpDelete $i
+    set env(HOME) $savedHOME
+    unset savedHOME
+} -result {~}
+test safe-16.6 {Bug 3529949: defang ~ in paths used by AliasGlob (2)} -setup {
+    set savedHOME $env(HOME)
+    set env(HOME) /foo/bar
+    set i [safe::interpCreate]
+} -body {
+    $i eval {
+       set d [format %c 126]
+       file join {$p(:0:)/foo/bar} $d
+    }
+} -cleanup {
+    safe::interpDelete $i
+    set env(HOME) $savedHOME
+    unset savedHOME
+} -result {~}
+test safe-16.7 {Bug 3529949: defang ~user in paths used by AliasGlob (1)} -setup {
+    set i [safe::interpCreate]
+    set user $tcl_platform(user)
+} -body {
+    string map [list $user USER] [$i eval [list file join {$p(:0:)} ~$user]]
+} -cleanup {
+    safe::interpDelete $i
+    unset user
+} -result {~USER}
+test safe-16.8 {Bug 3529949: defang ~user in paths used by AliasGlob (2)} -setup {
+    set i [safe::interpCreate]
+    set user $tcl_platform(user)
+} -body {
+    string map [list $user USER] [$i eval [list file join {$p(:0:)/foo/bar} ~$user]]
+} -cleanup {
+    safe::interpDelete $i
+    unset user
+} -result {~USER}
 \f
-set ::auto_path $saveAutoPath
 # cleanup
+set ::auto_path $SaveAutoPath
+unset SaveAutoPath TestsDir PathMapp
+unset -nocomplain path
+rename mapList {}
+rename mapAndSortList {}
 ::tcltest::cleanupTests
 return
 
index 98c581b..e3fab05 100644 (file)
@@ -12,7 +12,7 @@
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index eeabc9c..3235a1f 100644 (file)
@@ -11,7 +11,7 @@
 # All rights reserved.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 6138ed8..68e0497 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -940,7 +940,7 @@ catch {rename foo {}}
 
 # cleanup
 ::tcltest::cleanupTests
-return 
+return
 
 # Local Variables:
 # mode: tcl
index 374ff7a..303c2d7 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -561,7 +561,7 @@ catch {unset i}
 catch {unset x}
 catch {unset z}
 ::tcltest::cleanupTests
-return 
+return
 
 # Local Variables:
 # mode: tcl
index 1c77f06..0dfff53 100644 (file)
 # listening at port 2048. If all fails, a message is printed and the tests
 # using the remote server are not performed.
 
-package require tcltest 2
-namespace import -force ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
+
+::tcltest::loadTestedCommands
 
-if {[expr {[info exists ::env(TRAVIS_OSX_IMAGE)] && [string match xcode* $::env(TRAVIS_OSX_IMAGE)]}]} {
+# A bad interaction between socket creation, macOS, and unattended CI
+# environments make this whole file impractical to run; too many weird hangs.
+if {[info exists ::env(MAC_CI)]} {
     return
 }
 
@@ -233,7 +239,7 @@ if {$doTestsWithRemoteServer} {
 # Some tests are run only if we are doing testing against a remote server.
 testConstraint doTestsWithRemoteServer $doTestsWithRemoteServer
 if {!$doTestsWithRemoteServer} {
-    if {[string first s $::tcltest::verbose] != -1} {
+    if {[string first s $::tcltest::verbose] >= 0} {
        puts "Skipping tests with remote server. See tests/socket.test for"
        puts "information on how to run remote server."
        puts "Reason for not doing remote tests: $noRemoteTestReason"
@@ -279,6 +285,8 @@ proc getPort sock {
 # Some tests in this file are known to hang *occasionally* on OSX; stop the
 # worst offenders.
 testConstraint notOSX [expr {$::tcl_platform(os) ne "Darwin"}]
+# Here "Windows" means derived platforms as Cygwin or Msys2 too.
+testConstraint notWindows [expr {![regexp {^(Windows|MSYS|CYGWIN)} $::tcl_platform(os)]}]
 \f
 # ----------------------------------------------------------------------
 
@@ -903,7 +911,7 @@ test socket_$af-5.1 {byte order problems, socket numbers, htons} -body {
         return {htons problem, should be disallowed, are you running as SU?}
     }
     return {couldn't open socket: not owner}
-} -constraints [list socket supported_$af unix notRoot] -result {couldn't open socket: not owner}
+} -constraints [list socket supported_$af unix notRoot notOSX notWindows] -result {couldn't open socket: not owner}
 test socket_$af-5.2 {byte order problems, socket numbers, htons} -body {
     if {![catch {socket -server dodo 0x10000} msg]} {
        close $msg
@@ -917,7 +925,7 @@ test socket_$af-5.3 {byte order problems, socket numbers, htons} -body {
        return {htons problem, should be disallowed, are you running as SU?}
     }
     return {couldn't open socket: not owner}
-} -constraints [list socket supported_$af unix notRoot] -result {couldn't open socket: not owner}
+} -constraints [list socket supported_$af unix notRoot notOSX notWindows] -result {couldn't open socket: not owner}
 
 test socket_$af-6.1 {accept callback error} -constraints [list socket supported_$af stdio] -setup {
     proc myHandler {msg options} {
@@ -935,7 +943,7 @@ test socket_$af-6.1 {accept callback error} -constraints [list socket supported_
     }
     close $f
     set f [open "|[list [interpreter] $path(script)]" r+]
-    proc accept {s a p} {expr 10 / 0}
+    proc accept {s a p} {expr {10 / 0}}
     set s [socket -server accept -myaddr $localhost 0]
     puts $f [lindex [fconfigure $s -sockname] 2]
     close $f
@@ -1816,6 +1824,105 @@ test socket_$af-13.1 {Testing use of shared socket between two threads} -body {
     thread::release $serverthread
     append result " " [llength [thread::names]]
 } -result {hello 1} -constraints [list socket supported_$af thread]
+
+proc transf_test {{testmode transfer} {maxIter 1000} {maxTime 10000}} {
+  try {
+    set ::count 0
+    set ::testmode $testmode
+    set port 0
+    set srvsock {}
+    # if binding on port 0 is not possible (system related, blocked on ISPs etc):
+    if {[catch {close [socket -async $::localhost $port]}]} {
+      # simplest server on random port (immediatelly closing a connect):
+      set port [randport]
+      set srvsock [socket -server {apply {{ch args} {close $ch}}} -myaddr $::localhost $port]
+      # socket on windows has some issues yet (e. g. bug [b6d0d8cc2c]), so we simply decrease iteration count (to 1/4):
+      if {$::tcl_platform(platform) eq "windows" && $maxIter > 50} {
+       set ::count [expr {$maxIter / 4 * 3 - 1}]; # bypass 3/4 iterations
+      }
+    }
+    tcltest::DebugPuts 2 "== test \[$::localhost\]:$port $testmode =="
+    set ::parent [thread::id]
+    # helper thread creating async connection and initiating transfer (detach) to parent:
+    set ::helper [thread::create]
+    thread::send -async $::helper [list \
+      lassign [list $::parent $::localhost $port $testmode] \
+                     ::parent ::localhost ::port ::testmode
+    ]
+    thread::send -async $::helper {
+      set ::helper [thread::id]
+      proc iteration {args} {
+        set fd [socket -async $::localhost $::port]
+        if {"helper-writable" in $::testmode} {;# to test both sides during connect
+          fileevent $fd writable [list apply {{fd} {
+            if {[thread::id] ne $::helper} {
+              thread::send -async $::parent {set ::count "ERROR: invalid thread, $::helper is expecting"}
+              close $fd
+              return
+            }
+          }} $fd]
+        };#
+        thread::detach $fd
+        thread::send -async $::parent [list transf_parent $fd {*}$args]
+      }
+      iteration first
+    }
+    # parent proc commiting transfer attempt (attach) and checking acquire was successful:
+    proc transf_parent {fd args} {
+      tcltest::DebugPuts 2 "** trma / $::count ** $args **"
+      thread::attach $fd
+      if {"parent-close" in $::testmode} {;# to test close during connect
+        set ::count $::count
+        close $fd
+        return
+      };#
+      fileevent $fd writable [list apply {{fd} {
+        if {[thread::id] ne $::parent} {
+          thread::send -async $::parent {set ::count "ERROR: invalid thread, $::parent is expecting"}
+          close $fd
+          return
+        }
+        set ::count $::count
+        close $fd
+      }} $fd]
+    }
+    # repeat maxIter times (up to maxTime ms as timeout):
+    set tout [after $maxTime {set ::count "TIMEOUT"}]
+    while 1 {
+      vwait ::count
+      if {![string is integer $::count]} {
+        # if timeout just skip (test was successful until now):
+       if {$::count eq "TIMEOUT"} {::tcltest::Skip "timing issue"}
+        break
+      }
+      if {[incr ::count] >= $maxIter} break
+      tcltest::DebugPuts 2 "** iter / $::count **"
+      thread::send -async $::helper [list iteration nr $::count]
+    }
+    update
+    set ::count
+  } finally {
+    catch {after cancel $tout}
+    if {$srvsock ne {}} {close $srvsock}
+    if {[info exists ::helper]} {thread::release -wait $::helper}
+    tcltest::DebugPuts 2 "== stop / $::count =="
+    unset -nocomplain ::count ::testmode ::parent ::helper
+  }
+}
+test socket_$af-13.2.tr1 {Testing socket transfer between threads during async connect} -body {
+    transf_test {transfer} 1000
+} -result 1000 -constraints [list socket supported_$af thread]
+test socket_$af-13.2.tr2 {Testing socket transfer between threads during async connect} -body {
+    transf_test {transfer helper-writable} 100
+} -result 100 -constraints [list socket supported_$af thread]
+test socket_$af-13.2.cl1 {Testing socket transfer between threads during async connect} -body {
+    transf_test {parent-close} 100
+} -result 100 -constraints [list socket supported_$af thread]
+test socket_$af-13.2.cl2 {Testing socket transfer between threads during async connect} -body {
+    transf_test {parent-close helper-writable} 100
+} -result 100 -constraints [list socket supported_$af thread]
+catch {rename transf_parent {}}
+rename transf_test {}
 \f
 # ----------------------------------------------------------------------
 
index 18055b3..8e82367 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index 13bc524..44417df 100644 (file)
@@ -9,8 +9,10 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 # Note that a failure in this test may result in a crash of the executable.
 
index a3590e5..46eb6fd 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -24,7 +24,8 @@ catch [list package require -exact Tcltest [info patchlevel]]
 
 testConstraint testobj [expr {[info commands testobj] != {}}]
 testConstraint testindexobj [expr {[info commands testindexobj] != {}}]
-testConstraint tip389 [expr {[string length \U010000] == 2}]
+testConstraint utf16 [expr {[string length \U010000] == 2}]
+testConstraint testbytestring   [llength [info commands testbytestring]]
 
 # Used for constraining memory leak tests
 testConstraint memory [llength [info commands memory]]
@@ -36,7 +37,7 @@ test string-1.2 {error conditions} {
     list [catch {string} msg] $msg
 } {1 {wrong # args: should be "string subcommand ?arg ...?"}}
 
-test string-2.1 {string compare, too few args} {
+test string-2.1 {string compare, not enough args} {
     list [catch {string compare a} msg] $msg
 } {1 {wrong # args: should be "string compare ?-nocase? ?-length int? string1 string2"}}
 test string-2.2 {string compare, bad args} {
@@ -70,11 +71,11 @@ test string-2.11 {string compare, unicode} {
     string compare ab\u7266 ab\u7267
 } -1
 test string-2.12 {string compare, high bit} {
-    # This test will fail if the underlying comparaison
+    # This test will fail if the underlying comparison
     # is using signed chars instead of unsigned chars.
     # (like SunOS's default memcmp thus the compat/memcmp.c)
     string compare "\x80" "@"
-    # Nb this tests works also in utf8 space because \x80 is
+    # Nb this tests works also in utf-8 space because \x80 is
     # translated into a 2 or more bytelength but whose first byte has
     # the high bit set.
 } 1
@@ -148,6 +149,18 @@ test string-2.33 {string compare, high bit} {
     proc foo {} {string compare "\x00\x00" "\x00\x01"}
     foo
 } -1
+test string-2.34 {string compare, binary equal} {
+    proc foo {} {string compare [binary format a100 0] [binary format a100 0]}
+   foo
+} 0
+test string-2.35 {string compare, binary neq} {
+    proc foo {} {string compare [binary format a100a 0 1] [binary format a100a 0 0]}
+    foo
+} 1
+test string-2.36 {string compare, binary neq unequal length} {
+    proc foo {} {string compare [binary format a20a 0 1] [binary format a100a 0 0]}
+    foo
+} 1
 
 # only need a few tests on equal, since it uses the same code as
 # string compare, but just modifies the return output
@@ -176,7 +189,7 @@ test string-3.8 {string equal with length, unequal strings} {
     string equal -length 2 abc abde
 } 1
 
-test string-4.1 {string first, too few args} {
+test string-4.1 {string first, not enough args} {
     list [catch {string first a} msg] $msg
 } {1 {wrong # args: should be "string first needleString haystackString ?startIndex?"}}
 test string-4.2 {string first, bad args} {
@@ -222,7 +235,7 @@ test string-4.15 {string first, ability to two-byte encoded utf-8 chars} {
     # Test for a bug in Tcl 8.3 where test for all-single-byte-encoded
     # strings was incorrect, leading to an index returned by [string first]
     # which pointed past the end of the string.
-    set uchar \u057e    ;# character with two-byte encoding in utf-8
+    set uchar \u057E    ;# character with two-byte encoding in utf-8
     string first % %#$uchar$uchar#$uchar$uchar#% 3
 } 8
 test string-4.17 {string first, corner case} {
@@ -309,9 +322,6 @@ test string-5.19 {string index, bytearray object out of bounds} {
 test string-5.20 {string index, bytearray object out of bounds} {
     string index [binary format I* {0x50515253 0x52}] 20
 } {}
-test string-5.21 {string index, surrogates, bug [11ae2be95dac9417]} tip389 {
-    list [string index a\U100000b 1] [string index a\U100000b 2] [string index a\U100000b 3]
-} [list \U100000 {} b]
 
 
 proc largest_int {} {
@@ -323,10 +333,10 @@ proc largest_int {} {
     return [expr {$int-1}]
 }
 
-test string-6.1 {string is, too few args} {
+test string-6.1 {string is, not enough args} {
     list [catch {string is} msg] $msg
 } {1 {wrong # args: should be "string is class ?-strict? ?-failindex var? str"}}
-test string-6.2 {string is, too few args} {
+test string-6.2 {string is, not enough args} {
     list [catch {string is alpha} msg] $msg
 } {1 {wrong # args: should be "string is class ?-strict? ?-failindex var? str"}}
 test string-6.3 {string is, bad args} {
@@ -395,7 +405,7 @@ test string-6.24 {string is digit, true} {
     string is digit 0123456789
 } 1
 test string-6.25 {string is digit, false} {
-    list [string is digit -fail var 0123\u00dc567] $var
+    list [string is digit -fail var 0123\u00DC567] $var
 } {0 4}
 test string-6.26 {string is digit, false} {
     list [string is digit -fail var +123567] $var
@@ -518,7 +528,7 @@ test string-6.60 {string is lower, true} {
     string is lower abc
 } 1
 test string-6.61 {string is lower, unicode true} {
-    string is lower abc\u00fcue
+    string is lower abc\u00FCue
 } 1
 test string-6.62 {string is lower, false} {
     list [string is lower -fail var aBc] $var
@@ -527,7 +537,7 @@ test string-6.63 {string is lower, false} {
     list [string is lower -fail var abc1] $var
 } {0 3}
 test string-6.64 {string is lower, unicode false} {
-    list [string is lower -fail var ab\u00dcUE] $var
+    list [string is lower -fail var ab\u00DCUE] $var
 } {0 2}
 test string-6.65 {string is space, true} {
     string is space " \t\n\v\f"
@@ -565,7 +575,7 @@ test string-6.75 {string is upper, true} {
     string is upper ABC
 } 1
 test string-6.76 {string is upper, unicode true} {
-    string is upper ABC\u00dcUE
+    string is upper ABC\u00DCUE
 } 1
 test string-6.77 {string is upper, false} {
     list [string is upper -fail var AbC] $var
@@ -574,13 +584,13 @@ test string-6.78 {string is upper, false} {
     list [string is upper -fail var AB2C] $var
 } {0 2}
 test string-6.79 {string is upper, unicode false} {
-    list [string is upper -fail var ABC\u00fcue] $var
+    list [string is upper -fail var ABC\u00FCue] $var
 } {0 3}
 test string-6.80 {string is wordchar, true} {
     string is wordchar abc_123
 } 1
 test string-6.81 {string is wordchar, unicode true} {
-    string is wordchar abc\u00fcab\u00dcAB\u5001
+    string is wordchar abc\u00FCab\u00DCAB\u5001
 } 1
 test string-6.82 {string is wordchar, false} {
     list [string is wordchar -fail var abcd.ef] $var
@@ -606,7 +616,7 @@ test string-6.87 {string is print} {
 } {0 15}
 test string-6.88 {string is punct} {
     ## any graph char that isn't alnum
-    list [string is punct -fail var "_!@#\u00beq0"] $var
+    list [string is punct -fail var "_!@#\u00BEq0"] $var
 } {0 4}
 test string-6.89 {string is xdigit} {
     list [string is xdigit -fail var 0123456789\u0061bcdefABCDEFg] $var
@@ -699,7 +709,7 @@ test string-6.108 {string is double, Bug 1382287} {
     string is double $x
 } 0
 test string-6.109 {string is double, Bug 1360532} {
-    string is double 1\u00a0
+    string is double 1\u00A0
 } 0
 test string-6.110 {string is entier, true} {
     string is entier +1234567890
@@ -776,7 +786,7 @@ test string-6.131 {string is entier, false on bad hex} {
 
 catch {rename largest_int {}}
 
-test string-7.1 {string last, too few args} {
+test string-7.1 {string last, not enough args} {
     list [catch {string last a} msg] $msg
 } {1 {wrong # args: should be "string last needleString haystackString ?startIndex?"}}
 test string-7.2 {string last, bad args} {
@@ -862,7 +872,7 @@ test string-9.7 {string length, bytearray object} {
     string length [binary format I* {0x50515253 0x52}]
 } 8
 
-test string-10.1 {string map, too few args} {
+test string-10.1 {string map, not enough args} {
     list [catch {string map} msg] $msg
 } {1 {wrong # args: should be "string map ?-nocase? charMap string"}}
 test string-10.2 {string map, bad args} {
@@ -962,7 +972,7 @@ test string-10.31 {string map, nasty sharing crash from [Bug 1018562]} {
     string map $a $a
 } {b b}
 
-test string-11.1 {string match, too few args} {
+test string-11.1 {string match, not enough args} {
     list [catch {string match a} msg] $msg
 } {1 {wrong # args: should be "string match ?-nocase? pattern string"}}
 test string-11.2 {string match, too many args} {
@@ -1278,8 +1288,8 @@ test string-12.19 {string range, bytearray object} {
     string equal $r1 $r2
 } 1
 test string-12.20 {string range, out of bounds indices} {
-    string range \u00ff 0 1
-} \u00ff
+    string range \u00FF 0 1
+} \u00FF
 # Bug 1410553
 test string-12.21 {string range, regenerates correct reps, bug 1410553} {
     set bytes "\x00 \x03 \x41"
@@ -1301,7 +1311,7 @@ test string-12.22 {string range, shimmering binary/index} {
     binary scan $s a* x
     string range $s $s end
 } 000000001
-test string-12.23 {string range, surrogates, bug [11ae2be95dac9417]} tip389 {
+test string-12.23 {string range, surrogates, bug [11ae2be95dac9417]} utf16 {
     list [string range a\U100000b 1 1] [string range a\U100000b 2 2] [string range a\U100000b 3 3]
 } [list \U100000 {} b]
 
@@ -1406,7 +1416,7 @@ test string-14.19 {string replace} {
     string replace {} -1 0 A
 } A
 
-test string-15.1 {string tolower too few args} {
+test string-15.1 {string tolower not enough args} {
     list [catch {string tolower} msg] $msg
 } {1 {wrong # args: should be "string tolower string ?first? ?last?"}}
 test string-15.2 {string tolower bad args} {
@@ -1490,18 +1500,14 @@ test string-17.5 {string totitle} {
     string totitle {123#$&*()}
 } {123#$&*()}
 test string-17.6 {string totitle, unicode} {
-    string totitle ABCabc\xc7\xe7
-} "Abcabc\xe7\xe7"
+    string totitle ABCabc\xC7\xE7
+} "Abcabc\xE7\xE7"
 test string-17.7 {string totitle, unicode} {
-    string totitle \u01f3BCabc\xc7\xe7
-} "\u01f2bcabc\xe7\xe7"
+    string totitle \u01F3BCabc\xc7\xe7
+} "\u01F2bcabc\xe7\xe7"
 test string-17.8 {string totitle, compiled} {
     lindex [string totitle [list aa bb [list cc]]] 0
 } Aa
-test string-17.9 {string totitle, surrogates, bug [11ae2be95dac9417]} tip389 {
-    list [string totitle a\U118c0c 1 1] [string totitle a\U118c0c 2 2] \
-       [string totitle a\U118c0c 3 3]
-} [list a\U118a0c a\U118c0C a\U118c0C]
 
 test string-18.1 {string trim} {
     list [catch {string trim} msg] $msg
@@ -1537,7 +1543,7 @@ test string-18.11 {string trim, unicode} {
     string trim "\xe7\xe8 AB\xe7C \xe8\xe7" \xe7\xe8
 } " AB\xe7C "
 test string-18.12 {string trim, unicode default} {
-    string trim \ufeff\x00\u0085\u00a0\u1680\u180eABC\u1361\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000
+    string trim \uFEFF\x00\u0085\u00A0\u1680\u180EABC\u1361\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u202F\u205F\u3000
 } ABC\u1361
 
 test string-19.1 {string trimleft} {
@@ -1547,7 +1553,7 @@ test string-19.2 {string trimleft} {
     string trimleft "    XYZ      "
 } {XYZ      }
 test string-19.3 {string trimleft, unicode default} {
-    string trimleft \ufeff\u0085\u00a0\x00\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000\u1361ABC
+    string trimleft \uFEFF\u0085\u00A0\x00\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u202F\u205F\u3000\u1361ABC
 } \u1361ABC
 
 test string-20.1 {string trimright errors} {
@@ -1566,8 +1572,36 @@ test string-20.5 {string trimright} {
     string trimright ""
 } {}
 test string-20.6 {string trimright, unicode default} {
-    string trimright ABC\u1361\u0085\x00\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u202f\u205f\u3000
+    string trimright ABC\u1361\u0085\x00\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u202F\u205F\u3000
 } ABC\u1361
+test string-20.7 {string trim on not valid utf-8 sequence (consider NTS as continuation char), bug [c61818e4c9]} testbytestring {
+    set result {}
+    set a [testbytestring \xc0\x80\xA0]
+    set b foo$a
+    set m [list \u0000 U \xA0 V [testbytestring \xA0] W]
+    lappend result [string map $m $b]
+    lappend result [string map $m [string trimright $b x]]
+    lappend result [string map $m [string trimright $b \u0000]]
+    lappend result [string map $m [string trimleft $b fox]]
+    lappend result [string map $m [string trimleft $b fo\u0000]]
+    lappend result [string map $m [string trim $b fox]]
+    lappend result [string map $m [string trim $b fo\u0000]]
+} [list {*}[lrepeat 3 fooUV] {*}[lrepeat 2 UV V]]
+test string-20.8 {[c61818e4c9] [string trimright] fails when UtfPrev is ok} testbytestring {
+    set result {}
+    set a [testbytestring \xE8\xA0]
+    set b foo$a
+    set m [list \xE8 U \xA0 V [testbytestring \xE8] W [testbytestring \xA0] X]]
+    lappend result [string map $m $b]
+    lappend result [string map $m [string trimright $b x]]
+    lappend result [string map $m [string trimright $b \xE8]]
+    lappend result [string map $m [string trimright $b [bytestring \xE8]]]
+    lappend result [string map $m [string trimright $b \xA0]]
+    lappend result [string map $m [string trimright $b [bytestring \xA0]]]
+    lappend result [string map $m [string trimright $b \xE8\xA0]]
+    lappend result [string map $m [string trimright $b [bytestring \xE8\xA0]]]
+    lappend result [string map $m [string trimright $b \u0000]]
+} [list {*}[lrepeat 4 fooUV] {*}[lrepeat 2 fooU] {*}[lrepeat 2 foo] fooUV]
 
 test string-21.1 {string wordend} {
     list [catch {string wordend a} msg] $msg
@@ -1597,19 +1631,19 @@ test string-21.9 {string wordend} {
     string worde "x.y" end-1
 } 2
 test string-21.10 {string wordend, unicode} {
-    string wordend "xyz\u00c7de fg" 0
+    string wordend "xyz\u00C7de fg" 0
 } 6
 test string-21.11 {string wordend, unicode} {
-    string wordend "xyz\uc700de fg" 0
+    string wordend "xyz\uC700de fg" 0
 } 6
 test string-21.12 {string wordend, unicode} {
-    string wordend "xyz\u203fde fg" 0
+    string wordend "xyz\u203Fde fg" 0
 } 6
 test string-21.13 {string wordend, unicode} {
     string wordend "xyz\u2045de fg" 0
 } 3
 test string-21.14 {string wordend, unicode} {
-    string wordend "\uc700\uc700 abc" 8
+    string wordend "\uC700\uC700 abc" 8
 } 6
 
 test string-22.1 {string wordstart} {
@@ -1643,14 +1677,19 @@ test string-22.10 {string wordstart} {
     string wordstart "one two three" end-5
 } 7
 test string-22.11 {string wordstart, unicode} {
-    string wordstart "one tw\u00c7o three" 7
+    string wordstart "one tw\u00C7o three" 7
 } 4
 test string-22.12 {string wordstart, unicode} {
-    string wordstart "ab\uc700\uc700 cdef ghi" 12
+    string wordstart "ab\uC700\uC700 cdef ghi" 12
 } 10
 test string-22.13 {string wordstart, unicode} {
-    string wordstart "\uc700\uc700 abc" 8
+    string wordstart "\uC700\uC700 abc" 8
 } 3
+test string-22.14 {string wordstart, invalid UTF-8} testbytestring {
+    # See Bug c61818e4c9
+    set demo [testbytestring "abc def\xE0\xA9ghi"]
+    string index $demo [string wordstart $demo 10]
+} g
 
 test string-23.0 {string is boolean, Bug 1187123} testindexobj {
     set x 5
@@ -1720,40 +1759,40 @@ test string-24.4 {string reverse command - unshared string} {
     string reverse $x$y
 } edcba
 test string-24.5 {string reverse command - shared unicode string} {
-    set x abcde\ud0ad
+    set x abcde\uD0AD
     string reverse $x
-} \ud0adedcba
+} \uD0ADedcba
 test string-24.6 {string reverse command - unshared string} {
     set x abc
-    set y de\ud0ad
+    set y de\uD0AD
     string reverse $x$y
-} \ud0adedcba
+} \uD0ADedcba
 test string-24.7 {string reverse command - simple case} {
     string reverse a
 } a
 test string-24.8 {string reverse command - simple case} {
-    string reverse \ud0ad
-} \ud0ad
+    string reverse \uD0AD
+} \uD0AD
 test string-24.9 {string reverse command - simple case} {
     string reverse {}
 } {}
 test string-24.10 {string reverse command - corner case} {
-    set x \ubeef\ud0ad
+    set x \uBEEF\uD0AD
     string reverse $x
-} \ud0ad\ubeef
+} \uD0AD\uBEEF
 test string-24.11 {string reverse command - corner case} {
-    set x \ubeef
-    set y \ud0ad
+    set x \uBEEF
+    set y \uD0AD
     string reverse $x$y
-} \ud0ad\ubeef
+} \uD0AD\uBEEF
 test string-24.12 {string reverse command - corner case} {
-    set x \ubeef
-    set y \ud0ad
+    set x \uBEEF
+    set y \uD0AD
     string is ascii [string reverse $x$y]
 } 0
 test string-24.13 {string reverse command - pure Unicode string} {
-    string reverse [string range \ubeef\ud0ad\ubeef\ud0ad\ubeef\ud0ad 1 5]
-} \ud0ad\ubeef\ud0ad\ubeef\ud0ad
+    string reverse [string range \uBEEF\uD0AD\uBEEF\uD0AD\uBEEF\uD0AD 1 5]
+} \uD0AD\uBEEF\uD0AD\uBEEF\uD0AD
 test string-24.14 {string reverse command - pure bytearray} {
     binary scan [string reverse [binary format H* 010203]] H* x
     set x
@@ -1809,10 +1848,10 @@ test string-25.13 {string is list} {
 } {0 2}
 test string-25.14 {string is list} {
     set x {}
-    list [string is list -failindex x "\uabcd {b c}d e"] $x
+    list [string is list -failindex x "\uABCD {b c}d e"] $x
 } {0 2}
 
-test string-26.1 {tcl::prefix, too few args} -body {
+test string-26.1 {tcl::prefix, not enough args} -body {
     tcl::prefix match a
 } -returnCodes 1 -result {wrong # args: should be "tcl::prefix match ?options? table string"}
 test string-26.2 {tcl::prefix, bad args} -body {
@@ -1939,7 +1978,7 @@ test string-26.13 {tcl::prefix: testing for leaks} -body {
     }
 } -constraints memory -result {0}
 
-test string-27.1 {tcl::prefix all, too few args} -body {
+test string-27.1 {tcl::prefix all, not enough args} -body {
     tcl::prefix all a
 } -returnCodes 1 -result {wrong # args: should be "tcl::prefix all table string"}
 test string-27.2 {tcl::prefix all, bad args} -body {
@@ -1970,7 +2009,7 @@ test string-27.10 {tcl::prefix all} {
     tcl::prefix all {apa aska appa} {}
 } {apa aska appa}
 
-test string-28.1 {tcl::prefix longest, too few args} -body {
+test string-28.1 {tcl::prefix longest, not enough args} -body {
     tcl::prefix longest a
 } -returnCodes 1 -result {wrong # args: should be "tcl::prefix longest table string"}
 test string-28.2 {tcl::prefix longest, bad args} -body {
@@ -2007,7 +2046,7 @@ test string-28.12 {tcl::prefix longest} {
     tcl::prefix longest {apa {} appa} {}
 } {}
 test string-28.13 {tcl::prefix longest} {
-    # Test UTF8 handling
+    # Test utf-8 handling
     tcl::prefix longest {ax\x90 bep ax\x91} a
 } ax
 
index 2aeb08e..a17390d 100644 (file)
@@ -15,8 +15,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -100,11 +100,11 @@ foreach {tname tbody tresult tcode} {
     {unicode} {string compare \334 \u00fc} -1 {}
     {unicode} {string compare \334\334\334\374\374 \334\334\334\334\334} 1 {}
     {high bit} {
-       # This test will fail if the underlying comparaison
+       # This test will fail if the underlying comparison
        # is using signed chars instead of unsigned chars.
        # (like SunOS's default memcmp thus the compat/memcmp.c)
        string compare "\x80" "@"
-       # Nb this tests works also in utf8 space because \x80 is
+       # Nb this tests works also in utf-8 space because \x80 is
        # translated into a 2 or more bytelength but whose first byte has
        # the high bit set.
     } {1} {}
index 8209142..bfe9da1 100644 (file)
@@ -12,8 +12,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -27,8 +27,8 @@ testConstraint testdstring [llength [info commands testdstring]]
 test stringObj-1.1 {string type registration} testobj {
     set t [testobj types]
     set first [string first "string" $t]
-    set result [expr {$first != -1}]
-} {1}
+    set result [expr {$first >= 0}]
+} 1
 
 test stringObj-2.1 {Tcl_NewStringObj} testobj {
     set result ""
@@ -414,10 +414,10 @@ test stringObj-13.3 {Tcl_GetCharLength with byte-size chars} testobj {
     list [string length $a] [string length $a]
 } {6 6}
 test stringObj-13.4 {Tcl_GetCharLength with mixed width chars} testobj {
-    string length "\u00ae" 
+    string length "\u00ae"
 } 1
 test stringObj-13.5 {Tcl_GetCharLength with mixed width chars} testobj {
-    # string length "○○" 
+    # string length "○○"
     # Use \uXXXX notation below instead of hardcoding the values, otherwise
     # the test will fail in multibyte locales.
     string length "\u00EF\u00BF\u00AE\u00EF\u00BF\u00AE"
index 2115772..8a8b3f1 100644 (file)
@@ -11,7 +11,7 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
+if {"::tcltest" ni [namespace children]} {
     package require tcltest 2.1
     namespace import -force ::tcltest::*
 }
@@ -91,29 +91,29 @@ test subst-5.4 {command substitutions} {
 } {1 {invalid command name "bogus_command"}}
 test subst-5.5 {command substitutions} {
     set a 0
-    list [catch {subst {[set a 1}} msg] $a $msg 
+    list [catch {subst {[set a 1}} msg] $a $msg
 } {1 0 {missing close-bracket}}
 test subst-5.6 {command substitutions} {
     set a 0
-    list [catch {subst {0[set a 1}} msg] $a $msg 
+    list [catch {subst {0[set a 1}} msg] $a $msg
 } {1 0 {missing close-bracket}}
 test subst-5.7 {command substitutions} {
     set a 0
-    list [catch {subst {0[set a 1; set a 2}} msg] $a $msg 
+    list [catch {subst {0[set a 1; set a 2}} msg] $a $msg
 } {1 1 {missing close-bracket}}
 
 # repeat the tests above simulating cmd line input
 test subst-5.8 {command substitutions} {
     set script {[subst {[set a 1}]}
-    list [catch {exec [info nameofexecutable] << $script} msg] $msg 
+    list [catch {exec [info nameofexecutable] << $script} msg] $msg
 } {1 {missing close-bracket}}
 test subst-5.9 {command substitutions} {
     set script {[subst {0[set a 1}]}
-    list [catch {exec [info nameofexecutable] << $script} msg] $msg 
+    list [catch {exec [info nameofexecutable] << $script} msg] $msg
 } {1 {missing close-bracket}}
 test subst-5.10 {command substitutions} {
     set script {[subst {0[set a 1; set a 2}]}
-    list [catch {exec [info nameofexecutable] << $script} msg] $msg 
+    list [catch {exec [info nameofexecutable] << $script} msg] $msg
 } {1 {missing close-bracket}}
 
 test subst-6.1 {clear the result after command substitution} -body {
@@ -132,20 +132,20 @@ test subst-7.3 {switches} -returnCodes error -body {
 } -result {bad option "-bogus": must be -nobackslashes, -nocommands, or -novariables}
 test subst-7.4 {switches} {
     set x 123
-    subst -nobackslashes {abc $x [expr 1+2] \\\x41}
+    subst -nobackslashes {abc $x [expr {1 + 2}] \\\x41}
 } {abc 123 3 \\\x41}
 test subst-7.5 {switches} {
     set x 123
-    subst -nocommands {abc $x [expr 1+2] \\\x41}
-} {abc 123 [expr 1+2] \A}
+    subst -nocommands {abc $x [expr {1 + 2}] \\\x41}
+} {abc 123 [expr {1 + 2}] \A}
 test subst-7.6 {switches} {
     set x 123
-    subst -novariables {abc $x [expr 1+2] \\\x41}
+    subst -novariables {abc $x [expr {1 + 2}] \\\x41}
 } {abc $x 3 \A}
 test subst-7.7 {switches} {
     set x 123
-    subst -nov -nob -noc {abc $x [expr 1+2] \\\x41}
-} {abc $x [expr 1+2] \\\x41}
+    subst -nov -nob -noc {abc $x [expr {1 + 2}] \\\x41}
+} {abc $x [expr {1 + 2}] \\\x41}
 
 test subst-8.1 {return in a subst} {
     subst {foo [return {x}; bogus code] bar}
@@ -166,7 +166,7 @@ test subst-8.6 {return in a subst} -returnCodes error -body {
     subst "foo \[return {x}; bogus code bar"
 } -result {missing close-bracket}
 test subst-8.7 {return in a subst, parse error} -body {
-    subst {foo [return {x} ; set a {}"" ; stuff] bar} 
+    subst {foo [return {x} ; set a {}"" ; stuff] bar}
 } -returnCodes error -result {extra characters after close-brace}
 test subst-8.8 {return in a subst, parse error} -body {
     subst {foo [return {x} ; set bar baz ; set a {}"" ; stuff] bar}
@@ -282,18 +282,18 @@ test subst-13.1 {Bug 3081065} -setup {
        demo name2
     } subst13.tcl]
 } -body {
-    interp create slave
-    slave eval [list source $script]
-    interp delete slave
-    interp create slave
-    slave eval {
+    interp create child
+    child eval [list source $script]
+    interp delete child
+    interp create child
+    child eval {
        set count 400
        while {[incr count -1]} {
            lappend bloat [expr {rand()}]
        }
     }
-    slave eval [list source $script]
-    interp delete slave
+    child eval [list source $script]
+    interp delete child
 } -cleanup {
     removeFile subst13.tcl
 }
index 4d204bb..8ca049c 100644 (file)
@@ -12,7 +12,7 @@
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 \f
index 3751c35..c664455 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index c856209..9b1bb4b 100644 (file)
@@ -13,7 +13,7 @@
 # testing to run the test itself.  Ditto on things like [verbose].
 #
 # It would be better to have the -body of the tests run the tcltest
-# commands in a slave interp so the [test] being tested would not
+# commands in a child interp so the [test] being tested would not
 # interfere with the [test] doing the testing.
 #
 
@@ -27,7 +27,7 @@ namespace eval ::tcltest::test {
 namespace import ::tcltest::*
 
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import ::tcltest::test
     test a-1.0 {test a} {
        list 0
@@ -63,11 +63,11 @@ test tcltest-1.3 {tcltest -h} {exec} {
 } {1 0}
 
 # -verbose, implicit & explicit testing of [verbose]
-proc slave {msgVar args} {
+proc child {msgVar args} {
     upvar 1 $msgVar msg
 
     interp create [namespace current]::i
-    # Fake the slave interp into dumping output to a file
+    # Fake the child interp into dumping output to a file
     i eval {namespace eval ::tcltest {}}
     i eval "set tcltest::outputChannel\
            \[[list open [set of [makeFile {} output]] w]]"
@@ -99,44 +99,44 @@ proc slave {msgVar args} {
     return $code
 }
 test tcltest-2.0 {tcltest (verbose default - 'b')} {unixOrWin} {
-    set result [slave msg test.tcl]
+    set result [child msg test.tcl]
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 1 0 0 1}
 test tcltest-2.1 {tcltest -verbose 'b'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose 'b']
+    set result [child msg test.tcl -verbose 'b']
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 1 0 0 1}
 test tcltest-2.2 {tcltest -verbose 'p'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose 'p']
+    set result [child msg test.tcl -verbose 'p']
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 0 1 0 1}
 test tcltest-2.3 {tcltest -verbose 's'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose 's']
+    set result [child msg test.tcl -verbose 's']
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 0 0 1 1}
 test tcltest-2.4 {tcltest -verbose 'ps'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose 'ps']
+    set result [child msg test.tcl -verbose 'ps']
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 0 1 1 1}
 test tcltest-2.5 {tcltest -verbose 'psb'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose 'psb']
+    set result [child msg test.tcl -verbose 'psb']
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 1 1 1 1}
 
 test tcltest-2.5a {tcltest -verbose 'pass skip body'} {unixOrWin} {
-    set result [slave msg test.tcl -verbose "pass skip body"]
+    set result [child msg test.tcl -verbose "pass skip body"]
     list $result [regexp "Contents of test case" $msg] [regexp a-1.0 $msg] \
            [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
@@ -145,7 +145,7 @@ test tcltest-2.5a {tcltest -verbose 'pass skip body'} {unixOrWin} {
 test tcltest-2.6 {tcltest -verbose 't'}  {
     -constraints {unixOrWin}
     -body {
-       set result [slave msg test.tcl -verbose 't']
+       set result [child msg test.tcl -verbose 't']
        list $result $msg
     }
     -result {^0 .*a-1.0 start.*b-1.0 start}
@@ -155,7 +155,7 @@ test tcltest-2.6 {tcltest -verbose 't'}  {
 test tcltest-2.6a {tcltest -verbose 'start'}  {
     -constraints {unixOrWin}
     -body {
-       set result [slave msg test.tcl -verbose start]
+       set result [child msg test.tcl -verbose start]
        list $result $msg
     }
     -result {^0 .*a-1.0 start.*b-1.0 start}
@@ -178,7 +178,7 @@ test tcltest-2.7 {tcltest::verbose}  {
 test tcltest-2.8 {tcltest -verbose 'error'} {
     -constraints {unixOrWin}
     -body {
-       set result [slave msg test.tcl -verbose error]
+       set result [child msg test.tcl -verbose error]
        list $result $msg
     }
     -result {errorInfo: foo.*errorCode: 9}
@@ -186,22 +186,22 @@ test tcltest-2.8 {tcltest -verbose 'error'} {
 }
 # -match, [match]
 test tcltest-3.1 {tcltest -match 'a*'} {unixOrWin} {
-    set result [slave msg test.tcl -match a* -verbose 'ps']
+    set result [child msg test.tcl -match a* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+3.+Failed.+0" $msg]
 } {0 1 0 0 1}
 test tcltest-3.2 {tcltest -match 'b*'} {unixOrWin} {
-    set result [slave msg test.tcl -match b* -verbose 'ps']
+    set result [child msg test.tcl -match b* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+0.+Skipped.+3.+Failed.+1" $msg]
 } {0 0 1 0 1}
 test tcltest-3.3 {tcltest -match 'c*'} {unixOrWin} {
-    set result [slave msg test.tcl -match c* -verbose 'ps']
+    set result [child msg test.tcl -match c* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+0.+Skipped.+4.+Failed.+0" $msg]
 } {0 0 0 1 1}
 test tcltest-3.4 {tcltest -match 'a* b*'} {unixOrWin} {
-    set result [slave msg test.tcl -match {a* b*} -verbose 'ps']
+    set result [child msg test.tcl -match {a* b*} -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+2.+Failed.+1" $msg]
 } {0 1 1 0 1}
@@ -221,27 +221,27 @@ test tcltest-3.5 {tcltest::match}  {
 
 # -skip, [skip]
 test tcltest-4.1 {tcltest -skip 'a*'} {unixOrWin} {
-    set result [slave msg test.tcl -skip a* -verbose 'ps']
+    set result [child msg test.tcl -skip a* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+0.+Skipped.+2.+Failed.+1" $msg]
 } {0 0 1 1 1}
 test tcltest-4.2 {tcltest -skip 'b*'} {unixOrWin} {
-    set result [slave msg test.tcl -skip b* -verbose 'ps']
+    set result [child msg test.tcl -skip b* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+2.+Failed.+1" $msg]
 } {0 1 0 1 1}
 test tcltest-4.3 {tcltest -skip 'c*'} {unixOrWin} {
-    set result [slave msg test.tcl -skip c* -verbose 'ps']
+    set result [child msg test.tcl -skip c* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+1.+Failed.+2" $msg]
 } {0 1 1 0 1}
 test tcltest-4.4 {tcltest -skip 'a* b*'} {unixOrWin} {
-    set result [slave msg test.tcl -skip {a* b*} -verbose 'ps']
+    set result [child msg test.tcl -skip {a* b*} -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+0.+Skipped.+3.+Failed.+1" $msg]
 } {0 0 0 1 1}
 test tcltest-4.5 {tcltest -match 'a* b*' -skip 'b*'} {unixOrWin} {
-    set result [slave msg test.tcl -match {a* b*} -skip b* -verbose 'ps']
+    set result [child msg test.tcl -match {a* b*} -skip b* -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+3.+Failed.+0" $msg]
 } {0 1 0 0 1}
@@ -262,12 +262,12 @@ test tcltest-4.6 {tcltest::skip} {
 # -constraints, -limitconstraints, [testConstraint],
 # $constraintsSpecified, [limitConstraints]
 test tcltest-5.1 {tcltest -constraints 'knownBug'} {unixOrWin} {
-    set result [slave msg test.tcl -constraints knownBug -verbose 'ps']
+    set result [child msg test.tcl -constraints knownBug -verbose 'ps']
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+2.+Skipped.+0.+Failed.+2" $msg]
 } {0 1 1 1 1}
 test tcltest-5.2 {tcltest -constraints 'knownBug' -limitconstraints 1} {unixOrWin} {
-    set result [slave msg test.tcl -constraints knownBug -verbose 'p' -limitconstraints 1]
+    set result [child msg test.tcl -constraints knownBug -verbose 'p' -limitconstraints 1]
     list $result [regexp a-1.0 $msg] [regexp b-1.0 $msg] [regexp c-1.0 $msg] \
            [regexp "Total.+4.+Passed.+1.+Skipped.+3.+Failed.+0" $msg]
 } {0 0 0 1 1}
@@ -340,7 +340,7 @@ test tcltest-5.5 {InitConstraints: list of built-in constraints} \
 
 # -outfile, -errfile, [outputChannel], [outputFile], [errorChannel], [errorFile]
 set printerror [makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import ::tcltest::*
     puts [outputChannel] "a test"
     ::tcltest::PrintError "a really short string"
@@ -357,28 +357,28 @@ set printerror [makeFile {
 test tcltest-6.1 {tcltest -outfile, -errfile defaults} {
     -constraints unixOrWin
     -body {
-       slave msg $printerror
+       child msg $printerror
        return $msg
     }
     -result {a test.*a really}
     -match regexp
 }
 test tcltest-6.2 {tcltest -outfile a.tmp} {unixOrWin unixExecs} {
-    slave msg $printerror -outfile a.tmp
+    child msg $printerror -outfile a.tmp
     set result1 [catch {exec grep "a test" a.tmp}]
     set result2 [catch {exec grep "a really" a.tmp}]
     list [regexp "a test" $msg] [regexp "a really" $msg] \
            $result1 $result2 [file exists a.tmp] [file delete a.tmp]
 } {0 1 0 1 1 {}}
 test tcltest-6.3 {tcltest -errfile a.tmp} {unixOrWin unixExecs} {
-    slave msg $printerror -errfile a.tmp
+    child msg $printerror -errfile a.tmp
     set result1 [catch {exec grep "a test" a.tmp}]
     set result2 [catch {exec grep "a really" a.tmp}]
     list [regexp "a test" $msg] [regexp "a really" $msg] \
            $result1 $result2 [file exists a.tmp] [file delete a.tmp]
 } {1 0 1 0 1 {}}
 test tcltest-6.4 {tcltest -outfile a.tmp -errfile b.tmp} {unixOrWin unixExecs} {
-    slave msg $printerror -outfile a.tmp -errfile b.tmp
+    child msg $printerror -outfile a.tmp -errfile b.tmp
     set result1 [catch {exec grep "a test" a.tmp}]
     set result2 [catch {exec grep "a really" b.tmp}]
     list [regexp "a test" $msg] [regexp "a really" $msg] \
@@ -463,7 +463,7 @@ test tcltest-6.8 {tcltest::outputFile (implicit outputFile)} {
 # -debug, [debug]
 # Must use child processes to test -debug because it always writes
 # messages to stdout, and we have no way to capture stdout of a
-# slave interp
+# child interp
 test tcltest-7.1 {tcltest test.tcl -debug 0} {unixOrWin} {
     catch {exec [interpreter] test.tcl -debug 0} msg
     regexp "Flags passed into tcltest" $msg
@@ -510,7 +510,7 @@ removeFile test.tcl
 # directory tests
 
 set a [makeFile {
-    package require tcltest
+    package require tcltest 2.5
     tcltest::makeFile {} a.tmp
     puts [tcltest::outputChannel] "testdir: [tcltest::testsDirectory]"
     exit
@@ -525,7 +525,7 @@ normalizePath normaldirectory
 test tcltest-8.1 {tcltest a.tcl -tmpdir a} -constraints unixOrWin -setup {
     file delete -force thisdirectorydoesnotexist
 } -body {
-    slave msg $a -tmpdir thisdirectorydoesnotexist
+    child msg $a -tmpdir thisdirectorydoesnotexist
     file exists [file join thisdirectorydoesnotexist a.tmp]
 } -cleanup {
     file delete -force thisdirectorydoesnotexist
@@ -533,7 +533,7 @@ test tcltest-8.1 {tcltest a.tcl -tmpdir a} -constraints unixOrWin -setup {
 test tcltest-8.2 {tcltest a.tcl -tmpdir thisdirectoryisafile} {
     -constraints unixOrWin
     -body {
-       slave msg $a -tmpdir $tdiaf
+       child msg $a -tmpdir $tdiaf
        return $msg
     }
     -result {*not a directory*}
@@ -546,8 +546,8 @@ makeDirectory notreadable
 makeDirectory notwriteable
 switch -- $::tcl_platform(platform) {
     unix {
-       file attributes $notReadableDir -permissions 00333
-       file attributes $notWriteableDir -permissions 00555
+       file attributes $notReadableDir -permissions 0o333
+       file attributes $notWriteableDir -permissions 0o555
     }
     default {
        # note in FAT/NTFS we won't be able to protect directory with read-only attribute...
@@ -558,7 +558,7 @@ switch -- $::tcl_platform(platform) {
 test tcltest-8.3 {tcltest a.tcl -tmpdir notReadableDir} {
     -constraints {unix notRoot}
     -body {
-       slave msg $a -tmpdir $notReadableDir
+       child msg $a -tmpdir $notReadableDir
        return $msg
     }
     -result {*not readable*}
@@ -574,7 +574,7 @@ testConstraint notFAT [expr {
 test tcltest-8.4 {tcltest a.tcl -tmpdir notWriteableDir} {
     -constraints {unixOrWin notRoot notFAT}
     -body {
-       slave msg $a -tmpdir $notWriteableDir
+       child msg $a -tmpdir $notWriteableDir
        return $msg
     }
     -result {*not writeable*}
@@ -583,7 +583,7 @@ test tcltest-8.4 {tcltest a.tcl -tmpdir notWriteableDir} {
 test tcltest-8.5 {tcltest a.tcl -tmpdir normaldirectory} {
     -constraints unixOrWin
     -body {
-       slave msg $a -tmpdir $normaldirectory
+       child msg $a -tmpdir $normaldirectory
        # The join is necessary because the message can be split on multiple
        # lines
        file exists [file join $normaldirectory a.tmp]
@@ -629,7 +629,7 @@ test tcltest-8.10 {tcltest a.tcl -testdir thisdirectorydoesnotexist} {
        file delete -force thisdirectorydoesnotexist
     }
     -body {
-       slave msg $a -testdir thisdirectorydoesnotexist
+       child msg $a -testdir thisdirectorydoesnotexist
        return $msg
     }
     -match glob
@@ -638,7 +638,7 @@ test tcltest-8.10 {tcltest a.tcl -testdir thisdirectorydoesnotexist} {
 test tcltest-8.11 {tcltest a.tcl -testdir thisdirectoryisafile} {
     -constraints unixOrWin
     -body {
-       slave msg $a -testdir $tdiaf
+       child msg $a -testdir $tdiaf
        return $msg
     }
     -match glob
@@ -647,7 +647,7 @@ test tcltest-8.11 {tcltest a.tcl -testdir thisdirectoryisafile} {
 test tcltest-8.12 {tcltest a.tcl -testdir notReadableDir} {
     -constraints {unix notRoot}
     -body {
-       slave msg $a -testdir $notReadableDir
+       child msg $a -testdir $notReadableDir
        return $msg
     }
     -match glob
@@ -656,7 +656,7 @@ test tcltest-8.12 {tcltest a.tcl -testdir notReadableDir} {
 test tcltest-8.13 {tcltest a.tcl -testdir normaldirectory} {
     -constraints unixOrWin
     -body {
-       slave msg $a -testdir $normaldirectory
+       child msg $a -testdir $normaldirectory
        # The join is necessary because the message can be split on multiple
        # lines
        list [string first "testdir: $normaldirectory" [join $msg]] \
@@ -735,7 +735,7 @@ test tcltest-9.1 {-file d*.tcl} -constraints {unixOrWin} -setup {
     set old [testsDirectory]
     testsDirectory [file dirname [info script]]
 } -body {
-    slave msg [file join [testsDirectory] all.tcl] -file d*.test
+    child msg [file join [testsDirectory] all.tcl] -file d*.test
     return $msg
 } -cleanup {
     testsDirectory $old
@@ -745,7 +745,7 @@ test tcltest-9.2 {-file d*.tcl} -constraints {unixOrWin} -setup {
     set old [testsDirectory]
     testsDirectory [file dirname [info script]]
 } -body {
-    slave msg [file join [testsDirectory] all.tcl] \
+    child msg [file join [testsDirectory] all.tcl] \
            -file d*.test -notfile dstring*
     regexp {dstring\.test} $msg
 } -cleanup {
@@ -784,7 +784,7 @@ test tcltest-9.5 {GetMatchingFiles: Bug 1119798} -setup {
     makeFile {} fee $d
     file copy [file join [file dirname [info script]] all.tcl] $d
 } -body {
-    slave msg [file join [temporaryDirectory] all.tcl] -file f*
+    child msg [file join [temporaryDirectory] all.tcl] -file f*
     regexp {exiting with errors:} $msg
 } -cleanup {
     file delete [file join $d all.tcl]
@@ -795,7 +795,7 @@ test tcltest-9.5 {GetMatchingFiles: Bug 1119798} -setup {
 
 # -preservecore, [preserveCore]
 set mc [makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import ::tcltest::test
     test makecore {make a core file} {
        set f [open core w]
@@ -807,23 +807,23 @@ set mc [makeFile {
 
 cd [temporaryDirectory]
 test tcltest-10.1 {-preservecore 0} {unixOrWin} {
-    slave msg $mc -preservecore 0
+    child msg $mc -preservecore 0
     file delete core
     regexp "Core file produced" $msg
 } {0}
 test tcltest-10.2 {-preservecore 1} {unixOrWin} {
-    slave msg $mc -preservecore 1
+    child msg $mc -preservecore 1
     file delete core
     regexp "Core file produced" $msg
 } {1}
 test tcltest-10.3 {-preservecore 2} {unixOrWin} {
-    slave msg $mc -preservecore 2
+    child msg $mc -preservecore 2
     file delete core
     list [regexp "Core file produced" $msg] [regexp "Moving file to" $msg] \
            [regexp "core-" $msg] [file delete core-makecore]
 } {1 1 1 {}}
 test tcltest-10.4 {-preservecore 3} {unixOrWin} {
-    slave msg $mc -preservecore 3
+    child msg $mc -preservecore 3
     file delete core
     list [regexp "Core file produced" $msg] [regexp "Moving file to" $msg] \
            [regexp "core-" $msg] [file delete core-makecore]
@@ -846,7 +846,7 @@ removeFile makecore.tcl
 
 # -load, -loadfile, [loadScript], [loadFile]
 set contents {
-    package require tcltest
+    package require tcltest 2.5
     namespace import tcltest::*
     puts [outputChannel] $::tcltest::loadScript
     exit
@@ -854,7 +854,7 @@ set contents {
 set loadfile [makeFile $contents load.tcl]
 
 test tcltest-12.1 {-load xxx} {unixOrWin} {
-    slave msg $loadfile -load xxx
+    child msg $loadfile -load xxx
     return $msg
 } {xxx}
 
@@ -942,7 +942,7 @@ makeFile {
 } single2.test $spd
 
 set allfile [makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import tcltest::*
     testsDirectory [file join [temporaryDirectory] singleprocdir]
     runAllTests
@@ -952,7 +952,7 @@ cd [workingDirectory]
 test tcltest-14.1 {-singleproc - single process} {
     -constraints {unixOrWin}
     -body {
-       slave msg $allfile -singleproc 0 -tmpdir [temporaryDirectory]
+       child msg $allfile -singleproc 0 -tmpdir [temporaryDirectory]
        return $msg
     }
     -result {Test file error: can't unset .foo.: no such variable}
@@ -962,7 +962,7 @@ test tcltest-14.1 {-singleproc - single process} {
 test tcltest-14.2 {-singleproc - multiple process} {
     -constraints {unixOrWin}
     -body {
-       slave msg $allfile -singleproc 1 -tmpdir [temporaryDirectory]
+       child msg $allfile -singleproc 1 -tmpdir [temporaryDirectory]
        return $msg
     }
     -result {single1.test.*single2.test.*all\-single.tcl:.*Total.*0.*Passed.*0.*Skipped.*0.*Failed.*0}
@@ -999,25 +999,25 @@ set dtd1 [makeDirectory dirtestdir2.1 $dtd]
 set dtd2 [makeDirectory dirtestdir2.2 $dtd]
 set dtd3 [makeDirectory dirtestdir2.3 $dtd]
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     testsDirectory [file join [temporaryDirectory] dirtestdir]
     runAllTests
 } all.tcl $dtd
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     testsDirectory [file join [temporaryDirectory] dirtestdir dirtestdir2.1]
     runAllTests
 } all.tcl $dtd1
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     testsDirectory [file join [temporaryDirectory]  dirtestdir dirtestdir2.2]
     runAllTests
 } all.tcl $dtd2
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     testsDirectory [file join [temporaryDirectory] dirtestdir dirtestdir2.3]
     runAllTests
@@ -1026,7 +1026,7 @@ makeFile {
 test tcltest-15.1 {basic directory walking} {
     -constraints {unixOrWin}
     -body {
-       if {[slave msg \
+       if {[child msg \
                [file join $dtd all.tcl] \
                -tmpdir [temporaryDirectory]] == 1} {
            error $msg
@@ -1040,7 +1040,7 @@ test tcltest-15.1 {basic directory walking} {
 test tcltest-15.2 {-asidefromdir} {
     -constraints {unixOrWin}
     -body {
-       if {[slave msg \
+       if {[child msg \
                [file join $dtd all.tcl] \
                -asidefromdir dirtestdir2.3 \
                -tmpdir [temporaryDirectory]] == 1} {
@@ -1058,7 +1058,7 @@ Error:  No test files remain after applying your match and skip patterns!$}
 test tcltest-15.3 {-relateddir, non-existent dir} {
     -constraints {unixOrWin}
     -body {
-       if {[slave msg \
+       if {[child msg \
                [file join $dtd all.tcl] \
                -relateddir [file join [temporaryDirectory] dirtestdir0] \
                -tmpdir [temporaryDirectory]] == 1} {
@@ -1073,7 +1073,7 @@ test tcltest-15.3 {-relateddir, non-existent dir} {
 test tcltest-15.4 {-relateddir, subdir} {
     -constraints {unixOrWin}
     -body {
-       if {[slave msg \
+       if {[child msg \
                [file join $dtd all.tcl] \
                -relateddir dirtestdir2.1 -tmpdir [temporaryDirectory]] == 1} {
            error $msg
@@ -1086,7 +1086,7 @@ test tcltest-15.4 {-relateddir, subdir} {
 test tcltest-15.5 {-relateddir, -asidefromdir} {
     -constraints {unixOrWin}
     -body {
-       if {[slave msg \
+       if {[child msg \
                [file join $dtd all.tcl] \
                -relateddir "dirtestdir2.1 dirtestdir2.2" \
                -asidefromdir dirtestdir2.2 \
@@ -1147,25 +1147,25 @@ test tcltest-19.1 {TCLTEST_OPTIONS default} -setup {
        # set this to { } instead of just {} to get around quirk in
        # Windows env handling that removes empty elements from env array.
        set ::env(TCLTEST_OPTIONS) { }
-       interp create slave1
-       slave1 eval [list set argv {-debug 2}]
-       slave1 alias puts puts
-       interp create slave2
-       slave2 alias puts puts
+       interp create child1
+       child1 eval [list set argv {-debug 2}]
+       child1 alias puts puts
+       interp create child2
+       child2 alias puts puts
     } -cleanup {
-       interp delete slave2
-       interp delete slave1
+       interp delete child2
+       interp delete child1
        if {$oldoptions eq "none"} {
            unset ::env(TCLTEST_OPTIONS)
        } else {
            set ::env(TCLTEST_OPTIONS) $oldoptions
        }
     } -body {
-       slave1 eval [package ifneeded tcltest [package provide tcltest]]
-       slave1 eval tcltest::debug
+       child1 eval [package ifneeded tcltest [package provide tcltest]]
+       child1 eval tcltest::debug
        set ::env(TCLTEST_OPTIONS) "-debug 3"
-       slave2 eval [package ifneeded tcltest [package provide tcltest]]
-       slave2 eval tcltest::debug
+       child2 eval [package ifneeded tcltest [package provide tcltest]]
+       child2 eval tcltest::debug
     } -result {^3$} -match regexp -output\
 {tcltest::debug\s+= 2.*tcltest::debug\s+= 3}
 
@@ -1174,7 +1174,7 @@ test tcltest-19.1 {TCLTEST_OPTIONS default} -setup {
 cd [temporaryDirectory]
 # PrintError
 test tcltest-20.1 {PrintError} {unixOrWin} {
-    set result [slave msg $printerror]
+    set result [child msg $printerror]
     list $result [regexp "Error:  a really short string" $msg] \
            [regexp "     \"quotes\"" $msg] [regexp "    \"Path" $msg] \
            [regexp "    \"Really" $msg] [regexp Problem $msg]
@@ -1385,7 +1385,7 @@ test tcltest-21.12 {
 
 set atd [makeDirectory alltestdir]
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     testsDirectory [file join [temporaryDirectory] alltestdir]
     runAllTests
@@ -1397,7 +1397,7 @@ makeFile {
     error "throw an error"
 } error.test $atd
 makeFile {
-    package require tcltest
+    package require tcltest 2.5
     namespace import -force tcltest::*
     test foo-1.1 {foo} {
        -body { return 1 }
@@ -1407,7 +1407,7 @@ makeFile {
 } test.test $atd
 
 # Must use a child process because stdout/stderr parsing can't be
-# duplicated in slave interp.
+# duplicated in child interp.
 test tcltest-22.1 {runAllTests} {
     -constraints {unixOrWin}
     -body {
@@ -1444,7 +1444,7 @@ test tcltest-23.2 {removeFile} {
        file mkdir $mfdir
        makeFile {} t1.tmp
        makeFile {} et1.tmp $mfdir
-       if  {![file exists [file join [temporaryDirectory] t1.tmp]] || \
+       if {![file exists [file join [temporaryDirectory] t1.tmp]] || \
                ![file exists [file join $mfdir et1.tmp]]} {
            error "file creation didn't work"
        }
@@ -1796,7 +1796,7 @@ test tcltest-25.3 {
 
 test tcltest-26.1 {Bug/RFE 1017151} -setup {
     makeFile {
-       package require tcltest
+       package require tcltest 2.5
        set ::errorInfo "Should never see this"
        tcltest::test tcltest-26.1.0 {
            no errorInfo when only return code mismatch
@@ -1806,7 +1806,7 @@ test tcltest-26.1 {Bug/RFE 1017151} -setup {
        tcltest::cleanupTests
     } test.tcl
 } -body {
-    slave msg [file join [temporaryDirectory] test.tcl]
+    child msg [file join [temporaryDirectory] test.tcl]
     return $msg
 } -cleanup {
     removeFile test.tcl
@@ -1816,7 +1816,7 @@ test tcltest-26.1 {Bug/RFE 1017151} -setup {
 
 test tcltest-26.2 {Bug/RFE 1017151} -setup {
     makeFile {
-       package require tcltest
+       package require tcltest 2.5
        set ::errorInfo "Should never see this"
        tcltest::test tcltest-26.2.0 {do not mask body errorInfo} -body {
            error "body error"
@@ -1826,7 +1826,7 @@ test tcltest-26.2 {Bug/RFE 1017151} -setup {
        tcltest::cleanupTests
     } test.tcl
 } -body {
-    slave msg [file join [temporaryDirectory] test.tcl]
+    child msg [file join [temporaryDirectory] test.tcl]
     return $msg
 } -cleanup {
     removeFile test.tcl
index a1fdb3d..58e6bfb 100644 (file)
@@ -1,6 +1,6 @@
 #! /usr/bin/env tclsh
 
-package require tcltest 2.2
+package require tcltest 2.5
 namespace import ::tcltest::*
 
 testConstraint exec          [llength [info commands exec]]
index eaaaa41..7c7dc27 100644 (file)
@@ -36,11 +36,11 @@ set threadSuperKillScript {
 proc getThreadErrorFromInfo { info } {
     set list [split $info \n]
     set idx [lsearch -glob $list "*eval*unwound*"]
-    if {$idx != -1} then {
+    if {$idx >= 0} then {
         return [lindex $list $idx]
     }
     set idx [lsearch -glob $list "*eval*canceled*"]
-    if {$idx != -1} then {
+    if {$idx >= 0} then {
         return [lindex $list $idx]
     }
     return ""; # some other error we do not care about.
@@ -802,7 +802,7 @@ test thread-7.21 {cancel: subst -unwind} -constraints {thread drainEventQueue} -
 } -cleanup {
     unset -nocomplain ::threadSawError ::threadError ::threadId ::threadIdStarted
 } -result {{} 1 1 {eval unwound}}
-test thread-7.22 {cancel: slave interp} -constraints {thread drainEventQueue} -setup {
+test thread-7.22 {cancel: child interp} -constraints {thread drainEventQueue} -setup {
     unset -nocomplain ::threadSawError ::threadError ::threadId ::threadIdStarted
 } -body {
     set serverthread [thread::create -joinable \
@@ -832,7 +832,7 @@ test thread-7.22 {cancel: slave interp} -constraints {thread drainEventQueue} -s
 } -cleanup {
     unset -nocomplain ::threadSawError ::threadError ::threadId ::threadIdStarted
 } -result {{} 1 1 {eval canceled}}
-test thread-7.23 {cancel: slave interp -unwind} -constraints {thread drainEventQueue} -setup {
+test thread-7.23 {cancel: child interp -unwind} -constraints {thread drainEventQueue} -setup {
     unset -nocomplain ::threadSawError ::threadError ::threadId ::threadIdStarted
 } -body {
     set serverthread [thread::create -joinable \
index 740d05e..48d88b6 100644 (file)
@@ -13,8 +13,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -568,15 +568,15 @@ test timer-9.1 {AfterCleanupProc procedure} -setup {
 } -result {before after2 after4}
 
 test timer-10.1 {Bug 1016167: [after] overwrites imports} -setup {
-    interp create slave
-    slave eval namespace export after
-    slave eval namespace eval foo namespace import ::after
+    interp create child
+    child eval namespace export after
+    child eval namespace eval foo namespace import ::after
 } -body {
-    slave eval foo::after 1
-    slave eval namespace origin foo::after
+    child eval foo::after 1
+    child eval namespace origin foo::after
 } -cleanup {
     # Bug will cause crash here; would cause failure otherwise
-    interp delete slave
+    interp delete child
 } -result ::after
 
 test timer-11.1 {Bug 1350291: [after] overflowing 32-bit field} -body {
index 001b73e..ed14567 100644 (file)
@@ -8,7 +8,7 @@
 
 package require Tcl 8.5-
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index d830f3c..c1e1a24 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest
-namespace import ::tcltest::*
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
+    namespace import -force ::tcltest::*
+}
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
@@ -164,30 +166,30 @@ test trace-1.10 {trace variable reads} {
 } {}
 test trace-1.11 {read traces that modify the array structure} {
     unset -nocomplain x
-    set x(bar) 0 
-    trace variable x r {set x(foo) 1 ;#} 
-    trace variable x r {unset -nocomplain x(bar) ;#} 
+    set x(bar) 0
+    trace variable x r {set x(foo) 1 ;#}
+    trace variable x r {unset -nocomplain x(bar) ;#}
     array get x
 } {}
 test trace-1.12 {read traces that modify the array structure} {
     unset -nocomplain x
-    set x(bar) 0 
-    trace variable x r {unset -nocomplain x(bar) ;#} 
-    trace variable x r {set x(foo) 1 ;#} 
+    set x(bar) 0
+    trace variable x r {unset -nocomplain x(bar) ;#}
+    trace variable x r {set x(foo) 1 ;#}
     array get x
 } {}
 test trace-1.13 {read traces that modify the array structure} {
     unset -nocomplain x
-    set x(bar) 0 
-    trace variable x r {set x(foo) 1 ;#} 
-    trace variable x r {unset -nocomplain x;#} 
+    set x(bar) 0
+    trace variable x r {set x(foo) 1 ;#}
+    trace variable x r {unset -nocomplain x;#}
     list [catch {array get x} res] $res
 } {1 {can't read "x(bar)": no such variable}}
 test trace-1.14 {read traces that modify the array structure} {
     unset -nocomplain x
-    set x(bar) 0 
-    trace variable x r {unset -nocomplain x;#} 
-    trace variable x r {set x(foo) 1 ;#} 
+    set x(bar) 0
+    trace variable x r {unset -nocomplain x;#}
+    trace variable x r {set x(foo) 1 ;#}
     list [catch {array get x} res] $res
 } {1 {can't read "x(bar)": no such variable}}
 
@@ -419,7 +421,7 @@ test trace-5.8 {array traces fire for undefined variables} {
     trace add variable x array {set x(foo) 1 ;#}
     set res "names: [array names x]"
 } {names: foo}
-    
+
 # Trace multiple trace types at once.
 
 test trace-6.1 {multiple ops traced at once} {
@@ -767,7 +769,7 @@ test trace-13.1 {delete one trace from another} {
     trace add variable x read {traceTag 2}
     trace add variable x read {traceTag 3}
     trace add variable x read {traceTag 4}
-    trace add variable x read delTraces 
+    trace add variable x read delTraces
     trace add variable x read {traceTag 5}
     set x
     set info
@@ -872,7 +874,7 @@ test trace-14.5 {trace command, invalid option} {
 } [list 1 "bad option \"gorp\": must be add, info, remove, variable, vdelete, or vinfo"]
 
 # Again, [trace ... command] and [trace ... variable] share syntax and
-# error message styles for their opList options; these loops test those 
+# error message styles for their opList options; these loops test those
 # error messages.
 
 set i 0
@@ -2104,7 +2106,7 @@ foo foo 0 1 leave}
 test trace-28.2 {exec traces with 'error'} {
     set info {}
     set res {}
-    
+
     proc foo {} {
        if {[catch {bar}]} {
            return "error"
@@ -2126,7 +2128,7 @@ test trace-28.2 {exec traces with 'error'} {
 
     trace remove execution foo {enter enterstep leave leavestep} \
       [list traceExecute foo]
-    
+
     list $res [join $info \n]
 } {{error error} {foo foo enter
 foo {if {[catch {bar}]} {
@@ -2152,7 +2154,7 @@ foo foo 0 error leave}}
 test trace-28.3 {exec traces with 'return -code error'} {
     set info {}
     set res {}
-    
+
     proc foo {} {
        if {[catch {bar}]} {
            return "error"
@@ -2174,7 +2176,7 @@ test trace-28.3 {exec traces with 'return -code error'} {
 
     trace remove execution foo {enter enterstep leave leavestep} \
       [list traceExecute foo]
-    
+
     list $res [join $info \n]
 } {{error error} {foo foo enter
 foo {if {[catch {bar}]} {
@@ -2197,14 +2199,14 @@ foo {if {[catch {bar}]} {
        }} 2 error leavestep
 foo foo 0 error leave}}
 
-test trace-28.4 {exec traces in slave with 'return -code error'} {
-    interp create slave
-    interp alias slave traceExecute {} traceExecute
+test trace-28.4 {exec traces in child with 'return -code error'} {
+    interp create child
+    interp alias child traceExecute {} traceExecute
     set info {}
-    set res [interp eval slave {
+    set res [interp eval child {
        set info {}
        set res {}
-       
+
        proc foo {} {
            if {[catch {bar}]} {
                return "error"
@@ -2212,24 +2214,24 @@ test trace-28.4 {exec traces in slave with 'return -code error'} {
                return "ok"
            }
        }
-       
+
        proc bar {} { return -code error "msg" }
-       
+
        lappend res [foo]
-       
+
        trace add execution foo {enter enterstep leave leavestep} \
          [list traceExecute foo]
-       
+
        # With the trace active
-       
+
        lappend res [foo]
-       
+
        trace remove execution foo {enter enterstep leave leavestep} \
          [list traceExecute foo]
-       
+
        list $res
     }]
-    interp delete slave
+    interp delete child
     lappend res [join $info \n]
 } {{error error} {foo foo enter
 foo {if {[catch {bar}]} {
@@ -2312,8 +2314,8 @@ test trace-28.10 {exec trace info nonsense} {
 } {1 {wrong # args: should be "trace remove execution name opList command"}}
 
 test trace-29.1 {Tcl_CreateTrace, correct command and argc/argv arguments of trace proc} {testcmdtrace} {
-    testcmdtrace tracetest {set stuff [expr 14 + 16]}
-} {{expr 14 + 16} {expr 14 + 16} {set stuff [expr 14 + 16]} {set stuff 30}}
+    testcmdtrace tracetest {set stuff [expr {14 + 16}]}
+} {{expr {14 + 16}} {expr {14 + 16}} {set stuff [expr {14 + 16}]} {set stuff 30}}
 test trace-29.2 {Tcl_CreateTrace, correct command and argc/argv arguments of trace proc} {testcmdtrace} {
     testcmdtrace tracetest {set stuff [info tclversion]}
 } [concat {{info tclversion} {info tclversion} ::tcl::info::tclversion {::tcl::info::tclversion} {set stuff [info tclversion]}} [list "set stuff [info tclversion]"]]
@@ -2610,7 +2612,7 @@ test trace-39 {bug #3484621: tracing Bc'ed commands} -setup {
     proc foo {} {
        incr ::traceCalls
        # choose a BC'ed command that is 'unlikely' to interfere with tcltest's
-       # internals 
+       # internals
        lset ::bar 1 2
     }
 } -body {
@@ -2631,7 +2633,7 @@ test trace-39 {bug #3484621: tracing Bc'ed commands} -setup {
     rename dotrace {}
     rename foo {}
 } -result {3 | 0 1 1}
-    
+
 test trace-39.1 {bug #3485022: tracing Bc'ed commands} -setup {
     set ::traceLog 0
     set ::traceCalls 0
@@ -2668,7 +2670,7 @@ test trace-40.1 {execution trace errors become command errors} {
     catch foo m
     return -level 0 $m[unset m]
 } bar
-    
+
 # Delete procedures when done, so we don't clash with other tests
 # (e.g. foobar will clash with 'unknown' tests).
 catch {rename foobar {}}
index 183c145..4b1687f 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -96,10 +96,10 @@ test unixFCmd-1.1 {TclpRenameFile: EACCES} -setup {
     cleanup
 } -constraints {unix notRoot} -body {
     file mkdir td1/td2/td3
-    file attributes td1/td2 -permissions 0000
+    file attributes td1/td2 -permissions 0o000
     file rename td1/td2/td3 td2
 } -returnCodes error -cleanup {
-    file attributes td1/td2 -permissions 0755
+    file attributes td1/td2 -permissions 0o755
     cleanup
 } -result {error renaming "td1/td2/td3": permission denied}
 test unixFCmd-1.2 {TclpRenameFile: EEXIST} -setup {
@@ -137,11 +137,11 @@ test unixFCmd-1.7 {TclpRenameFile: EXDEV} -setup {
     cleanup
 } -constraints {unix notRoot} -body {
     file mkdir foo/bar
-    file attr foo -perm 040555
+    file attr foo -perm 0o40555
     file rename foo/bar /tmp
 } -returnCodes error -cleanup {
     catch {file delete /tmp/bar}
-    catch {file attr foo -perm 040777}
+    catch {file attr foo -perm 0o40777}
     catch {file delete -force foo}
 } -match glob -result {*: permission denied}
 test unixFCmd-1.8 {Checking EINTR Bug} {unix notRoot nonPortable} {
@@ -221,12 +221,12 @@ test unixFCmd-2.5 {TclpCopyFile: copy attributes} -setup {
     cleanup
 } -constraints {unix notRoot} -body {
     close [open tf1 a]
-    file attributes tf1 -permissions 0472
+    file attributes tf1 -permissions 0o472
     file copy tf1 tf2
-    file attributes tf2 -permissions
+    format 0o%03o [file attributes tf2 -permissions]
 } -cleanup {
     cleanup
-} -result 00472 ;# i.e. perms field of [exec ls -l tf2] is -r--rwx-w-
+} -result 0o472 ;# i.e. perms field of [exec ls -l tf2] is -r--rwx-w-
 
 test unixFCmd-3.1 {CopyFile not done} {emptyTest unix notRoot} {
 } {}
@@ -336,15 +336,15 @@ test unixFCmd-17.1 {SetPermissionsAttribute} -setup {
     catch {file delete -force -- foo.test}
 } -constraints {unix notRoot} -body {
     close [open foo.test w]
-    list [file attributes foo.test -permissions 0000] \
-       [file attributes foo.test -permissions]
+    list [file attributes foo.test -permissions 0o000] \
+       [format 0o%03o [file attributes foo.test -permissions]]
 } -cleanup {
     file delete -force -- foo.test
-} -result {{} 00000}
+} -result {{} 0o000}
 test unixFCmd-17.2 {SetPermissionsAttribute} -setup {
     catch {file delete -force -- foo.test}
 } -constraints {unix notRoot} -returnCodes error -body {
-    file attributes foo.test -permissions 0000
+    file attributes foo.test -permissions 0o000
 } -result {could not set permissions for file "foo.test": no such file or directory}
 test unixFCmd-17.3 {SetPermissionsAttribute} -setup {
     catch {file delete -force -- foo.test}
@@ -370,16 +370,16 @@ proc permcheck {testnum permList expected} {
       set result {}
       foreach permstr $permList {
        file attributes foo.test -permissions $permstr
-       lappend result [file attributes foo.test -permissions]
+       lappend result [format 0o%03o [file attributes foo.test -permissions]]
       }
       set result
     } $expected
 }
-permcheck unixFCmd-17.5   rwxrwxrwx    00777
-permcheck unixFCmd-17.6   r--r---w-    00442
-permcheck unixFCmd-17.7   {0 u+rwx,g+r u-w o+rwx} {00000 00740 00540 00547}
-permcheck unixFCmd-17.11  --x--x--x    00111
-permcheck unixFCmd-17.12  {0 a+rwx} {00000 00777}
+permcheck unixFCmd-17.5   rwxrwxrwx    0o777
+permcheck unixFCmd-17.6   r--r---w-    0o442
+permcheck unixFCmd-17.7   {0 u+rwx,g+r u-w o+rwx} {0o000 0o740 0o540 0o547}
+permcheck unixFCmd-17.11  --x--x--x    0o111
+permcheck unixFCmd-17.12  {0 a+rwx} {0o000 0o777}
 file delete -force -- foo.test
 
 test unixFCmd-18.1 {Unix pwd} -constraints {unix notRoot nonPortable} -setup {
@@ -390,11 +390,11 @@ test unixFCmd-18.1 {Unix pwd} -constraints {unix notRoot nonPortable} -setup {
     set nd $cd/tstdir
     file mkdir $nd
     cd $nd
-    file attributes $nd -permissions 0000
+    file attributes $nd -permissions 0o000
     pwd
 } -returnCodes error -cleanup {
     cd $cd
-    file attributes $nd -permissions 0755
+    file attributes $nd -permissions 0o755
     file delete $nd
 } -match glob -result {error getting working directory name:*}
 
index 8147f48..3669cce 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -24,7 +24,7 @@ cd [temporaryDirectory]
 
 catch {
     set oldPath $env(PATH)
-    file attributes [makeFile "" junk] -perm 0777
+    file attributes [makeFile "" junk] -perm 0o777
 }
 set absPath [file join [temporaryDirectory] junk]
 
index 120f362..4a0ac15 100644 (file)
@@ -8,7 +8,7 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+package require tcltest 2.5
 namespace import -force ::tcltest::*
 
 testConstraint testfork [llength [info commands testfork]]
index 681a931..51ecafe 100644 (file)
@@ -10,7 +10,7 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2.2
+package require tcltest 2.5
 namespace import ::tcltest::*
 unset -nocomplain path
 catch {set oldlang $env(LANG)}
index 2f03529..df95c46 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index e80d3a6..7600cba 100644 (file)
@@ -11,7 +11,7 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest 2
+package require tcltest 2.5
 namespace import ::tcltest::*
 
 unset -nocomplain x
@@ -58,7 +58,7 @@ test unknown-4.1 {errors in "unknown" procedure} {
 catch {rename unknown {}}
 catch {rename unknown.old unknown}
 cleanupTests
-return 
+return
 
 # Local Variables:
 # mode: tcl
index 73f1091..32767fa 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -38,9 +38,6 @@ testConstraint $loaded [expr {![string match *pkgua* $alreadyLoaded]}]
 
 set alreadyTotalLoaded [info loaded]
 
-# Certain tests require the 'teststaticpkg' command from tcltest
-testConstraint teststaticpkg [llength [info commands teststaticpkg]]
-
 # Certain tests need the 'testsimplefilsystem' in tcltest
 testConstraint testsimplefilesystem \
        [llength [info commands testsimplefilesystem]]
@@ -156,14 +153,14 @@ test unload-3.3 {unloading of a package that has never been loaded from a safe i
     unload [file join $testDir pkga$ext] {} child
 } -result {file "*" has never been loaded in this interpreter}
 test unload-3.4 {basic unloading of a non-unloadable package from a safe interpreter, with guess for package name} -setup {
-    if {[lsearch -index 1 [info loaded child] Pkgb] == -1} {
+    if {[lsearch -index 1 [info loaded child] Pkgb] < 0} {
        load [file join $testDir pkgb$ext] pKgB child
     }
 } -constraints [list $dll $loaded] -returnCodes error -match glob -body {
     unload [file join $testDir pkgb$ext] {} child
 } -result {file "*" cannot be unloaded under a safe interpreter}
 test unload-3.5 {basic unloading of an unloadable package from a safe interpreter, with guess for package name} -setup {
-    if {[lsearch -index 1 [info loaded child] Pkgua] == -1} {
+    if {[lsearch -index 1 [info loaded child] Pkgua] < 0} {
        load [file join $testDir pkgua$ext] pkgua child
     }
 } -constraints [list $dll $loaded] -body {
index 9fe1645..fa3be92 100644 (file)
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
 proc a {x y} {
-    newset z [expr $x+$y]
+    newset z [expr {$x + $y}]
     return $z
 }
 proc newset {name value} {
@@ -247,7 +247,7 @@ test uplevel-7.1 {var access, no LVT in either level} -setup {
     unset -nocomplain y z
 } -body {
     namespace eval foo {
-       set x 2 
+       set x 2
        set y 2
        uplevel 1 {
            set x 3
@@ -266,7 +266,7 @@ test uplevel-7.2 {var access, no LVT in upper level} -setup {
     unset -nocomplain y z
 } -body {
     proc foo {} {
-       set x 2 
+       set x 2
        set y 2
        uplevel 1 {
            set x 3
@@ -290,7 +290,7 @@ test uplevel-7.3 {var access, LVT in upper level} -setup {
     }
 } -body {
     proc foo {} {
-       set x 2 
+       set x 2
        set y 2
        uplevel 1 {
            set x 3
@@ -304,7 +304,24 @@ test uplevel-7.3 {var access, LVT in upper level} -setup {
     rename foo {}
     rename moo {}
 } -result {3 3 3}
+
+
+test uplevel-8.0 {
+    string representation isn't generated when there is only one argument
+} -body {
+    set res {}
+    set script [list lindex 5]
+    lappend res [apply {script {
+       uplevel $script
+    }} $script]
+    lappend res [string match {value is a list *no string representation*} [
+       ::tcl::unsupported::representation $script]]
+} -cleanup {
+    unset script
+    unset res
+} -result {5 1}
 \f
+
 # cleanup
 ::tcltest::cleanupTests
 return
index aea9333..10e0e9f 100644 (file)
@@ -11,8 +11,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 95775a8..99d4c36 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest 2
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
 ::tcltest::loadTestedCommands
 catch [list package require -exact Tcltest [info patchlevel]]
 
+testConstraint ucs2 [expr {[format %c 0x010000] eq "\uFFFD"}]
+testConstraint fullutf [expr {[format %c 0x010000] ne "\uFFFD"}]
+testConstraint utf16 [expr {[string length [format %c 0x10000]] == 2}]
+testConstraint ucs4 [expr {[testConstraint fullutf]
+               && [string length [format %c 0x10000]] == 1}]
+
+testConstraint Uesc [expr {"\U0041" eq "A"}]
+testConstraint pre388 [expr {"\x741" eq "A"}]
+testConstraint pairsTo4bytes [expr {[llength [info commands teststringbytes]]
+               && [string length [teststringbytes \uD83D\uDCA9]] == 4}]
+
 testConstraint testbytestring [llength [info commands testbytestring]]
+testConstraint testfindfirst [llength [info commands testfindfirst]]
+testConstraint testfindlast [llength [info commands testfindlast]]
+testConstraint testnumutfchars [llength [info commands testnumutfchars]]
+testConstraint teststringobj [llength [info commands teststringobj]]
+testConstraint testutfnext [llength [info commands testutfnext]]
+testConstraint testutfprev [llength [info commands testutfprev]]
 
-catch {unset x}
+testConstraint tip413 [expr {[string trim \x00] eq {}}]
 
-# Some tests require support for 4-byte UTF-8 sequences
-testConstraint fullutf [expr {[format %c 0x010000] != "\ufffd"}]
+catch {unset x}
 
 test utf-1.1 {Tcl_UniCharToUtf: 1 byte sequences} testbytestring {
-    expr {"\x01" eq [testbytestring "\x01"]}
+    expr {"\x01" eq [testbytestring \x01]}
 } 1
 test utf-1.2 {Tcl_UniCharToUtf: 2 byte sequences} testbytestring {
-    expr {"\x00" eq [testbytestring "\xc0\x80"]}
+    expr {"\x00" eq [testbytestring \xC0\x80]}
 } 1
 test utf-1.3 {Tcl_UniCharToUtf: 2 byte sequences} testbytestring {
-    expr {"\xe0" eq [testbytestring "\xc3\xa0"]}
+    expr {"\xE0" eq [testbytestring \xC3\xA0]}
 } 1
 test utf-1.4 {Tcl_UniCharToUtf: 3 byte sequences} testbytestring {
-    expr {"\u4e4e" eq [testbytestring "\xe4\xb9\x8e"]}
+    expr {"\u4E4E" eq [testbytestring \xE4\xB9\x8E]}
 } 1
 test utf-1.5 {Tcl_UniCharToUtf: overflowed Tcl_UniChar} testbytestring {
-    expr {[format %c 0x110000] eq [testbytestring "\xef\xbf\xbd"]}
+    expr {[format %c 0x110000] eq [testbytestring \xEF\xBF\xBD]}
 } 1
 test utf-1.6 {Tcl_UniCharToUtf: negative Tcl_UniChar} testbytestring {
-    expr {[format %c -1] eq [testbytestring "\xef\xbf\xbd"]}
+    expr {[format %c -1] eq [testbytestring \xEF\xBF\xBD]}
+} 1
+test utf-1.7.0 {Tcl_UniCharToUtf: 4 byte sequences} {fullutf Uesc testbytestring} {
+    expr {"\U014E4E" eq [testbytestring \xF0\x94\xB9\x8E]}
+} 1
+test utf-1.7.1 {Tcl_UniCharToUtf: 4 byte sequences} {ucs2 Uesc testbytestring} {
+    expr {"\U014E4E" eq [testbytestring \xF0\x94\xB9\x8E]}
+} 0
+test utf-1.8 {Tcl_UniCharToUtf: 3 byte sequence, high surrogate} testbytestring {
+    expr {"\uD842" eq [testbytestring \xED\xA1\x82]}
+} 1
+test utf-1.9 {Tcl_UniCharToUtf: 3 byte sequence, low surrogate} testbytestring {
+    expr {"\uDC42" eq [testbytestring \xED\xB1\x82]}
+} 1
+test utf-1.10 {Tcl_UniCharToUtf: 3 byte sequence, high surrogate} testbytestring {
+    expr {[format %c 0xD842] eq [testbytestring \xED\xA1\x82]}
+} 1
+test utf-1.11 {Tcl_UniCharToUtf: 3 byte sequence, low surrogate} testbytestring {
+    expr {[format %c 0xDC42] eq [testbytestring \xED\xB1\x82]}
+} 1
+test utf-1.12 {Tcl_UniCharToUtf: 4 byte sequence, high/low surrogate} {pairsTo4bytes testbytestring} {
+    expr {"\uD842\uDC42" eq [testbytestring \xF0\xA0\xA1\x82]}
+} 1
+test utf-1.13 {Tcl_UniCharToUtf: Invalid surrogate} {Uesc ucs2} {
+    expr {"\UD842" eq "\uD842"}
 } 1
-test utf-1.7 {Tcl_UniCharToUtf: 4 byte sequences} -constraints {fullutf testbytestring} -body {
-    expr {"\U014e4e" eq [testbytestring "\xf0\x94\xb9\x8e"]}
-} -result 1
 
 test utf-2.1 {Tcl_UtfToUniChar: low ascii} {
     string length "abc"
-} {3}
+} 3
 test utf-2.2 {Tcl_UtfToUniChar: naked trail bytes} testbytestring {
-    string length [testbytestring "\x82\x83\x84"]
-} {3}
+    string length [testbytestring \x82\x83\x84]
+} 3
 test utf-2.3 {Tcl_UtfToUniChar: lead (2-byte) followed by non-trail} testbytestring {
-    string length [testbytestring "\xC2"]
-} {1}
-test utf-2.4 {Tcl_UtfToUniChar: lead (2-byte) followed by trail} testbytestring {
-    string length [testbytestring "\xC2\xa2"]
-} {1}
+    string length [testbytestring \xC2]
+} 1
+test utf-2.4 {Tcl_UtfToUniChar: lead (2-byte) followed by trail} {
+    string length \xA2
+} 1
 test utf-2.5 {Tcl_UtfToUniChar: lead (3-byte) followed by non-trail} testbytestring {
-    string length [testbytestring "\xE2"]
-} {1}
+    string length [testbytestring \xE2]
+} 1
 test utf-2.6 {Tcl_UtfToUniChar: lead (3-byte) followed by 1 trail} testbytestring {
-    string length [testbytestring "\xE2\xA2"]
-} {2}
+    string length [testbytestring \xE2\xA2]
+} 2
 test utf-2.7 {Tcl_UtfToUniChar: lead (3-byte) followed by 2 trail} testbytestring {
-    string length [testbytestring "\xE4\xb9\x8e"]
-} {1}
-test utf-2.8 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} -constraints {fullutf testbytestring} -body {
-    string length [testbytestring "\xF0\x90\x80\x80"]
-} -result {2}
-test utf-2.9 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} -constraints {fullutf testbytestring} -body {
-    string length [testbytestring "\xF4\x8F\xBF\xBF"]
-} -result {2}
+    string length [testbytestring \xE4\xB9\x8E]
+} 1
+test utf-2.8.0 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} {testbytestring ucs2} {
+    string length [testbytestring \xF0\x90\x80\x80]
+} 2
+test utf-2.8.1 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} {testbytestring ucs4} {
+    string length [testbytestring \xF0\x90\x80\x80]
+} 1
+test utf-2.9.0 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} {testbytestring ucs2} {
+    string length [testbytestring \xF4\x8F\xBF\xBF]
+} 2
+test utf-2.9.1 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail} {Uesc ucs4} {
+    string length \U10FFFF
+} 1
 test utf-2.10 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail, underflow} testbytestring {
-    string length [testbytestring "\xF0\x8F\xBF\xBF"]
-} {4}
+    string length [testbytestring \xF0\x8F\xBF\xBF]
+} 4
 test utf-2.11 {Tcl_UtfToUniChar: lead (4-byte) followed by 3 trail, overflow} testbytestring {
-    string length [testbytestring "\xF4\x90\x80\x80"]
-} {4}
+    # Would decode to U+110000 but that is outside the Unicode range.
+    string length [testbytestring \xF4\x90\x80\x80]
+} 4
 test utf-2.12 {Tcl_UtfToUniChar: longer UTF sequences not supported} testbytestring {
-    string length [testbytestring "\xF8\xA2\xA2\xA2\xA2"]
-} {5}
+    string length [testbytestring \xF8\xA2\xA2\xA2\xA2]
+} 5
 
 test utf-3.1 {Tcl_UtfCharComplete} {
 } {}
 
-testConstraint testnumutfchars [llength [info commands testnumutfchars]]
-testConstraint testfindfirst [llength [info commands testfindfirst]]
-testConstraint testfindlast [llength [info commands testfindlast]]
-
 test utf-4.1 {Tcl_NumUtfChars: zero length} testnumutfchars {
     testnumutfchars ""
-} {0}
-test utf-4.2 {Tcl_NumUtfChars: length 1} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\xC2\xA2"]
-} {1}
+} 0
+test utf-4.2 {Tcl_NumUtfChars: length 1} testnumutfchars {
+    testnumutfchars \xA2
+} 1
 test utf-4.3 {Tcl_NumUtfChars: long string} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "abc\xC2\xA2\xe4\xb9\x8e\uA2\u4e4e"]
-} {7}
-test utf-4.4 {Tcl_NumUtfChars: #u0000} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\xC0\x80"]
-} {1}
+    testnumutfchars abc\xA2[testbytestring \xE4\xB9\x8E\xA2\x4E]
+} 7
+test utf-4.4 {Tcl_NumUtfChars: #x00} testnumutfchars {
+    testnumutfchars \x00
+} 1
 test utf-4.5 {Tcl_NumUtfChars: zero length, calc len} testnumutfchars {
     testnumutfchars "" 0
-} {0}
+} 0
 test utf-4.6 {Tcl_NumUtfChars: length 1, calc len} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\xC2\xA2"] 2
-} {1}
+    testnumutfchars \xA2 end
+} 1
 test utf-4.7 {Tcl_NumUtfChars: long string, calc len} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "abc\xC2\xA2\xe4\xb9\x8e\uA2\u4e4e"] 10
-} {7}
-test utf-4.8 {Tcl_NumUtfChars: #u0000, calc len} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\xC0\x80"] 2
-} {1}
+    testnumutfchars abc\xA2[testbytestring \xE4\xB9\x8E\xA2\x4E] end
+} 7
+test utf-4.8 {Tcl_NumUtfChars: #x00, calc len} testnumutfchars {
+    testnumutfchars \x00 end
+} 1
 # Bug [2738427]: Tcl_NumUtfChars(...) no overflow check
 test utf-4.9 {Tcl_NumUtfChars: #u20AC, calc len, incomplete} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\xE2\x82\xAC"] 2
-} {2}
-test utf-4.10 {Tcl_NumUtfChars: #u0000, calc len, overcomplete} {testnumutfchars testbytestring} {
-    testnumutfchars [testbytestring "\x00"] 2
-} {2}
+    testnumutfchars [testbytestring \xE2\x82\xAC] end-1
+} 2
+test utf-4.10 {Tcl_NumUtfChars: #x00, calc len, overcomplete} {testnumutfchars testbytestring} {
+    testnumutfchars [testbytestring \x00] end+1
+} 2
+test utf-4.11 {Tcl_NumUtfChars: 3 bytes of 4-byte UTF-8 characater} {testnumutfchars testbytestring} {
+    testnumutfchars [testbytestring \xF0\x9F\x92\xA9] end-1
+} 3
+test utf-4.12.0 {Tcl_NumUtfChars: #4-byte UTF-8 character} {testnumutfchars testbytestring ucs2} {
+    testnumutfchars [testbytestring \xF0\x9F\x92\xA9] end
+} 2
+test utf-4.12.1 {Tcl_NumUtfChars: #4-byte UTF-8 character} {testnumutfchars testbytestring ucs4} {
+    testnumutfchars [testbytestring \xF0\x9F\x92\xA9] end
+} 1
+test utf-4.13 {Tcl_NumUtfChars: end of string} {testnumutfchars testbytestring} {
+    testnumutfchars foobar[testbytestring \xF2\xC2\xA0] end
+} 8
+test utf-4.14 {Tcl_NumUtfChars: 3 bytes of 4-byte UTF-8 characater} {testnumutfchars testbytestring} {
+    testnumutfchars [testbytestring \xF4\x90\x80\x80] end-1
+} 3
 
 test utf-5.1 {Tcl_UtfFindFirst} {testfindfirst testbytestring} {
-    testfindfirst [testbytestring "abcbc"] 98
-} {bcbc}
+    testfindfirst [testbytestring abcbc] 98
+} bcbc
 test utf-5.2 {Tcl_UtfFindLast} {testfindlast testbytestring} {
-    testfindlast [testbytestring "abcbc"] 98
-} {bc}
+    testfindlast [testbytestring abcbc] 98
+} bc
 
-test utf-6.1 {Tcl_UtfNext} {
-} {}
+test utf-6.1 {Tcl_UtfNext} {testutfnext testbytestring} {
+    # This takes the pointer one past the terminating NUL.
+    # This is really an invalid call.
+    testutfnext [testbytestring \x00]
+} 1
+test utf-6.2 {Tcl_UtfNext} testutfnext {
+    testutfnext A
+} 1
+test utf-6.3 {Tcl_UtfNext} testutfnext {
+    testutfnext AA
+} 1
+test utf-6.4 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xA0]
+} 1
+test utf-6.5 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xD0]
+} 1
+test utf-6.6 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xE8]
+} 1
+test utf-6.7 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xF2]
+} 1
+test utf-6.8 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xF8]
+} 1
+test utf-6.9 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\x00]
+} 1
+test utf-6.10 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0]G
+} 1
+test utf-6.11 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\x00]
+} 1
+test utf-6.12 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xD0]
+} 1
+test utf-6.13 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xE8]
+} 1
+test utf-6.14 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xF2]
+} 1
+test utf-6.15 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xF8]
+} 1
+test utf-6.16 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\x00]
+} 1
+test utf-6.17 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0]G
+} 1
+test utf-6.18 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0]
+} 2
+test utf-6.19 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xD0]
+} 1
+test utf-6.20 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xE8]
+} 1
+test utf-6.21 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xF2]
+} 1
+test utf-6.22 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xF8]
+} 1
+test utf-6.23 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\x00]
+} 1
+test utf-6.24 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8]G
+} 1
+test utf-6.25 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0\x00]
+} 1
+test utf-6.26 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xD0]
+} 1
+test utf-6.27 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xE8]
+} 1
+test utf-6.28 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xF2]
+} 1
+test utf-6.29 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xF8]
+} 1
+test utf-6.30.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2]
+} 1
+test utf-6.30.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\x00]
+} 1
+test utf-6.31 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2]G
+} 1
+test utf-6.32.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0]
+} 1
+test utf-6.32.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\x00]
+} 1
+test utf-6.33 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xD0]
+} 1
+test utf-6.34 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xE8]
+} 1
+test utf-6.35 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xF2]
+} 1
+test utf-6.36 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xF8]
+} 1
+test utf-6.37 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8]
+} 1
+test utf-6.38 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8]G
+} 1
+test utf-6.39 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8\xA0]
+} 1
+test utf-6.40 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8\xD0]
+} 1
+test utf-6.41 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8\xE8]
+} 1
+test utf-6.42 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8\xF2]
+} 1
+test utf-6.43 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF8\xF8]
+} 1
+test utf-6.44 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0]G
+} 2
+test utf-6.45 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xA0]
+} 2
+test utf-6.46 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xD0]
+} 2
+test utf-6.47 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xE8]
+} 2
+test utf-6.48 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xF2]
+} 2
+test utf-6.49 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xF8]
+} 2
+test utf-6.50 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0]G
+} 1
+test utf-6.51 {Tcl_UtfNext} testutfnext {
+    testutfnext \u8820
+} 3
+test utf-6.52 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0\xD0]
+} 1
+test utf-6.53 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0\xE8]
+} 1
+test utf-6.54 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0\xF2]
+} 1
+test utf-6.55 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE8\xA0\xF8]
+} 1
+test utf-6.56 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0]G
+} 1
+test utf-6.57 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\x00]
+} 1
+test utf-6.58 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xD0]
+} 1
+test utf-6.59 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xE8]
+} 1
+test utf-6.60 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xF2]
+} 1
+test utf-6.61 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xF8]
+} 1
+test utf-6.62 {Tcl_UtfNext} testutfnext {
+    testutfnext \u8820G
+} 3
+test utf-6.63 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xA0]
+} 3
+test utf-6.64 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xD0]
+} 3
+test utf-6.65 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xE8]
+} 3
+test utf-6.66 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xF2]
+} 3
+test utf-6.67 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xF8]
+} 3
+test utf-6.68 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0]G
+} 1
+test utf-6.69.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]
+} 1
+test utf-6.69.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]
+} 4
+test utf-6.70 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xD0]
+} 1
+test utf-6.71 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xE8]
+} 1
+test utf-6.72 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xF2]
+} 1
+test utf-6.73 {Tcl_UtfNext} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xF8]
+} 1
+test utf-6.74.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G
+} 1
+test utf-6.74.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G
+} 4
+test utf-6.75.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0]
+} 1
+test utf-6.75.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0]
+} 4
+test utf-6.76.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xD0]
+} 1
+test utf-6.76.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xD0]
+} 4
+test utf-6.77.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xE8]
+} 1
+test utf-6.77.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xE8]
+} 4
+test utf-6.78.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xF2]
+} 1
+test utf-6.78.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xF2]
+} 4
+test utf-6.79.0 {Tcl_UtfNext} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0G\xF8]
+} 1
+test utf-6.79.1 {Tcl_UtfNext} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0G\xF8]
+} 4
+test utf-6.80 {Tcl_UtfNext - overlong sequences} testutfnext {
+    testutfnext \x00
+} 2
+test utf-6.81 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xC0\x81]
+} 1
+test utf-6.82 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xC1\x80]
+} 1
+test utf-6.83 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xC2\x80]
+} 2
+test utf-6.84 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE0\x80\x80]
+} 1
+test utf-6.85 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xE0\xA0\x80]
+} 3
+test utf-6.86 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF0\x80\x80\x80]
+} 1
+test utf-6.87.0 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF0\x90\x80\x80]
+} 1
+test utf-6.87.1 {Tcl_UtfNext - overlong sequences} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF0\x90\x80\x80]
+} 4
+test utf-6.88 {Tcl_UtfNext, pointing to 2th byte of 3-byte valid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\x00]
+} 1
+test utf-6.89 {Tcl_UtfNext, pointing to 2th byte of 3-byte invalid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \x80\x80\x00]
+} 1
+test utf-6.90.0 {Tcl_UtfNext, validity check [493dccc2de]} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF4\x8F\xBF\xBF]
+} 1
+test utf-6.90.1 {Tcl_UtfNext, validity check [493dccc2de]} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF4\x8F\xBF\xBF]
+} 4
+test utf-6.91 {Tcl_UtfNext, validity check [493dccc2de]} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF4\x90\x80\x80]
+} 1
+test utf-6.92 {Tcl_UtfNext, pointing to 2th byte of 4-byte valid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0]
+} 1
+test utf-6.93 {Tcl_UtfNext, pointing to 2th byte of 4-byte invalid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \x80\x80\x80]
+} 1
+test utf-6.94 {Tcl_UtfNext, pointing to 2th byte of 5-byte invalid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0\xA0]
+} 1
+test utf-6.95 {Tcl_UtfNext, pointing to 2th byte of 5-byte invalid sequence} {testutfnext testbytestring} {
+    testutfnext [testbytestring \x80\x80\x80\x80]
+} 1
+test utf-6.96 {Tcl_UtfNext, read limits} testutfnext {
+    testutfnext G 0
+} 0
+test utf-6.97 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0] 0
+} 0
+test utf-6.98 {Tcl_UtfNext, read limits} testutfnext {
+    testutfnext AG 1
+} 1
+test utf-6.99 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext A[testbytestring \xA0] 1
+} 1
+test utf-6.100 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0]G 1
+} 0
+test utf-6.101 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0]G 2
+} 2
+test utf-6.102 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xA0] 1
+} 0
+test utf-6.103 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xD0\xA0\xA0] 2
+} 2
+test utf-6.104 {Tcl_UtfNext, read limits} testutfnext {
+    testutfnext \u8820G 1
+} 0
+test utf-6.105 {Tcl_UtfNext, read limits} testutfnext {
+    testutfnext \u8820G 2
+} 0
+test utf-6.106 {Tcl_UtfNext, read limits} testutfnext {
+    testutfnext \u8820G 3
+} 3
+test utf-6.107 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xA0] 1
+} 0
+test utf-6.108 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xA0] 2
+} 0
+test utf-6.109 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext \u8820[testbytestring \xA0] 3
+} 3
+# This testcase actually tests Tcl_UtfCharComplete, not Tcl_UtfNext
+test utf-6.110 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 1
+} 0
+# This testcase actually tests Tcl_UtfCharComplete, not Tcl_UtfNext
+test utf-6.111 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 2
+} 0
+test utf-6.112.0 {Tcl_UtfNext, read limits} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 3
+} 1
+test utf-6.112.1 {Tcl_UtfNext, read limits} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 3
+} 0
+test utf-6.113.0 {Tcl_UtfNext, read limits} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 4
+} 1
+test utf-6.113.1 {Tcl_UtfNext, read limits} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0]G 4
+} 4
+# This testcase actually tests Tcl_UtfCharComplete, not Tcl_UtfNext
+test utf-6.114 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 1
+} 0
+# This testcase actually tests Tcl_UtfCharComplete, not Tcl_UtfNext
+test utf-6.115 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 2
+} 0
+test utf-6.116.0 {Tcl_UtfNext, read limits} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 3
+} 1
+test utf-6.116.1 {Tcl_UtfNext, read limits} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 3
+} 0
+test utf-6.117.0 {Tcl_UtfNext, read limits} {testutfnext testbytestring ucs2} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 4
+} 1
+test utf-6.117.1 {Tcl_UtfNext, read limits} {testutfnext testbytestring fullutf} {
+    testutfnext [testbytestring \xF2\xA0\xA0\xA0\xA0] 4
+} 4
+test utf-6.118 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0]G 0
+} 0
+test utf-6.119 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0]G 1
+} 0
+test utf-6.120 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0] 1
+} 0
+test utf-6.121 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0]G 2
+} 0
+test utf-6.122 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0] 2
+} 0
+test utf-6.123 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0]G 3
+} 1
+test utf-6.124 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0\xA0] 3
+} 1
+test utf-6.125 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0\xA0]G 4
+} 1
+test utf-6.126 {Tcl_UtfNext, read limits} {testutfnext testbytestring} {
+    testutfnext [testbytestring \xA0\xA0\xA0\xA0\xA0] 4
+} 1
 
-test utf-7.1 {Tcl_UtfPrev} {
-} {}
+test utf-7.1 {Tcl_UtfPrev} testutfprev {
+    testutfprev {}
+} 0
+test utf-7.2 {Tcl_UtfPrev} testutfprev {
+    testutfprev A
+} 0
+test utf-7.3 {Tcl_UtfPrev} testutfprev {
+    testutfprev AA
+} 1
+test utf-7.4 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8]
+} 1
+test utf-7.4.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0\xA0] 2
+} 1
+test utf-7.4.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xF8\xA0\xA0] 2
+} 1
+test utf-7.5 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF2]
+} 1
+test utf-7.5.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0] 2
+} 1
+test utf-7.5.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF2\xF8\xA0\xA0] 2
+} 1
+test utf-7.6 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE8]
+} 1
+test utf-7.6.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A\u8820[testbytestring \xA0] 2
+} 1
+test utf-7.6.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE8\xF8\xA0\xA0] 2
+} 1
+test utf-7.7 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0]
+} 1
+test utf-7.7.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0\xA0] 2
+} 1
+test utf-7.7.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xF8\xA0\xA0] 2
+} 1
+test utf-7.8 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0]
+} 1
+test utf-7.8.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0\xA0] 2
+} 1
+test utf-7.8.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xF8\xA0\xA0] 2
+} 1
+test utf-7.9 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0]
+} 2
+test utf-7.9.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0\xA0] 3
+} 2
+test utf-7.9.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xF8\xA0] 3
+} 2
+test utf-7.10.0 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0]
+} 2
+test utf-7.10.1 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0]
+} 1
+test utf-7.10.2 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0] 3
+} 2
+test utf-7.10.3 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0] 3
+} 1
+test utf-7.10.4 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0\xF8\xA0] 3
+} 2
+test utf-7.10.5 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0\xF8\xA0] 3
+} 1
+test utf-7.11 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE8\xA0]
+} 1
+test utf-7.11.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A\u8820[testbytestring \xA0] 3
+} 1
+test utf-7.11.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE8\xA0\xF8\xA0] 3
+} 1
+test utf-7.11.3 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE8\xA0\xF8] 3
+} 1
+test utf-7.12 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0]
+} 1
+test utf-7.12.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0\xA0] 3
+} 1
+test utf-7.12.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xF8\xA0] 3
+} 1
+test utf-7.13 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0]
+} 2
+test utf-7.13.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0\xA0] 3
+} 2
+test utf-7.13.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xF8\xA0] 3
+} 2
+test utf-7.14 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0]
+} 3
+test utf-7.14.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0\xA0] 4
+} 3
+test utf-7.14.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0\xF8] 4
+} 3
+test utf-7.15.0 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0\xA0]
+} 3
+test utf-7.15.1 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0\xA0]
+} 1
+test utf-7.15.2 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0] 4
+} 3
+test utf-7.15.3 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0] 4
+} 1
+test utf-7.15.4 {Tcl_UtfPrev} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xF8] 4
+} 3
+test utf-7.15.5 {Tcl_UtfPrev} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xF8] 4
+} 1
+test utf-7.16 {Tcl_UtfPrev} testutfprev {
+    testutfprev A\u8820
+} 1
+test utf-7.16.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A\u8820[testbytestring \xA0] 4
+} 1
+test utf-7.16.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A\u8820[testbytestring \xF8] 4
+} 1
+test utf-7.17 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0]
+} 3
+test utf-7.17.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0\xA0] 4
+} 3
+test utf-7.17.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0\xF8] 4
+} 3
+test utf-7.18.0 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0]
+} 3
+test utf-7.18.1 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0\xA0] 4
+} 3
+test utf-7.18.2 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0\xF8] 4
+} 3
+test utf-7.19 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF8\xA0\xA0\xA0]
+} 4
+test utf-7.20 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF2\xA0\xA0\xA0]
+} 4
+test utf-7.21 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A\u8820[testbytestring \xA0]
+} 4
+test utf-7.22 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xD0\xA0\xA0\xA0]
+} 4
+test utf-7.23 {Tcl_UtfPrev} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xA0\xA0\xA0\xA0]
+} 4
+test utf-7.24 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xC0\x81]
+} 2
+test utf-7.25 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xC0\x81] 2
+} 1
+test utf-7.26 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\x80\x80]
+} 3
+test utf-7.27 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\x80]
+} 2
+test utf-7.27.1 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\x80\x80] 3
+} 2
+test utf-7.28 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0]
+} 1
+test utf-7.28.1 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\x80\x80] 2
+} 1
+test utf-7.29 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x80\x80\x80]
+} 4
+test utf-7.30 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x80\x80\x80] 4
+} 3
+test utf-7.31 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x80\x80\x80] 3
+} 2
+test utf-7.32 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x80\x80\x80] 2
+} 1
+test utf-7.33 {Tcl_UtfPrev -- overlong sequence}  testutfprev {
+    testutfprev A\x00
+} 1
+test utf-7.34 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xC1\x80]
+} 2
+test utf-7.35 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xC2\x80]
+} 1
+test utf-7.36 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\xA0\x80]
+} 1
+test utf-7.37 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\xA0\x80] 3
+} 1
+test utf-7.38 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xE0\xA0\x80] 2
+} 1
+test utf-7.39 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80]
+} 4
+test utf-7.40.0 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80] 4
+} 3
+test utf-7.40.1 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80] 4
+} 1
+test utf-7.41.0 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80] 3
+} 2
+test utf-7.41.1 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80] 3
+} 1
+test utf-7.42 {Tcl_UtfPrev -- overlong sequence}  {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF0\x90\x80\x80] 2
+} 1
+test utf-7.43 {Tcl_UtfPrev -- no lead byte at start}  {testutfprev testbytestring} {
+    testutfprev [testbytestring \xA0]
+} 0
+test utf-7.44 {Tcl_UtfPrev -- no lead byte at start}  {testutfprev testbytestring} {
+    testutfprev [testbytestring \xA0\xA0]
+} 1
+test utf-7.45 {Tcl_UtfPrev -- no lead byte at start}  {testutfprev testbytestring} {
+    testutfprev [testbytestring \xA0\xA0\xA0]
+} 2
+test utf-7.46 {Tcl_UtfPrev -- no lead byte at start}  {testutfprev testbytestring} {
+    testutfprev [testbytestring \xA0\xA0\xA0\xA0]
+} 3
+test utf-7.47 {Tcl_UtfPrev, pointing to 3th byte of 3-byte valid sequence} {testutfprev testbytestring} {
+    testutfprev [testbytestring \xE8\xA0]
+} 0
+test utf-7.47.1 {Tcl_UtfPrev, pointing to 3th byte of 3-byte valid sequence} testutfprev {
+    testutfprev \u8820 2
+} 0
+test utf-7.47.2 {Tcl_UtfPrev, pointing to 3th byte of 3-byte invalid sequence} {testutfprev testbytestring} {
+    testutfprev [testbytestring \xE8\xA0\x00] 2
+} 0
+test utf-7.48.0 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF]
+} 4
+test utf-7.48.1 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF] 4
+} 3
+test utf-7.48.2 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF] 4
+} 1
+test utf-7.48.3 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring ucs2} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF] 3
+} 2
+test utf-7.48.4 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring fullutf} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF] 3
+} 1
+test utf-7.48.5 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x8F\xBF\xBF] 2
+} 1
+test utf-7.49.0 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x90\x80\x80]
+} 4
+test utf-7.49.1 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x90\x80\x80] 4
+} 3
+test utf-7.49.2 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x90\x80\x80] 3
+} 2
+test utf-7.49.3 {Tcl_UtfPrev, validity check [493dccc2de]} {testutfprev testbytestring} {
+    testutfprev A[testbytestring \xF4\x90\x80\x80] 2
+} 1
 
 test utf-8.1 {Tcl_UniCharAtIndex: index = 0} {
     string index abcd 0
-} {a}
+} a
 test utf-8.2 {Tcl_UniCharAtIndex: index = 0} {
-    string index \u4e4e\u25a 0
-} "\u4e4e"
+    string index \u4E4E\u25A 0
+} \u4E4E
 test utf-8.3 {Tcl_UniCharAtIndex: index > 0} {
     string index abcd 2
-} {c}
+} c
 test utf-8.4 {Tcl_UniCharAtIndex: index > 0} {
-    string index \u4e4e\u25a\xff\u543 2
-} "\uff"
+    string index \u4E4E\u25A\xFF\u543 2
+} \xFF
+test utf-8.5.0 {Tcl_UniCharAtIndex: high surrogate} ucs2 {
+    string index \uD842 0
+} \uD842
+test utf-8.5.1 {Tcl_UniCharAtIndex: high surrogate} ucs4 {
+    string index \uD842 0
+} \uD842
+test utf-8.5.2 {Tcl_UniCharAtIndex: high surrogate} utf16 {
+    string index \uD842 0
+} \uD842
+test utf-8.6 {Tcl_UniCharAtIndex: low surrogate} {
+    string index \uDC42 0
+} \uDC42
+test utf-8.7.0 {Tcl_UniCharAtIndex: Emoji} ucs2 {
+    string index \uD83D\uDE00G 0
+} \uD83D
+test utf-8.7.1 {Tcl_UniCharAtIndex: Emoji} ucs4 {
+    string index \uD83D\uDE00G 0
+} \U1F600
+test utf-8.7.2 {Tcl_UniCharAtIndex: Emoji} utf16 {
+    string index \uD83D\uDE00G 0
+} \U1F600
+test utf-8.8.0 {Tcl_UniCharAtIndex: Emoji} ucs2 {
+    string index \uD83D\uDE00G 1
+} \uDE00
+test utf-8.8.1 {Tcl_UniCharAtIndex: Emoji} ucs4 {
+    string index \uD83D\uDE00G 1
+} G
+test utf-8.8.2 {Tcl_UniCharAtIndex: Emoji} utf16 {
+    string index \uD83D\uDE00G 1
+} {}
+test utf-8.9.0 {Tcl_UniCharAtIndex: Emoji} ucs2 {
+    string index \uD83D\uDE00G 2
+} G
+test utf-8.9.1 {Tcl_UniCharAtIndex: Emoji} ucs4 {
+    string index \uD83D\uDE00G 2
+} {}
+test utf-8.9.2 {Tcl_UniCharAtIndex: Emoji} utf16 {
+    string index \uD83D\uDE00G 2
+} G
+test utf-8.10.0 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs2} {
+    string index \U1F600G 0
+} \uFFFD
+test utf-8.10.1 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs4} {
+    string index \U1F600G 0
+} \U1F600
+test utf-8.10.2 {Tcl_UniCharAtIndex: Emoji} {Uesc utf16} {
+    string index \U1F600G 0
+} \U1F600
+test utf-8.11.0 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs2} {
+    string index \U1F600G 1
+} G
+test utf-8.11.1 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs4} {
+    string index \U1F600G 1
+} G
+test utf-8.11.2 {Tcl_UniCharAtIndex: Emoji} {Uesc utf16} {
+    string index \U1F600G 1
+} {}
+test utf-8.12.0 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs2} {
+    string index \U1F600G 2
+} {}
+test utf-8.12.1 {Tcl_UniCharAtIndex: Emoji} {Uesc ucs4} {
+    string index \U1F600G 2
+} {}
+test utf-8.12.2 {Tcl_UniCharAtIndex: Emoji} {Uesc utf16} {
+    string index \U1F600G 2
+} G
 
 test utf-9.1 {Tcl_UtfAtIndex: index = 0} {
     string range abcd 0 2
-} {abc}
+} abc
 test utf-9.2 {Tcl_UtfAtIndex: index > 0} {
-    string range \u4e4e\u25a\xff\u543klmnop 1 5
-} "\u25a\xff\u543kl"
-
+    string range \u4E4E\u25A\xFF\u543klmnop 1 5
+} \u25A\xFF\u543kl
+test utf-9.3.0 {Tcl_UtfAtIndex: index = 0, Emoji} ucs2 {
+    string range \uD83D\uDE00G 0 0
+} \uD83D
+test utf-9.3.1 {Tcl_UtfAtIndex: index = 0, Emoji} ucs4 {
+    string range \uD83D\uDE00G 0 0
+} \U1F600
+test utf-9.3.2 {Tcl_UtfAtIndex: index = 0, Emoji} utf16 {
+    string range \uD83D\uDE00G 0 0
+} \U1F600
+test utf-9.4.0 {Tcl_UtfAtIndex: index > 0, Emoji} ucs2 {
+    string range \uD83D\uDE00G 1 1
+} \uDE00
+test utf-9.4.1 {Tcl_UtfAtIndex: index > 0, Emoji} ucs4 {
+    string range \uD83D\uDE00G 1 1
+} G
+test utf-9.4.2 {Tcl_UtfAtIndex: index > 0, Emoji} utf16 {
+    string range \uD83D\uDE00G 1 1
+} {}
+test utf-9.5.0 {Tcl_UtfAtIndex: index > 0, Emoji} ucs2 {
+    string range \uD83D\uDE00G 2 2
+} G
+test utf-9.5.1 {Tcl_UtfAtIndex: index > 0, Emoji} ucs4 {
+    string range \uD83D\uDE00G 2 2
+} {}
+test utf-9.5.2 {Tcl_UtfAtIndex: index > 0, Emoji} utf16 {
+    string range \uD83D\uDE00G 2 2
+} G
+test utf-9.6.0 {Tcl_UtfAtIndex: index = 0, Emoji} {Uesc ucs2} {
+    string range \U1f600G 0 0
+} \uFFFD
+test utf-9.6.1 {Tcl_UtfAtIndex: index = 0, Emoji} {Uesc ucs4} {
+    string range \U1f600G 0 0
+} \U1F600
+test utf-9.6.2 {Tcl_UtfAtIndex: index = 0, Emoji} {Uesc utf16} {
+    string range \U1f600G 0 0
+} \U1F600
+test utf-9.7.0 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc ucs2} {
+    string range \U1f600G 1 1
+} G
+test utf-9.7.1 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc ucs4} {
+    string range \U1f600G 1 1
+} G
+test utf-9.7.2 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc utf16} {
+    string range \U1f600G 1 1
+} {}
+test utf-9.8.0 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc ucs2} {
+    string range \U1f600G 2 2
+} {}
+test utf-9.8.1 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc ucs4} {
+    string range \U1f600G 2 2
+} {}
+test utf-9.8.2 {Tcl_UtfAtIndex: index > 0, Emoji} {Uesc utf16} {
+    string range \U1f600G 2 2
+} G
 
 test utf-10.1 {Tcl_UtfBackslash: dst == NULL} {
     set x \n
 } {
 }
 test utf-10.2 {Tcl_UtfBackslash: \u subst} testbytestring {
-    expr {"\ua2" eq [testbytestring "\xc2\xa2"]}
+    expr {"\uA2" eq [testbytestring \xC2\xA2]}
 } 1
 test utf-10.3 {Tcl_UtfBackslash: longer \u subst} testbytestring {
-    expr {"\u4e21" eq [testbytestring "\xe4\xb8\xa1"]}
+    expr {"\u4E21" eq [testbytestring \xE4\xB8\xA1]}
 } 1
 test utf-10.4 {Tcl_UtfBackslash: stops at first non-hex} testbytestring {
-    expr {"\u4e2k" eq "[testbytestring \xd3\xa2]k"}
+    expr {"\u4E2k" eq "[testbytestring \xD3\xA2]k"}
 } 1
 test utf-10.5 {Tcl_UtfBackslash: stops after 4 hex chars} testbytestring {
-    expr {"\u4e216" eq "[testbytestring \xe4\xb8\xa1]6"}
+    expr {"\u4E216" eq "[testbytestring \xE4\xB8\xA1]6"}
+} 1
+test utf-10.6 {Tcl_UtfBackslash: stops after 5 hex chars} {Uesc fullutf testbytestring} {
+    expr {"\U1E2165" eq "[testbytestring \xF0\x9E\x88\x96]5"}
+} 1
+test utf-10.7 {Tcl_UtfBackslash: stops after 6 hex chars} {Uesc fullutf testbytestring} {
+    expr {"\U10E2165" eq "[testbytestring \xF4\x8E\x88\x96]5"}
 } 1
-proc bsCheck {char num} {
+
+proc bsCheck {char num {constraints {}}} {
     global errNum
-    test utf-10.$errNum {backslash substitution} {
+    test utf-10.$errNum {backslash substitution} $constraints {
        scan $char %c value
        set value
     } $num
     incr errNum
 }
-set errNum 6
+set errNum 8
 bsCheck \b     8
 bsCheck \e     101
 bsCheck \f     12
@@ -208,35 +1114,35 @@ bsCheck \x       120
 bsCheck \xa    10
 bsCheck \xA    10
 bsCheck \x41   65
-bsCheck \x541  84
+bsCheck \x541  65      pre388  ;# == \x41
+bsCheck \x541  84      !pre388 ;# == \x54 1
 bsCheck \u     117
 bsCheck \uk    117
 bsCheck \u41   65
 bsCheck \ua    10
 bsCheck \uA    10
 bsCheck \340   224
-bsCheck \ua1   161
-bsCheck \u4e21 20001
-bsCheck \741   60
-bsCheck \U     85
-bsCheck \Uk    85
-bsCheck \U41   65
-bsCheck \Ua    10
-bsCheck \UA    10
-bsCheck \Ua1   161
-bsCheck \U4e21 20001
-bsCheck \U004e21       20001
-bsCheck \U00004e21     20001
-bsCheck \U0000004e21   78
-if {[testConstraint fullutf]} {
-    bsCheck \U00110000 69632
-    bsCheck \U01100000 69632
-    bsCheck \U11000000 69632
-    bsCheck \U0010FFFF 1114111
-    bsCheck \U010FFFF0 1114111
-    bsCheck \U10FFFF00 1114111
-    bsCheck \UFFFFFFFF 1048575
-}
+bsCheck \uA1   161
+bsCheck \u4E21 20001
+bsCheck \741    225    pre388  ;# == \341
+bsCheck \741    60     !pre388 ;# == \74 1
+bsCheck \U      85
+bsCheck \Uk     85
+bsCheck \U41    65                     Uesc
+bsCheck \Ua     10                     Uesc
+bsCheck \UA     10                     Uesc
+bsCheck \UA1    161                    Uesc
+bsCheck \U4E21  20001                  Uesc
+bsCheck \U004E21        20001          Uesc
+bsCheck \U00004E21      20001          Uesc
+bsCheck \U0000004E21    78             Uesc
+bsCheck \U00110000      69632          {Uesc fullutf}
+bsCheck \U01100000      69632          {Uesc fullutf}
+bsCheck \U11000000      69632          {Uesc fullutf}
+bsCheck \U0010FFFF      1114111                {Uesc fullutf}
+bsCheck \U010FFFF0      1114111                {Uesc fullutf}
+bsCheck \U10FFFF00      1114111                {Uesc fullutf}
+bsCheck \UFFFFFFFF      1048575                {Uesc fullutf}
 
 test utf-11.1 {Tcl_UtfToUpper} {
     string toupper {}
@@ -245,11 +1151,23 @@ test utf-11.2 {Tcl_UtfToUpper} {
     string toupper abc
 } ABC
 test utf-11.3 {Tcl_UtfToUpper} {
-    string toupper \u00e3ab
-} \u00c3AB
+    string toupper \xE3gh
+} \xC3GH
 test utf-11.4 {Tcl_UtfToUpper} {
-    string toupper \u01e3ab
-} \u01e2AB
+    string toupper \u01E3gh
+} \u01E2GH
+test utf-11.5 {Tcl_UtfToUpper Georgian (new in Unicode 11)} {
+    string toupper \u10D0\u1C90
+} \u1C90\u1C90
+test utf-11.6 {Tcl_UtfToUpper beyond U+FFFF} {Uesc fullutf} {
+    string toupper \U10428
+} \U10400
+test utf-11.7 {Tcl_UtfToUpper beyond U+FFFF} fullutf {
+    string toupper \uD801\uDC28
+} \uD801\uDC00
+test utf-11.8 {Tcl_UtfToUpper low/high surrogate)} {
+    string toupper \uDC24\uD824
+} \uDC24\uD824
 
 test utf-12.1 {Tcl_UtfToLower} {
     string tolower {}
@@ -258,11 +1176,23 @@ test utf-12.2 {Tcl_UtfToLower} {
     string tolower ABC
 } abc
 test utf-12.3 {Tcl_UtfToLower} {
-    string tolower \u00c3AB
-} \u00e3ab
+    string tolower \xC3GH
+} \xE3gh
 test utf-12.4 {Tcl_UtfToLower} {
-    string tolower \u01e2AB
-} \u01e3ab
+    string tolower \u01E2GH
+} \u01E3gh
+test utf-12.5 {Tcl_UtfToLower Georgian (new in Unicode 11)} {
+    string tolower \u10D0\u1C90
+} \u10D0\u10D0
+test utf-12.6 {Tcl_UtfToLower low/high surrogate)} {
+    string tolower \uDC24\uD824
+} \uDC24\uD824
+test utf-12.7 {Tcl_UtfToLower beyond U+FFFF} {Uesc fullutf} {
+    string tolower \U10400
+} \U10428
+test utf-12.8 {Tcl_UtfToLower beyond U+FFFF} fullutf {
+    string tolower \uD801\uDC00
+} \uD801\uDC28
 
 test utf-13.1 {Tcl_UtfToTitle} {
     string totitle {}
@@ -271,11 +1201,26 @@ test utf-13.2 {Tcl_UtfToTitle} {
     string totitle abc
 } Abc
 test utf-13.3 {Tcl_UtfToTitle} {
-    string totitle \u00e3ab
-} \u00c3ab
+    string totitle \xE3GH
+} \xC3gh
 test utf-13.4 {Tcl_UtfToTitle} {
-    string totitle \u01f3ab
-} \u01f2ab
+    string totitle \u01F3AB
+} \u01F2ab
+test utf-13.5 {Tcl_UtfToTitle Georgian (new in Unicode 11)} {
+    string totitle \u10D0\u1C90
+} \u10D0\u1C90
+test utf-13.6 {Tcl_UtfToTitle Georgian (new in Unicode 11)} {
+    string totitle \u1C90\u10D0
+} \u1C90\u10D0
+test utf-13.7 {Tcl_UtfToTitle low/high surrogate)} {
+    string totitle \uDC24\uD824
+} \uDC24\uD824
+test utf-13.8 {Tcl_UtfToTitle beyond U+FFFF} {Uesc fullutf} {
+    string totitle \U10428\U10400
+} \U10400\U10428
+test utf-13.9 {Tcl_UtfToTitle beyond U+FFFF} fullutf {
+    string totitle \uD801\uDC28\uD801\uDC00
+} \uD801\uDC00\uD801\uDC28
 
 test utf-14.1 {Tcl_UtfNcasecmp} {
     string compare -nocase a b
@@ -294,7 +1239,7 @@ test utf-15.1 {Tcl_UniCharToUpper, negative delta} {
     string toupper aA
 } AA
 test utf-15.2 {Tcl_UniCharToUpper, positive delta} {
-    string toupper \u0178\u00ff
+    string toupper \u0178\xFF
 } \u0178\u0178
 test utf-15.3 {Tcl_UniCharToUpper, no delta} {
     string toupper !
@@ -304,24 +1249,24 @@ test utf-16.1 {Tcl_UniCharToLower, negative delta} {
     string tolower aA
 } aa
 test utf-16.2 {Tcl_UniCharToLower, positive delta} {
-    string tolower \u0178\u00ff\uA78D\u01c5\U10400
-} \u00ff\u00ff\u0265\u01c6\U10428
+    string tolower \u0178\xFF\uA78D\u01C5
+} \xFF\xFF\u0265\u01C6
 
 test utf-17.1 {Tcl_UniCharToLower, no delta} {
     string tolower !
 } !
 
 test utf-18.1 {Tcl_UniCharToTitle, add one for title} {
-    string totitle \u01c4
-} \u01c5
+    string totitle \u01C4
+} \u01C5
 test utf-18.2 {Tcl_UniCharToTitle, subtract one for title} {
-    string totitle \u01c6
-} \u01c5
+    string totitle \u01C6
+} \u01C5
 test utf-18.3 {Tcl_UniCharToTitle, subtract delta for title (positive)} {
-    string totitle \u017f
-} \u0053
+    string totitle \u017F
+} \x53
 test utf-18.4 {Tcl_UniCharToTitle, subtract delta for title (negative)} {
-    string totitle \u00ff
+    string totitle \xFF
 } \u0178
 test utf-18.5 {Tcl_UniCharToTitle, no delta} {
     string totitle !
@@ -333,155 +1278,174 @@ test utf-19.1 {TclUniCharLen} -body {
     unset -nocomplain foo
 } -result {1 4}
 
-test utf-20.1 {TclUniCharNcmp} {
-} {}
+test utf-20.1 {TclUniCharNcmp} ucs4 {
+    string compare [string range [format %c 0xFFFF] 0 0] [string range [format %c 0x10000] 0 0]
+} -1
+test utf-20.2 {[4c591fa487] TclUniCharNcmp/TclUtfNcmp} ucs2 {
+    set one [format %c 0xFFFF]
+    set two [format %c 0x10000]
+    set first [string compare $one $two]
+    string range $one 0 0
+    string range $two 0 0
+    set second [string compare $one $two]
+    expr {($first == $second) ? "agree" : "disagree"}
+} agree
+test utf-20.2.1 {[4c591fa487] TclUniCharNcmp/TclUtfNcmp} {utf16 knownBug} {
+    set one [format %c 0xFFFF]
+    set two [format %c 0x10000]
+    set first [string compare $one $two]
+    string range $one 0 0
+    string range $two 0 0
+    set second [string compare $one $two]
+    expr {($first == $second) ? "agree" : "disagree"}
+} agree
+test utf-20.2.2 {[4c591fa487] TclUniCharNcmp/TclUtfNcmp} ucs4 {
+    set one [format %c 0xFFFF]
+    set two [format %c 0x10000]
+    set first [string compare $one $two]
+    string range $one 0 0
+    string range $two 0 0
+    set second [string compare $one $two]
+    expr {($first == $second) ? "agree" : "disagree"}
+} agree
 
 test utf-21.1 {TclUniCharIsAlnum} {
     # this returns 1 with Unicode 7 compliance
-    string is alnum \u1040\u021f\u0220
-} {1}
+    string is alnum \u1040\u021F\u0220
+} 1
 test utf-21.2 {unicode alnum char in regc_locale.c} {
     # this returns 1 with Unicode 7 compliance
-    list [regexp {^[[:alnum:]]+$} \u1040\u021f\u0220] [regexp {^\w+$} \u1040\u021f\u0220_\u203f\u2040\u2054\ufe33\ufe34\ufe4d\ufe4e\ufe4f\uff3f]
+    list [regexp {^[[:alnum:]]+$} \u1040\u021F\u0220] [regexp {^\w+$} \u1040\u021F\u0220_\u203F\u2040\u2054\uFE33\uFE34\uFE4D\uFE4E\uFE4F\uFF3F]
 } {1 1}
 test utf-21.3 {unicode print char in regc_locale.c} {
     # this returns 1 with Unicode 7 compliance
-    regexp {^[[:print:]]+$} \ufbc1
+    regexp {^[[:print:]]+$} \uFBC1
 } 1
 test utf-21.4 {TclUniCharIsGraph} {
     # [Bug 3464428]
     string is graph \u0120
-} {1}
+} 1
 test utf-21.5 {unicode graph char in regc_locale.c} {
     # [Bug 3464428]
     regexp {^[[:graph:]]+$} \u0120
-} {1}
+} 1
 test utf-21.6 {TclUniCharIsGraph} {
     # [Bug 3464428]
-    string is graph \u00a0
-} {0}
+    string is graph \xA0
+} 0
 test utf-21.7 {unicode graph char in regc_locale.c} {
     # [Bug 3464428]
-    regexp {[[:graph:]]} \u0020\u00a0\u2028\u2029
-} {0}
+    regexp {[[:graph:]]} \x20\xA0\u2028\u2029
+} 0
 test utf-21.8 {TclUniCharIsPrint} {
     # [Bug 3464428]
-    string is print \u0009
-} {0}
+    string is print \x09
+} 0
 test utf-21.9 {unicode print char in regc_locale.c} {
     # [Bug 3464428]
-    regexp {[[:print:]]} \u0009
-} {0}
+    regexp {[[:print:]]} \x09
+} 0
 test utf-21.10 {unicode print char in regc_locale.c} {
     # [Bug 3464428]
-    regexp {[[:print:]]} \u0009
-} {0}
+    regexp {[[:print:]]} \x09
+} 0
 test utf-21.11 {TclUniCharIsControl} {
     # [Bug 3464428]
-    string is control \u0000\u001f\u00ad\u0605\u061c\u180e\u2066\ufeff
-} {1}
+    string is control \x00\x1F\xAD\u0605\u061C\u180E\u2066\uFEFF
+} 1
 test utf-21.12 {unicode control char in regc_locale.c} {
     # [Bug 3464428], [Bug a876646efe]
-    regexp {^[[:cntrl:]]*$} \u0000\u001f\u00ad\u0605\u061c\u180e\u2066\ufeff
-} {1}
+    regexp {^[[:cntrl:]]*$} \x00\x1F\xAD\u0605\u061C\u180E\u2066\uFEFF
+} 1
 
 test utf-22.1 {TclUniCharIsWordChar} {
     string wordend "xyz123_bar fg" 0
 } 10
 test utf-22.2 {TclUniCharIsWordChar} {
-    string wordend "x\u5080z123_bar\u203c fg" 0
+    string wordend "x\u5080z123_bar\u203C fg" 0
 } 10
 
 test utf-23.1 {TclUniCharIsAlpha} {
     # this returns 1 with Unicode 7 compliance
-    string is alpha \u021f\u0220\u037f\u052f
-} {1}
+    string is alpha \u021F\u0220\u037F\u052F
+} 1
 test utf-23.2 {unicode alpha char in regc_locale.c} {
     # this returns 1 with Unicode 7 compliance
-    regexp {^[[:alpha:]]+$} \u021f\u0220\u037f\u052f
-} {1}
+    regexp {^[[:alpha:]]+$} \u021F\u0220\u037F\u052F
+} 1
 
 test utf-24.1 {TclUniCharIsDigit} {
     # this returns 1 with Unicode 7 compliance
-    string is digit \u1040\uabf0
-} {1}
+    string is digit \u1040\uABF0
+} 1
 test utf-24.2 {unicode digit char in regc_locale.c} {
     # this returns 1 with Unicode 7 compliance
-    list [regexp {^[[:digit:]]+$} \u1040\uabf0] [regexp {^\d+$} \u1040\uabf0]
+    list [regexp {^[[:digit:]]+$} \u1040\uABF0] [regexp {^\d+$} \u1040\uABF0]
 } {1 1}
 
 test utf-24.3 {TclUniCharIsSpace} {
-    # this returns 1 with Unicode 7/TIP 413 compliance
-    string is space \u0085\u1680\u180e\u200b\u202f\u2060
-} {1}
+    # this returns 1 with Unicode 7 compliance
+    string is space \u1680\u180E\u202F
+} 1
 test utf-24.4 {unicode space char in regc_locale.c} {
+    # this returns 1 with Unicode 7 compliance
+    list [regexp {^[[:space:]]+$} \u1680\u180E\u202F] [regexp {^\s+$} \u1680\u180E\u202F]
+} {1 1}
+test utf-24.5 {TclUniCharIsSpace} tip413 {
     # this returns 1 with Unicode 7/TIP 413 compliance
-    list [regexp {^[[:space:]]+$} \u0085\u1680\u180e\u200b\u202f\u2060] [regexp {^\s+$} \u0085\u1680\u180e\u200b\u202f\u2060]
+    string is space \x85\u1680\u180E\u200B\u202F\u2060
+} 1
+test utf-24.6 {unicode space char in regc_locale.c} tip413 {
+    # this returns 1 with Unicode 7/TIP 413 compliance
+    list [regexp {^[[:space:]]+$} \x85\u1680\u180E\u200B\u202F\u2060] [regexp {^\s+$} \x85\u1680\u180E\u200B\u202F\u2060]
 } {1 1}
 
-testConstraint teststringobj [llength [info commands teststringobj]]
-
-test utf-25.1 {Tcl_UniCharNcasecmp} -constraints teststringobj \
-    -setup {
-       testobj freeallvars
-    } \
-    -body {
-       teststringobj set 1 a
-       teststringobj set 2 b
-       teststringobj getunicode 1
-       teststringobj getunicode 2
-       string compare -nocase [teststringobj get 1] [teststringobj get 2]
-    } \
-    -cleanup {
+proc UniCharCaseCmpTest {order one two {constraints {}}} {
+    variable count
+    test utf-25.$count {Tcl_UniCharNcasecmp} -setup {
        testobj freeallvars
-    } \
-    -result -1
-test utf-25.2 {Tcl_UniCharNcasecmp} -constraints teststringobj \
-    -setup {
+    } -constraints [linsert $constraints 0 teststringobj] -cleanup {
        testobj freeallvars
-    } \
-    -body {
-       teststringobj set 1 b
-       teststringobj set 2 a
+    } -body {
+       teststringobj set 1 $one
+       teststringobj set 2 $two
        teststringobj getunicode 1
        teststringobj getunicode 2
-       string compare -nocase [teststringobj get 1] [teststringobj get 2]
-    } \
-    -cleanup {
-       testobj freeallvars
-    } \
-    -result 1
-test utf-25.3 {Tcl_UniCharNcasecmp} -constraints teststringobj \
-    -setup {
-       testobj freeallvars
-    } \
-    -body {
-       teststringobj set 1 B
-       teststringobj set 2 a
-       teststringobj getunicode 1
-       teststringobj getunicode 2
-       string compare -nocase [teststringobj get 1] [teststringobj get 2]
-    } \
-    -cleanup {
-       testobj freeallvars
-    } \
-    -result 1
+       set result [string compare -nocase [teststringobj get 1] [teststringobj get 2]]
+       if {$result eq [string map {< -1 = 0 > 1} $order]} {
+           set result ok
+       } else {
+           set result "'$one' should be $order '$two' (no case)"
+       }
+       set result
+    } -result ok
+    incr count
+}
+variable count 1
+UniCharCaseCmpTest < a b
+UniCharCaseCmpTest > b a
+UniCharCaseCmpTest > B a
+UniCharCaseCmpTest > aBcB abca
+UniCharCaseCmpTest < \uFFFF [format %c 0x10000] ucs4
+UniCharCaseCmpTest < \uFFFF \U10000            {Uesc ucs4}
+UniCharCaseCmpTest > [format %c 0x10000] \uFFFF        ucs4
+UniCharCaseCmpTest > \U10000 \uFFFF            {Uesc ucs4}
 
-test utf-25.4 {Tcl_UniCharNcasecmp} -constraints teststringobj \
-    -setup {
-       testobj freeallvars
-    } \
-    -body {
-       teststringobj set 1 aBcB
-       teststringobj set 2 abca
-       teststringobj getunicode 1
-       teststringobj getunicode 2
-       string compare -nocase [teststringobj get 1] [teststringobj get 2]
-    } \
-    -cleanup {
-       testobj freeallvars
-    } \
-    -result 1
+
+test utf-26.1 {Tcl_UniCharDString} -setup {
+    testobj freeallvars
+} -constraints {teststringobj testbytestring} -cleanup {
+    testobj freeallvars
+} -body {
+    teststringobj set 1 foo
+    teststringobj getunicode 1
+    teststringobj append 1 [testbytestring barsoom\xF2\xC2\x80] 10
+    scan [string index [teststringobj get 1] 11] %c
+} -result 128
+
+
+unset count
+rename UniCharCaseCmpTest {}
 
 # cleanup
 ::tcltest::cleanupTests
index 2ac11bf..c8a081b 100644 (file)
@@ -7,8 +7,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -383,6 +383,10 @@ test util-5.50 {Tcl_StringMatch} {
 test util-5.51 {Tcl_StringMatch} {
     Wrapper_Tcl_StringMatch "" ""
 } 1
+test util-5.52 {Tcl_StringMatch} {
+    Wrapper_Tcl_StringMatch \[a\u0000 a\x80
+} 0
+
 
 test util-6.1 {Tcl_PrintDouble - using tcl_precision} -setup {
     set old_precision $::tcl_precision
@@ -468,7 +472,7 @@ test util-7.4 {TclPrecTraceProc - write traces, bogus values} -setup {
 } -result {1 {can't set "tcl_precision": improper value for precision} 12}
 
 # This test always succeeded in the C locale anyway...
-test util-8.1 {TclNeedSpace - correct UTF8 handling} {
+test util-8.1 {TclNeedSpace - correct utf-8 handling} {
     # Bug 411825
     # Note that this test relies on the fact that
     # [interp target] calls on Tcl_AppendElement()
@@ -482,7 +486,7 @@ test util-8.1 {TclNeedSpace - correct UTF8 handling} {
     interp delete \u5420
     set result
 } "\u5420 foo"
-test util-8.2 {TclNeedSpace - correct UTF8 handling} testdstring {
+test util-8.2 {TclNeedSpace - correct utf-8 handling} testdstring {
     # Bug 411825
     # This tests the same bug as the previous test, but
     # should be more future-proof, as the DString
@@ -492,14 +496,14 @@ test util-8.2 {TclNeedSpace - correct UTF8 handling} testdstring {
     testdstring element foo
     llength [testdstring get]
 } 2
-test util-8.3 {TclNeedSpace - correct UTF8 handling} testdstring {
+test util-8.3 {TclNeedSpace - correct utf-8 handling} testdstring {
     # Bug 411825 - new variant reported by Dossy Shiobara
     testdstring free
     testdstring append \u00A0 -1
     testdstring element foo
     llength [testdstring get]
 } 2
-test util-8.4 {TclNeedSpace - correct UTF8 handling} testdstring {
+test util-8.4 {TclNeedSpace - correct utf-8 handling} testdstring {
     # Another bug uncovered while fixing 411825
     testdstring free
     testdstring append {\ } -1
@@ -507,26 +511,65 @@ test util-8.4 {TclNeedSpace - correct UTF8 handling} testdstring {
     testdstring element foo
     llength [testdstring get]
 } 2
-test util-8.5 {TclNeedSpace - correct UTF8 handling} testdstring {
-    # Note that in this test TclNeedSpace actually gets it wrong,
-    # claiming we need a space when we really do not.  Extra space
-    # between list elements is harmless though, and better to have
-    # extra space in really weird string reps of lists, than to
-    # invest the effort required to make TclNeedSpace foolproof.
+test util-8.5 {TclNeedSpace - correct utf-8 handling} testdstring {
     testdstring free
     testdstring append {\\ } -1
     testdstring element foo
     list [llength [testdstring get]] [string length [testdstring get]]
-} {2 7}
-test util-8.6 {TclNeedSpace - correct UTF8 handling} testdstring {
-    # Another example of TclNeedSpace harmlessly getting it wrong.
+} {2 6}
+test util-8.6 {TclNeedSpace - correct utf-8 handling} testdstring {
     testdstring free
     testdstring append {\\ } -1
     testdstring append \{ -1
     testdstring element foo
     testdstring append \} -1
     list [llength [testdstring get]] [string length [testdstring get]]
-} {2 9}
+} {2 8}
+test util-8.7 {TclNeedSpace - watch out for escaped space} {
+    testdstring free
+    testdstring append {\ } -1
+    testdstring start
+    testdstring end
+
+    # Should make {\  {}}
+    list [llength [testdstring get]] [string index [testdstring get] 3]
+} {2 \{}
+test util-8.8 {TclNeedSpace - watch out for escaped space} {
+    testdstring free
+    testdstring append {\\ } -1
+    testdstring start
+    testdstring end
+
+    # Should make {\\ {}}
+    list [llength [testdstring get]] [string index [testdstring get] 3]
+} {2 \{}
+test util-8.9 {TclNeedSpace - watch out for escaped space} {
+    testdstring free
+    testdstring append {\\\ } -1
+    testdstring start
+    testdstring end
+
+    # Should make {\\\  {}}
+    list [llength [testdstring get]] [string index [testdstring get] 5]
+} {2 \{}
+test util-8.10 {TclNeedSpace - watch out for escaped space} {
+    testdstring free
+    testdstring append {\\\\\\\ } -1
+    testdstring start
+    testdstring end
+
+    # Should make {\\\\\\\  {}}
+    list [llength [testdstring get]] [string index [testdstring get] 9]
+} {2 \{}
+test util-8.11 {TclNeedSpace - watch out for escaped space} {
+    testdstring free
+    testdstring append {\\\\\\\\ } -1
+    testdstring start
+    testdstring end
+
+    # Should make {\\\\\\\\ {}}
+    list [llength [testdstring get]] [string index [testdstring get] 9]
+} {2 \{}
 
 test util-9.0.0 {TclGetIntForIndex} {
     string index abcd 0
index 32388a2..8bb55a2 100644 (file)
@@ -15,7 +15,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2.2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -53,7 +53,7 @@ catch {unset arr}
 test var-1.1 {TclLookupVar, Array handling} -setup {
     catch {unset a}
 } -body {
-    set x "incr"  ;# force no compilation and runtime call to Tcl_IncrCmd 
+    set x "incr"  ;# force no compilation and runtime call to Tcl_IncrCmd
     set i 10
     set arr(foo) 37
     list [$x i] $i [$x arr(foo)] $arr(foo)
@@ -256,7 +256,7 @@ test var-3.3 {MakeUpvar, my var has TCL_GLOBAL_ONLY specified} -setup {
     set a 123321
     proc p {} {
        # create global xx linked to global a
-       testupvar 1 a {} xx global 
+       testupvar 1 a {} xx global
     }
     list [p] $xx [set xx 789] $a
 } -result {{} 123321 789 789}
@@ -268,7 +268,7 @@ test var-3.4 {MakeUpvar, my var has TCL_NAMESPACE_ONLY specified} -setup {
        catch {unset ::test_ns_var::vv}
        proc p {} {
            # create namespace var vv linked to global a
-           testupvar 1 a {} vv namespace 
+           testupvar 1 a {} vv namespace
        }
        p
     }
@@ -451,7 +451,7 @@ test var-7.4 {Tcl_VariableObjCmd, list of vars} -setup {
         variable three 3 four 4
     }
     list [lsort [info vars test_ns_var::*]] \
-         [namespace eval test_ns_var {expr $three+$four}]
+         [namespace eval test_ns_var {expr {$three+$four}}]
 } -result [list [lsort {::test_ns_var::four ::test_ns_var::three ::test_ns_var::two ::test_ns_var::one}] 7]
 test var-7.5 {Tcl_VariableObjCmd, value for last var is optional} -setup {
     catch {unset a}
@@ -570,11 +570,11 @@ test var-7.14 {Tcl_VariableObjCmd, array element parameter} -body {
     namespace eval test_ns_var { variable arrayvar(1) }
 } -returnCodes error -result "can't define \"arrayvar(1)\": name refers to an element in an array"
 test var-7.15 {Tcl_VariableObjCmd, array element parameter} -body {
-    namespace eval test_ns_var { 
+    namespace eval test_ns_var {
        variable arrayvar
        set arrayvar(1) x
        variable arrayvar(1) y
-    }   
+    }
 } -returnCodes error -result "can't define \"arrayvar(1)\": name refers to an element in an array"
 test var-7.16 {Tcl_VariableObjCmd, no args (TIP 323)} {
     variable
@@ -828,7 +828,7 @@ test var-15.1 {segfault in [unset], [Bug 735335]} {
        set var $name
     }
     #
-    # Note that the variable name has to be 
+    # Note that the variable name has to be
     # unused previously for the segfault to
     # be triggered.
     #
@@ -1046,15 +1046,15 @@ test var-22.1 {leak in localVarName intrep: Bug 80304238ac} -setup {
        lindex [split [memory info] \n] 3 3
     }
     proc doit {} {
-       interp create slave
-       slave eval {
+       interp create child
+       child eval {
            proc doit script {
                eval $script
                set foo bar
            }
            doit {foreach foo baz {}}
        }
-       interp delete slave
+       interp delete child
     }
 } -constraints memory -body {
     set end [getbytes]
index ee17d0b..f5315fb 100644 (file)
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
 test while-old-1.1 {basic while loops} {
     set count 0
-    while {$count < 10} {set count [expr $count+1]}
+    while {$count < 10} {set count [expr {$count + 1}]}
     set count
 } 10
 test while-old-1.2 {basic while loops} {
@@ -58,9 +58,9 @@ test while-old-2.1 {continue in while loop} {
     set index 0
     set result {}
     while {$index < 5} {
-       if {$index == 2} {set index [expr $index+1]; continue}
+       if {$index == 2} {set index [expr {$index + 1}]; continue}
        set result [concat $result [lindex $list $index]]
-       set index [expr $index+1]
+       set index [expr {$index + 1}]
     }
     set result
 } {1 2 4 5}
@@ -72,7 +72,7 @@ test while-old-3.1 {break in while loop} {
     while {$index < 5} {
        if {$index == 3} break
        set result [concat $result [lindex $list $index]]
-       set index [expr $index+1]
+       set index [expr {$index + 1}]
     }
     set result
 } {1 2 3}
index 642ec93..b804aa5 100644 (file)
@@ -11,7 +11,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -77,7 +77,7 @@ test while-1.9 {TclCompileWhileCmd: simple command body} -body {
     set a {}
     set i 1
     while {$i<6} {
-       if $i==4 break
+       if {$i==4} break
        set a [concat $a $i]
         incr i
     }
@@ -112,8 +112,8 @@ test while-1.12 {TclCompileWhileCmd: long command body} -body {
     set a {}
     set i 1
     while {$i<6} {
-       if $i==4 break
-       if $i>5 continue
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -155,7 +155,7 @@ test while-1.13 {TclCompileWhileCmd: while command result} -body {
 } -result {}
 test while-1.14 {TclCompileWhileCmd: while command result} -body {
     set i 0
-    set a [while {$i < 5} {if $i==3 break; incr i}]
+    set a [while {$i < 5} {if {$i==3} break; incr i}]
     return $a
 } -cleanup {
     unset a i
@@ -207,9 +207,9 @@ test while-2.4 {continue tests, long command body} -body {
     set a {}
     set i 1
     while {$i<6} {
-       if $i==2 {incr i; continue}
-       if $i==4 break
-       if $i>5 continue
+       if {$i==2} {incr i; continue}
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -277,9 +277,9 @@ test while-3.3 {break tests, long command body} -body {
     set a {}
     set i 1
     while {$i<6} {
-       if $i==2 {incr i; continue}
-       if $i==5 break
-       if $i>5 continue
+       if {$i==2} {incr i; continue}
+       if {$i==5} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -295,7 +295,7 @@ test while-3.3 {break tests, long command body} -body {
            catch {incr i 5} msg
            catch {incr i -5} msg
        }
-       if $i==4 break
+       if {$i==4} break
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -401,7 +401,7 @@ test while-4.10 {while (not compiled): simple command body} -body {
     set i 1
     set z while
     $z {$i<6} {
-       if $i==4 break
+       if {$i==4} break
        set a [concat $a $i]
         incr i
     }
@@ -439,8 +439,8 @@ test while-4.13 {while (not compiled): long command body} -body {
     set z while
     set i 1
     $z {$i<6} {
-       if $i==4 break
-       if $i>5 continue
+       if {$i==4} break
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -484,7 +484,7 @@ test while-4.14 {while (not compiled): while command result} -body {
 test while-4.15 {while (not compiled): while command result} -body {
     set i 0
     set z while
-    set a [$z {$i < 5} {if $i==3 break; incr i}]
+    set a [$z {$i < 5} {if {$i==3} break; incr i}]
     return $a
 } -cleanup {
     unset a i z
@@ -538,9 +538,9 @@ test while-5.4 {break tests, long command body with computed command names} -bod
     set i 1
     set z break
     while {$i<6} {
-       if $i==2 {incr i; continue}
-       if $i==5 $z
-       if $i>5 continue
+       if {$i==2} {incr i; continue}
+       if {$i==5} $z
+       if {$i>5} continue
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -556,7 +556,7 @@ test while-5.4 {break tests, long command body with computed command names} -bod
            catch {incr i 5} msg
            catch {incr i -5} msg
        }
-       if $i==4 $z
+       if {$i==4} $z
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
@@ -637,9 +637,9 @@ test while-6.5 {continue tests, long command body with computed command names} -
     set i 1
     set z continue
     while {$i<6} {
-       if $i==2 {incr i; continue}
-       if $i==4 break
-       if $i>5 $z
+       if {$i==2} {incr i; continue}
+       if {$i==4} break
+       if {$i>5} $z
        if {$i>6 && $tcl_platform(machine)=="xxx"} {
            catch {set a $a} msg
            catch {incr i 5} msg
index fdde41c..9075ff3 100644 (file)
@@ -9,8 +9,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 412c476..9b5fd9e 100644 (file)
@@ -10,7 +10,7 @@
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2
+    package require tcltest 2.5
     #tcltest::configure -verbose {pass start}
     namespace import -force ::tcltest::*
 }
@@ -20,8 +20,8 @@ testConstraint dde 0
 if {[testConstraint win]} {
     if {![catch {
            ::tcltest::loadTestedCommands
-           set ::ddever [package require dde 1.4.2]
-           set ::ddelib [lindex [package ifneeded dde $::ddever] 1]}]} {
+           set ::ddever [package require dde 1.4.3]
+           set ::ddelib [info loaded "" Dde]}]} {
        testConstraint dde 1
     }
 }
@@ -38,12 +38,12 @@ proc createChildProcess {ddeServerName args} {
 
     set f [open $::scriptName w+]
     puts $f [list set ddeServerName $ddeServerName]
-    puts $f [list load $::ddelib dde]
+    puts $f [list load $::ddelib Dde]
     puts $f {
         # DDE child server -
         #
        if {"::tcltest" ni [namespace children]} {
-           package require tcltest
+           package require tcltest 2.5
            namespace import -force ::tcltest::*
        }
 
@@ -104,14 +104,14 @@ proc createChildProcess {ddeServerName args} {
 # -------------------------------------------------------------------------
 test winDde-1.0 {check if we are testing the right dll} {win dde} {
     set ::ddever
-} {1.4.2}
+} {1.4.3}
 
 test winDde-1.1 {Settings the server's topic name} -constraints dde -body {
     list [dde servername foobar] [dde servername] [dde servername self]
 } -result {foobar foobar self}
 
 test winDde-2.1 {Checking for other services} -constraints dde -body {
-    expr [llength [dde services {} {}]] >= 0
+    expr {[llength [dde services {} {}]] >= 0}
 } -result 1
 test winDde-2.2 {Checking for existence, with service and topic specified} \
        -constraints dde -body {
@@ -119,11 +119,11 @@ test winDde-2.2 {Checking for existence, with service and topic specified} \
 } -result 1
 test winDde-2.3 {Checking for existence, with only the service specified} \
        -constraints dde -body {
-    expr [llength [dde services TclEval {}]] >= 1
+    expr {[llength [dde services TclEval {}]] >= 1}
 } -result 1
 test winDde-2.4 {Checking for existence, with only the topic specified} \
        -constraints dde -body {
-    expr [llength [dde services {} self]] >= 1
+    expr {[llength [dde services {} self]] >= 1}
 } -result 1
 
 # -------------------------------------------------------------------------
@@ -154,8 +154,8 @@ test winDde-3.5 {DDE request locally} -constraints dde -body {
     dde request -binary TclEval self \xe1
 } -result "foo\x00"
 # Set variable a to A with diaeresis (unicode C4) by relying on the fact
-# that utf8 is sent (e.g. "c3 84" on the wire)
-test winDde-3.6 {DDE request utf8} -constraints dde -body {
+# that utf-8 is sent (e.g. "c3 84" on the wire)
+test winDde-3.6 {DDE request utf-8} -constraints dde -body {
     set \xe1 "not set"
     dde execute TclEval self "set \xe1 \xc4"
     scan [set \xe1] %c
@@ -279,19 +279,19 @@ test winDde-6.6 {DDE remote servername collision force} -constraints {dde stdio}
 
 # -------------------------------------------------------------------------
 
-test winDde-7.1 {Load DDE in slave interpreter} -constraints dde -setup {
-    interp create slave
+test winDde-7.1 {Load DDE in child interpreter} -constraints dde -setup {
+    interp create child
 } -body {
-    slave eval [list load $::ddelib Dde]
-    slave eval [list dde servername -- dde-interp-7.1]
+    child eval [list load $::ddelib Dde]
+    child eval [list dde servername -- dde-interp-7.1]
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {dde-interp-7.1}
-test winDde-7.2 {DDE slave cleanup} -constraints dde -setup {
-    interp create slave
-    slave eval [list load $::ddelib Dde]
-    slave eval [list dde servername -- dde-interp-7.5]
-    interp delete slave
+test winDde-7.2 {DDE child cleanup} -constraints dde -setup {
+    interp create child
+    child eval [list load $::ddelib Dde]
+    child eval [list dde servername -- dde-interp-7.5]
+    interp delete child
 } -body {
     dde services TclEval {}
     set s [dde services TclEval {}]
@@ -300,128 +300,128 @@ test winDde-7.2 {DDE slave cleanup} -constraints dde -setup {
        set s
     }
 } -result {}
-test winDde-7.3 {DDE present in slave interp} -constraints dde -setup {
-    interp create slave
-    slave eval [list load $::ddelib Dde]
-    slave eval [list dde servername -- dde-interp-7.3]
+test winDde-7.3 {DDE present in child interp} -constraints dde -setup {
+    interp create child
+    child eval [list load $::ddelib Dde]
+    child eval [list dde servername -- dde-interp-7.3]
 } -body {
     dde services TclEval dde-interp-7.3
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {{TclEval dde-interp-7.3}}
 test winDde-7.4 {interp name collision with -force} -constraints dde -setup {
-    interp create slave
-    slave eval [list load $::ddelib Dde]
-    slave eval [list dde servername -- dde-interp-7.4]
+    interp create child
+    child eval [list load $::ddelib Dde]
+    child eval [list dde servername -- dde-interp-7.4]
 } -body {
     dde servername -force -- dde-interp-7.4
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result {dde-interp-7.4}
 test winDde-7.5 {interp name collision without -force} -constraints dde -setup {
-    interp create slave
-    slave eval [list load $::ddelib Dde]
-    slave eval [list dde servername -- dde-interp-7.5]
+    interp create child
+    child eval [list load $::ddelib Dde]
+    child eval [list dde servername -- dde-interp-7.5]
 } -body {
     dde servername -- dde-interp-7.5
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -result "dde-interp-7.5 #2"
 
 # -------------------------------------------------------------------------
 
 test winDde-8.1 {Safe DDE load} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
 } -body {
-    slave eval dde servername slave
+    child eval dde servername child
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -result {invalid command name "dde"}
 test winDde-8.2 {Safe DDE set servername} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
 } -body {
-    slave invokehidden dde servername slave
-} -cleanup {interp delete slave} -result {slave}
+    child invokehidden dde servername child
+} -cleanup {interp delete child} -result {child}
 test winDde-8.3 {Safe DDE check handler required for eval} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave invokehidden dde servername slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child invokehidden dde servername child
 } -body {
-    catch {dde eval slave set a 1} msg
-} -cleanup {interp delete slave} -result {1}
+    catch {dde eval child set a 1} msg
+} -cleanup {interp delete child} -result {1}
 test winDde-8.4 {Safe DDE check that execute is denied} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave invokehidden dde servername slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child invokehidden dde servername child
 } -body {
-    slave eval set a 1
-    dde execute TclEval slave {set a 2}
-    slave eval set a
-} -cleanup {interp delete slave} -result 1
+    child eval set a 1
+    dde execute TclEval child {set a 2}
+    child eval set a
+} -cleanup {interp delete child} -result 1
 test winDde-8.5 {Safe DDE check that request is denied} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave invokehidden dde servername slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child invokehidden dde servername child
 } -body {
-    slave eval set a 1
-    dde request TclEval slave a
+    child eval set a 1
+    dde request TclEval child a
 } -cleanup {
-    interp delete slave
+    interp delete child
 } -returnCodes error -result {remote server cannot handle this command}
 test winDde-8.6 {Safe DDE assign handler procedure} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
 } -body {
-    slave invokehidden dde servername -handler DDEACCEPT slave
-} -cleanup {interp delete slave} -result slave
+    child invokehidden dde servername -handler DDEACCEPT child
+} -cleanup {interp delete child} -result child
 test winDde-8.7 {Safe DDE check simple command} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
-    slave invokehidden dde servername -handler DDEACCEPT slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
+    child invokehidden dde servername -handler DDEACCEPT child
 } -body {
-    dde eval slave set x 1
-} -cleanup {interp delete slave} -result {set x 1}
+    dde eval child set x 1
+} -cleanup {interp delete child} -result {set x 1}
 test winDde-8.8 {Safe DDE check non-list command} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
-    slave invokehidden dde servername -handler DDEACCEPT slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD $cmd}}
+    child invokehidden dde servername -handler DDEACCEPT child
 } -body {
     set s "c:\\Program Files\\Microsoft Visual Studio\\"
-    dde eval slave $s
-    string equal [slave eval set DDECMD] $s
-} -cleanup {interp delete slave} -result 1
+    dde eval child $s
+    string equal [child eval set DDECMD] $s
+} -cleanup {interp delete child} -result 1
 test winDde-8.9 {Safe DDE check command evaluation} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
-    slave invokehidden dde servername -handler DDEACCEPT slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
+    child invokehidden dde servername -handler DDEACCEPT child
 } -body {
-    dde eval slave set \xe1 1
-    slave eval set \xe1
-} -cleanup {interp delete slave} -result 1
+    dde eval child set \xe1 1
+    child eval set \xe1
+} -cleanup {interp delete child} -result 1
 test winDde-8.10 {Safe DDE check command evaluation (2)} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
-    slave invokehidden dde servername -handler DDEACCEPT slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
+    child invokehidden dde servername -handler DDEACCEPT child
 } -body {
-    dde eval slave [list set x 1]
-    slave eval set x
-} -cleanup {interp delete slave} -result 1
+    dde eval child [list set x 1]
+    child eval set x
+} -cleanup {interp delete child} -result 1
 test winDde-8.11 {Safe DDE check command evaluation (3)} -constraints dde -setup {
-    interp create -safe slave
-    slave invokehidden load $::ddelib Dde
-    slave eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
-    slave invokehidden dde servername -handler DDEACCEPT slave
+    interp create -safe child
+    child invokehidden load $::ddelib Dde
+    child eval {proc DDEACCEPT {cmd} {set ::DDECMD [uplevel \#0 $cmd]}}
+    child invokehidden dde servername -handler DDEACCEPT child
 } -body {
-    dde eval slave [list [list set x 1]]
-    slave eval set x
-} -cleanup {interp delete slave} -returnCodes error -result {invalid command name "set x 1"}
+    dde eval child [list [list set x 1]]
+    child eval set x
+} -cleanup {interp delete child} -returnCodes error -result {invalid command name "set x 1"}
 
 # -------------------------------------------------------------------------
 
@@ -481,7 +481,7 @@ test winDde-9.4 {External safe DDE check null data passing} -constraints {dde st
 # -------------------------------------------------------------------------
 
 #cleanup
-#catch {interp delete $slave};           # ensure we clean up the slave.
+#catch {interp delete $child};           # ensure we clean up the child.
 file delete -force $::scriptName
 ::tcltest::cleanupTests
 return
index 2ce4916..500b114 100644 (file)
@@ -5,13 +5,13 @@
 # generates output for errors.  No output means no errors were found.
 #
 # Copyright (c) 1996-1997 Sun Microsystems, Inc.
-# Copyright (c) 1998-1999 by Scriptics Corporation.
+# Copyright (c) 1998-1999 Scriptics Corporation.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -29,7 +29,9 @@ testConstraint testchmod      [llength [info commands testchmod]]
 testConstraint cdrom 0
 testConstraint exdev 0
 testConstraint longFileNames 0
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+# Some things fail under all Continuous Integration systems for subtle reasons
+# such as CI often running with elevated privileges in a container.
+testConstraint notInCIenv     [expr {![info exists ::env(CI)]}]
 
 proc createfile {file {string a}} {
     set f [open $file w]
@@ -401,7 +403,7 @@ proc MakeFiles {dirname} {
         set f [open $filename w]
         close $f
         file stat $filename stat
-        if {[set n [lsearch -exact -integer $inodes $stat(ino)]] != -1} {
+        if {[set n [lsearch -exact -integer $inodes $stat(ino)]] >= 0} {
             return [list [file join $dirname Test$n] $filename]
         }
         lappend inodes $stat(ino)
@@ -411,7 +413,7 @@ proc MakeFiles {dirname} {
 
 test winFCmd-1.38 {TclpRenameFile: check rename of conflicting inodes} -setup {
     cleanup
-} -constraints {win winNonZeroInodes knownMsvcBug} -body {
+} -constraints {win winNonZeroInodes notInCIenv} -body {
     file mkdir td1
     foreach {a b} [MakeFiles td1] break
     file rename -force $a $b
@@ -661,7 +663,7 @@ test winFCmd-5.1 {TclpCopyDirectory: calls TraverseWinTree} -setup {
 
 test winFCmd-6.1 {TclpRemoveDirectory: errno: EACCES} -setup {
     cleanup
-} -constraints {winVista testfile testchmod knownMsvcBug} -body {
+} -constraints {winVista testfile testchmod notInCIenv} -body {
     file mkdir td1
     testchmod 0 td1
     testfile rmdir td1
@@ -715,7 +717,7 @@ test winFCmd-6.8 {TclpRemoveDirectory: RemoveDirectory fails} -setup {
 } -result {1 {tf1 ENOTDIR}}
 test winFCmd-6.9 {TclpRemoveDirectory: errno == EACCES} -setup {
     cleanup
-} -constraints {winVista testfile testchmod knownMsvcBug} -body {
+} -constraints {winVista testfile testchmod notInCIenv} -body {
     file mkdir td1
     testchmod 0 td1
     testfile rmdir td1
@@ -733,7 +735,7 @@ test winFCmd-6.11 {TclpRemoveDirectory: attr == -1} -setup {
 } -returnCodes error -match regexp -result {^/ E(ACCES|EXIST)$}
 test winFCmd-6.13 {TclpRemoveDirectory: write-protected} -setup {
     cleanup
-} -constraints {winVista testfile testchmod knownMsvcBug} -body {
+} -constraints {winVista testfile testchmod notInCIenv} -body {
     file mkdir td1
     testchmod 0 td1
     testfile rmdir td1
@@ -962,7 +964,7 @@ test winFCmd-9.1 {TraversalDelete: DOTREE_F} -setup {
 } -result {}
 test winFCmd-9.3 {TraversalDelete: DOTREE_PRED} -setup {
     cleanup
-} -constraints {winVista testfile testchmod knownMsvcBug} -body {
+} -constraints {winVista testfile testchmod notInCIenv} -body {
     file mkdir td1/td2
     testchmod 0 td1
     testfile rmdir -force td1
@@ -1381,7 +1383,7 @@ test winFCmd-19.3 {Windows extended path names} -constraints nt -setup {
 } -cleanup {
     catch {file delete $tmpfile}
 } -result [list 0 {}]
-test winFCmd-19.4 {Windows extended path names} -constraints nt -setup {
+test winFCmd-19.4 {Windows extended path names} -constraints {win nt} -setup {
     set tmpfile [file join $::env(TEMP) tcl[string repeat x 20].tmp]
     set tmpfile //?/[file normalize $tmpfile]
 } -body {
@@ -1403,7 +1405,7 @@ test winFCmd-19.5 {Windows extended path names} -constraints nt -setup {
 } -cleanup {
     catch {file delete $tmpfile}
 } -result [list 0 {}]
-test winFCmd-19.6 {Windows extended path names} -constraints nt -setup {
+test winFCmd-19.6 {Windows extended path names} -constraints {win nt} -setup {
     set tmpfile [file join $::env(TEMP) tcl[string repeat x 248].tmp]
     set tmpfile //?/[file normalize $tmpfile]
 } -body {
@@ -1414,7 +1416,7 @@ test winFCmd-19.6 {Windows extended path names} -constraints nt -setup {
 } -cleanup {
     catch {file delete $tmpfile}
 } -result [list 0 {}]
-test winFCmd-19.7 {Windows extended path names} -constraints nt -setup {
+test winFCmd-19.7 {Windows extended path names} -constraints {win nt} -setup {
     set tmpfile [file join $::env(TEMP) "tcl[pid].tmp "]
     set tmpfile [file normalize $tmpfile]
 } -body {
@@ -1425,7 +1427,7 @@ test winFCmd-19.7 {Windows extended path names} -constraints nt -setup {
 } -cleanup {
     catch {file delete $tmpfile}
 } -result [list 0 {} [list tcl[pid].tmp]]
-test winFCmd-19.8 {Windows extended path names} -constraints nt -setup {
+test winFCmd-19.8 {Windows extended path names} -constraints {win nt} -setup {
     set tmpfile [file join $::env(TEMP) "tcl[pid].tmp "]
     set tmpfile //?/[file normalize $tmpfile]
 } -body {
@@ -1437,7 +1439,7 @@ test winFCmd-19.8 {Windows extended path names} -constraints nt -setup {
     catch {file delete $tmpfile}
 } -result [list 0 {} [list "tcl[pid].tmp "]]
 
-test winFCmd-19.9 {Windows devices path names} -constraints nt -body {
+test winFCmd-19.9 {Windows devices path names} -constraints {win nt} -body {
     file normalize //./com1
 } -result //./com1
 
index eb6addd..3737d9f 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[catch {package require tcltest 2.0.2}]} {
-    puts stderr "Skipping tests in [info script]. tcltest 2.0.2 required."
+if {[catch {package require tcltest 2.5}]} {
+    puts stderr "Skipping tests in [info script]. tcltest 2.5 required."
     return
 }
 namespace import -force ::tcltest::*
index 3e9aa29..0433b4a 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
index 06bd67e..d3a580c 100644 (file)
@@ -12,7 +12,7 @@
 # See the file "license.terms" for information on usage and redistribution of
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-package require tcltest
+package require tcltest 2.5
 namespace import -force ::tcltest::*
 unset -nocomplain path
 
index dbaa14c..68be966 100644 (file)
@@ -10,8 +10,8 @@
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
-if {[lsearch [namespace children] ::tcltest] == -1} {
-    package require tcltest
+if {"::tcltest" ni [namespace children]} {
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -19,7 +19,9 @@ if {[lsearch [namespace children] ::tcltest] == -1} {
 catch [list package require -exact Tcltest [info patchlevel]]
 
 testConstraint testwinclock [llength [info commands testwinclock]]
-testConstraint knownMsvcBug [expr {![info exists ::env(TRAVIS_OS_NAME)] || ![string match windows $::env(TRAVIS_OS_NAME)]}]
+# Some things fail under all Continuous Integration systems for subtle reasons
+# such as CI often running with elevated privileges in a container.
+testConstraint notInCIenv   [expr {![info exists ::env(CI)]}]
 
 # The next two tests will crash on Windows if the check for negative
 # clock values is not done properly.
@@ -41,7 +43,7 @@ test winTime-1.2 {TclpGetDate} {win} {
 # with the Windows clock.  30 sec really isn't enough,
 # but how much time does a tester have patience for?
 
-test winTime-2.1 {Synchronization of Tcl and Windows clocks} {testwinclock knownMsvcBug} {
+test winTime-2.1 {Synchronization of Tcl and Windows clocks} {testwinclock notInCIenv} {
     # May fail due to OS/hardware discrepancies.  See:
     # http://support.microsoft.com/default.aspx?scid=kb;en-us;274323
     set failed {}
index c2f7825..7ddf1d7 100644 (file)
@@ -11,7 +11,7 @@
 # this file, and for a DISCLAIMER OF ALL WARRANTIES.
 
 if {"::tcltest" ni [namespace children]} {
-    package require tcltest 2.1
+    package require tcltest 2.5
     namespace import -force ::tcltest::*
 }
 
@@ -140,7 +140,7 @@ test zlib-7.7 {zlib stream: Bug 25842c161} -constraints zlib -body {
 } -result ""
 # Also causes Tk Bug 10f2e7872b
 test zlib-7.8 {zlib stream: Bug b26e38a3e4} -constraints zlib -setup {
-    expr srand(12345)
+    expr {srand(12345)}
     set randdata {}
     for {set i 0} {$i<6001} {incr i} {
        append randdata [binary format c [expr {int(256*rand())}]]
@@ -451,7 +451,7 @@ test zlib-8.16 {Bug 3603553: buffer transfer with large writes} -setup {
     # Actual data isn't very important; needs to be substantially larger than
     # the internal buffer (32kB) and incompressible.
     set largeData {}
-    for {set i 0;expr srand(1)} {$i < 100000} {incr i} {
+    for {set i 0;expr {srand(1)}} {$i < 100000} {incr i} {
        append largeData [lindex "a b c d e f g h i j k l m n o p" \
                [expr {int(16*rand())}]]
     }
@@ -920,7 +920,7 @@ test zlib-10.2 "bug #2818131 (mismatch gets)" -constraints {
     rename zlibRead {}
 } -result {error {invalid block type}}
 
-test zlib-11.1 "Bug #3390073: mis-appled gzip filtering" -setup {
+test zlib-11.1 "Bug #3390073: mis-applied gzip filtering" -setup {
     set file [makeFile {} test.input]
 } -constraints zlib -body {
     set f [open $file wb]
@@ -934,7 +934,7 @@ test zlib-11.1 "Bug #3390073: mis-appled gzip filtering" -setup {
 } -cleanup {
     removeFile $file
 } -result {1000 0}
-test zlib-11.2 "Bug #3390073: mis-appled gzip filtering" -setup {
+test zlib-11.2 "Bug #3390073: mis-applied gzip filtering" -setup {
     set file [makeFile {} test.input]
 } -constraints zlib -body {
     set f [open $file wb]
@@ -1005,6 +1005,86 @@ test zlib-12.2 {Patrick Dunnigan's issue} -constraints zlib -setup {
     removeFile $filesrc
     removeFile $filedst
 } -result 56
+
+set zlibbinf ""
+proc _zlibbinf {} {
+  # inlined zlib.bin file creator:
+  variable zlibbinf
+  if {$zlibbinf eq ""} {
+    set zlibbinf [makeFile {} test-zlib-13.bin]
+    set f [open $zlibbinf wb]
+    puts -nonewline $f [zlib decompress [binary decode base64 {
+      eJx7e+6s1+EAgYaLjK3ratptGmOck0vT/y/ZujHAd0qJelDBXfUPJ3tfrtLbpX+wOOFHmtn03/tizm
+      /+tXROXU3d203b79p5X6/0cvUyFzTsqOj4sa9r8SrZI5zT7265e2Xzq595Fb9LbpgffVy7cZaJ/d15
+      4U9L7LLM2vdqut8+aSU/r6q9Ltv6+T9mBhTgIK97bH33m/O1C1eBwf9FDKNgaIDaj9wA+5hToA==
+    }]]
+    close $f
+  }
+  return $zlibbinf
+}
+test zlib-13.1 {Ticket [8af92dfb66] - zlib stream mis-expansion} -constraints zlib -setup {
+    set pathin  [_zlibbinf]
+    set chanin  [open $pathin rb]
+    set pathout [makeFile {} test-zlib-13.deflated]
+    set chanout [open $pathout wb]
+    zlib push inflate $chanin
+    fcopy $chanin $chanout
+    close $chanin
+    close $chanout
+} -body {
+    file size $pathout
+} -cleanup {
+    removeFile $pathout
+    unset chanin pathin chanout pathout
+} -result 458752
+
+test zlib-13.2 {Ticket [f70ce1fead] - zlib multi-stream expansion} -constraints zlib -setup {
+    # Start from the basic asset
+    set pathin  [_zlibbinf]
+    set chanin  [open $pathin rb]
+    # Create a multi-stream by copying the asset twice into it.
+    set pathout [makeFile {} test-zlib-13.multi]
+    set chanout [open $pathout wb]
+    fcopy $chanin $chanout
+    seek  $chanin 0 start
+    fcopy $chanin $chanout
+    close $chanin
+    close $chanout
+    # The multi-stream file shall be our input
+    set pathin $pathout
+    set chanin [open $pathin rb]
+    # And our destinations
+    set pathout1 [makeFile {} test-zlib-13.multi-1]
+    set pathout2 [makeFile {} test-zlib-13.multi-2]
+} -body {
+    # Decode first stream
+    set chanout [open $pathout1 wb]
+    zlib push inflate $chanin
+    fcopy $chanin $chanout
+    chan pop $chanin
+    close $chanout
+    # Decode second stream
+    set chanout [open $pathout2 wb]
+    zlib push inflate $chanin
+    fcopy $chanin $chanout
+    chan pop $chanin
+    close $chanout
+    #
+    list [file size $pathout1] [file size $pathout2]
+} -cleanup {
+    close $chanin
+    removeFile $pathout
+    removeFile $pathout1
+    removeFile $pathout2
+    unset chanin pathin chanout pathout pathout1 pathout2
+} -result {458752 458752}
+
+if {$zlibbinf ne ""} {
+   removeFile $zlibbinf
+}
+unset zlibbinf
+rename _zlibbinf {}
+
 \f
 ::tcltest::cleanupTests
 return
old mode 100755 (executable)
new mode 100644 (file)
index 6d147ac..a3aa309
@@ -3,7 +3,7 @@
 # This script attempts to determine what APIs exist in the source base that
 # have not been documented.  By grepping through all of the doc/*.3 man
 # pages, looking for "Pkg_*" (e.g., Tcl_ or Tk_), and comparing this list
-# against the list of Pkg_ APIs found in the source (e.g., tcl8.2/*/*.[ch])
+# against the list of Pkg_ APIs found in the source (e.g., tcl8.6/*/*.[ch])
 # we create six lists:
 #      1) APIs in Source not in Docs.
 #      2) APIs in Docs not in Source.
@@ -16,7 +16,7 @@
 # non-standard code, this script will produce erroneous results.  Each
 # list should be carefully checked for accuracy.
 #
-# Copyright (c) 1998-1999 by Scriptics Corporation.
+# Copyright (c) 1998-1999 Scriptics Corporation.
 # All rights reserved.
 
 
@@ -69,6 +69,7 @@ set StructList {
     Tk_GeomMgr \
     Tk_Image \
     Tk_ImageMaster \
+    Tk_ImageModel \
     Tk_ImageType \
     Tk_Item \
     Tk_ItemType \
@@ -106,7 +107,6 @@ proc main {} {
     if {($len != 2) && ($len != 3)} {
        puts "usage: $argv0 pkgName pkgDir \[outFile\]"
        puts "   pkgName == Tcl,Tk"
-       puts "   pkgDir  == /home/surles/cvs/tcl8.2"
        exit 1
     }
 
index 04bf857..8e92400 100755 (executable)
@@ -3,7 +3,7 @@
 #      Changes to 'tommath.h' to make it conform with Tcl's linking
 #      conventions.
 #
-# Copyright (c) 2005 by Kevin B. Kenny.  All rights reserved.
+# Copyright (c) 2005 Kevin B. Kenny.  All rights reserved.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 83ee6c7..bc0d700 100644 (file)
@@ -4,7 +4,7 @@
 #      interface.
 #
 #
-# Copyright (c) 1998-1999 by Scriptics Corporation.
+# Copyright (c) 1998-1999 Scriptics Corporation.
 # Copyright (c) 2007 Daniel A. Steffen <das@users.sourceforge.net>
 #
 # See the file "license.terms" for information on usage and redistribution
@@ -479,11 +479,15 @@ proc genStubs::makeDecl {name decl index} {
     if {[info exists stubs($name,deprecated,$index)]} {
        append text "[string toupper $libraryName]_DEPRECATED(\"$stubs($name,deprecated,$index)\")\n"
        set line "$rtype"
+    } elseif {[string range $rtype end-5 end] eq "MP_WUR"} {
+       set line "$scspec [string trim [string range $rtype 0 end-6]]"
     } else {
        set line "$scspec $rtype"
     }
     set count [expr {2 - ([string length $line] / 8)}]
-    append line [string range "\t\t\t" 0 $count]
+    if {$count >= 0} {
+       append line [string range "\t\t\t" 0 $count]
+    }
     set pad [expr {24 - [string length $line]}]
     if {$pad <= 0} {
        append line " "
@@ -548,6 +552,9 @@ proc genStubs::makeDecl {name decl index} {
            append line ")"
        }
     }
+    if {[string range $rtype end-5 end] eq "MP_WUR"} {
+       append line " MP_WUR"
+    }
     return "$text$line;\n"
 }
 
@@ -611,6 +618,8 @@ proc genStubs::makeSlot {name decl index} {
        append text [string trim [string range $rtype 0 end-9]] " (__stdcall *" $lfname ") "
     } elseif {[string range $rtype 0 11] eq "TCL_NORETURN"} {
        append text "TCL_NORETURN1 " [string trim [string range $rtype 12 end]] " (*" $lfname ") "
+    } elseif {[string range $rtype end-5 end] eq "MP_WUR"} {
+       append text [string trim [string range $rtype 0 end-6]] " (*" $lfname ") "
     } else {
        append text $rtype " (*" $lfname ") "
     }
@@ -648,6 +657,9 @@ proc genStubs::makeSlot {name decl index} {
        }
     }
 
+    if {[string range $rtype end-5 end] eq "MP_WUR"} {
+       append text " MP_WUR"
+    }
     append text "; /* $index */\n"
     return $text
 }
index 71329c2..0e645c4 100644 (file)
@@ -4,7 +4,7 @@
 # the man page conversion.  It is used to extract information used to
 # generate a table of contents and a keyword list.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
index 4b43f1e..4a3b1ee 100644 (file)
@@ -12,7 +12,7 @@ exec tclsh "$0" ${1+"$@"}
 #
 #----------------------------------------------------------------------
 #
-# Copyright (c) 2004 by Kevin B. Kenny.  All rights reserved.
+# Copyright (c) 2004 Kevin B. Kenny.  All rights reserved.
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 #----------------------------------------------------------------------
@@ -32,7 +32,7 @@ proc copyDir {d1 d2} {
        } elseif {[file isfile $f]} {
            file copy -force $f [file join $d2 $ftail]
            if {$::tcl_platform(platform) eq {unix}} {
-               file attributes [file join $d2 $ftail] -permissions 0644
+               file attributes [file join $d2 $ftail] -permissions 0o644
            } else {
                file attributes [file join $d2 $ftail] -readonly 1
            }
@@ -40,7 +40,7 @@ proc copyDir {d1 d2} {
     }
 
     if {$::tcl_platform(platform) eq {unix}} {
-       file attributes $d2 -permissions 0755
+       file attributes $d2 -permissions 0o755
     } else {
        file attributes $d2 -readonly 1
     }
index 31f1e54..204783a 100755 (executable)
@@ -22,7 +22,7 @@
 #
 #----------------------------------------------------------------------
 #
-# Copyright (c) 2004 by Kevin B. Kenny.  All rights reserved.
+# Copyright (c) 2004 Kevin B. Kenny.  All rights reserved.
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 #----------------------------------------------------------------------
@@ -588,7 +588,7 @@ proc backslashify { string } {
     set retval {}
     foreach char [split $string {}] {
        scan $char %c ccode
-       if { $ccode >= 0x0020 && $ccode < 0x007f && $char ne "\""
+       if { $ccode >= 0x20 && $ccode < 0x7F && $char ne "\""
             && $char ne "\{" && $char ne "\}" && $char ne "\["
             && $char ne "\]" && $char ne "\\" && $char ne "\$" } {
            append retval $char
index 6cc033b..70213e0 100755 (executable)
@@ -592,7 +592,7 @@ proc testcases5 { f2 } {
        foreach { t offset isdst tzname } $row break
        if { $t > -4000000000000 } {
            set conds [list detroit]
-           if { $t > wide(0x7fffffff) } {
+           if { $t > wide(0x7FFFFFFF) } {
                set conds [list detroit y2038]
            }
            incr t -1
index ca29226..4a928d8 100644 (file)
@@ -4,7 +4,7 @@
 # man2tcl program to generate a Windows help file from Tcl manual
 # entries.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 
 #
 # PASS 1
index 4f3b7e5..655e55b 100644 (file)
@@ -4,7 +4,7 @@
 # the man page conversion.  It converts the man format input to rtf
 # form suitable for use by the Windows help compiler.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 #
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
@@ -157,7 +157,7 @@ proc text {string} {
            "\t"        {\tab } \
            ''          "\\rdblquote " \
            ``          "\\ldblquote " \
-           "\u00b7"    "\\bullet " \
+           "\xB7"      "\\bullet " \
            ] $string]
 
     # Check if this is the beginning of an international character string.
@@ -824,7 +824,7 @@ proc IPmacro {argList} {
        set indent 5
     }
     if {$text == {\(bu}} {
-       set text "\u00b7"
+       set text "\xB7"
     }
 
     set tab [expr {$indent * 0.1}]i
index 2d03ab6..28a6751 100644 (file)
@@ -7,7 +7,7 @@ exec tclsh "$0" ${1+"$@"}
 # This file contains procedures that work in conjunction with the
 # man2tcl program to generate a HTML files from Tcl manual entries.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 
 
 # sarray -
index 64982ff..7a789f7 100644 (file)
@@ -3,7 +3,7 @@
 # This file defines procedures that are used during the first pass of the
 # man page to html conversion process. It is sourced by h.tcl.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 
 # Global variables used by these scripts:
 #
index 8483204..19d6ce0 100644 (file)
@@ -4,7 +4,7 @@
 # This file defines procedures that are used during the second pass of the man
 # page to html conversion process. It is sourced by man2html.tcl.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 
 # Global variables used by these scripts:
 #
index ecb2206..b1ad076 100644 (file)
@@ -88,7 +88,7 @@ proc readDepends {chan} {
     set line ""
     array set depends {}
 
-    while {[gets $chan line] != -1} {
+    while {[gets $chan line] >= 0} {
         if {[regexp {^#line [0-9]+ \"(.*)\"$} $line dummy fname] != 0} {
            set fname [file normalize $fname]
             if {![info exists target]} {
@@ -98,7 +98,7 @@ proc readDepends {chan} {
             } else {
                # don't include ourselves as a dependency of ourself.
                if {![string compare $fname $target]} {continue}
-               # store in an array so multiple occurances are not counted.
+               # store in an array so multiple occurrences are not counted.
                 set depends($target|$fname) ""
             }
         }
index 8379159..a94d90f 100644 (file)
@@ -4,7 +4,7 @@
 # spencer2regexp.tcl, which are programs written to convert Henry
 # Spencer's test suite to tcl test files.
 #
-# Copyright (c) 1996 by Sun Microsystems, Inc.
+# Copyright (c) 1996 Sun Microsystems, Inc.
 
 proc readInputFile {} {
     global inFileName
index 85c9ba9..52b86ea 100755 (executable)
@@ -25,7 +25,7 @@
 #
 #----------------------------------------------------------------------
 #
-# Copyright (c) 2004 by Kevin B. Kenny.         All rights reserved.
+# Copyright (c) 2004 Kevin B. Kenny.    All rights reserved.
 # See the file "license.terms" for information on usage and redistribution
 # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 #----------------------------------------------------------------------
@@ -36,7 +36,7 @@
 set olsonFiles {
     africa antarctica asia australasia
     backward etcetera europe northamerica
-    pacificnew southamerica systemv
+    southamerica
 }
 
 # Define the year at which the DST information will stop.
index 65d81de..34222e3 100644 (file)
@@ -50,7 +50,7 @@ proc indexfile {} {
 proc copyright {copyright {level {}}} {
     # We don't actually generate a separate copyright page anymore
     #set page "${level}copyright.htm"
-    #return "<A HREF=\"$page\">Copyright</A> &#169; [htmlize-text [lrange $copyright 2 end]]"
+    #return "<A HREF=\"$page\">Copyright</A> &copy; [htmlize-text [lrange $copyright 2 end]]"
     # obfuscate any email addresses that may appear in name
     set who [string map {@ (at)} [lrange $copyright 2 end]]
     return "Copyright &copy; [htmlize-text $who]"
@@ -130,8 +130,8 @@ proc htmlize-text {text {charmap {}}} {
        \"      {&quot;} \
        {<}     {&lt;} \
        {>}     {&gt;} \
-       \u201c "&#8220;" \
-       \u201d "&#8221;"
+       \u201c "&ldquo;" \
+       \u201d "&rdquo;"
 
     return [string map $charmap $text]
 }
@@ -144,20 +144,73 @@ proc process-text {text} {
            {\&}        "\t" \
            {\%}        {} \
            "\\\n"      "\n" \
-           {\(+-}      "&#177;" \
+           {\(r!}      "&iexcl;" \
+           {\(ct}      "&cent;" \
+           {\(Po}      "&pound;" \
+           {\(Cs}      "&curren;" \
+           {\(Ye}      "&yen;" \
+           {\(bb}      "&brvbar;" \
+           {\(sc}      "&sect;" \
+           {\(ad}      "&die;" \
            {\(co}      "&copy;" \
-           {\(em}      "&#8212;" \
-           {\(en}      "&#8211;" \
-           {\(fm}      "&#8242;" \
-           {\(mc}      "&#181;" \
-           {\(mu}      "&#215;" \
-           {\(mi}      "&#8722;" \
-           {\(->}      "<font size=\"+1\">&#8594;</font>" \
+           {\(Of}      "&ordf;" \
+           {\(Fo}      "&laquo;" \
+           {\(no}      "&not;" \
+           {\(rg}      "&reg;" \
+           {\(a-}      "&macr;" \
+           {\(de}      "&deg;" \
+           {\(+-}      "&plusmn;" \
+           {\(S2}      "&sup2;" \
+           {\(S3}      "&sup3;" \
+           {\(aa}      "&acute;" \
+           {\(mc}      "&micro;" \
+           {\(ps}      "&para;" \
+           {\(pc}      "&middot;" \
+           {\(ac}      "&cedil;" \
+           {\(S1}      "&sup1;" \
+           {\(Om}      "&ordm;" \
+           {\(Fc}      "&raquo;" \
+           {\(14}      "&frac14;" \
+           {\(12}      "&frac12;" \
+           {\(34}      "&frac34;" \
+           {\(r?}      "&iquest;" \
+           {\(AE}      "&AElig;" \
+           {\(-D}      "&ETH;" \
+           {\(mu}      "&times;" \
+           {\(TP}      "&THORN;" \
+           {\(ss}      "&szlig;" \
+           {\(ae}      "&aelig;" \
+           {\(Sd}      "&eth;" \
+           {\(di}      "&divide;" \
+           {\(Tp}      "&thorn;" \
+           {\(em}      "&mdash;" \
+           {\(en}      "&ndash;" \
+           {\(fm}      "&prime;" \
+           {\(mi}      "&minus;" \
+           {\(.i}      "&imath;" \
+           {\(.j}      "&jmath;" \
+           {\(Fn}      "&fnof;" \
+           {\(OE}      "&OElig;" \
+           {\(oe}      "&oelig;" \
+           {\(IJ}      "&IJlig;" \
+           {\(ij}      "&ijlig;" \
+           {\(<-}      "<font size=\"+1\">&larr;</font>" \
+           {\(->}      "<font size=\"+1\">&rarr;</font>" \
+           {\(eu}      "&euro;" \
            {\fP}       {\fR} \
            {\.}        . \
-           {\(bu}      "&#8226;" \
+           {\(bu}      "&bull;" \
            {\*(qo}     "&ocirc;" \
            ]
+    # This might make a few invalid mappings, but we don't use them
+    foreach c {a c e g i l n o s t u y z A C E G I L N O S T U Y Z} {
+       foreach {prefix suffix} {
+           o ring / slash : uml ' acute ^ circ ` grave ~ tilde , cedil v caron
+       } {
+           lappend charmap "\\\[${prefix}${c}\]" "&${c}${suffix};"
+           lappend charmap "\\(${prefix}${c}" "&${c}${suffix};"
+       }
+    }
     lappend charmap {\-\|\-} --        ; # two hyphens
     lappend charmap {\-} -             ; # a hyphen
 
@@ -520,7 +573,7 @@ proc output-IP-list {context code rest} {
            if {[regexp {^\[[\da-f]+\]|\(?[\da-f]+\)$} $rest]} {
                set dl "<OL class=\"[string tolower $manual(section)]\">"
                set enddl "</OL>"
-           } elseif {"&#8226;" eq $rest} {
+           } elseif {"&bull;" eq $rest} {
                set dl "<UL class=\"[string tolower $manual(section)]\">"
                set enddl "</UL>"
            }
@@ -546,7 +599,7 @@ proc output-IP-list {context code rest} {
                            man-puts "$para<LI value=\"$value\">"
                        } elseif {[regexp {^\(?([\da-f]+)\)$} $rest -> value]} {
                            man-puts "$para<LI value=\"$value\">"
-                       } elseif {"&#8226;" eq $rest} {
+                       } elseif {"&bull;" eq $rest} {
                            man-puts "$para<LI>"
                        } else {
                            man-puts "$para<DT>[long-toc $rest]<DD>"
@@ -1559,6 +1612,10 @@ proc make-manpage-section {outputDir sectionDescriptor} {
        puts stderr ""
     }
 
+    if {![llength $manual(wing-toc)]} {
+       fatal "not table of contents."
+    }
+
     #
     # make the wing table of contents for the section
     #
index d607905..a9327b8 100755 (executable)
@@ -557,6 +557,7 @@ array set remap_link_target {
     Tk_Font    Tk_GetFont
     Tk_Image   Tk_GetImage
     Tk_ImageMaster Tk_GetImage
+    Tk_ImageModel Tk_GetImage
     Tk_ItemType Tk_CreateItemType
     Tk_Justify Tk_GetJustify
     Ttk_Theme  Ttk_GetTheme
@@ -586,6 +587,7 @@ array set exclude_refs_map {
     scrollbar.n                {set}
     selection.n                {string}
     tcltest.n          {error}
+    text.n             {bind image lower raise}
     tkvars.n           {tk}
     tkwait.n           {variable}
     tm.n               {exec}
index 86ec931..39fa28d 100644 (file)
@@ -16,33 +16,33 @@ proc emitRange {first last} {
     global ranges numranges chars numchars extchars extranges
 
     if {$first < ($last-1)} {
-       if {!$extranges && ($first) > 0xffff} {
+       if {!$extranges && ($first) > 0xFFFF} {
            set extranges 1
            set numranges 0
            set ranges [string trimright $ranges " \n\r\t,"]
            append ranges "\n#if CHRBITS > 16\n    ,"
        }
-       append ranges [format "{0x%x, 0x%x}, " \
+       append ranges [format "{0x%X, 0x%X}, " \
                $first $last]
        if {[incr numranges] % 4 == 0} {
            set ranges [string trimright $ranges]
            append ranges "\n    "
        }
     } else {
-       if {!$extchars && ($first) > 0xffff} {
+       if {!$extchars && ($first) > 0xFFFF} {
            set extchars 1
            set numchars 0
            set chars [string trimright $chars " \n\r\t,"]
            append chars "\n#if CHRBITS > 16\n    ,"
        }
-       append chars [format "0x%x, " $first]
+       append chars [format "0x%X, " $first]
        incr numchars
        if {$numchars % 9 == 0} {
            set chars [string trimright $chars]
            append chars "\n    "
        }
        if {$first != $last} {
-           append chars [format "0x%x, " $last]
+           append chars [format "0x%X, " $last]
            incr numchars
            if {$numchars % 9 == 0} {
                append chars "\n    "
@@ -63,11 +63,11 @@ proc genTable {type} {
     set extchars 0
     set extranges 0
 
-    for {set i 0} {$i <= 0x10ffff} {incr i} {
-    if {$i == 0xd800} {
-       # Skip surrogates
-       set i 0xe000
-    }
+    for {set i 0} {$i <= 0x10FFFF} {incr i} {
+       if {$i == 0xD800} {
+           # Skip surrogates
+           set i 0xE000
+       }
        if {[string is $type [format %c $i]]} {
            if {$i == ($last + 1)} {
                set last $i
index 561c28e..90d249a 100644 (file)
@@ -6,7 +6,7 @@
 #      UnicodeData file from:
 #          ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
 #
-# Copyright (c) 1998-1999 by Scriptics Corporation.
+# Copyright (c) 1998-1999 Scriptics Corporation.
 # All rights reserved.
 
 
@@ -68,7 +68,7 @@ proc uni::getGroup {value} {
     variable groups
 
     set gIndex [lsearch -exact $groups $value]
-    if {$gIndex == -1} {
+    if {$gIndex < 0} {
        set gIndex [llength $groups]
        lappend groups $value
     }
@@ -81,7 +81,7 @@ proc uni::addPage {info} {
     variable shift
 
     set pIndex [lsearch -exact $pages $info]
-    if {$pIndex == -1} {
+    if {$pIndex < 0} {
        set pIndex [llength $pages]
        lappend pages $info
     }
@@ -114,8 +114,8 @@ proc uni::buildTables {data} {
        set items [split $line \;]
 
        scan [lindex $items 0] %x index
-       if {$index > 0x2ffff} then {
-           # Ignore non-BMP characters, as long as Tcl doesn't support them
+       if {$index > 0x3FFFF} then {
+           # Ignore characters > plane 3
            continue
        }
        set index [format %d $index]
@@ -185,7 +185,7 @@ proc uni::main {} {
  *     automatically generated by the tools/uniParse.tcl script.  Do not
  *     modify this file by hand.
  *
- * Copyright (c) 1998 by Scriptics Corporation.
+ * Copyright (c) 1998 Scriptics Corporation.
  * All rights reserved.
  */
 
@@ -343,9 +343,9 @@ static const int groups\[\] = {"
     puts -nonewline $f "};
 
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
-#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1fffff) >= [format 0x%x $next])
+#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1FFFFF) >= [format 0x%X $next])
 #else
-#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1f0000) != 0)
+#   define UNICODE_OUT_OF_RANGE(ch) (((ch) & 0x1F0000) != 0)
 #endif
 
 /*
@@ -392,8 +392,8 @@ enum {
  * to do sign extension on right shifts.
  */
 
-#define GetCaseType(info) (((info) & 0xe0) >> 5)
-#define GetCategory(ch) (GetUniCharInfo(ch) & 0x1f)
+#define GetCaseType(info) (((info) & 0xE0) >> 5)
+#define GetCategory(ch) (GetUniCharInfo(ch) & 0x1F)
 #define GetDelta(info) ((info) >> 8)
 
 /*
@@ -402,9 +402,9 @@ enum {
  */
 
 #if TCL_UTF_MAX > 3 || TCL_MAJOR_VERSION > 8 || TCL_MINOR_VERSION > 6
-#   define GetUniCharInfo(ch) (groups\[groupMap\[pageMap\[((ch) & 0x1fffff) >> OFFSET_BITS\] | ((ch) & ((1 << OFFSET_BITS)-1))\]\])
+#   define GetUniCharInfo(ch) (groups\[groupMap\[pageMap\[((ch) & 0x1FFFFF) >> OFFSET_BITS\] | ((ch) & ((1 << OFFSET_BITS)-1))\]\])
 #else
-#   define GetUniCharInfo(ch) (groups\[groupMap\[pageMap\[((ch) & 0xffff) >> OFFSET_BITS\] | ((ch) & ((1 << OFFSET_BITS)-1))\]\])
+#   define GetUniCharInfo(ch) (groups\[groupMap\[pageMap\[((ch) & 0xFFFF) >> OFFSET_BITS\] | ((ch) & ((1 << OFFSET_BITS)-1))\]\])
 #endif
 "
 
index 99bdf05..85acc1f 100644 (file)
@@ -53,6 +53,9 @@ DLL_INSTALL_DIR               = @DLL_INSTALL_DIR@
 # Path name to use when installing library scripts.
 SCRIPT_INSTALL_DIR     = $(INSTALL_ROOT)$(TCL_LIBRARY)
 
+# Path name to use when installing Tcl modules.
+MODULE_INSTALL_DIR     = $(SCRIPT_INSTALL_DIR)/../tcl8
+
 # Directory in which to install the include file tcl.h:
 INCLUDE_INSTALL_DIR    = $(INSTALL_ROOT)$(includedir)
 
@@ -111,11 +114,6 @@ LDFLAGS_DEBUG              = @LDFLAGS_DEBUG@
 LDFLAGS_OPTIMIZE       = @LDFLAGS_OPTIMIZE@
 LDFLAGS                        = @LDFLAGS_DEFAULT@ @LDFLAGS@
 
-# To disable ANSI-C procedure prototypes reverse the comment characters on the
-# following lines:
-PROTO_FLAGS            =
-#PROTO_FLAGS           = -DNO_PROTOTYPE
-
 # If you use the setenv, putenv, or unsetenv procedures to modify environment
 # variables in your application and you'd like those modifications to appear
 # in the "env" Tcl variable, switch the comments on the two lines below so
@@ -275,7 +273,7 @@ VALGRINDARGS                = --tool=memcheck --num-callers=24 \
 
 STUB_CC_SWITCHES = ${CFLAGS} ${CFLAGS_WARNING} ${SHLIB_CFLAGS} \
 -I"${BUILD_DIR}" -I${UNIX_DIR} -I${GENERIC_DIR} -I${TOMMATH_DIR} \
-${AC_FLAGS} ${PROTO_FLAGS} ${ENV_FLAGS} ${EXTRA_CFLAGS} @EXTRA_CC_SWITCHES@
+${AC_FLAGS} ${ENV_FLAGS} ${EXTRA_CFLAGS} @EXTRA_CC_SWITCHES@
 
 CC_SWITCHES = $(STUB_CC_SWITCHES) ${NO_DEPRECATED_FLAGS} -DMP_FIXED_CUTOFFS -DMP_NO_STDINT
 
@@ -284,7 +282,7 @@ APP_CC_SWITCHES = $(CC_SWITCHES) @EXTRA_APP_CC_SWITCHES@
 LIBS           = @TCL_LIBS@
 
 DEPEND_SWITCHES        = ${CFLAGS} -I${UNIX_DIR} -I${GENERIC_DIR} \
-${AC_FLAGS} ${PROTO_FLAGS} ${EXTRA_CFLAGS} @EXTRA_CC_SWITCHES@
+${AC_FLAGS} ${EXTRA_CFLAGS} @EXTRA_CC_SWITCHES@
 
 TCLSH_OBJS = tclAppInit.o
 
@@ -907,11 +905,11 @@ install-binaries: binaries
        fi
        @EXTRA_INSTALL_BINARIES@
        @echo "Installing pkg-config file to $(LIB_INSTALL_DIR)/pkgconfig/"
-       @$(INSTALL_DATA_DIR) $(LIB_INSTALL_DIR)/pkgconfig
-       @$(INSTALL_DATA) tcl.pc $(LIB_INSTALL_DIR)/pkgconfig/tcl.pc
+       @$(INSTALL_DATA_DIR) "$(LIB_INSTALL_DIR)/pkgconfig"
+       @$(INSTALL_DATA) tcl.pc "$(LIB_INSTALL_DIR)/pkgconfig/tcl.pc"
 
 install-libraries: libraries
-       @for i in "$(SCRIPT_INSTALL_DIR)"; \
+       @for i in "$(SCRIPT_INSTALL_DIR)" "$(MODULE_INSTALL_DIR)"; \
            do \
            if [ ! -d "$$i" ] ; then \
                echo "Making directory $$i"; \
@@ -919,11 +917,19 @@ install-libraries: libraries
                else true; \
                fi; \
            done;
-       @for i in opt0.4 http1.0 encoding ../tcl8 ../tcl8/8.4  ../tcl8/8.4/platform ../tcl8/8.5 ../tcl8/8.6; \
+       @for i in opt0.4 http1.0 encoding; \
            do \
-           if [ ! -d "$(SCRIPT_INSTALL_DIR)"/$$i ] ; then \
+           if [ ! -d "$(SCRIPT_INSTALL_DIR)/$$i" ] ; then \
                echo "Making directory $(SCRIPT_INSTALL_DIR)/$$i"; \
-               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)"/$$i; \
+               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)/$$i"; \
+               else true; \
+               fi; \
+           done;
+       @for i in 8.4  8.4/platform 8.5 8.6; \
+           do \
+           if [ ! -d "$(MODULE_INSTALL_DIR)/$$i" ] ; then \
+               echo "Making directory $(MODULE_INSTALL_DIR)/$$i"; \
+               $(INSTALL_DATA_DIR) "$(MODULE_INSTALL_DIR)/$$i"; \
                else true; \
                fi; \
            done;
@@ -936,41 +942,41 @@ install-libraries: libraries
        @echo "Installing package http1.0 files to $(SCRIPT_INSTALL_DIR)/http1.0/";
        @for i in $(TOP_DIR)/library/http1.0/*.tcl ; \
            do \
-           $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)"/http1.0; \
+           $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)/http1.0"; \
            done;
-       @echo "Installing package http 2.9.1 as a Tcl Module";
-       @$(INSTALL_DATA) $(TOP_DIR)/library/http/http.tcl "$(SCRIPT_INSTALL_DIR)"/../tcl8/8.6/http-2.9.1.tm;
+       @echo "Installing package http 2.9.5 as a Tcl Module";
+       @$(INSTALL_DATA) $(TOP_DIR)/library/http/http.tcl "$(MODULE_INSTALL_DIR)/8.6/http-2.9.5.tm";
        @echo "Installing package opt0.4 files to $(SCRIPT_INSTALL_DIR)/opt0.4/";
        @for i in $(TOP_DIR)/library/opt/*.tcl ; \
            do \
-           $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)"/opt0.4; \
+           $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)/opt0.4"; \
            done;
        @echo "Installing package msgcat 1.6.1 as a Tcl Module";
-       @$(INSTALL_DATA) $(TOP_DIR)/library/msgcat/msgcat.tcl "$(SCRIPT_INSTALL_DIR)"/../tcl8/8.5/msgcat-1.6.1.tm;
-       @echo "Installing package tcltest 2.5.1 as a Tcl Module";
-       @$(INSTALL_DATA) $(TOP_DIR)/library/tcltest/tcltest.tcl "$(SCRIPT_INSTALL_DIR)"/../tcl8/8.5/tcltest-2.5.1.tm;
+       @$(INSTALL_DATA) $(TOP_DIR)/library/msgcat/msgcat.tcl "$(MODULE_INSTALL_DIR)/8.5/msgcat-1.6.1.tm";
+       @echo "Installing package tcltest 2.5.3 as a Tcl Module";
+       @$(INSTALL_DATA) $(TOP_DIR)/library/tcltest/tcltest.tcl "$(MODULE_INSTALL_DIR)/8.5/tcltest-2.5.3.tm";
 
-       @echo "Installing package platform 1.0.14 as a Tcl Module";
-       @$(INSTALL_DATA) $(TOP_DIR)/library/platform/platform.tcl "$(SCRIPT_INSTALL_DIR)"/../tcl8/8.4/platform-1.0.14.tm;
+       @echo "Installing package platform 1.0.15 as a Tcl Module";
+       @$(INSTALL_DATA) $(TOP_DIR)/library/platform/platform.tcl "$(MODULE_INSTALL_DIR)/8.4/platform-1.0.15.tm";
        @echo "Installing package platform::shell 1.1.4 as a Tcl Module";
-       @$(INSTALL_DATA) $(TOP_DIR)/library/platform/shell.tcl "$(SCRIPT_INSTALL_DIR)"/../tcl8/8.4/platform/shell-1.1.4.tm;
+       @$(INSTALL_DATA) $(TOP_DIR)/library/platform/shell.tcl "$(MODULE_INSTALL_DIR)/8.4/platform/shell-1.1.4.tm";
 
        @echo "Installing encoding files to $(SCRIPT_INSTALL_DIR)/encoding/";
        @for i in $(TOP_DIR)/library/encoding/*.enc ; do \
-               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)"/encoding; \
+               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)/encoding"; \
        done;
        @if [ -n "$(TCL_MODULE_PATH)" -a -f $(TOP_DIR)/library/tm.tcl ]; then \
            echo "Customizing tcl module path"; \
            echo "if {![interp issafe]} { ::tcl::tm::roots {$(TCL_MODULE_PATH)} }" >> \
-               "$(SCRIPT_INSTALL_DIR)"/tm.tcl; \
+               "$(SCRIPT_INSTALL_DIR)/tm.tcl"; \
        fi
 
 install-tzdata:
        @for i in tzdata; \
            do \
-           if [ ! -d "$(SCRIPT_INSTALL_DIR)"/$$i ] ; then \
+           if [ ! -d "$(SCRIPT_INSTALL_DIR)/$$i" ] ; then \
                echo "Making directory $(SCRIPT_INSTALL_DIR)/$$i"; \
-               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)"/$$i; \
+               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)/$$i"; \
                else true; \
                fi; \
            done;
@@ -978,39 +984,39 @@ install-tzdata:
        @for i in $(TOP_DIR)/library/tzdata/* ; do \
            if [ -d $$i ] ; then \
                ii=`basename $$i`; \
-               if [ ! -d "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii ] ; then \
-                   $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii; \
+               if [ ! -d "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii" ] ; then \
+                   $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii"; \
                fi; \
                for j in $$i/* ; do \
                    if [ -d $$j ] ; then \
                        jj=`basename $$j`; \
-                       if [ ! -d "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii/$$jj ] ; then \
-                           $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii/$$jj; \
+                       if [ ! -d "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii/$$jj" ] ; then \
+                           $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii/$$jj"; \
                        fi; \
                        for k in $$j/* ; do \
-                           $(INSTALL_DATA) $$k "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii/$$jj; \
+                           $(INSTALL_DATA) $$k "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii/$$jj"; \
                        done; \
                    else \
-                       $(INSTALL_DATA) $$j "$(SCRIPT_INSTALL_DIR)"/tzdata/$$ii; \
+                       $(INSTALL_DATA) $$j "$(SCRIPT_INSTALL_DIR)/tzdata/$$ii"; \
                    fi; \
                done; \
            else \
-               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)"/tzdata; \
+               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)/tzdata"; \
            fi; \
        done;
 
 install-msgs:
        @for i in msgs; \
            do \
-           if [ ! -d "$(SCRIPT_INSTALL_DIR)"/$$i ] ; then \
+           if [ ! -d "$(SCRIPT_INSTALL_DIR)/$$i" ] ; then \
                echo "Making directory $(SCRIPT_INSTALL_DIR)/$$i"; \
-               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)"/$$i; \
+               $(INSTALL_DATA_DIR) "$(SCRIPT_INSTALL_DIR)/$$i"; \
                else true; \
                fi; \
            done;
        @echo "Installing message catalog files to $(SCRIPT_INSTALL_DIR)/msgs/"
        @for i in $(TOP_DIR)/library/msgs/*.msg ; do \
-               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)"/msgs; \
+               $(INSTALL_DATA) $$i "$(SCRIPT_INSTALL_DIR)/msgs"; \
        done;
 
 install-doc: doc
@@ -2021,9 +2027,9 @@ rpm: all
        rm -rf RPMS THIS.TCL.SPEC
 
 #
-# Target to create a proper Tcl distribution from information in the master
-# source directory. DISTDIR must be defined to indicate where to put the
-# distribution. DISTDIR must be an absolute path name.
+# Target to create a proper Tcl distribution from information in the
+# source directory. DISTDIR must be defined to indicate where to put
+# the distribution. DISTDIR must be an absolute path name.
 #
 
 DISTROOT = /tmp/dist
@@ -2038,20 +2044,25 @@ $(MAC_OSX_DIR)/configure: $(MAC_OSX_DIR)/configure.ac $(UNIX_DIR)/configure
 $(UNIX_DIR)/tclConfig.h.in: $(MAC_OSX_DIR)/configure
        cd $(MAC_OSX_DIR); autoheader; touch $@
 
-dist: $(UNIX_DIR)/configure $(UNIX_DIR)/tclConfig.h.in $(UNIX_DIR)/tcl.pc.in $(MAC_OSX_DIR)/configure genstubs dist-packages ${NATIVE_TCLSH}
+$(TOP_DIR)/manifest.uuid:
+       printf "git." >$(TOP_DIR)/manifest.uuid
+       git rev-parse HEAD >>$(TOP_DIR)/manifest.uuid
+
+dist: $(UNIX_DIR)/configure $(UNIX_DIR)/tclConfig.h.in $(UNIX_DIR)/tcl.pc.in $(MAC_OSX_DIR)/configure $(TOP_DIR)/manifest.uuid genstubs dist-packages ${NATIVE_TCLSH}
        rm -rf $(DISTDIR)
        mkdir -p $(DISTDIR)/unix
+       cp -p $(TOP_DIR)/manifest.uuid $(DISTDIR)
        cp -p $(UNIX_DIR)/*.[ch] $(DISTDIR)/unix
-       cp $(UNIX_DIR)/Makefile.in $(DISTDIR)/unix
+       cp -p $(UNIX_DIR)/Makefile.in $(DISTDIR)/unix
        chmod 664 $(DISTDIR)/unix/Makefile.in
-       cp $(UNIX_DIR)/configure $(UNIX_DIR)/configure.in \
+       cp -p $(UNIX_DIR)/configure $(UNIX_DIR)/configure.in \
                $(UNIX_DIR)/tcl.m4 $(UNIX_DIR)/aclocal.m4 \
                $(UNIX_DIR)/tclConfig.sh.in $(UNIX_DIR)/tclooConfig.sh \
                $(UNIX_DIR)/install-sh \
                $(UNIX_DIR)/README $(UNIX_DIR)/ldAix $(UNIX_DIR)/tcl.spec \
                $(UNIX_DIR)/installManPage $(UNIX_DIR)/tclConfig.h.in \
                $(UNIX_DIR)/tcl.pc.in $(DISTDIR)/unix
-       chmod 775 $(DISTDIR)/unix/configure $(DISTDIR)/unix/configure.in
+       chmod 775 $(DISTDIR)/unix/configure
        chmod 775 $(DISTDIR)/unix/ldAix
        @mkdir $(DISTDIR)/generic
        cp -p $(GENERIC_DIR)/*.[cdh] $(DISTDIR)/generic
@@ -2094,9 +2105,22 @@ dist: $(UNIX_DIR)/configure $(UNIX_DIR)/tclConfig.h.in $(UNIX_DIR)/tcl.pc.in $(M
        cp -p $(TOP_DIR)/tests/*.test $(TOP_DIR)/tests/README \
                $(TOP_DIR)/tests/httpd $(TOP_DIR)/tests/*.tcl \
                $(DISTDIR)/tests
+       @mkdir $(DISTDIR)/tests/auto0
+       for i in auto1 auto2 ; \
+           do \
+               mkdir $(DISTDIR)/tests/auto0/$$i ;\
+               cp -p $(TOP_DIR)/tests/auto0/$$i/tclIndex $(TOP_DIR)/tests/auto0/$$i/*.tcl \
+                       $(DISTDIR)/tests/auto0/$$i; \
+           done;
+       for i in modules modules/mod1 modules/mod2 ; \
+           do \
+               mkdir $(DISTDIR)/tests/auto0/$$i ;\
+               cp -p $(TOP_DIR)/tests/auto0/$$i/*.tm \
+                       $(DISTDIR)/tests/auto0/$$i; \
+           done;
        @mkdir $(DISTDIR)/win
-       cp $(TOP_DIR)/win/Makefile.in $(DISTDIR)/win
-       cp $(TOP_DIR)/win/configure.in $(TOP_DIR)/win/configure \
+       cp -p $(TOP_DIR)/win/Makefile.in $(DISTDIR)/win
+       cp -p $(TOP_DIR)/win/configure.in $(TOP_DIR)/win/configure \
                $(TOP_DIR)/win/tclConfig.sh.in $(TOP_DIR)/win/tclooConfig.sh \
                $(TOP_DIR)/win/tcl.m4 $(TOP_DIR)/win/aclocal.m4 \
                $(TOP_DIR)/win/tclsh.exe.manifest.in \
@@ -2136,11 +2160,14 @@ dist: $(UNIX_DIR)/configure $(UNIX_DIR)/tclConfig.h.in $(UNIX_DIR)/tcl.pc.in $(M
        @mkdir $(DISTDIR)/libtommath
        cp -p $(TOMMATH_SRCS) $(TOMMATH_DIR)/*.h $(DISTDIR)/libtommath
        @mkdir $(DISTDIR)/pkgs
-       cp $(TOP_DIR)/pkgs/README $(DISTDIR)/pkgs
-       cp $(TOP_DIR)/pkgs/package.list.txt $(DISTDIR)/pkgs
+       cp -p $(TOP_DIR)/pkgs/README $(DISTDIR)/pkgs
+       cp -p $(TOP_DIR)/pkgs/package.list.txt $(DISTDIR)/pkgs
        for i in `ls $(DISTROOT)/pkgs/*.tar.gz 2> /dev/null`; do \
            tar -C $(DISTDIR)/pkgs -xzf "$$i"; \
        done
+       cp -p $(TOP_DIR)/.travis.yml $(DISTDIR)
+       mkdir -p $(DISTDIR)/.github/workflows
+       cp -p $(TOP_DIR)/.github/workflows/*.yml $(DISTDIR)/.github/workflows
 
 alldist: dist
        rm -f $(DISTROOT)/$(DISTNAME)-src.tar.gz $(DISTROOT)/$(ZIPNAME)
index 2576665..b71cdaa 100755 (executable)
@@ -1335,7 +1335,7 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 TCL_VERSION=8.6
 TCL_MAJOR_VERSION=8
 TCL_MINOR_VERSION=6
-TCL_PATCH_LEVEL=".10"
+TCL_PATCH_LEVEL=".11"
 VERSION=${TCL_VERSION}
 
 EXTRA_INSTALL_BINARIES=${EXTRA_INSTALL_BINARIES:-"@:"}
@@ -2823,6 +2823,7 @@ cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 #include <ctype.h>
+#include <stdlib.h>
 #if ((' ' & 0x0FF) == 0x020)
 # define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
 # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
@@ -5714,14 +5715,6 @@ if test "${enable_shared+set}" = set; then
 else
   tcl_ok=yes
 fi;
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
     if test "$tcl_ok" = "yes" ; then
        echo "$as_me:$LINENO: result: shared" >&5
 echo "${ECHO_T}shared" >&6
@@ -6496,7 +6489,7 @@ fi
     if test "$GCC" = yes; then
 
        CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
+       CFLAGS_WARNING="-Wall -Wpointer-arith"
 
 else
 
@@ -6787,7 +6780,7 @@ fi
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            ;;
-       CYGWIN_*|MINGW32*)
+       CYGWIN_*|MINGW32_*|MSYS_*)
            SHLIB_CFLAGS=""
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
@@ -6798,7 +6791,7 @@ fi
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            TCL_NEEDS_EXP_FILE=1
-           TCL_EXPORT_FILE_SUFFIX='${VERSION}\$\{DBGX\}.dll.a'
+           TCL_EXPORT_FILE_SUFFIX='${VERSION}.dll.a'
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$@.a"
            echo "$as_me:$LINENO: checking for Cygwin version of gcc" >&5
 echo $ECHO_N "checking for Cygwin version of gcc... $ECHO_C" >&6
@@ -7099,7 +7092,7 @@ fi
                            SHLIB_LD='${CC} -shared'
                            if test $doRpath = yes; then
 
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
@@ -7223,7 +7216,7 @@ esac
 
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
 
@@ -7244,7 +7237,7 @@ esac
 
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
 
@@ -7285,7 +7278,7 @@ esac
 
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
 
@@ -7328,7 +7321,7 @@ fi
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
@@ -7428,8 +7421,8 @@ fi
            LD_FLAGS="-Wl,--export-dynamic"
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
            ;;
@@ -7470,7 +7463,7 @@ fi
            DL_LIBS=""
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
@@ -7500,7 +7493,7 @@ fi
            LDFLAGS="$LDFLAGS -export-dynamic"
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
@@ -7522,11 +7515,10 @@ fi
            SHLIB_SUFFIX=".so"
            DL_OBJS="tclLoadDl.o"
            DL_LIBS=""
-           LDFLAGS=""
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
 fi
 
            if test "${TCL_THREADS}" = "1"; then
@@ -7851,6 +7843,7 @@ cat >>confdefs.h <<\_ACEOF
 #define MODULE_SCOPE __private_extern__
 _ACEOF
 
+               tcl_cv_cc_visibility_hidden=yes
 
 fi
 
@@ -8114,7 +8107,7 @@ fi
            DL_LIBS=""
            if test $doRpath = yes; then
 
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'
 fi
 
@@ -8713,7 +8706,7 @@ fi
        case $system in
            AIX-*) ;;
            BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*) ;;
+           CYGWIN_*|MINGW32_*|MSYS_*) ;;
            IRIX*) ;;
            NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
            Darwin-*) ;;
@@ -8749,7 +8742,7 @@ fi
     if test "${SHARED_BUILD}" = 1 -a "${SHLIB_SUFFIX}" != ""; then
 
         LIB_SUFFIX=${SHARED_LIB_SUFFIX}
-        MAKE_LIB='${SHLIB_LD} -o $@ ${OBJS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
+        MAKE_LIB='${SHLIB_LD} -o $@ ${OBJS} ${LDFLAGS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
         if test "${SHLIB_SUFFIX}" = ".dll"; then
 
             INSTALL_LIB='$(INSTALL_LIBRARY) $(LIB_FILE) "$(BIN_INSTALL_DIR)/$(LIB_FILE)";if test -f $(LIB_FILE).a; then $(INSTALL_DATA) $(LIB_FILE).a "$(LIB_INSTALL_DIR)"; fi;'
@@ -8925,7 +8918,6 @@ else
   tcl_ok=no
 fi;
 # FIXME: Currently, LDFLAGS_DEFAULT is not used, it should work like CFLAGS_DEFAULT.
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT='$(CFLAGS_OPTIMIZE)'
        LDFLAGS_DEFAULT='$(LDFLAGS_OPTIMIZE)'
@@ -14031,7 +14023,7 @@ cat >>conftest.$ac_ext <<_ACEOF
 int
 main ()
 {
-struct tm tm; tm.tm_gmtoff;
+struct tm tm; (void)tm.tm_gmtoff;
   ;
   return 0;
 }
@@ -14923,8 +14915,10 @@ _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
+
+#include <stdlib.h>
+#include <string.h>
 int main() {
-    extern int strstr();
     exit(strstr("\0test", "test") ? 1 : 0);
 }
 _ACEOF
@@ -15090,8 +15084,10 @@ _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
+
+#include <stdlib.h>
+#include <string.h>
 int main() {
-    extern int strtoul();
     char *term, *string = "0";
     exit(strtoul(string,&term,0) != 0 || term != string+1);
 }
@@ -16463,6 +16459,7 @@ cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 
        #include <stdlib.h>
+       #include <string.h>
        #define OURVAR "havecopy=yes"
        int main (int argc, char *argv[])
        {
@@ -18761,7 +18758,7 @@ echo "${ECHO_T}static library" >&6
 
     TCL_SHLIB_LD_EXTRAS="-compatibility_version ${TCL_VERSION} -current_version ${TCL_VERSION}`echo ${TCL_PATCH_LEVEL} | awk '{match($0, "\\\.[0-9]+"); print substr($0,RSTART,RLENGTH)}'`"
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -install_name "${DYLIB_INSTALL_DIR}"/${TCL_LIB_FILE}'
-    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xa000000'
+    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xA000000'
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -sectcreate __TEXT __info_plist Tcl-Info.plist'
     EXTRA_TCLSH_LIBS='-sectcreate __TEXT __info_plist Tclsh-Info.plist'
     EXTRA_APP_CC_SWITCHES='-mdynamic-no-pic'
@@ -18801,7 +18798,7 @@ _ACEOF
     PRIVATE_INCLUDE_DIR="${libdir}/PrivateHeaders"
     HTML_DIR="${libdir}/Resources/Documentation/Reference/Tcl"
     EXTRA_INSTALL="install-private-headers html-tcl"
-    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)"/TclTOC.html'
+    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)/TclTOC.html"'
     EXTRA_INSTALL_BINARIES='@echo "Installing Info.plist to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA_DIR) "$(LIB_INSTALL_DIR)/Resources" && $(INSTALL_DATA) Tcl-Info.plist "$(LIB_INSTALL_DIR)/Resources/Info.plist"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Installing license.terms to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA) "$(TOP_DIR)/license.terms" "$(LIB_INSTALL_DIR)/Resources"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Finalizing Tcl.framework" && rm -f "$(LIB_INSTALL_DIR)/../Current" && ln -s "$(VERSION)" "$(LIB_INSTALL_DIR)/../Current" && for f in "$(LIB_FILE)" tclConfig.sh Resources Headers PrivateHeaders; do rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/Current/$$f" "$(LIB_INSTALL_DIR)/../.."; done && f="$(STUB_LIB_FILE)" && rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/$(VERSION)/$$f" "$(LIB_INSTALL_DIR)/../.."'
@@ -18841,9 +18838,9 @@ if test "$FRAMEWORK_BUILD" = "1" ; then
     test -z "$TCL_MODULE_PATH"  && \
        TCL_MODULE_PATH="~/Library/Tcl /Library/Tcl"
 elif test "$prefix/lib" != "$libdir"; then
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${libdir} ${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${libdir}} {${prefix}/lib} ${TCL_PACKAGE_PATH}"
 else
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${prefix}/lib} ${TCL_PACKAGE_PATH}"
 fi
 
 #--------------------------------------------------------------------
@@ -18856,7 +18853,7 @@ fi
 #
 eval "TCL_STUB_LIB_FILE=libtclstub${TCL_UNSHARED_LIB_SUFFIX}"
 eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-eval "TCL_STUB_LIB_DIR=${libdir}"
+eval "TCL_STUB_LIB_DIR=\"${libdir}\""
 
 if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
     TCL_STUB_LIB_FLAG="-ltclstub${TCL_VERSION}"
old mode 100755 (executable)
new mode 100644 (file)
index 0d3f426..572fb48
@@ -25,7 +25,7 @@ m4_ifdef([SC_USE_CONFIG_HEADERS], [
 TCL_VERSION=8.6
 TCL_MAJOR_VERSION=8
 TCL_MINOR_VERSION=6
-TCL_PATCH_LEVEL=".10"
+TCL_PATCH_LEVEL=".11"
 VERSION=${TCL_VERSION}
 
 EXTRA_INSTALL_BINARIES=${EXTRA_INSTALL_BINARIES:-"@:"}
@@ -342,7 +342,6 @@ AC_CHECK_FUNC(memmove, , [
 #--------------------------------------------------------------------
 
 SC_TCL_CHECK_BROKEN_FUNC(strstr, [
-    extern int strstr();
     exit(strstr("\0test", "test") ? 1 : 0);
 ])
 
@@ -353,7 +352,6 @@ SC_TCL_CHECK_BROKEN_FUNC(strstr, [
 #--------------------------------------------------------------------
 
 SC_TCL_CHECK_BROKEN_FUNC(strtoul, [
-    extern int strtoul();
     char *term, *string = "0";
     exit(strtoul(string,&term,0) != 0 || term != string+1);
 ])
@@ -499,6 +497,7 @@ fi
 AC_CACHE_CHECK([for a putenv() that copies the buffer], tcl_cv_putenv_copy, [
     AC_TRY_RUN([
        #include <stdlib.h>
+       #include <string.h>
        #define OURVAR "havecopy=yes"
        int main (int argc, char *argv[])
        {
@@ -786,7 +785,7 @@ if test "`uname -s`" = "Darwin" ; then
     SC_ENABLE_FRAMEWORK
     TCL_SHLIB_LD_EXTRAS="-compatibility_version ${TCL_VERSION} -current_version ${TCL_VERSION}`echo ${TCL_PATCH_LEVEL} | awk ['{match($0, "\\\.[0-9]+"); print substr($0,RSTART,RLENGTH)}']`"
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -install_name "${DYLIB_INSTALL_DIR}"/${TCL_LIB_FILE}'
-    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xa000000'
+    echo "$LDFLAGS " | grep -q -- '-prebind ' && TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -seg1addr 0xA000000'
     TCL_SHLIB_LD_EXTRAS="${TCL_SHLIB_LD_EXTRAS}"' -sectcreate __TEXT __info_plist Tcl-Info.plist'
     EXTRA_TCLSH_LIBS='-sectcreate __TEXT __info_plist Tclsh-Info.plist'
     EXTRA_APP_CC_SWITCHES='-mdynamic-no-pic'
@@ -826,7 +825,7 @@ if test "$FRAMEWORK_BUILD" = "1" ; then
     PRIVATE_INCLUDE_DIR="${libdir}/PrivateHeaders"
     HTML_DIR="${libdir}/Resources/Documentation/Reference/Tcl"
     EXTRA_INSTALL="install-private-headers html-tcl"
-    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)"/TclTOC.html'
+    EXTRA_BUILD_HTML='@ln -fs contents.htm "$(HTML_INSTALL_DIR)/TclTOC.html"'
     EXTRA_INSTALL_BINARIES='@echo "Installing Info.plist to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA_DIR) "$(LIB_INSTALL_DIR)/Resources" && $(INSTALL_DATA) Tcl-Info.plist "$(LIB_INSTALL_DIR)/Resources/Info.plist"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Installing license.terms to $(LIB_INSTALL_DIR)/Resources/" && $(INSTALL_DATA) "$(TOP_DIR)/license.terms" "$(LIB_INSTALL_DIR)/Resources"'
     EXTRA_INSTALL_BINARIES="$EXTRA_INSTALL_BINARIES"' && echo "Finalizing Tcl.framework" && rm -f "$(LIB_INSTALL_DIR)/../Current" && ln -s "$(VERSION)" "$(LIB_INSTALL_DIR)/../Current" && for f in "$(LIB_FILE)" tclConfig.sh Resources Headers PrivateHeaders; do rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/Current/$$f" "$(LIB_INSTALL_DIR)/../.."; done && f="$(STUB_LIB_FILE)" && rm -f "$(LIB_INSTALL_DIR)/../../$$f" && ln -s "Versions/$(VERSION)/$$f" "$(LIB_INSTALL_DIR)/../.."'
@@ -866,9 +865,9 @@ if test "$FRAMEWORK_BUILD" = "1" ; then
     test -z "$TCL_MODULE_PATH"  && \
        TCL_MODULE_PATH="~/Library/Tcl /Library/Tcl"
 elif test "$prefix/lib" != "$libdir"; then
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${libdir} ${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${libdir}} {${prefix}/lib} ${TCL_PACKAGE_PATH}"
 else
-    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="${prefix}/lib ${TCL_PACKAGE_PATH}"
+    test -z "$TCL_PACKAGE_PATH" && TCL_PACKAGE_PATH="{${prefix}/lib} ${TCL_PACKAGE_PATH}"
 fi
 
 #--------------------------------------------------------------------
@@ -881,7 +880,7 @@ fi
 #
 eval "TCL_STUB_LIB_FILE=libtclstub${TCL_UNSHARED_LIB_SUFFIX}"
 eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-eval "TCL_STUB_LIB_DIR=${libdir}"
+eval "TCL_STUB_LIB_DIR=\"${libdir}\""
 
 if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then
     TCL_STUB_LIB_FLAG="-ltclstub${TCL_VERSION}"
index 7c34c3f..21b733a 100755 (executable)
@@ -1,7 +1,7 @@
 #!/bin/sh
 # install - install a program, script, or datafile
 
-scriptversion=2011-04-20.01; # UTC
+scriptversion=2020-07-26.22; # UTC
 
 # This originates from X11R5 (mit/util/scripts/install.sh), which was
 # later released in X11R6 (xc/config/util/install.sh) with the
@@ -35,25 +35,21 @@ scriptversion=2011-04-20.01; # UTC
 # FSF changes to this file are in the public domain.
 #
 # Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
+# '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.
 
+tab='  '
 nl='
 '
-IFS=" ""       $nl"
+IFS=" $tab$nl"
 
-# set DOITPROG to echo to test this script
+# Set DOITPROG to "echo" to test this script.
 
-# Don't use :- since 4.3BSD and earlier shells don't like it.
 doit=${DOITPROG-}
-if test -z "$doit"; then
-  doit_exec=exec
-else
-  doit_exec=$doit
-fi
+doit_exec=${doit:-exec}
 
 # Put in absolute file names if you don't have them in your path;
 # or use environment vars.
@@ -68,22 +64,15 @@ mvprog=${MVPROG-mv}
 rmprog=${RMPROG-rm}
 stripprog=${STRIPPROG-strip}
 
-posix_glob='?'
-initialize_posix_glob='
-  test "$posix_glob" != "?" || {
-    if (set -f) 2>/dev/null; then
-      posix_glob=
-    else
-      posix_glob=:
-    fi
-  }
-'
-
 posix_mkdir=
 
 # Desired mode of installed file.
 mode=0755
 
+# Create dirs (including intermediate dirs) using mode 755.
+# This is like GNU 'install' as of coreutils 8.32 (2020).
+mkdir_umask=22
+
 chgrpcmd=
 chmodcmd=$chmodprog
 chowncmd=
@@ -97,7 +86,7 @@ dir_arg=
 dst_arg=
 
 copy_on_change=false
-no_target_directory=
+is_target_a_directory=possibly
 
 usage="\
 Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
@@ -120,7 +109,7 @@ Options:
   -m MODE       $chmodprog installed files to MODE.
   -o USER       $chownprog installed files to USER.
   -s            $stripprog installed files.
-  -S            $stripprog installed files.
+  -S OPTION     $stripprog installed files using OPTION.
   -t DIRECTORY  install into DIRECTORY.
   -T            report an error if DSTFILE is a directory.
 
@@ -138,45 +127,60 @@ while test $# -ne 0; do
     -d) dir_arg=true;;
 
     -g) chgrpcmd="$chgrpprog $2"
-       shift;;
+        shift;;
 
     --help) echo "$usage"; exit $?;;
 
     -m) mode=$2
-       case $mode in
-         *' '* | *'    '* | *'
-'*       | *'*'* | *'?'* | *'['*)
-           echo "$0: invalid mode: $mode" >&2
-           exit 1;;
-       esac
-       shift;;
+        case $mode in
+          *' '* | *"$tab"* | *"$nl"* | *'*'* | *'?'* | *'['*)
+            echo "$0: invalid mode: $mode" >&2
+            exit 1;;
+        esac
+        shift;;
 
     -o) chowncmd="$chownprog $2"
-       shift;;
+        shift;;
 
     -s) stripcmd=$stripprog;;
 
     -S) stripcmd="$stripprog $2"
-       shift;;
+        shift;;
 
-    -t) dst_arg=$2
-       shift;;
+    -t)
+        is_target_a_directory=always
+        dst_arg=$2
+        # Protect names problematic for 'test' and other utilities.
+        case $dst_arg in
+          -* | [=\(\)!]) dst_arg=./$dst_arg;;
+        esac
+        shift;;
 
-    -T) no_target_directory=true;;
+    -T) is_target_a_directory=never;;
 
     --version) echo "$0 $scriptversion"; exit $?;;
 
-    --)        shift
-       break;;
+    --) shift
+        break;;
 
-    -*)        echo "$0: invalid option: $1" >&2
-       exit 1;;
+    -*) echo "$0: invalid option: $1" >&2
+        exit 1;;
 
     *)  break;;
   esac
   shift
 done
 
+# We allow the use of options -d and -T together, by making -d
+# take the precedence; this is for compatibility with GNU install.
+
+if test -n "$dir_arg"; then
+  if test -n "$dst_arg"; then
+    echo "$0: target directory not allowed when installing a directory." >&2
+    exit 1
+  fi
+fi
+
 if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
   # When -d is used, all remaining arguments are directories to create.
   # When -t is used, the destination is already specified.
@@ -190,6 +194,10 @@ if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
     fi
     shift # arg
     dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
   done
 fi
 
@@ -198,12 +206,21 @@ if test $# -eq 0; then
     echo "$0: no input file specified." >&2
     exit 1
   fi
-  # It's OK to call `install-sh -d' without argument.
+  # It's OK to call 'install-sh -d' without argument.
   # This can happen when creating conditional directories.
   exit 0
 fi
 
 if test -z "$dir_arg"; then
+  if test $# -gt 1 || test "$is_target_a_directory" = always; then
+    if test ! -d "$dst_arg"; then
+      echo "$0: $dst_arg: Is not a directory." >&2
+      exit 1
+    fi
+  fi
+fi
+
+if test -z "$dir_arg"; then
   do_exit='(exit $ret); exit $ret'
   trap "ret=129; $do_exit" 1
   trap "ret=130; $do_exit" 2
@@ -219,16 +236,16 @@ if test -z "$dir_arg"; then
 
     *[0-7])
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw='% 200'
+        u_plus_rw='% 200'
       fi
       cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
     *)
       if test -z "$stripcmd"; then
-       u_plus_rw=
+        u_plus_rw=
       else
-       u_plus_rw=,u+rw
+        u_plus_rw=,u+rw
       fi
       cp_umask=$mode$u_plus_rw;;
   esac
@@ -236,9 +253,9 @@ fi
 
 for src
 do
-  # Protect names starting with `-'.
+  # Protect names problematic for 'test' and other utilities.
   case $src in
-    -*) src=./$src;;
+    -* | [=\(\)!]) src=./$src;;
   esac
 
   if test -n "$dir_arg"; then
@@ -260,185 +277,150 @@ do
       echo "$0: no destination specified." >&2
       exit 1
     fi
-
     dst=$dst_arg
-    # Protect names starting with `-'.
-    case $dst in
-      -*) dst=./$dst;;
-    esac
 
-    # If destination is a directory, append the input filename; won't work
-    # if double slashes aren't ignored.
+    # If destination is a directory, append the input filename.
     if test -d "$dst"; then
-      if test -n "$no_target_directory"; then
-       echo "$0: $dst_arg: Is a directory" >&2
-       exit 1
+      if test "$is_target_a_directory" = never; then
+        echo "$0: $dst_arg: Is a directory" >&2
+        exit 1
       fi
       dstdir=$dst
-      dst=$dstdir/`basename "$src"`
+      dstbase=`basename "$src"`
+      case $dst in
+       */) dst=$dst$dstbase;;
+       *)  dst=$dst/$dstbase;;
+      esac
       dstdir_status=0
     else
-      # Prefer dirname, but fall back on a substitute if dirname fails.
-      dstdir=`
-       (dirname "$dst") 2>/dev/null ||
-       expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-            X"$dst" : 'X\(//\)[^/]' \| \
-            X"$dst" : 'X\(//\)$' \| \
-            X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
-       echo X"$dst" |
-           sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)[^/].*/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\/\)$/{
-                  s//\1/
-                  q
-                }
-                /^X\(\/\).*/{
-                  s//\1/
-                  q
-                }
-                s/.*/./; q'
-      `
-
+      dstdir=`dirname "$dst"`
       test -d "$dstdir"
       dstdir_status=$?
     fi
   fi
 
+  case $dstdir in
+    */) dstdirslash=$dstdir;;
+    *)  dstdirslash=$dstdir/;;
+  esac
+
   obsolete_mkdir_used=false
 
   if test $dstdir_status != 0; then
     case $posix_mkdir in
       '')
-       # Create intermediate dirs using mode 755 as modified by the umask.
-       # This is like FreeBSD 'install' as of 1997-10-28.
-       umask=`umask`
-       case $stripcmd.$umask in
-         # Optimize common cases.
-         *[2367][2367]) mkdir_umask=$umask;;
-         .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
-
-         *[0-7])
-           mkdir_umask=`expr $umask + 22 \
-             - $umask % 100 % 40 + $umask % 20 \
-             - $umask % 10 % 4 + $umask % 2
-           `;;
-         *) mkdir_umask=$umask,go-w;;
-       esac
-
-       # With -d, create the new directory with the user-specified mode.
-       # Otherwise, rely on $mkdir_umask.
-       if test -n "$dir_arg"; then
-         mkdir_mode=-m$mode
+        # With -d, create the new directory with the user-specified mode.
+        # Otherwise, rely on $mkdir_umask.
+        if test -n "$dir_arg"; then
+          mkdir_mode=-m$mode
+        else
+          mkdir_mode=
+        fi
+
+        posix_mkdir=false
+       # The $RANDOM variable is not portable (e.g., dash).  Use it
+       # here however when possible just to lower collision chance.
+       tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+
+       trap '
+         ret=$?
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir" 2>/dev/null
+         exit $ret
+       ' 0
+
+       # Because "mkdir -p" follows existing symlinks and we likely work
+       # directly in world-writeable /tmp, make sure that the '$tmpdir'
+       # directory is successfully created first before we actually test
+       # 'mkdir -p'.
+       if (umask $mkdir_umask &&
+           $mkdirprog $mkdir_mode "$tmpdir" &&
+           exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1
+       then
+         if test -z "$dir_arg" || {
+              # Check for POSIX incompatibilities with -m.
+              # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+              # other-writable bit of parent directory when it shouldn't.
+              # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+              test_tmpdir="$tmpdir/a"
+              ls_ld_tmpdir=`ls -ld "$test_tmpdir"`
+              case $ls_ld_tmpdir in
+                d????-?r-*) different_mode=700;;
+                d????-?--*) different_mode=755;;
+                *) false;;
+              esac &&
+              $mkdirprog -m$different_mode -p -- "$test_tmpdir" && {
+                ls_ld_tmpdir_1=`ls -ld "$test_tmpdir"`
+                test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+              }
+            }
+         then posix_mkdir=:
+         fi
+         rmdir "$tmpdir/a/b" "$tmpdir/a" "$tmpdir"
        else
-         mkdir_mode=
+         # Remove any dirs left behind by ancient mkdir implementations.
+         rmdir ./$mkdir_mode ./-p ./-- "$tmpdir" 2>/dev/null
        fi
-
-       posix_mkdir=false
-       case $umask in
-         *[123567][0-7][0-7])
-           # POSIX mkdir -p sets u+wx bits regardless of umask, which
-           # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
-           ;;
-         *)
-           tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
-           trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
-
-           if (umask $mkdir_umask &&
-               exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
-           then
-             if test -z "$dir_arg" || {
-                  # Check for POSIX incompatibilities with -m.
-                  # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
-                  # other-writeable bit of parent directory when it shouldn't.
-                  # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
-                  ls_ld_tmpdir=`ls -ld "$tmpdir"`
-                  case $ls_ld_tmpdir in
-                    d????-?r-*) different_mode=700;;
-                    d????-?--*) different_mode=755;;
-                    *) false;;
-                  esac &&
-                  $mkdirprog -m$different_mode -p -- "$tmpdir" && {
-                    ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
-                    test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
-                  }
-                }
-             then posix_mkdir=:
-             fi
-             rmdir "$tmpdir/d" "$tmpdir"
-           else
-             # Remove any dirs left behind by ancient mkdir implementations.
-             rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
-           fi
-           trap '' 0;;
-       esac;;
+       trap '' 0;;
     esac
 
     if
       $posix_mkdir && (
-       umask $mkdir_umask &&
-       $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+        umask $mkdir_umask &&
+        $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
       )
     then :
     else
 
-      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # mkdir does not conform to POSIX,
       # or it failed possibly due to a race condition.  Create the
       # directory the slow way, step by step, checking for races as we go.
 
       case $dstdir in
-       /*) prefix='/';;
-       -*) prefix='./';;
-       *)  prefix='';;
+        /*) prefix='/';;
+        [-=\(\)!]*) prefix='./';;
+        *)  prefix='';;
       esac
 
-      eval "$initialize_posix_glob"
-
       oIFS=$IFS
       IFS=/
-      $posix_glob set -f
+      set -f
       set fnord $dstdir
       shift
-      $posix_glob set +f
+      set +f
       IFS=$oIFS
 
       prefixes=
 
       for d
       do
-       test -z "$d" && continue
-
-       prefix=$prefix$d
-       if test -d "$prefix"; then
-         prefixes=
-       else
-         if $posix_mkdir; then
-           (umask=$mkdir_umask &&
-            $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
-           # Don't fail if two instances are running concurrently.
-           test -d "$prefix" || exit 1
-         else
-           case $prefix in
-             *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
-             *) qprefix=$prefix;;
-           esac
-           prefixes="$prefixes '$qprefix'"
-         fi
-       fi
-       prefix=$prefix/
+        test X"$d" = X && continue
+
+        prefix=$prefix$d
+        if test -d "$prefix"; then
+          prefixes=
+        else
+          if $posix_mkdir; then
+            (umask $mkdir_umask &&
+             $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+            # Don't fail if two instances are running concurrently.
+            test -d "$prefix" || exit 1
+          else
+            case $prefix in
+              *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+              *) qprefix=$prefix;;
+            esac
+            prefixes="$prefixes '$qprefix'"
+          fi
+        fi
+        prefix=$prefix/
       done
 
       if test -n "$prefixes"; then
-       # Don't fail if two instances are running concurrently.
-       (umask $mkdir_umask &&
-        eval "\$doit_exec \$mkdirprog $prefixes") ||
-         test -d "$dstdir" || exit 1
-       obsolete_mkdir_used=true
+        # Don't fail if two instances are running concurrently.
+        (umask $mkdir_umask &&
+         eval "\$doit_exec \$mkdirprog $prefixes") ||
+          test -d "$dstdir" || exit 1
+        obsolete_mkdir_used=true
       fi
     fi
   fi
@@ -451,14 +433,25 @@ do
   else
 
     # Make a couple of temp file names in the proper directory.
-    dsttmp=$dstdir/_inst.$$_
-    rmtmp=$dstdir/_rm.$$_
+    dsttmp=${dstdirslash}_inst.$$_
+    rmtmp=${dstdirslash}_rm.$$_
 
     # Trap to clean up those temp files at exit.
     trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
 
     # Copy the file name to the temp name.
-    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+    (umask $cp_umask &&
+     { test -z "$stripcmd" || {
+        # Create $dsttmp read-write so that cp doesn't create it read-only,
+        # which would cause strip to fail.
+        if test -z "$doit"; then
+          : >"$dsttmp" # No need to fork-exec 'touch'.
+        else
+          $doit touch "$dsttmp"
+        fi
+       }
+     } &&
+     $doit_exec $cpprog "$src" "$dsttmp") &&
 
     # and set any options; do chmod last to preserve setuid bits.
     #
@@ -473,15 +466,12 @@ do
 
     # If -C, don't bother to copy if it wouldn't change the file.
     if $copy_on_change &&
-       old=`LC_ALL=C ls -dlL "$dst"    2>/dev/null` &&
-       new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` &&
-
-       eval "$initialize_posix_glob" &&
-       $posix_glob set -f &&
+       old=`LC_ALL=C ls -dlL "$dst"     2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"  2>/dev/null` &&
+       set -f &&
        set X $old && old=:$2:$4:$5:$6 &&
        set X $new && new=:$2:$4:$5:$6 &&
-       $posix_glob set +f &&
-
+       set +f &&
        test "$old" = "$new" &&
        $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
     then
@@ -494,24 +484,24 @@ do
       # to itself, or perhaps because mv is so ancient that it does not
       # support -f.
       {
-       # Now remove or move aside any old file at destination location.
-       # We try this two ways since rm can't unlink itself on some
-       # systems and the destination file might be busy for other
-       # reasons.  In this case, the final cleanup might fail but the new
-       # file should still install successfully.
-       {
-         test ! -f "$dst" ||
-         $doit $rmcmd -f "$dst" 2>/dev/null ||
-         { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
-           { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
-         } ||
-         { echo "$0: cannot unlink or rename $dst" >&2
-           (exit 1); exit 1
-         }
-       } &&
-
-       # Now rename the file to the real destination.
-       $doit $mvcmd "$dsttmp" "$dst"
+        # Now remove or move aside any old file at destination location.
+        # We try this two ways since rm can't unlink itself on some
+        # systems and the destination file might be busy for other
+        # reasons.  In this case, the final cleanup might fail but the new
+        # file should still install successfully.
+        {
+          test ! -f "$dst" ||
+          $doit $rmcmd -f "$dst" 2>/dev/null ||
+          { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+            { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+          } ||
+          { echo "$0: cannot unlink or rename $dst" >&2
+            (exit 1); exit 1
+          }
+        } &&
+
+        # Now rename the file to the real destination.
+        $doit $mvcmd "$dsttmp" "$dst"
       }
     fi || exit 1
 
@@ -520,9 +510,9 @@ do
 done
 
 # Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
+# eval: (add-hook 'before-save-hook 'time-stamp)
 # time-stamp-start: "scriptversion="
 # time-stamp-format: "%:y-%02m-%02d.%02H"
-# time-stamp-time-zone: "UTC"
+# time-stamp-time-zone: "UTC0"
 # time-stamp-end: "; # UTC"
-# End:
+# End:
\ No newline at end of file
index 2814259..a442892 100755 (executable)
@@ -43,7 +43,7 @@ if test -f $ManPage ; then : ; else
     echo "source manual page file must exist"
     exit 1
 fi
-if test -d $Dir ; then : ; else
+if test -d "$Dir" ; then : ; else
     echo "target directory must exist"
     exit 1
 fi
@@ -99,7 +99,7 @@ SrcDir=`dirname $ManPage`
 ### Process Page to Create Target Pages
 ###
 
-Specials="DString Thread Notifier RegExp library packagens pkgMkIndex safesock"
+Specials="DString Thread Notifier RegExp library packagens pkgMkIndex safesock FindPhoto FontId MeasureChar"
 for n in $Specials; do
     if [ "$Name" = "$n" ] ; then
        Names="$n $Names"
@@ -109,15 +109,15 @@ done
 First=""
 for Target in $Names; do
     Target=$Target.$Section$Suffix
-    rm -f $Dir/$Target $Dir/$Target.*
+    rm -f "$Dir/$Target" "$Dir/$Target.*"
     if test -z "$First" ; then
        First=$Target
        sed -e "/man\.macros/r $SrcDir/man.macros" -e "/man\.macros/d" \
-           $ManPage > $Dir/$First
-       chmod 644 $Dir/$First
-       $Gzip $Dir/$First
+           $ManPage > "$Dir/$First"
+       chmod 644 "$Dir/$First"
+       $Gzip "$Dir/$First"
     else
-       ln $SymOrLoc$First$Gz $Dir/$Target$Gz
+       ln $SymOrLoc"$First$Gz" "$Dir/$Target$Gz"
     fi
 done
 
index 0e146e4..27b7540 100644 (file)
@@ -293,10 +293,6 @@ AC_DEFUN([SC_LOAD_TCLCONFIG], [
         AC_MSG_RESULT([could not find ${TCL_BIN_DIR}/tclConfig.sh])
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FILE=\"${TCL_LIB_FILE}\""
-    eval "TCL_STUB_LIB_FILE=\"${TCL_STUB_LIB_FILE}\""
-
     # If the TCL_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TCL_LIB_SPEC will be set to the value
@@ -330,12 +326,6 @@ AC_DEFUN([SC_LOAD_TCLCONFIG], [
        esac
     fi
 
-    # eval is required to do the TCL_DBGX substitution
-    eval "TCL_LIB_FLAG=\"${TCL_LIB_FLAG}\""
-    eval "TCL_LIB_SPEC=\"${TCL_LIB_SPEC}\""
-    eval "TCL_STUB_LIB_FLAG=\"${TCL_STUB_LIB_FLAG}\""
-    eval "TCL_STUB_LIB_SPEC=\"${TCL_STUB_LIB_SPEC}\""
-
     AC_SUBST(TCL_VERSION)
     AC_SUBST(TCL_PATCH_LEVEL)
     AC_SUBST(TCL_BIN_DIR)
@@ -376,10 +366,6 @@ AC_DEFUN([SC_LOAD_TKCONFIG], [
         AC_MSG_RESULT([could not find ${TK_BIN_DIR}/tkConfig.sh])
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FILE=\"${TK_LIB_FILE}\""
-    eval "TK_STUB_LIB_FILE=\"${TK_STUB_LIB_FILE}\""
-
     # If the TK_BIN_DIR is the build directory (not the install directory),
     # then set the common variable name to the value of the build variables.
     # For example, the variable TK_LIB_SPEC will be set to the value
@@ -413,12 +399,6 @@ AC_DEFUN([SC_LOAD_TKCONFIG], [
        esac
     fi
 
-    # eval is required to do the TK_DBGX substitution
-    eval "TK_LIB_FLAG=\"${TK_LIB_FLAG}\""
-    eval "TK_LIB_SPEC=\"${TK_LIB_SPEC}\""
-    eval "TK_STUB_LIB_FLAG=\"${TK_STUB_LIB_FLAG}\""
-    eval "TK_STUB_LIB_SPEC=\"${TK_STUB_LIB_SPEC}\""
-
     AC_SUBST(TK_VERSION)
     AC_SUBST(TK_BIN_DIR)
     AC_SUBST(TK_SRC_DIR)
@@ -531,14 +511,6 @@ AC_DEFUN([SC_ENABLE_SHARED], [
        AC_HELP_STRING([--enable-shared],
            [build and link with shared libraries (default: on)]),
        [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
     if test "$tcl_ok" = "yes" ; then
        AC_MSG_RESULT([shared])
        SHARED_BUILD=1
@@ -730,8 +702,6 @@ AC_DEFUN([SC_ENABLE_THREADS], [
 #                              Sets to $(CFLAGS_OPTIMIZE) if false
 #              LDFLAGS_DEFAULT Sets to $(LDFLAGS_DEBUG) if true
 #                              Sets to $(LDFLAGS_OPTIMIZE) if false
-#              DBGX            Formerly used as debug library extension;
-#                              always blank now.
 #------------------------------------------------------------------------
 
 AC_DEFUN([SC_ENABLE_SYMBOLS], [
@@ -741,7 +711,6 @@ AC_DEFUN([SC_ENABLE_SYMBOLS], [
            [build with debugging symbols (default: off)]),
        [tcl_ok=$enableval], [tcl_ok=no])
 # FIXME: Currently, LDFLAGS_DEFAULT is not used, it should work like CFLAGS_DEFAULT.
-    DBGX=""
     if test "$tcl_ok" = "no"; then
        CFLAGS_DEFAULT='$(CFLAGS_OPTIMIZE)'
        LDFLAGS_DEFAULT='$(LDFLAGS_OPTIMIZE)'
@@ -1103,7 +1072,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
     CFLAGS_DEBUG=-g
     AS_IF([test "$GCC" = yes], [
        CFLAGS_OPTIMIZE=-O2
-       CFLAGS_WARNING="-Wall"
+       CFLAGS_WARNING="-Wall -Wpointer-arith"
     ], [
        CFLAGS_OPTIMIZE=-O
        CFLAGS_WARNING=""
@@ -1212,7 +1181,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            ;;
-       CYGWIN_*|MINGW32*)
+       CYGWIN_*|MINGW32_*|MSYS_*)
            SHLIB_CFLAGS=""
            SHLIB_LD='${CC} -shared'
            SHLIB_SUFFIX=".dll"
@@ -1223,7 +1192,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
            TCL_NEEDS_EXP_FILE=1
-           TCL_EXPORT_FILE_SUFFIX='${VERSION}\$\{DBGX\}.dll.a'
+           TCL_EXPORT_FILE_SUFFIX='${VERSION}.dll.a'
            SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -Wl,--out-implib,\$[@].a"
            AC_CACHE_CHECK(for Cygwin version of gcc,
                ac_cv_cygwin,
@@ -1312,7 +1281,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
                            do64bit_ok=yes
                            SHLIB_LD='${CC} -shared'
                            AS_IF([test $doRpath = yes], [
-                               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+                               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
                            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
                            ;;
                        *)
@@ -1347,7 +1316,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS=""
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            ;;
        IRIX-6.*)
@@ -1358,7 +1327,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS=""
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [
                CFLAGS="$CFLAGS -mabi=n32"
@@ -1384,7 +1353,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS=""
            AC_LIBOBJ(mkstemp)
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
 
            # Check to enable 64-bit flags for compiler/linker
@@ -1415,7 +1384,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS="-ldl"
            LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
            AS_IF([test $do64bit = yes], [
@@ -1447,8 +1416,8 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS="-mshared -ldl"
            LD_FLAGS="-Wl,--export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            ;;
        MP-RAS-02*)
            SHLIB_CFLAGS="-K PIC"
@@ -1486,7 +1455,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_OBJS="tclLoadDl.o"
            DL_LIBS=""
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so${SHLIB_VERSION}'
            LDFLAGS="-Wl,-export-dynamic"
@@ -1510,7 +1479,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_LIBS=""
            LDFLAGS="$LDFLAGS -export-dynamic"
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
            AS_IF([test "${TCL_THREADS}" = "1"], [
                # The -pthread needs to go in the CFLAGS, not LIBS
@@ -1527,10 +1496,9 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            SHLIB_SUFFIX=".so"
            DL_OBJS="tclLoadDl.o"
            DL_LIBS=""
-           LDFLAGS=""
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
-               LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
+               LD_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'])
            AS_IF([test "${TCL_THREADS}" = "1"], [
                # The -pthread needs to go in the LDFLAGS, not LIBS
                LIBS=`echo $LIBS | sed s/-pthread//`
@@ -1619,6 +1587,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
                AC_DEFINE(MODULE_SCOPE, [__private_extern__],
                    [Compiler support for module scope symbols])
+               tcl_cv_cc_visibility_hidden=yes
            ])
            CC_SEARCH_FLAGS=""
            LD_SEARCH_FLAGS=""
@@ -1733,7 +1702,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
            DL_OBJS="tclLoadDl.o"
            DL_LIBS=""
            AS_IF([test $doRpath = yes], [
-               CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
+               CC_SEARCH_FLAGS='"-Wl,-rpath,${LIB_RUNTIME_DIR}"'
                LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
            AS_IF([test "$GCC" = yes], [CFLAGS="$CFLAGS -mieee"], [
                CFLAGS="$CFLAGS -DHAVE_TZSET -std1 -ieee"])
@@ -2009,7 +1978,7 @@ dnl # preprocessing tests use only CPPFLAGS.
        case $system in
            AIX-*) ;;
            BSD/OS*) ;;
-           CYGWIN_*|MINGW32_*) ;;
+           CYGWIN_*|MINGW32_*|MSYS_*) ;;
            IRIX*) ;;
            NetBSD-*|DragonFly-*|FreeBSD-*|OpenBSD-*) ;;
            Darwin-*) ;;
@@ -2030,7 +1999,7 @@ dnl # preprocessing tests use only CPPFLAGS.
 
     AS_IF([test "${SHARED_BUILD}" = 1 -a "${SHLIB_SUFFIX}" != ""], [
         LIB_SUFFIX=${SHARED_LIB_SUFFIX}
-        MAKE_LIB='${SHLIB_LD} -o [$]@ ${OBJS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
+        MAKE_LIB='${SHLIB_LD} -o [$]@ ${OBJS} ${LDFLAGS} ${SHLIB_LD_LIBS} ${TCL_SHLIB_LD_EXTRAS} ${TK_SHLIB_LD_EXTRAS} ${LD_SEARCH_FLAGS}'
         AS_IF([test "${SHLIB_SUFFIX}" = ".dll"], [
             INSTALL_LIB='$(INSTALL_LIBRARY) $(LIB_FILE) "$(BIN_INSTALL_DIR)/$(LIB_FILE)";if test -f $(LIB_FILE).a; then $(INSTALL_DATA) $(LIB_FILE).a "$(LIB_INSTALL_DIR)"; fi;'
             DLL_INSTALL_DIR="\$(BIN_INSTALL_DIR)"
@@ -2137,13 +2106,13 @@ dnl # preprocessing tests use only CPPFLAGS.
 #
 #      Defines some of the following vars:
 #              NO_DIRENT_H
+#              NO_FLOAT_H
 #              NO_VALUES_H
 #              NO_STDLIB_H
 #              NO_STRING_H
 #              NO_SYS_WAIT_H
 #              NO_DLFCN_H
 #              HAVE_SYS_PARAM_H
-#
 #              HAVE_STRING_H ?
 #
 #--------------------------------------------------------------------
@@ -2362,7 +2331,7 @@ AC_DEFUN([SC_TIME_HANDLER], [
     fi
 
     AC_CACHE_CHECK([tm_gmtoff in struct tm], tcl_cv_member_tm_gmtoff, [
-       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; tm.tm_gmtoff;],
+       AC_TRY_COMPILE([#include <time.h>], [struct tm tm; (void)tm.tm_gmtoff;],
            tcl_cv_member_tm_gmtoff=yes, tcl_cv_member_tm_gmtoff=no)])
     if test $tcl_cv_member_tm_gmtoff = yes ; then
        AC_DEFINE(HAVE_TM_GMTOFF, 1, [Should we use the tm_gmtoff field of struct tm?])
@@ -2651,7 +2620,10 @@ AC_DEFUN([SC_TCL_CHECK_BROKEN_FUNC],[
     AC_CHECK_FUNC($1, tcl_ok=1, tcl_ok=0)
     if test ["$tcl_ok"] = 1; then
        AC_CACHE_CHECK([proper ]$1[ implementation], [tcl_cv_]$1[_unbroken],
-           AC_TRY_RUN([[int main() {]$2[}]],[tcl_cv_]$1[_unbroken]=ok,
+           AC_TRY_RUN([[
+#include <stdlib.h>
+#include <string.h>
+int main() {]$2[}]],[tcl_cv_]$1[_unbroken]=ok,
                [tcl_cv_]$1[_unbroken]=broken,[tcl_cv_]$1[_unbroken]=unknown))
        if test ["$tcl_cv_]$1[_unbroken"] = "ok"; then
            tcl_ok=1
index e050a30..1758836 100644 (file)
@@ -4,7 +4,7 @@
 
 Name:          tcl
 Summary:       Tcl scripting language development environment
-Version:       8.6.10
+Version:       8.6.11
 Release:       2
 License:       BSD
 Group:         Development/Languages
index 88e6b50..fea9494 100644 (file)
@@ -98,7 +98,7 @@ dlopen(
     const char *path,
     int mode)
 {
-    register ModulePtr mp;
+    ModulePtr mp;
     static void *mainModule;
 
     /*
@@ -134,7 +134,7 @@ dlopen(
        return NULL;
     }
 
-    mp->name = malloc((unsigned) (strlen(path) + 1));
+    mp->name = malloc(strlen(path) + 1);
     strcpy(mp->name, path);
 
     /*
@@ -191,7 +191,7 @@ dlopen(
      */
 
     if (mode & RTLD_GLOBAL) {
-       register ModulePtr mp1;
+       ModulePtr mp1;
 
        for (mp1 = mp->next; mp1; mp1 = mp1->next) {
            if (loadbind(0, mp1->entry, mp->entry) == -1) {
@@ -243,7 +243,7 @@ static void
 caterr(
     char *s)
 {
-    register char *p = s;
+    char *p = s;
 
     while (*p >= '0' && *p <= '9') {
        p++;
@@ -282,9 +282,9 @@ dlsym(
     void *handle,
     const char *symbol)
 {
-    register ModulePtr mp = (ModulePtr)handle;
-    register ExportPtr ep;
-    register int i;
+    ModulePtr mp = (ModulePtr)handle;
+    ExportPtr ep;
+    int i;
 
     /*
      * Could speed up the search, but I assume that one assigns the result to
@@ -317,9 +317,9 @@ int
 dlclose(
     void *handle)
 {
-    register ModulePtr mp = (ModulePtr)handle;
+    ModulePtr mp = (ModulePtr)handle;
     int result;
-    register ModulePtr mp1;
+    ModulePtr mp1;
 
     if (--mp->refCnt > 0) {
        return 0;
@@ -343,8 +343,8 @@ dlclose(
     }
 
     if (mp->exports) {
-       register ExportPtr ep;
-       register int i;
+       ExportPtr ep;
+       int i;
        for (ep = mp->exports, i = mp->nExports; i; i--, ep++) {
            if (ep->name) {
                free(ep->name);
@@ -541,7 +541,7 @@ readExports(
            tmpsym[SYMNMLEN] = '\0';
            symname = tmpsym;
        }
-       ep->name = malloc((unsigned) (strlen(symname) + 1));
+       ep->name = malloc(strlen(symname) + 1);
        strcpy(ep->name, symname);
        ep->addr = (void *)((unsigned long)
                mp->entry + ls->l_value - shdata.s_vaddr);
index e998bf9..7d462da 100644 (file)
@@ -292,8 +292,9 @@ TclpDlopen(
        *loadHandle = newHandle;
        result = TCL_OK;
     } else {
-       Tcl_Obj *errObj = Tcl_NewObj();
+       Tcl_Obj *errObj;
 
+       TclNewObj(errObj);
        if (errMsg != NULL) {
            Tcl_AppendToObj(errObj, errMsg, -1);
        }
index 27f2710..fc01616 100644 (file)
@@ -99,6 +99,8 @@ typedef struct TtyAttrs {
 static int             FileBlockModeProc(ClientData instanceData, int mode);
 static int             FileCloseProc(ClientData instanceData,
                            Tcl_Interp *interp);
+static int             FileClose2Proc(ClientData instanceData,
+                           Tcl_Interp *interp, int flags);
 static int             FileGetHandleProc(ClientData instanceData,
                            int direction, ClientData *handlePtr);
 static int             FileInputProc(ClientData instanceData, char *buf,
@@ -144,7 +146,7 @@ static const Tcl_ChannelType fileChannelType = {
     NULL,                      /* Get option proc. */
     FileWatchProc,             /* Initialize notifier. */
     FileGetHandleProc,         /* Get OS handles out of channel. */
-    NULL,                      /* close2proc. */
+    FileClose2Proc,                    /* close2proc. */
     FileBlockModeProc,         /* Set blocking or non-blocking mode.*/
     NULL,                      /* flush proc. */
     NULL,                      /* handler proc. */
@@ -170,7 +172,7 @@ static const Tcl_ChannelType ttyChannelType = {
     TtyGetOptionProc,          /* Get option proc. */
     FileWatchProc,             /* Initialize notifier. */
     FileGetHandleProc,         /* Get OS handles out of channel. */
-    NULL,                      /* close2proc. */
+    FileClose2Proc,                    /* close2proc. */
     FileBlockModeProc,         /* Set blocking or non-blocking mode.*/
     NULL,                      /* flush proc. */
     NULL,                      /* handler proc. */
@@ -197,7 +199,6 @@ static const Tcl_ChannelType ttyChannelType = {
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 FileBlockModeProc(
     ClientData instanceData,   /* File state. */
@@ -347,6 +348,17 @@ FileCloseProc(
     ckfree(fsPtr);
     return errorCode;
 }
+static int
+FileClose2Proc(
+    ClientData instanceData,   /* File state. */
+    Tcl_Interp *interp,                /* For error reporting - unused. */
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return FileCloseProc(instanceData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
index 2a68f7f..00e9737 100644 (file)
@@ -49,7 +49,7 @@
 
 #ifdef TCL_THREADS
 
-typedef struct ThreadSpecificData {
+typedef struct {
     struct passwd pwd;
 #if defined(HAVE_GETPWNAM_R_5) || defined(HAVE_GETPWUID_R_5)
 #define NEED_PW_CLEANER 1
@@ -118,10 +118,10 @@ static int                CopyString(const char *src, char *buf, int buflen);
 #endif
 
 #ifdef NEED_PW_CLEANER
-static void            FreePwBuf(ClientData ignored);
+static void            FreePwBuf(ClientData dummy);
 #endif
 #ifdef NEED_GR_CLEANER
-static void            FreeGrBuf(ClientData ignored);
+static void            FreeGrBuf(ClientData dummy);
 #endif
 #endif /* TCL_THREADS */
 \f
@@ -201,7 +201,7 @@ TclpGetPwNam(
        if (tsdPtr->pbuflen < 1) {
            tsdPtr->pbuflen = 1024;
        }
-       tsdPtr->pbuf = ckalloc(tsdPtr->pbuflen);
+       tsdPtr->pbuf = (char *)ckalloc(tsdPtr->pbuflen);
        Tcl_CreateThreadExitHandler(FreePwBuf, NULL);
     }
     while (1) {
@@ -214,7 +214,7 @@ TclpGetPwNam(
            return NULL;
        }
        tsdPtr->pbuflen *= 2;
-       tsdPtr->pbuf = ckrealloc(tsdPtr->pbuf, tsdPtr->pbuflen);
+       tsdPtr->pbuf = (char *)ckrealloc(tsdPtr->pbuf, tsdPtr->pbuflen);
     }
     return (pwPtr != NULL ? &tsdPtr->pwd : NULL);
 
@@ -281,7 +281,7 @@ TclpGetPwUid(
        if (tsdPtr->pbuflen < 1) {
            tsdPtr->pbuflen = 1024;
        }
-       tsdPtr->pbuf = ckalloc(tsdPtr->pbuflen);
+       tsdPtr->pbuf = (char *)ckalloc(tsdPtr->pbuflen);
        Tcl_CreateThreadExitHandler(FreePwBuf, NULL);
     }
     while (1) {
@@ -294,7 +294,7 @@ TclpGetPwUid(
            return NULL;
        }
        tsdPtr->pbuflen *= 2;
-       tsdPtr->pbuf = ckrealloc(tsdPtr->pbuf, tsdPtr->pbuflen);
+       tsdPtr->pbuf = (char *)ckrealloc(tsdPtr->pbuf, tsdPtr->pbuflen);
     }
     return (pwPtr != NULL ? &tsdPtr->pwd : NULL);
 
@@ -336,9 +336,10 @@ TclpGetPwUid(
 #ifdef NEED_PW_CLEANER
 static void
 FreePwBuf(
-    ClientData ignored)
+    ClientData dummy)
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
 
     ckfree(tsdPtr->pbuf);
 }
@@ -384,7 +385,7 @@ TclpGetGrNam(
        if (tsdPtr->gbuflen < 1) {
            tsdPtr->gbuflen = 1024;
        }
-       tsdPtr->gbuf = ckalloc(tsdPtr->gbuflen);
+       tsdPtr->gbuf = (char *)ckalloc(tsdPtr->gbuflen);
        Tcl_CreateThreadExitHandler(FreeGrBuf, NULL);
     }
     while (1) {
@@ -397,7 +398,7 @@ TclpGetGrNam(
            return NULL;
        }
        tsdPtr->gbuflen *= 2;
-       tsdPtr->gbuf = ckrealloc(tsdPtr->gbuf, tsdPtr->gbuflen);
+       tsdPtr->gbuf = (char *)ckrealloc(tsdPtr->gbuf, tsdPtr->gbuflen);
     }
     return (grPtr != NULL ? &tsdPtr->grp : NULL);
 
@@ -464,7 +465,7 @@ TclpGetGrGid(
        if (tsdPtr->gbuflen < 1) {
            tsdPtr->gbuflen = 1024;
        }
-       tsdPtr->gbuf = ckalloc(tsdPtr->gbuflen);
+       tsdPtr->gbuf = (char *)ckalloc(tsdPtr->gbuflen);
        Tcl_CreateThreadExitHandler(FreeGrBuf, NULL);
     }
     while (1) {
@@ -477,7 +478,7 @@ TclpGetGrGid(
            return NULL;
        }
        tsdPtr->gbuflen *= 2;
-       tsdPtr->gbuf = ckrealloc(tsdPtr->gbuf, tsdPtr->gbuflen);
+       tsdPtr->gbuf = (char *)ckrealloc(tsdPtr->gbuf, tsdPtr->gbuflen);
     }
     return (grPtr != NULL ? &tsdPtr->grp : NULL);
 
@@ -519,9 +520,10 @@ TclpGetGrGid(
 #ifdef NEED_GR_CLEANER
 static void
 FreeGrBuf(
-    ClientData ignored)
+    ClientData dummy)
 {
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
+    (void)dummy;
 
     ckfree(tsdPtr->gbuf);
 }
@@ -554,17 +556,17 @@ TclpGetHostByName(
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
 #if defined(HAVE_GETHOSTBYNAME_R_5)
-    int h_errno;
+    int local_errno;
 
     return gethostbyname_r(name, &tsdPtr->hent, tsdPtr->hbuf,
-                          sizeof(tsdPtr->hbuf), &h_errno);
+                          sizeof(tsdPtr->hbuf), &local_errno);
 
 #elif defined(HAVE_GETHOSTBYNAME_R_6)
     struct hostent *hePtr = NULL;
-    int h_errno, result;
+    int local_errno, result;
 
     result = gethostbyname_r(name, &tsdPtr->hent, tsdPtr->hbuf,
-           sizeof(tsdPtr->hbuf), &hePtr, &h_errno);
+           sizeof(tsdPtr->hbuf), &hePtr, &local_errno);
     return (result == 0) ? hePtr : NULL;
 
 #elif defined(HAVE_GETHOSTBYNAME_R_3)
@@ -624,17 +626,17 @@ TclpGetHostByAddr(
     ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
 #if defined(HAVE_GETHOSTBYADDR_R_7)
-    int h_errno;
+    int local_errno;
 
     return gethostbyaddr_r(addr, length, type, &tsdPtr->hent, tsdPtr->hbuf,
-           sizeof(tsdPtr->hbuf), &h_errno);
+           sizeof(tsdPtr->hbuf), &local_errno);
 
 #elif defined(HAVE_GETHOSTBYADDR_R_8)
     struct hostent *hePtr;
-    int h_errno;
+    int local_errno;
 
     return (gethostbyaddr_r(addr, length, type, &tsdPtr->hent, tsdPtr->hbuf,
-               sizeof(tsdPtr->hbuf), &hePtr, &h_errno) == 0)
+               sizeof(tsdPtr->hbuf), &hePtr, &local_errno) == 0)
            ? &tsdPtr->hent : NULL;
 #else
 #define NEED_COPYHOSTENT 1
@@ -685,8 +687,8 @@ CopyGrp(
     char *buf,
     int buflen)
 {
-    register char *p = buf;
-    register int copied, len = 0;
+    char *p = buf;
+    int copied, len = 0;
 
     /*
      * Copy username.
@@ -887,7 +889,7 @@ CopyArray(
     int buflen)                        /* Size of buffer. */
 {
     int i, j, len = 0;
-    char *p, **new;
+    char *p, **newBuffer;
 
     if (src == NULL) {
        return 0;
@@ -903,7 +905,7 @@ CopyArray(
        return -1;
     }
 
-    new = (char **) buf;
+    newBuffer = (char **)buf;
     p = buf + len;
 
     for (j = 0; j < i; j++) {
@@ -914,10 +916,10 @@ CopyArray(
            return -1;
        }
        memcpy(p, src[j], sz);
-       new[j] = p;
+       newBuffer[j] = p;
        p = buf + len;
     }
-    new[j] = NULL;
+    newBuffer[j] = NULL;
 
     return len;
 }
index ae20ee0..8660818 100644 (file)
@@ -1369,7 +1369,7 @@ GetGroupAttribute(
     groupPtr = TclpGetGrGid(statBuf.st_gid);
 
     if (groupPtr == NULL) {
-       *attributePtrPtr = Tcl_NewIntObj((int) statBuf.st_gid);
+       TclNewIntObj(*attributePtrPtr, (int) statBuf.st_gid);
     } else {
        Tcl_DString ds;
        const char *utf;
@@ -1423,7 +1423,7 @@ GetOwnerAttribute(
     pwPtr = TclpGetPwUid(statBuf.st_uid);
 
     if (pwPtr == NULL) {
-       *attributePtrPtr = Tcl_NewIntObj((int) statBuf.st_uid);
+       TclNewIntObj(*attributePtrPtr, (int) statBuf.st_uid);
     } else {
        Tcl_DString ds;
 
@@ -1841,7 +1841,7 @@ GetModeFromPermString(
                /* who */
                switch (*(modeStringPtr+n+i)) {
                case 'u':
-                   who |= 0x9c0;
+                   who |= 0x9C0;
                    continue;
                case 'g':
                    who |= 0x438;
@@ -1850,13 +1850,13 @@ GetModeFromPermString(
                    who |= 0x207;
                    continue;
                case 'a':
-                   who |= 0xfff;
+                   who |= 0xFFF;
                    continue;
                }
            }
            who_found = 1;
            if (who == 0) {
-               who = 0xfff;
+               who = 0xFFF;
            }
            if (!op_found) {
                /* op */
@@ -1889,7 +1889,7 @@ GetModeFromPermString(
                what |= 0x49;
                continue;
            case 's':
-               what |= 0xc00;
+               what |= 0xC00;
                continue;
            case 't':
                what |= 0x200;
@@ -2341,7 +2341,7 @@ GetUnixFileAttributes(
        return TCL_ERROR;
     }
 
-    *attributePtrPtr = Tcl_NewIntObj((fileAttributes&attributeArray[objIndex])!=0);
+    TclNewIntObj(*attributePtrPtr, (fileAttributes&attributeArray[objIndex])!=0);
 
     return TCL_OK;
 }
index 5684b16..35046a5 100644 (file)
@@ -98,7 +98,7 @@ TclpFindExecutable(
      */
 
     while (1) {
-       while (TclIsSpaceProc(*p)) {
+       while (TclIsSpaceProcM(*p)) {
            p++;
        }
        name = p;
@@ -1116,7 +1116,7 @@ TclNativeCreateNativeRep(
     }
     Tcl_DecrRefCount(validPathPtr);
     nativePathPtr = ckalloc(len);
-    memcpy(nativePathPtr, Tcl_DStringValue(&ds), (size_t) len);
+    memcpy(nativePathPtr, Tcl_DStringValue(&ds), len);
 
     Tcl_DStringFree(&ds);
     return nativePathPtr;
index aac8a8d..72039ac 100644 (file)
 #endif
 
 #ifdef __CYGWIN__
+#ifdef __cplusplus
+extern "C" {
+#endif
+#ifdef __clang__
+#pragma clang diagnostic ignored "-Wignored-attributes"
+#endif
 DLLIMPORT extern __stdcall unsigned char GetVersionExW(void *);
 DLLIMPORT extern __stdcall void *GetModuleHandleW(const void *);
 DLLIMPORT extern __stdcall void FreeLibrary(void *);
 DLLIMPORT extern __stdcall void *GetProcAddress(void *, const char *);
 DLLIMPORT extern __stdcall void GetSystemInfo(void *);
-
-#define NUMPLATFORMS 4
-static const char *const platforms[NUMPLATFORMS] = {
-    "Win32s", "Windows 95", "Windows NT", "Windows CE"
-};
+#ifdef __cplusplus
+}
+#endif
 
 #define NUMPROCESSORS 11
 static const char *const processors[NUMPROCESSORS] = {
@@ -52,29 +56,29 @@ static const char *const processors[NUMPROCESSORS] = {
 
 typedef struct {
   union {
-    DWORD  dwOemId;
+    unsigned int  dwOemId;
     struct {
       int wProcessorArchitecture;
       int wReserved;
     };
   };
-  DWORD     dwPageSize;
+  unsigned int     dwPageSize;
   void *lpMinimumApplicationAddress;
   void *lpMaximumApplicationAddress;
   void *dwActiveProcessorMask;
-  DWORD     dwNumberOfProcessors;
-  DWORD     dwProcessorType;
-  DWORD     dwAllocationGranularity;
+  unsigned int     dwNumberOfProcessors;
+  unsigned int     dwProcessorType;
+  unsigned int     dwAllocationGranularity;
   int      wProcessorLevel;
   int      wProcessorRevision;
 } SYSTEM_INFO;
 
 typedef struct {
-  DWORD dwOSVersionInfoSize;
-  DWORD dwMajorVersion;
-  DWORD dwMinorVersion;
-  DWORD dwBuildNumber;
-  DWORD dwPlatformId;
+  unsigned int dwOSVersionInfoSize;
+  unsigned int dwMajorVersion;
+  unsigned int dwMinorVersion;
+  unsigned int dwBuildNumber;
+  unsigned int dwPlatformId;
   wchar_t szCSDVersion[128];
 } OSVERSIONINFOW;
 #endif
@@ -115,7 +119,7 @@ static char pkgPath[sizeof(TCL_PACKAGE_PATH)+200] = TCL_PACKAGE_PATH;
  * first list checked for a mapping from env encoding to Tcl encoding name.
  */
 
-typedef struct LocaleTable {
+typedef struct {
     const char *lang;
     const char *encoding;
 } LocaleTable;
@@ -131,9 +135,9 @@ typedef struct LocaleTable {
  */
 
 static const LocaleTable localeTable[] = {
-           {"",                "iso8859-1"},
-                   {"ansi-1251",       "cp1251"},
-           {"ansi_x3.4-1968",  "iso8859-1"},
+    {"",               "iso8859-1"},
+    {"ansi-1251",      "cp1251"},
+    {"ansi_x3.4-1968", "iso8859-1"},
     {"ascii",          "ascii"},
     {"big5",           "big5"},
     {"cp1250",         "cp1250"},
@@ -170,61 +174,61 @@ static const LocaleTable localeTable[] = {
     {"euc-cn",         "euc-cn"},
     {"euc-jp",         "euc-jp"},
     {"euc-kr",         "euc-kr"},
-                   {"eucjp",           "euc-jp"},
-                   {"euckr",           "euc-kr"},
-                   {"euctw",           "euc-cn"},
+    {"eucjp",          "euc-jp"},
+    {"euckr",          "euc-kr"},
+    {"euctw",          "euc-cn"},
     {"gb12345",                "gb12345"},
     {"gb1988",         "gb1988"},
     {"gb2312",         "gb2312"},
-                   {"gb2312-1980",     "gb2312"},
+    {"gb2312-1980",    "gb2312"},
     {"gb2312-raw",     "gb2312-raw"},
-                   {"greek8",          "cp869"},
-           {"ibm1250",         "cp1250"},
-           {"ibm1251",         "cp1251"},
-           {"ibm1252",         "cp1252"},
-           {"ibm1253",         "cp1253"},
-           {"ibm1254",         "cp1254"},
-           {"ibm1255",         "cp1255"},
-           {"ibm1256",         "cp1256"},
-           {"ibm1257",         "cp1257"},
-           {"ibm1258",         "cp1258"},
-           {"ibm437",          "cp437"},
-           {"ibm737",          "cp737"},
-           {"ibm775",          "cp775"},
-           {"ibm850",          "cp850"},
-           {"ibm852",          "cp852"},
-           {"ibm855",          "cp855"},
-           {"ibm857",          "cp857"},
-           {"ibm860",          "cp860"},
-           {"ibm861",          "cp861"},
-           {"ibm862",          "cp862"},
-           {"ibm863",          "cp863"},
-           {"ibm864",          "cp864"},
-           {"ibm865",          "cp865"},
-           {"ibm866",          "cp866"},
-           {"ibm869",          "cp869"},
-           {"ibm874",          "cp874"},
-           {"ibm932",          "cp932"},
-           {"ibm936",          "cp936"},
-           {"ibm949",          "cp949"},
-           {"ibm950",          "cp950"},
-           {"iso-2022",        "iso2022"},
-           {"iso-2022-jp",     "iso2022-jp"},
-           {"iso-2022-kr",     "iso2022-kr"},
-           {"iso-8859-1",      "iso8859-1"},
-           {"iso-8859-10",     "iso8859-10"},
-           {"iso-8859-13",     "iso8859-13"},
-           {"iso-8859-14",     "iso8859-14"},
-           {"iso-8859-15",     "iso8859-15"},
-           {"iso-8859-16",     "iso8859-16"},
-           {"iso-8859-2",      "iso8859-2"},
-           {"iso-8859-3",      "iso8859-3"},
-           {"iso-8859-4",      "iso8859-4"},
-           {"iso-8859-5",      "iso8859-5"},
-           {"iso-8859-6",      "iso8859-6"},
-           {"iso-8859-7",      "iso8859-7"},
-           {"iso-8859-8",      "iso8859-8"},
-           {"iso-8859-9",      "iso8859-9"},
+    {"greek8",         "cp869"},
+    {"ibm1250",                "cp1250"},
+    {"ibm1251",                "cp1251"},
+    {"ibm1252",                "cp1252"},
+    {"ibm1253",                "cp1253"},
+    {"ibm1254",                "cp1254"},
+    {"ibm1255",                "cp1255"},
+    {"ibm1256",                "cp1256"},
+    {"ibm1257",                "cp1257"},
+    {"ibm1258",                "cp1258"},
+    {"ibm437",         "cp437"},
+    {"ibm737",         "cp737"},
+    {"ibm775",         "cp775"},
+    {"ibm850",         "cp850"},
+    {"ibm852",         "cp852"},
+    {"ibm855",         "cp855"},
+    {"ibm857",         "cp857"},
+    {"ibm860",         "cp860"},
+    {"ibm861",         "cp861"},
+    {"ibm862",         "cp862"},
+    {"ibm863",         "cp863"},
+    {"ibm864",         "cp864"},
+    {"ibm865",         "cp865"},
+    {"ibm866",         "cp866"},
+    {"ibm869",         "cp869"},
+    {"ibm874",         "cp874"},
+    {"ibm932",         "cp932"},
+    {"ibm936",         "cp936"},
+    {"ibm949",         "cp949"},
+    {"ibm950",         "cp950"},
+    {"iso-2022",       "iso2022"},
+    {"iso-2022-jp",    "iso2022-jp"},
+    {"iso-2022-kr",    "iso2022-kr"},
+    {"iso-8859-1",     "iso8859-1"},
+    {"iso-8859-10",    "iso8859-10"},
+    {"iso-8859-13",    "iso8859-13"},
+    {"iso-8859-14",    "iso8859-14"},
+    {"iso-8859-15",    "iso8859-15"},
+    {"iso-8859-16",    "iso8859-16"},
+    {"iso-8859-2",     "iso8859-2"},
+    {"iso-8859-3",     "iso8859-3"},
+    {"iso-8859-4",     "iso8859-4"},
+    {"iso-8859-5",     "iso8859-5"},
+    {"iso-8859-6",     "iso8859-6"},
+    {"iso-8859-7",     "iso8859-7"},
+    {"iso-8859-8",     "iso8859-8"},
+    {"iso-8859-9",     "iso8859-9"},
     {"iso2022",                "iso2022"},
     {"iso2022-jp",     "iso2022-jp"},
     {"iso2022-kr",     "iso2022-kr"},
@@ -242,47 +246,47 @@ static const LocaleTable localeTable[] = {
     {"iso8859-7",      "iso8859-7"},
     {"iso8859-8",      "iso8859-8"},
     {"iso8859-9",      "iso8859-9"},
-                   {"iso88591",        "iso8859-1"},
-                   {"iso885915",       "iso8859-15"},
-                   {"iso88592",        "iso8859-2"},
-                   {"iso88595",        "iso8859-5"},
-                   {"iso88596",        "iso8859-6"},
-                   {"iso88597",        "iso8859-7"},
-                   {"iso88598",        "iso8859-8"},
-                   {"iso88599",        "iso8859-9"},
+    {"iso88591",       "iso8859-1"},
+    {"iso885915",      "iso8859-15"},
+    {"iso88592",       "iso8859-2"},
+    {"iso88595",       "iso8859-5"},
+    {"iso88596",       "iso8859-6"},
+    {"iso88597",       "iso8859-7"},
+    {"iso88598",       "iso8859-8"},
+    {"iso88599",       "iso8859-9"},
 #ifdef hpux
-                   {"ja",              "shiftjis"},
+    {"ja",             "shiftjis"},
 #else
-                   {"ja",              "euc-jp"},
+    {"ja",             "euc-jp"},
 #endif
-                   {"ja_jp",           "euc-jp"},
-                   {"ja_jp.euc",       "euc-jp"},
-                   {"ja_jp.eucjp",     "euc-jp"},
-                   {"ja_jp.jis",       "iso2022-jp"},
-                   {"ja_jp.mscode",    "shiftjis"},
-                   {"ja_jp.sjis",      "shiftjis"},
-                   {"ja_jp.ujis",      "euc-jp"},
-                   {"japan",           "euc-jp"},
+    {"ja_jp",          "euc-jp"},
+       {"ja_jp.euc",   "euc-jp"},
+    {"ja_jp.eucjp",    "euc-jp"},
+    {"ja_jp.jis",      "iso2022-jp"},
+    {"ja_jp.mscode",   "shiftjis"},
+    {"ja_jp.sjis",     "shiftjis"},
+    {"ja_jp.ujis",     "euc-jp"},
+    {"japan",          "euc-jp"},
 #ifdef hpux
-                   {"japanese",        "shiftjis"},
+    {"japanese",       "shiftjis"},
 #else
-                   {"japanese",        "euc-jp"},
+    {"japanese",       "euc-jp"},
 #endif
-                   {"japanese-sjis",   "shiftjis"},
-                   {"japanese-ujis",   "euc-jp"},
-                   {"japanese.euc",    "euc-jp"},
-                   {"japanese.sjis",   "shiftjis"},
+    {"japanese-sjis",  "shiftjis"},
+    {"japanese-ujis",  "euc-jp"},
+    {"japanese.euc",   "euc-jp"},
+    {"japanese.sjis",  "shiftjis"},
     {"jis0201",                "jis0201"},
     {"jis0208",                "jis0208"},
     {"jis0212",                "jis0212"},
-                   {"jp_jp",           "shiftjis"},
-                   {"ko",              "euc-kr"},
-                   {"ko_kr",           "euc-kr"},
-                   {"ko_kr.euc",       "euc-kr"},
-                   {"ko_kw.euckw",     "euc-kr"},
+    {"jp_jp",          "shiftjis"},
+    {"ko",             "euc-kr"},
+    {"ko_kr",          "euc-kr"},
+    {"ko_kr.euc",      "euc-kr"},
+    {"ko_kw.euckw",    "euc-kr"},
     {"koi8-r",         "koi8-r"},
     {"koi8-u",         "koi8-u"},
-                   {"korean",          "euc-kr"},
+    {"korean",         "euc-kr"},
     {"ksc5601",                "ksc5601"},
     {"maccenteuro",    "macCentEuro"},
     {"maccroatian",    "macCroatian"},
@@ -296,23 +300,23 @@ static const LocaleTable localeTable[] = {
     {"macthai",                "macThai"},
     {"macturkish",     "macTurkish"},
     {"macukraine",     "macUkraine"},
-                   {"roman8",          "iso8859-1"},
-                   {"ru",              "iso8859-5"},
-                   {"ru_ru",           "iso8859-5"},
-                   {"ru_su",           "iso8859-5"},
+    {"roman8",         "iso8859-1"},
+    {"ru",             "iso8859-5"},
+    {"ru_ru",          "iso8859-5"},
+    {"ru_su",          "iso8859-5"},
     {"shiftjis",       "shiftjis"},
-                   {"sjis",            "shiftjis"},
+    {"sjis",           "shiftjis"},
     {"symbol",         "symbol"},
     {"tis-620",                "tis-620"},
-                   {"tis620",          "tis-620"},
-                   {"turkish8",        "cp857"},
-                   {"utf8",            "utf-8"},
-                   {"zh",              "cp936"},
-                   {"zh_cn.gb2312",    "euc-cn"},
-                   {"zh_cn.gbk",       "euc-cn"},
-                   {"zh_cz.gb2312",    "euc-cn"},
-                   {"zh_tw",           "euc-tw"},
-                   {"zh_tw.big5",      "big5"},
+    {"tis620",         "tis-620"},
+    {"turkish8",       "cp857"},
+    {"utf8",           "utf-8"},
+    {"zh",             "cp936"},
+    {"zh_cn.gb2312",   "euc-cn"},
+    {"zh_cn.gbk",      "euc-cn"},
+    {"zh_cz.gb2312",   "euc-cn"},
+    {"zh_tw",          "euc-tw"},
+    {"zh_tw.big5",     "big5"},
 };
 
 #ifdef HAVE_COREFOUNDATION
@@ -469,7 +473,7 @@ TclpInitLibraryPath(
     const char *str;
     Tcl_DString buffer;
 
-    pathPtr = Tcl_NewObj();
+    TclNewObj(pathPtr);
 
     /*
      * Look for the library relative to the TCL_LIBRARY env variable. If the
@@ -551,8 +555,8 @@ TclpInitLibraryPath(
 
     *encodingPtr = Tcl_GetEncoding(NULL, NULL);
     str = Tcl_GetStringFromObj(pathPtr, lengthPtr);
-    *valuePtr = ckalloc((*lengthPtr) + 1);
-    memcpy(*valuePtr, str, (size_t)(*lengthPtr)+1);
+    *valuePtr = (char *)ckalloc(*lengthPtr + 1);
+    memcpy(*valuePtr, str, *lengthPtr + 1);
     Tcl_DecrRefCount(pathPtr);
 }
 \f
@@ -589,12 +593,6 @@ TclpSetInitialEncodings(void)
     Tcl_DStringFree(&encodingName);
 }
 
-void
-TclpSetInterfaces(void)
-{
-    /* do nothing */
-}
-
 static const char *
 SearchKnownEncodings(
     const char *encoding)
@@ -775,7 +773,7 @@ InitMacLocaleInfoVar(
        if (!Tcl_CreateNamespace(interp, "::tcl::mac", NULL, NULL)) {
            Tcl_ResetResult(interp);
        }
-       Tcl_SetVar(interp, "::tcl::mac::locale", loc, TCL_GLOBAL_ONLY);
+       Tcl_SetVar2(interp, "::tcl::mac::locale", NULL, loc, TCL_GLOBAL_ONLY);
     }
     CFRelease(localeRef);
 }
@@ -811,9 +809,9 @@ TclpSetVariables(
        const char *str;
        CFBundleRef bundleRef;
 
-       Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
-       Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
-       Tcl_SetVar(interp, "tcl_pkgPath", " ",
+       Tcl_SetVar2(interp, "tclDefaultLibrary", NULL, tclLibPath, TCL_GLOBAL_ONLY);
+       Tcl_SetVar2(interp, "tcl_pkgPath", NULL, tclLibPath, TCL_GLOBAL_ONLY);
+       Tcl_SetVar2(interp, "tcl_pkgPath", NULL, " ",
                TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
 
        str = TclGetEnv("DYLD_FRAMEWORK_PATH", &ds);
@@ -829,9 +827,9 @@ TclpSetVariables(
                    *p = ' ';
                }
            } while (*p++);
-           Tcl_SetVar(interp, "tcl_pkgPath", Tcl_DStringValue(&ds),
+           Tcl_SetVar2(interp, "tcl_pkgPath", NULL, Tcl_DStringValue(&ds),
                    TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
-           Tcl_SetVar(interp, "tcl_pkgPath", " ",
+           Tcl_SetVar2(interp, "tcl_pkgPath", NULL, " ",
                    TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
            Tcl_DStringFree(&ds);
        }
@@ -846,9 +844,9 @@ TclpSetVariables(
                        (unsigned char*) tclLibPath, MAXPATHLEN) &&
                        ! TclOSstat(tclLibPath, &statBuf) &&
                        S_ISDIR(statBuf.st_mode)) {
-                   Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath,
+                   Tcl_SetVar2(interp, "tcl_pkgPath", NULL, tclLibPath,
                            TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
-                   Tcl_SetVar(interp, "tcl_pkgPath", " ",
+                   Tcl_SetVar2(interp, "tcl_pkgPath", NULL, " ",
                            TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
                }
                CFRelease(frameworksURL);
@@ -859,20 +857,20 @@ TclpSetVariables(
                        (unsigned char*) tclLibPath, MAXPATHLEN) &&
                        ! TclOSstat(tclLibPath, &statBuf) &&
                        S_ISDIR(statBuf.st_mode)) {
-                   Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath,
+                   Tcl_SetVar2(interp, "tcl_pkgPath", NULL, tclLibPath,
                            TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
-                   Tcl_SetVar(interp, "tcl_pkgPath", " ",
+                   Tcl_SetVar2(interp, "tcl_pkgPath", NULL, " ",
                            TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
                }
                CFRelease(frameworksURL);
            }
        }
-       Tcl_SetVar(interp, "tcl_pkgPath", pkgPath,
+       Tcl_SetVar2(interp, "tcl_pkgPath", NULL, pkgPath,
                TCL_GLOBAL_ONLY | TCL_APPEND_VALUE);
     } else
 #endif /* HAVE_COREFOUNDATION */
     {
-       Tcl_SetVar(interp, "tcl_pkgPath", pkgPath, TCL_GLOBAL_ONLY);
+       Tcl_SetVar2(interp, "tcl_pkgPath", NULL, pkgPath, TCL_GLOBAL_ONLY);
     }
 
 #ifdef DJGPP
@@ -885,7 +883,7 @@ TclpSetVariables(
 #ifdef __CYGWIN__
        unameOK = 1;
     if (!osInfoInitialized) {
-       HANDLE handle = GetModuleHandleW(L"NTDLL");
+       void *handle = GetModuleHandleW(L"NTDLL");
        int(__stdcall *getversion)(void *) =
                (int(__stdcall *)(void *))GetProcAddress(handle, "RtlGetVersion");
        osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
@@ -897,10 +895,8 @@ TclpSetVariables(
 
     GetSystemInfo(&sysInfo);
 
-    if (osInfo.dwPlatformId < NUMPLATFORMS) {
-       Tcl_SetVar2(interp, "tcl_platform", "os",
-               platforms[osInfo.dwPlatformId], TCL_GLOBAL_ONLY);
-    }
+    Tcl_SetVar2(interp, "tcl_platform", "os",
+           "Windows NT", TCL_GLOBAL_ONLY);
     sprintf(buffer, "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
     Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
     if (sysInfo.wProcessorArchitecture < NUMPROCESSORS) {
@@ -1022,7 +1018,7 @@ TclpFindVariable(
                                 * searches). */
 {
     int i, result = -1;
-    register const char *env, *p1, *p2;
+    const char *env, *p1, *p2;
     Tcl_DString envString;
 
     Tcl_DStringInit(&envString);
index aeadf49..0a5712a 100644 (file)
@@ -32,7 +32,7 @@ typedef struct FileHandler {
                                 * for this file. */
     Tcl_FileProc *proc;                /* Function to call, in the style of
                                 * Tcl_CreateFileHandler. */
-    ClientData clientData;     /* Argument to pass to proc. */
+    void *clientData;  /* Argument to pass to proc. */
     struct FileHandler *nextPtr;/* Next in list of all files we care about. */
 } FileHandler;
 
@@ -94,16 +94,17 @@ typedef struct ThreadSpecificData {
                                 * notifierMutex lock before accessing these
                                 * fields. */
 #ifdef __CYGWIN__
-    void *event;     /* Any other thread alerts a notifier
-        * that an event is ready to be processed
-        * by sending this event. */
+    void *event;               /* Any other thread alerts a notifier that an
+                                * event is ready to be processed by sending
+                                * this event. */
     void *hwnd;                        /* Messaging window. */
 #else /* !__CYGWIN__ */
     pthread_cond_t waitCV;     /* Any other thread alerts a notifier that an
                                 * event is ready to be processed by signaling
                                 * this condition variable. */
 #endif /* __CYGWIN__ */
-    int waitCVinitialized;     /* Variable to flag initialization of the structure */
+    int waitCVinitialized;     /* Variable to flag initialization of the
+                                * structure. */
     int eventReady;            /* True if an event is ready to be processed.
                                 * Used as condition flag together with waitCV
                                 * above. */
@@ -171,12 +172,14 @@ static int notifierThreadRunning = 0;
 static pthread_cond_t notifierCV = PTHREAD_COND_INITIALIZER;
 
 /*
- * The pollState bits
- *     POLL_WANT is set by each thread before it waits on its condition
- *             variable. It is checked by the notifier before it does select.
- *     POLL_DONE is set by the notifier if it goes into select after seeing
- *             POLL_WANT. The idea is to ensure it tries a select with the
- *             same bits the initial thread had set.
+ * The pollState bits:
+ *
+ * POLL_WANT is set by each thread before it waits on its condition variable.
+ *     It is checked by the notifier before it does select.
+ *
+ * POLL_DONE is set by the notifier if it goes into select after seeing
+ *     POLL_WANT. The idea is to ensure it tries a select with the same bits
+ *     the initial thread had set.
  */
 
 #define POLL_WANT      0x1
@@ -187,7 +190,6 @@ static pthread_cond_t notifierCV = PTHREAD_COND_INITIALIZER;
  */
 
 static Tcl_ThreadId notifierThread;
-
 #endif /* TCL_THREADS */
 
 /*
@@ -195,9 +197,9 @@ static Tcl_ThreadId notifierThread;
  */
 
 #ifdef TCL_THREADS
-static void    NotifierThreadProc(ClientData clientData);
+static void    NotifierThreadProc(void *clientData);
 #if defined(HAVE_PTHREAD_ATFORK)
-static int     atForkInit = AT_FORK_INIT_VALUE;
+static int atForkInit = AT_FORK_INIT_VALUE;
 static void    AtForkPrepare(void);
 static void    AtForkParent(void);
 static void    AtForkChild(void);
@@ -211,13 +213,14 @@ static int        FileHandlerEventProc(Tcl_Event *evPtr, int flags);
 
 #if defined(TCL_THREADS) && defined(__CYGWIN__)
 typedef struct {
-    void *hwnd;
-    unsigned int *message;
-    int wParam;
-    int lParam;
-    int time;
-    int x;
+    void *hwnd;                        /* Messaging window. */
+    unsigned int *message;     /* Message payload. */
+    size_t wParam;                     /* Event-specific "word" parameter. */
+    size_t lParam;                     /* Event-specific "long" parameter. */
+    int time;                  /* Event timestamp. */
+    int x;                     /* Event location (where meaningful). */
     int y;
+    int lPrivate;
 } MSG;
 
 typedef struct {
@@ -229,7 +232,7 @@ typedef struct {
     void *hIcon;
     void *hCursor;
     void *hbrBackground;
-    void *lpszMenuName;
+    const void *lpszMenuName;
     const void *lpszClassName;
 } WNDCLASSW;
 
@@ -237,13 +240,13 @@ extern void __stdcall     CloseHandle(void *);
 extern void *__stdcall CreateEventW(void *, unsigned char, unsigned char,
                            void *);
 extern void * __stdcall        CreateWindowExW(void *, const void *, const void *,
-                           DWORD, int, int, int, int, void *, void *, void *, void *);
-extern DWORD __stdcall DefWindowProcW(void *, int, void *, void *);
+                           unsigned int, int, int, int, int, void *, void *, void *, void *);
+extern unsigned int __stdcall  DefWindowProcW(void *, int, void *, void *);
 extern unsigned char __stdcall DestroyWindow(void *);
 extern int __stdcall   DispatchMessageW(const MSG *);
 extern unsigned char __stdcall GetMessageW(MSG *, void *, int, int);
-extern void __stdcall  MsgWaitForMultipleObjects(DWORD, void *,
-                           unsigned char, DWORD, DWORD);
+extern void __stdcall  MsgWaitForMultipleObjects(unsigned int, void *,
+                           unsigned char, unsigned int, unsigned int);
 extern unsigned char __stdcall PeekMessageW(MSG *, void *, int, int, int);
 extern unsigned char __stdcall PostMessageW(void *, unsigned int, void *,
                                    void *);
@@ -256,8 +259,8 @@ extern unsigned char __stdcall      TranslateMessage(const MSG *);
  * Threaded-cygwin specific constants and functions in this file:
  */
 
-static const WCHAR NotfyClassName[] = L"TclNotifier";
-static DWORD __stdcall NotifierProc(void *hwnd, unsigned int message,
+static const wchar_t *NotfyClassName = L"TclNotifier";
+static unsigned int __stdcall  NotifierProc(void *hwnd, unsigned int message,
                            void *wParam, void *lParam);
 #endif /* TCL_THREADS && __CYGWIN__ */
 \f
@@ -321,7 +324,7 @@ StartNotifierThread(const char *proc)
  *----------------------------------------------------------------------
  */
 
-ClientData
+void *
 Tcl_InitNotifier(void)
 {
     if (tclNotifierHooks.initNotifierProc) {
@@ -337,23 +340,23 @@ Tcl_InitNotifier(void)
         */
        if (tsdPtr->waitCVinitialized == 0) {
 #ifdef __CYGWIN__
-           WNDCLASSW class;
-
-           class.style = 0;
-           class.cbClsExtra = 0;
-           class.cbWndExtra = 0;
-           class.hInstance = TclWinGetTclInstance();
-           class.hbrBackground = NULL;
-           class.lpszMenuName = NULL;
-           class.lpszClassName = NotfyClassName;
-           class.lpfnWndProc = NotifierProc;
-           class.hIcon = NULL;
-           class.hCursor = NULL;
-
-           RegisterClassW(&class);
-           tsdPtr->hwnd = CreateWindowExW(NULL, class.lpszClassName,
-                   class.lpszClassName, 0, 0, 0, 0, 0, NULL, NULL,
-                   TclWinGetTclInstance(), NULL);
+           WNDCLASSW clazz;
+
+           clazz.style = 0;
+           clazz.cbClsExtra = 0;
+           clazz.cbWndExtra = 0;
+           clazz.hInstance = TclWinGetTclInstance();
+           clazz.hbrBackground = NULL;
+           clazz.lpszMenuName = NULL;
+           clazz.lpszClassName = NotfyClassName;
+           clazz.lpfnWndProc = (void *)NotifierProc;
+           clazz.hIcon = NULL;
+           clazz.hCursor = NULL;
+
+           RegisterClassW(&clazz);
+           tsdPtr->hwnd = CreateWindowExW(NULL, clazz.lpszClassName,
+                   clazz.lpszClassName, 0, 0, 0, 0, 0, NULL, NULL,
+                   clazz.hInstance, NULL);
            tsdPtr->event = CreateEventW(NULL, 1 /* manual */,
                    0 /* !signaled */, NULL);
 #else
@@ -380,7 +383,6 @@ Tcl_InitNotifier(void)
 #endif /* HAVE_PTHREAD_ATFORK */
 
        notifierCount++;
-
        pthread_mutex_unlock(&notifierInitMutex);
 
 #endif /* TCL_THREADS */
@@ -408,7 +410,7 @@ Tcl_InitNotifier(void)
 
 void
 Tcl_FinalizeNotifier(
-    ClientData clientData)             /* Not used. */
+    void *clientData)
 {
     if (tclNotifierHooks.finalizeNotifierProc) {
        tclNotifierHooks.finalizeNotifierProc(clientData);
@@ -425,28 +427,25 @@ Tcl_FinalizeNotifier(
         * pipe and wait for the background thread to terminate.
         */
 
-       if (notifierCount == 0) {
+       if (notifierCount == 0 && triggerPipe != -1) {
+           if (write(triggerPipe, "q", 1) != 1) {
+               Tcl_Panic("Tcl_FinalizeNotifier: %s",
+                       "unable to write 'q' to triggerPipe");
+           }
+           close(triggerPipe);
+           pthread_mutex_lock(&notifierMutex);
+           while(triggerPipe != -1) {
+               pthread_cond_wait(&notifierCV, &notifierMutex);
+           }
+           pthread_mutex_unlock(&notifierMutex);
+           if (notifierThreadRunning) {
+               int result = pthread_join((pthread_t) notifierThread, NULL);
 
-           if (triggerPipe != -1) {
-               if (write(triggerPipe, "q", 1) != 1) {
+               if (result) {
                    Tcl_Panic("Tcl_FinalizeNotifier: %s",
-                           "unable to write q to triggerPipe");
-               }
-               close(triggerPipe);
-               pthread_mutex_lock(&notifierMutex);
-               while(triggerPipe != -1) {
-                   pthread_cond_wait(&notifierCV, &notifierMutex);
-               }
-               pthread_mutex_unlock(&notifierMutex);
-               if (notifierThreadRunning) {
-                   int result = pthread_join((pthread_t) notifierThread, NULL);
-
-                   if (result) {
-                       Tcl_Panic("Tcl_FinalizeNotifier: unable to join notifier "
-                               "thread");
-                   }
-                   notifierThreadRunning = 0;
+                           "unable to join notifier thread");
                }
+               notifierThreadRunning = 0;
            }
        }
 
@@ -488,14 +487,14 @@ Tcl_FinalizeNotifier(
 
 void
 Tcl_AlertNotifier(
-    ClientData clientData)
+    void *clientData)
 {
     if (tclNotifierHooks.alertNotifierProc) {
        tclNotifierHooks.alertNotifierProc(clientData);
        return;
     } else {
 #ifdef TCL_THREADS
-       ThreadSpecificData *tsdPtr = clientData;
+       ThreadSpecificData *tsdPtr = (ThreadSpecificData *)clientData;
 
        pthread_mutex_lock(&notifierMutex);
        tsdPtr->eventReady = 1;
@@ -600,7 +599,7 @@ Tcl_CreateFileHandler(
                                 * called. */
     Tcl_FileProc *proc,                /* Function to call for each selected
                                 * event. */
-    ClientData clientData)     /* Arbitrary data to pass to proc. */
+    void *clientData)  /* Arbitrary data to pass to proc. */
 {
     if (tclNotifierHooks.createFileHandlerProc) {
        tclNotifierHooks.createFileHandlerProc(fd, mask, proc, clientData);
@@ -616,7 +615,7 @@ Tcl_CreateFileHandler(
            }
        }
        if (filePtr == NULL) {
-           filePtr = ckalloc(sizeof(FileHandler));
+           filePtr = (FileHandler *)ckalloc(sizeof(FileHandler));
            filePtr->fd = fd;
            filePtr->readyMask = 0;
            filePtr->nextPtr = tsdPtr->firstFileHandlerPtr;
@@ -815,7 +814,7 @@ FileHandlerEventProc(
 \f
 #if defined(TCL_THREADS) && defined(__CYGWIN__)
 
-static DWORD __stdcall
+static unsigned int __stdcall
 NotifierProc(
     void *hwnd,
     unsigned int message,
@@ -866,12 +865,13 @@ Tcl_WaitForEvent(
        FileHandler *filePtr;
        int mask;
        Tcl_Time vTime;
+       ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 #ifdef TCL_THREADS
        int waitForFiles;
 #   ifdef __CYGWIN__
        MSG msg;
 #   endif /* __CYGWIN__ */
-#else
+#else /* !TCL_THREADS */
        /*
         * Impl. notes: timeout & timeoutPtr are used if, and only if threads
         * are not enabled. They are the arguments for the regular select()
@@ -881,7 +881,6 @@ Tcl_WaitForEvent(
        struct timeval timeout, *timeoutPtr;
        int numFound;
 #endif /* TCL_THREADS */
-       ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
 
        /*
         * Set up the timeout structure. Note that if there are no events to
@@ -986,7 +985,7 @@ Tcl_WaitForEvent(
        if (!tsdPtr->eventReady) {
 #ifdef __CYGWIN__
            if (!PeekMessageW(&msg, NULL, 0, 0, 0)) {
-               DWORD timeout;
+               unsigned int timeout;
 
                if (timePtr) {
                    timeout = timePtr->sec * 1000 + timePtr->usec / 1000;
@@ -997,18 +996,19 @@ Tcl_WaitForEvent(
                MsgWaitForMultipleObjects(1, &tsdPtr->event, 0, timeout, 1279);
                pthread_mutex_lock(&notifierMutex);
            }
-#else
+#else /* !__CYGWIN__ */
            if (timePtr != NULL) {
-              Tcl_Time now;
-              struct timespec ptime;
+               Tcl_Time now;
+               struct timespec ptime;
 
-              Tcl_GetTime(&now);
-              ptime.tv_sec = timePtr->sec + now.sec + (timePtr->usec + now.usec) / 1000000;
-              ptime.tv_nsec = 1000 * ((timePtr->usec + now.usec) % 1000000);
+               Tcl_GetTime(&now);
+               ptime.tv_sec = timePtr->sec + now.sec +
+                       (timePtr->usec + now.usec) / 1000000;
+               ptime.tv_nsec = 1000 * ((timePtr->usec + now.usec) % 1000000);
 
-              pthread_cond_timedwait(&tsdPtr->waitCV, &notifierMutex, &ptime);
+               pthread_cond_timedwait(&tsdPtr->waitCV, &notifierMutex, &ptime);
            } else {
-              pthread_cond_wait(&tsdPtr->waitCV, &notifierMutex);
+               pthread_cond_wait(&tsdPtr->waitCV, &notifierMutex);
            }
 #endif /* __CYGWIN__ */
        }
@@ -1020,12 +1020,12 @@ Tcl_WaitForEvent(
             * Retrieve and dispatch the message.
             */
 
-           DWORD result = GetMessageW(&msg, NULL, 0, 0);
+           unsigned int result = GetMessageW(&msg, NULL, 0, 0);
 
            if (result == 0) {
                PostQuitMessage(msg.wParam);
                /* What to do here? */
-           } else if (result != (DWORD) -1) {
+           } else if (result != (unsigned int) -1) {
                TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
@@ -1056,8 +1056,7 @@ Tcl_WaitForEvent(
                        "unable to write to triggerPipe");
            }
        }
-
-#else
+#else /* !TCL_THREADS */
        tsdPtr->readyMasks = tsdPtr->checkMasks;
        numFound = select(tsdPtr->numFdBits, &tsdPtr->readyMasks.readable,
                &tsdPtr->readyMasks.writable, &tsdPtr->readyMasks.exception,
@@ -1103,7 +1102,7 @@ Tcl_WaitForEvent(
 
            if (filePtr->readyMask == 0) {
                FileHandlerEvent *fileEvPtr =
-                       ckalloc(sizeof(FileHandlerEvent));
+                       (FileHandlerEvent *)ckalloc(sizeof(FileHandlerEvent));
 
                fileEvPtr->header.proc = FileHandlerEventProc;
                fileEvPtr->fd = filePtr->fd;
@@ -1145,17 +1144,19 @@ Tcl_WaitForEvent(
 
 static void
 NotifierThreadProc(
-    ClientData clientData)     /* Not used. */
+    void *dummy)       /* Not used. */
 {
     ThreadSpecificData *tsdPtr;
     fd_set readableMask;
     fd_set writableMask;
     fd_set exceptionMask;
-    int fds[2];
-    int i, numFdBits = 0, receivePipe;
+    int i;
+    int fds[2], receivePipe;
     long found;
-    struct timeval poll = {0., 0.}, *timePtr;
+    struct timeval poll = {0, 0}, *timePtr;
     char buf[2];
+    int numFdBits = 0;
+    (void)dummy;
 
     if (pipe(fds) != 0) {
        Tcl_Panic("NotifierThreadProc: %s", "could not create trigger pipe");
@@ -1204,7 +1205,7 @@ NotifierThreadProc(
        FD_ZERO(&exceptionMask);
 
        /*
-        * Compute the logical OR of the select masks from all the waiting
+        * Compute the logical OR of the masks from all the waiting
         * notifiers.
         */
 
index 8b26694..d5cb765 100644 (file)
@@ -229,9 +229,10 @@ TclpCreateTempFile(
 Tcl_Obj *
 TclpTempFileName(void)
 {
-    Tcl_Obj *retVal, *nameObj = Tcl_NewObj();
+    Tcl_Obj *retVal, *nameObj;
     int fd;
 
+    TclNewObj(nameObj);
     Tcl_IncrRefCount(nameObj);
     fd = TclUnixOpenTemporaryFile(NULL, NULL, NULL, nameObj);
     if (fd == -1) {
@@ -374,7 +375,6 @@ TclpCloseFile(
  *---------------------------------------------------------------------------
  */
 
-    /* ARGSUSED */
 int
 TclpCreateProcess(
     Tcl_Interp *interp,                /* Interpreter in which to leave errors that
@@ -900,7 +900,6 @@ TclGetAndDetachPids(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 PipeBlockModeProc(
     ClientData instanceData,   /* Pipe state. */
@@ -1249,7 +1248,6 @@ Tcl_WaitPid(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 int
 Tcl_PidObjCmd(
     ClientData dummy,          /* Not used. */
@@ -1287,7 +1285,7 @@ Tcl_PidObjCmd(
         */
 
        pipePtr = Tcl_GetChannelInstanceData(chan);
-       resultPtr = Tcl_NewObj();
+       TclNewObj(resultPtr);
        for (i = 0; i < pipePtr->numPids; i++) {
            Tcl_ListObjAppendElement(NULL, resultPtr,
                    Tcl_NewIntObj(PTR2INT(TclpGetPid(pipePtr->pidPtr[i]))));
index af0b4dc..0ae4f25 100644 (file)
@@ -86,7 +86,6 @@ typedef off_t         Tcl_SeekOffset;
 #endif
 
 #ifdef __CYGWIN__
-
     /* Make some symbols available without including <windows.h> */
 #   define DWORD unsigned int
 #   define CP_UTF8 65001
@@ -103,26 +102,20 @@ typedef off_t             Tcl_SeekOffset;
     __declspec(dllimport) extern __stdcall int MultiByteToWideChar(int, int, const char *, int,
            WCHAR *, int);
     __declspec(dllimport) extern __stdcall void OutputDebugStringW(const WCHAR *);
-    __declspec(dllimport) extern __stdcall int IsDebuggerPresent();
-    __declspec(dllimport) extern __stdcall int GetLastError();
+    __declspec(dllimport) extern __stdcall int IsDebuggerPresent(void);
+    __declspec(dllimport) extern __stdcall int GetLastError(void);
     __declspec(dllimport) extern __stdcall int GetFileAttributesW(const WCHAR *);
     __declspec(dllimport) extern __stdcall int SetFileAttributesW(const WCHAR *, int);
-
     __declspec(dllimport) extern int cygwin_conv_path(int, const void *, void *, int);
-/* On Cygwin, the environment is imported from the Cygwin DLL. */
-#ifndef __x86_64__
-#   define environ __cygwin_environ
-    extern char **__cygwin_environ;
-#endif
 #   define timezone _timezone
     extern int TclOSstat(const char *name, void *statBuf);
     extern int TclOSlstat(const char *name, void *statBuf);
 #elif defined(HAVE_STRUCT_STAT64) && !defined(__APPLE__)
-#   define TclOSstat           stat64
-#   define TclOSlstat          lstat64
+#   define TclOSstat(name, buf) stat64(name, (struct stat64 *)buf)
+#   define TclOSlstat(name,buf) lstat64(name, (struct stat64 *)buf)
 #else
-#   define TclOSstat           stat
-#   define TclOSlstat          lstat
+#   define TclOSstat(name, buf) stat(name, (struct stat *)buf)
+#   define TclOSlstat(name, buf) lstat(name, (struct stat *)buf)
 #endif
 \f
 /*
@@ -250,29 +243,29 @@ extern int TclUnixSetBlockingMode(int fd, int mode);
  */
 
 #ifndef WIFEXITED
-#   define WIFEXITED(stat)     (((*((int *) &(stat))) & 0xff) == 0)
+#   define WIFEXITED(stat)     (((*((int *) &(stat))) & 0xFF) == 0)
 #endif
 
 #ifndef WEXITSTATUS
-#   define WEXITSTATUS(stat)   (((*((int *) &(stat))) >> 8) & 0xff)
+#   define WEXITSTATUS(stat)   (((*((int *) &(stat))) >> 8) & 0xFF)
 #endif
 
 #ifndef WIFSIGNALED
 #   define WIFSIGNALED(stat) \
        (((*((int *) &(stat)))) && ((*((int *) &(stat))) \
-               == ((*((int *) &(stat))) & 0x00ff)))
+               == ((*((int *) &(stat))) & 0x00FF)))
 #endif
 
 #ifndef WTERMSIG
-#   define WTERMSIG(stat)      ((*((int *) &(stat))) & 0x7f)
+#   define WTERMSIG(stat)      ((*((int *) &(stat))) & 0x7F)
 #endif
 
 #ifndef WIFSTOPPED
-#   define WIFSTOPPED(stat)    (((*((int *) &(stat))) & 0xff) == 0177)
+#   define WIFSTOPPED(stat)    (((*((int *) &(stat))) & 0xFF) == 0177)
 #endif
 
 #ifndef WSTOPSIG
-#   define WSTOPSIG(stat)      (((*((int *) &(stat))) >> 8) & 0xff)
+#   define WSTOPSIG(stat)      (((*((int *) &(stat))) >> 8) & 0xFF)
 #endif
 \f
 /*
index 90c72c0..1a54914 100644 (file)
@@ -118,6 +118,7 @@ struct TcpState {
  * Static routines for this file:
  */
 
+static void            TcpAsyncCallback(ClientData clientData, int mask);
 static int             TcpConnect(Tcl_Interp *interp, TcpState *state);
 static void            TcpAccept(ClientData data, int mask);
 static int             TcpBlockModeProc(ClientData data, int mode);
@@ -134,6 +135,7 @@ static int          TcpInputProc(ClientData instanceData, char *buf,
                            int toRead, int *errorCode);
 static int             TcpOutputProc(ClientData instanceData,
                            const char *buf, int toWrite, int *errorCode);
+static void            TcpThreadActionProc(ClientData instanceData, int action);
 static void            TcpWatchProc(ClientData instanceData, int mask);
 static int             WaitForConnect(TcpState *statePtr, int *errorCodePtr);
 static void            WrapNotify(ClientData clientData, int mask);
@@ -159,7 +161,7 @@ static const Tcl_ChannelType tcpChannelType = {
     NULL,                      /* flush proc. */
     NULL,                      /* handler proc. */
     NULL,                      /* wide seek proc. */
-    NULL,                      /* thread action proc. */
+    TcpThreadActionProc,       /* thread action proc. */
     NULL                       /* truncate proc. */
 };
 
@@ -228,9 +230,9 @@ InitializeHostName(
            char *dot = strchr(u.nodename, '.');
 
            if (dot != NULL) {
-               char *node = ckalloc(dot - u.nodename + 1);
+               char *node = (char *)ckalloc(dot - u.nodename + 1);
 
-               memcpy(node, u.nodename, (size_t) (dot - u.nodename));
+               memcpy(node, u.nodename, dot - u.nodename);
                node[dot - u.nodename] = '\0';
                hp = TclpGetHostByName(node);
                ckfree(node);
@@ -275,7 +277,7 @@ InitializeHostName(
     *encodingPtr = Tcl_GetEncoding(NULL, NULL);
     *lengthPtr = strlen(native);
     *valuePtr = ckalloc(*lengthPtr + 1);
-    memcpy(*valuePtr, native, (size_t)(*lengthPtr) + 1);
+    memcpy(*valuePtr, native, *lengthPtr + 1);
 }
 \f
 /*
@@ -320,8 +322,10 @@ Tcl_GetHostName(void)
 
 int
 TclpHasSockets(
-    Tcl_Interp *interp)                /* Not used. */
+    Tcl_Interp *dummy)         /* Not used. */
 {
+    (void)dummy;
+
     return TCL_OK;
 }
 \f
@@ -364,7 +368,6 @@ TclpFinalizeSockets(void)
  * ----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpBlockModeProc(
     ClientData instanceData,   /* Socket state. */
@@ -372,7 +375,7 @@ TcpBlockModeProc(
                                 * TCL_MODE_BLOCKING or
                                 * TCL_MODE_NONBLOCKING. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
 
     if (mode == TCL_MODE_BLOCKING) {
        CLEAR_BITS(statePtr->flags, TCP_NONBLOCKING);
@@ -496,7 +499,6 @@ WaitForConnect(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpInputProc(
     ClientData instanceData,   /* Socket state. */
@@ -505,7 +507,7 @@ TcpInputProc(
                                 * buffer? */
     int *errorCodePtr)         /* Where to store error code. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
     int bytesRead;
 
     *errorCodePtr = 0;
@@ -555,7 +557,7 @@ TcpOutputProc(
     int toWrite,               /* How many bytes to write? */
     int *errorCodePtr)         /* Where to store error code. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
     int written;
 
     *errorCodePtr = 0;
@@ -589,15 +591,15 @@ TcpOutputProc(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpCloseProc(
     ClientData instanceData,   /* The socket to close. */
-    Tcl_Interp *interp)                /* For error reporting - unused. */
+    Tcl_Interp *dummy)         /* For error reporting - unused. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
     int errorCode = 0;
     TcpFdList *fds;
+    (void)dummy;
 
     /*
      * Delete a file handler that may be active for this socket if this is a
@@ -654,36 +656,27 @@ TcpCloseProc(
 static int
 TcpClose2Proc(
     ClientData instanceData,   /* The socket to close. */
-    Tcl_Interp *interp,                /* For error reporting. */
+    Tcl_Interp *dummy,         /* For error reporting. */
     int flags)                 /* Flags that indicate which side to close. */
 {
-    TcpState *statePtr = instanceData;
-    int errorCode = 0;
-    int sd;
+    TcpState *statePtr = (TcpState *)instanceData;
+    int readError = 0;
+    int writeError = 0;
+    (void)dummy;
 
     /*
      * Shutdown the OS socket handle.
      */
-
-    switch(flags) {
-    case TCL_CLOSE_READ:
-        sd = SHUT_RD;
-        break;
-    case TCL_CLOSE_WRITE:
-        sd = SHUT_WR;
-        break;
-    default:
-        if (interp) {
-            Tcl_SetObjResult(interp, Tcl_NewStringObj(
-                    "socket close2proc called bidirectionally", -1));
-        }
-        return TCL_ERROR;
+    if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
+       return TcpCloseProc(instanceData, NULL);
     }
-    if (shutdown(statePtr->fds.fd,sd) < 0) {
-       errorCode = errno;
+    if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->fds.fd, SHUT_RD) < 0)) {
+       readError = errno;
     }
-
-    return errorCode;
+    if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->fds.fd, SHUT_WR) < 0)) {
+       writeError = errno;
+    }
+    return (readError != 0) ? readError : writeError;
 }
 \f
 /*
@@ -822,7 +815,7 @@ TcpGetOptionProc(
     Tcl_DString *dsPtr)                /* Where to store the computed value;
                                 * initialized by caller. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
     size_t len = 0;
 
     WaitForConnect(statePtr, NULL);
@@ -964,6 +957,51 @@ TcpGetOptionProc(
 /*
  * ----------------------------------------------------------------------
  *
+ * TcpThreadActionProc --
+ *
+ *     Handles detach/attach for asynchronously connecting socket.
+ *
+ *     Reassigning the file handler associated with thread-related channel
+ *     notification, responsible for callbacks (signaling that asynchronous
+ *     connection attempt has succeeded or failed).
+ *
+ * Results:
+ *     None.
+ *
+ * ----------------------------------------------------------------------
+ */
+
+static void
+TcpThreadActionProc(
+    ClientData instanceData,
+    int action)
+{
+    TcpState *statePtr = (TcpState *)instanceData;
+
+    if (GOT_BITS(statePtr->flags, TCP_ASYNC_CONNECT)) {
+       /*
+        * Async-connecting socket must get reassigned handler if it have been
+        * transferred to another thread. Remove the handler if the socket is
+        * not managed by this thread anymore and create new handler (TSD related)
+        * so the callback will run in the correct thread, bug [f583715154].
+        */
+       switch (action) {
+         case TCL_CHANNEL_THREAD_REMOVE:
+           CLEAR_BITS(statePtr->flags, TCP_ASYNC_PENDING);
+           Tcl_DeleteFileHandler(statePtr->fds.fd);
+         break;
+         case TCL_CHANNEL_THREAD_INSERT:
+           Tcl_CreateFileHandler(statePtr->fds.fd,
+               TCL_WRITABLE | TCL_EXCEPTION, TcpAsyncCallback, statePtr);
+           SET_BITS(statePtr->flags, TCP_ASYNC_PENDING);
+         break;
+       }
+    }
+}
+\f
+/*
+ * ----------------------------------------------------------------------
+ *
  * TcpWatchProc --
  *
  *     Initialize the notifier to watch the fd from this channel.
@@ -1014,7 +1052,7 @@ TcpWatchProc(
                                 * TCL_READABLE, TCL_WRITABLE and
                                 * TCL_EXCEPTION. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
 
     if (statePtr->acceptProc != NULL) {
         /*
@@ -1080,14 +1118,14 @@ TcpWatchProc(
  * ----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpGetHandleProc(
     ClientData instanceData,   /* The socket state. */
     int direction,             /* Not used. */
     ClientData *handlePtr)     /* Where to store the handle. */
 {
-    TcpState *statePtr = instanceData;
+    TcpState *statePtr = (TcpState *)instanceData;
+    (void)direction;
 
     *handlePtr = INT2PTR(statePtr->fds.fd);
     return TCL_OK;
@@ -1112,7 +1150,9 @@ TcpAsyncCallback(
                                 * TCL_READABLE, TCL_WRITABLE and
                                 * TCL_EXCEPTION. */
 {
-    TcpConnect(NULL, clientData);
+    (void)mask;
+
+    TcpConnect(NULL, (TcpState *)clientData);
 }
 \f
 /*
@@ -1371,7 +1411,7 @@ Tcl_OpenTcpClient(
      * Allocate a new TcpState for this socket.
      */
 
-    statePtr = ckalloc(sizeof(TcpState));
+    statePtr = (TcpState *)ckalloc(sizeof(TcpState));
     memset(statePtr, 0, sizeof(TcpState));
     statePtr->flags = async ? TCP_ASYNC_CONNECT : 0;
     statePtr->cachedBlocking = TCL_MODE_BLOCKING;
@@ -1450,7 +1490,7 @@ TclpMakeTcpClientChannelMode(
     TcpState *statePtr;
     char channelName[SOCK_CHAN_LENGTH];
 
-    statePtr = ckalloc(sizeof(TcpState));
+    statePtr = (TcpState *)ckalloc(sizeof(TcpState));
     memset(statePtr, 0, sizeof(TcpState));
     statePtr->fds.fd = PTR2INT(sock);
     statePtr->flags = 0;
@@ -1610,14 +1650,14 @@ Tcl_OpenTcpServer(
              * Allocate a new TcpState for this socket.
              */
 
-            statePtr = ckalloc(sizeof(TcpState));
+            statePtr = (TcpState *)ckalloc(sizeof(TcpState));
             memset(statePtr, 0, sizeof(TcpState));
             statePtr->acceptProc = acceptProc;
             statePtr->acceptProcData = acceptProcData;
             sprintf(channelName, SOCK_TEMPLATE, (long) statePtr);
             newfds = &statePtr->fds;
         } else {
-            newfds = ckalloc(sizeof(TcpFdList));
+            newfds = (TcpFdList *)ckalloc(sizeof(TcpFdList));
             memset(newfds, (int) 0, sizeof(TcpFdList));
             fds->next = newfds;
         }
@@ -1675,19 +1715,19 @@ Tcl_OpenTcpServer(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static void
 TcpAccept(
     ClientData data,           /* Callback token. */
     int mask)                  /* Not used. */
 {
-    TcpFdList *fds = data;     /* Client data of server socket. */
+    TcpFdList *fds = (TcpFdList *)data;        /* Client data of server socket. */
     int newsock;               /* The new client socket */
     TcpState *newSockState;    /* State for new socket. */
     address addr;              /* The remote address */
     socklen_t len;             /* For accept interface */
     char channelName[SOCK_CHAN_LENGTH];
     char host[NI_MAXHOST], port[NI_MAXSERV];
+    (void)mask;
 
     len = sizeof(addr);
     newsock = accept(fds->fd, &addr.sa, &len);
@@ -1702,7 +1742,7 @@ TcpAccept(
 
     (void) fcntl(newsock, F_SETFD, FD_CLOEXEC);
 
-    newSockState = ckalloc(sizeof(TcpState));
+    newSockState = (TcpState *)ckalloc(sizeof(TcpState));
     memset(newSockState, 0, sizeof(TcpState));
     newSockState->flags = 0;
     newSockState->fds.fd = newsock;
index 0609230..afb795d 100644 (file)
@@ -22,23 +22,23 @@ typedef struct ThreadSpecificData {
 static Tcl_ThreadDataKey dataKey;
 
 /*
- * masterLock is used to serialize creation of mutexes, condition variables,
+ * globalLock is used to serialize creation of mutexes, condition variables,
  * and thread local storage. This is the only place that can count on the
  * ability to statically initialize the mutex.
  */
 
-static pthread_mutex_t masterLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t globalLock = PTHREAD_MUTEX_INITIALIZER;
 
 /*
  * initLock is used to serialize initialization and finalization of Tcl. It
- * cannot use any dyamically allocated storage.
+ * cannot use any dynamically allocated storage.
  */
 
 static pthread_mutex_t initLock = PTHREAD_MUTEX_INITIALIZER;
 
 /*
  * allocLock is used by Tcl's version of malloc for synchronization. For
- * obvious reasons, cannot use any dyamically allocated storage.
+ * obvious reasons, cannot use any dynamically allocated storage.
  */
 
 static pthread_mutex_t allocLock = PTHREAD_MUTEX_INITIALIZER;
@@ -48,8 +48,8 @@ static pthread_mutex_t *allocLockPtr = &allocLock;
  * These are for the critical sections inside this file.
  */
 
-#define MASTER_LOCK    pthread_mutex_lock(&masterLock)
-#define MASTER_UNLOCK  pthread_mutex_unlock(&masterLock)
+#define GLOBAL_LOCK    pthread_mutex_lock(&globalLock)
+#define GLOBAL_UNLOCK  pthread_mutex_unlock(&globalLock)
 
 #endif /* TCL_THREADS */
 \f
@@ -89,7 +89,7 @@ TclpThreadCreate(
 
 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
     if (stackSize != TCL_THREAD_STACK_DEFAULT) {
-       pthread_attr_setstacksize(&attr, (size_t) stackSize);
+       pthread_attr_setstacksize(&attr, stackSize);
 #ifdef TCL_THREAD_STACK_MIN
     } else {
        /*
@@ -114,14 +114,14 @@ TclpThreadCreate(
     }
 #endif /* HAVE_PTHREAD_ATTR_SETSTACKSIZE */
 
-    if (! (flags & TCL_THREAD_JOINABLE)) {
-       pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
+    if (!(flags & TCL_THREAD_JOINABLE)) {
+       pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
     }
 
     if (pthread_create(&theThread, &attr,
-           (void * (*)(void *))proc, (void *)clientData) &&
+           (void * (*)(void *))(void *)proc, (void *)clientData) &&
            pthread_create(&theThread, NULL,
-                   (void * (*)(void *))proc, (void *)clientData)) {
+                   (void * (*)(void *))(void *)proc, (void *)clientData)) {
        result = TCL_ERROR;
     } else {
        *idPtr = (Tcl_ThreadId)theThread;
@@ -252,7 +252,7 @@ TclpInitLock(void)
 /*
  *----------------------------------------------------------------------
  *
- * TclpFinalizeLock
+ * TclFinalizeLock
  *
  *     This procedure is used to destroy all private resources used in this
  *     file.
@@ -274,7 +274,7 @@ TclFinalizeLock(void)
     /*
      * You do not need to destroy mutexes that were created with the
      * PTHREAD_MUTEX_INITIALIZER macro. These mutexes do not need any
-     * destruction: masterLock, allocLock, and initLock.
+     * destruction: globalLock, allocLock, and initLock.
      */
 
     pthread_mutex_unlock(&initLock);
@@ -309,7 +309,7 @@ TclpInitUnlock(void)
 /*
  *----------------------------------------------------------------------
  *
- * TclpMasterLock
+ * TclpGlobalLock
  *
  *     This procedure is used to grab a lock that serializes creation and
  *     finalization of serialization objects. This interface is only needed
@@ -322,24 +322,23 @@ TclpInitUnlock(void)
  *     None.
  *
  * Side effects:
- *     Acquire the master mutex.
+ *     Acquire the global mutex.
  *
  *----------------------------------------------------------------------
  */
 
 void
-TclpMasterLock(void)
+TclpGlobalLock(void)
 {
 #ifdef TCL_THREADS
-    pthread_mutex_lock(&masterLock);
+    pthread_mutex_lock(&globalLock);
 #endif
 }
-
 \f
 /*
  *----------------------------------------------------------------------
  *
- * TclpMasterUnlock
+ * TclpGlobalUnlock
  *
  *     This procedure is used to release a lock that serializes creation and
  *     finalization of synchronization objects.
@@ -348,16 +347,16 @@ TclpMasterLock(void)
  *     None.
  *
  * Side effects:
- *     Release the master mutex.
+ *     Release the global mutex.
  *
  *----------------------------------------------------------------------
  */
 
 void
-TclpMasterUnlock(void)
+TclpGlobalUnlock(void)
 {
 #ifdef TCL_THREADS
-    pthread_mutex_unlock(&masterLock);
+    pthread_mutex_unlock(&globalLock);
 #endif
 }
 \f
@@ -367,7 +366,7 @@ TclpMasterUnlock(void)
  * Tcl_GetAllocMutex
  *
  *     This procedure returns a pointer to a statically initialized mutex for
- *     use by the memory allocator. The alloctor must use this lock, because
+ *     use by the memory allocator. The allocator must use this lock, because
  *     all other locks are allocated...
  *
  * Results:
@@ -421,18 +420,18 @@ Tcl_MutexLock(
     pthread_mutex_t *pmutexPtr;
 
     if (*mutexPtr == NULL) {
-       MASTER_LOCK;
+       GLOBAL_LOCK;
        if (*mutexPtr == NULL) {
            /*
-            * Double inside master lock check to avoid a race condition.
+            * Double inside global lock check to avoid a race condition.
             */
 
-           pmutexPtr = ckalloc(sizeof(pthread_mutex_t));
+           pmutexPtr = (pthread_mutex_t *)ckalloc(sizeof(pthread_mutex_t));
            pthread_mutex_init(pmutexPtr, NULL);
            *mutexPtr = (Tcl_Mutex)pmutexPtr;
            TclRememberMutex(mutexPtr);
        }
-       MASTER_UNLOCK;
+       GLOBAL_UNLOCK;
     }
     pmutexPtr = *((pthread_mutex_t **)mutexPtr);
     pthread_mutex_lock(pmutexPtr);
@@ -472,7 +471,7 @@ Tcl_MutexUnlock(
  *     This procedure is invoked to clean up one mutex. This is only safe to
  *     call at the end of time.
  *
- *     This assumes the Master Lock is held.
+ *     This assumes the Global Lock is held.
  *
  * Results:
  *     None.
@@ -529,7 +528,7 @@ Tcl_ConditionWait(
     struct timespec ptime;
 
     if (*condPtr == NULL) {
-       MASTER_LOCK;
+       GLOBAL_LOCK;
 
        /*
         * Double check inside mutex to avoid race, then initialize condition
@@ -537,12 +536,12 @@ Tcl_ConditionWait(
         */
 
        if (*condPtr == NULL) {
-           pcondPtr = ckalloc(sizeof(pthread_cond_t));
+           pcondPtr = (pthread_cond_t *)ckalloc(sizeof(pthread_cond_t));
            pthread_cond_init(pcondPtr, NULL);
            *condPtr = (Tcl_Condition) pcondPtr;
            TclRememberCondition(condPtr);
        }
-       MASTER_UNLOCK;
+       GLOBAL_UNLOCK;
     }
     pmutexPtr = *((pthread_mutex_t **)mutexPtr);
     pcondPtr = *((pthread_cond_t **)condPtr);
@@ -588,11 +587,12 @@ Tcl_ConditionNotify(
     Tcl_Condition *condPtr)
 {
     pthread_cond_t *pcondPtr = *((pthread_cond_t **)condPtr);
+
     if (pcondPtr != NULL) {
        pthread_cond_broadcast(pcondPtr);
     } else {
        /*
-        * Noone has used the condition variable, so there are no waiters.
+        * No-one has used the condition variable, so there are no waiters.
         */
     }
 }
@@ -605,7 +605,7 @@ Tcl_ConditionNotify(
  *     This procedure is invoked to clean up a condition variable. This is
  *     only safe to call at the end of time.
  *
- *     This assumes the Master Lock is held.
+ *     This assumes the Global Lock is held.
  *
  * Results:
  *     None.
@@ -683,18 +683,18 @@ TclpInetNtoa(
 static volatile int initialized = 0;
 static pthread_key_t key;
 
-typedef struct allocMutex {
+typedef struct {
     Tcl_Mutex tlock;
     pthread_mutex_t plock;
-} allocMutex;
+} AllocMutex;
 
 Tcl_Mutex *
 TclpNewAllocMutex(void)
 {
-    struct allocMutex *lockPtr;
-    register pthread_mutex_t *plockPtr;
+    AllocMutex *lockPtr;
+    pthread_mutex_t *plockPtr;
 
-    lockPtr = malloc(sizeof(struct allocMutex));
+    lockPtr = (AllocMutex *)malloc(sizeof(AllocMutex));
     if (lockPtr == NULL) {
        Tcl_Panic("could not allocate lock");
     }
@@ -708,7 +708,8 @@ void
 TclpFreeAllocMutex(
     Tcl_Mutex *mutex)          /* The alloc mutex to free. */
 {
-    allocMutex* lockPtr = (allocMutex*) mutex;
+    AllocMutex *lockPtr = (AllocMutex *)mutex;
+
     if (!lockPtr) {
        return;
     }
@@ -767,7 +768,7 @@ TclpThreadCreateKey(void)
 {
     pthread_key_t *ptkeyPtr;
 
-    ptkeyPtr = TclpSysAlloc(sizeof *ptkeyPtr, 0);
+    ptkeyPtr = (pthread_key_t *)TclpSysAlloc(sizeof(pthread_key_t), 0);
     if (NULL == ptkeyPtr) {
        Tcl_Panic("unable to allocate thread key!");
     }
@@ -783,7 +784,7 @@ void
 TclpThreadDeleteKey(
     void *keyPtr)
 {
-    pthread_key_t *ptkeyPtr = keyPtr;
+    pthread_key_t *ptkeyPtr = (pthread_key_t *)keyPtr;
 
     if (pthread_key_delete(*ptkeyPtr)) {
        Tcl_Panic("unable to delete key!");
@@ -793,22 +794,22 @@ TclpThreadDeleteKey(
 }
 
 void
-TclpThreadSetMasterTSD(
+TclpThreadSetGlobalTSD(
     void *tsdKeyPtr,
     void *ptr)
 {
-    pthread_key_t *ptkeyPtr = tsdKeyPtr;
+    pthread_key_t *ptkeyPtr = (pthread_key_t *)tsdKeyPtr;
 
     if (pthread_setspecific(*ptkeyPtr, ptr)) {
-       Tcl_Panic("unable to set master TSD value");
+       Tcl_Panic("unable to set global TSD value");
     }
 }
 
 void *
-TclpThreadGetMasterTSD(
+TclpThreadGetGlobalTSD(
     void *tsdKeyPtr)
 {
-    pthread_key_t *ptkeyPtr = tsdKeyPtr;
+    pthread_key_t *ptkeyPtr = (pthread_key_t *)tsdKeyPtr;
 
     return pthread_getspecific(*ptkeyPtr);
 }
index d24575f..c6cdf89 100644 (file)
@@ -49,6 +49,9 @@ LIB_INSTALL_DIR               = $(INSTALL_ROOT)$(libdir)
 # Path name to use when installing library scripts.
 SCRIPT_INSTALL_DIR     = $(INSTALL_ROOT)$(TCL_LIBRARY)
 
+# Path name to use when installing Tcl modules.
+MODULE_INSTALL_DIR     = $(SCRIPT_INSTALL_DIR)/../tcl8
+
 # Directory in which to install the include file tcl.h:
 INCLUDE_INSTALL_DIR    = $(INSTALL_ROOT)$(includedir)
 
@@ -82,7 +85,7 @@ CFLAGS_OPTIMIZE       = @CFLAGS_OPTIMIZE@
 #CFLAGS =              $(CFLAGS_DEBUG)
 #CFLAGS =              $(CFLAGS_OPTIMIZE)
 #CFLAGS =              $(CFLAGS_DEBUG) $(CFLAGS_OPTIMIZE)
-CFLAGS =               @CFLAGS@ @CFLAGS_DEFAULT@ -D_ATL_XP_TARGETING -DMP_FIXED_CUTOFFS -DMP_NO_STDINT
+CFLAGS =               @CFLAGS@ @CFLAGS_DEFAULT@ -D_ATL_XP_TARGETING=1 -D__USE_MINGW_ANSI_STDIO=0 -DMP_FIXED_CUTOFFS -DMP_NO_STDINT
 
 # To compile without backward compatibility and deprecated code uncomment the
 # following
@@ -117,6 +120,9 @@ GENERIC_DIR_NATIVE  = $(shell $(CYGPATH) '$(GENERIC_DIR)')
 TOMMATH_DIR_NATIVE     = $(shell $(CYGPATH) '$(TOMMATH_DIR)')
 WIN_DIR_NATIVE         = $(shell $(CYGPATH) '$(WIN_DIR)')
 ROOT_DIR_NATIVE                = $(shell $(CYGPATH) '$(ROOT_DIR)')
+SCRIPT_INSTALL_DIR_NATIVE      = $(shell $(CYGPATH) '$(SCRIPT_INSTALL_DIR)')
+INCLUDE_INSTALL_DIR_NATIVE     = $(shell $(CYGPATH) '$(INCLUDE_INSTALL_DIR)')
+MAN_INSTALL_DIR_NATIVE = $(shell $(CYGPATH) '$(MAN_INSTALL_DIR)')
 ROOT_DIR_WIN_NATIVE    = $(shell cd '$(ROOT_DIR)' ; pwd -W 2>/dev/null || pwd -P)
 ZLIB_DIR_NATIVE                = $(shell $(CYGPATH) '$(ZLIB_DIR)')
 #GENERIC_DIR_NATIVE    = $(GENERIC_DIR)
@@ -143,15 +149,15 @@ TCL_STUB_LIB_FILE = @TCL_STUB_LIB_FILE@
 TCL_DLL_FILE           = @TCL_DLL_FILE@
 TCL_LIB_FILE           = @TCL_LIB_FILE@
 DDE_DLL_FILE           = tcldde$(DDEVER)${DLLSUFFIX}
-DDE_LIB_FILE           = @LIBPREFIX@tcldde$(DDEVER)${LIBSUFFIX}
+DDE_LIB_FILE           = @LIBPREFIX@tcldde$(DDEVER)${DLLSUFFIX}${LIBSUFFIX}
 REG_DLL_FILE           = tclreg$(REGVER)${DLLSUFFIX}
-REG_LIB_FILE           = @LIBPREFIX@tclreg$(REGVER)${LIBSUFFIX}
+REG_LIB_FILE           = @LIBPREFIX@tclreg$(REGVER)${DLLSUFFIX}${LIBSUFFIX}
 TEST_DLL_FILE          = tcltest$(VER)${DLLSUFFIX}
 TEST_EXE_FILE          = tcltest${EXESUFFIX}
-TEST_LIB_FILE          = @LIBPREFIX@tcltest$(VER)${LIBSUFFIX}
-TEST_LOAD_PRMS         = package ifneeded dde 1.4.2 [list load [file normalize ${DDE_DLL_FILE}] dde];\
-                         package ifneeded registry 1.3.4 [list load [file normalize ${REG_DLL_FILE}] registry]
-TEST_LOAD_FACILITIES   = package ifneeded Tcltest ${VERSION}@TCL_PATCH_LEVEL@ [list load [file normalize ${TEST_DLL_FILE}] Tcltest];\
+TEST_LIB_FILE          = @LIBPREFIX@tcltest$(VER)${DLLSUFFIX}${LIBSUFFIX}
+TEST_LOAD_PRMS         = package ifneeded dde 1.4.3 [list load [file normalize ${DDE_DLL_FILE}] Dde];\
+                         package ifneeded registry 1.3.5 [list load [file normalize ${REG_DLL_FILE}] Registry]
+TEST_LOAD_FACILITIES   = package ifneeded Tcltest ${VERSION}@TCL_PATCH_LEVEL@ [list load [file normalize ${TEST_DLL_FILE}]];\
                          $(TEST_LOAD_PRMS)
 ZLIB_DLL_FILE          = zlib1.dll
 
@@ -203,7 +209,7 @@ SHELL               = @SHELL@
 RM             = rm -f
 COPY           = cp
 
-CC_SWITCHES = ${CFLAGS} ${CFLAGS_WARNING} ${TCL_SHLIB_CFLAGS} \
+CC_SWITCHES = ${CFLAGS} ${CFLAGS_WARNING} ${SHLIB_CFLAGS} \
 -I"${ZLIB_DIR_NATIVE}" -I"${GENERIC_DIR_NATIVE}" -DTCL_TOMMATH \
 -DMP_PREC=4 -I"${TOMMATH_DIR_NATIVE}" -I"${WIN_DIR_NATIVE}" \
 ${AC_FLAGS} ${COMPILE_DEBUG_FLAGS} ${NO_DEPRECATED_FLAGS}
@@ -563,7 +569,7 @@ tclPkgConfig.${OBJEXT}: tclPkgConfig.c
                -DCFG_INSTALL_BINDIR="\"$(BIN_INSTALL_DIR_NATIVE)\"" \
                -DCFG_INSTALL_SCRDIR="\"$(SCRIPT_INSTALL_DIR_NATIVE)\"" \
                -DCFG_INSTALL_INCDIR="\"$(INCLUDE_INSTALL_DIR_NATIVE)\"" \
-               -DCFG_INSTALL_DOCDIR="\"$(MAN_INSTALL_DIR)\"" \
+               -DCFG_INSTALL_DOCDIR="\"$(MAN_INSTALL_DIR_NATIVE)\"" \
                \
                -DCFG_RUNTIME_LIBDIR="\"$(libdir_native)\"" \
                -DCFG_RUNTIME_BINDIR="\"$(bindir_native)\"" \
@@ -618,18 +624,18 @@ install: all install-binaries install-libraries install-doc install-packages
 install-binaries: binaries
        @for i in "$(LIB_INSTALL_DIR)" "$(BIN_INSTALL_DIR)" ; \
            do \
-           if [ ! -d $$i ] ; then \
+           if [ ! -d "$$i" ] ; then \
                echo "Making directory $$i"; \
-               $(MKDIR) $$i; \
-               chmod 755 $$i; \
+               $(MKDIR) "$$i"; \
+               chmod 755 "$$i"; \
                else true; \
                fi; \
            done;
        @for i in dde${DDEDOTVER} reg${REGDOTVER}; \
            do \
-           if [ ! -d $(LIB_INSTALL_DIR)/$$i ] ; then \
+           if [ ! -d "$(LIB_INSTALL_DIR)/$$i" ] ; then \
                echo "Making directory $(LIB_INSTALL_DIR)/$$i"; \
-               $(MKDIR) $(LIB_INSTALL_DIR)/$$i; \
+               $(MKDIR) "$(LIB_INSTALL_DIR)/$$i"; \
                else true; \
                fi; \
            done;
@@ -649,40 +655,48 @@ install-binaries: binaries
            done
        @if [ -f $(DDE_DLL_FILE) ]; then \
            echo Installing $(DDE_DLL_FILE); \
-           $(COPY) $(DDE_DLL_FILE) $(LIB_INSTALL_DIR)/dde${DDEDOTVER}; \
+           $(COPY) $(DDE_DLL_FILE) "$(LIB_INSTALL_DIR)/dde${DDEDOTVER}"; \
            $(COPY) $(ROOT_DIR)/library/dde/pkgIndex.tcl \
-               $(LIB_INSTALL_DIR)/dde${DDEDOTVER}; \
+               "$(LIB_INSTALL_DIR)/dde${DDEDOTVER}"; \
            fi
        @if [ -f $(DDE_LIB_FILE) ]; then \
            echo Installing $(DDE_LIB_FILE); \
-           $(COPY) $(DDE_LIB_FILE) $(LIB_INSTALL_DIR)/dde${DDEDOTVER}; \
+           $(COPY) $(DDE_LIB_FILE) "$(LIB_INSTALL_DIR)/dde${DDEDOTVER}"; \
            fi
        @if [ -f $(REG_DLL_FILE) ]; then \
            echo Installing $(REG_DLL_FILE); \
-           $(COPY) $(REG_DLL_FILE) $(LIB_INSTALL_DIR)/reg${REGDOTVER}; \
+           $(COPY) $(REG_DLL_FILE) "$(LIB_INSTALL_DIR)/reg${REGDOTVER}"; \
            $(COPY) $(ROOT_DIR)/library/reg/pkgIndex.tcl \
-               $(LIB_INSTALL_DIR)/reg${REGDOTVER}; \
+               "$(LIB_INSTALL_DIR)/reg${REGDOTVER}"; \
            fi
        @if [ -f $(REG_LIB_FILE) ]; then \
            echo Installing $(REG_LIB_FILE); \
-           $(COPY) $(REG_LIB_FILE) $(LIB_INSTALL_DIR)/reg${REGDOTVER}; \
+           $(COPY) $(REG_LIB_FILE) "$(LIB_INSTALL_DIR)/reg${REGDOTVER}"; \
            fi
 
 install-libraries: libraries install-tzdata install-msgs
-       @for i in "$$($(CYGPATH) $(prefix)/lib)" "$(INCLUDE_INSTALL_DIR)" \
-               $(SCRIPT_INSTALL_DIR); \
+       @for i in "$(prefix)/lib" "$(INCLUDE_INSTALL_DIR)" \
+               "$(SCRIPT_INSTALL_DIR)" "$(MODULE_INSTALL_DIR)"; \
            do \
-           if [ ! -d $$i ] ; then \
+           if [ ! -d "$$i" ] ; then \
                echo "Making directory $$i"; \
-               $(MKDIR) $$i; \
+               $(MKDIR) "$$i"; \
                else true; \
                fi; \
            done;
-       @for i in http1.0 opt0.4 encoding ../tcl8 ../tcl8/8.4  ../tcl8/8.4/platform ../tcl8/8.5 ../tcl8/8.6; \
+       @for i in http1.0 opt0.4 encoding; \
            do \
-           if [ ! -d $(SCRIPT_INSTALL_DIR)/$$i ] ; then \
+           if [ ! -d "$(SCRIPT_INSTALL_DIR)/$$i" ] ; then \
                echo "Making directory $(SCRIPT_INSTALL_DIR)/$$i"; \
-               $(MKDIR) $(SCRIPT_INSTALL_DIR)/$$i; \
+               $(MKDIR) "$(SCRIPT_INSTALL_DIR)/$$i"; \
+               else true; \
+               fi; \
+           done;
+       @for i in 8.4  8.4/platform 8.5 8.6; \
+           do \
+           if [ ! -d "$(MODULE_INSTALL_DIR)/$$i" ] ; then \
+               echo "Making directory $(MODULE_INSTALL_DIR)/$$i"; \
+               $(MKDIR) "$(MODULE_INSTALL_DIR)/$$i"; \
                else true; \
                fi; \
            done;
@@ -705,21 +719,21 @@ install-libraries: libraries install-tzdata install-msgs
            do \
            $(COPY) "$$j" "$(SCRIPT_INSTALL_DIR)/http1.0"; \
            done;
-       @echo "Installing package http 2.9.1 as a Tcl Module";
-       @$(COPY) $(ROOT_DIR)/library/http/http.tcl $(SCRIPT_INSTALL_DIR)/../tcl8/8.6/http-2.9.1.tm;
+       @echo "Installing package http 2.9.5 as a Tcl Module";
+       @$(COPY) $(ROOT_DIR)/library/http/http.tcl "$(MODULE_INSTALL_DIR)/8.6/http-2.9.5.tm";
        @echo "Installing library opt0.4 directory";
        @for j in $(ROOT_DIR)/library/opt/*.tcl; \
            do \
            $(COPY) "$$j" "$(SCRIPT_INSTALL_DIR)/opt0.4"; \
            done;
        @echo "Installing package msgcat 1.6.1 as a Tcl Module";
-       @$(COPY) $(ROOT_DIR)/library/msgcat/msgcat.tcl $(SCRIPT_INSTALL_DIR)/../tcl8/8.5/msgcat-1.6.1.tm;
-       @echo "Installing package tcltest 2.5.1 as a Tcl Module";
-       @$(COPY) $(ROOT_DIR)/library/tcltest/tcltest.tcl $(SCRIPT_INSTALL_DIR)/../tcl8/8.5/tcltest-2.5.1.tm;
-       @echo "Installing package platform 1.0.14 as a Tcl Module";
-       @$(COPY) $(ROOT_DIR)/library/platform/platform.tcl $(SCRIPT_INSTALL_DIR)/../tcl8/8.4/platform-1.0.14.tm;
+       @$(COPY) $(ROOT_DIR)/library/msgcat/msgcat.tcl "$(MODULE_INSTALL_DIR)/8.5/msgcat-1.6.1.tm";
+       @echo "Installing package tcltest 2.5.3 as a Tcl Module";
+       @$(COPY) $(ROOT_DIR)/library/tcltest/tcltest.tcl "$(MODULE_INSTALL_DIR)/8.5/tcltest-2.5.3.tm";
+       @echo "Installing package platform 1.0.15 as a Tcl Module";
+       @$(COPY) $(ROOT_DIR)/library/platform/platform.tcl "$(MODULE_INSTALL_DIR)/8.4/platform-1.0.15.tm";
        @echo "Installing package platform::shell 1.1.4 as a Tcl Module";
-       @$(COPY) $(ROOT_DIR)/library/platform/shell.tcl $(SCRIPT_INSTALL_DIR)/../tcl8/8.4/platform/shell-1.1.4.tm;
+       @$(COPY) $(ROOT_DIR)/library/platform/shell.tcl "$(MODULE_INSTALL_DIR)/8.4/platform/shell-1.1.4.tm";
        @echo "Installing encodings";
        @for i in $(ROOT_DIR)/library/encoding/*.enc ; do \
                $(COPY) "$$i" "$(SCRIPT_INSTALL_DIR)/encoding"; \
@@ -728,12 +742,12 @@ install-libraries: libraries install-tzdata install-msgs
 install-tzdata:
        @echo "Installing time zone data"
        @$(TCL_EXE) "$(ROOT_DIR)/tools/installData.tcl" \
-           "$(ROOT_DIR)/library/tzdata" "$(SCRIPT_INSTALL_DIR)/tzdata"
+           "$(ROOT_DIR)/library/tzdata" "$(SCRIPT_INSTALL_DIR_NATIVE)/tzdata"
 
 install-msgs:
        @echo "Installing message catalogs"
-       @$(TCL_EXE) "$(ROOT_DIR)/tools/installData.tcl" \
-           "$(ROOT_DIR)/library/msgs" "$(SCRIPT_INSTALL_DIR)/msgs"
+       $(TCL_EXE) "$(ROOT_DIR)/tools/installData.tcl" \
+           "$(ROOT_DIR)/library/msgs" "$(SCRIPT_INSTALL_DIR_NATIVE)/msgs"
 
 install-doc: doc
 
index c6f95f5..e3addbf 100755 (executable)
@@ -1312,7 +1312,7 @@ SHELL=/bin/sh
 TCL_VERSION=8.6
 TCL_MAJOR_VERSION=8
 TCL_MINOR_VERSION=6
-TCL_PATCH_LEVEL=".10"
+TCL_PATCH_LEVEL=".11"
 VER=$TCL_MAJOR_VERSION$TCL_MINOR_VERSION
 
 TCL_DDE_VERSION=1.4
@@ -3133,14 +3133,6 @@ if test "${enable_shared+set}" = set; then
 else
   tcl_ok=yes
 fi;
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
     if test "$tcl_ok" = "yes" ; then
        echo "$as_me:$LINENO: result: shared" >&5
 echo "${ECHO_T}shared" >&6
@@ -3182,78 +3174,6 @@ fi
 # after SC_ENABLE_SHARED checks the configure switches.
 #--------------------------------------------------------------------
 
-# 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
-
-
 
 
     # Step 0: Enable 64 bit support?
@@ -3412,14 +3332,14 @@ echo "${ECHO_T}$ac_cv_cross" >&6
       if test "$ac_cv_cross" = "yes"; then
        case "$do64bit" in
            amd64|x64|yes)
-               CC="x86_64-w64-mingw32-gcc"
+               CC="x86_64-w64-mingw32-${CC}"
                LD="x86_64-w64-mingw32-ld"
                AR="x86_64-w64-mingw32-ar"
                RANLIB="x86_64-w64-mingw32-ranlib"
                RC="x86_64-w64-mingw32-windres"
            ;;
            *)
-               CC="i686-w64-mingw32-gcc"
+               CC="i686-w64-mingw32-${CC}"
                LD="i686-w64-mingw32-ld"
                AR="i686-w64-mingw32-ar"
                RANLIB="i686-w64-mingw32-ranlib"
@@ -3656,7 +3576,7 @@ echo "$as_me: error: ${CC} does not support the -shared option.
        SHLIB_LD='${CC} -shared'
        SHLIB_LD_LIBS='${LIBS}'
        MAKE_DLL="\${SHLIB_LD} \$(LDFLAGS) -o \$@ ${extra_ldflags} \
-           -Wl,--out-implib,\$(patsubst %.dll,lib%.a,\$@)"
+           -Wl,--out-implib,\$(patsubst %.dll,lib%.dll.a,\$@)"
        # DLLSUFFIX is separate because it is the building block for
        # users of tclConfig.sh that may build shared or static.
        DLLSUFFIX="\${DBGX}.dll"
@@ -3668,10 +3588,19 @@ echo "$as_me: error: ${CC} does not support the -shared option.
 
        CFLAGS_DEBUG=-g
        CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-       CFLAGS_WARNING="-Wall -Wdeclaration-after-statement"
+       CFLAGS_WARNING="-Wall -Wpointer-arith"
        LDFLAGS_DEBUG=
        LDFLAGS_OPTIMIZE=
 
+       case "${CC}" in
+           *++)
+               CFLAGS_WARNING="${CFLAGS_WARNING} -Wno-format"
+               ;;
+           *)
+               CFLAGS_WARNING="${CFLAGS_WARNING} -Wdeclaration-after-statement"
+               ;;
+       esac
+
        # Specify the CC output file names based on the target name
        CC_OBJNAME="-o \$@"
        CC_EXENAME="-o \$@"
@@ -3794,29 +3723,15 @@ echo "${ECHO_T}using shared flags" >&6
        LIBSUFFIX="\${DBGX}.lib"
        LIBFLAGSUFFIX="\${DBGX}"
 
-       # This is a 2-stage check to make sure we have the 64-bit SDK
-       # We have to know where the SDK is installed.
-       # This magic is based on MS Platform SDK for Win2003 SP1 - hobbs
        if test "$do64bit" != "no" ; then
-           if test "x${MSSDK}x" = "xx" ; then
-               MSSDK="C:/Progra~1/Microsoft Platform SDK"
-           fi
-           MSSDK=`echo "$MSSDK" | sed -e 's!\\\!/!g'`
-           PATH64=""
            case "$do64bit" in
                amd64|x64|yes)
                    MACHINE="AMD64" ; # assume AMD64 as default 64-bit build
-                   PATH64="${MSSDK}/Bin/Win64/x86/AMD64"
                    ;;
                ia64)
                    MACHINE="IA64"
-                   PATH64="${MSSDK}/Bin/Win64"
                    ;;
            esac
-           if test ! -d "${PATH64}" ; then
-               { echo "$as_me:$LINENO: WARNING: Could not find 64-bit $MACHINE SDK" >&5
-echo "$as_me: WARNING: Could not find 64-bit $MACHINE SDK" >&2;}
-           fi
            echo "$as_me:$LINENO: result:    Using 64-bit $MACHINE mode" >&5
 echo "${ECHO_T}   Using 64-bit $MACHINE mode" >&6
        fi
@@ -3832,81 +3747,12 @@ echo "${ECHO_T}   Using 64-bit $MACHINE mode" >&6
        esac
 
        if test "$do64bit" != "no" ; then
-           # The space-based-path will work for the Makefile, but will
-           # not work if AC_TRY_COMPILE is called.  TEA has the
-           # TEA_PATH_NOSPACE to avoid this issue.
-           # Check if _WIN64 is already recognized, and if so we don't
-           # need to modify CC.
-           echo "$as_me:$LINENO: checking whether _WIN64 is declared" >&5
-echo $ECHO_N "checking whether _WIN64 is declared... $ECHO_C" >&6
-if test "${ac_cv_have_decl__WIN64+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 ()
-{
-#ifndef _WIN64
-  char *p = (char *) _WIN64;
-#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_have_decl__WIN64=yes
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-ac_cv_have_decl__WIN64=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_have_decl__WIN64" >&5
-echo "${ECHO_T}$ac_cv_have_decl__WIN64" >&6
-if test $ac_cv_have_decl__WIN64 = yes; then
-  :
-else
-  CC="\"${PATH64}/cl.exe\" -I\"${MSSDK}/Include\" \
-                        -I\"${MSSDK}/Include/crt\" \
-                        -I\"${MSSDK}/Include/crt/sys\""
-fi
-
-           RC="\"${MSSDK}/bin/rc.exe\""
+           RC="rc"
            CFLAGS_DEBUG="-nologo -Zi -Od ${runtime}d"
            # Do not use -O2 for Win64 - this has proved buggy in code gen.
            CFLAGS_OPTIMIZE="-nologo -O1 ${runtime}"
-           lflags="${lflags} -nologo -MACHINE:${MACHINE} -LIBPATH:\"${MSSDK}/Lib/${MACHINE}\""
-           LINKBIN="\"${PATH64}/link.exe\""
+           lflags="${lflags} -nologo -MACHINE:${MACHINE}"
+           LINKBIN="link"
            # Avoid 'unresolved external symbol __security_cookie' errors.
            # c.f. http://support.microsoft.com/?id=894573
            LIBS="$LIBS bufferoverflowU.lib"
@@ -4430,6 +4276,78 @@ cat >>confdefs.h <<\_ACEOF
 _ACEOF
 
 
+# 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
+
+
 echo "$as_me:$LINENO: checking for intptr_t" >&5
 echo $ECHO_N "checking for intptr_t... $ECHO_C" >&6
 if test "${ac_cv_type_intptr_t+set}" = set; then
@@ -5138,10 +5056,6 @@ TCL_SHARED_BUILD=${SHARED_BUILD}
 # Perform final evaluations of variables with possible substitutions.
 #--------------------------------------------------------------------
 
-TCL_SHARED_LIB_SUFFIX="\${NODOT_VERSION}${DLLSUFFIX}"
-TCL_UNSHARED_LIB_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
-TCL_EXPORT_FILE_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
-
 eval "TCL_SRC_DIR=\"`cd $srcdir/..; $CYGPATH $(pwd)`\""
 
 eval "TCL_DLL_FILE=tcl${VER}${DLLSUFFIX}"
@@ -5153,19 +5067,26 @@ eval "TCL_STUB_LIB_SPEC=\"-L${libdir} ${TCL_STUB_LIB_FLAG}\""
 eval "TCL_BUILD_STUB_LIB_PATH=\"`$CYGPATH $(pwd)`/${TCL_STUB_LIB_FILE}\""
 eval "TCL_STUB_LIB_PATH=\"${libdir}/${TCL_STUB_LIB_FILE}\""
 
-eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${LIBSUFFIX}\""
+if test ${SHARED_BUILD} = 0 ; then
+ eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${LIBSUFFIX}\""
+else
+ eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${DLLSUFFIX}.a\""
+fi
 eval "TCL_BUILD_LIB_SPEC=\"-L`$CYGPATH $(pwd)` -ltcl${VER}${FLAGSUFFIX}\""
 eval "TCL_LIB_SPEC=\"-L${libdir} -ltcl${VER}${FLAGSUFFIX}\""
 
 # Install time header dir can be set via --includedir
 eval "TCL_INCLUDE_SPEC=\"-I${includedir}\""
 
-
 eval "DLLSUFFIX=${DLLSUFFIX}"
 eval "LIBPREFIX=${LIBPREFIX}"
 eval "LIBSUFFIX=${LIBSUFFIX}"
 eval "EXESUFFIX=${EXESUFFIX}"
 
+TCL_SHARED_LIB_SUFFIX="\${NODOT_VERSION}${DLLSUFFIX}"
+TCL_UNSHARED_LIB_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
+TCL_EXPORT_FILE_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
+
 CFG_TCL_SHARED_LIB_SUFFIX=${TCL_SHARED_LIB_SUFFIX}
 CFG_TCL_UNSHARED_LIB_SUFFIX=${TCL_UNSHARED_LIB_SUFFIX}
 CFG_TCL_EXPORT_FILE_SUFFIX=${TCL_EXPORT_FILE_SUFFIX}
@@ -5197,9 +5118,9 @@ fi
 #--------------------------------------------------------------------
 
 if test "$prefix/lib" != "$libdir"; then
-    TCL_PACKAGE_PATH="${libdir} ${prefix}/lib"
+    TCL_PACKAGE_PATH="{${libdir}} {${prefix}/lib}"
 else
-    TCL_PACKAGE_PATH="${prefix}/lib"
+    TCL_PACKAGE_PATH="{${prefix}/lib}"
 fi
 
 # The tclsh.exe.manifest requires these
index cae6568..7050726 100644 (file)
@@ -14,7 +14,7 @@ SHELL=/bin/sh
 TCL_VERSION=8.6
 TCL_MAJOR_VERSION=8
 TCL_MINOR_VERSION=6
-TCL_PATCH_LEVEL=".10"
+TCL_PATCH_LEVEL=".11"
 VER=$TCL_MAJOR_VERSION$TCL_MINOR_VERSION
 
 TCL_DDE_VERSION=1.4
@@ -300,10 +300,6 @@ TCL_SHARED_BUILD=${SHARED_BUILD}
 # Perform final evaluations of variables with possible substitutions.
 #--------------------------------------------------------------------
 
-TCL_SHARED_LIB_SUFFIX="\${NODOT_VERSION}${DLLSUFFIX}"
-TCL_UNSHARED_LIB_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
-TCL_EXPORT_FILE_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
-
 eval "TCL_SRC_DIR=\"`cd $srcdir/..; $CYGPATH $(pwd)`\""
 
 eval "TCL_DLL_FILE=tcl${VER}${DLLSUFFIX}"
@@ -315,19 +311,26 @@ eval "TCL_STUB_LIB_SPEC=\"-L${libdir} ${TCL_STUB_LIB_FLAG}\""
 eval "TCL_BUILD_STUB_LIB_PATH=\"`$CYGPATH $(pwd)`/${TCL_STUB_LIB_FILE}\""
 eval "TCL_STUB_LIB_PATH=\"${libdir}/${TCL_STUB_LIB_FILE}\""
 
-eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${LIBSUFFIX}\""
+if test ${SHARED_BUILD} = 0 ; then
+ eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${LIBSUFFIX}\""
+else
+ eval "TCL_LIB_FILE=\"${LIBPREFIX}tcl${VER}${DLLSUFFIX}.a\""
+fi
 eval "TCL_BUILD_LIB_SPEC=\"-L`$CYGPATH $(pwd)` -ltcl${VER}${FLAGSUFFIX}\""
 eval "TCL_LIB_SPEC=\"-L${libdir} -ltcl${VER}${FLAGSUFFIX}\""
 
 # Install time header dir can be set via --includedir
 eval "TCL_INCLUDE_SPEC=\"-I${includedir}\""
 
-
 eval "DLLSUFFIX=${DLLSUFFIX}"
 eval "LIBPREFIX=${LIBPREFIX}"
 eval "LIBSUFFIX=${LIBSUFFIX}"
 eval "EXESUFFIX=${EXESUFFIX}"
 
+TCL_SHARED_LIB_SUFFIX="\${NODOT_VERSION}${DLLSUFFIX}"
+TCL_UNSHARED_LIB_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
+TCL_EXPORT_FILE_SUFFIX="\${NODOT_VERSION}${LIBSUFFIX}"
+
 CFG_TCL_SHARED_LIB_SUFFIX=${TCL_SHARED_LIB_SUFFIX}
 CFG_TCL_UNSHARED_LIB_SUFFIX=${TCL_UNSHARED_LIB_SUFFIX}
 CFG_TCL_EXPORT_FILE_SUFFIX=${TCL_EXPORT_FILE_SUFFIX}
@@ -359,9 +362,9 @@ fi
 #--------------------------------------------------------------------
 
 if test "$prefix/lib" != "$libdir"; then
-    TCL_PACKAGE_PATH="${libdir} ${prefix}/lib"
+    TCL_PACKAGE_PATH="{${libdir}} {${prefix}/lib}"
 else
-    TCL_PACKAGE_PATH="${prefix}/lib"
+    TCL_PACKAGE_PATH="{${prefix}/lib}"
 fi
 
 # The tclsh.exe.manifest requires these
index 9b36abf..60b6bf0 100644 (file)
@@ -16,7 +16,7 @@
 # General usage:\r
 #   nmake [-nologo] -f makefile.vc [TARGET|MACRODEF [TARGET|MACRODEF] [...]]\r
 #\r
-# For MACRODEF, see TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md)\r
+# For MACRODEF, see TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md)\r
 # or examine Sections 6-8 in rules.vc.\r
 #\r
 # Possible values of TARGET are:\r
 # turn on the 64-bit compiler, if your SDK has it.\r
 #\r
 # Basic macros and options usable on the commandline (see rules.vc for more info):\r
-#      OPTS=msvcrt,static,staticpkg,symbols,nothreads,profile,unchecked,time64bit,none\r
+#      OPTS=msvcrt,nothreads,pdbs,profile,static,staticpkg,symbols,thrdalloc,time64bit,unchecked,utfmax,none\r
 #              Sets special options for the core.  The default is for none.\r
 #              Any combination of the above may be used (comma separated).\r
 #              'none' will over-ride everything to nothing.\r
 #\r
-#              msvcrt   = Affects the static option only to switch it from\r
-#                         using libcmt(d) as the C runtime [by default] to\r
-#                         msvcrt(d). This is useful for static embedding\r
-#                         support.\r
-#              static   = Builds a static library of the core instead of a\r
-#                         dll.  The shell will be static (and large), as well.\r
-#              staticpkg= Affects the static option only to switch\r
-#                         tclshXX.exe to have the dde and reg extension linked\r
-#                         inside it.\r
-#              nothreads  = Turns off full multithreading support (default on).\r
+#              msvcrt    = Affects the static option only to switch it from\r
+#                          using libcmt(d) as the C runtime [by default] to\r
+#                          msvcrt(d). This is useful for static embedding\r
+#                          support.\r
+#              nothreads = Turns off full multithreading support (default on).\r
+#              pbds      =  Produce separate debug symbol files.\r
+#              profile   =  Adds profiling hooks.  Map file is assumed.\r
+#              static    = Builds a static library of the core instead of a\r
+#                          dll.  The shell will be static (and large), as well.\r
+#              staticpkg = Affects the static option only to switch\r
+#                          tclshXX.exe to have the dde and reg extension linked\r
+#                          inside it.\r
+#              symbols   =  Adds symbols for step debugging.\r
 #              thrdalloc = Use the thread allocator (shared global free pool).\r
-#              symbols =  Adds symbols for step debugging.\r
-#              profile =  Adds profiling hooks.  Map file is assumed.\r
-#              unchecked = Allows a symbols build to not use the debug\r
-#                         enabled runtime (msvcrt.dll not msvcrtd.dll\r
-#                         or libcmt.lib not libcmtd.lib).\r
 #              time64bit = Forces a build using 64-bit time_t for 32-bit build\r
-#                         (CRT library should support this).\r
+#                          (CRT library should support this).\r
+#              unchecked = Allows a symbols build to not use the debug\r
+#                          enabled runtime (msvcrt.dll not msvcrtd.dll\r
+#                          or libcmt.lib not libcmtd.lib).\r
+#              utfmax    = Forces a build allowing 4-byte UTF-8 sequences\r
+#                          internally.\r
 #\r
 #      STATS=compdbg,memdbg,none\r
 #              Sets optional memory and bytecode compiler debugging code added\r
 #      TESTPAT=<file>\r
 #              Reads the tests requested to be run from this file.\r
 #\r
-#      CFG_ENCODING=encoding\r
-#              name of encoding for configuration information. Defaults\r
-#              to cp1252\r
-#\r
 # Examples:\r
 #       c:\tcl_src\win\>nmake -f makefile.vc release\r
 #       c:\tcl_src\win\>nmake -f makefile.vc test\r
@@ -153,6 +152,9 @@ VERSION         = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)
 !if [echo PKG_HTTP_VER = \>> versions.vc] \\r
    && [nmakehlp -V ..\library\http\pkgIndex.tcl http >> versions.vc]\r
 !endif\r
+!if [echo PKG_OPT_VER = \>> versions.vc] \\r
+   && [nmakehlp -V ..\library\opt\pkgIndex.tcl opt >> versions.vc]\r
+!endif\r
 !if [echo PKG_TCLTEST_VER = \>> versions.vc] \\r
    && [nmakehlp -V ..\library\tcltest\pkgIndex.tcl tcltest >> versions.vc]\r
 !endif\r
@@ -415,7 +417,7 @@ PKGSDIR             = $(ROOT)\pkgs
 # Additional include and C macro definitions for the implicit rules\r
 # defined in rules.vc\r
 PRJ_INCLUDES   = -I"$(TOMMATHDIR)"\r
-PRJ_DEFINES    = /DTCL_TOMMATH /DMP_PREC=4 /Dinline=__inline /DHAVE_ZLIB=1 /D_CRT_SECURE_NO_DEPRECATE /D_CRT_NONSTDC_NO_DEPRECATE /DMP_FIXED_CUTOFFS /DMP_NO_STDINT\r
+PRJ_DEFINES    = /DTCL_TOMMATH /DMP_PREC=4 /Dinline=__inline /DHAVE_ZLIB=1 /D_CRT_SECURE_NO_DEPRECATE /D_CRT_NONSTDC_NO_DEPRECATE /DMP_FIXED_CUTOFFS\r
 \r
 # Additional Link libraries needed beyond those in rules.vc\r
 PRJ_LIBS   = netapi32.lib user32.lib userenv.lib ws2_32.lib\r
@@ -449,8 +451,8 @@ test: test-core test-pkgs
 test-core: setup $(TCLTEST) dlls $(CAT32)\r
        set TCL_LIBRARY=$(ROOT:\=/)/library\r
        $(DEBUGGER) $(TCLTEST) "$(ROOT:\=/)/tests/all.tcl" $(TESTFLAGS) -loadfile <<\r
-               package ifneeded dde 1.4.2 [list load "$(TCLDDELIB:\=/)" dde]\r
-               package ifneeded registry 1.3.4 [list load "$(TCLREGLIB:\=/)" registry]\r
+               package ifneeded dde 1.4.3 [list load "$(TCLDDELIB:\=/)" Dde]\r
+               package ifneeded registry 1.3.5 [list load "$(TCLREGLIB:\=/)" Registry]\r
 <<\r
 \r
 runtest: setup $(TCLTEST) dlls $(CAT32)\r
@@ -872,16 +874,18 @@ install-binaries:
 install-libraries: tclConfig tcl-nmake install-msgs install-tzdata\r
        @if not exist "$(SCRIPT_INSTALL_DIR)" \\r
                $(MKDIR) "$(SCRIPT_INSTALL_DIR)"\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)\..\tcl8" \\r
-               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\..\tcl8"\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4" \\r
-               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4"\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4\platform" \\r
-               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4\platform"\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.5" \\r
-               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.5"\r
-       @if not exist "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.6" \\r
-               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.6"\r
+       @if not exist "$(SCRIPT_INSTALL_DIR)\opt0.4" \\r
+               $(MKDIR) "$(SCRIPT_INSTALL_DIR)\opt0.4"\r
+       @if not exist "$(MODULE_INSTALL_DIR)" \\r
+               $(MKDIR) "$(MODULE_INSTALL_DIR)"\r
+       @if not exist "$(MODULE_INSTALL_DIR)\8.4" \\r
+               $(MKDIR) "$(MODULE_INSTALL_DIR)\8.4"\r
+       @if not exist "$(MODULE_INSTALL_DIR)\8.4\platform" \\r
+               $(MKDIR) "$(MODULE_INSTALL_DIR)\8.4\platform"\r
+       @if not exist "$(MODULE_INSTALL_DIR)\8.5" \\r
+               $(MKDIR) "$(MODULE_INSTALL_DIR)\8.5"\r
+       @if not exist "$(MODULE_INSTALL_DIR)\8.6" \\r
+               $(MKDIR) "$(MODULE_INSTALL_DIR)\8.6"\r
        @if not exist "$(LIB_INSTALL_DIR)\nmake" \\r
                $(MKDIR) "$(LIB_INSTALL_DIR)\nmake"\r
        @echo Installing header files\r
@@ -909,27 +913,27 @@ install-libraries: tclConfig tcl-nmake install-msgs install-tzdata
        @$(CPY) "$(WIN_DIR)\targets.vc"              "$(LIB_INSTALL_DIR)\nmake\"\r
        @$(CPY) "$(WIN_DIR)\nmakehlp.c"            "$(LIB_INSTALL_DIR)\nmake\"\r
        @$(CPY) "$(OUT_DIR)\tcl.nmake"            "$(LIB_INSTALL_DIR)\nmake\"\r
-       @echo Installing library http1.0 directory\r
+       @echo Installing package http 1.0 (obsolete)\r
        @$(CPY) "$(ROOT)\library\http1.0\*.tcl" \\r
            "$(SCRIPT_INSTALL_DIR)\http1.0\"\r
-       @echo Installing library opt0.4 directory\r
+       @echo Installing package opt $(PKG_OPT_VER)\r
        @$(CPY) "$(ROOT)\library\opt\*.tcl" \\r
            "$(SCRIPT_INSTALL_DIR)\opt0.4\"\r
        @echo Installing package http $(PKG_HTTP_VER) as a Tcl Module\r
        @$(COPY) "$(ROOT)\library\http\http.tcl" \\r
-           "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.6\http-$(PKG_HTTP_VER).tm"\r
+           "$(MODULE_INSTALL_DIR)\8.6\http-$(PKG_HTTP_VER).tm"\r
        @echo Installing package msgcat $(PKG_MSGCAT_VER) as a Tcl Module\r
        @$(COPY) "$(ROOT)\library\msgcat\msgcat.tcl" \\r
-           "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.5\msgcat-$(PKG_MSGCAT_VER).tm"\r
+           "$(MODULE_INSTALL_DIR)\8.5\msgcat-$(PKG_MSGCAT_VER).tm"\r
        @echo Installing package tcltest $(PKG_TCLTEST_VER) as a Tcl Module\r
        @$(COPY) "$(ROOT)\library\tcltest\tcltest.tcl" \\r
-           "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.5\tcltest-$(PKG_TCLTEST_VER).tm"\r
+           "$(MODULE_INSTALL_DIR)\8.5\tcltest-$(PKG_TCLTEST_VER).tm"\r
        @echo Installing package platform $(PKG_PLATFORM_VER) as a Tcl Module\r
        @$(COPY) "$(ROOT)\library\platform\platform.tcl" \\r
-           "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4\platform-$(PKG_PLATFORM_VER).tm"\r
+           "$(MODULE_INSTALL_DIR)\8.4\platform-$(PKG_PLATFORM_VER).tm"\r
        @echo Installing package platform::shell $(PKG_SHELL_VER) as a Tcl Module\r
        @$(COPY) "$(ROOT)\library\platform\shell.tcl" \\r
-           "$(SCRIPT_INSTALL_DIR)\..\tcl8\8.4\platform\shell-$(PKG_SHELL_VER).tm"\r
+           "$(MODULE_INSTALL_DIR)\8.4\platform\shell-$(PKG_SHELL_VER).tm"\r
        @echo Installing $(TCLDDELIBNAME)\r
 !if $(STATIC_BUILD)\r
 !if !$(TCL_USE_STATIC_PACKAGES)\r
index fac32ee..7536ede 100644 (file)
@@ -708,7 +708,7 @@ QualifyPath(
 {
     char szCwd[MAX_PATH + 1];
 
-       GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
+    GetFullPathName(szPath, sizeof(szCwd)-1, szCwd, NULL);
     printf("%s\n", szCwd);
     return 0;
 }
index 531e070..6da5689 100644 (file)
@@ -31,7 +31,7 @@ macro to the name of the project makefile.
 # We extract version numbers using the nmakehlp program. For now use\r
 # the local copy of nmakehlp. Once we locate Tcl, we will use that\r
 # one if it is newer.\r
-!if [$(CC) -nologo "nmakehlp.c" -link -subsystem:console > nul]\r
+!if [$(CC) -nologo -DNDEBUG "nmakehlp.c" -link -subsystem:console > nul]\r
 !endif\r
 \r
 # First locate the Tcl directory that we are working with.\r
index cf80c91..13e3879 100644 (file)
@@ -6,7 +6,7 @@
 # compiler switches, defining common targets and macros. The Tcl makefile\r
 # directly includes this. Extensions include it via "rules-ext.vc".\r
 #\r
-# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for\r
 # detailed documentation.\r
 #\r
 # See the file "license.terms" for information on usage and redistribution\r
@@ -24,7 +24,7 @@ _RULES_VC = 1
 # For modifications that are not backward-compatible, you *must* change\r
 # the major version.\r
 RULES_VERSION_MAJOR = 1\r
-RULES_VERSION_MINOR = 4\r
+RULES_VERSION_MINOR = 8\r
 \r
 # The PROJECT macro must be defined by parent makefile.\r
 !if "$(PROJECT)" == ""\r
@@ -302,7 +302,7 @@ TCLDIR          = $(_INSTALLDIR)\..
 _TCLDIR                = $(_INSTALLDIR)\..\r
 _TCL_H          = $(_TCLDIR)\include\tcl.h\r
 \r
-!else # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!else # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !if [echo _TCLDIR = \> nmakehlp.out] \\r
    || [nmakehlp -L generic\tcl.h >> nmakehlp.out]\r
@@ -313,7 +313,7 @@ TCLINSTALL      = 0
 TCLDIR         = $(_TCLDIR)\r
 _TCL_H          = $(_TCLDIR)\generic\tcl.h\r
 \r
-!endif # exist(...) && ! $(NEED_TCL_SOURCE)\r
+!endif # exist(...) && !$(NEED_TCL_SOURCE)\r
 \r
 !endif # TCLDIR\r
 \r
@@ -415,9 +415,6 @@ _INSTALLDIR=$(_INSTALLDIR)\lib
 # NATIVE_ARCH - set to IX86 or AMD64 for the host machine\r
 # MACHINE - same as $(ARCH) - legacy\r
 # _VC_MANIFEST_EMBED_{DLL,EXE} - commands for embedding a manifest if needed\r
-# CFG_ENCODING - set to an character encoding.\r
-#   TBD - this is passed to compiler as TCL_CFGVAL_ENCODING but can't\r
-#   see where it is used\r
 \r
 cc32           = $(CC)   # built-in default.\r
 link32         = link\r
@@ -503,10 +500,6 @@ _VC_MANIFEST_EMBED_EXE=if exist $@.manifest mt -nologo -manifest $@.manifest -ou
 _VC_MANIFEST_EMBED_DLL=if exist $@.manifest mt -nologo -manifest $@.manifest -outputresource:$@;2\r
 !endif\r
 \r
-!ifndef CFG_ENCODING\r
-CFG_ENCODING   = \"cp1252\"\r
-!endif\r
-\r
 ################################################################\r
 # 4. Build the nmakehlp program\r
 # This is a helper app we need to overcome nmake's limiting\r
@@ -514,7 +507,7 @@ CFG_ENCODING        = \"cp1252\"
 # information about supported compiler options etc.\r
 #\r
 # Tcl itself will always use the nmakehlp.c program which is\r
-# in its own source. This is the "master" copy and kept updated.\r
+# in its own source. It will be kept updated there.\r
 #\r
 # Extensions built against an installed Tcl will use the installed\r
 # copy of Tcl's nmakehlp.c if there is one and their own version\r
@@ -537,7 +530,7 @@ NMAKEHLPC = nmakehlp.c
 !if exist("$(_TCLDIR)\lib\nmake\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\lib\nmake\nmakehlp.c\r
 !endif\r
-!else # ! $(TCLINSTALL)\r
+!else # !$(TCLINSTALL)\r
 !if exist("$(_TCLDIR)\win\nmakehlp.c")\r
 NMAKEHLPC = $(_TCLDIR)\win\nmakehlp.c\r
 !endif\r
@@ -659,8 +652,130 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 !endif\r
 !endif\r
 \r
+\r
+################################################################\r
+# 6. Extract various version numbers from headers\r
+# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
+# respectively. For extensions, versions are extracted from the\r
+# configure.in or configure.ac from the TEA configuration if it\r
+# exists, and unset otherwise.\r
+# Sets the following macros:\r
+# TCL_MAJOR_VERSION\r
+# TCL_MINOR_VERSION\r
+# TCL_RELEASE_SERIAL\r
+# TCL_PATCH_LEVEL\r
+# TCL_PATCH_LETTER\r
+# TCL_VERSION\r
+# TK_MAJOR_VERSION\r
+# TK_MINOR_VERSION\r
+# TK_RELEASE_SERIAL\r
+# TK_PATCH_LEVEL\r
+# TK_PATCH_LETTER\r
+# TK_VERSION\r
+# DOTVERSION - set as (for example) 2.5\r
+# VERSION - set as (for example 25)\r
+#--------------------------------------------------------------\r
+\r
+!if [echo REM = This file is generated from rules.vc > versions.vc]\r
+!endif\r
+!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TCL_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
+!endif\r
+!if [echo TK_RELEASE_SERIAL = \>> versions.vc] \\r
+   && [nmakehlp -V "$(_TK_H)" TK_RELEASE_SERIAL >> versions.vc]\r
+!endif\r
+!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
+   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
+!endif\r
+!endif # _TK_H\r
+\r
+!include versions.vc\r
+\r
+TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
+TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+!if [nmakehlp -f $(TCL_PATCH_LEVEL) "a"]\r
+TCL_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TCL_PATCH_LEVEL) "b"]\r
+TCL_PATCH_LETTER = b\r
+!else\r
+TCL_PATCH_LETTER = .\r
+!endif\r
+\r
+!if defined(_TK_H)\r
+\r
+TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
+TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
+!if [nmakehlp -f $(TK_PATCH_LEVEL) "a"]\r
+TK_PATCH_LETTER = a\r
+!elseif [nmakehlp -f $(TK_PATCH_LEVEL) "b"]\r
+TK_PATCH_LETTER = b\r
+!else\r
+TK_PATCH_LETTER = .\r
+!endif\r
+\r
+!endif\r
+\r
+# Set DOTVERSION and VERSION\r
+!if $(DOING_TCL)\r
+\r
+DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+VERSION = $(TCL_VERSION)\r
+\r
+!elseif $(DOING_TK)\r
+\r
+DOTVERSION = $(TK_DOTVERSION)\r
+VERSION = $(TK_VERSION)\r
+\r
+!else # Doing a non-Tk extension\r
+\r
+# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
+# first from a configure.in file, and then from configure.ac\r
+!ifndef DOTVERSION\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
+!if [echo DOTVERSION = \> versions.vc] \\r
+   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
+!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
+!endif\r
+!endif\r
+!include versions.vc\r
+!endif # DOTVERSION\r
+VERSION         = $(DOTVERSION:.=)\r
+\r
+!endif # $(DOING_TCL) ... etc.\r
+\r
+# Windows RC files have 3 version components. Ensure this irrespective\r
+# of how many components the package has specified. Basically, ensure\r
+# minimum 4 components by appending 4 0's and then pick out the first 4.\r
+# Also take care of the fact that DOTVERSION may have "a" or "b" instead\r
+# of "." separating the version components.\r
+DOTSEPARATED=$(DOTVERSION:a=.)\r
+DOTSEPARATED=$(DOTSEPARATED:b=.)\r
+!if [echo RCCOMMAVERSION = \> versions.vc] \\r
+  || [for /f "tokens=1,2,3,4,5* delims=." %a in ("$(DOTSEPARATED).0.0.0.0") do echo %a,%b,%c,%d >> versions.vc]\r
+!error *** Could not generate RCCOMMAVERSION ***\r
+!endif\r
+!include versions.vc\r
+\r
 ########################################################################\r
-# 6. Parse the OPTS macro to work out the requested build configuration.\r
+# 7. Parse the OPTS macro to work out the requested build configuration.\r
 # Based on this, we will construct the actual switches to be passed to the\r
 # compiler and linker using the macros defined in the previous section.\r
 # The following macros are defined by this section based on OPTS\r
@@ -674,9 +789,10 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # MSVCRT  - 1 -> link to dynamic C runtime even when building static Tcl build\r
 #           0 -> link to static C runtime for static Tcl build.\r
 #           Does not impact shared Tcl builds (STATIC_BUILD == 0)\r
+#           Default: 1 for Tcl 8.7 and up, 0 otherwise.\r
 # TCL_USE_STATIC_PACKAGES - 1 -> statically link the registry and dde extensions\r
-#           in the Tcl shell. 0 -> keep them as shared libraries\r
-#           Does not impact shared Tcl builds.\r
+#           in the Tcl and Wish shell. 0 -> keep them as shared libraries. Does\r
+#           not impact shared Tcl builds. Implied by STATIC_BUILD since Tcl 8.7.\r
 # USE_THREAD_ALLOC - 1 -> Use a shared global free pool for allocation.\r
 #           0 -> Use the non-thread allocator.\r
 # UNCHECKED - 1 -> when doing a debug build with symbols, use the release\r
@@ -685,7 +801,9 @@ LINKERFLAGS     = $(LINKERFLAGS) -ltcg
 # CONFIG_CHECK - 1 -> check current build configuration against Tcl\r
 #           configuration (ignored for Tcl itself)\r
 # _USE_64BIT_TIME_T - forces a build using 64-bit time_t for 32-bit build\r
-#           (CRT library should support this)\r
+#           (CRT library should support this, not needed for Tcl 9.x)\r
+# TCL_UTF_MAX=4 - forces a build allowing 4-byte UTF-8 sequences internally.\r
+#           (Not needed for Tcl 9.x)\r
 # Further, LINKERFLAGS are modified based on above.\r
 \r
 # Default values for all the above\r
@@ -728,11 +846,8 @@ MSVCRT             = 0
 !else\r
 !if [nmakehlp -f $(OPTS) "msvcrt"]\r
 !message *** Doing msvcrt\r
-MSVCRT         = 1\r
-!else\r
-!if !$(STATIC_BUILD)\r
-MSVCRT         = 1\r
 !else\r
+!if $(TCL_MAJOR_VERSION) == 8 && $(TCL_MINOR_VERSION) < 7 && $(STATIC_BUILD)\r
 MSVCRT         = 0\r
 !endif\r
 !endif\r
@@ -741,24 +856,26 @@ MSVCRT            = 0
 !if [nmakehlp -f $(OPTS) "staticpkg"] && $(STATIC_BUILD)\r
 !message *** Doing staticpkg\r
 TCL_USE_STATIC_PACKAGES        = 1\r
-!else\r
-TCL_USE_STATIC_PACKAGES        = 0\r
 !endif\r
 \r
 !if [nmakehlp -f $(OPTS) "nothreads"]\r
 !message *** Compile explicitly for non-threaded tcl\r
 TCL_THREADS = 0\r
 USE_THREAD_ALLOC= 0\r
-!else\r
-TCL_THREADS    = 1\r
-USE_THREAD_ALLOC= 1\r
 !endif\r
 \r
+!if $(TCL_MAJOR_VERSION) == 8\r
 !if [nmakehlp -f $(OPTS) "time64bit"]\r
 !message *** Force 64-bit time_t\r
 _USE_64BIT_TIME_T = 1\r
 !endif\r
 \r
+!if [nmakehlp -f $(OPTS) "utfmax"]\r
+!message *** Force allowing 4-byte UTF-8 sequences internally\r
+TCL_UTF_MAX = 4\r
+!endif\r
+!endif\r
+\r
 # Yes, it's weird that the "symbols" option controls DEBUG and\r
 # the "pdbs" option controls SYMBOLS. That's historical.\r
 !if [nmakehlp -f $(OPTS) "symbols"]\r
@@ -842,7 +959,7 @@ This compiler does not support profile guided optimization.
 !endif\r
 \r
 ################################################################\r
-# 7. Parse the STATS macro to configure code instrumentation\r
+# 8. Parse the STATS macro to configure code instrumentation\r
 # The following macros are set by this section:\r
 # TCL_MEM_DEBUG - 1 -> enables memory allocation instrumentation\r
 #                 0 -> disables\r
@@ -872,7 +989,7 @@ TCL_COMPILE_DEBUG   = 0
 !endif\r
 \r
 ####################################################################\r
-# 8. Parse the CHECKS macro to configure additional compiler checks\r
+# 9. Parse the CHECKS macro to configure additional compiler checks\r
 # The following macros are set by this section:\r
 # WARNINGS - compiler switches that control the warnings level\r
 # TCL_NO_DEPRECATED - 1 -> disable support for deprecated functions\r
@@ -904,86 +1021,6 @@ WARNINGS              = $(WARNINGS) -Wp64
 \r
 !endif\r
 \r
-################################################################\r
-# 9. Extract various version numbers\r
-# For Tcl and Tk, version numbers are extracted from tcl.h and tk.h\r
-# respectively. For extensions, versions are extracted from the\r
-# configure.in or configure.ac from the TEA configuration if it\r
-# exists, and unset otherwise.\r
-# Sets the following macros:\r
-# TCL_MAJOR_VERSION\r
-# TCL_MINOR_VERSION\r
-# TCL_PATCH_LEVEL\r
-# TCL_VERSION\r
-# TK_MAJOR_VERSION\r
-# TK_MINOR_VERSION\r
-# TK_PATCH_LEVEL\r
-# TK_VERSION\r
-# DOTVERSION - set as (for example) 2.5\r
-# VERSION - set as (for example 25)\r
-#--------------------------------------------------------------\r
-\r
-!if [echo REM = This file is generated from rules.vc > versions.vc]\r
-!endif\r
-!if [echo TCL_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TCL_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V "$(_TCL_H)" TCL_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-\r
-!if defined(_TK_H)\r
-!if [echo TK_MAJOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MAJOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_MINOR_VERSION = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_MINOR_VERSION >> versions.vc]\r
-!endif\r
-!if [echo TK_PATCH_LEVEL = \>> versions.vc] \\r
-   && [nmakehlp -V $(_TK_H) TK_PATCH_LEVEL >> versions.vc]\r
-!endif\r
-!endif # _TK_H\r
-\r
-!include versions.vc\r
-\r
-TCL_VERSION    = $(TCL_MAJOR_VERSION)$(TCL_MINOR_VERSION)\r
-TCL_DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-!if defined(_TK_H)\r
-TK_VERSION     = $(TK_MAJOR_VERSION)$(TK_MINOR_VERSION)\r
-TK_DOTVERSION  = $(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
-!endif\r
-\r
-# Set DOTVERSION and VERSION\r
-!if $(DOING_TCL)\r
-\r
-DOTVERSION = $(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
-VERSION = $(TCL_VERSION)\r
-\r
-!elseif $(DOING_TK)\r
-\r
-DOTVERSION = $(TK_DOTVERSION)\r
-VERSION = $(TK_VERSION)\r
-\r
-!else # Doing a non-Tk extension\r
-\r
-# If parent makefile has not defined DOTVERSION, try to get it from TEA\r
-# first from a configure.in file, and then from configure.ac\r
-!ifndef DOTVERSION\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.in ^[$(PROJECT)^] >> versions.vc]\r
-!if [echo DOTVERSION = \> versions.vc] \\r
-   || [nmakehlp -V $(ROOT)\configure.ac ^[$(PROJECT)^] >> versions.vc]\r
-!error *** Could not figure out extension version. Please define DOTVERSION in parent makefile before including rules.vc.\r
-!endif\r
-!endif\r
-!include versions.vc\r
-!endif # DOTVERSION\r
-VERSION         = $(DOTVERSION:.=)\r
-\r
-!endif # $(DOING_TCL) ... etc.\r
 \r
 ################################################################\r
 # 10. Construct output directory and file paths\r
@@ -1029,7 +1066,7 @@ BUILDDIRTOP =$(BUILDDIRTOP)_$(MACHINE)
 BUILDDIRTOP =$(BUILDDIRTOP)_VC$(VCVER)\r
 !endif\r
 \r
-!if !$(DEBUG) || $(DEBUG) && $(UNCHECKED)\r
+!if !$(DEBUG) || $(TCL_VERSION) > 86 || $(DEBUG) && $(UNCHECKED)\r
 SUFX       = $(SUFX:g=)\r
 !endif\r
 \r
@@ -1080,20 +1117,35 @@ OUT_DIR     = $(TMP_DIR)
 # The name of the stubs library for the project being built\r
 STUBPREFIX      = $(PROJECT)stub\r
 \r
+#\r
 # Set up paths to various Tcl executables and libraries needed by extensions\r
-!if $(DOING_TCL)\r
+#\r
 \r
+# TIP 430. Unused for 8.6 but no harm defining it to allow a common rules.vc\r
+!if "$(TCL_PATCH_LETTER)" == "."\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_RELEASE_SERIAL).zip\r
+!else\r
+TCLSCRIPTZIPNAME = libtcl_$(TCL_MAJOR_VERSION)_$(TCL_MINOR_VERSION)_$(TCL_PATCH_LETTER)$(TCL_RELEASE_SERIAL).zip\r
+!endif\r
+!if "$(TK_PATCH_LETTER)" == "."\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_RELEASE_SERIAL).zip\r
+!else\r
+TKSCRIPTZIPNAME = libtk_$(TK_MAJOR_VERSION)_$(TK_MINOR_VERSION)_$(TK_PATCH_LETTER)$(TK_RELEASE_SERIAL).zip\r
+!endif\r
+\r
+!if $(DOING_TCL)\r
 TCLSHNAME       = $(PROJECT)sh$(VERSION)$(SUFX).exe\r
 TCLSH          = $(OUT_DIR)\$(TCLSHNAME)\r
 TCLIMPLIB      = $(OUT_DIR)\$(PROJECT)$(VERSION)$(SUFX).lib\r
 TCLLIBNAME     = $(PROJECT)$(VERSION)$(SUFX).$(EXT)\r
 TCLLIB         = $(OUT_DIR)\$(TCLLIBNAME)\r
+TCLSCRIPTZIP    = $(OUT_DIR)\$(TCLSCRIPTZIPNAME)\r
 \r
 TCLSTUBLIBNAME = $(STUBPREFIX)$(VERSION).lib\r
 TCLSTUBLIB     = $(OUT_DIR)\$(TCLSTUBLIBNAME)\r
 TCL_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
 \r
-!else # ! $(DOING_TCL)\r
+!else # !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 \r
@@ -1115,6 +1167,7 @@ TCLIMPLIB = $(_TCLDIR)\lib\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\lib\r
 TCLREGLIB      = $(_TCLDIR)\lib\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\lib\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\lib\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = \must\have\tcl\sources\to\build\this\target\r
 TCL_INCLUDES    = -I"$(_TCLDIR)\include"\r
 \r
@@ -1134,6 +1187,7 @@ TCLIMPLIB = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcl$(TCL_VERSION)t$(SUFX:t=).lib
 TCL_LIBRARY    = $(_TCLDIR)\library\r
 TCLREGLIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tclreg13$(SUFX:t=).lib\r
 TCLDDELIB      = $(_TCLDIR)\win\$(BUILDDIRTOP)\tcldde14$(SUFX:t=).lib\r
+TCLSCRIPTZIP   = $(_TCLDIR)\win\$(BUILDDIRTOP)\$(TCLSCRIPTZIPNAME)\r
 TCLTOOLSDIR    = $(_TCLDIR)\tools\r
 TCL_INCLUDES   = -I"$(_TCLDIR)\generic" -I"$(_TCLDIR)\win"\r
 \r
@@ -1166,7 +1220,8 @@ WISH              = $(OUT_DIR)\$(WISHNAME)
 TKSTUBLIB      = $(OUT_DIR)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(OUT_DIR)\$(TKIMPLIBNAME)\r
 TKLIB          = $(OUT_DIR)\$(TKLIBNAME)\r
-TK_INCLUDES    = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TK_INCLUDES     = -I"$(WIN_DIR)" -I"$(GENERICDIR)"\r
+TKSCRIPTZIP     = $(OUT_DIR)\$(TKSCRIPTZIPNAME)\r
 \r
 !else # effectively NEED_TK\r
 \r
@@ -1181,7 +1236,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\lib\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\include"\r
+TKSCRIPTZIP     = $(_TKDIR)\lib\$(TKSCRIPTZIPNAME)\r
+\r
 !else # Building against Tk sources\r
+\r
 WISH           = $(_TKDIR)\win\$(BUILDDIRTOP)\$(WISHNAME)\r
 TKSTUBLIB      = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSTUBLIBNAME)\r
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
@@ -1192,7 +1250,10 @@ TKIMPLIBNAME     = tk$(TK_VERSION)$(SUFX:t=).lib
 TKIMPLIB       = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKIMPLIBNAME)\r
 !endif\r
 TK_INCLUDES     = -I"$(_TKDIR)\generic" -I"$(_TKDIR)\win" -I"$(_TKDIR)\xlib"\r
+TKSCRIPTZIP     = $(_TKDIR)\win\$(BUILDDIRTOP)\$(TKSCRIPTZIPNAME)\r
+\r
 !endif # TKINSTALL\r
+\r
 tklibs = "$(TKSTUBLIB)" "$(TKIMPLIB)"\r
 \r
 !endif # $(DOING_TK)\r
@@ -1233,6 +1294,7 @@ BIN_INSTALL_DIR           = $(_INSTALLDIR)\bin
 DOC_INSTALL_DIR                = $(_INSTALLDIR)\doc\r
 !if $(DOING_TCL)\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TCL_MAJOR_VERSION).$(TCL_MINOR_VERSION)\r
+MODULE_INSTALL_DIR     = $(_INSTALLDIR)\lib\tcl$(TCL_MAJOR_VERSION)\r
 !else # DOING_TK\r
 SCRIPT_INSTALL_DIR     = $(_INSTALLDIR)\lib\$(PROJECT)$(TK_MAJOR_VERSION).$(TK_MINOR_VERSION)\r
 !endif\r
@@ -1277,7 +1339,15 @@ INCLUDE_INSTALL_DIR      = $(_INSTALLDIR)\..\include
 # baselibs - minimum Windows libraries required. Parent makefile can\r
 #    define PRJ_LIBS before including rules.rc if additional libs are needed\r
 \r
-OPTDEFINES     = /DTCL_CFGVAL_ENCODING=$(CFG_ENCODING) /DSTDC_HEADERS\r
+OPTDEFINES     = /DSTDC_HEADERS\r
+!if $(VCVERSION) > 1600\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_STDINT_H=1\r
+!else\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_NO_STDINT=1\r
+!endif\r
+!if $(VCVERSION) >= 1800\r
+OPTDEFINES     = $(OPTDEFINES) /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1\r
+!endif\r
 \r
 !if $(TCL_MEM_DEBUG)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_MEM_DEBUG\r
@@ -1293,6 +1363,11 @@ OPTDEFINES       = $(OPTDEFINES) /DUSE_THREAD_ALLOC=1
 !endif\r
 !if $(STATIC_BUILD)\r
 OPTDEFINES     = $(OPTDEFINES) /DSTATIC_BUILD\r
+!elseif $(TCL_VERSION) > 86\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_WITH_EXTERNAL_TOMMATH\r
+!if "$(MACHINE)" == "AMD64"\r
+OPTDEFINES     = $(OPTDEFINES) /DMP_64BIT\r
+!endif\r
 !endif\r
 !if $(TCL_NO_DEPRECATED)\r
 OPTDEFINES     = $(OPTDEFINES) /DTCL_NO_DEPRECATED\r
@@ -1301,7 +1376,7 @@ OPTDEFINES        = $(OPTDEFINES) /DTCL_NO_DEPRECATED
 !if $(USE_STUBS)\r
 # Note we do not define USE_TCL_STUBS even when building tk since some\r
 # test targets in tk do not use stubs\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 USE_STUBS_DEFS  = /DUSE_TCL_STUBS /DUSE_TCLOO_STUBS\r
 !if $(NEED_TK)\r
 USE_STUBS_DEFS  = $(USE_STUBS_DEFS) /DUSE_TK_STUBS\r
@@ -1322,15 +1397,20 @@ OPTDEFINES      = $(OPTDEFINES) /DTCL_CFG_PROFILED
 OPTDEFINES     = $(OPTDEFINES) /DTCL_CFG_DO64BIT\r
 !endif\r
 !if $(VCVERSION) < 1300\r
-OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64\r
+OPTDEFINES     = $(OPTDEFINES) /DNO_STRTOI64=1\r
 !endif\r
 \r
+!if "$(TCL_MAJOR_VERSION)" == "8"\r
 !if "$(_USE_64BIT_TIME_T)" == "1"\r
-OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T\r
+OPTDEFINES     = $(OPTDEFINES) /D_USE_64BIT_TIME_T=1\r
+!endif\r
+!if "$(TCL_UTF_MAX)" == "4"\r
+OPTDEFINES     = $(OPTDEFINES) /DTCL_UTF_MAX=4\r
 !endif\r
 \r
 # _ATL_XP_TARGETING - Newer SDK's need this to build for XP\r
 COMPILERFLAGS  = /D_ATL_XP_TARGETING\r
+!endif\r
 \r
 # Like the TEA system only set this non empty for non-Tk extensions\r
 # Note: some extensions use PACKAGE_NAME and others use PACKAGE_TCLNAME\r
@@ -1455,18 +1535,6 @@ lflags   = -nologo -machine:$(MACHINE) $(LINKERFLAGS) $(ldebug)
 lflags = $(lflags) -nodefaultlib:libucrt.lib\r
 !endif\r
 \r
-# Old linkers (Visual C++ 6 in particular) will link for fast loading\r
-# on Win98. Since we do not support Win98 any more, we specify nowin98\r
-# as recommended for NT and later. However, this is only required by\r
-# IX86 on older compilers and only needed if we are not doing a static build.\r
-\r
-!if "$(MACHINE)" == "IX86" && !$(STATIC_BUILD)\r
-!if [nmakehlp -l -opt:nowin98 $(LINKER_TESTFLAGS)]\r
-# Align sections for PE size savings.\r
-lflags = $(lflags) -opt:nowin98\r
-!endif\r
-!endif\r
-\r
 dlllflags = $(lflags) -dll\r
 conlflags = $(lflags) -subsystem:console\r
 guilflags = $(lflags) -subsystem:windows\r
@@ -1508,7 +1576,7 @@ GUIEXECMD = $(link32) $(guilflags) -out:$@ $(baselibs) $(tcllibs) $(tklibs)
 RESCMD  = $(rc32) -fo $@ -r -i "$(GENERICDIR)" -i "$(TMP_DIR)" \\r
            $(TCL_INCLUDES) \\r
            /DDEBUG=$(DEBUG) -d UNCHECKED=$(UNCHECKED) \\r
-           /DCOMMAVERSION=$(DOTVERSION:.=,),0 \\r
+           /DCOMMAVERSION=$(RCCOMMAVERSION) \\r
            /DDOTVERSION=\"$(DOTVERSION)\" \\r
            /DVERSION=\"$(VERSION)\" \\r
            /DSUFX=\"$(SUFX)\" \\r
@@ -1524,11 +1592,11 @@ default-target: $(DEFAULT_BUILD_TARGET)
 !if $(MULTIPLATFORM_INSTALL)\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PLATFORM_IDENTIFY) $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !else\r
 default-pkgindex:\r
        @echo package ifneeded $(PRJ_PACKAGE_TCLNAME) $(DOTVERSION) \\r
-           [list load [file join $$dir $(PRJLIBNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
+           [list load [file join $$dir $(PRJLIBNAME)] [string totitle $(PRJ_PACKAGE_TCLNAME)]] > $(OUT_DIR)\pkgIndex.tcl\r
 !endif\r
 \r
 default-pkgindex-tea:\r
@@ -1574,6 +1642,8 @@ default-install-pdbs:
        @if not exist "$(LIB_INSTALL_DIR)" mkdir "$(LIB_INSTALL_DIR)"\r
        @$(CPY) "$(OUT_DIR)\*.pdb" "$(LIB_INSTALL_DIR)\"\r
 \r
+# "emacs font-lock highlighting fix\r
+\r
 default-install-docs-html:\r
        @echo Installing documentation files to '$(DOC_INSTALL_DIR)'\r
        @if not exist "$(DOC_INSTALL_DIR)" mkdir "$(DOC_INSTALL_DIR)"\r
@@ -1636,7 +1706,7 @@ default-shell: default-setup $(PROJECT)
 !ifdef RCFILE\r
 \r
 # Note: don't use $** in below rule because there may be other dependencies\r
-# and only the "master" rc must be passed to the resource compiler\r
+# and only the "main" rc must be passed to the resource compiler\r
 $(TMP_DIR)\$(PROJECT).res: $(RCDIR)\$(PROJECT).rc\r
        $(RESCMD) $(RCDIR)\$(PROJECT).rc\r
 \r
@@ -1690,7 +1760,7 @@ DISABLE_IMPLICIT_RULES = 0
 \r
 !if !$(DISABLE_IMPLICIT_RULES)\r
 # Implicit rule definitions - only for building library objects. For stubs and\r
-# main application, the master makefile should define explicit rules.\r
+# main application, the makefile should define explicit rules.\r
 \r
 {$(ROOT)}.c{$(TMP_DIR)}.obj::\r
        $(CCPKGCMD) @<<\r
@@ -1731,15 +1801,15 @@ $<
 # When building an extension, certain configuration options should\r
 # match the ones used when Tcl was built. Here we check and\r
 # warn on a mismatch.\r
-!if ! $(DOING_TCL)\r
+!if !$(DOING_TCL)\r
 \r
 !if $(TCLINSTALL) # Building against an installed Tcl\r
 !if exist("$(_TCLDIR)\lib\nmake\tcl.nmake")\r
 TCLNMAKECONFIG = "$(_TCLDIR)\lib\nmake\tcl.nmake"\r
 !endif\r
-!else # ! $(TCLINSTALL) - building against Tcl source\r
-!if exist("$(OUT_DIR)\tcl.nmake")\r
-TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"\r
+!else # !$(TCLINSTALL) - building against Tcl source\r
+!if exist("$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake")\r
+TCLNMAKECONFIG = "$(_TCLDIR)\win\$(BUILDDIRTOP)\tcl.nmake"\r
 !endif\r
 !endif # TCLINSTALL\r
 \r
@@ -1760,7 +1830,7 @@ TCLNMAKECONFIG = "$(OUT_DIR)\tcl.nmake"
 \r
 !endif # TCLNMAKECONFIG\r
 \r
-!endif # ! $(DOING_TCL)\r
+!endif # !$(DOING_TCL)\r
 \r
 \r
 #----------------------------------------------------------\r
index 6bfebc7..077e8f7 100644 (file)
@@ -4,7 +4,7 @@
 # Part of the nmake based build system for Tcl and its extensions.\r
 # This file defines some standard targets for the convenience of extensions\r
 # and can be optionally included by the extension makefile.\r
-# See TIP 477 (https://core.tcl-lang.org/tips/doc/trunk/tip/477.md) for docs.\r
+# See TIP 477 (https://core.tcl-lang.org/tips/doc/main/tip/477.md) for docs.\r
 \r
 $(PROJECT): setup pkgindex $(PRJLIB)\r
 \r
index e8b1a33..4f35cb3 100644 (file)
@@ -364,7 +364,7 @@ SOURCE=..\doc\CrtObjCmd.3
 # End Source File\r
 # Begin Source File\r
 \r
-SOURCE=..\doc\CrtSlave.3\r
+SOURCE=..\doc\CrtAlias.3\r
 # End Source File\r
 # Begin Source File\r
 \r
index 84f0dff..70b7b19 100644 (file)
@@ -364,14 +364,6 @@ AC_DEFUN([SC_ENABLE_SHARED], [
     AC_ARG_ENABLE(shared,
        [  --enable-shared         build and link with shared libraries (default: on)],
        [tcl_ok=$enableval], [tcl_ok=yes])
-
-    if test "${enable_shared+set}" = set; then
-       enableval="$enable_shared"
-       tcl_ok=$enableval
-    else
-       tcl_ok=yes
-    fi
-
     if test "$tcl_ok" = "yes" ; then
        AC_MSG_RESULT([shared])
        SHARED_BUILD=1
@@ -583,14 +575,14 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
       if test "$ac_cv_cross" = "yes"; then
        case "$do64bit" in
            amd64|x64|yes)
-               CC="x86_64-w64-mingw32-gcc"
+               CC="x86_64-w64-mingw32-${CC}"
                LD="x86_64-w64-mingw32-ld"
                AR="x86_64-w64-mingw32-ar"
                RANLIB="x86_64-w64-mingw32-ranlib"
                RC="x86_64-w64-mingw32-windres"
            ;;
            *)
-               CC="i686-w64-mingw32-gcc"
+               CC="i686-w64-mingw32-${CC}"
                LD="i686-w64-mingw32-ld"
                AR="i686-w64-mingw32-ar"
                RANLIB="i686-w64-mingw32-ranlib"
@@ -715,7 +707,7 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
        SHLIB_LD='${CC} -shared'
        SHLIB_LD_LIBS='${LIBS}'
        MAKE_DLL="\${SHLIB_LD} \$(LDFLAGS) -o \[$]@ ${extra_ldflags} \
-           -Wl,--out-implib,\$(patsubst %.dll,lib%.a,\[$]@)"
+           -Wl,--out-implib,\$(patsubst %.dll,lib%.dll.a,\[$]@)"
        # DLLSUFFIX is separate because it is the building block for
        # users of tclConfig.sh that may build shared or static.
        DLLSUFFIX="\${DBGX}.dll"
@@ -727,10 +719,19 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
 
        CFLAGS_DEBUG=-g
        CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
-       CFLAGS_WARNING="-Wall -Wdeclaration-after-statement"
+       CFLAGS_WARNING="-Wall -Wpointer-arith"
        LDFLAGS_DEBUG=
        LDFLAGS_OPTIMIZE=
 
+       case "${CC}" in
+           *++)
+               CFLAGS_WARNING="${CFLAGS_WARNING} -Wno-format"
+               ;;
+           *)
+               CFLAGS_WARNING="${CFLAGS_WARNING} -Wdeclaration-after-statement"
+               ;;
+       esac
+
        # Specify the CC output file names based on the target name
        CC_OBJNAME="-o \[$]@"
        CC_EXENAME="-o \[$]@"
@@ -806,28 +807,15 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
        LIBSUFFIX="\${DBGX}.lib"
        LIBFLAGSUFFIX="\${DBGX}"
 
-       # This is a 2-stage check to make sure we have the 64-bit SDK
-       # We have to know where the SDK is installed.
-       # This magic is based on MS Platform SDK for Win2003 SP1 - hobbs
        if test "$do64bit" != "no" ; then
-           if test "x${MSSDK}x" = "xx" ; then
-               MSSDK="C:/Progra~1/Microsoft Platform SDK"
-           fi
-           MSSDK=`echo "$MSSDK" | sed -e 's!\\\!/!g'`
-           PATH64=""
            case "$do64bit" in
                amd64|x64|yes)
                    MACHINE="AMD64" ; # assume AMD64 as default 64-bit build
-                   PATH64="${MSSDK}/Bin/Win64/x86/AMD64"
                    ;;
                ia64)
                    MACHINE="IA64"
-                   PATH64="${MSSDK}/Bin/Win64"
                    ;;
            esac
-           if test ! -d "${PATH64}" ; then
-               AC_MSG_WARN([Could not find 64-bit $MACHINE SDK])
-           fi
            AC_MSG_RESULT([   Using 64-bit $MACHINE mode])
        fi
 
@@ -842,21 +830,12 @@ AC_DEFUN([SC_CONFIG_CFLAGS], [
        esac
 
        if test "$do64bit" != "no" ; then
-           # The space-based-path will work for the Makefile, but will
-           # not work if AC_TRY_COMPILE is called.  TEA has the
-           # TEA_PATH_NOSPACE to avoid this issue.
-           # Check if _WIN64 is already recognized, and if so we don't
-           # need to modify CC.
-           AC_CHECK_DECL([_WIN64], [],
-                         [CC="\"${PATH64}/cl.exe\" -I\"${MSSDK}/Include\" \
-                        -I\"${MSSDK}/Include/crt\" \
-                        -I\"${MSSDK}/Include/crt/sys\""])
-           RC="\"${MSSDK}/bin/rc.exe\""
+           RC="rc"
            CFLAGS_DEBUG="-nologo -Zi -Od ${runtime}d"
            # Do not use -O2 for Win64 - this has proved buggy in code gen.
            CFLAGS_OPTIMIZE="-nologo -O1 ${runtime}"
-           lflags="${lflags} -nologo -MACHINE:${MACHINE} -LIBPATH:\"${MSSDK}/Lib/${MACHINE}\""
-           LINKBIN="\"${PATH64}/link.exe\""
+           lflags="${lflags} -nologo -MACHINE:${MACHINE}"
+           LINKBIN="link"
            # Avoid 'unresolved external symbol __security_cookie' errors.
            # c.f. http://support.microsoft.com/?id=894573
            LIBS="$LIBS bufferoverflowU.lib"
index 2236da3..695099e 100644 (file)
@@ -29,7 +29,7 @@ extern Tcl_PackageInitProc Tcltest_Init;
 extern Tcl_PackageInitProc Tcltest_SafeInit;
 #endif /* TCL_TEST */
 
-#if defined(STATIC_BUILD) && TCL_USE_STATIC_PACKAGES
+#if defined(STATIC_BUILD) && defined(TCL_USE_STATIC_PACKAGES) && TCL_USE_STATIC_PACKAGES
 extern Tcl_PackageInitProc Registry_Init;
 extern Tcl_PackageInitProc Dde_Init;
 extern Tcl_PackageInitProc Dde_SafeInit;
@@ -159,16 +159,16 @@ Tcl_AppInit(
        return TCL_ERROR;
     }
 
-#if defined(STATIC_BUILD) && TCL_USE_STATIC_PACKAGES
+#if defined(STATIC_BUILD) && defined(TCL_USE_STATIC_PACKAGES) && TCL_USE_STATIC_PACKAGES
     if (Registry_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
     }
-    Tcl_StaticPackage(interp, "registry", Registry_Init, NULL);
+    Tcl_StaticPackage(interp, "Registry", Registry_Init, NULL);
 
     if (Dde_Init(interp) == TCL_ERROR) {
        return TCL_ERROR;
     }
-    Tcl_StaticPackage(interp, "dde", Dde_Init, Dde_SafeInit);
+    Tcl_StaticPackage(interp, "Dde", Dde_Init, Dde_SafeInit);
 #endif
 
 #ifdef TCL_TEST
@@ -268,7 +268,7 @@ setargv(
     #undef Tcl_Alloc
     #undef Tcl_DbCkalloc
 
-    argSpace = ckalloc(size * sizeof(char *)
+    argSpace = (TCHAR *)ckalloc(size * sizeof(char *)
            + (_tcslen(cmdLine) * sizeof(TCHAR)) + sizeof(TCHAR));
     argv = (TCHAR **) argSpace;
     argSpace += size * (sizeof(char *)/sizeof(TCHAR));
index e77fbc0..9061dd0 100644 (file)
@@ -23,7 +23,6 @@
  */
 
 static HINSTANCE hInstance;    /* HINSTANCE of this DLL. */
-static int platformId;         /* Running under NT, or 95/98? */
 
 /*
  * VC++ 5.x has no 'cpuid' assembler instruction, so we must emulate it
@@ -186,18 +185,14 @@ TclWinInit(
     hInstance = hInst;
     os.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
     GetVersionExW(&os);
-    platformId = os.dwPlatformId;
 
     /*
-     * We no longer support Win32s or Win9x, so just in case someone manages
-     * to get a runtime there, make sure they know that.
+     * We no longer support Win32s or Win9x or Windows CE, so just in case
+     * someone manages to get a runtime there, make sure they know that.
      */
 
-    if (platformId == VER_PLATFORM_WIN32s) {
-       Tcl_Panic("Win32s is not a supported platform");
-    }
-    if (platformId == VER_PLATFORM_WIN32_WINDOWS) {
-       Tcl_Panic("Windows 9x is not a supported platform");
+    if (os.dwPlatformId != VER_PLATFORM_WIN32_NT) {
+       Tcl_Panic("Windows NT is the only supported platform");
     }
 }
 \f
@@ -210,11 +205,8 @@ TclWinInit(
  *     conditional code.
  *
  * Results:
- *     The return value is one of:
- *     VER_PLATFORM_WIN32s        Win32s on Windows 3.1 (not supported)
- *     VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95, 98, ME (not supported)
+ *     The return value is always:
  *     VER_PLATFORM_WIN32_NT   Win32 on Windows NT, 2000, XP
- *     VER_PLATFORM_WIN32_CE   Win32 on Windows CE
  *
  * Side effects:
  *     None.
@@ -225,7 +217,7 @@ TclWinInit(
 int
 TclWinGetPlatformId(void)
 {
-    return platformId;
+    return VER_PLATFORM_WIN32_NT;
 }
 \f
 /*
@@ -262,34 +254,10 @@ TclWinNoBackslash(
 /*
  *---------------------------------------------------------------------------
  *
- * TclpSetInterfaces --
- *
- *     A helper proc.
- *
- * Results:
- *     None.
- *
- * Side effects:
- *     None.
- *
- *---------------------------------------------------------------------------
- */
-
-void
-TclpSetInterfaces(void)
-{
-}
-\f
-/*
- *---------------------------------------------------------------------------
- *
  * TclWinEncodingsCleanup --
  *
- *     Called during finalization to free up any encodings we use.
- *
- *     We also clean up any memory allocated in our mount point map which is
- *     used to follow certain kinds of symlinks. That code should never be
- *     used once encodings are taken down.
+ *     Called during finalization to clean up any memory allocated in our
+ *     mount point map which is used to follow certain kinds of symlinks.
  *
  * Results:
  *     None.
@@ -446,7 +414,7 @@ TclWinDriveLetterForVolMountPoint(
      * We couldn't find it, so we must iterate over the letters.
      */
 
-    for (drive[0] = L'A'; drive[0] <= L'Z'; drive[0]++) {
+    for (drive[0] = 'A'; drive[0] <= 'Z'; drive[0]++) {
        /*
         * Try to read the volume mount point and see where it points.
         */
@@ -463,8 +431,8 @@ TclWinDriveLetterForVolMountPoint(
                }
            }
            if (!alreadyStored) {
-               dlPtr2 = ckalloc(sizeof(MountPointMap));
-               dlPtr2->volumeName = TclNativeDupInternalRep(Target);
+               dlPtr2 = (MountPointMap *)ckalloc(sizeof(MountPointMap));
+               dlPtr2->volumeName = (WCHAR *)TclNativeDupInternalRep(Target);
                dlPtr2->driveLetter = (char) drive[0];
                dlPtr2->nextPtr = driveLetterLookup;
                driveLetterLookup = dlPtr2;
@@ -489,8 +457,8 @@ TclWinDriveLetterForVolMountPoint(
      * that fact and store '-1' so we don't have to look it up each time.
      */
 
-    dlPtr2 = ckalloc(sizeof(MountPointMap));
-    dlPtr2->volumeName = TclNativeDupInternalRep((ClientData) mountPoint);
+    dlPtr2 = (MountPointMap *)ckalloc(sizeof(MountPointMap));
+    dlPtr2->volumeName = (WCHAR *)TclNativeDupInternalRep((void *)mountPoint);
     dlPtr2->driveLetter = -1;
     dlPtr2->nextPtr = driveLetterLookup;
     driveLetterLookup = dlPtr2;
@@ -717,7 +685,7 @@ TclWinCPUID(
        "movl   %%eax,          0x0(%%edi)"     "\n\t"
        "movl   %%ebx,          0x4(%%edi)"     "\n\t"
        "movl   %%ecx,          0x8(%%edi)"     "\n\t"
-       "movl   %%edx,          0xc(%%edi)"     "\n\t"
+       "movl   %%edx,          0xC(%%edi)"     "\n\t"
 
        :
        /* No outputs */
@@ -749,7 +717,7 @@ TclWinCPUID(
        "leal   1f,             %%eax"          "\n\t"
        "movl   %%eax,          0x4(%%edx)"     "\n\t" /* handler */
        "movl   %%ebp,          0x8(%%edx)"     "\n\t" /* ebp */
-       "movl   %%esp,          0xc(%%edx)"     "\n\t" /* esp */
+       "movl   %%esp,          0xC(%%edx)"     "\n\t" /* esp */
        "movl   %[error],       0x10(%%edx)"    "\n\t" /* status */
 
        /*
@@ -769,7 +737,7 @@ TclWinCPUID(
        "movl   %%eax,          0x0(%%edi)"     "\n\t"
        "movl   %%ebx,          0x4(%%edi)"     "\n\t"
        "movl   %%ecx,          0x8(%%edi)"     "\n\t"
-       "movl   %%edx,          0xc(%%edi)"     "\n\t"
+       "movl   %%edx,          0xC(%%edi)"     "\n\t"
 
        /*
         * Come here on a normal exit. Recover the TCLEXCEPTION_REGISTRATION and
@@ -796,7 +764,7 @@ TclWinCPUID(
         */
 
        "2:"                                    "\t"
-       "movl   0xc(%%edx),     %%esp"          "\n\t"
+       "movl   0xC(%%edx),     %%esp"          "\n\t"
        "movl   0x8(%%edx),     %%ebp"          "\n\t"
        "movl   0x0(%%edx),     %%eax"          "\n\t"
        "movl   %%eax,          %%fs:0"         "\n\t"
index 209b860..573ac7d 100644 (file)
@@ -76,6 +76,8 @@ static void           FileChannelExitHandler(ClientData clientData);
 static void            FileCheckProc(ClientData clientData, int flags);
 static int             FileCloseProc(ClientData instanceData,
                            Tcl_Interp *interp);
+static int             FileClose2Proc(ClientData instanceData,
+                           Tcl_Interp *interp, int flags);
 static int             FileEventProc(Tcl_Event *evPtr, int flags);
 static int             FileGetHandleProc(ClientData instanceData,
                            int direction, ClientData *handlePtr);
@@ -111,7 +113,7 @@ static const Tcl_ChannelType fileChannelType = {
     NULL,                      /* Get option proc. */
     FileWatchProc,             /* Set up the notifier to watch the channel. */
     FileGetHandleProc,         /* Get an OS handle from channel. */
-    NULL,                      /* close2proc. */
+       FileClose2Proc,         /* close2proc. */
     FileBlockProc,             /* Set blocking or non-blocking mode.*/
     NULL,                      /* flush proc. */
     NULL,                      /* handler proc. */
@@ -360,7 +362,7 @@ FileBlockProc(
 /*
  *----------------------------------------------------------------------
  *
- * FileCloseProc --
+ * FileCloseProc/FileClose2Proc --
  *
  *     Closes the IO channel.
  *
@@ -427,6 +429,18 @@ FileCloseProc(
     ckfree(fileInfoPtr);
     return errorCode;
 }
+
+static int
+FileClose2Proc(
+    ClientData instanceData,   /* Pointer to FileInfo structure. */
+    Tcl_Interp *interp,                /* Not used. */
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return FileCloseProc(instanceData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -954,7 +968,7 @@ TclpOpenFileChannel(
     if (handle == INVALID_HANDLE_VALUE) {
        DWORD err = GetLastError();
 
-       if ((err & 0xffffL) == ERROR_OPEN_FAILED) {
+       if ((err & 0xFFFFL) == ERROR_OPEN_FAILED) {
            err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
        }
        TclWinConvertError(err);
@@ -1052,7 +1066,7 @@ Tcl_MakeFileChannel(
     int mode)                  /* ORed combination of TCL_READABLE and
                                 * TCL_WRITABLE to indicate file mode. */
 {
-#if defined(HAVE_NO_SEH) && !defined(_WIN64)
+#if defined(HAVE_NO_SEH) && !defined(_WIN64) && !defined(__clang__)
     TCLEXCEPTION_REGISTRATION registration;
 #endif
     char channelName[16 + TCL_INTEGER_SPACE];
@@ -1105,7 +1119,7 @@ Tcl_MakeFileChannel(
 
        if (result == 0) {
            /*
-            * Unable to make a duplicate. It's definately invalid at this
+            * Unable to make a duplicate. It's definitely invalid at this
             * point.
             */
 
@@ -1118,7 +1132,7 @@ Tcl_MakeFileChannel(
         */
 
        result = 0;
-#if defined(HAVE_NO_SEH) && !defined(_WIN64)
+#if defined(HAVE_NO_SEH) && !defined(_WIN64) && !defined(__clang__)
        /*
         * Don't have SEH available, do things the hard way. Note that this
         * needs to be one block of asm, to avoid stack imbalance; also, it is
@@ -1144,7 +1158,7 @@ Tcl_MakeFileChannel(
            "leal       1f,             %%eax"          "\n\t"
            "movl       %%eax,          0x4(%%edx)"     "\n\t" /* handler */
            "movl       %%ebp,          0x8(%%edx)"     "\n\t" /* ebp */
-           "movl       %%esp,          0xc(%%edx)"     "\n\t" /* esp */
+           "movl       %%esp,          0xC(%%edx)"     "\n\t" /* esp */
            "movl       $0,             0x10(%%edx)"    "\n\t" /* status */
 
            /*
@@ -1184,7 +1198,7 @@ Tcl_MakeFileChannel(
             */
 
            "2:"                                        "\t"
-           "movl       0xc(%%edx),     %%esp"          "\n\t"
+           "movl       0xC(%%edx),     %%esp"          "\n\t"
            "movl       0x8(%%edx),     %%ebp"          "\n\t"
            "movl       0x0(%%edx),     %%eax"          "\n\t"
            "movl       %%eax,          %%fs:0"         "\n\t"
@@ -1363,7 +1377,7 @@ TclWinOpenFileChannel(
     infoPtr->flags = appendMode;
     infoPtr->handle = handle;
     infoPtr->dirty = 0;
-    sprintf(channelName, "file%" TCL_I_MODIFIER "x", (size_t) infoPtr);
+    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&fileChannelType, channelName,
            infoPtr, permissions);
index 173fe9e..bb5166b 100644 (file)
@@ -140,6 +140,8 @@ static int          ConsoleBlockModeProc(ClientData instanceData,
 static void            ConsoleCheckProc(ClientData clientData, int flags);
 static int             ConsoleCloseProc(ClientData instanceData,
                            Tcl_Interp *interp);
+static int             ConsoleClose2Proc(ClientData instanceData,
+                           Tcl_Interp *interp, int flags);
 static int             ConsoleEventProc(Tcl_Event *evPtr, int flags);
 static void            ConsoleExitHandler(ClientData clientData);
 static int             ConsoleGetHandleProc(ClientData instanceData,
@@ -179,7 +181,7 @@ static const Tcl_ChannelType consoleChannelType = {
     NULL,                      /* Get option proc. */
     ConsoleWatchProc,          /* Set up notifier to watch the channel. */
     ConsoleGetHandleProc,      /* Get an OS handle from channel. */
-    NULL,                      /* close2proc. */
+       ConsoleClose2Proc,              /* close2proc. */
     ConsoleBlockModeProc,      /* Set blocking or non-blocking mode. */
     NULL,                      /* Flush proc. */
     NULL,                      /* Handler proc. */
@@ -506,7 +508,7 @@ ConsoleBlockModeProc(
 /*
  *----------------------------------------------------------------------
  *
- * ConsoleCloseProc --
+ * ConsoleCloseProc/ConsoleClose2Proc --
  *
  *     Closes a console based IO channel.
  *
@@ -604,6 +606,18 @@ ConsoleCloseProc(
 
     return errorCode;
 }
+
+static int
+ConsoleClose2Proc(
+    ClientData instanceData,   /* Pointer to ConsoleInfo structure. */
+    Tcl_Interp *interp,                /* For error reporting. */
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return ConsoleCloseProc(instanceData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -658,11 +672,11 @@ ConsoleInputProc(
         */
 
        if (bufSize < (infoPtr->bytesRead - infoPtr->offset)) {
-           memcpy(buf, &infoPtr->buffer[infoPtr->offset], (size_t) bufSize);
+           memcpy(buf, &infoPtr->buffer[infoPtr->offset], bufSize);
            bytesRead = bufSize;
            infoPtr->offset += bufSize;
        } else {
-           memcpy(buf, &infoPtr->buffer[infoPtr->offset], (size_t) bufSize);
+           memcpy(buf, &infoPtr->buffer[infoPtr->offset], bufSize);
            bytesRead = infoPtr->bytesRead - infoPtr->offset;
 
            /*
@@ -769,7 +783,7 @@ ConsoleOutputProc(
            infoPtr->writeBufLen = toWrite;
            infoPtr->writeBuf = ckalloc(toWrite);
        }
-       memcpy(infoPtr->writeBuf, buf, (size_t) toWrite);
+       memcpy(infoPtr->writeBuf, buf, toWrite);
        infoPtr->toWrite = toWrite;
        ResetEvent(threadInfo->readyEvent);
        TclPipeThreadSignal(&threadInfo->TI);
@@ -1318,7 +1332,7 @@ TclWinOpenConsoleChannel(
      * for instance).
      */
 
-    sprintf(channelName, "file%" TCL_I_MODIFIER "x", (size_t) infoPtr);
+    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&consoleChannelType, channelName,
            infoPtr, permissions);
index 267ee6e..2fc4990 100644 (file)
@@ -79,7 +79,7 @@ static DWORD ddeInstance;     /* The application instance handle given to us
                                 * by DdeInitialize. */
 static int ddeIsServer = 0;
 
-#define TCL_DDE_VERSION                "1.4.2"
+#define TCL_DDE_VERSION                "1.4.3"
 #define TCL_DDE_PACKAGE_NAME   "dde"
 #define TCL_DDE_SERVICE_NAME   L"TclEval"
 #define TCL_DDE_EXECUTE_RESULT L"$TCLEVAL$EXECUTE$RESULT"
@@ -251,7 +251,7 @@ Initialize(void)
     if (ddeInstance == 0) {
        Tcl_MutexLock(&ddeMutex);
        if (ddeInstance == 0) {
-           if (DdeInitializeW(&ddeInstance, (PFNCALLBACK) DdeServerProc,
+           if (DdeInitializeW(&ddeInstance, (PFNCALLBACK)(void *)DdeServerProc,
                    CBF_SKIP_REGISTRATIONS | CBF_SKIP_UNREGISTRATIONS
                    | CBF_FAIL_POKES, 0) != DMLERR_NO_ERROR) {
                ddeInstance = 0;
index 9df9d82..86fea7e 100644 (file)
@@ -204,7 +204,7 @@ DoRenameFile(
        "leal       1f,             %%eax"          "\n\t"
        "movl       %%eax,          0x4(%%edx)"     "\n\t" /* handler */
        "movl       %%ebp,          0x8(%%edx)"     "\n\t" /* ebp */
-       "movl       %%esp,          0xc(%%edx)"     "\n\t" /* esp */
+       "movl       %%esp,          0xC(%%edx)"     "\n\t" /* esp */
        "movl       $0,             0x10(%%edx)"    "\n\t" /* status */
 
        /*
@@ -245,7 +245,7 @@ DoRenameFile(
         */
 
        "2:"                                        "\t"
-       "movl       0xc(%%edx),     %%esp"          "\n\t"
+       "movl       0xC(%%edx),     %%esp"          "\n\t"
        "movl       0x8(%%edx),     %%ebp"          "\n\t"
        "movl       0x0(%%edx),     %%eax"          "\n\t"
        "movl       %%eax,          %%fs:0"         "\n\t"
@@ -283,7 +283,7 @@ DoRenameFile(
 
     srcAttr = GetFileAttributesW(nativeSrc);
     dstAttr = GetFileAttributesW(nativeDst);
-    if (srcAttr == 0xffffffff) {
+    if (srcAttr == 0xFFFFFFFF) {
        if (GetFullPathNameW(nativeSrc, 0, NULL,
                NULL) >= MAX_PATH) {
            errno = ENAMETOOLONG;
@@ -291,7 +291,7 @@ DoRenameFile(
        }
        srcAttr = 0;
     }
-    if (dstAttr == 0xffffffff) {
+    if (dstAttr == 0xFFFFFFFF) {
        if (GetFullPathNameW(nativeDst, 0, NULL,
                NULL) >= MAX_PATH) {
            errno = ENAMETOOLONG;
@@ -337,7 +337,7 @@ DoRenameFile(
             * character is either end-of-string or a directory separator
             */
 
-           if ((strncmp(src, dst, (size_t) Tcl_DStringLength(&srcString))==0)
+           if ((strncmp(src, dst, Tcl_DStringLength(&srcString))==0)
                    && (dst[Tcl_DStringLength(&srcString)] == '\\'
                    || dst[Tcl_DStringLength(&srcString)] == '/'
                    || dst[Tcl_DStringLength(&srcString)] == '\0')) {
@@ -591,7 +591,7 @@ DoCopyFile(
        "leal       1f,             %%eax"          "\n\t"
        "movl       %%eax,          0x4(%%edx)"     "\n\t" /* handler */
        "movl       %%ebp,          0x8(%%edx)"     "\n\t" /* ebp */
-       "movl       %%esp,          0xc(%%edx)"     "\n\t" /* esp */
+       "movl       %%esp,          0xC(%%edx)"     "\n\t" /* esp */
        "movl       $0,             0x10(%%edx)"    "\n\t" /* status */
 
        /*
@@ -633,7 +633,7 @@ DoCopyFile(
         */
 
        "2:"                                        "\t"
-       "movl       0xc(%%edx),     %%esp"          "\n\t"
+       "movl       0xC(%%edx),     %%esp"          "\n\t"
        "movl       0x8(%%edx),     %%ebp"          "\n\t"
        "movl       0x0(%%edx),     %%eax"          "\n\t"
        "movl       %%eax,          %%fs:0"         "\n\t"
@@ -677,8 +677,8 @@ DoCopyFile(
 
        srcAttr = GetFileAttributesW(nativeSrc);
        dstAttr = GetFileAttributesW(nativeDst);
-       if (srcAttr != 0xffffffff) {
-           if (dstAttr == 0xffffffff) {
+       if (srcAttr != 0xFFFFFFFF) {
+           if (dstAttr == 0xFFFFFFFF) {
                dstAttr = 0;
            }
            if ((srcAttr & FILE_ATTRIBUTE_DIRECTORY) ||
@@ -768,7 +768,7 @@ TclpDeleteFile(
 
     if (Tcl_GetErrno() == EACCES) {
        attr = GetFileAttributesW(path);
-       if (attr != 0xffffffff) {
+       if (attr != 0xFFFFFFFF) {
            if (attr & FILE_ATTRIBUTE_DIRECTORY) {
                if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
                    /*
@@ -803,7 +803,7 @@ TclpDeleteFile(
        }
     } else if (Tcl_GetErrno() == ENOENT) {
        attr = GetFileAttributesW(path);
-       if (attr != 0xffffffff) {
+       if (attr != 0xFFFFFFFF) {
            if (attr & FILE_ATTRIBUTE_DIRECTORY) {
                /*
                 * Windows 95 reports removing a directory as ENOENT instead
@@ -1053,7 +1053,7 @@ DoRemoveJustDirectory(
 
     if (Tcl_GetErrno() == EACCES) {
        attr = GetFileAttributesW(nativePath);
-       if (attr != 0xffffffff) {
+       if (attr != 0xFFFFFFFF) {
            if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
                /*
                 * Windows 95 reports calling RemoveDirectory on a file as an
@@ -1195,7 +1195,7 @@ TraverseWinTree(
 
     oldSourceLen = Tcl_DStringLength(sourcePtr);
     sourceAttr = GetFileAttributesW(nativeSource);
-    if (sourceAttr == 0xffffffff) {
+    if (sourceAttr == 0xFFFFFFFF) {
        nativeErrfile = nativeSource;
        goto end;
     }
@@ -1509,7 +1509,7 @@ GetWinFileAttributes(
     nativeName = Tcl_FSGetNativePath(fileName);
     result = GetFileAttributesW(nativeName);
 
-    if (result == 0xffffffff) {
+    if (result == 0xFFFFFFFF) {
        StatError(interp, fileName);
        return TCL_ERROR;
     }
@@ -1836,7 +1836,7 @@ SetWinFileAttributes(
     nativeName = Tcl_FSGetNativePath(fileName);
     fileAttributes = old = GetFileAttributesW(nativeName);
 
-    if (fileAttributes == 0xffffffff) {
+    if (fileAttributes == 0xFFFFFFFF) {
        StatError(interp, fileName);
        return TCL_ERROR;
     }
@@ -1916,7 +1916,7 @@ TclpObjListVolumes(void)
     int i;
     char *p;
 
-    resultPtr = Tcl_NewObj();
+    TclNewObj(resultPtr);
 
     /*
      * On Win32s:
index e050862..fba82d7 100644 (file)
@@ -169,7 +169,7 @@ static int          NativeWriteReparse(const WCHAR *LinkDirectory,
                            REPARSE_DATA_BUFFER *buffer);
 static int             NativeMatchType(int isDrive, DWORD attr,
                            const WCHAR *nativeName, Tcl_GlobTypeData *types);
-static int             WinIsDrive(const char *name, int nameLen);
+static int             WinIsDrive(const char *name, size_t nameLen);
 static int             WinIsReserved(const char *path);
 static Tcl_Obj *       WinReadLink(const WCHAR *LinkSource);
 static Tcl_Obj *       WinReadLinkDirectory(const WCHAR *LinkDirectory);
@@ -264,11 +264,21 @@ WinLink(
 
            TclWinConvertError(GetLastError());
        } else if (linkAction & TCL_CREATE_SYMBOLIC_LINK) {
-           /*
-            * Can't symlink files.
-            */
+           if (!tclWinProcs.createSymbolicLink) {
+               /*
+                * Can't symlink files.
+                */
+               Tcl_SetErrno(EINVAL);
+           } else if (tclWinProcs.createSymbolicLink(linkSourcePath, linkTargetPath,
+                   0x2 /* SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE */)) {
+               /*
+                * Success!
+                */
 
-           Tcl_SetErrno(ENOTDIR);
+               return 0;
+           } else {
+               TclWinConvertError(GetLastError());
+           }
        } else {
            Tcl_SetErrno(ENODEV);
        }
@@ -395,11 +405,11 @@ WinSymLinkDirectory(
      */
 
     for (loop = nativeTarget; *loop != 0; loop++) {
-       if (*loop == L'/') {
-           *loop = L'\\';
+       if (*loop == '/') {
+           *loop = '\\';
        }
     }
-    if ((nativeTarget[len-1] == L'\\') && (nativeTarget[len-2] != L':')) {
+    if ((nativeTarget[len-1] == '\\') && (nativeTarget[len-2] != ':')) {
        nativeTarget[len-1] = 0;
     }
 
@@ -572,8 +582,7 @@ WinReadLinkDirectory(
         */
 
        offset = 0;
-#if 1
-       if (reparseBuffer->MountPointReparseBuffer.PathBuffer[0] == L'\\') {
+       if (reparseBuffer->MountPointReparseBuffer.PathBuffer[0] == '\\') {
            /*
             * Check whether this is a mounted volume.
             */
@@ -587,7 +596,7 @@ WinReadLinkDirectory(
                 * to fix here. It doesn't seem very well documented.
                 */
 
-               reparseBuffer->MountPointReparseBuffer.PathBuffer[1]=L'\\';
+               reparseBuffer->MountPointReparseBuffer.PathBuffer[1] = '\\';
 
                /*
                 * Check if a corresponding drive letter exists, and use that
@@ -634,11 +643,10 @@ WinReadLinkDirectory(
                offset = 4;
            }
        }
-#endif /* UNICODE */
 
        Tcl_WinTCharToUtf((TCHAR *)
                reparseBuffer->MountPointReparseBuffer.PathBuffer,
-               (int) reparseBuffer->MountPointReparseBuffer
+               reparseBuffer->MountPointReparseBuffer
                .SubstituteNameLength, &ds);
 
        copy = Tcl_DStringValue(&ds)+offset;
@@ -810,13 +818,13 @@ tclWinDebugPanic(
 {
 #define TCL_MAX_WARN_LEN 1024
     va_list argList;
-    char buf[TCL_MAX_WARN_LEN * TCL_UTF_MAX];
+    char buf[TCL_MAX_WARN_LEN * 3];
     WCHAR msgString[TCL_MAX_WARN_LEN];
 
     va_start(argList, format);
     vsnprintf(buf, sizeof(buf), format, argList);
 
-    msgString[TCL_MAX_WARN_LEN-1] = L'\0';
+    msgString[TCL_MAX_WARN_LEN-1] = '\0';
     MultiByteToWideChar(CP_UTF8, 0, buf, -1, msgString, TCL_MAX_WARN_LEN);
 
     /*
@@ -824,7 +832,7 @@ tclWinDebugPanic(
      * and cause possible oversized window error.
      */
 
-    if (msgString[TCL_MAX_WARN_LEN-1] != L'\0') {
+    if (msgString[TCL_MAX_WARN_LEN-1] != '\0') {
        memcpy(msgString + (TCL_MAX_WARN_LEN - 5), L" ...", 5 * sizeof(WCHAR));
     }
     if (IsDebuggerPresent()) {
@@ -869,7 +877,7 @@ TclpFindExecutable(
                                 * ignore. */
 {
     WCHAR wName[MAX_PATH];
-    char name[MAX_PATH * TCL_UTF_MAX];
+    char name[MAX_PATH * 3];
 
     /*
      * Under Windows we ignore argv0, and return the path for the file used to
@@ -1093,7 +1101,6 @@ TclpMatchInDirectory(
        do {
            const char *utfname;
            int checkDrive = 0, isDrive;
-           DWORD attr;
 
            native = data.cFileName;
            attr = data.dwFileAttributes;
@@ -1174,7 +1181,7 @@ TclpMatchInDirectory(
 static int
 WinIsDrive(
     const char *name,          /* Name (UTF-8) */
-    int len)                   /* Length of name */
+    size_t len)                        /* Length of name */
 {
     int remove = 0;
 
@@ -1253,7 +1260,7 @@ WinIsReserved(
 
            if (path[4] == '\0') {
                return 4;
-           } else if (path [4] == ':' && path[5] == '\0') {
+           } else if (path[4] == ':' && path[5] == '\0') {
                return 4;
            }
        } else if ((path[2] == 'n' || path[2] == 'N') && path[3] == '\0') {
@@ -1274,7 +1281,7 @@ WinIsReserved(
 
            if (path[4] == '\0') {
                return 4;
-           } else if (path [4] == ':' && path[5] == '\0') {
+           } else if (path[4] == ':' && path[5] == '\0') {
                return 4;
            }
        }
@@ -1443,7 +1450,6 @@ TclpGetUserHome(
     int rc = 0;
     const char *domain;
     WCHAR *wName, *wHomeDir, *wDomain;
-    WCHAR buf[MAX_PATH];
 
     Tcl_DStringInit(bufferPtr);
 
@@ -1471,14 +1477,12 @@ TclpGetUserHome(
        }
        Tcl_DStringFree(&ds);
     } else {
-       Tcl_DStringInit(&ds);
        wName = (WCHAR *)Tcl_WinUtfToTChar(domain + 1, -1, &ds);
        rc = NetGetDCName(NULL, wName, (LPBYTE *) &wDomain);
        Tcl_DStringFree(&ds);
        nameLen = domain - name;
     }
     if (rc == 0) {
-       Tcl_DStringInit(&ds);
        wName = (WCHAR *)Tcl_WinUtfToTChar(name, nameLen, &ds);
        while (NetUserGetInfo(wDomain, wName, 1, (LPBYTE *) &uiPtr) != 0) {
            /*
@@ -1505,10 +1509,11 @@ TclpGetUserHome(
            DWORD i, size = MAX_PATH;
 
            wHomeDir = uiPtr->usri1_home_dir;
-           if ((wHomeDir != NULL) && (wHomeDir[0] != L'\0')) {
+           if ((wHomeDir != NULL) && (wHomeDir[0] != '\0')) {
                size = lstrlenW(wHomeDir);
                Tcl_WinTCharToUtf((TCHAR *)wHomeDir, size*sizeof(WCHAR), bufferPtr);
            } else {
+               WCHAR buf[MAX_PATH];
                /*
                 * User exists but has no home dir. Return
                 * "{GetProfilesDirectory}/<user>".
@@ -1522,7 +1527,7 @@ TclpGetUserHome(
            result = Tcl_DStringValue(bufferPtr);
 
            /*
-            * Be sure we returns normalized path
+            * Be sure we return normalized path
             */
 
            for (i = 0; i < size; ++i) {
@@ -1691,7 +1696,6 @@ NativeAccess(
      * what permissions the OS has set for a file.
      */
 
-#if 1
     {
        SECURITY_DESCRIPTOR *sdPtr = NULL;
        unsigned long size;
@@ -1854,7 +1858,6 @@ NativeAccess(
        }
 
     }
-#endif /* !UNICODE */
     return 0;
 }
 \f
@@ -1887,11 +1890,11 @@ NativeIsExec(
     }
 
     path += len-3;
-    if ((wcsicmp(path, L"exe") == 0)
-           || (wcsicmp(path, L"com") == 0)
-           || (wcsicmp(path, L"cmd") == 0)
-           || (wcsicmp(path, L"cmd") == 0)
-           || (wcsicmp(path, L"bat") == 0)) {
+    if ((_wcsicmp(path, L"exe") == 0)
+           || (_wcsicmp(path, L"com") == 0)
+           || (_wcsicmp(path, L"cmd") == 0)
+           || (_wcsicmp(path, L"cmd") == 0)
+           || (_wcsicmp(path, L"bat") == 0)) {
        return 1;
     }
     return 0;
@@ -2205,7 +2208,7 @@ NativeDev(
        p = strchr(p + 1, '\\');
        if (p == NULL) {
            /*
-            * Add terminating backslash to fullpath or GetVolumeInformationW()
+            * Add terminating backslash to fullpath or GetVolumeInformation()
             * won't work.
             */
 
@@ -2538,8 +2541,9 @@ TclpFilesystemPathType(
 int
 TclpObjNormalizePath(
     Tcl_Interp *interp,
-    Tcl_Obj *pathPtr,
-    int nextCheckpoint)
+    Tcl_Obj *pathPtr,          /* An unshared object containing the path to
+                                * normalize */
+    int nextCheckpoint)                /* offset to start at in pathPtr */
 {
     char *lastValidPathEnd = NULL;
     Tcl_DString dsNorm;                /* This will hold the normalized string. */
@@ -2586,8 +2590,8 @@ TclpObjNormalizePath(
                        for (i=0 ; i<len ; i++) {
                            WCHAR wc = ((WCHAR *) nativePath)[i];
 
-                           if (wc >= L'a') {
-                               wc -= (L'a' - L'A');
+                           if (wc >= 'a') {
+                               wc -= ('a' - 'A');
                                ((WCHAR *) nativePath)[i] = wc;
                            }
                        }
@@ -2677,8 +2681,8 @@ TclpObjNormalizePath(
            if (isDrive) {
                WCHAR drive = ((WCHAR *) nativePath)[0];
 
-               if (drive >= L'a') {
-                   drive -= (L'a' - L'A');
+               if (drive >= 'a') {
+                   drive -= ('a' - 'A');
                    ((WCHAR *) nativePath)[0] = drive;
                }
                Tcl_DStringAppend(&dsNorm, (const char *)nativePath,
@@ -2709,7 +2713,7 @@ TclpObjNormalizePath(
                    Tcl_DStringAppend(&dsNorm, ((const char *)nativePath)
                            + Tcl_DStringLength(&ds)
                            - (dotLen * sizeof(WCHAR)),
-                           (int)(dotLen * sizeof(WCHAR)));
+                           dotLen * sizeof(WCHAR));
                } else {
                    /*
                     * Normal path.
@@ -2775,8 +2779,8 @@ TclpObjNormalizePath(
             * We have to make the drive letter uppercase.
             */
 
-           if (wpath[0] >= L'a') {
-               wpath[0] -= (L'a' - L'A');
+           if (wpath[0] >= 'a') {
+               wpath[0] -= ('a' - 'A');
            }
            Tcl_DStringAppend(&dsNorm, (const char *) wpath,
                    wpathlen * sizeof(WCHAR));
@@ -2806,7 +2810,6 @@ TclpObjNormalizePath(
             */
 
            int len;
-           char *path;
            Tcl_Obj *tmpPathPtr;
 
            tmpPathPtr = Tcl_NewStringObj(Tcl_DStringValue(&ds),
@@ -3021,7 +3024,7 @@ TclpNativeToNormalized(
  *     The nativePath representation.
  *
  * Side effects:
- *     Memory will be allocated. The path may need to be normalized.
+ *     Memory will be allocated. The path might be normalized.
  *
  *---------------------------------------------------------------------------
  */
@@ -3073,7 +3076,7 @@ TclNativeCreateNativeRep(
     str = Tcl_GetString(validPathPtr);
     len = validPathPtr->length;
 
-    if (strlen(str) != (unsigned int) len) {
+    if (strlen(str) != len) {
        /*
         * String contains NUL-bytes. This is invalid.
         */
@@ -3107,7 +3110,8 @@ TclNativeCreateNativeRep(
       goto done;
     }
     MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str, -1, nativePathPtr,
-           len + 1);
+           len + 2);
+    nativePathPtr[len] = 0;
 
     /*
      * If path starts with "//?/" or "\\?\" (extended path), translate any
index cb13b20..409c87f 100644 (file)
@@ -83,16 +83,10 @@ typedef struct {
 TclWinProcs tclWinProcs;
 
 /*
- * The following arrays contain the human readable strings for the Windows
- * platform and processor values.
+ * The following arrays contain the human readable strings for the
+ * processor values.
  */
 
-
-#define NUMPLATFORMS 4
-static const char *const platforms[NUMPLATFORMS] = {
-    "Win32s", "Windows 95", "Windows NT", "Windows CE"
-};
-
 #define NUMPROCESSORS 11
 static const char *const processors[NUMPROCESSORS] = {
     "intel", "mips", "alpha", "ppc", "shx", "arm", "ia64", "alpha64", "msil",
@@ -160,7 +154,7 @@ TclpInitPlatform(void)
      * invoked.
      */
 
-    TclWinInit(GetModuleHandle(NULL));
+    TclWinInit(GetModuleHandleW(NULL));
 #endif
 
     /*
@@ -168,8 +162,11 @@ TclpInitPlatform(void)
      */
     handle = GetModuleHandleW(L"KERNEL32");
     tclWinProcs.cancelSynchronousIo =
-           (BOOL (WINAPI *)(HANDLE)) GetProcAddress(handle,
+           (BOOL (WINAPI *)(HANDLE))(void *)GetProcAddress(handle,
            "CancelSynchronousIo");
+    tclWinProcs.createSymbolicLink =
+           (BOOLEAN (WINAPI *)(LPCWSTR, LPCWSTR, DWORD))(void *)GetProcAddress(handle,
+           "CreateSymbolicLinkW");
 }
 \f
 /*
@@ -200,7 +197,7 @@ TclpInitLibraryPath(
     char installLib[LIBRARY_SIZE];
     const char *bytes;
 
-    pathPtr = Tcl_NewObj();
+    TclNewObj(pathPtr);
 
     /*
      * Initialize the substring used when locating the script library. The
@@ -235,8 +232,8 @@ TclpInitLibraryPath(
 
     *encodingPtr = NULL;
     bytes = Tcl_GetStringFromObj(pathPtr, lengthPtr);
-    *valuePtr = ckalloc((*lengthPtr) + 1);
-    memcpy(*valuePtr, bytes, (size_t)(*lengthPtr)+1);
+    *valuePtr = (char *)ckalloc(*lengthPtr + 1);
+    memcpy(*valuePtr, bytes, *lengthPtr + 1);
     Tcl_DecrRefCount(pathPtr);
 }
 \f
@@ -266,7 +263,7 @@ AppendEnvironment(
 {
     int pathc;
     WCHAR wBuf[MAX_PATH];
-    char buf[MAX_PATH * TCL_UTF_MAX];
+    char buf[MAX_PATH * 3];
     Tcl_Obj *objPtr;
     Tcl_DString ds;
     const char **pathv;
@@ -279,7 +276,7 @@ AppendEnvironment(
 
     for (shortlib = (char *) &lib[strlen(lib)-1]; shortlib>lib ; shortlib--) {
        if (*shortlib == '/') {
-           if ((unsigned)(shortlib - lib) == strlen(lib) - 1) {
+           if ((size_t)(shortlib - lib) == strlen(lib) - 1) {
                Tcl_Panic("last character in lib cannot be '/'");
            }
            shortlib++;
@@ -359,7 +356,7 @@ InitializeDefaultLibraryDir(
 {
     HMODULE hModule = TclWinGetTclInstance();
     WCHAR wName[MAX_PATH + LIBRARY_SIZE];
-    char name[(MAX_PATH + LIBRARY_SIZE) * TCL_UTF_MAX];
+    char name[(MAX_PATH + LIBRARY_SIZE) * 3];
     char *end, *p;
 
     if (GetModuleFileNameW(hModule, wName, MAX_PATH) == 0) {
@@ -379,9 +376,9 @@ InitializeDefaultLibraryDir(
     TclWinNoBackslash(name);
     sprintf(end + 1, "lib/tcl%s", TCL_VERSION);
     *lengthPtr = strlen(name);
-    *valuePtr = ckalloc(*lengthPtr + 1);
+    *valuePtr = (char *)ckalloc(*lengthPtr + 1);
     *encodingPtr = NULL;
-    memcpy(*valuePtr, name, (size_t) *lengthPtr + 1);
+    memcpy(*valuePtr, name, *lengthPtr + 1);
 }
 \f
 /*
@@ -430,9 +427,9 @@ InitializeSourceLibraryDir(
     TclWinNoBackslash(name);
     sprintf(end + 1, "../library");
     *lengthPtr = strlen(name);
-    *valuePtr = ckalloc(*lengthPtr + 1);
+    *valuePtr = (char *)ckalloc(*lengthPtr + 1);
     *encodingPtr = NULL;
-    memcpy(*valuePtr, name, (size_t) *lengthPtr + 1);
+    memcpy(*valuePtr, name, *lengthPtr + 1);
 }
 \f
 /*
@@ -494,7 +491,6 @@ TclpSetInitialEncodings(void)
 {
     Tcl_DString encodingName;
 
-    TclpSetInterfaces();
     Tcl_SetSystemEncoding(NULL,
            Tcl_GetEncodingNameFromEnvironment(&encodingName));
     Tcl_DStringFree(&encodingName);
@@ -503,17 +499,23 @@ TclpSetInitialEncodings(void)
 void TclWinSetInterfaces(
     int dummy)                 /* Not used. */
 {
-    TclpSetInterfaces();
+    (void)dummy;
 }
 
 const char *
 Tcl_GetEncodingNameFromEnvironment(
     Tcl_DString *bufPtr)
 {
+    UINT acp = GetACP();
+
     Tcl_DStringInit(bufPtr);
-    Tcl_DStringSetLength(bufPtr, 2+TCL_INTEGER_SPACE);
-    wsprintfA(Tcl_DStringValue(bufPtr), "cp%d", GetACP());
-    Tcl_DStringSetLength(bufPtr, strlen(Tcl_DStringValue(bufPtr)));
+    if (acp == CP_UTF8) {
+       Tcl_DStringAppend(bufPtr, "utf-8", 5);
+    } else {
+       Tcl_DStringSetLength(bufPtr, 2+TCL_INTEGER_SPACE);
+       wsprintfA(Tcl_DStringValue(bufPtr), "cp%d", GetACP());
+       Tcl_DStringSetLength(bufPtr, strlen(Tcl_DStringValue(bufPtr)));
+    }
     return Tcl_DStringValue(bufPtr);
 }
 \f
@@ -575,7 +577,7 @@ TclpSetVariables(
     if (!osInfoInitialized) {
        HMODULE handle = GetModuleHandleW(L"NTDLL");
        int(__stdcall *getversion)(void *) =
-               (int(__stdcall *)(void *)) GetProcAddress(handle, "RtlGetVersion");
+               (int(__stdcall *)(void *))(void *)GetProcAddress(handle, "RtlGetVersion");
        osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
        if (!getversion || getversion(&osInfo)) {
            GetVersionExW(&osInfo);
@@ -590,10 +592,8 @@ TclpSetVariables(
 
     Tcl_SetVar2(interp, "tcl_platform", "platform", "windows",
            TCL_GLOBAL_ONLY);
-    if (osInfo.dwPlatformId < NUMPLATFORMS) {
-       Tcl_SetVar2(interp, "tcl_platform", "os",
-               platforms[osInfo.dwPlatformId], TCL_GLOBAL_ONLY);
-    }
+    Tcl_SetVar2(interp, "tcl_platform", "os",
+           "Windows NT", TCL_GLOBAL_ONLY);
     wsprintfA(buffer, "%d.%d", osInfo.dwMajorVersion, osInfo.dwMinorVersion);
     Tcl_SetVar2(interp, "tcl_platform", "osVersion", buffer, TCL_GLOBAL_ONLY);
     if (sys.oemId.wProcessorArchitecture < NUMPROCESSORS) {
@@ -687,7 +687,8 @@ TclpFindVariable(
                                 * searches). */
 {
     int i, length, result = -1;
-    register const char *env, *p1, *p2;
+    const WCHAR *env;
+    const char *p1, *p2;
     char *envUpper, *nameUpper;
     Tcl_DString envString;
 
@@ -696,19 +697,21 @@ TclpFindVariable(
      */
 
     length = strlen(name);
-    nameUpper = ckalloc(length + 1);
-    memcpy(nameUpper, name, (size_t) length+1);
+    nameUpper = (char *)ckalloc(length + 1);
+    memcpy(nameUpper, name, length+1);
     Tcl_UtfToUpper(nameUpper);
 
     Tcl_DStringInit(&envString);
-    for (i = 0, env = environ[i]; env != NULL; i++, env = environ[i]) {
+    for (i = 0, env = _wenviron[i];
+       env != NULL;
+       i++, env = _wenviron[i]) {
        /*
         * Chop the env string off after the equal sign, then Convert the name
         * to all upper case, so we do not have to convert all the characters
         * after the equal sign.
         */
 
-       envUpper = Tcl_ExternalToUtfDString(NULL, env, -1, &envString);
+       envUpper = Tcl_WinTCharToUtf((TCHAR *)env, -1, &envString);
        p1 = strchr(envUpper, '=');
        if (p1 == NULL) {
            continue;
index ed99ad0..7aac7d0 100644 (file)
@@ -36,6 +36,7 @@ typedef struct TCLEXCEPTION_REGISTRATION {
  */
 typedef struct TclWinProcs {
     BOOL (WINAPI *cancelSynchronousIo)(HANDLE);
+    BOOLEAN (WINAPI *createSymbolicLink)(LPCWSTR, LPCWSTR, DWORD);
 } TclWinProcs;
 
 MODULE_SCOPE TclWinProcs tclWinProcs;
@@ -53,11 +54,18 @@ MODULE_SCOPE TclWinProcs tclWinProcs;
 #define VER_PLATFORM_WIN32_CE 3
 #endif
 
-#ifdef _WIN64
-#         define TCL_I_MODIFIER        "I"
-#else
-#         define TCL_I_MODIFIER        ""
+#ifndef TCL_Z_MODIFIER
+#   ifdef _WIN64
+#      if defined(__USE_MINGW_ANSI_STDIO) && __USE_MINGW_ANSI_STDIO
+#         define TCL_Z_MODIFIER        "ll"
+#      else
+#         define TCL_Z_MODIFIER        "I"
+#      endif
+#   else
+#         define TCL_Z_MODIFIER        ""
+#   endif
 #endif
+#define TCL_I_MODIFIER TCL_Z_MODIFIER
 
 /*
  * Declarations of functions that are not accessible by way of the
@@ -66,7 +74,7 @@ MODULE_SCOPE TclWinProcs tclWinProcs;
 
 MODULE_SCOPE char      TclWinDriveLetterForVolMountPoint(
                            const WCHAR *mountPoint);
-MODULE_SCOPE void      TclWinEncodingsCleanup();
+MODULE_SCOPE void      TclWinEncodingsCleanup(void);
 MODULE_SCOPE void      TclWinInit(HINSTANCE hInst);
 MODULE_SCOPE TclFile   TclWinMakeFile(HANDLE handle);
 MODULE_SCOPE Tcl_Channel TclWinOpenConsoleChannel(HANDLE handle,
index 89adcc3..1d64d18 100644 (file)
@@ -67,6 +67,7 @@ TclpDlopen(
     const WCHAR *nativeName;
     Tcl_LoadHandle handlePtr;
     DWORD firstError;
+    (void)flags;
 
     /*
      * First try the full path the user gave us. This is particularly
@@ -74,7 +75,7 @@ TclpDlopen(
      * relative path.
      */
 
-    nativeName = Tcl_FSGetNativePath(pathPtr);
+    nativeName = (const WCHAR *)Tcl_FSGetNativePath(pathPtr);
     if (nativeName != NULL) {
        hInstance = LoadLibraryExW(nativeName, NULL,
                LOAD_WITH_ALTERED_SEARCH_PATH);
@@ -170,7 +171,7 @@ TclpDlopen(
      * Succeded; package everything up for Tcl.
      */
 
-    handlePtr = ckalloc(sizeof(struct Tcl_LoadHandle_));
+    handlePtr = (Tcl_LoadHandle)ckalloc(sizeof(struct Tcl_LoadHandle_));
     handlePtr->clientData = (ClientData) hInstance;
     handlePtr->findSymbolProcPtr = &FindSymbol;
     handlePtr->unloadFileProcPtr = &UnloadFile;
@@ -202,14 +203,14 @@ FindSymbol(
     const char *symbol)
 {
     HINSTANCE hInstance = (HINSTANCE) loadHandle->clientData;
-    Tcl_PackageInitProc *proc = NULL;
+    void *proc = NULL;
 
     /*
      * For each symbol, check for both Symbol and _Symbol, since Borland
      * generates C symbols with a leading '_' by default.
      */
 
-    proc = (void *) GetProcAddress(hInstance, symbol);
+    proc = (void *)GetProcAddress(hInstance, symbol);
     if (proc == NULL) {
        Tcl_DString ds;
        const char *sym2;
@@ -217,7 +218,7 @@ FindSymbol(
        Tcl_DStringInit(&ds);
        TclDStringAppendLiteral(&ds, "_");
        sym2 = Tcl_DStringAppend(&ds, symbol, -1);
-       proc = (Tcl_PackageInitProc *) GetProcAddress(hInstance, sym2);
+       proc = (void *)GetProcAddress(hInstance, sym2);
        Tcl_DStringFree(&ds);
     }
     if (proc == NULL && interp != NULL) {
@@ -285,6 +286,9 @@ TclGuessPackageName(
     Tcl_DString *bufPtr)       /* Initialized empty dstring. Append package
                                 * name to this if possible. */
 {
+    (void)fileName;
+    (void)bufPtr;
+
     return 0;
 }
 \f
@@ -416,7 +420,7 @@ InitDLLDirectoryName(void)
      */
 
   copyToGlobalBuffer:
-    dllDirectoryName = ckalloc((nameLen+1) * sizeof(WCHAR));
+    dllDirectoryName = (WCHAR *)ckalloc((nameLen+1) * sizeof(WCHAR));
     wcscpy(dllDirectoryName, name);
     return TCL_OK;
 }
index 6120358..00bc9fe 100644 (file)
@@ -609,7 +609,7 @@ TclpOpenFile(
        DWORD err;
 
        err = GetLastError();
-       if ((err & 0xffffL) == ERROR_OPEN_FAILED) {
+       if ((err & 0xFFFFL) == ERROR_OPEN_FAILED) {
            err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
        }
        TclWinConvertError(err);
@@ -1322,7 +1322,7 @@ ApplicationType(
         */
 
        attr = GetFileAttributesW(nativeFullPath);
-       if ((attr == 0xffffffff) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+       if ((attr == 0xFFFFFFFF) || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
            continue;
        }
        strcpy(fullName, Tcl_WinTCharToUtf((TCHAR *)nativeFullPath, -1, &ds));
@@ -1834,7 +1834,7 @@ TclpCreateCommandChannel(
      * unique, in case channels share handles (stdin/stdout).
      */
 
-    sprintf(channelName, "file%" TCL_I_MODIFIER "x", (size_t) infoPtr);
+    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
     infoPtr->channel = Tcl_CreateChannel(&pipeChannelType, channelName,
            infoPtr, infoPtr->validMask);
 
@@ -2317,7 +2317,7 @@ PipeOutputProc(
            infoPtr->writeBufLen = toWrite;
            infoPtr->writeBuf = ckalloc(toWrite);
        }
-       memcpy(infoPtr->writeBuf, buf, (size_t) toWrite);
+       memcpy(infoPtr->writeBuf, buf, toWrite);
        infoPtr->toWrite = toWrite;
        ResetEvent(infoPtr->writable);
        TclPipeThreadSignal(&infoPtr->writeTI);
@@ -2752,7 +2752,6 @@ TclWinAddProcess(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 int
 Tcl_PidObjCmd(
     ClientData dummy,          /* Not used. */
@@ -2784,7 +2783,7 @@ Tcl_PidObjCmd(
        }
 
        pipePtr = (PipeInfo *) Tcl_GetChannelInstanceData(chan);
-       resultPtr = Tcl_NewObj();
+       TclNewObj(resultPtr);
        for (i = 0; i < pipePtr->numPids; i++) {
            Tcl_ListObjAppendElement(/*interp*/ NULL, resultPtr,
                    Tcl_NewWideIntObj((unsigned)
@@ -3232,7 +3231,7 @@ TclpOpenTemporaryFile(
        Tcl_DStringFree(&buf);
     } else {
        const WCHAR *baseStr = L"TCL";
-       int length = 3 * sizeof(WCHAR);
+       length = 3 * sizeof(WCHAR);
 
        memcpy(namePtr, baseStr, length);
        namePtr += length;
index 5e63c02..8641e5e 100644 (file)
@@ -14,7 +14,6 @@
 #ifndef _TCLWINPORT
 #define _TCLWINPORT
 
-
 #if !defined(_WIN64) && !defined(__MINGW_USE_VC2005_COMPAT)
 /* See [Bug 3354324]: file mtime sets wrong time */
 #   define __MINGW_USE_VC2005_COMPAT
@@ -23,7 +22,7 @@
 /*
  * We must specify the lower version we intend to support.
  *
- * WINVER = 0x0500 means Windows 2000 and above
+ * WINVER = 0x0501 means Windows XP and above
  */
 
 #ifndef WINVER
@@ -46,7 +45,9 @@ typedef DWORD_PTR * PDWORD_PTR;
 /*
  * Ask for the winsock function typedefs, also.
  */
-#define INCL_WINSOCK_API_TYPEDEFS   1
+#ifndef INCL_WINSOCK_API_TYPEDEFS
+#   define INCL_WINSOCK_API_TYPEDEFS   1
+#endif
 #include <winsock2.h>
 #include <ws2tcpip.h>
 #ifdef HAVE_WSPIAPI_H
@@ -92,7 +93,7 @@ typedef DWORD_PTR * PDWORD_PTR;
 #include <malloc.h>
 #include <process.h>
 #include <signal.h>
-#if HAVE_INTTYPES_H
+#ifdef HAVE_INTTYPES_H
 #   include <inttypes.h>
 #endif
 #include <limits.h>
@@ -296,7 +297,7 @@ typedef DWORD_PTR * PDWORD_PTR;
  * defined in header files above.
  */
 
-#if TCL_UNION_WAIT
+#ifdef TCL_UNION_WAIT
 #   define WAIT_STATUS_TYPE union wait
 #else
 #   define WAIT_STATUS_TYPE int
@@ -315,7 +316,7 @@ typedef DWORD_PTR * PDWORD_PTR;
 #endif
 
 #ifndef WTERMSIG
-#   define WTERMSIG(stat)    ((*((int *) &(stat))) & 0x7f)
+#   define WTERMSIG(stat)    ((*((int *) &(stat))) & 0x7F)
 #endif
 
 #ifndef WIFSTOPPED
@@ -323,7 +324,7 @@ typedef DWORD_PTR * PDWORD_PTR;
 #endif
 
 #ifndef WSTOPSIG
-#   define WSTOPSIG(stat)    (((*((int *) &(stat))) >> 8) & 0xff)
+#   define WSTOPSIG(stat)    (((*((int *) &(stat))) >> 8) & 0xFF)
 #endif
 
 /*
@@ -438,10 +439,10 @@ typedef DWORD_PTR * PDWORD_PTR;
  * Define pid_t and uid_t if they're not already defined.
  */
 
-#if ! TCL_PID_T
+#if !defined(TCL_PID_T)
 #   define pid_t int
 #endif /* !TCL_PID_T */
-#if ! TCL_UID_T
+#if !defined(TCL_UID_T)
 #   define uid_t int
 #endif /* !TCL_UID_T */
 
@@ -485,6 +486,7 @@ typedef DWORD_PTR * PDWORD_PTR;
  * (_MSC_VER is 1200 for VC6, 1300 or 1310 for vc7.net, 1400 for 8.0)
  */
 #if defined(_MSC_VER)
+#   pragma warning(disable:4146)
 #   pragma warning(disable:4244)
 #   if _MSC_VER >= 1400
 #      pragma warning(disable:4267)
index 2c1b8a5..16a0d3d 100644 (file)
@@ -191,7 +191,7 @@ Registry_Init(
     cmd = Tcl_CreateObjCommand(interp, "registry", RegistryObjCmd,
            interp, DeleteCmd);
     Tcl_SetAssocData(interp, REGISTRY_ASSOC_KEY, NULL, cmd);
-    return Tcl_PkgProvideEx(interp, "registry", "1.3.4", NULL);
+    return Tcl_PkgProvideEx(interp, "registry", "1.3.5", NULL);
 }
 \f
 /*
@@ -444,7 +444,7 @@ DeleteKey(
      */
 
     keyName = Tcl_GetString(keyNameObj);
-    buffer = Tcl_Alloc(keyNameObj->length + 1);
+    buffer = (char *)Tcl_Alloc(keyNameObj->length + 1);
     strcpy(buffer, keyName);
 
     if (ParseKeyName(interp, buffer, &hostName, &rootKey,
@@ -977,7 +977,7 @@ OpenKey(
     DWORD result;
 
     keyName = Tcl_GetString(keyNameObj);
-    buffer = Tcl_Alloc(keyNameObj->length + 1);
+    buffer = (char *)Tcl_Alloc(keyNameObj->length + 1);
     strcpy(buffer, keyName);
 
     result = ParseKeyName(interp, buffer, &hostName, &rootKey, &keyName);
@@ -1235,7 +1235,7 @@ RecursiveDeleteKey(
                checkExProc = 1;
                handle = GetModuleHandleW(L"ADVAPI32");
                regDeleteKeyExProc = (LONG (*) (HKEY, LPCWSTR, REGSAM, DWORD))
-                       GetProcAddress(handle, "RegDeleteKeyExW");
+                       (void *)GetProcAddress(handle, "RegDeleteKeyExW");
            }
            if (mode && regDeleteKeyExProc) {
                result = regDeleteKeyExProc(startKey, keyName, mode, 0);
index 4f7c0be..d7fa9f5 100644 (file)
@@ -160,6 +160,8 @@ static int          SerialBlockProc(ClientData instanceData, int mode);
 static void            SerialCheckProc(ClientData clientData, int flags);
 static int             SerialCloseProc(ClientData instanceData,
                            Tcl_Interp *interp);
+static int             SerialClose2Proc(ClientData instanceData,
+                           Tcl_Interp *interp, int flags);
 static int             SerialEventProc(Tcl_Event *evPtr, int flags);
 static void            SerialExitHandler(ClientData clientData);
 static int             SerialGetHandleProc(ClientData instanceData,
@@ -203,7 +205,7 @@ static const Tcl_ChannelType serialChannelType = {
     SerialGetOptionProc,       /* Get option proc. */
     SerialWatchProc,           /* Set up notifier to watch the channel. */
     SerialGetHandleProc,       /* Get an OS handle from channel. */
-    NULL,                      /* close2proc. */
+    SerialClose2Proc,                  /* close2proc. */
     SerialBlockProc,           /* Set blocking or non-blocking mode.*/
     NULL,                      /* flush proc. */
     NULL,                      /* handler proc. */
@@ -572,7 +574,7 @@ SerialBlockProc(
 /*
  *----------------------------------------------------------------------
  *
- * SerialCloseProc --
+ * SerialCloseProc/SerialClose2Proc --
  *
  *     Closes a serial based IO channel.
  *
@@ -664,6 +666,18 @@ SerialCloseProc(
     }
     return errorCode;
 }
+
+static int
+SerialClose2Proc(
+    ClientData instanceData,    /* Pointer to SerialInfo structure. */
+    Tcl_Interp *interp,                /* For error reporting. */
+       int flags)
+{
+    if ((flags & (TCL_CLOSE_READ | TCL_CLOSE_WRITE)) == 0) {
+       return SerialCloseProc(instanceData, interp);
+    }
+    return EINVAL;
+}
 \f
 /*
  *----------------------------------------------------------------------
@@ -1024,7 +1038,7 @@ SerialOutputProc(
            infoPtr->writeBufLen = toWrite;
            infoPtr->writeBuf = ckalloc(toWrite);
        }
-       memcpy(infoPtr->writeBuf, buf, (size_t) toWrite);
+       memcpy(infoPtr->writeBuf, buf, toWrite);
        infoPtr->toWrite = toWrite;
        ResetEvent(infoPtr->evWritable);
        TclPipeThreadSignal(&infoPtr->writeTI);
@@ -1442,7 +1456,7 @@ TclWinOpenSerialChannel(
      * are shared between multiple channels (stdin/stdout).
      */
 
-    sprintf(channelName, "file%" TCL_I_MODIFIER "x", (size_t) infoPtr);
+    sprintf(channelName, "file%" TCL_Z_MODIFIER "x", (size_t) infoPtr);
 
     infoPtr->channel = Tcl_CreateChannel(&serialChannelType, channelName,
            infoPtr, permissions);
@@ -1738,16 +1752,16 @@ SerialSetOptionProc(
        dcb.XonChar = argv[0][0];
        dcb.XoffChar = argv[1][0];
        if (argv[0][0] & 0x80 || argv[1][0] & 0x80) {
-           Tcl_UniChar character;
+           int character;
            int charLen;
 
-           charLen = Tcl_UtfToUniChar(argv[0], &character);
-           if (argv[0][charLen]) {
+           charLen = TclUtfToUCS4(argv[0], &character);
+           if ((character & ~0xFF) || argv[0][charLen]) {
                goto badXchar;
            }
            dcb.XonChar = (char) character;
-           charLen = Tcl_UtfToUniChar(argv[1], &character);
-           if (argv[1][charLen]) {
+           charLen = TclUtfToUCS4(argv[1], &character);
+           if ((character & ~0xFF) || argv[1][charLen]) {
                goto badXchar;
            }
            dcb.XoffChar = (char) character;
@@ -1765,7 +1779,7 @@ SerialSetOptionProc(
      */
 
     if ((len > 4) && (strncmp(optionName, "-ttycontrol", len) == 0)) {
-       int i, result = TCL_OK;
+       int i, res = TCL_OK;
 
        if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
            return TCL_ERROR;
@@ -1783,7 +1797,7 @@ SerialSetOptionProc(
 
        for (i = 0; i < argc - 1; i += 2) {
            if (Tcl_GetBoolean(interp, argv[i+1], &flag) == TCL_ERROR) {
-               result = TCL_ERROR;
+               res = TCL_ERROR;
                break;
            }
            if (strncasecmp(argv[i], "DTR", strlen(argv[i])) == 0) {
@@ -1795,7 +1809,7 @@ SerialSetOptionProc(
                        Tcl_SetErrorCode(interp, "TCL", "OPERATION",
                                "FCONFIGURE", "TTY_SIGNAL", NULL);
                    }
-                   result = TCL_ERROR;
+                   res = TCL_ERROR;
                    break;
                }
            } else if (strncasecmp(argv[i], "RTS", strlen(argv[i])) == 0) {
@@ -1807,7 +1821,7 @@ SerialSetOptionProc(
                        Tcl_SetErrorCode(interp, "TCL", "OPERATION",
                                "FCONFIGURE", "TTY_SIGNAL", NULL);
                    }
-                   result = TCL_ERROR;
+                   res = TCL_ERROR;
                    break;
                }
            } else if (strncasecmp(argv[i], "BREAK", strlen(argv[i])) == 0) {
@@ -1819,7 +1833,7 @@ SerialSetOptionProc(
                        Tcl_SetErrorCode(interp, "TCL", "OPERATION",
                                "FCONFIGURE", "TTY_SIGNAL", NULL);
                    }
-                   result = TCL_ERROR;
+                   res = TCL_ERROR;
                    break;
                }
            } else {
@@ -1830,13 +1844,13 @@ SerialSetOptionProc(
                    Tcl_SetErrorCode(interp, "TCL", "VALUE", "TTY_SIGNAL",
                            NULL);
                }
-               result = TCL_ERROR;
+               res = TCL_ERROR;
                break;
            }
        }
 
        ckfree(argv);
-       return result;
+       return res;
     }
 
     /*
index a397a30..a05b8f6 100644 (file)
@@ -343,11 +343,11 @@ InitializeHostName(
     int *lengthPtr,
     Tcl_Encoding *encodingPtr)
 {
-    WCHAR wbuf[MAX_COMPUTERNAME_LENGTH + 1];
-    DWORD length = MAX_COMPUTERNAME_LENGTH + 1;
+    WCHAR wbuf[256];
+    DWORD length = sizeof(wbuf)/sizeof(WCHAR);
     Tcl_DString ds;
 
-    if (GetComputerNameW(wbuf, &length) != 0) {
+    if (GetComputerNameExW(ComputerNamePhysicalDnsFullyQualified, wbuf, &length) != 0) {
        /*
         * Convert string from native to UTF then change to lowercase.
         */
@@ -378,7 +378,7 @@ InitializeHostName(
     *encodingPtr = Tcl_GetEncoding(NULL, "utf-8");
     *lengthPtr = Tcl_DStringLength(&ds);
     *valuePtr = ckalloc((*lengthPtr) + 1);
-    memcpy(*valuePtr, Tcl_DStringValue(&ds), (size_t)(*lengthPtr)+1);
+    memcpy(*valuePtr, Tcl_DStringValue(&ds), *lengthPtr + 1);
     Tcl_DStringFree(&ds);
 }
 \f
@@ -522,7 +522,6 @@ TclpFinalizeSockets(void)
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpBlockModeProc(
     ClientData instanceData,   /* Socket state. */
@@ -722,7 +721,6 @@ WaitForConnect(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpInputProc(
     ClientData instanceData,   /* Socket state. */
@@ -973,7 +971,6 @@ TcpOutputProc(
  *----------------------------------------------------------------------
  */
 
-    /* ARGSUSED */
 static int
 TcpCloseProc(
     ClientData instanceData,   /* The socket to close. */
@@ -1068,36 +1065,28 @@ TcpClose2Proc(
     int flags)                 /* Flags that indicate which side to close. */
 {
     TcpState *statePtr = instanceData;
-    int errorCode = 0;
-    int sd;
+    int readError = 0;
+    int writeError = 0;
 
     /*
      * Shutdown the OS socket handle.
      */
 
-    switch(flags) {
-    case TCL_CLOSE_READ:
-       sd = SD_RECEIVE;
-       break;
-    case TCL_CLOSE_WRITE:
-       sd = SD_SEND;
-       break;
-    default:
-       if (interp) {
-           Tcl_SetObjResult(interp, Tcl_NewStringObj(
-                   "socket close2proc called bidirectionally", -1));
-       }
-       return TCL_ERROR;
+    if ((flags & (TCL_CLOSE_READ|TCL_CLOSE_WRITE)) == 0) {
+       return TcpCloseProc(instanceData, interp);
     }
 
     /* single fd operation: Tcl_OpenTcpServer() does not set TCL_READABLE or
      * TCL_WRITABLE so this should never be called for a server socket. */
-    if (shutdown(statePtr->sockets->fd, sd) == SOCKET_ERROR) {
+    if ((flags & TCL_CLOSE_READ) && (shutdown(statePtr->sockets->fd, SD_RECEIVE) == SOCKET_ERROR)) {
        TclWinConvertError((DWORD) WSAGetLastError());
-       errorCode = Tcl_GetErrno();
+       readError = Tcl_GetErrno();
     }
-
-    return errorCode;
+    if ((flags & TCL_CLOSE_WRITE) && (shutdown(statePtr->sockets->fd, SD_SEND) == SOCKET_ERROR)) {
+       TclWinConvertError((DWORD) WSAGetLastError());
+       writeError = Tcl_GetErrno();
+    }
+    return (readError != 0) ? readError : writeError;
 }
 \f
 /*
@@ -1582,7 +1571,6 @@ TcpWatchProc(
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static int
 TcpGetHandleProc(
     ClientData instanceData,   /* The socket state. */
@@ -2233,7 +2221,6 @@ error:
  *----------------------------------------------------------------------
  */
 
-       /* ARGSUSED */
 static void
 TcpAccept(
     TcpFdList *fds,    /* Server socket that accepted newSocket. */
@@ -2423,7 +2410,6 @@ InitSockets(void)
  *----------------------------------------------------------------------
  */
 
-    /* ARGSUSED */
 static int
 SocketsEnabled(void)
 {
@@ -2453,7 +2439,6 @@ SocketsEnabled(void)
  *----------------------------------------------------------------------
  */
 
-    /* ARGSUSED */
 static void
 SocketExitHandler(
     ClientData clientData)             /* Not used. */
index dd4d5ec..8525718 100644 (file)
@@ -461,7 +461,7 @@ TestplatformChmod(
      * nativePath not found
      */
 
-    if (attr == 0xffffffff) {
+    if (attr == 0xFFFFFFFF) {
        res = -1;
        goto done;
     }
index 5316075..44b5f6c 100644 (file)
@@ -24,18 +24,18 @@ _CRTIMP unsigned int __cdecl _controlfp (unsigned int unNew, unsigned int unMask
 #endif
 
 /*
- * This is the master lock used to serialize access to other serialization
+ * This is the global lock used to serialize access to other serialization
  * data structures.
  */
 
-static CRITICAL_SECTION masterLock;
+static CRITICAL_SECTION globalLock;
 static int init = 0;
-#define MASTER_LOCK TclpMasterLock()
-#define MASTER_UNLOCK TclpMasterUnlock()
+#define GLOBAL_LOCK TclpGlobalLock()
+#define GLOBAL_UNLOCK TclpGlobalUnlock()
 
 
 /*
- * This is the master lock used to serialize initialization and finalization
+ * This is the global lock used to serialize initialization and finalization
  * of Tcl as a whole.
  */
 
@@ -43,7 +43,7 @@ static CRITICAL_SECTION initLock;
 
 /*
  * allocLock is used by Tcl's version of malloc for synchronization. For
- * obvious reasons, cannot use any dyamically allocated storage.
+ * obvious reasons, cannot use any dynamically allocated storage.
  */
 
 #ifdef TCL_THREADS
@@ -368,7 +368,7 @@ TclpInitLock(void)
        init = 1;
        InitializeCriticalSection(&joinLock);
        InitializeCriticalSection(&initLock);
-       InitializeCriticalSection(&masterLock);
+       InitializeCriticalSection(&globalLock);
     }
     EnterCriticalSection(&initLock);
 }
@@ -399,7 +399,7 @@ TclpInitUnlock(void)
 /*
  *----------------------------------------------------------------------
  *
- * TclpMasterLock
+ * TclpGlobalLock
  *
  *     This procedure is used to grab a lock that serializes creation of
  *     mutexes, condition variables, and thread local storage keys.
@@ -411,13 +411,13 @@ TclpInitUnlock(void)
  *     None.
  *
  * Side effects:
- *     Acquire the master mutex.
+ *     Acquire the global mutex.
  *
  *----------------------------------------------------------------------
  */
 
 void
-TclpMasterLock(void)
+TclpGlobalLock(void)
 {
     if (!init) {
        /*
@@ -430,15 +430,15 @@ TclpMasterLock(void)
        init = 1;
        InitializeCriticalSection(&joinLock);
        InitializeCriticalSection(&initLock);
-       InitializeCriticalSection(&masterLock);
+       InitializeCriticalSection(&globalLock);
     }
-    EnterCriticalSection(&masterLock);
+    EnterCriticalSection(&globalLock);
 }
 \f
 /*
  *----------------------------------------------------------------------
  *
- * TclpMasterUnlock
+ * TclpGlobalUnlock
  *
  *     This procedure is used to release a lock that serializes creation and
  *     deletion of synchronization objects.
@@ -447,15 +447,15 @@ TclpMasterLock(void)
  *     None.
  *
  * Side effects:
- *     Release the master mutex.
+ *     Release the global mutex.
  *
  *----------------------------------------------------------------------
  */
 
 void
-TclpMasterUnlock(void)
+TclpGlobalUnlock(void)
 {
-    LeaveCriticalSection(&masterLock);
+    LeaveCriticalSection(&globalLock);
 }
 \f
 /*
@@ -464,7 +464,7 @@ TclpMasterUnlock(void)
  * Tcl_GetAllocMutex
  *
  *     This procedure returns a pointer to a statically initialized mutex for
- *     use by the memory allocator. The alloctor must use this lock, because
+ *     use by the memory allocator. The allocator must use this lock, because
  *     all other locks are allocated...
  *
  * Results:
@@ -512,14 +512,14 @@ Tcl_GetAllocMutex(void)
 void
 TclFinalizeLock(void)
 {
-    MASTER_LOCK;
+    GLOBAL_LOCK;
     DeleteCriticalSection(&joinLock);
 
     /*
      * Destroy the critical section that we are holding!
      */
 
-    DeleteCriticalSection(&masterLock);
+    DeleteCriticalSection(&globalLock);
     init = 0;
 
 #ifdef TCL_THREADS
@@ -567,10 +567,10 @@ Tcl_MutexLock(
     CRITICAL_SECTION *csPtr;
 
     if (*mutexPtr == NULL) {
-       MASTER_LOCK;
+       GLOBAL_LOCK;
 
        /*
-        * Double inside master lock check to avoid a race.
+        * Double inside global lock check to avoid a race.
         */
 
        if (*mutexPtr == NULL) {
@@ -579,7 +579,7 @@ Tcl_MutexLock(
            *mutexPtr = (Tcl_Mutex)csPtr;
            TclRememberMutex(mutexPtr);
        }
-       MASTER_UNLOCK;
+       GLOBAL_UNLOCK;
     }
     csPtr = *((CRITICAL_SECTION **)mutexPtr);
     EnterCriticalSection(csPtr);
@@ -681,7 +681,7 @@ Tcl_ConditionWait(
      */
 
     if (tsdPtr->flags == WIN_THREAD_UNINIT) {
-       MASTER_LOCK;
+       GLOBAL_LOCK;
 
        /*
         * Create the per-thread event and queue pointers.
@@ -695,14 +695,14 @@ Tcl_ConditionWait(
            tsdPtr->flags = WIN_THREAD_RUNNING;
            doExit = 1;
        }
-       MASTER_UNLOCK;
+       GLOBAL_UNLOCK;
 
        if (doExit) {
            /*
             * Create a per-thread exit handler to clean up the condEvent. We
-            * must be careful to do this outside the Master Lock because
+            * must be careful to do this outside the Global Lock because
             * Tcl_CreateThreadExitHandler uses its own ThreadSpecificData,
-            * and initializing that may drop back into the Master Lock.
+            * and initializing that may drop back into the Global Lock.
             */
 
            Tcl_CreateThreadExitHandler(FinalizeConditionEvent, tsdPtr);
@@ -710,7 +710,7 @@ Tcl_ConditionWait(
     }
 
     if (*condPtr == NULL) {
-       MASTER_LOCK;
+       GLOBAL_LOCK;
 
        /*
         * Initialize the per-condition queue pointers and Mutex.
@@ -724,7 +724,7 @@ Tcl_ConditionWait(
            *condPtr = (Tcl_Condition) winCondPtr;
            TclRememberCondition(condPtr);
        }
-       MASTER_UNLOCK;
+       GLOBAL_UNLOCK;
     }
     csPtr = *((CRITICAL_SECTION **)mutexPtr);
     winCondPtr = *((WinCondition **)condPtr);
@@ -902,7 +902,7 @@ FinalizeConditionEvent(
  *     This procedure is invoked to clean up a condition variable. This is
  *     only safe to call at the end of time.
  *
- *     This assumes the Master Lock is held.
+ *     This assumes the Global Lock is held.
  *
  * Results:
  *     None.
@@ -1073,19 +1073,19 @@ TclpThreadDeleteKey(
 }
 
 void
-TclpThreadSetMasterTSD(
+TclpThreadSetGlobalTSD(
     void *tsdKeyPtr,
     void *ptr)
 {
     DWORD *key = tsdKeyPtr;
 
     if (!TlsSetValue(*key, ptr)) {
-       Tcl_Panic("unable to set master TSD value");
+       Tcl_Panic("unable to set global TSD value");
     }
 }
 
 void *
-TclpThreadGetMasterTSD(
+TclpThreadGetGlobalTSD(
     void *tsdKeyPtr)
 {
     DWORD *key = tsdKeyPtr;
index 33d87a7..976dd61 100644 (file)
@@ -519,9 +519,9 @@ NativeGetMicroseconds(void)
 
                GetSystemInfo(&systemInfo);
                if (TclWinCPUID(0, regs) == TCL_OK
-                       && regs[1] == 0x756e6547        /* "Genu" */
-                       && regs[3] == 0x49656e69        /* "ineI" */
-                       && regs[2] == 0x6c65746e        /* "ntel" */
+                       && regs[1] == 0x756E6547        /* "Genu" */
+                       && regs[3] == 0x49656E69        /* "ineI" */
+                       && regs[2] == 0x6C65746E        /* "ntel" */
                        && TclWinCPUID(1, regs) == TCL_OK
                        && ((regs[0]&0x00000F00) == 0x00000F00 /* Pentium 4 */
                        || ((regs[0] & 0x00F00000)      /* Extended family */
@@ -1358,7 +1358,7 @@ TclpGmtime(
 #if defined(_WIN64) || defined(_USE_64BIT_TIME_T) || (defined(_MSC_VER) && _MSC_VER < 1400)
     return gmtime(timePtr);
 #else
-    return _gmtime32((CONST __time32_t *)timePtr);
+    return _gmtime32((const __time32_t *)timePtr);
 #endif
 }
 \f
@@ -1393,7 +1393,7 @@ TclpLocaltime(
 #if defined(_WIN64) || defined(_USE_64BIT_TIME_T) || (defined(_MSC_VER) && _MSC_VER < 1400)
     return localtime(timePtr);
 #else
-    return _localtime32((CONST __time32_t *)timePtr);
+    return _localtime32((const __time32_t *)timePtr);
 #endif
 }
 \f